Add server components
build-winui / winui (push) Has been cancelled

This commit is contained in:
QWQLwToo
2026-06-26 13:28:09 +08:00
parent 7ecc6a8923
commit 079ee4eaeb
168 changed files with 37475 additions and 0 deletions
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>YMhut Unified Admin</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,23 @@
{
"name": "ymhut-unified-admin",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --host 127.0.0.1",
"build": "vite build",
"preview": "vite preview --host 127.0.0.1"
},
"dependencies": {
"@vitejs/plugin-vue": "^5.2.4",
"echarts": "^6.1.0",
"lucide-vue-next": "^0.468.0",
"vite": "^6.3.5",
"vue": "^3.5.16",
"vue-echarts": "^8.0.1",
"vue-router": "^4.6.4"
},
"devDependencies": {
"typescript": "^5.8.3"
}
}
@@ -0,0 +1,777 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
ArrowDownToLine,
CheckCircle2,
ClipboardList,
Code2,
Database,
FileJson,
HeartPulse,
LayoutDashboard,
ListChecks,
LogOut,
MessageSquareText,
Network,
RefreshCw,
Settings,
ShieldCheck,
} from "lucide-vue-next";
import AuditView from "./views/AuditView.vue";
import DashboardView from "./views/DashboardView.vue";
import DatabaseView from "./views/DatabaseView.vue";
import EndpointsView from "./views/EndpointsView.vue";
import FeedbacksView from "./views/FeedbacksView.vue";
import HealthView from "./views/HealthView.vue";
import LegacyJsonView from "./views/LegacyJsonView.vue";
import ReleasesView from "./views/ReleasesView.vue";
import SettingsView from "./views/SettingsView.vue";
import SourcesView from "./views/SourcesView.vue";
type LegacyName = "update-info" | "media-types";
type Captcha = {
captchaId: string;
image: string;
};
type AuthBootstrap = {
isDefaultPassword: boolean;
defaultUsername: string;
defaultPassword: string;
};
type RouteItem = {
path: string;
label: string;
description: string;
icon: any;
};
const csrf = ref(localStorage.getItem("ymhut.csrf") || "");
const route = useRoute();
const router = useRouter();
const currentPath = computed(() => normalizeAdminPath(route.path));
const loading = ref(false);
const toast = ref("");
const autoRefreshPaused = ref(false);
let refreshTimer: number | undefined;
const captcha = ref<Captcha | null>(null);
const authBootstrap = ref<AuthBootstrap | null>(null);
const dashboard = ref<any>({});
const feedbackPage = ref<any>({ items: [], total: 0, page: 1, perPage: 20 });
const selectedFeedback = ref<any | null>(null);
const releases = ref<any>(null);
const releaseNotices = ref<any[]>([]);
const selectedNotice = ref<any | null>(null);
const sources = ref<any>({ categories: [] });
const endpoints = ref<any[]>([]);
const database = ref<any>(null);
const healthSnapshot = ref<any>(null);
const auditLogs = ref<any[]>([]);
const legacySync = ref<any>(null);
const legacyDocuments = reactive<Record<LegacyName, any | null>>({ "update-info": null, "media-types": null });
const loginForm = reactive({ username: "admin", password: "", captcha: "" });
const passwordForm = reactive({ currentPassword: "", newPassword: "" });
const feedbackFilters = reactive({ q: "", status: "", page: 1, perPage: 20 });
const feedbackUpdate = reactive({ status: "", statusDetail: "", publicReply: "" });
const commentDraft = reactive({ body: "", internal: true });
const databaseForm = reactive({ provider: "sqlite", sqlitePath: "", mysqlDsn: "" });
const sourceDraft = reactive({
sourceId: "",
categoryId: "custom",
categoryName: "自定义接口",
name: "",
description: "",
method: "GET",
apiUrl: "",
urlTemplate: "",
thumbnailUrl: "",
proxyMode: "client_direct",
timeoutMs: 8000,
retryCount: 1,
cacheSeconds: 300,
checkIntervalSec: 300,
enabled: true,
clientVisible: true,
supportedFormats: "[\"json\"]",
});
const legacyDrafts = reactive<Record<LegacyName, { raw: string; note: string; preview: any | null }>>({
"update-info": { raw: "", note: "", preview: null },
"media-types": { raw: "", note: "", preview: null },
});
const noticeDraft = reactive({ version: "", raw: "", note: "", preview: null as any });
const routes: RouteItem[] = [
{ path: "/admin/dashboard", label: "仪表盘", description: "服务状态、接口心跳与运营指标", icon: LayoutDashboard },
{ path: "/admin/feedbacks", label: "反馈工单", description: "旧客户端反馈与处理流转", icon: MessageSquareText },
{ path: "/admin/releases", label: "发布与日志", description: "发布包、版本公告和兼容日志", icon: ArrowDownToLine },
{ path: "/admin/legacy/update-info", label: "更新 JSON", description: "可视化维护 update-info.json", icon: FileJson },
{ path: "/admin/legacy/media-types", label: "媒体源 JSON", description: "维护旧客户端媒体源结构", icon: ClipboardList },
{ path: "/admin/sources", label: "来源目录", description: "媒体/数据源目录和健康检测", icon: Network },
{ path: "/admin/endpoints", label: "客户端接口", description: "新版客户端动态接口配置", icon: Code2 },
{ path: "/admin/database", label: "数据库与同步", description: "SQLite、MySQL 和旧项目同步", icon: Database },
{ path: "/admin/health", label: "健康快照", description: "服务端运行状态和预检信息", icon: HeartPulse },
{ path: "/admin/settings", label: "系统设置", description: "密码与旧库同步入口", icon: Settings },
{ path: "/admin/audit", label: "审计日志", description: "后台操作和同步记录", icon: ListChecks },
];
const navGroups = [
{ label: "概览", items: routes.filter((item) => ["/admin/dashboard"].includes(item.path)) },
{ label: "反馈", items: routes.filter((item) => ["/admin/feedbacks"].includes(item.path)) },
{ label: "发布与兼容", items: routes.filter((item) => ["/admin/releases", "/admin/legacy/update-info", "/admin/legacy/media-types"].includes(item.path)) },
{ label: "客户端接口", items: routes.filter((item) => ["/admin/sources", "/admin/endpoints"].includes(item.path)) },
{ label: "系统运维", items: routes.filter((item) => ["/admin/database", "/admin/health", "/admin/settings", "/admin/audit"].includes(item.path)) },
];
const quickActions = [
{ path: "/admin/feedbacks", label: "反馈处理", description: "查看和处理客户端反馈工单", icon: MessageSquareText },
{ path: "/admin/releases", label: "发布与日志", description: "维护发布包和 update-notice", icon: ArrowDownToLine },
{ path: "/admin/legacy/update-info", label: "更新 JSON", description: "编辑旧版 update-info.json", icon: FileJson },
{ path: "/admin/legacy/media-types", label: "媒体源 JSON", description: "同步旧客户端媒体源结构", icon: ClipboardList },
{ path: "/admin/sources", label: "接口源目录", description: "新增接口并执行健康检测", icon: Network },
{ path: "/admin/database", label: "数据库同步", description: "管理 SQLite/MySQL 和旧项目同步", icon: Database },
{ path: "/admin/audit", label: "审计日志", description: "查看后台操作与同步记录", icon: ListChecks },
];
const pageMeta = computed(() => routes.find((item) => item.path === currentPath.value) || routes[0]);
const activeLegacyName = computed<LegacyName | null>(() => {
if (currentPath.value.endsWith("/update-info")) return "update-info";
if (currentPath.value.endsWith("/media-types")) return "media-types";
return null;
});
const kpis = computed(() => dashboard.value?.kpis || {});
const sourceHealth = computed(() => dashboard.value?.sourceHealth || {});
const feedbackStatus = computed(() => dashboard.value?.feedbackStatus || {});
const heartbeats = computed(() => dashboard.value?.heartbeats || []);
const clientCalls = computed(() => dashboard.value?.clientCalls || []);
const releasePackages = computed(() => releases.value?.packages || []);
const sourceCategories = computed(() => sources.value?.categories || []);
const visibleEndpointCount = computed(() => endpoints.value.filter((item) => item.enabled && item.clientVisible).length);
const healthyEndpointCount = computed(() => endpoints.value.filter((item) => endpointStatus(item) === "ok").length);
const latestNotice = computed(() => releaseNotices.value[0] || null);
const activeLegacyLabel = computed(() => activeLegacyName.value === "media-types" ? "media-types.json" : "update-info.json");
const heartbeatOption = computed(() => ({
tooltip: { trigger: "axis" },
grid: { left: 44, right: 18, top: 28, bottom: 34 },
xAxis: {
type: "category",
data: heartbeats.value.slice().reverse().map((item: any) => timeLabel(item.checkedAt)),
axisLine: { lineStyle: { color: "#cbd5e1" } },
},
yAxis: { type: "value", name: "ms", axisLine: { lineStyle: { color: "#cbd5e1" } }, splitLine: { lineStyle: { color: "#e5e7eb" } } },
series: [
{
name: "接口延迟",
type: "line",
smooth: true,
areaStyle: { opacity: 0.18 },
data: heartbeats.value.slice().reverse().map((item: any) => item.latencyMs || 0),
color: "#2563eb",
},
],
}));
const healthOption = computed(() => ({
tooltip: { trigger: "item" },
legend: { bottom: 0 },
series: [
{
name: "接口健康",
type: "pie",
radius: ["48%", "72%"],
data: objectEntries(sourceHealth.value),
color: ["#16a34a", "#f59e0b", "#dc2626", "#64748b"],
},
],
}));
const feedbackOption = computed(() => ({
tooltip: { trigger: "axis" },
grid: { left: 34, right: 12, top: 20, bottom: 28 },
xAxis: { type: "category", data: objectEntries(feedbackStatus.value).map((item) => item.name) },
yAxis: { type: "value", splitLine: { lineStyle: { color: "#e5e7eb" } } },
series: [{ name: "工单", type: "bar", data: objectEntries(feedbackStatus.value).map((item) => item.value), color: "#0f766e" }],
}));
const availabilityOption = computed(() => {
const total = Number(kpis.value.sourceTotal || 0);
const ok = Number(sourceHealth.value.ok || 0);
const value = total ? Math.round((ok / total) * 100) : 0;
return {
series: [
{
type: "gauge",
progress: { show: true, width: 12 },
axisLine: { lineStyle: { width: 12 } },
axisLabel: { distance: 16 },
pointer: { width: 4 },
detail: { formatter: "{value}%", fontSize: 24 },
data: [{ value, name: "可用率" }],
},
],
};
});
const viewContext = computed(() => ({
activeLegacyLabel: activeLegacyLabel.value,
activeLegacyName: activeLegacyName.value,
addFeedbackComment,
auditLogs: auditLogs.value,
autoRefreshPaused: autoRefreshPaused.value,
availabilityOption: availabilityOption.value,
changePassword,
checkSources,
clientCalls: clientCalls.value,
commentDraft,
copyEndpointToSource,
database: database.value,
databaseForm,
endpointStatus,
endpoints: endpoints.value,
feedbackFilters,
feedbackOption: feedbackOption.value,
feedbackPage: feedbackPage.value,
feedbackUpdate,
formatBytes,
healthOption: healthOption.value,
healthSnapshot: healthSnapshot.value,
healthyEndpointCount: healthyEndpointCount.value,
heartbeatOption: heartbeatOption.value,
heartbeats: heartbeats.value,
importNotices,
kpis: kpis.value,
labelStatus,
latestNotice: latestNotice.value,
legacyDocuments,
legacyDrafts,
legacySync: legacySync.value,
loadAudit,
loadFeedbacks,
navigate,
noticeDraft,
openFeedback,
openNotice,
passwordForm,
pretty,
previewLegacySync,
quickActions,
releaseNotices: releaseNotices.value,
releasePackages: releasePackages.value,
releases: releases.value,
restoreLegacy,
restoreNotice,
runLegacySync,
saveFeedbackUpdate,
saveLegacy,
saveNotice,
saveSource,
selectedFeedback: selectedFeedback.value,
selectedNotice: selectedNotice.value,
sourceCategories: sourceCategories.value,
sourceDraft,
statusTone,
syncDatabase,
testDatabase,
toggleAutoRefresh,
validateLegacy,
validateNotice,
visibleEndpointCount: visibleEndpointCount.value,
}));
async function api<T>(target: string, init: RequestInit = {}): Promise<T> {
const headers = new Headers(init.headers);
if (!headers.has("Content-Type") && init.body) headers.set("Content-Type", "application/json");
if (csrf.value) headers.set("X-CSRF-Token", csrf.value);
const res = await fetch(target, { ...init, headers, credentials: "include" });
const data = await res.json().catch(() => ({}));
if (!res.ok || data.ok === false) throw new Error(data.message || data.error || `HTTP ${res.status}`);
return data as T;
}
function normalizeAdminPath(value: string) {
if (value === "/admin" || value === "/admin/") return "/admin/dashboard";
if (value === "/") return "/admin/dashboard";
return value;
}
function navigate(next: string) {
if (currentPath.value === next) {
void load();
return;
}
void router.push(next);
}
function toggleAutoRefresh() {
autoRefreshPaused.value = !autoRefreshPaused.value;
}
function setToast(message: string) {
toast.value = message;
window.setTimeout(() => {
if (toast.value === message) toast.value = "";
}, 4200);
}
async function guarded(task: () => Promise<void>) {
loading.value = true;
try {
await task();
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
toast.value = message;
if (message.includes("Login required") || message.includes("UNAUTHORIZED")) {
navigate("/admin/login");
}
} finally {
loading.value = false;
}
}
async function loadCaptcha() {
captcha.value = await api<Captcha>("/api/admin/auth/captcha");
}
async function loadAuthBootstrap() {
authBootstrap.value = await api<AuthBootstrap>("/api/admin/auth/bootstrap");
}
async function login() {
await guarded(async () => {
const data = await api<{ csrfToken: string }>("/api/admin/auth/login", {
method: "POST",
body: JSON.stringify({ ...loginForm, captchaId: captcha.value?.captchaId }),
});
csrf.value = data.csrfToken;
localStorage.setItem("ymhut.csrf", csrf.value);
navigate("/admin/dashboard");
});
}
async function logout() {
await api("/api/admin/auth/logout", { method: "POST", body: "{}" }).catch(() => undefined);
csrf.value = "";
localStorage.removeItem("ymhut.csrf");
navigate("/admin/login");
}
async function load() {
await guarded(async () => {
if (currentPath.value === "/admin/login") {
await Promise.all([loadAuthBootstrap(), loadCaptcha()]);
return;
}
if (currentPath.value === "/admin/dashboard") await loadDashboard();
if (currentPath.value === "/admin/feedbacks") await loadFeedbacks();
if (currentPath.value === "/admin/releases") await loadReleases();
if (currentPath.value === "/admin/sources") await loadSources();
if (currentPath.value === "/admin/endpoints") await loadEndpoints();
if (currentPath.value === "/admin/database") await loadDatabase();
if (currentPath.value === "/admin/health") await loadHealth();
if (currentPath.value === "/admin/audit") await loadAudit();
if (currentPath.value === "/admin/settings") await previewLegacySync();
const legacyName = activeLegacyName.value;
if (legacyName) await loadLegacy(legacyName);
});
}
async function loadDashboard() {
dashboard.value = await api("/api/admin/dashboard/overview?window=24h");
}
async function loadFeedbacks() {
const params = new URLSearchParams({ page: String(feedbackFilters.page), perPage: String(feedbackFilters.perPage) });
if (feedbackFilters.q) params.set("q", feedbackFilters.q);
if (feedbackFilters.status) params.set("status", feedbackFilters.status);
const data = await api<{ page: any }>(`/api/admin/feedbacks?${params}`);
feedbackPage.value = data.page || { items: [], total: 0, page: 1, perPage: 20 };
}
async function openFeedback(item: any) {
const data = await api<{ feedback: any }>(`/api/admin/feedbacks/${encodeURIComponent(item.code)}`);
selectedFeedback.value = data.feedback;
feedbackUpdate.status = data.feedback.status || "new";
feedbackUpdate.statusDetail = data.feedback.statusDetail || "";
feedbackUpdate.publicReply = data.feedback.publicReply || "";
}
async function saveFeedbackUpdate() {
if (!selectedFeedback.value) return;
await guarded(async () => {
await api(`/api/admin/feedbacks/${encodeURIComponent(selectedFeedback.value.code)}`, { method: "PATCH", body: JSON.stringify(feedbackUpdate) });
setToast("反馈工单已更新");
await openFeedback(selectedFeedback.value);
await loadFeedbacks();
});
}
async function addFeedbackComment() {
if (!selectedFeedback.value || !commentDraft.body.trim()) return;
await guarded(async () => {
await api(`/api/admin/feedbacks/${encodeURIComponent(selectedFeedback.value.code)}/comments`, {
method: "POST",
body: JSON.stringify({ author: "admin", body: commentDraft.body, internal: commentDraft.internal }),
});
commentDraft.body = "";
await openFeedback(selectedFeedback.value);
});
}
async function loadReleases() {
const [releaseData, noticeData] = await Promise.all([
api<{ manifest: any }>("/api/admin/releases"),
api<{ items: any[] }>("/api/admin/releases/notices"),
]);
releases.value = releaseData.manifest;
releaseNotices.value = noticeData.items || [];
if (releaseNotices.value.length && !noticeDraft.version) await openNotice(releaseNotices.value[0].version);
}
async function importNotices() {
await guarded(async () => {
const data = await api<{ items: any[] }>("/api/admin/releases/notices/import", { method: "POST", body: "{}" });
releaseNotices.value = data.items || [];
setToast("版本日志已从目录重新导入");
});
}
async function openNotice(version: string) {
const data = await api<{ document: any }>(`/api/admin/releases/notices/${encodeURIComponent(version)}`);
selectedNotice.value = data.document;
noticeDraft.version = version;
noticeDraft.raw = data.document.raw || "";
noticeDraft.preview = data.document.parsed || null;
}
async function validateNotice() {
if (!noticeDraft.version) return;
const data = await api<{ document: any }>(`/api/admin/releases/notices/${encodeURIComponent(noticeDraft.version)}/validate`, {
method: "POST",
body: JSON.stringify({ raw: noticeDraft.raw }),
});
noticeDraft.raw = data.document.raw;
noticeDraft.preview = data.document.parsed;
setToast("版本日志 JSON 校验通过");
}
async function saveNotice() {
if (!noticeDraft.version) return;
await guarded(async () => {
const data = await api<{ document: any }>(`/api/admin/releases/notices/${encodeURIComponent(noticeDraft.version)}`, {
method: "PUT",
body: JSON.stringify({ raw: noticeDraft.raw, note: noticeDraft.note }),
});
selectedNotice.value = data.document;
noticeDraft.note = "";
setToast("版本日志已保存并同步兼容更新信息");
await loadReleases();
});
}
async function restoreNotice(revisionId: number) {
if (!noticeDraft.version) return;
await guarded(async () => {
const data = await api<{ document: any }>(`/api/admin/releases/notices/${encodeURIComponent(noticeDraft.version)}/restore`, {
method: "POST",
body: JSON.stringify({ revisionId }),
});
selectedNotice.value = data.document;
noticeDraft.raw = data.document.raw || "";
noticeDraft.preview = data.document.parsed || null;
setToast("版本日志已恢复");
});
}
async function loadLegacy(name: LegacyName) {
const data = await api<{ document: any }>(`/api/admin/legacy/${name}`);
legacyDocuments[name] = data.document;
legacyDrafts[name].raw = data.document.raw || "";
legacyDrafts[name].preview = data.document.parsed || null;
}
async function validateLegacy(name: LegacyName) {
const data = await api<{ document: any }>(`/api/admin/legacy/${name}/validate`, {
method: "POST",
body: JSON.stringify({ raw: legacyDrafts[name].raw }),
});
legacyDrafts[name].raw = data.document.raw;
legacyDrafts[name].preview = data.document.parsed;
setToast("兼容 JSON 校验通过");
}
async function saveLegacy(name: LegacyName) {
await guarded(async () => {
const data = await api<{ document: any }>(`/api/admin/legacy/${name}`, {
method: "PUT",
body: JSON.stringify({ raw: legacyDrafts[name].raw, note: legacyDrafts[name].note }),
});
legacyDocuments[name] = data.document;
legacyDrafts[name].raw = data.document.raw;
legacyDrafts[name].preview = data.document.parsed;
legacyDrafts[name].note = "";
setToast("兼容 JSON 已保存并发布到旧路径");
});
}
async function restoreLegacy(name: LegacyName, revisionId: number) {
await guarded(async () => {
const data = await api<{ document: any }>(`/api/admin/legacy/${name}/restore`, {
method: "POST",
body: JSON.stringify({ revisionId }),
});
legacyDocuments[name] = data.document;
legacyDrafts[name].raw = data.document.raw;
legacyDrafts[name].preview = data.document.parsed;
setToast("兼容 JSON 已恢复");
});
}
async function loadSources() {
const data = await api<{ catalog: any }>("/api/admin/sources");
sources.value = data.catalog || { categories: [] };
}
async function saveSource() {
await guarded(async () => {
await api("/api/admin/sources", { method: "POST", body: JSON.stringify(sourceDraft) });
setToast("接口源已保存");
await Promise.all([loadSources(), loadEndpoints()]);
});
}
async function checkSources() {
await guarded(async () => {
await api("/api/admin/sources/check", { method: "POST", body: "{}" });
setToast("接口心跳检测已进入队列");
if (currentPath.value === "/admin/dashboard") await loadDashboard();
if (currentPath.value === "/admin/sources") await loadSources();
});
}
async function loadEndpoints() {
const data = await api<{ items: any[] }>("/api/admin/endpoints");
endpoints.value = data.items || [];
}
function copyEndpointToSource(item: any) {
Object.assign(sourceDraft, {
sourceId: item.id || item.sourceId,
categoryId: item.category || item.categoryId || "custom",
categoryName: item.category || item.categoryName || "自定义接口",
name: item.name,
method: item.method || "GET",
apiUrl: item.urlTemplate || item.apiUrl || "",
urlTemplate: item.urlTemplate || item.apiUrl || "",
proxyMode: item.proxyMode || "client_direct",
enabled: item.enabled,
clientVisible: item.clientVisible,
cacheSeconds: item.cacheSeconds || 300,
checkIntervalSec: item.checkIntervalSec || item.cacheSeconds || 300,
supportedFormats: JSON.stringify(item.supportedFormats || ["json"]),
});
navigate("/admin/sources");
}
async function loadDatabase() {
const data = await api<{ database: any }>("/api/admin/database/status");
database.value = data.database;
databaseForm.provider = data.database?.configProvider || "sqlite";
await previewLegacySync();
}
async function testDatabase() {
await guarded(async () => {
await api("/api/admin/database/test", {
method: "POST",
body: JSON.stringify({ provider: databaseForm.provider, sqlite_path: databaseForm.sqlitePath, mysql_dsn: databaseForm.mysqlDsn }),
});
setToast("数据库连接测试通过");
});
}
async function syncDatabase(direction: "import" | "sync") {
await guarded(async () => {
await api(direction === "import" ? "/api/admin/database/import-sqlite" : "/api/admin/database/sync", { method: "POST", body: "{}" });
setToast(direction === "import" ? "SQLite 已导入远端库" : "远端库已同步回本地");
await loadDatabase();
});
}
async function previewLegacySync() {
legacySync.value = await api("/api/admin/sync/legacy/preview").catch((error) => ({ ok: false, errors: [String(error)] }));
}
async function runLegacySync() {
await guarded(async () => {
legacySync.value = await api("/api/admin/sync/legacy/run", { method: "POST", body: "{}" });
setToast("旧项目同步已完成");
await Promise.all([loadDatabase(), loadReleases().catch(() => undefined), loadSources().catch(() => undefined)]);
});
}
async function loadHealth() {
healthSnapshot.value = await api("/api/admin/system/health");
}
async function loadAudit() {
const data = await api<{ items: any[] }>("/api/admin/system/audit");
auditLogs.value = data.items || [];
}
async function changePassword() {
await guarded(async () => {
await api("/api/admin/auth/password", { method: "POST", body: JSON.stringify(passwordForm) });
passwordForm.currentPassword = "";
passwordForm.newPassword = "";
setToast("后台密码已修改,登录页将不再提示默认密码");
});
}
function endpointStatus(item: any) {
return item.health?.status || item.lastStatus || "unknown";
}
function statusTone(status: string) {
const value = String(status || "").toLowerCase();
if (["ok", "online", "new", "sqlite", "mysql", "sent", "ready"].includes(value)) return "good";
if (["degraded", "pending", "processing", "queued", "missing"].includes(value)) return "warn";
if (["error", "failed", "closed", "offline"].includes(value)) return "bad";
return "neutral";
}
function objectEntries(value: Record<string, number>) {
return Object.entries(value || {}).map(([name, item]) => ({ name: labelStatus(name), value: item || 0 }));
}
function labelStatus(value: string) {
const labels: Record<string, string> = {
ok: "正常",
error: "错误",
degraded: "降级",
unknown: "未知",
new: "新建",
processing: "处理中",
closed: "已关闭",
failed: "失败",
};
return labels[value] || value || "未知";
}
function formatBytes(value: number) {
if (!Number.isFinite(value) || value <= 0) return "0 B";
const units = ["B", "KB", "MB", "GB"];
let next = value;
let index = 0;
while (next >= 1024 && index < units.length - 1) {
next /= 1024;
index += 1;
}
return `${next.toFixed(index === 0 ? 0 : 1)} ${units[index]}`;
}
function timeLabel(value: string) {
if (!value) return "-";
return value.length > 10 ? value.slice(11, 19) : value;
}
function pretty(value: any) {
return JSON.stringify(value || {}, null, 2);
}
onMounted(() => {
void load();
refreshTimer = window.setInterval(() => {
if (!autoRefreshPaused.value && currentPath.value === "/admin/dashboard" && csrf.value) void loadDashboard();
}, 15000);
});
onUnmounted(() => {
if (refreshTimer) window.clearInterval(refreshTimer);
});
</script>
<template>
<main v-if="currentPath === '/admin/login'" class="login-shell">
<section class="login-panel">
<div>
<p class="eyebrow">YMhut Unified Management</p>
<h1>后台登录</h1>
<p class="muted">验证码和密码都由服务端校验登录后写操作继续要求 CSRF Token</p>
</div>
<p v-if="authBootstrap?.isDefaultPassword" class="alert-line">
当前使用默认账号{{ authBootstrap.defaultUsername || "admin" }} / {{ authBootstrap.defaultPassword || "admin" }}
</p>
<form class="form-stack" @submit.prevent="login">
<label>账号<input v-model="loginForm.username" autocomplete="username" /></label>
<label>密码<input v-model="loginForm.password" type="password" autocomplete="current-password" /></label>
<label>
验证码
<div class="captcha-row">
<input v-model="loginForm.captcha" />
<button class="captcha-button" type="button" title="刷新验证码" @click="loadCaptcha">
<img v-if="captcha?.image" :src="captcha.image" alt="验证码" />
<span v-else>刷新</span>
</button>
</div>
</label>
<button class="btn primary full" type="submit">登录</button>
</form>
<p v-if="toast" class="notice">{{ toast }}</p>
</section>
</main>
<main v-else class="app-shell">
<aside class="sidebar">
<div class="brand">
<span class="brand-mark"><ShieldCheck :size="22" /></span>
<div><strong>YMhut</strong><small>统一管理台</small></div>
</div>
<nav class="nav-groups">
<section v-for="group in navGroups" :key="group.label" class="nav-group">
<p>{{ group.label }}</p>
<button
v-for="item in group.items"
:key="item.path"
:class="{ active: currentPath === item.path || (item.path.includes('/legacy/') && activeLegacyName) }"
@click="navigate(item.path)"
>
<component :is="item.icon" :size="17" />
<span>{{ item.label }}</span>
</button>
</section>
</nav>
<button class="logout" @click="logout"><LogOut :size="16" />退出</button>
</aside>
<section class="workspace">
<header class="topbar">
<div>
<p class="eyebrow">update.ymhut.cn</p>
<h1>{{ pageMeta.label }}</h1>
<p class="muted">{{ pageMeta.description }}</p>
</div>
<div class="top-actions">
<span v-if="loading" class="badge warn">加载中</span>
<button class="btn ghost" @click="load"><RefreshCw :size="16" />刷新</button>
</div>
</header>
<p v-if="toast" class="notice">{{ toast }}</p>
<DashboardView v-if="currentPath === '/admin/dashboard'" :ctx="viewContext" />
<FeedbacksView v-else-if="currentPath === '/admin/feedbacks'" :ctx="viewContext" />
<ReleasesView v-else-if="currentPath === '/admin/releases'" :ctx="viewContext" />
<LegacyJsonView v-else-if="activeLegacyName" :ctx="viewContext" />
<SourcesView v-else-if="currentPath === '/admin/sources'" :ctx="viewContext" />
<EndpointsView v-else-if="currentPath === '/admin/endpoints'" :ctx="viewContext" />
<DatabaseView v-else-if="currentPath === '/admin/database'" :ctx="viewContext" />
<HealthView v-else-if="currentPath === '/admin/health'" :ctx="viewContext" />
<SettingsView v-else-if="currentPath === '/admin/settings'" :ctx="viewContext" />
<AuditView v-else-if="currentPath === '/admin/audit'" :ctx="viewContext" />
</section>
</main>
</template>
@@ -0,0 +1,11 @@
<script setup lang="ts">
withDefaults(defineProps<{ tone?: "default" | "warning" | "danger" }>(), {
tone: "default"
});
</script>
<template>
<div :class="['ui-alert', `ui-alert--${tone}`]">
<slot />
</div>
</template>
@@ -0,0 +1,14 @@
<script setup lang="ts">
import { computed } from "vue";
import { cn } from "../../lib/cn";
const props = withDefaults(defineProps<{ variant?: "default" | "secondary" | "warning" }>(), {
variant: "default"
});
const classes = computed(() => cn("ui-badge", `ui-badge--${props.variant}`));
</script>
<template>
<span :class="classes"><slot /></span>
</template>
@@ -0,0 +1,20 @@
<script setup lang="ts">
import { computed } from "vue";
import { cn } from "../../lib/cn";
const props = withDefaults(defineProps<{
variant?: "default" | "primary" | "ghost" | "outline";
type?: "button" | "submit" | "reset";
}>(), {
variant: "default",
type: "button"
});
const classes = computed(() => cn("ui-button", `ui-button--${props.variant}`));
</script>
<template>
<button :type="type" :class="classes">
<slot />
</button>
</template>
@@ -0,0 +1,5 @@
<template>
<section class="ui-card">
<slot />
</section>
</template>
@@ -0,0 +1,7 @@
<template>
<div class="ui-table-wrap">
<table class="ui-table">
<slot />
</table>
</div>
</template>
@@ -0,0 +1,3 @@
export function cn(...values: Array<string | false | null | undefined>) {
return values.filter(Boolean).join(" ");
}
@@ -0,0 +1,32 @@
import { createApp } from "vue";
import { createRouter, createWebHistory } from "vue-router";
import App from "./App.vue";
import "./styles.css";
const RoutePlaceholder = { template: "<span />" };
const routes = [
"/admin/login",
"/admin/dashboard",
"/admin/feedbacks",
"/admin/releases",
"/admin/legacy/update-info",
"/admin/legacy/media-types",
"/admin/sources",
"/admin/endpoints",
"/admin/database",
"/admin/health",
"/admin/settings",
"/admin/audit",
].map((path) => ({ path, component: RoutePlaceholder }));
const router = createRouter({
history: createWebHistory(),
routes: [
...routes,
{ path: "/admin", redirect: "/admin/dashboard" },
{ path: "/admin/:pathMatch(.*)*", redirect: "/admin/dashboard" },
],
});
createApp(App).use(router).mount("#app");
@@ -0,0 +1,325 @@
:root {
color-scheme: light;
font-family: "Microsoft YaHei UI", "Segoe UI", Arial, sans-serif;
background: #f5f7fb;
color: #111827;
--bg: #f5f7fb;
--panel: #ffffff;
--panel-soft: #f8fafc;
--line: #dfe5ee;
--line-strong: #c6d1de;
--ink: #111827;
--muted: #5f6b7a;
--primary: #2563eb;
--primary-dark: #1d4ed8;
--primary-soft: #e8f0ff;
--good: #047857;
--good-bg: #e8f7ef;
--warn: #b45309;
--warn-bg: #fff7e6;
--bad: #b42318;
--bad-bg: #fff0ed;
--shadow: 0 18px 50px rgba(15, 23, 42, 0.08);
}
* { box-sizing: border-box; }
html { min-width: 320px; }
body { margin: 0; background: var(--bg); }
button, input, textarea, select { font: inherit; }
button { cursor: pointer; }
button:disabled { cursor: not-allowed; opacity: 0.65; }
a { color: inherit; }
h1, h2, h3, p { margin-top: 0; }
h1 { margin-bottom: 4px; font-size: 28px; line-height: 1.15; letter-spacing: 0; }
h2 { margin-bottom: 12px; font-size: 18px; line-height: 1.25; }
h3 { margin-bottom: 8px; font-size: 15px; }
.muted { margin-bottom: 0; color: var(--muted); line-height: 1.65; }
.mono, .hash, pre, .code-editor { font-family: "Cascadia Mono", "SFMono-Regular", Consolas, monospace; }
.hash { max-width: 380px; overflow-wrap: anywhere; font-size: 12px; }
.eyebrow { margin: 0 0 6px; color: var(--primary); text-transform: uppercase; letter-spacing: 0.08em; font-size: 12px; font-weight: 800; }
.login-shell {
min-height: 100dvh;
display: grid;
place-items: center;
padding: 24px;
background:
linear-gradient(135deg, rgba(37, 99, 235, 0.12), transparent 40%),
radial-gradient(circle at 82% 12%, rgba(4, 120, 87, 0.10), transparent 34%),
#f5f7fb;
}
.login-panel {
width: min(460px, 100%);
display: flex;
flex-direction: column;
gap: 18px;
padding: 28px;
background: rgba(255, 255, 255, 0.96);
border: 1px solid var(--line);
border-radius: 8px;
box-shadow: var(--shadow);
}
.form-stack, .page-stack, .editor-panel { display: flex; flex-direction: column; gap: 14px; }
label { display: flex; flex-direction: column; gap: 6px; color: #374151; font-weight: 700; font-size: 13px; }
input, textarea, select {
width: 100%;
min-height: 40px;
border: 1px solid var(--line);
border-radius: 6px;
background: #fff;
color: var(--ink);
padding: 8px 10px;
outline: none;
}
textarea { resize: vertical; line-height: 1.55; }
input:focus, textarea:focus, select:focus {
border-color: var(--primary);
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.12);
}
.captcha-row { display: grid; grid-template-columns: 1fr 150px; gap: 10px; align-items: end; }
.captcha-button {
min-height: 40px;
border: 1px solid var(--line);
border-radius: 6px;
background: #fff;
padding: 0;
overflow: hidden;
display: grid;
place-items: center;
font-weight: 800;
}
.captcha-button img { width: 100%; height: 42px; object-fit: cover; display: block; }
.btn {
min-height: 38px;
border: 1px solid var(--line);
border-radius: 6px;
background: #fff;
color: var(--ink);
padding: 8px 12px;
text-decoration: none;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
font-weight: 800;
transition: background-color 0.18s ease, border-color 0.18s ease, color 0.18s ease, box-shadow 0.18s ease;
}
.btn:hover { border-color: var(--line-strong); background: #f9fafb; }
.btn.primary { background: var(--primary); color: #fff; border-color: var(--primary); }
.btn.primary:hover { background: var(--primary-dark); border-color: var(--primary-dark); }
.btn.ghost { background: transparent; }
.btn.compact { min-height: 30px; padding: 5px 8px; font-size: 12px; }
.btn.full { width: 100%; }
.button-row, .top-actions, .toolbar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.alert-line, .notice {
border: 1px solid #f0c36a;
background: var(--warn-bg);
color: #7a3b00;
border-radius: 6px;
padding: 11px 12px;
line-height: 1.55;
}
.app-shell { min-height: 100dvh; display: grid; grid-template-columns: 260px minmax(0, 1fr); }
.sidebar {
border-right: 1px solid var(--line);
background: rgba(255, 255, 255, 0.94);
backdrop-filter: blur(12px);
padding: 18px;
display: flex;
flex-direction: column;
gap: 18px;
position: sticky;
top: 0;
height: 100dvh;
}
.brand { display: flex; gap: 12px; align-items: center; padding-bottom: 14px; border-bottom: 1px solid var(--line); }
.brand-mark { width: 38px; height: 38px; border-radius: 8px; display: grid; place-items: center; background: #111827; color: #fff; }
.brand strong { display: block; }
.brand small { display: block; color: var(--muted); margin-top: 2px; }
.nav-groups { display: flex; flex-direction: column; gap: 14px; flex: 1; overflow-y: auto; }
.nav-group { display: flex; flex-direction: column; gap: 5px; }
.nav-group p {
margin: 0 0 2px;
color: var(--muted);
font-size: 11px;
font-weight: 900;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.nav-group button, .logout {
border: 0;
border-radius: 6px;
background: transparent;
text-align: left;
padding: 10px;
display: flex;
align-items: center;
gap: 10px;
color: #526070;
font-weight: 800;
transition: background-color 0.18s ease, color 0.18s ease;
}
.nav-group button:hover, .logout:hover { background: #eef4ff; color: var(--primary-dark); }
.nav-group button.active { background: var(--primary-soft); color: var(--primary-dark); }
.logout { color: #7f1d1d; }
.workspace { min-width: 0; padding: 24px; display: flex; flex-direction: column; gap: 18px; }
.topbar, .section-head { display: flex; justify-content: space-between; align-items: center; gap: 14px; }
.topbar { min-height: 72px; }
.section-head h2 { margin: 0; }
.section-head a { color: var(--primary); font-weight: 800; text-decoration: none; }
.metric-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; }
.metric, .panel {
background: rgba(255, 255, 255, 0.98);
border: 1px solid var(--line);
border-radius: 8px;
padding: 16px;
box-shadow: 0 1px 2px rgba(17, 24, 39, 0.04);
}
.metric { min-height: 116px; display: flex; flex-direction: column; justify-content: space-between; }
.metric span, .metric small { color: var(--muted); }
.metric strong { font-size: 26px; overflow-wrap: anywhere; }
.chart-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; }
.chart-panel { min-height: 330px; display: flex; flex-direction: column; }
.chart { min-height: 260px; width: 100%; flex: 1; }
.quick-panel { display: flex; flex-direction: column; gap: 12px; }
.quick-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; }
.quick-grid button {
min-height: 112px;
border: 1px solid var(--line);
border-radius: 8px;
background: #fff;
color: var(--ink);
padding: 12px;
display: grid;
align-content: start;
gap: 7px;
text-align: left;
}
.quick-grid button:hover { border-color: var(--primary); background: #f8fbff; }
.quick-grid svg { color: var(--primary); }
.quick-grid span { color: var(--muted); line-height: 1.45; font-size: 13px; }
.split { display: grid; grid-template-columns: minmax(0, 1fr) 390px; gap: 14px; align-items: start; }
.split.wide-split { grid-template-columns: minmax(380px, 0.95fr) minmax(0, 1.05fr); }
.search-box {
min-width: min(420px, 100%);
flex: 1;
display: flex;
flex-direction: row;
align-items: center;
background: #fff;
border: 1px solid var(--line);
border-radius: 6px;
padding: 0 10px;
color: var(--muted);
}
.search-box input { border: 0; box-shadow: none; }
.search-box input:focus { box-shadow: none; }
table { width: 100%; border-collapse: collapse; font-size: 14px; }
th, td { border-bottom: 1px solid var(--line); padding: 10px 8px; text-align: left; vertical-align: top; }
th { color: var(--muted); font-size: 12px; text-transform: uppercase; letter-spacing: 0.03em; }
tr.clickable { cursor: pointer; }
tr.clickable:hover td { background: #f8fbff; }
tr.selected td { background: #eef4ff; }
.badge {
display: inline-flex;
min-height: 24px;
align-items: center;
gap: 4px;
border: 1px solid var(--line);
border-radius: 999px;
background: #f3f4f6;
color: #374151;
padding: 2px 8px;
font-size: 12px;
font-weight: 900;
white-space: nowrap;
}
.badge.good { background: var(--good-bg); color: var(--good); border-color: #b7e4ca; }
.badge.warn { background: var(--warn-bg); color: var(--warn); border-color: #f4d38c; }
.badge.bad { background: var(--bad-bg); color: var(--bad); border-color: #f0b8b1; }
.badge.neutral { background: #f3f4f6; color: #4b5563; border-color: var(--line); }
.two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.checkbox { flex-direction: row; align-items: center; font-weight: 700; color: var(--muted); }
.checkbox input { width: auto; min-height: auto; }
.detail-panel { position: sticky; top: 18px; max-height: calc(100dvh - 36px); overflow: auto; }
hr { border: 0; border-top: 1px solid var(--line); width: 100%; margin: 12px 0; }
.comment-list { display: flex; flex-direction: column; gap: 8px; }
.comment { border: 1px solid var(--line); border-radius: 6px; padding: 9px; background: var(--panel-soft); }
.comment p { margin: 4px 0 0; color: var(--muted); }
.empty-state { min-height: 220px; display: grid; place-items: center; align-content: center; gap: 10px; color: var(--muted); text-align: center; }
.empty-state.compact { min-height: 96px; border: 1px dashed var(--line); border-radius: 6px; }
.source-group { margin-top: 12px; }
.source-group h3 { display: flex; align-items: center; gap: 8px; }
.code-editor { min-height: 56dvh; white-space: pre; overflow: auto; font-size: 13px; }
.compact-editor { min-height: 260px; }
details {
border: 1px solid var(--line);
border-radius: 6px;
padding: 10px;
background: #fff;
}
summary { cursor: pointer; font-weight: 900; margin-bottom: 10px; }
.json-preview {
margin: 0;
max-height: 360px;
overflow: auto;
border: 1px solid var(--line);
border-radius: 6px;
background: #0f172a;
color: #dbeafe;
padding: 12px;
font-size: 12px;
line-height: 1.6;
}
.json-preview.small { max-height: 260px; }
.json-preview.tall { max-height: 70dvh; }
.revision-list { display: flex; flex-direction: column; gap: 8px; }
.revision-list button {
border: 1px solid var(--line);
border-radius: 6px;
background: #fff;
color: var(--ink);
text-align: left;
padding: 10px;
}
.revision-list button:hover, .revision-list button.active { border-color: var(--primary); background: #f8fbff; }
.revision-list small { display: block; color: var(--muted); margin-top: 3px; }
.kv-grid { display: grid; grid-template-columns: 140px minmax(0, 1fr); gap: 11px 14px; }
.kv-grid span { color: var(--muted); }
.kv-grid strong { overflow-wrap: anywhere; }
@media (max-width: 1180px) {
.metric-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.chart-grid, .split, .split.wide-split { grid-template-columns: 1fr; }
.detail-panel { position: static; max-height: none; }
}
@media (max-width: 820px) {
.app-shell { grid-template-columns: 1fr; }
.sidebar { position: static; height: auto; }
.nav-groups { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); }
.workspace { padding: 16px; }
.topbar, .section-head { align-items: stretch; flex-direction: column; }
.metric-grid, .two-col { grid-template-columns: 1fr; }
.quick-grid { grid-template-columns: 1fr; }
.captcha-row { grid-template-columns: 1fr; }
table { min-width: 720px; }
.panel { overflow-x: auto; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { transition: none !important; scroll-behavior: auto !important; }
}
@@ -0,0 +1,22 @@
<script setup lang="ts">
defineProps<{ ctx: any }>();
</script>
<template>
<section class="panel page-stack">
<div class="section-head"><h2>审计日志</h2><button class="btn ghost" @click="ctx.loadAudit">刷新</button></div>
<table>
<thead><tr><th>类型</th><th>目标</th><th>信息</th><th>IP</th><th>时间</th></tr></thead>
<tbody>
<tr v-for="item in ctx.auditLogs" :key="item.id">
<td>{{ item.type }}</td>
<td>{{ item.target }}</td>
<td>{{ item.message }}</td>
<td>{{ item.ip || "-" }}</td>
<td>{{ item.createdAt }}</td>
</tr>
<tr v-if="ctx.auditLogs.length === 0"><td colspan="5">暂无审计日志</td></tr>
</tbody>
</table>
</section>
</template>
@@ -0,0 +1,84 @@
<script setup lang="ts">
import VChart from "vue-echarts";
import { use } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { BarChart, GaugeChart, LineChart, PieChart } from "echarts/charts";
import { GridComponent, LegendComponent, TooltipComponent } from "echarts/components";
import { Activity, PauseCircle, PlayCircle } from "lucide-vue-next";
defineProps<{ ctx: any }>();
use([CanvasRenderer, LineChart, PieChart, BarChart, GaugeChart, GridComponent, TooltipComponent, LegendComponent]);
</script>
<template>
<section class="page-stack">
<div class="metric-grid">
<article class="metric"><span>反馈总数</span><strong>{{ ctx.kpis.feedbackTotal || 0 }}</strong><small>今日新增 {{ ctx.kpis.feedbackToday || 0 }}</small></article>
<article class="metric"><span>可见接口</span><strong>{{ ctx.kpis.sourceVisible || 0 }}</strong><small>接口总数 {{ ctx.kpis.sourceTotal || 0 }}</small></article>
<article class="metric"><span>版本日志</span><strong>{{ ctx.kpis.releaseNotices || 0 }}</strong><small>{{ ctx.latestNotice?.version || "暂无最新版本" }}</small></article>
<article class="metric"><span>邮件失败</span><strong>{{ ctx.kpis.mailFailed || 0 }}</strong><small>旧反馈兼容记录</small></article>
</div>
<div class="toolbar">
<button class="btn primary" @click="ctx.checkSources"><Activity :size="16" />立即心跳检测</button>
<button class="btn ghost" @click="ctx.toggleAutoRefresh">
<component :is="ctx.autoRefreshPaused ? PlayCircle : PauseCircle" :size="16" />
{{ ctx.autoRefreshPaused ? "恢复自动刷新" : "暂停自动刷新" }}
</button>
<span class="muted"> 15 秒自动刷新仪表盘数据</span>
</div>
<section class="panel quick-panel">
<div class="section-head"><h2>功能总览</h2><span class="badge">{{ ctx.quickActions.length }} 个入口</span></div>
<div class="quick-grid">
<button v-for="item in ctx.quickActions" :key="item.path" @click="ctx.navigate(item.path)">
<component :is="item.icon" :size="18" />
<strong>{{ item.label }}</strong>
<span>{{ item.description }}</span>
</button>
</div>
</section>
<div class="chart-grid">
<section class="panel chart-panel"><h2>接口心跳延迟</h2><VChart class="chart" :option="ctx.heartbeatOption" autoresize /></section>
<section class="panel chart-panel"><h2>接口健康分布</h2><VChart class="chart" :option="ctx.healthOption" autoresize /></section>
<section class="panel chart-panel"><h2>反馈状态分布</h2><VChart class="chart" :option="ctx.feedbackOption" autoresize /></section>
<section class="panel chart-panel"><h2>服务可用率</h2><VChart class="chart" :option="ctx.availabilityOption" autoresize /></section>
</div>
<section class="panel">
<div class="section-head"><h2>最近接口心跳</h2><span class="badge">{{ ctx.heartbeats.length }} </span></div>
<table>
<thead><tr><th>接口</th><th>状态</th><th>延迟</th><th>错误</th><th>时间</th></tr></thead>
<tbody>
<tr v-for="item in ctx.heartbeats.slice(0, 10)" :key="item.id">
<td>{{ item.name || item.sourceId }}</td>
<td><span :class="['badge', ctx.statusTone(item.status)]">{{ ctx.labelStatus(item.status) }}</span></td>
<td>{{ item.latencyMs || 0 }}ms</td>
<td class="hash">{{ item.error || "-" }}</td>
<td>{{ item.checkedAt || "-" }}</td>
</tr>
<tr v-if="ctx.heartbeats.length === 0"><td colspan="5">暂无心跳记录点击立即心跳检测后会刷新</td></tr>
</tbody>
</table>
</section>
<section class="panel">
<div class="section-head"><h2>客户端调用上报</h2><span class="badge">{{ ctx.clientCalls.length }} </span></div>
<table>
<thead><tr><th>接口</th><th>状态</th><th>延迟</th><th>客户端</th><th>时间</th></tr></thead>
<tbody>
<tr v-for="item in ctx.clientCalls.slice(0, 8)" :key="item.id">
<td>{{ item.sourceId }}</td>
<td><span :class="['badge', ctx.statusTone(item.status)]">{{ ctx.labelStatus(item.status) }}</span></td>
<td>{{ item.latencyMs || 0 }}ms</td>
<td class="hash">{{ item.client || "-" }}</td>
<td>{{ item.createdAt || "-" }}</td>
</tr>
<tr v-if="ctx.clientCalls.length === 0"><td colspan="5">暂无客户端调用上报</td></tr>
</tbody>
</table>
</section>
</section>
</template>
@@ -0,0 +1,31 @@
<script setup lang="ts">
defineProps<{ ctx: any }>();
</script>
<template>
<section class="split">
<section class="panel page-stack">
<div class="section-head"><h2>数据库运行状态</h2><span :class="['badge', ctx.statusTone(ctx.database?.activeProvider)]">{{ ctx.database?.activeProvider || "-" }}</span></div>
<div class="kv-grid">
<span>配置类型</span><strong>{{ ctx.database?.configProvider || "-" }}</strong>
<span>SQLite</span><strong>{{ ctx.database?.sqliteReady ? "ready" : "missing" }}</strong>
<span>MySQL</span><strong>{{ ctx.database?.remoteReady ? "ready" : "offline" }}</strong>
<span>最后同步</span><strong>{{ ctx.database?.lastSyncAt || "-" }}</strong>
<span>最近错误</span><strong>{{ ctx.database?.lastSyncError || ctx.database?.lastError || "-" }}</strong>
</div>
<hr />
<div class="section-head"><h2>旧项目同步</h2><button class="btn ghost" @click="ctx.previewLegacySync">预览</button></div>
<pre class="json-preview small">{{ ctx.pretty(ctx.legacySync) }}</pre>
<button class="btn primary" @click="ctx.runLegacySync">执行旧项目同步</button>
</section>
<aside class="panel editor-panel">
<h2>连接与同步</h2>
<label>Provider<select v-model="ctx.databaseForm.provider"><option>sqlite</option><option>mysql</option></select></label>
<label>SQLite 路径<input v-model="ctx.databaseForm.sqlitePath" placeholder="留空使用当前配置" /></label>
<label>MySQL DSN<input v-model="ctx.databaseForm.mysqlDsn" placeholder="user:pass@tcp(host:3306)/db?parseTime=true" /></label>
<button class="btn ghost" @click="ctx.testDatabase">测试连接</button>
<button class="btn primary" @click="ctx.syncDatabase('import')">SQLite 导入远端</button>
<button class="btn ghost" @click="ctx.syncDatabase('sync')">远端同步回本地</button>
</aside>
</section>
</template>
@@ -0,0 +1,24 @@
<script setup lang="ts">
defineProps<{ ctx: any }>();
</script>
<template>
<section class="panel page-stack">
<div class="section-head"><h2>客户端动态接口</h2><span class="badge">{{ ctx.visibleEndpointCount }} 可见 / {{ ctx.healthyEndpointCount }} 健康</span></div>
<table>
<thead><tr><th>ID</th><th>分类</th><th>模式</th><th>健康</th><th>缓存</th><th>URL</th><th></th></tr></thead>
<tbody>
<tr v-for="item in ctx.endpoints" :key="item.id || item.sourceId">
<td class="mono">{{ item.id || item.sourceId }}</td>
<td>{{ item.category || item.categoryId }}</td>
<td>{{ item.proxyMode }}</td>
<td><span :class="['badge', ctx.statusTone(ctx.endpointStatus(item))]">{{ ctx.endpointStatus(item) }}</span></td>
<td>{{ item.cacheSeconds || 0 }}s</td>
<td class="hash">{{ item.urlTemplate || item.apiUrl }}</td>
<td><button class="btn ghost compact" @click="ctx.copyEndpointToSource(item)">编辑</button></td>
</tr>
<tr v-if="ctx.endpoints.length === 0"><td colspan="7">暂无客户端接口</td></tr>
</tbody>
</table>
</section>
</template>
@@ -0,0 +1,54 @@
<script setup lang="ts">
import { Save, Search, UploadCloud } from "lucide-vue-next";
defineProps<{ ctx: any }>();
</script>
<template>
<section class="split">
<section class="panel page-stack">
<div class="toolbar">
<label class="search-box"><Search :size="16" /><input v-model="ctx.feedbackFilters.q" placeholder="搜索编号、标题、联系方式" @keyup.enter="ctx.loadFeedbacks" /></label>
<select v-model="ctx.feedbackFilters.status" @change="ctx.loadFeedbacks"><option value="">全部状态</option><option value="new">new</option><option value="processing">processing</option><option value="closed">closed</option></select>
<button class="btn ghost" @click="ctx.loadFeedbacks">查询</button>
<a class="btn ghost" href="/api/admin/feedbacks/export" target="_blank"><UploadCloud :size="16" />CSV</a>
</div>
<table>
<thead><tr><th>编号</th><th>标题</th><th>状态</th><th>优先级</th><th>最近活动</th></tr></thead>
<tbody>
<tr v-for="item in ctx.feedbackPage.items" :key="item.code" class="clickable" :class="{ selected: ctx.selectedFeedback?.code === item.code }" @click="ctx.openFeedback(item)">
<td class="mono">{{ item.code }}</td>
<td>{{ item.title || item.summaryText || "未命名反馈" }}</td>
<td><span :class="['badge', ctx.statusTone(item.status)]">{{ item.status }}</span></td>
<td>{{ item.priority || "-" }}</td>
<td>{{ item.lastActivityAt || item.createdAt }}</td>
</tr>
<tr v-if="!ctx.feedbackPage.items?.length"><td colspan="5">暂无反馈工单</td></tr>
</tbody>
</table>
</section>
<aside class="panel detail-panel">
<template v-if="ctx.selectedFeedback">
<h2>{{ ctx.selectedFeedback.code }}</h2>
<p class="muted">{{ ctx.selectedFeedback.title || ctx.selectedFeedback.body }}</p>
<label>状态<select v-model="ctx.feedbackUpdate.status"><option>new</option><option>processing</option><option>closed</option></select></label>
<label>状态说明<input v-model="ctx.feedbackUpdate.statusDetail" /></label>
<label>公开回复<textarea v-model="ctx.feedbackUpdate.publicReply" rows="3"></textarea></label>
<button class="btn primary" @click="ctx.saveFeedbackUpdate"><Save :size="16" />保存状态</button>
<hr />
<h3>评论</h3>
<div class="comment-list">
<div v-for="item in ctx.selectedFeedback.comments || []" :key="item.id" class="comment"><strong>{{ item.author }}</strong><p>{{ item.body }}</p></div>
</div>
<label>新增评论<textarea v-model="ctx.commentDraft.body" rows="3"></textarea></label>
<label class="checkbox"><input v-model="ctx.commentDraft.internal" type="checkbox" />内部备注</label>
<button class="btn ghost" @click="ctx.addFeedbackComment">添加评论</button>
<details>
<summary>旧反馈事件 / 邮件记录</summary>
<pre class="json-preview small">{{ ctx.pretty({ events: ctx.selectedFeedback.legacyEvents, mail: ctx.selectedFeedback.mailRecords }) }}</pre>
</details>
</template>
<div v-else class="empty-state">选择一条工单查看详情</div>
</aside>
</section>
</template>
@@ -0,0 +1,10 @@
<script setup lang="ts">
defineProps<{ ctx: any }>();
</script>
<template>
<section class="panel page-stack">
<h2>健康快照</h2>
<pre class="json-preview tall">{{ ctx.pretty(ctx.healthSnapshot) }}</pre>
</section>
</template>
@@ -0,0 +1,30 @@
<script setup lang="ts">
import { CheckCircle2, Save } from "lucide-vue-next";
defineProps<{ ctx: any }>();
</script>
<template>
<section class="split wide-split">
<section class="panel editor-panel">
<div class="section-head">
<h2>{{ ctx.activeLegacyLabel }}</h2>
<div class="button-row">
<button class="btn ghost" @click="ctx.validateLegacy(ctx.activeLegacyName)"><CheckCircle2 :size="16" />校验</button>
<button class="btn primary" @click="ctx.saveLegacy(ctx.activeLegacyName)"><Save :size="16" />保存发布</button>
</div>
</div>
<textarea v-model="ctx.legacyDrafts[ctx.activeLegacyName].raw" class="code-editor"></textarea>
<label>保存备注<input v-model="ctx.legacyDrafts[ctx.activeLegacyName].note" /></label>
</section>
<aside class="panel page-stack">
<h2>预览与历史</h2>
<pre class="json-preview">{{ ctx.pretty(ctx.legacyDrafts[ctx.activeLegacyName].preview) }}</pre>
<div class="revision-list">
<button v-for="revision in ctx.legacyDocuments[ctx.activeLegacyName]?.revisions || []" :key="revision.id" @click="ctx.restoreLegacy(ctx.activeLegacyName, revision.id)">
#{{ revision.id }} {{ revision.createdAt }}<small>{{ revision.note || "无备注" }}</small>
</button>
</div>
</aside>
</section>
</template>
@@ -0,0 +1,51 @@
<script setup lang="ts">
import { CheckCircle2, Save } from "lucide-vue-next";
defineProps<{ ctx: any }>();
</script>
<template>
<section class="split wide-split">
<section class="panel page-stack">
<div class="section-head">
<h2>发布包</h2>
<a href="/update-info.json" target="_blank">查看旧版 update-info.json</a>
</div>
<table>
<thead><tr><th>文件</th><th>版本</th><th>平台</th><th>大小</th><th>SHA256</th></tr></thead>
<tbody>
<tr v-for="pkg in ctx.releasePackages" :key="pkg.fileName || pkg.url">
<td>{{ pkg.fileName || pkg.name }}</td>
<td>{{ pkg.version || ctx.releases?.app_version || "-" }}</td>
<td>{{ pkg.platform || "-" }}/{{ pkg.arch || "-" }}</td>
<td>{{ ctx.formatBytes(pkg.sizeBytes || pkg.size || 0) }}</td>
<td class="hash">{{ pkg.sha256 || "-" }}</td>
</tr>
<tr v-if="ctx.releasePackages.length === 0"><td colspan="5">暂无可见发布包</td></tr>
</tbody>
</table>
</section>
<aside class="panel editor-panel">
<div class="section-head"><h2>版本日志</h2><button class="btn ghost" @click="ctx.importNotices">导入目录</button></div>
<div class="revision-list">
<button v-for="item in ctx.releaseNotices" :key="item.version" :class="{ active: ctx.noticeDraft.version === item.version }" @click="ctx.openNotice(item.version)">
<strong>{{ item.version }}</strong><small>{{ item.title || item.updatedAt }}</small>
</button>
<div v-if="ctx.releaseNotices.length === 0" class="empty-state compact">暂无版本日志可先执行导入</div>
</div>
<label>版本<input v-model="ctx.noticeDraft.version" placeholder="1.0.0" /></label>
<label>Raw JSON<textarea v-model="ctx.noticeDraft.raw" class="code-editor compact-editor"></textarea></label>
<label>备注<input v-model="ctx.noticeDraft.note" /></label>
<div class="button-row">
<button class="btn ghost" @click="ctx.validateNotice"><CheckCircle2 :size="16" />校验</button>
<button class="btn primary" @click="ctx.saveNotice"><Save :size="16" />保存日志</button>
</div>
<details v-if="ctx.selectedNotice?.revisions?.length">
<summary>历史版本</summary>
<div class="revision-list">
<button v-for="revision in ctx.selectedNotice.revisions" :key="revision.id" @click="ctx.restoreNotice(revision.id)">#{{ revision.id }} {{ revision.createdAt }}</button>
</div>
</details>
</aside>
</section>
</template>
@@ -0,0 +1,21 @@
<script setup lang="ts">
import { KeyRound } from "lucide-vue-next";
defineProps<{ ctx: any }>();
</script>
<template>
<section class="split">
<section class="panel editor-panel">
<h2>修改后台密码</h2>
<label>当前密码<input v-model="ctx.passwordForm.currentPassword" type="password" /></label>
<label>新密码<input v-model="ctx.passwordForm.newPassword" type="password" /></label>
<button class="btn primary" @click="ctx.changePassword"><KeyRound :size="16" />保存密码</button>
</section>
<section class="panel page-stack">
<div class="section-head"><h2>旧项目同步预览</h2><button class="btn ghost" @click="ctx.previewLegacySync">刷新预览</button></div>
<pre class="json-preview">{{ ctx.pretty(ctx.legacySync) }}</pre>
<button class="btn primary" @click="ctx.runLegacySync">执行同步</button>
</section>
</section>
</template>
@@ -0,0 +1,43 @@
<script setup lang="ts">
defineProps<{ ctx: any }>();
</script>
<template>
<section class="split">
<section class="panel page-stack">
<div class="section-head"><h2>媒体/数据源</h2><button class="btn primary" @click="ctx.checkSources">批量检测</button></div>
<div v-for="cat in ctx.sourceCategories" :key="cat.id || cat.name" class="source-group">
<h3>{{ cat.name || cat.id }} <span class="badge">{{ cat.subcategories?.length || 0 }}</span></h3>
<table>
<thead><tr><th>名称</th><th>模式</th><th>状态</th><th>延迟</th><th>URL</th></tr></thead>
<tbody>
<tr v-for="src in cat.subcategories || []" :key="src.id || src.sourceId">
<td>{{ src.name }}</td>
<td>{{ src.proxyMode || src.proxy_mode || "client_direct" }}</td>
<td><span :class="['badge', ctx.statusTone(src.health?.status || src.lastStatus)]">{{ src.health?.status || src.lastStatus || "unknown" }}</span></td>
<td>{{ src.health?.latency_ms || src.lastLatencyMs || 0 }}ms</td>
<td class="hash">{{ src.api_url || src.urlTemplate || src.apiUrl }}</td>
</tr>
</tbody>
</table>
</div>
<div v-if="ctx.sourceCategories.length === 0" class="empty-state">暂无接口源可从旧 media-types.json 导入或手动添加</div>
</section>
<aside class="panel editor-panel">
<h2>添加/覆盖接口</h2>
<label>ID<input v-model="ctx.sourceDraft.sourceId" /></label>
<label>名称<input v-model="ctx.sourceDraft.name" /></label>
<label>分类 ID<input v-model="ctx.sourceDraft.categoryId" /></label>
<label>分类名称<input v-model="ctx.sourceDraft.categoryName" /></label>
<label>URL<input v-model="ctx.sourceDraft.apiUrl" /></label>
<label>代理模式<select v-model="ctx.sourceDraft.proxyMode"><option>client_direct</option><option>server_proxy</option><option>disabled</option></select></label>
<div class="two-col">
<label>缓存秒数<input v-model.number="ctx.sourceDraft.cacheSeconds" type="number" /></label>
<label>检测间隔<input v-model.number="ctx.sourceDraft.checkIntervalSec" type="number" /></label>
</div>
<label class="checkbox"><input v-model="ctx.sourceDraft.enabled" type="checkbox" />启用</label>
<label class="checkbox"><input v-model="ctx.sourceDraft.clientVisible" type="checkbox" />客户端可见</label>
<button class="btn primary" @click="ctx.saveSource">保存接口</button>
</aside>
</section>
</template>
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"jsx": "preserve",
"resolveJsonModule": true,
"isolatedModules": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"types": ["vite/client"]
},
"include": ["src/**/*.ts", "src/**/*.vue"]
}
@@ -0,0 +1,12 @@
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
export default defineConfig({
base: "/admin/",
plugins: [vue()],
server: {
proxy: {
"/api": "http://127.0.0.1:33550"
}
}
});