提交代码
This commit is contained in:
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* 系统参数配置接口封装。
|
||||
* 后端实现见 HardwareWeb/Controllers/SystemConfigController.cs:
|
||||
* POST /api/system-config/auth -> { token, expiresAt }
|
||||
* GET /api/system-config -> SystemConfig[]
|
||||
* POST /api/system-config -> SystemConfig
|
||||
* PUT /api/system-config/{id} -> SystemConfig
|
||||
* DELETE /api/system-config/{id} -> 204
|
||||
* 除密码校验外,其余接口都需要携带 X-Admin-Token 请求头。
|
||||
*/
|
||||
|
||||
export interface SystemConfig {
|
||||
configId: number
|
||||
configClass: string
|
||||
configName: string
|
||||
configValue: string
|
||||
configDescript: string
|
||||
}
|
||||
|
||||
export interface SystemConfigInput {
|
||||
configClass: string
|
||||
configName: string
|
||||
configValue: string
|
||||
configDescript: string
|
||||
}
|
||||
|
||||
interface AdminAuthResult {
|
||||
token: string
|
||||
expiresAt: string
|
||||
}
|
||||
|
||||
const API_BASE = (import.meta.env.VITE_API_BASE ?? '').replace(/\/$/, '')
|
||||
const REQUEST_TIMEOUT = 8000
|
||||
const TOKEN_KEY = 'libs-admin-token'
|
||||
|
||||
export class SystemConfigApiError extends Error {
|
||||
readonly status: number
|
||||
|
||||
constructor(message: string, status = 0) {
|
||||
super(message)
|
||||
this.name = 'SystemConfigApiError'
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
export function getAdminToken(): string {
|
||||
return window.sessionStorage.getItem(TOKEN_KEY) ?? ''
|
||||
}
|
||||
|
||||
export function hasAdminSession(): boolean {
|
||||
return getAdminToken() !== ''
|
||||
}
|
||||
|
||||
export function clearAdminSession() {
|
||||
window.sessionStorage.removeItem(TOKEN_KEY)
|
||||
}
|
||||
|
||||
function setAdminToken(token: string) {
|
||||
window.sessionStorage.setItem(TOKEN_KEY, token)
|
||||
}
|
||||
|
||||
async function request<T>(
|
||||
path: string,
|
||||
init?: RequestInit,
|
||||
withToken = true,
|
||||
): Promise<T> {
|
||||
const controller = new AbortController()
|
||||
const timer = window.setTimeout(() => controller.abort(), REQUEST_TIMEOUT)
|
||||
|
||||
try {
|
||||
const token = withToken ? getAdminToken() : ''
|
||||
const response = await fetch(`${API_BASE}${path}`, {
|
||||
...init,
|
||||
cache: 'no-store',
|
||||
signal: controller.signal,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
...(init?.body ? { 'Content-Type': 'application/json' } : {}),
|
||||
...(token ? { 'X-Admin-Token': token } : {}),
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
let detail = `HTTP ${response.status}`
|
||||
try {
|
||||
const body = (await response.json()) as { message?: string; error?: string }
|
||||
detail = body.message ?? body.error ?? detail
|
||||
} catch {
|
||||
// 响应不是 JSON 时保留状态码信息
|
||||
}
|
||||
|
||||
if (response.status === 401 && withToken) {
|
||||
clearAdminSession()
|
||||
}
|
||||
|
||||
throw new SystemConfigApiError(detail, response.status)
|
||||
}
|
||||
|
||||
if (response.status === 204) {
|
||||
return undefined as T
|
||||
}
|
||||
|
||||
return (await response.json()) as T
|
||||
} catch (error) {
|
||||
if (error instanceof SystemConfigApiError) throw error
|
||||
if (error instanceof DOMException && error.name === 'AbortError') {
|
||||
throw new SystemConfigApiError('系统参数服务响应超时')
|
||||
}
|
||||
throw new SystemConfigApiError(
|
||||
error instanceof Error ? error.message : '无法连接系统参数服务',
|
||||
)
|
||||
} finally {
|
||||
window.clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
||||
/** 校验管理密码,成功后令牌会写入 sessionStorage。 */
|
||||
export async function verifyAdminPassword(password: string): Promise<void> {
|
||||
const result = await request<AdminAuthResult>(
|
||||
'/api/system-config/auth',
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ password }),
|
||||
},
|
||||
false,
|
||||
)
|
||||
setAdminToken(result.token)
|
||||
}
|
||||
|
||||
export function listSystemConfigs(keyword = ''): Promise<SystemConfig[]> {
|
||||
const query = keyword ? `?keyword=${encodeURIComponent(keyword)}` : ''
|
||||
return request<SystemConfig[]>(`/api/system-config${query}`)
|
||||
}
|
||||
|
||||
export function createSystemConfig(input: SystemConfigInput): Promise<SystemConfig> {
|
||||
return request<SystemConfig>('/api/system-config', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(input),
|
||||
})
|
||||
}
|
||||
|
||||
export function updateSystemConfig(
|
||||
configId: number,
|
||||
input: SystemConfigInput,
|
||||
): Promise<SystemConfig> {
|
||||
return request<SystemConfig>(`/api/system-config/${configId}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(input),
|
||||
})
|
||||
}
|
||||
|
||||
export function deleteSystemConfig(configId: number): Promise<void> {
|
||||
return request<void>(`/api/system-config/${configId}`, { method: 'DELETE' })
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { verifyAdminPassword } from '@/api/systemConfig'
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: []
|
||||
success: []
|
||||
}>()
|
||||
|
||||
const password = ref('')
|
||||
const error = ref('')
|
||||
const submitting = ref(false)
|
||||
const inputElement = ref<HTMLInputElement | null>(null)
|
||||
|
||||
function close() {
|
||||
if (submitting.value) return
|
||||
emit('close')
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent) {
|
||||
if (event.key === 'Escape') close()
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (submitting.value) return
|
||||
|
||||
if (!password.value) {
|
||||
error.value = '请输入密码'
|
||||
return
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
error.value = ''
|
||||
|
||||
try {
|
||||
await verifyAdminPassword(password.value)
|
||||
password.value = ''
|
||||
emit('success')
|
||||
} catch (err) {
|
||||
error.value = err instanceof Error ? err.message : '密码校验失败'
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
async (open) => {
|
||||
if (open) {
|
||||
password.value = ''
|
||||
error.value = ''
|
||||
window.addEventListener('keydown', onKeydown)
|
||||
await nextTick()
|
||||
inputElement.value?.focus()
|
||||
} else {
|
||||
window.removeEventListener('keydown', onKeydown)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('keydown', onKeydown)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<Transition name="auth-modal">
|
||||
<div v-if="open" class="auth-backdrop" @click.self="close">
|
||||
<section class="auth-card" role="dialog" aria-modal="true" aria-label="管理员验证">
|
||||
<div class="auth-card__icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 64 64">
|
||||
<rect
|
||||
x="14"
|
||||
y="28"
|
||||
width="36"
|
||||
height="26"
|
||||
rx="6"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="3"
|
||||
/>
|
||||
<path
|
||||
d="M22 28v-8a10 10 0 0 1 20 0v8"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="3"
|
||||
stroke-linecap="round"
|
||||
/>
|
||||
<circle cx="32" cy="41" r="3.2" fill="currentColor" />
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<h2>管理员验证</h2>
|
||||
<p>请输入管理员密码以进入系统参数管理</p>
|
||||
|
||||
<form class="auth-card__form" @submit.prevent="submit">
|
||||
<input
|
||||
ref="inputElement"
|
||||
v-model="password"
|
||||
class="auth-card__input"
|
||||
type="password"
|
||||
autocomplete="off"
|
||||
placeholder="请输入密码"
|
||||
:disabled="submitting"
|
||||
/>
|
||||
<p v-if="error" class="auth-card__error">{{ error }}</p>
|
||||
|
||||
<div class="auth-card__actions">
|
||||
<button
|
||||
class="auth-card__button auth-card__button--ghost"
|
||||
type="button"
|
||||
:disabled="submitting"
|
||||
@click="close"
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
class="auth-card__button auth-card__button--primary"
|
||||
type="submit"
|
||||
:disabled="submitting"
|
||||
>
|
||||
{{ submitting ? '验证中...' : '确定' }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
</Transition>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.auth-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 70;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 24px;
|
||||
background: rgba(18, 33, 54, 0.44);
|
||||
backdrop-filter: blur(5px);
|
||||
}
|
||||
|
||||
.auth-card {
|
||||
width: 560px;
|
||||
padding: 42px 44px 38px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.65);
|
||||
border-radius: 24px;
|
||||
background: #fff;
|
||||
box-shadow: 0 30px 80px rgba(12, 30, 55, 0.3);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.auth-card__icon {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 86px;
|
||||
height: 86px;
|
||||
margin: 0 auto 24px;
|
||||
border-radius: 50%;
|
||||
color: var(--blue);
|
||||
background: linear-gradient(145deg, #f1f7ff, #dfeaff);
|
||||
box-shadow: inset 0 1px 0 #fff, 0 8px 22px rgba(47, 111, 208, 0.14);
|
||||
}
|
||||
|
||||
.auth-card__icon svg {
|
||||
width: 46px;
|
||||
height: 46px;
|
||||
}
|
||||
|
||||
.auth-card h2 {
|
||||
color: #1f2937;
|
||||
font-size: 30px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.auth-card p {
|
||||
margin-top: 14px;
|
||||
color: #778394;
|
||||
font-size: 19px;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.auth-card__form {
|
||||
margin-top: 26px;
|
||||
}
|
||||
|
||||
.auth-card__input {
|
||||
width: 100%;
|
||||
height: 62px;
|
||||
padding: 0 22px;
|
||||
border: 2px solid var(--line-strong);
|
||||
border-radius: 12px;
|
||||
color: var(--ink);
|
||||
font-family: inherit;
|
||||
font-size: 22px;
|
||||
letter-spacing: 2px;
|
||||
outline: none;
|
||||
transition: border-color 0.2s ease, box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
.auth-card__input:focus {
|
||||
border-color: var(--blue);
|
||||
box-shadow: 0 0 0 4px rgba(47, 111, 208, 0.14);
|
||||
}
|
||||
|
||||
.auth-card__input:disabled {
|
||||
background: #f4f6f9;
|
||||
}
|
||||
|
||||
.auth-card__error {
|
||||
margin-top: 12px;
|
||||
color: var(--red);
|
||||
font-size: 17px;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.auth-card__actions {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 18px;
|
||||
margin-top: 30px;
|
||||
}
|
||||
|
||||
.auth-card__button {
|
||||
height: 56px;
|
||||
border-radius: 12px;
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 3px;
|
||||
transition: transform 0.2s ease, box-shadow 0.2s ease, background 0.2s ease;
|
||||
}
|
||||
|
||||
.auth-card__button:disabled {
|
||||
cursor: default;
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
.auth-card__button--ghost {
|
||||
border: 2px solid var(--line-strong);
|
||||
color: var(--ink-soft);
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.auth-card__button--ghost:hover:not(:disabled) {
|
||||
background: var(--surface-soft);
|
||||
}
|
||||
|
||||
.auth-card__button--primary {
|
||||
color: #fff;
|
||||
background: linear-gradient(180deg, #4b89e4 0%, #2f6fd0 100%);
|
||||
box-shadow: 0 10px 22px rgba(47, 111, 208, 0.28);
|
||||
}
|
||||
|
||||
.auth-card__button--primary:hover:not(:disabled) {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 14px 28px rgba(47, 111, 208, 0.36);
|
||||
}
|
||||
|
||||
.auth-modal-enter-active,
|
||||
.auth-modal-leave-active {
|
||||
transition: opacity 0.24s ease;
|
||||
}
|
||||
|
||||
.auth-modal-enter-active .auth-card,
|
||||
.auth-modal-leave-active .auth-card {
|
||||
transition: transform 0.24s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.24s ease;
|
||||
}
|
||||
|
||||
.auth-modal-enter-from,
|
||||
.auth-modal-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.auth-modal-enter-from .auth-card,
|
||||
.auth-modal-leave-to .auth-card {
|
||||
opacity: 0;
|
||||
transform: translateY(16px) scale(0.97);
|
||||
}
|
||||
</style>
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import HomeView from '@/views/HomeView.vue'
|
||||
import { hasAdminSession } from '@/api/systemConfig'
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
@@ -38,6 +39,12 @@ const router = createRouter({
|
||||
path: '/pay',
|
||||
redirect: { name: 'sample' },
|
||||
},
|
||||
{
|
||||
path: '/system-config',
|
||||
name: 'systemConfig',
|
||||
component: () => import('@/views/SystemConfigView.vue'),
|
||||
meta: { title: '系统参数管理', requiresAdmin: true },
|
||||
},
|
||||
{
|
||||
path: '/:pathMatch(.*)*',
|
||||
redirect: { name: 'home' },
|
||||
@@ -45,6 +52,14 @@ const router = createRouter({
|
||||
],
|
||||
})
|
||||
|
||||
router.beforeEach((to) => {
|
||||
if (to.meta.requiresAdmin && !hasAdminSession()) {
|
||||
return { name: 'home' }
|
||||
}
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
router.afterEach((to) => {
|
||||
document.title = (to.meta.title as string | undefined) ?? 'LIBS Lab'
|
||||
})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { onBeforeUnmount, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import AdminPasswordModal from '@/components/AdminPasswordModal.vue'
|
||||
import AppStage from '@/components/AppStage.vue'
|
||||
import ModuleButton from '@/components/ModuleButton.vue'
|
||||
import PrinciplePlayer from '@/components/PrinciplePlayer.vue'
|
||||
@@ -27,6 +28,43 @@ const modules: HomeModule[] = [
|
||||
const router = useRouter()
|
||||
const modalOpen = ref(false)
|
||||
const modalModule = ref('')
|
||||
const adminModalOpen = ref(false)
|
||||
|
||||
// 隐藏入口:800ms 内连续点击 Logo 三次,打开管理员密码框。
|
||||
const LOGO_CLICK_WINDOW = 800
|
||||
let logoClickCount = 0
|
||||
let logoTimer: number | undefined
|
||||
|
||||
function onLogoClick() {
|
||||
if (logoTimer !== undefined) {
|
||||
window.clearTimeout(logoTimer)
|
||||
}
|
||||
|
||||
logoClickCount += 1
|
||||
|
||||
if (logoClickCount >= 3) {
|
||||
logoClickCount = 0
|
||||
logoTimer = undefined
|
||||
adminModalOpen.value = true
|
||||
return
|
||||
}
|
||||
|
||||
logoTimer = window.setTimeout(() => {
|
||||
logoClickCount = 0
|
||||
logoTimer = undefined
|
||||
}, LOGO_CLICK_WINDOW)
|
||||
}
|
||||
|
||||
function onAdminSuccess() {
|
||||
adminModalOpen.value = false
|
||||
void router.push({ name: 'systemConfig' })
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (logoTimer !== undefined) {
|
||||
window.clearTimeout(logoTimer)
|
||||
}
|
||||
})
|
||||
|
||||
function openModule(module: HomeModule) {
|
||||
if (module.key === 'element') {
|
||||
@@ -44,7 +82,7 @@ function openModule(module: HomeModule) {
|
||||
<div class="home">
|
||||
<header class="home-header">
|
||||
<div class="brand">
|
||||
<img :src="logo" alt="泽科技 LIBS 标识" />
|
||||
<img :src="logo" alt="泽科技 LIBS 标识" @click="onLogoClick" />
|
||||
<span>LIBS</span>
|
||||
</div>
|
||||
|
||||
@@ -77,6 +115,12 @@ function openModule(module: HomeModule) {
|
||||
:module-name="modalModule"
|
||||
@close="modalOpen = false"
|
||||
/>
|
||||
|
||||
<AdminPasswordModal
|
||||
:open="adminModalOpen"
|
||||
@close="adminModalOpen = false"
|
||||
@success="onAdminSuccess"
|
||||
/>
|
||||
</AppStage>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -0,0 +1,743 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import AppStage from '@/components/AppStage.vue'
|
||||
import PageHeader from '@/components/PageHeader.vue'
|
||||
import {
|
||||
SystemConfigApiError,
|
||||
clearAdminSession,
|
||||
createSystemConfig,
|
||||
deleteSystemConfig,
|
||||
listSystemConfigs,
|
||||
updateSystemConfig,
|
||||
type SystemConfig,
|
||||
type SystemConfigInput,
|
||||
} from '@/api/systemConfig'
|
||||
import { showToast } from '@/composables/useToast'
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
const items = ref<SystemConfig[]>([])
|
||||
const keyword = ref('')
|
||||
const appliedKeyword = ref('')
|
||||
const loading = ref(false)
|
||||
|
||||
const formOpen = ref(false)
|
||||
const editingId = ref<number | null>(null)
|
||||
const formError = ref('')
|
||||
const saving = ref(false)
|
||||
const form = reactive<SystemConfigInput>({
|
||||
configClass: '',
|
||||
configName: '',
|
||||
configValue: '',
|
||||
configDescript: '',
|
||||
})
|
||||
const nameInput = ref<HTMLInputElement | null>(null)
|
||||
|
||||
const deleting = ref<SystemConfig | null>(null)
|
||||
const removing = ref(false)
|
||||
|
||||
const emptyText = computed(() => {
|
||||
if (loading.value) return '加载中...'
|
||||
return appliedKeyword.value ? '没有匹配的系统参数' : '暂无系统参数'
|
||||
})
|
||||
|
||||
function goHome() {
|
||||
void router.push({ name: 'home' })
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
try {
|
||||
items.value = await listSystemConfigs(appliedKeyword.value)
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function search() {
|
||||
appliedKeyword.value = keyword.value.trim()
|
||||
void load()
|
||||
}
|
||||
|
||||
function handleError(error: unknown, fallback = '操作失败') {
|
||||
if (error instanceof SystemConfigApiError) {
|
||||
if (error.status === 401) {
|
||||
clearAdminSession()
|
||||
showToast('管理员凭证已过期,请重新进入系统参数管理')
|
||||
void router.push({ name: 'home' })
|
||||
return
|
||||
}
|
||||
showToast(error.message || fallback)
|
||||
return
|
||||
}
|
||||
|
||||
showToast(error instanceof Error ? error.message : fallback)
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
editingId.value = null
|
||||
form.configClass = ''
|
||||
form.configName = ''
|
||||
form.configValue = ''
|
||||
form.configDescript = ''
|
||||
formError.value = ''
|
||||
formOpen.value = true
|
||||
void focusName()
|
||||
}
|
||||
|
||||
function openEdit(item: SystemConfig) {
|
||||
editingId.value = item.configId
|
||||
form.configClass = item.configClass
|
||||
form.configName = item.configName
|
||||
form.configValue = item.configValue
|
||||
form.configDescript = item.configDescript
|
||||
formError.value = ''
|
||||
formOpen.value = true
|
||||
void focusName()
|
||||
}
|
||||
|
||||
async function focusName() {
|
||||
await nextTick()
|
||||
nameInput.value?.focus()
|
||||
}
|
||||
|
||||
function closeForm() {
|
||||
if (saving.value) return
|
||||
formOpen.value = false
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (saving.value) return
|
||||
|
||||
if (!form.configName.trim()) {
|
||||
formError.value = '配置名称不能为空'
|
||||
return
|
||||
}
|
||||
|
||||
saving.value = true
|
||||
formError.value = ''
|
||||
|
||||
const payload: SystemConfigInput = {
|
||||
configClass: form.configClass.trim(),
|
||||
configName: form.configName.trim(),
|
||||
configValue: form.configValue.trim(),
|
||||
configDescript: form.configDescript.trim(),
|
||||
}
|
||||
|
||||
try {
|
||||
if (editingId.value === null) {
|
||||
await createSystemConfig(payload)
|
||||
showToast('系统参数已新增')
|
||||
} else {
|
||||
await updateSystemConfig(editingId.value, payload)
|
||||
showToast('系统参数已更新')
|
||||
}
|
||||
|
||||
formOpen.value = false
|
||||
await load()
|
||||
} catch (error) {
|
||||
if (error instanceof SystemConfigApiError && error.status === 401) {
|
||||
formOpen.value = false
|
||||
handleError(error)
|
||||
return
|
||||
}
|
||||
formError.value = error instanceof Error ? error.message : '保存失败'
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function askDelete(item: SystemConfig) {
|
||||
deleting.value = item
|
||||
}
|
||||
|
||||
function cancelDelete() {
|
||||
if (removing.value) return
|
||||
deleting.value = null
|
||||
}
|
||||
|
||||
async function confirmDelete() {
|
||||
const target = deleting.value
|
||||
if (!target || removing.value) return
|
||||
|
||||
removing.value = true
|
||||
try {
|
||||
await deleteSystemConfig(target.configId)
|
||||
deleting.value = null
|
||||
showToast('系统参数已删除')
|
||||
await load()
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
removing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void load()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppStage>
|
||||
<PageHeader title="系统参数管理" subtitle="系统运行参数集中配置">
|
||||
<template #left>
|
||||
<button class="header-button header-button--outline" type="button" @click="goHome">
|
||||
返回
|
||||
</button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<main class="system-main">
|
||||
<section class="config-card">
|
||||
<div class="config-toolbar">
|
||||
<div class="config-search">
|
||||
<input
|
||||
v-model="keyword"
|
||||
class="config-search__input"
|
||||
type="text"
|
||||
placeholder="搜索分类 / 名称 / 值 / 描述"
|
||||
@keyup.enter="search"
|
||||
/>
|
||||
<button class="toolbar-button" type="button" @click="search">查询</button>
|
||||
</div>
|
||||
|
||||
<div class="config-toolbar__right">
|
||||
<button class="toolbar-button toolbar-button--ghost" type="button" @click="load">
|
||||
刷新
|
||||
</button>
|
||||
<button class="toolbar-button toolbar-button--primary" type="button" @click="openCreate">
|
||||
新增参数
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="config-table">
|
||||
<div class="config-table__head">
|
||||
<span class="col-class">分类</span>
|
||||
<span class="col-name">名称</span>
|
||||
<span class="col-value">值</span>
|
||||
<span class="col-descript">描述</span>
|
||||
<span class="col-actions">操作</span>
|
||||
</div>
|
||||
|
||||
<div class="config-table__body">
|
||||
<div v-for="item in items" :key="item.configId" class="config-row">
|
||||
<span class="col-class">{{ item.configClass || '—' }}</span>
|
||||
<span class="col-name" :title="item.configName">{{ item.configName }}</span>
|
||||
<span class="col-value" :title="item.configValue">{{ item.configValue || '—' }}</span>
|
||||
<span class="col-descript" :title="item.configDescript">
|
||||
{{ item.configDescript || '—' }}
|
||||
</span>
|
||||
<span class="col-actions">
|
||||
<button class="row-button" type="button" @click="openEdit(item)">编辑</button>
|
||||
<button
|
||||
class="row-button row-button--danger"
|
||||
type="button"
|
||||
@click="askDelete(item)"
|
||||
>
|
||||
删除
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p v-if="!items.length" class="config-empty">{{ emptyText }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer class="config-footer">共 {{ items.length }} 条参数</footer>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<Teleport to="body">
|
||||
<Transition name="config-modal">
|
||||
<div v-if="formOpen" class="config-backdrop" @click.self="closeForm">
|
||||
<section class="form-card" role="dialog" aria-modal="true" aria-label="系统参数表单">
|
||||
<h2>{{ editingId === null ? '新增系统参数' : '编辑系统参数' }}</h2>
|
||||
|
||||
<div class="form-grid">
|
||||
<label class="form-field">
|
||||
<span>配置分类</span>
|
||||
<input v-model="form.configClass" type="text" placeholder="例如:设备、界面" />
|
||||
</label>
|
||||
|
||||
<label class="form-field">
|
||||
<span>配置名称 <em>*</em></span>
|
||||
<input
|
||||
ref="nameInput"
|
||||
v-model="form.configName"
|
||||
type="text"
|
||||
placeholder="例如:ExposureUs"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label class="form-field form-field--wide">
|
||||
<span>配置值</span>
|
||||
<input v-model="form.configValue" type="text" placeholder="参数值" />
|
||||
</label>
|
||||
|
||||
<label class="form-field form-field--wide">
|
||||
<span>配置描述</span>
|
||||
<textarea
|
||||
v-model="form.configDescript"
|
||||
rows="3"
|
||||
placeholder="说明该参数的用途"
|
||||
></textarea>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<p v-if="formError" class="form-error">{{ formError }}</p>
|
||||
|
||||
<div class="form-actions">
|
||||
<button
|
||||
class="form-button form-button--ghost"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
@click="closeForm"
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
class="form-button form-button--primary"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
@click="save"
|
||||
>
|
||||
{{ saving ? '保存中...' : '保存' }}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</Transition>
|
||||
</Teleport>
|
||||
|
||||
<Teleport to="body">
|
||||
<Transition name="config-modal">
|
||||
<div v-if="deleting" class="config-backdrop" @click.self="cancelDelete">
|
||||
<section class="confirm-card" role="dialog" aria-modal="true" aria-label="删除确认">
|
||||
<h2>删除系统参数</h2>
|
||||
<p>
|
||||
确定删除「{{ deleting.configName }}」吗?删除后不可恢复。
|
||||
</p>
|
||||
|
||||
<div class="form-actions">
|
||||
<button
|
||||
class="form-button form-button--ghost"
|
||||
type="button"
|
||||
:disabled="removing"
|
||||
@click="cancelDelete"
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
class="form-button form-button--danger"
|
||||
type="button"
|
||||
:disabled="removing"
|
||||
@click="confirmDelete"
|
||||
>
|
||||
{{ removing ? '删除中...' : '删除' }}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</Transition>
|
||||
</Teleport>
|
||||
</AppStage>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.system-main {
|
||||
position: absolute;
|
||||
top: 176px;
|
||||
right: 44px;
|
||||
bottom: 40px;
|
||||
left: 44px;
|
||||
}
|
||||
|
||||
.config-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
border-radius: var(--radius-lg);
|
||||
background: #fff;
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
|
||||
.config-toolbar {
|
||||
display: flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 24px;
|
||||
padding: 24px 30px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.config-search {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.config-search__input {
|
||||
width: 460px;
|
||||
height: 54px;
|
||||
padding: 0 20px;
|
||||
border: 2px solid var(--line-strong);
|
||||
border-radius: 10px;
|
||||
color: var(--ink);
|
||||
font-family: inherit;
|
||||
font-size: 19px;
|
||||
outline: none;
|
||||
transition: border-color 0.2s ease, box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
.config-search__input:focus {
|
||||
border-color: var(--blue);
|
||||
box-shadow: 0 0 0 4px rgba(47, 111, 208, 0.12);
|
||||
}
|
||||
|
||||
.config-toolbar__right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.toolbar-button {
|
||||
height: 54px;
|
||||
padding: 0 26px;
|
||||
border-radius: 10px;
|
||||
border: 2px solid var(--blue);
|
||||
color: var(--blue);
|
||||
font-size: 19px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 2px;
|
||||
background: #fff;
|
||||
transition: background 0.2s ease, transform 0.2s ease, box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
.toolbar-button:hover {
|
||||
background: var(--blue-soft);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.toolbar-button--ghost {
|
||||
border-color: var(--line-strong);
|
||||
color: var(--ink-soft);
|
||||
}
|
||||
|
||||
.toolbar-button--ghost:hover {
|
||||
background: var(--surface-soft);
|
||||
}
|
||||
|
||||
.toolbar-button--primary {
|
||||
border-color: transparent;
|
||||
color: #fff;
|
||||
background: linear-gradient(180deg, #4b89e4 0%, #2f6fd0 100%);
|
||||
box-shadow: 0 8px 18px rgba(47, 111, 208, 0.24);
|
||||
}
|
||||
|
||||
.toolbar-button--primary:hover {
|
||||
background: linear-gradient(180deg, #4b89e4 0%, #2f6fd0 100%);
|
||||
box-shadow: 0 12px 24px rgba(47, 111, 208, 0.32);
|
||||
}
|
||||
|
||||
.config-table {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
padding: 0 30px;
|
||||
}
|
||||
|
||||
.config-table__head,
|
||||
.config-row {
|
||||
display: grid;
|
||||
grid-template-columns: 180px 280px minmax(0, 1fr) minmax(0, 1fr) 200px;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
padding: 0 18px;
|
||||
}
|
||||
|
||||
.config-table__head {
|
||||
flex: none;
|
||||
height: 62px;
|
||||
margin-top: 18px;
|
||||
border-radius: 12px;
|
||||
background: var(--surface-soft);
|
||||
color: var(--muted);
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.config-table__body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.config-row {
|
||||
min-height: 72px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
color: var(--ink-soft);
|
||||
font-size: 19px;
|
||||
transition: background 0.18s ease;
|
||||
}
|
||||
|
||||
.config-row:hover {
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.col-name {
|
||||
color: var(--ink);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.col-value,
|
||||
.col-descript {
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.col-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.row-button {
|
||||
height: 42px;
|
||||
padding: 0 18px;
|
||||
border: 1px solid var(--line-strong);
|
||||
border-radius: 8px;
|
||||
color: var(--blue);
|
||||
font-size: 17px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 1px;
|
||||
background: #fff;
|
||||
transition: background 0.18s ease, border-color 0.18s ease;
|
||||
}
|
||||
|
||||
.row-button:hover {
|
||||
border-color: var(--blue);
|
||||
background: var(--blue-soft);
|
||||
}
|
||||
|
||||
.row-button--danger {
|
||||
color: var(--red);
|
||||
}
|
||||
|
||||
.row-button--danger:hover {
|
||||
border-color: var(--red);
|
||||
background: #fdeeee;
|
||||
}
|
||||
|
||||
.config-empty {
|
||||
padding: 80px 0;
|
||||
color: var(--muted-light);
|
||||
font-size: 20px;
|
||||
letter-spacing: 1px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.config-footer {
|
||||
flex: none;
|
||||
height: 64px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
padding: 0 48px;
|
||||
border-top: 1px solid var(--line);
|
||||
color: var(--muted);
|
||||
font-size: 18px;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.config-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 70;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 24px;
|
||||
background: rgba(18, 33, 54, 0.44);
|
||||
backdrop-filter: blur(5px);
|
||||
}
|
||||
|
||||
.form-card {
|
||||
width: 760px;
|
||||
padding: 36px 40px 34px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.65);
|
||||
border-radius: 24px;
|
||||
background: #fff;
|
||||
box-shadow: 0 30px 80px rgba(12, 30, 55, 0.3);
|
||||
}
|
||||
|
||||
.form-card h2,
|
||||
.confirm-card h2 {
|
||||
color: #1f2937;
|
||||
font-size: 30px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 1px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 22px;
|
||||
margin-top: 28px;
|
||||
}
|
||||
|
||||
.form-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
color: var(--ink-soft);
|
||||
font-size: 18px;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.form-field--wide {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.form-field em {
|
||||
color: var(--red);
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
.form-field input,
|
||||
.form-field textarea {
|
||||
width: 100%;
|
||||
padding: 14px 18px;
|
||||
border: 2px solid var(--line-strong);
|
||||
border-radius: 10px;
|
||||
color: var(--ink);
|
||||
font-family: inherit;
|
||||
font-size: 19px;
|
||||
outline: none;
|
||||
resize: vertical;
|
||||
transition: border-color 0.2s ease, box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
.form-field input {
|
||||
height: 56px;
|
||||
}
|
||||
|
||||
.form-field input:focus,
|
||||
.form-field textarea:focus {
|
||||
border-color: var(--blue);
|
||||
box-shadow: 0 0 0 4px rgba(47, 111, 208, 0.12);
|
||||
}
|
||||
|
||||
.form-error {
|
||||
margin-top: 16px;
|
||||
color: var(--red);
|
||||
font-size: 17px;
|
||||
letter-spacing: 0.5px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 20px;
|
||||
margin-top: 30px;
|
||||
}
|
||||
|
||||
.form-button {
|
||||
width: 190px;
|
||||
height: 56px;
|
||||
border-radius: 12px;
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 3px;
|
||||
transition: transform 0.2s ease, box-shadow 0.2s ease, background 0.2s ease;
|
||||
}
|
||||
|
||||
.form-button:disabled {
|
||||
cursor: default;
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
.form-button--ghost {
|
||||
border: 2px solid var(--line-strong);
|
||||
color: var(--ink-soft);
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.form-button--ghost:hover:not(:disabled) {
|
||||
background: var(--surface-soft);
|
||||
}
|
||||
|
||||
.form-button--primary {
|
||||
color: #fff;
|
||||
background: linear-gradient(180deg, #4b89e4 0%, #2f6fd0 100%);
|
||||
box-shadow: 0 10px 22px rgba(47, 111, 208, 0.28);
|
||||
}
|
||||
|
||||
.form-button--primary:hover:not(:disabled) {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 14px 28px rgba(47, 111, 208, 0.36);
|
||||
}
|
||||
|
||||
.form-button--danger {
|
||||
color: #fff;
|
||||
background: linear-gradient(180deg, #ef6d66 0%, #e15b55 100%);
|
||||
box-shadow: 0 10px 22px rgba(225, 91, 85, 0.26);
|
||||
}
|
||||
|
||||
.form-button--danger:hover:not(:disabled) {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 14px 28px rgba(225, 91, 85, 0.34);
|
||||
}
|
||||
|
||||
.confirm-card {
|
||||
width: 600px;
|
||||
padding: 38px 44px 34px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.65);
|
||||
border-radius: 24px;
|
||||
background: #fff;
|
||||
box-shadow: 0 30px 80px rgba(12, 30, 55, 0.3);
|
||||
}
|
||||
|
||||
.confirm-card p {
|
||||
margin-top: 18px;
|
||||
color: var(--muted);
|
||||
font-size: 19px;
|
||||
letter-spacing: 0.5px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.config-modal-enter-active,
|
||||
.config-modal-leave-active {
|
||||
transition: opacity 0.24s ease;
|
||||
}
|
||||
|
||||
.config-modal-enter-active .form-card,
|
||||
.config-modal-leave-active .form-card,
|
||||
.config-modal-enter-active .confirm-card,
|
||||
.config-modal-leave-active .confirm-card {
|
||||
transition: transform 0.24s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.24s ease;
|
||||
}
|
||||
|
||||
.config-modal-enter-from,
|
||||
.config-modal-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.config-modal-enter-from .form-card,
|
||||
.config-modal-leave-to .form-card,
|
||||
.config-modal-enter-from .confirm-card,
|
||||
.config-modal-leave-to .confirm-card {
|
||||
opacity: 0;
|
||||
transform: translateY(16px) scale(0.97);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,25 @@
|
||||
using HardwareControl.Core.SystemSetting;
|
||||
|
||||
namespace HardwareControl.Core.HardwareServiceImpl.HardwareService
|
||||
{
|
||||
/// <summary>
|
||||
/// 系统参数配置服务:对上层提供增删改查能力,屏蔽本地存储细节。
|
||||
/// </summary>
|
||||
public interface ISystemConfigService
|
||||
{
|
||||
/// <summary>读取全部配置,可按关键字过滤(分类、名称、值、描述)。</summary>
|
||||
IReadOnlyList<SystemConfig> GetAll(string? keyword = null);
|
||||
|
||||
/// <summary>按主键读取单条配置;不存在时返回 null。</summary>
|
||||
SystemConfig? GetById(int id);
|
||||
|
||||
/// <summary>新增配置,返回带主键的实体。</summary>
|
||||
SystemConfig Create(SystemConfig config);
|
||||
|
||||
/// <summary>更新配置;主键不存在时抛出 <see cref="HardwareException"/>。</summary>
|
||||
SystemConfig Update(SystemConfig config);
|
||||
|
||||
/// <summary>删除配置;返回是否成功删除。</summary>
|
||||
bool Delete(int id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
|
||||
using HardwareControl.Core.SystemSetting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace HardwareControl.Core.HardwareServiceImpl
|
||||
{
|
||||
/// <summary>
|
||||
/// 系统参数配置服务实现。负责入参校验与日志,持久化委托给 <see cref="SystemConfigRepository"/>。
|
||||
/// </summary>
|
||||
public sealed class SystemConfigService : ISystemConfigService
|
||||
{
|
||||
private readonly SystemConfigRepository _repository;
|
||||
private readonly ILogger<SystemConfigService> _logger;
|
||||
|
||||
public SystemConfigService(
|
||||
SystemConfigRepository repository,
|
||||
ILogger<SystemConfigService> logger)
|
||||
{
|
||||
_repository = repository;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public IReadOnlyList<SystemConfig> GetAll(string? keyword = null) =>
|
||||
_repository.GetAll(keyword);
|
||||
|
||||
public SystemConfig? GetById(int id) => _repository.FindById(id);
|
||||
|
||||
public SystemConfig Create(SystemConfig config)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(config);
|
||||
Normalize(config);
|
||||
|
||||
var created = _repository.Insert(config);
|
||||
_logger.LogInformation(
|
||||
"新增系统参数:{ConfigClass}/{ConfigName}(Id={ConfigId})",
|
||||
created.ConfigClass,
|
||||
created.ConfigName,
|
||||
created.ConfigId);
|
||||
|
||||
return created;
|
||||
}
|
||||
|
||||
public SystemConfig Update(SystemConfig config)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(config);
|
||||
|
||||
if (config.ConfigId <= 0)
|
||||
{
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.InvalidArgument, "系统参数 ID 无效");
|
||||
}
|
||||
|
||||
Normalize(config);
|
||||
|
||||
if (!_repository.Update(config))
|
||||
{
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.InvalidArgument,
|
||||
$"系统参数 {config.ConfigId} 不存在");
|
||||
}
|
||||
|
||||
_logger.LogInformation(
|
||||
"更新系统参数:{ConfigClass}/{ConfigName}(Id={ConfigId})",
|
||||
config.ConfigClass,
|
||||
config.ConfigName,
|
||||
config.ConfigId);
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
public bool Delete(int id)
|
||||
{
|
||||
if (id <= 0)
|
||||
{
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.InvalidArgument, "系统参数 ID 无效");
|
||||
}
|
||||
|
||||
var deleted = _repository.Delete(id);
|
||||
if (deleted)
|
||||
{
|
||||
_logger.LogInformation("删除系统参数:Id={ConfigId}", id);
|
||||
}
|
||||
|
||||
return deleted;
|
||||
}
|
||||
|
||||
private static void Normalize(SystemConfig config)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(config.ConfigName))
|
||||
{
|
||||
throw new HardwareException(
|
||||
HardwareErrorKind.InvalidArgument, "配置名称不能为空");
|
||||
}
|
||||
|
||||
config.ConfigClass = config.ConfigClass?.Trim() ?? string.Empty;
|
||||
config.ConfigName = config.ConfigName.Trim();
|
||||
config.ConfigValue = config.ConfigValue?.Trim() ?? string.Empty;
|
||||
config.ConfigDescript = config.ConfigDescript?.Trim() ?? string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using LiteDB;
|
||||
|
||||
namespace HardwareControl.Core.SystemSetting
|
||||
{
|
||||
/// <summary>
|
||||
/// 系统参数配置的本地存储层(LiteDB)。
|
||||
/// 数据库文件由调用方指定,建议整个进程只注册一个实例。
|
||||
/// </summary>
|
||||
public sealed class SystemConfigRepository : IDisposable
|
||||
{
|
||||
private const string CollectionName = "system_config";
|
||||
|
||||
private readonly LiteDatabase _database;
|
||||
private readonly ILiteCollection<SystemConfig> _collection;
|
||||
|
||||
public SystemConfigRepository(string databasePath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(databasePath))
|
||||
{
|
||||
throw new ArgumentException("数据库路径不能为空", nameof(databasePath));
|
||||
}
|
||||
|
||||
var fullPath = Path.GetFullPath(databasePath);
|
||||
var directory = Path.GetDirectoryName(fullPath);
|
||||
if (!string.IsNullOrWhiteSpace(directory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
_database = new LiteDatabase(new ConnectionString
|
||||
{
|
||||
Filename = fullPath,
|
||||
Connection = ConnectionType.Shared,
|
||||
});
|
||||
_collection = _database.GetCollection<SystemConfig>(CollectionName);
|
||||
}
|
||||
|
||||
/// <summary>读取全部配置,可按关键字过滤(分类、名称、值、描述)。</summary>
|
||||
public IReadOnlyList<SystemConfig> GetAll(string? keyword = null)
|
||||
{
|
||||
var items = _collection
|
||||
.FindAll()
|
||||
.OrderBy(x => x.ConfigClass)
|
||||
.ThenBy(x => x.ConfigName)
|
||||
.ToList();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(keyword))
|
||||
{
|
||||
return items;
|
||||
}
|
||||
|
||||
var value = keyword.Trim();
|
||||
return items
|
||||
.Where(x =>
|
||||
Contains(x.ConfigClass, value) ||
|
||||
Contains(x.ConfigName, value) ||
|
||||
Contains(x.ConfigValue, value) ||
|
||||
Contains(x.ConfigDescript, value))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public SystemConfig? FindById(int id) => _collection.FindById(id);
|
||||
|
||||
public SystemConfig Insert(SystemConfig config)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(config);
|
||||
|
||||
config.ConfigId = 0;
|
||||
var id = _collection.Insert(config);
|
||||
config.ConfigId = id.AsInt32;
|
||||
return config;
|
||||
}
|
||||
|
||||
public bool Update(SystemConfig config)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(config);
|
||||
return _collection.Update(config);
|
||||
}
|
||||
|
||||
public bool Delete(int id) => _collection.Delete(id);
|
||||
|
||||
public void Dispose() => _database.Dispose();
|
||||
|
||||
private static bool Contains(string? source, string value) =>
|
||||
source is not null &&
|
||||
source.Contains(value, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
using HardwareControl.Core;
|
||||
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
|
||||
using HardwareWeb.Models;
|
||||
using HardwareWeb.Services;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace HardwareWeb.Controllers
|
||||
{
|
||||
/// <summary>
|
||||
/// 系统参数配置 Web 接口。
|
||||
/// 除密码校验外,其余接口都需要在请求头携带 X-Admin-Token。
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/system-config")]
|
||||
public class SystemConfigController : ControllerBase
|
||||
{
|
||||
private const string TokenHeader = "X-Admin-Token";
|
||||
|
||||
private readonly ISystemConfigService _service;
|
||||
private readonly AdminAccessService _access;
|
||||
private readonly ILogger<SystemConfigController> _logger;
|
||||
|
||||
public SystemConfigController(
|
||||
ISystemConfigService service,
|
||||
AdminAccessService access,
|
||||
ILogger<SystemConfigController> logger)
|
||||
{
|
||||
_service = service;
|
||||
_access = access;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>校验管理密码,通过后返回访问令牌。</summary>
|
||||
[HttpPost("auth")]
|
||||
[ProducesResponseType(typeof(AdminAuthPayload), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||
public IActionResult Auth([FromBody] AdminAuthRequest? request)
|
||||
{
|
||||
var session = _access.SignIn(request?.Password);
|
||||
if (session is null)
|
||||
{
|
||||
_logger.LogWarning("系统参数管理密码校验失败");
|
||||
return Unauthorized(new
|
||||
{
|
||||
error = "Unauthorized",
|
||||
message = "密码错误"
|
||||
});
|
||||
}
|
||||
|
||||
_logger.LogInformation("系统参数管理密码校验通过");
|
||||
return Ok(new AdminAuthPayload(session.Token, session.ExpiresAt));
|
||||
}
|
||||
|
||||
/// <summary>读取系统参数列表,可按关键字过滤。</summary>
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(IReadOnlyList<SystemConfigPayload>), StatusCodes.Status200OK)]
|
||||
public IActionResult List([FromQuery] string? keyword)
|
||||
{
|
||||
if (!IsAuthorized())
|
||||
{
|
||||
return AdminUnauthorized();
|
||||
}
|
||||
|
||||
var items = _service
|
||||
.GetAll(keyword)
|
||||
.Select(SystemConfigPayload.From)
|
||||
.ToList();
|
||||
|
||||
return Ok(items);
|
||||
}
|
||||
|
||||
/// <summary>按主键读取单条系统参数。</summary>
|
||||
[HttpGet("{id:int}")]
|
||||
[ProducesResponseType(typeof(SystemConfigPayload), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public IActionResult Get(int id)
|
||||
{
|
||||
if (!IsAuthorized())
|
||||
{
|
||||
return AdminUnauthorized();
|
||||
}
|
||||
|
||||
var config = _service.GetById(id);
|
||||
return config is null
|
||||
? NotFound(new { error = "NotFound", message = $"系统参数 {id} 不存在" })
|
||||
: Ok(SystemConfigPayload.From(config));
|
||||
}
|
||||
|
||||
/// <summary>新增系统参数。</summary>
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(SystemConfigPayload), StatusCodes.Status200OK)]
|
||||
public IActionResult Create([FromBody] SystemConfigUpsertRequest? request)
|
||||
{
|
||||
if (!IsAuthorized())
|
||||
{
|
||||
return AdminUnauthorized();
|
||||
}
|
||||
|
||||
if (request is null)
|
||||
{
|
||||
return BadRequest(new { error = "InvalidArgument", message = "请求体不能为空" });
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var created = _service.Create(request.ToEntity());
|
||||
return Ok(SystemConfigPayload.From(created));
|
||||
}
|
||||
catch (HardwareException ex)
|
||||
{
|
||||
return ServiceError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>按主键更新系统参数。</summary>
|
||||
[HttpPut("{id:int}")]
|
||||
[ProducesResponseType(typeof(SystemConfigPayload), StatusCodes.Status200OK)]
|
||||
public IActionResult Update(int id, [FromBody] SystemConfigUpsertRequest? request)
|
||||
{
|
||||
if (!IsAuthorized())
|
||||
{
|
||||
return AdminUnauthorized();
|
||||
}
|
||||
|
||||
if (request is null)
|
||||
{
|
||||
return BadRequest(new { error = "InvalidArgument", message = "请求体不能为空" });
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var updated = _service.Update(request.ToEntity(id));
|
||||
return Ok(SystemConfigPayload.From(updated));
|
||||
}
|
||||
catch (HardwareException ex)
|
||||
{
|
||||
return ServiceError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>按主键删除系统参数。</summary>
|
||||
[HttpDelete("{id:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public IActionResult Delete(int id)
|
||||
{
|
||||
if (!IsAuthorized())
|
||||
{
|
||||
return AdminUnauthorized();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return _service.Delete(id)
|
||||
? NoContent()
|
||||
: NotFound(new { error = "NotFound", message = $"系统参数 {id} 不存在" });
|
||||
}
|
||||
catch (HardwareException ex)
|
||||
{
|
||||
return ServiceError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsAuthorized() => _access.Validate(Request.Headers[TokenHeader]);
|
||||
|
||||
private IActionResult AdminUnauthorized() =>
|
||||
Unauthorized(new
|
||||
{
|
||||
error = "Unauthorized",
|
||||
message = "管理员凭证无效或已过期,请重新输入密码"
|
||||
});
|
||||
|
||||
private IActionResult ServiceError(HardwareException ex)
|
||||
{
|
||||
var statusCode = ex.Kind switch
|
||||
{
|
||||
HardwareErrorKind.InvalidArgument => StatusCodes.Status400BadRequest,
|
||||
_ => StatusCodes.Status500InternalServerError,
|
||||
};
|
||||
|
||||
if (statusCode >= 500)
|
||||
{
|
||||
_logger.LogError(ex, "系统参数接口失败:{Message}", ex.Message);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning("系统参数接口失败:{Message}", ex.Message);
|
||||
}
|
||||
|
||||
return new ObjectResult(new
|
||||
{
|
||||
error = ex.Kind.ToString(),
|
||||
message = ex.Message
|
||||
})
|
||||
{
|
||||
StatusCode = statusCode
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using HardwareControl.Core.SystemSetting;
|
||||
|
||||
namespace HardwareWeb.Models
|
||||
{
|
||||
/// <summary>系统参数配置的 Web 传输对象。</summary>
|
||||
public sealed record SystemConfigPayload(
|
||||
int ConfigId,
|
||||
string ConfigClass,
|
||||
string ConfigName,
|
||||
string ConfigValue,
|
||||
string ConfigDescript)
|
||||
{
|
||||
public static SystemConfigPayload From(SystemConfig config) =>
|
||||
new(
|
||||
config.ConfigId,
|
||||
config.ConfigClass ?? string.Empty,
|
||||
config.ConfigName ?? string.Empty,
|
||||
config.ConfigValue ?? string.Empty,
|
||||
config.ConfigDescript ?? string.Empty);
|
||||
}
|
||||
|
||||
/// <summary>新增 / 更新系统参数的请求体。</summary>
|
||||
public sealed record SystemConfigUpsertRequest(
|
||||
string? ConfigClass,
|
||||
string? ConfigName,
|
||||
string? ConfigValue,
|
||||
string? ConfigDescript)
|
||||
{
|
||||
public SystemConfig ToEntity(int configId = 0) =>
|
||||
new()
|
||||
{
|
||||
ConfigId = configId,
|
||||
ConfigClass = ConfigClass ?? string.Empty,
|
||||
ConfigName = ConfigName ?? string.Empty,
|
||||
ConfigValue = ConfigValue ?? string.Empty,
|
||||
ConfigDescript = ConfigDescript ?? string.Empty,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>管理员密码校验请求。</summary>
|
||||
public sealed record AdminAuthRequest(string? Password);
|
||||
|
||||
/// <summary>管理员密码校验通过后签发的令牌。</summary>
|
||||
public sealed record AdminAuthPayload(string Token, DateTimeOffset ExpiresAt);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using HardwareControl.Core.HardwareServiceImpl;
|
||||
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
|
||||
using HardwareControl.Core.Spectrometer;
|
||||
using HardwareControl.Core.SystemSetting;
|
||||
using HardwareControl.Core.UsbCamera;
|
||||
using HardwareWeb.Hubs;
|
||||
using HardwareWeb.Services;
|
||||
@@ -36,6 +37,17 @@ builder.Services.AddSignalR(options =>
|
||||
builder.Services.AddSingleton<CameraBroadcastChannel>();
|
||||
builder.Services.AddHostedService<CameraBroadcastService>();
|
||||
|
||||
// 7. 系统参数:LiteDB 本地库 + 管理密码校验
|
||||
var systemConfigDbPath = builder.Configuration["SystemSetting:DatabasePath"];
|
||||
if (string.IsNullOrWhiteSpace(systemConfigDbPath))
|
||||
{
|
||||
systemConfigDbPath = Path.Combine(
|
||||
AppContext.BaseDirectory, "Data", "system-config.db");
|
||||
}
|
||||
builder.Services.AddSingleton(_ => new SystemConfigRepository(systemConfigDbPath));
|
||||
builder.Services.AddSingleton<ISystemConfigService, SystemConfigService>();
|
||||
builder.Services.AddSingleton<AdminAccessService>();
|
||||
|
||||
|
||||
builder.Services.AddControllers();
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace HardwareWeb.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// 系统参数管理的轻量访问控制。
|
||||
/// 密码来自配置 SystemSetting:AdminPassword,未配置时使用默认密码;
|
||||
/// 校验通过后签发一个进程内有效、固定时长的令牌。
|
||||
/// </summary>
|
||||
public sealed class AdminAccessService
|
||||
{
|
||||
public const string DefaultPassword = "flzx3QC!1";
|
||||
|
||||
private static readonly TimeSpan TokenLifetime = TimeSpan.FromMinutes(30);
|
||||
|
||||
private readonly string _password;
|
||||
private readonly ConcurrentDictionary<string, DateTimeOffset> _tokens =
|
||||
new(StringComparer.Ordinal);
|
||||
|
||||
public AdminAccessService(IConfiguration configuration)
|
||||
{
|
||||
var configured = configuration["SystemSetting:AdminPassword"];
|
||||
_password = string.IsNullOrEmpty(configured) ? DefaultPassword : configured;
|
||||
}
|
||||
|
||||
/// <summary>校验密码,成功时返回新令牌,失败时返回 null。</summary>
|
||||
public AdminSession? SignIn(string? password)
|
||||
{
|
||||
if (!FixedTimeEquals(password, _password))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
CleanupExpired();
|
||||
|
||||
var token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
|
||||
var expiresAt = DateTimeOffset.UtcNow.Add(TokenLifetime);
|
||||
_tokens[token] = expiresAt;
|
||||
return new AdminSession(token, expiresAt);
|
||||
}
|
||||
|
||||
/// <summary>判断令牌是否存在且未过期。</summary>
|
||||
public bool Validate(string? token)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(token))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!_tokens.TryGetValue(token, out var expiresAt))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (expiresAt > DateTimeOffset.UtcNow)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
_tokens.TryRemove(token, out _);
|
||||
return false;
|
||||
}
|
||||
|
||||
private void CleanupExpired()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
foreach (var pair in _tokens)
|
||||
{
|
||||
if (pair.Value <= now)
|
||||
{
|
||||
_tokens.TryRemove(pair.Key, out _);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool FixedTimeEquals(string? left, string right)
|
||||
{
|
||||
if (left is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return CryptographicOperations.FixedTimeEquals(
|
||||
Encoding.UTF8.GetBytes(left),
|
||||
Encoding.UTF8.GetBytes(right));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record AdminSession(string Token, DateTimeOffset ExpiresAt);
|
||||
}
|
||||
@@ -32,5 +32,9 @@
|
||||
"SendOnlyWhenViewers": true,
|
||||
"MaxFrameAgeMs": 1500,
|
||||
"MaxFrameBytes": 8388608
|
||||
},
|
||||
"SystemSetting": {
|
||||
"DatabasePath": null,
|
||||
"AdminPassword": "flzx3QC!1"
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user