feat: implement license platform business flows and delivery tooling
Add admin and customer interfaces, orders, signed activation and leases, protected package delivery, keyring verification, migrations, security controls, tests and deployment documentation. Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
32
frontend/src/admin-api.test.ts
Normal file
32
frontend/src/admin-api.test.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
const api = vi.hoisted(() => ({get:vi.fn(),put:vi.fn(),post:vi.fn()}))
|
||||
vi.mock('./api', () => ({api}))
|
||||
import { changePassword, getSettings, listAuditEvents, redactAuditDetails, saveSettings, validatePassword, validateSettings } from './admin-api'
|
||||
beforeEach(() => vi.resetAllMocks())
|
||||
describe('admin API contract', () => {
|
||||
it('uses the exact endpoints, params and request fields', async () => {
|
||||
const params = {page:2,page_size:50,q:'admin',action:'update',resource_type:'settings',from:'2026-10-01T00:00:00.000Z',to:'2026-10-09T00:00:00.000Z'}
|
||||
await listAuditEvents(params); expect(api.get).toHaveBeenCalledWith('/audit-events',{params})
|
||||
await getSettings(); expect(api.get).toHaveBeenCalledWith('/settings')
|
||||
const body = {site_name:'License Hub',support_email:'',announcement:'维护公告'}
|
||||
await saveSettings(body); expect(api.put).toHaveBeenCalledWith('/settings',body)
|
||||
await changePassword({current_password:'old',new_password:'a'}); expect(api.post).toHaveBeenCalledWith('/settings/password',{current_password:'old',new_password:'a'})
|
||||
})
|
||||
it('redacts nested, array and encoded password fields without mutating input', () => {
|
||||
const details = {current_password:'secret',nested:[{newPassword:'secret2',PASSWORD_HASH:'hash',name:'visible'}],payload:'{"password":"encoded"}'}
|
||||
const result = redactAuditDetails(details)
|
||||
expect(JSON.stringify(result)).not.toMatch(/secret|hash|encoded/)
|
||||
expect(JSON.stringify(result)).toContain('visible'); expect(details.current_password).toBe('secret')
|
||||
})
|
||||
it('enforces Unicode character and UTF-8 byte limits without complexity rules', () => {
|
||||
expect(validatePassword('old','a','a')).toBe('')
|
||||
expect(validatePassword('old','密'.repeat(24),'密'.repeat(24))).toBe('')
|
||||
expect(validatePassword('old','密'.repeat(25),'密'.repeat(25))).toContain('72')
|
||||
expect(validatePassword('old','','')).not.toBe('')
|
||||
expect(validatePassword('old','a','b')).toContain('不一致')
|
||||
expect(validateSettings({site_name:'😀'.repeat(100),support_email:'',announcement:'文'.repeat(2000)})).toBe('')
|
||||
expect(validateSettings({site_name:'x'.repeat(101),support_email:'',announcement:''})).toContain('站点名称')
|
||||
expect(validateSettings({site_name:'x',support_email:'bad',announcement:''})).toContain('邮箱')
|
||||
expect(validateSettings({site_name:'x',support_email:'',announcement:'x'.repeat(2001)})).toContain('公告')
|
||||
})
|
||||
})
|
||||
49
frontend/src/admin-api.ts
Normal file
49
frontend/src/admin-api.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { api } from './api'
|
||||
|
||||
export type AuditEvent = { id:number; actor_admin_id:number; actor_email:string; action:string; resource_type:string; resource_id:string|number|null; details:Record<string, unknown>; created_at:string }
|
||||
export type AuditParams = { page:number; page_size:number; q?:string; action?:string; resource_type?:string; from?:string; to?:string }
|
||||
export type SiteSettings = { site_name:string; support_email:string; announcement:string; updated_at:string|null }
|
||||
export type SettingsInput = Pick<SiteSettings, 'site_name'|'support_email'|'announcement'>
|
||||
export const listAuditEvents = (params:AuditParams) => api.get<{data:AuditEvent[];meta:{page:number;page_size:number;total:number}}>('/audit-events', {params})
|
||||
export const getSettings = () => api.get<{data:SiteSettings}>('/settings')
|
||||
export const saveSettings = (body:SettingsInput) => api.put<{data:SiteSettings}>('/settings', body)
|
||||
export const changePassword = (body:{current_password:string;new_password:string}) => api.post<void>('/settings/password', body)
|
||||
export type AdminAccount = { id:number; username:string; email:string; active:boolean; created_at:string }
|
||||
export const listAdmins = () => api.get<{data:AdminAccount[]}>('/admins')
|
||||
export const createAdmin = (body:{username:string;email:string;password:string}) => api.post<{data:AdminAccount}>('/admins', body)
|
||||
export const setAdminActive = (id:number, active:boolean) => api.post<void>(`/admins/${id}/active`, {active})
|
||||
export const resetAdminPassword = (id:number, password:string) => api.post<void>(`/admins/${id}/reset-password`, {password})
|
||||
|
||||
export type IntegrationLanguage = 'python'|'go'|'java'|'dotnet'|'nodejs'
|
||||
export type IntegrationMode = 'desktop'|'service'|'container'
|
||||
export type IntegrationKit = {
|
||||
protocol_version:string; platform_base_url:string; language:IntegrationLanguage; language_label:string; mode:IntegrationMode; mode_label:string
|
||||
endpoints:{method:string;path:string;purpose:string}[]; security_rules:string[]; prompt:string
|
||||
protocol:string
|
||||
payload_example:{version:string;instance_id:string;state:string;server_time:string;entitlement_expires_at:string;lease_expires_at:string}
|
||||
}
|
||||
export const getIntegrationKit = (language:IntegrationLanguage, mode:IntegrationMode) => api.get<{data:IntegrationKit}>('/integration-kit', {params:{language,mode}})
|
||||
|
||||
// Apply at every depth, including arrays and serialized JSON, before rendering.
|
||||
export function redactAuditDetails(value:unknown):unknown {
|
||||
if (Array.isArray(value)) return value.map(redactAuditDetails)
|
||||
if (value !== null && typeof value === 'object') {
|
||||
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, /password|passwd|pwd|密码/i.test(key) ? '[已隐藏]' : redactAuditDetails(item)]))
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
try { return redactAuditDetails(JSON.parse(value)) } catch { return value }
|
||||
}
|
||||
return value
|
||||
}
|
||||
export function validateSettings(value:SettingsInput):string {
|
||||
if (!value.site_name.trim() || Array.from(value.site_name).length > 100) return '站点名称须为 1–100 个字符'
|
||||
if (Array.from(value.support_email).length > 254 || (value.support_email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.support_email))) return '联系邮箱须为空或合法邮箱,最多 254 个字符'
|
||||
if (Array.from(value.announcement).length > 2000) return '公告最多 2000 个字符'
|
||||
return ''
|
||||
}
|
||||
export function validatePassword(current:string, next:string, confirmation:string):string {
|
||||
if (!current) return '请输入当前密码'
|
||||
if (!next || new TextEncoder().encode(next).length > 72) return '新密码不能为空,且 UTF-8 编码不得超过 72 字节'
|
||||
if (next !== confirmation) return '两次输入的新密码不一致'
|
||||
return ''
|
||||
}
|
||||
27
frontend/src/api-health.test.ts
Normal file
27
frontend/src/api-health.test.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import axios from 'axios'
|
||||
import { checkApiHealth } from './api-health'
|
||||
|
||||
describe('checkApiHealth', () => {
|
||||
it('returns online for the live response', async () => {
|
||||
const request = vi.fn().mockResolvedValue({ data: { status: 'ok' } })
|
||||
await expect(checkApiHealth(request)).resolves.toBe('online')
|
||||
expect(request).toHaveBeenCalledWith('/api/v1/health/live', { timeout: 3000 })
|
||||
})
|
||||
|
||||
it('returns offline for invalid status', async () => {
|
||||
await expect(checkApiHealth(vi.fn().mockResolvedValue({ data: { status: 'degraded' } }))).resolves.toBe('offline')
|
||||
await expect(checkApiHealth(vi.fn().mockResolvedValue({ data: null }))).resolves.toBe('offline')
|
||||
})
|
||||
|
||||
it('returns offline when the request rejects', async () => {
|
||||
await expect(checkApiHealth(vi.fn().mockRejectedValue(new Error('network unavailable')))).resolves.toBe('offline')
|
||||
})
|
||||
|
||||
it('uses Axios by default', async () => {
|
||||
const request = vi.spyOn(axios, 'get').mockResolvedValue({ data: { status: 'ok' } } as never)
|
||||
await expect(checkApiHealth()).resolves.toBe('online')
|
||||
expect(request).toHaveBeenCalledOnce()
|
||||
request.mockRestore()
|
||||
})
|
||||
})
|
||||
14
frontend/src/api-health.ts
Normal file
14
frontend/src/api-health.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import axios from 'axios'
|
||||
|
||||
export type Connection = 'checking' | 'online' | 'offline'
|
||||
|
||||
export async function checkApiHealth(
|
||||
request: typeof axios.get = axios.get,
|
||||
): Promise<Exclude<Connection, 'checking'>> {
|
||||
try {
|
||||
const { data } = await request<{ status: string }>('/api/v1/health/live', { timeout: 3000 })
|
||||
return data.status === 'ok' ? 'online' : 'offline'
|
||||
} catch {
|
||||
return 'offline'
|
||||
}
|
||||
}
|
||||
30
frontend/src/api.ts
Normal file
30
frontend/src/api.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import axios from 'axios'
|
||||
|
||||
export const api = axios.create({ baseURL: '/api/v1', timeout: 8000, withCredentials: true })
|
||||
api.interceptors.response.use((response) => response, (error) => {
|
||||
const message = error.response?.data?.error?.message || '请求失败,请稍后重试'
|
||||
return Promise.reject(new Error(message))
|
||||
})
|
||||
|
||||
export type Customer = { id:number; name:string; contact_email:string; status:string; created_at:string; updated_at:string }
|
||||
export type Product = { id:number; code:string; name:string; description:string; active:boolean; created_at:string; updated_at:string }
|
||||
export async function login(username:string,password:string) { return api.post('/auth/login',{username,password}) }
|
||||
export async function logout() { return api.post('/auth/logout') }
|
||||
export async function me() { return api.get('/me') }
|
||||
export async function listCustomers(params?:Record<string,string|number>) { return api.get<{data:Customer[];meta:{page:number;page_size:number;total:number}}>('/customers',{params}) }
|
||||
export async function createCustomer(value:Pick<Customer,'name'|'contact_email'>) { return api.post('/customers',value) }
|
||||
export async function updateCustomer(id:number,value:Partial<Customer>) { return api.put(`/customers/${id}`,value) }
|
||||
export async function deleteCustomer(id:number) { return api.delete(`/customers/${id}`) }
|
||||
export async function listProducts() { return api.get<{data:Product[]}>('/products') }
|
||||
export async function createProduct(value:Pick<Product,'code'|'name'|'description'>) { return api.post('/products',value) }
|
||||
export async function updateProduct(id:number,value:Partial<Product>) { return api.put(`/products/${id}`,value) }
|
||||
export async function deleteProduct(id:number) { return api.delete(`/products/${id}`) }
|
||||
export type License = { id:number; license_key:string; customer_id:number; customer_name:string; product_id:number; product_name:string; product_code:string; status:'active'|'scheduled'|'expired'|'revoked'|string; starts_at:string; expires_at:string; created_at:string }
|
||||
export async function listLicenses(params?:Record<string,string|number>) { return api.get<{data:License[];meta:{page:number;page_size:number;total:number}}>('/licenses',{params}) }
|
||||
export async function issueLicense(value:{customer_id:number;product_id:number;starts_at:string;expires_at:string}, idempotencyKey:string) { return api.post('/licenses',value,{headers:{'Idempotency-Key':idempotencyKey}}) }
|
||||
export type LicenseInstance = { id:number; instance_id:string; license_id:number; customer_id:number; product_id:number; status:string; activated_at?:string; certificate_version?:string; created_at:string; last_seen_at?:string; lease_expires_at?:string; freeze_state:string; observed_state:string; entitlement_state:string }
|
||||
export async function setInstanceFrozen(instanceID:string,frozen:boolean,key:string) { return api.post(`/instances/${instanceID}/freeze`,{frozen},{headers:{'Idempotency-Key':key}}) }
|
||||
export async function listLicenseInstances(id:number) { return api.get<{data:LicenseInstance[]}>(`/licenses/${id}/instances`) }
|
||||
export async function getLicense(id:number) { return api.get<{data:License}>(`/licenses/${id}`) }
|
||||
export async function revokeLicense(id:number,idempotencyKey:string) { return api.post(`/licenses/${id}/revoke`,{}, {headers:{'Idempotency-Key':idempotencyKey}}) }
|
||||
export async function renewLicense(id:number,expires_at:string,idempotencyKey:string) { return api.post(`/licenses/${id}/renew`,{expires_at},{headers:{'Idempotency-Key':idempotencyKey}}) }
|
||||
3
frontend/src/dashboard-api.ts
Normal file
3
frontend/src/dashboard-api.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { api, type License } from './api'
|
||||
export type DashboardSummary = { active_licenses:number; new_customers:number; paid_revenue_cents:number; currency:string; expiring_licenses:number; generated_at:string; license_trend:{month:string;issued:number;expired:number}[]; upcoming_expirations:License[]; recent_licenses:License[] }
|
||||
export async function getDashboard(months:number) { return api.get<{data:DashboardSummary}>('/dashboard/summary', {params:{months}}) }
|
||||
26
frontend/src/date-format.test.ts
Normal file
26
frontend/src/date-format.test.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { formatDateTime } from './date-format'
|
||||
|
||||
function localExpected(date: Date) {
|
||||
const pad = (value: number) => String(value).padStart(2, '0')
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
|
||||
}
|
||||
|
||||
describe('formatDateTime', () => {
|
||||
it('formats an API UTC timestamp in the browser local timezone, including seconds', () => {
|
||||
const value = '2026-10-08T23:04:05Z'
|
||||
expect(formatDateTime(value)).toBe(localExpected(new Date(value)))
|
||||
expect(formatDateTime('2026-10-09T07:04:05+08:00')).toBe(formatDateTime(value))
|
||||
})
|
||||
|
||||
it('pads date components and displays midnight as 00', () => {
|
||||
expect(formatDateTime(new Date(2026, 0, 2, 0, 3, 4))).toBe('2026-01-02 00:03:04')
|
||||
})
|
||||
|
||||
it('handles missing and invalid timestamps without leaking Invalid Date or epoch dates', () => {
|
||||
for (const value of [null, undefined, '', 'not-a-date', new Date(NaN)]) {
|
||||
expect(formatDateTime(value)).toBe('—')
|
||||
expect(formatDateTime(value, '暂无租约')).toBe('暂无租约')
|
||||
}
|
||||
})
|
||||
})
|
||||
16
frontend/src/date-format.ts
Normal file
16
frontend/src/date-format.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
const formatter = new Intl.DateTimeFormat('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: false,
|
||||
})
|
||||
|
||||
export function formatDateTime(value: string | Date | null | undefined, empty = '—'): string {
|
||||
if (!value) return empty
|
||||
const date = value instanceof Date ? value : new Date(value)
|
||||
if (Number.isNaN(date.getTime())) return empty
|
||||
return formatter.format(date).replace(/\//g, '-')
|
||||
}
|
||||
9
frontend/src/orders-api.ts
Normal file
9
frontend/src/orders-api.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { api, type License } from './api'
|
||||
|
||||
export type Order = { id:number; order_no:string; customer_id:number; customer_name:string; product_id:number; product_name:string; amount_cents:number; currency:string; status:string; payment_reference:string|null; paid_at:string|null; license_id:number|null; created_at:string; updated_at:string }
|
||||
export type NewOrder = { customer_id:number; product_id:number; amount_cents:number; currency:string }
|
||||
export const listOrders = (page:number) => api.get<{data:Order[];meta:{total:number}}>('/orders',{params:{page,page_size:20}})
|
||||
export const getOrder = (id:number) => api.get<{data:Order}>(`/orders/${id}`)
|
||||
export const createOrder = (body:NewOrder,key:string) => api.post('/orders',body,{headers:{'Idempotency-Key':key}})
|
||||
export const confirmPayment = (id:number,body:{amount_cents:number;payment_reference:string},key:string) => api.post(`/orders/${id}/confirm-payment`,body,{headers:{'Idempotency-Key':key}})
|
||||
export const issueOrder = (id:number,body:{starts_at:string;expires_at:string},key:string) => api.post<{data:Order;license:License}>(`/orders/${id}/issue`,body,{headers:{'Idempotency-Key':key}})
|
||||
3
frontend/src/router.test.ts
Normal file
3
frontend/src/router.test.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import router from './router'
|
||||
describe('administration routes',()=>{it('provides a destination for all management navigation items while preserving the customer portal',()=>{const paths=router.getRoutes().map(route=>route.path);for(const path of ['/','/licenses','/customers','/products','/orders','/releases','/integration','/audit','/settings','/customer'])expect(paths).toContain(path)})})
|
||||
@@ -1,7 +1,11 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import Overview from './views/Overview.vue'
|
||||
|
||||
import CustomerPortal from './views/CustomerPortal.vue'
|
||||
export default createRouter({
|
||||
history: createWebHistory(),
|
||||
routes: [{ path: '/', component: Overview }]
|
||||
routes: [
|
||||
...[{path:'/',view:'dashboard'},{path:'/licenses',view:'licenses'},{path:'/customers',view:'customers'},{path:'/products',view:'products'},{path:'/orders',view:'orders'},{path:'/releases',view:'releases'},{path:'/integration',view:'integration'},{path:'/audit',view:'audit'},{path:'/settings',view:'settings'},{path:'/admins',view:'admins'}].map(({path,view})=>({path,component:Overview,meta:{view}})),
|
||||
{path:'/customer',component:CustomerPortal},
|
||||
{path:'/:pathMatch(.*)*',redirect:'/'}
|
||||
]
|
||||
})
|
||||
|
||||
File diff suppressed because one or more lines are too long
26
frontend/src/views/AdminsPanel.test.ts
Normal file
26
frontend/src/views/AdminsPanel.test.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import ElementPlus from 'element-plus'
|
||||
const calls=vi.hoisted(()=>({listAdmins:vi.fn(),createAdmin:vi.fn(),setAdminActive:vi.fn(),resetAdminPassword:vi.fn()}))
|
||||
vi.mock('../admin-api',()=>calls)
|
||||
import AdminsPanel from './AdminsPanel.vue'
|
||||
beforeEach(()=>{vi.resetAllMocks();calls.listAdmins.mockResolvedValue({data:{data:[{id:1,username:'admin-1',email:'admin@example.test',active:true,created_at:'2026-10-09T00:00:00Z'}]}});calls.createAdmin.mockResolvedValue({data:{data:{id:2}}})})
|
||||
describe('AdminsPanel',()=>{
|
||||
it('validates confirmation and clears credentials after creation',async()=>{
|
||||
const wrapper=mount(AdminsPanel,{props:{currentUsername:'admin-1'},global:{plugins:[ElementPlus]}});await flushPromises()
|
||||
expect(wrapper.text()).toContain('admin-1')
|
||||
await wrapper.find('input[aria-label="管理员用户名"]').setValue('Team_2')
|
||||
await wrapper.find('input[aria-label="管理员联系邮箱"]').setValue('team@example.test')
|
||||
await wrapper.find('input[aria-label="管理员密码"]').setValue('New-Password')
|
||||
await wrapper.find('input[aria-label="确认管理员密码"]').setValue('Wrong')
|
||||
await wrapper.find('form').trigger('submit');await flushPromises();expect(calls.createAdmin).not.toHaveBeenCalled();expect(wrapper.text()).toContain('两次输入的密码不一致')
|
||||
await wrapper.find('input[aria-label="确认管理员密码"]').setValue('New-Password');await wrapper.find('form').trigger('submit');await flushPromises()
|
||||
expect(calls.createAdmin).toHaveBeenCalledWith({username:'team_2',email:'team@example.test',password:'New-Password'})
|
||||
expect((wrapper.find('input[aria-label="管理员密码"]').element as HTMLInputElement).value).toBe('');expect(wrapper.text()).toContain('管理员已创建');wrapper.unmount()
|
||||
})
|
||||
it('prevents disabling the current account',async()=>{
|
||||
const wrapper=mount(AdminsPanel,{props:{currentUsername:'admin-1'},global:{plugins:[ElementPlus]}});await flushPromises()
|
||||
const button=wrapper.findAll('button').find(x=>x.text()==='停用');expect(button).toBeDefined();await button!.trigger('click');await flushPromises()
|
||||
expect(calls.setAdminActive).not.toHaveBeenCalled();expect(wrapper.text()).toContain('不能停用当前登录的管理员');wrapper.unmount()
|
||||
})
|
||||
})
|
||||
16
frontend/src/views/AdminsPanel.vue
Normal file
16
frontend/src/views/AdminsPanel.vue
Normal file
@@ -0,0 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import { createAdmin, listAdmins, resetAdminPassword, setAdminActive, type AdminAccount } from '../admin-api'
|
||||
import { formatDateTime } from '../date-format'
|
||||
const props = defineProps<{currentUsername:string}>()
|
||||
const admins = ref<AdminAccount[]>([]), loading = ref(false), saving = ref(false), error = ref(''), notice = ref('')
|
||||
const form = ref({username:'',email:'',password:'',confirmation:''})
|
||||
async function refresh() { if (loading.value) return; loading.value=true; error.value=''; try { admins.value=(await listAdmins()).data.data } catch(e) { error.value=e instanceof Error?e.message:'管理员列表加载失败' } finally { loading.value=false } }
|
||||
function validate() { const name=form.value.username.trim().toLowerCase(); if(!/^[a-z0-9_-]{3,32}$/.test(name)) return '用户名须为 3–32 位小写字母、数字、下划线或短横线'; if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.value.email.trim())) return '请输入有效邮箱'; if(!form.value.password || new TextEncoder().encode(form.value.password).length>72) return '密码不能为空,且 UTF-8 编码不得超过 72 字节'; if(form.value.password!==form.value.confirmation) return '两次输入的密码不一致'; return '' }
|
||||
async function add() { if(saving.value) return; error.value=validate(); notice.value=''; if(error.value) return; saving.value=true; try { await createAdmin({username:form.value.username.trim().toLowerCase(),email:form.value.email.trim(),password:form.value.password}); form.value={username:'',email:'',password:'',confirmation:''}; notice.value='管理员已创建'; await refresh() } catch(e) { error.value=e instanceof Error?e.message:'管理员创建失败' } finally { saving.value=false } }
|
||||
async function toggle(item:AdminAccount) { if(item.username===props.currentUsername && item.active) { error.value='不能停用当前登录的管理员'; return }; try { await ElMessageBox.confirm(item.active?'停用后将撤销该账号的全部会话,确认继续?':'确认启用该管理员?',item.active?'停用管理员':'启用管理员'); await setAdminActive(item.id,!item.active); notice.value=item.active?'管理员已停用':'管理员已启用'; await refresh() } catch(e) { if(e!=='cancel' && e!=='close') error.value=e instanceof Error?e.message:'管理员状态更新失败' } }
|
||||
async function reset(item:AdminAccount) { if(item.username===props.currentUsername) { error.value='请在系统设置中修改自己的密码,以保留当前登录会话'; return }; try { const result=await ElMessageBox.prompt(`为 ${item.username} 设置新密码`,`重置管理员密码`,{inputType:'password',inputPlaceholder:'最多 72 个 UTF-8 字节'}); if(!result.value || new TextEncoder().encode(result.value).length>72) { error.value='密码不能为空,且 UTF-8 编码不得超过 72 字节'; return }; await resetAdminPassword(item.id,result.value); notice.value='密码已重置,该管理员的全部会话已撤销' } catch(e) { if(e!=='cancel' && e!=='close') error.value=e instanceof Error?e.message:'密码重置失败' } }
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
<template><section class="data-section"><div class="section-heading"><div><h2>管理员账户</h2><p>管理员使用用户名和密码登录。停用或重置密码会撤销目标账户的全部会话。</p></div><el-button :loading="loading" @click="refresh">刷新</el-button></div><p v-if="error" class="error" role="alert">{{error}}</p><p v-if="notice" role="status">{{notice}}</p><div class="business-table"><el-table :data="admins" v-loading="loading" empty-text="暂无管理员"><el-table-column prop="username" label="用户名"/><el-table-column prop="email" label="联系邮箱" min-width="200"/><el-table-column label="状态"><template #default="scope">{{scope.row.active?'启用':'停用'}}</template></el-table-column><el-table-column label="创建时间" min-width="190"><template #default="scope">{{formatDateTime(scope.row.created_at)}}</template></el-table-column><el-table-column label="操作" width="180"><template #default="scope"><el-button link @click="reset(scope.row)">重置密码</el-button><el-button link :type="scope.row.active?'danger':'primary'" @click="toggle(scope.row)">{{scope.row.active?'停用':'启用'}}</el-button></template></el-table-column></el-table></div></section><section class="data-section"><div class="section-heading"><div><h2>新增管理员</h2><p>用户名创建后不可修改,密码不会展示或写入审计详情。</p></div></div><el-form label-position="top" :disabled="saving" @submit.prevent="add"><el-form-item label="用户名"><el-input v-model="form.username" aria-label="管理员用户名" autocomplete="username"/></el-form-item><el-form-item label="联系邮箱"><el-input v-model="form.email" aria-label="管理员联系邮箱" type="email" autocomplete="email"/></el-form-item><el-form-item label="密码"><el-input v-model="form.password" aria-label="管理员密码" type="password" autocomplete="new-password" show-password/></el-form-item><el-form-item label="确认密码"><el-input v-model="form.confirmation" aria-label="确认管理员密码" type="password" autocomplete="new-password" show-password/></el-form-item><el-button type="primary" native-type="submit" :loading="saving">创建管理员</el-button></el-form></section></template>
|
||||
60
frontend/src/views/AuditPanel.test.ts
Normal file
60
frontend/src/views/AuditPanel.test.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import ElementPlus from 'element-plus'
|
||||
import { defineComponent, nextTick } from 'vue'
|
||||
const calls = vi.hoisted(() => ({listAuditEvents:vi.fn()}))
|
||||
vi.mock('../admin-api', async importOriginal => ({...await importOriginal<typeof import('../admin-api')>(),...calls}))
|
||||
import AuditPanel from './AuditPanel.vue'
|
||||
const event = {id:1,actor_admin_id:2,actor_email:'admin@example.test',action:'settings.update',resource_type:'settings',resource_id:1,details:{password:'never-render',nested:{current_password:'also-secret',site_name:'Visible'}},created_at:'2026-10-09T00:00:00Z'}
|
||||
const response = {data:{data:[event],meta:{page:1,page_size:20,total:60}}}
|
||||
const PaginationStub = defineComponent({
|
||||
props: ['currentPage', 'pageSize', 'total', 'disabled'],
|
||||
emits: ['update:currentPage', 'current-change'],
|
||||
template: `<button class="btn-next" :disabled="disabled" @click="$emit('update:currentPage', currentPage + 1); $emit('current-change', currentPage + 1)">下一页</button>`,
|
||||
})
|
||||
const options = {global:{plugins:[ElementPlus],stubs:{teleport:true,ElPagination:PaginationStub}}}
|
||||
beforeEach(() => {vi.resetAllMocks();calls.listAuditEvents.mockResolvedValue(response)})
|
||||
describe('AuditPanel', () => {
|
||||
it('filters with UTC timestamps, paginates and renders redacted detail', async () => {
|
||||
const wrapper = mount(AuditPanel,options); await flushPromises()
|
||||
await wrapper.get('[aria-label="搜索审计日志"]').setValue('admin')
|
||||
await wrapper.get('[aria-label="审计动作"]').setValue('settings.update')
|
||||
await wrapper.get('[aria-label="资源类型"]').setValue('settings')
|
||||
await wrapper.get('[aria-label="审计开始时间"]').setValue('2026-10-01T10:00')
|
||||
await wrapper.get('form').trigger('submit'); await flushPromises()
|
||||
expect(calls.listAuditEvents).toHaveBeenLastCalledWith({page:1,page_size:20,q:'admin',action:'settings.update',resource_type:'settings',from:new Date('2026-10-01T10:00').toISOString(),to:undefined})
|
||||
await wrapper.get('.btn-next').trigger('click'); await flushPromises()
|
||||
expect(calls.listAuditEvents.mock.calls.at(-1)?.[0].page).toBe(2)
|
||||
await wrapper.findAll('button').find(b => b.text() === '详情')!.trigger('click'); await flushPromises()
|
||||
expect(wrapper.text()).toContain('Visible'); expect(wrapper.text()).not.toMatch(/never-render|also-secret/)
|
||||
await wrapper.findAll('button').find(b => b.text() === '重置')!.trigger('click'); await flushPromises()
|
||||
expect(calls.listAuditEvents.mock.calls.at(-1)?.[0]).toMatchObject({page:1,from:undefined,q:undefined})
|
||||
wrapper.unmount()
|
||||
})
|
||||
it('shows loading, empty and retryable error states', async () => {
|
||||
let resolve!: (value:typeof response) => void
|
||||
calls.listAuditEvents.mockReturnValueOnce(new Promise(r => {resolve=r}))
|
||||
const wrapper = mount(AuditPanel,options)
|
||||
await nextTick()
|
||||
expect(wrapper.get('[role="status"]').text()).toContain('正在加载')
|
||||
resolve({data:{data:[],meta:{page:1,page_size:20,total:0}}}); await flushPromises()
|
||||
expect(wrapper.text()).toContain('暂无符合条件')
|
||||
calls.listAuditEvents.mockRejectedValueOnce(new Error('日志接口失败'))
|
||||
await wrapper.findAll('button').find(b => b.text() === '刷新日志')!.trigger('click'); await flushPromises()
|
||||
expect(wrapper.get('[role="alert"]').text()).toBe('日志接口失败')
|
||||
await wrapper.findAll('button').find(b => b.text() === '刷新日志')!.trigger('click'); await flushPromises()
|
||||
expect(wrapper.find('[role="alert"]').exists()).toBe(false); wrapper.unmount()
|
||||
})
|
||||
it('rejects reversed dates and ignores stale responses', async () => {
|
||||
let resolve!: (value:typeof response) => void
|
||||
calls.listAuditEvents.mockReturnValueOnce(new Promise(r => {resolve=r}))
|
||||
const wrapper = mount(AuditPanel,options)
|
||||
await wrapper.get('[aria-label="审计开始时间"]').setValue('2026-10-09T10:00')
|
||||
await wrapper.get('[aria-label="审计结束时间"]').setValue('2026-10-01T10:00')
|
||||
await wrapper.get('form').trigger('submit'); expect(calls.listAuditEvents).toHaveBeenCalledTimes(1)
|
||||
await wrapper.get('[aria-label="审计结束时间"]').setValue('2026-10-10T10:00')
|
||||
calls.listAuditEvents.mockResolvedValueOnce({data:{data:[],meta:{page:1,page_size:20,total:0}}})
|
||||
await wrapper.get('form').trigger('submit'); await flushPromises(); resolve(response); await flushPromises()
|
||||
expect(wrapper.text()).not.toContain('admin@example.test'); wrapper.unmount()
|
||||
})
|
||||
})
|
||||
64
frontend/src/views/AuditPanel.vue
Normal file
64
frontend/src/views/AuditPanel.vue
Normal file
@@ -0,0 +1,64 @@
|
||||
<script setup lang="ts">
|
||||
import { formatDateTime } from '../date-format'
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { listAuditEvents, redactAuditDetails, type AuditEvent, type AuditParams } from '../admin-api'
|
||||
const filters = ref({ q:'', action:'', resource_type:'', from:'', to:'' })
|
||||
const applied = ref<Omit<AuditParams, 'page'|'page_size'>>({})
|
||||
const page = ref(1), pageSize = ref(20), total = ref(0), loading = ref(false), error = ref('')
|
||||
const events = ref<AuditEvent[]>([]), selected = ref<AuditEvent|null>(null), detailOpen = ref(false)
|
||||
const pageSizes = [20,50,100]
|
||||
let request = 0
|
||||
async function refresh() {
|
||||
const id = ++request
|
||||
loading.value = true; error.value = ''; events.value = []
|
||||
try {
|
||||
const response = await listAuditEvents({ ...applied.value, page:page.value, page_size:pageSize.value })
|
||||
if (id !== request) return
|
||||
events.value = response.data.data; total.value = response.data.meta.total
|
||||
} catch(e) { if (id === request) { total.value = 0; error.value = e instanceof Error ? e.message : '审计日志加载失败' } }
|
||||
finally { if (id === request) loading.value = false }
|
||||
}
|
||||
function search() {
|
||||
try {
|
||||
const { q, action, resource_type, from, to } = filters.value
|
||||
const start = from ? new Date(from).toISOString() : undefined
|
||||
const end = to ? new Date(to).toISOString() : undefined
|
||||
if (start && end && start > end) throw new Error('开始时间不能晚于结束时间')
|
||||
applied.value = {q:q.trim() || undefined, action:action.trim() || undefined, resource_type:resource_type.trim() || undefined, from:start, to:end}
|
||||
page.value = 1; refresh()
|
||||
} catch(e) { error.value = e instanceof Error ? e.message : '请选择有效时间' }
|
||||
}
|
||||
function reset() { filters.value = {q:'',action:'',resource_type:'',from:'',to:''}; search() }
|
||||
function detail(event:AuditEvent) { selected.value = {...event, details:redactAuditDetails(event.details) as Record<string, unknown>}; detailOpen.value = true }
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
<template>
|
||||
<section class="data-section">
|
||||
<div class="section-heading"><div><h2>管理员操作记录</h2><p>共 {{ total }} 条;按操作人邮箱、动作或资源类型搜索</p></div><el-button :loading="loading" @click="refresh">刷新日志</el-button></div>
|
||||
<form class="filters audit-filters" @submit.prevent="search">
|
||||
<input v-model="filters.q" aria-label="搜索审计日志" placeholder="邮箱 / 动作 / 资源类型"/>
|
||||
<input v-model="filters.action" aria-label="审计动作" placeholder="动作"/>
|
||||
<input v-model="filters.resource_type" aria-label="资源类型" placeholder="资源类型"/>
|
||||
<label>开始时间(本地)<input v-model="filters.from" type="datetime-local" aria-label="审计开始时间"/></label>
|
||||
<label>结束时间(本地)<input v-model="filters.to" type="datetime-local" aria-label="审计结束时间"/></label>
|
||||
<button class="search-button" type="submit">筛选</button><el-button @click="reset">重置</el-button>
|
||||
</form>
|
||||
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||
<p v-if="loading" role="status" class="muted">正在加载审计日志…</p>
|
||||
<div class="business-table">
|
||||
<el-table :data="events" v-loading="loading" :empty-text="loading ? '加载中' : error ? '日志未加载' : '暂无符合条件的审计日志'">
|
||||
<el-table-column prop="id" label="ID" width="85"/><el-table-column prop="actor_email" label="操作人邮箱" min-width="200"/>
|
||||
<el-table-column prop="action" label="动作" min-width="160"/><el-table-column prop="resource_type" label="资源类型" min-width="140"/><el-table-column prop="resource_id" label="资源 ID" min-width="100"/>
|
||||
<el-table-column label="时间(本地)" min-width="210"><template #default="scope">{{ formatDateTime(scope.row.created_at) }}</template></el-table-column>
|
||||
<el-table-column label="操作" width="80"><template #default="scope"><el-button link @click="detail(scope.row)">详情</el-button></template></el-table-column>
|
||||
</el-table>
|
||||
<el-pagination v-model:current-page="page" v-model:page-size="pageSize" :total="total" :page-sizes="pageSizes" :disabled="loading" layout="total, sizes, prev, pager, next" @current-change="refresh" @size-change="page=1;refresh()"/>
|
||||
</div>
|
||||
<el-drawer v-model="detailOpen" title="审计详情" size="min(620px, 95vw)">
|
||||
<template v-if="selected"><dl class="license-detail"><dt>记录 ID</dt><dd>{{ selected.id }}</dd><dt>操作人</dt><dd>{{ selected.actor_email }} (#{{ selected.actor_admin_id }})</dd><dt>动作</dt><dd>{{ selected.action }}</dd><dt>资源</dt><dd>{{ selected.resource_type }} / {{ selected.resource_id ?? '—' }}</dd><dt>时间(本地)</dt><dd>{{ formatDateTime(selected.created_at) }}</dd></dl><p class="subheading">操作详情(密码相关字段已隐藏)</p><pre class="audit-details">{{ JSON.stringify(selected.details, null, 2) }}</pre></template>
|
||||
</el-drawer>
|
||||
</section>
|
||||
</template>
|
||||
<style scoped>
|
||||
.audit-filters{flex-wrap:wrap;margin-bottom:16px}.audit-filters label{font-size:12px;color:#687586;display:flex;align-items:center;gap:8px}.audit-details{white-space:pre-wrap;overflow-wrap:anywhere;font-size:13px}.license-detail dd{overflow-wrap:anywhere}
|
||||
</style>
|
||||
31
frontend/src/views/CustomerPortal.test.ts
Normal file
31
frontend/src/views/CustomerPortal.test.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import CustomerPortal from './CustomerPortal.vue'
|
||||
|
||||
const post = vi.fn()
|
||||
vi.mock('axios', async () => {
|
||||
const actual = await vi.importActual<typeof import('axios')>('axios')
|
||||
return { ...actual, default: { ...actual.default, create: () => ({ post }) }, isAxiosError: () => true }
|
||||
})
|
||||
|
||||
describe('CustomerPortal', () => {
|
||||
afterEach(() => { post.mockReset(); vi.restoreAllMocks() })
|
||||
it('sends credentials, renders snapshot, and clears them on exit', async () => {
|
||||
post.mockResolvedValueOnce({ data: { data: { customer:{id:1,name:'Acme'},product:{name:'App',code:'app'},license:{id:3,status:'active',expires_at:'2026-12-01'},instance:{instance_id:'i',status:'activated',freeze_state:'none'},lease:{current_state:'active',expires_at:null},releases:[] },meta:{total:0} } })
|
||||
const wrapper = mount(CustomerPortal)
|
||||
await wrapper.get('input').setValue('instance-1'); await wrapper.get('input[type=password]').setValue('secret-value'); await wrapper.get('form').trigger('submit'); await flushPromises()
|
||||
expect(post).toHaveBeenCalledWith('/portal/snapshot',{instance_id:'instance-1',secret:'secret-value'},{params:{page:1,page_size:20}})
|
||||
expect(wrapper.text()).toContain('Acme'); expect(wrapper.text()).toContain('App'); expect(wrapper.find('input').exists()).toBe(false)
|
||||
await wrapper.get('button').trigger('click'); expect(wrapper.find('input').exists()).toBe(true); expect((wrapper.find('input[type=password]').element as HTMLInputElement).value).toBe('')
|
||||
})
|
||||
it('shows generic denial and keeps no credential after cross-tenant refusal', async () => {
|
||||
post.mockRejectedValueOnce({ response:{ data:{ error:{ message:'Invalid credentials' } } } })
|
||||
const wrapper=mount(CustomerPortal); await wrapper.get('input').setValue('other'); await wrapper.get('input[type=password]').setValue('bad'); await wrapper.get('form').trigger('submit'); await flushPromises()
|
||||
expect(wrapper.get('[role=alert]').text()).toContain('请求失败'); expect((wrapper.find('input[type=password]').element as HTMLInputElement).value).toBe('')
|
||||
})
|
||||
it('shows download failure without exposing secret', async () => {
|
||||
post.mockResolvedValueOnce({ data:{ data:{ customer:{id:1,name:'Acme'},product:{name:'App',code:'app'},license:{id:3,status:'active',expires_at:'2026-12-01'},instance:{instance_id:'i',status:'activated',freeze_state:'none'},lease:{current_state:'active',expires_at:null},releases:[{id:4,version:'1.0',size_bytes:1,download_allowed:true}] },meta:{total:1} } }).mockRejectedValueOnce(new Error('download failed'))
|
||||
const wrapper=mount(CustomerPortal); await wrapper.get('input').setValue('i'); await wrapper.get('input[type=password]').setValue('secret'); await wrapper.get('form').trigger('submit'); await flushPromises(); await wrapper.get('table button').trigger('click'); await flushPromises()
|
||||
expect(wrapper.get('[role=alert]').text()).toContain('下载失败'); expect(wrapper.text()).not.toContain('secret')
|
||||
})
|
||||
})
|
||||
50
frontend/src/views/CustomerPortal.vue
Normal file
50
frontend/src/views/CustomerPortal.vue
Normal file
@@ -0,0 +1,50 @@
|
||||
<script setup lang="ts">
|
||||
import { formatDateTime } from '../date-format'
|
||||
import { ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
const client = axios.create({ baseURL: '/api/v1', timeout: 8000, withCredentials: false })
|
||||
type Release = { id:number; version:string; sha256:string; size_bytes:number; download_allowed:boolean }
|
||||
type Snapshot = { customer:{id:number;name:string}; product:{name:string;code:string}; license:{id:number;status:string;expires_at:string}; instance:{instance_id:string;status:string;freeze_state:string}; lease:{current_state:string;expires_at:string|null}; releases:Release[] }
|
||||
const instanceID=ref(''), secret=ref(''), data=ref<Snapshot|null>(null), page=ref(1), total=ref(0), busy=ref(false), error=ref('')
|
||||
let credential: {instance_id:string;secret:string}|null=null
|
||||
function clear(){credential=null;secret.value='';instanceID.value='';data.value=null;error.value='';page.value=1;total.value=0}
|
||||
async function load(next=1){
|
||||
if(busy.value)return
|
||||
busy.value=true;error.value='';data.value=null
|
||||
try{
|
||||
const input=credential||{instance_id:instanceID.value.trim(),secret:secret.value}
|
||||
const response=await client.post<{data:Snapshot;meta:{total:number}}>('/portal/snapshot',input,{params:{page:next,page_size:20}})
|
||||
credential=input;secret.value='';data.value=response.data.data;total.value=response.data.meta.total;page.value=next
|
||||
}catch(e){error.value=axios.isAxiosError(e)?(e.response?.data?.error?.message||'客户入口暂时不可用'):'请求失败';credential=null;secret.value=''}finally{busy.value=false}
|
||||
}
|
||||
async function download(release:Release){
|
||||
if(!credential||!data.value||busy.value)return
|
||||
busy.value=true;error.value=''
|
||||
try{
|
||||
const response=await client.post(`/customers/${data.value.customer.id}/releases/${release.id}/download`,credential,{responseType:'blob'})
|
||||
const url=URL.createObjectURL(response.data);const a=document.createElement('a');a.href=url;a.download=`${release.version}.bin`;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000)
|
||||
}catch{error.value='下载失败或权限已失效'}finally{busy.value=false}
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<main class="portal">
|
||||
<header><h1>客户实例</h1><button v-if="credential" @click="clear" :disabled="busy">退出</button></header>
|
||||
<form v-if="!credential" @submit.prevent="load()">
|
||||
<label>实例 ID<input v-model="instanceID" required maxlength="36" autocomplete="off" :disabled="busy"></label>
|
||||
<label>实例凭据<input v-model="secret" required type="password" maxlength="128" autocomplete="off" :disabled="busy"></label>
|
||||
<button :disabled="busy">{{busy?'正在查询':'查看实例'}}</button>
|
||||
</form>
|
||||
<p v-if="error" role="alert">{{error}}</p>
|
||||
<p v-if="busy" role="status">正在加载</p>
|
||||
<template v-if="data">
|
||||
<h2>{{data.product.name}} <small>{{data.product.code}}</small></h2>
|
||||
<dl><dt>客户</dt><dd>{{data.customer.name}}</dd><dt>授权</dt><dd>{{data.license.id}} · {{data.license.status}}</dd><dt>权益到期</dt><dd>{{formatDateTime(data.license.expires_at)}}</dd><dt>实例</dt><dd>{{data.instance.instance_id}}</dd><dt>实例状态</dt><dd>{{data.instance.status}} · {{data.instance.freeze_state}}</dd><dt>当前权益</dt><dd>{{data.lease.current_state}}</dd><dt>租约到期</dt><dd>{{formatDateTime(data.lease.expires_at, '暂无租约')}}</dd></dl>
|
||||
<h2>产品版本</h2>
|
||||
<div class="table-wrap"><table><thead><tr><th>版本</th><th>大小</th><th>下载权限</th><th></th></tr></thead><tbody><tr v-for="release in data.releases" :key="release.id"><td>{{release.version}}</td><td>{{release.size_bytes}} B</td><td>{{release.download_allowed?'允许':'禁止'}}</td><td><button :disabled="busy||!release.download_allowed" @click="download(release)">下载</button></td></tr><tr v-if="!data.releases.length"><td colspan="4">暂无已发布版本</td></tr></tbody></table></div>
|
||||
<nav aria-label="版本分页"><button :disabled="busy||page<=1" @click="load(page-1)">上一页</button><span>第 {{page}} 页 · {{total}} 条</span><button :disabled="busy||page*20>=total" @click="load(page+1)">下一页</button></nav>
|
||||
</template>
|
||||
</main>
|
||||
</template>
|
||||
<style scoped>
|
||||
.portal{max-width:960px;margin:auto;padding:24px;color:#202124;background:#fff;min-height:100vh}header{display:flex;align-items:center;justify-content:space-between}h1{font-size:24px}h2{font-size:18px;margin-top:28px}form{display:grid;gap:16px;max-width:460px}label{display:grid;gap:6px}input{padding:10px;border:1px solid #aeb4bc;border-radius:4px;min-width:0}button{padding:8px 14px;border:1px solid #aeb4bc;border-radius:4px;cursor:pointer}button:disabled{cursor:default;opacity:.5}dl{display:grid;grid-template-columns:100px minmax(0,1fr);gap:12px}dd{margin:0;overflow-wrap:anywhere}dt{color:#62676f}.table-wrap{overflow:auto}table{width:100%;border-collapse:collapse}td,th{text-align:left;padding:12px;border-bottom:1px solid #ddd}nav{display:flex;gap:12px;align-items:center;margin-top:16px}small{font-weight:normal;color:#62676f}p[role=alert]{color:#a4262c}@media(max-width:480px){.portal{padding:16px}nav{flex-wrap:wrap}}
|
||||
</style>
|
||||
25
frontend/src/views/DashboardPanel.test.ts
Normal file
25
frontend/src/views/DashboardPanel.test.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import DashboardPanel from './DashboardPanel.vue'
|
||||
import { formatDateTime } from '../date-format'
|
||||
const mocks=vi.hoisted(()=>({getDashboard:vi.fn(),listLicenses:vi.fn()}))
|
||||
vi.mock('../dashboard-api',()=>({getDashboard:mocks.getDashboard}))
|
||||
vi.mock('../api',()=>({listLicenses:mocks.listLicenses}))
|
||||
const payload={active_licenses:12,new_customers:3,paid_revenue_cents:253400,currency:'CNY',expiring_licenses:2,generated_at:'2026-10-08T00:00:00Z',license_trend:[{month:'2026-10',issued:4,expired:1}],upcoming_expirations:[],recent_licenses:[]}
|
||||
describe('DashboardPanel',()=>{afterEach(()=>vi.resetAllMocks())
|
||||
it('renders values supplied by the dashboard API, never demo defaults',async()=>{mocks.getDashboard.mockResolvedValue({data:{data:payload}});const wrapper=mount(DashboardPanel,{global:{stubs:{'el-button':{template:'<button @click="$emit(\'click\')"><slot/></button>'}}}});await flushPromises();expect(wrapper.text()).toContain('12');expect(wrapper.text()).toContain('3');expect(wrapper.text()).toContain('¥2,534.00');expect(wrapper.text()).toContain('4');expect(wrapper.text()).toContain('未来 30 天暂无到期授权');expect(mocks.getDashboard).toHaveBeenCalledWith(6);wrapper.unmount()})
|
||||
it('renders searched licenses even when the summary is unavailable', async () => {
|
||||
mocks.getDashboard.mockRejectedValue(new Error('暂时不可用'))
|
||||
const expires = '2026-10-20T00:03:04Z'
|
||||
mocks.listLicenses.mockResolvedValue({ data: { data: [{ id: 1, license_key: 'test-license', customer_name: '测试客户', product_name: '测试产品', status: 'active', expires_at: expires }] } })
|
||||
const wrapper = mount(DashboardPanel, { global: { stubs: { 'el-button': true, 'router-link': true }, directives: { loading: () => {} } } })
|
||||
await flushPromises()
|
||||
await wrapper.get('form').trigger('submit')
|
||||
await flushPromises()
|
||||
expect(wrapper.get('tbody').text()).toContain('test-license')
|
||||
expect(wrapper.get('tbody').text()).toContain(formatDateTime(expires))
|
||||
expect(wrapper.get('tbody').text()).not.toContain(expires)
|
||||
wrapper.unmount()
|
||||
})
|
||||
it('shows an explicit error when summary loading fails',async()=>{mocks.getDashboard.mockRejectedValue(new Error('暂时不可用'));const wrapper=mount(DashboardPanel,{global:{stubs:{'el-button':true}}});await flushPromises();expect(wrapper.get('[role="alert"]').text()).toContain('暂时不可用');wrapper.unmount()})
|
||||
})
|
||||
28
frontend/src/views/DashboardPanel.vue
Normal file
28
frontend/src/views/DashboardPanel.vue
Normal file
@@ -0,0 +1,28 @@
|
||||
<script setup lang="ts">
|
||||
import { formatDateTime } from '../date-format'
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { getDashboard, type DashboardSummary } from '../dashboard-api'
|
||||
import { listLicenses, type License } from '../api'
|
||||
const emit = defineEmits<{ issue:[]; detail:[id:number] }>()
|
||||
const summary = ref<DashboardSummary|null>(null), loading=ref(false), error=ref(''), months=ref(6)
|
||||
const q=ref(''), status=ref(''), rows=ref<License[]>([]), searching=ref(false), searchError=ref('')
|
||||
let request=0
|
||||
async function search(){ const sequence=++request; searching.value=true; searchError.value=''; try{const r=await listLicenses({page:1,q:q.value,status:status.value}); if(sequence===request)rows.value=r.data.data} catch(e){if(sequence===request)searchError.value=e instanceof Error?e.message:'搜索失败'} finally{if(sequence===request)searching.value=false} }
|
||||
async function load(){loading.value=true;error.value='';try{summary.value=(await getDashboard(months.value)).data.data;if(!q.value&&!status.value)rows.value=summary.value.recent_licenses}catch(e){error.value=e instanceof Error?e.message:'统计加载失败'}finally{loading.value=false}}
|
||||
const maximum=computed(()=>Math.max(1,...(summary.value?.license_trend??[]).flatMap(x=>[x.issued,x.expired])))
|
||||
const money=computed(()=>new Intl.NumberFormat('zh-CN',{style:'currency',currency:summary.value?.currency??'CNY'}).format((summary.value?.paid_revenue_cents??0)/100))
|
||||
function days(value:string){return Math.max(0,Math.ceil((Date.parse(value)-Date.parse(summary.value?.generated_at ?? new Date().toISOString()))/86400000))}
|
||||
function statusLabel(license:License){if(license.status==='active'&&days(license.expires_at)<=30)return '即将到期';return ({active:'有效',scheduled:'未开始',expired:'已到期',revoked:'已撤销'} as Record<string,string>)[license.status]??license.status}
|
||||
function statusClass(license:License){if(license.status==='revoked'||license.status==='expired')return 'red';if(license.status==='active'&&days(license.expires_at)<=30)return 'amber';return license.status==='active'?'green':'amber'}
|
||||
onMounted(load)
|
||||
</script>
|
||||
<template>
|
||||
<div class="headline"><div><h1>平台运营概况</h1><p>查看授权、客户与线下订单的最新数据。</p></div><el-button type="primary" @click="emit('issue')">+ 生成授权</el-button></div>
|
||||
<p v-if="error" role="alert" class="error">{{error}} <el-button link @click="load">重试</el-button></p>
|
||||
<div v-loading="loading" :aria-busy="loading">
|
||||
<div class="stats"><article class="stat"><span>有效 License</span><strong>{{summary?.active_licenses??'—'}}</strong><small>当前已生效且未到期</small><i class="i-blue">◇</i></article><article class="stat"><span>本月新增客户</span><strong>{{summary?.new_customers??'—'}}</strong><small>按 UTC 月份统计</small><i class="i-green">♙</i></article><article class="stat"><span>本月已收款金额</span><strong>{{summary?money:'—'}}</strong><small>线下订单 · UTC 收款月份</small><i class="i-amber">¥</i></article><article class="stat"><span>即将到期(30天)</span><strong>{{summary?.expiring_licenses??'—'}}</strong><small>需要跟进</small><i class="i-red">!</i></article></div>
|
||||
<div class="dashboard-grid"><section class="panel"><div class="panel-head"><h2>授权趋势</h2><select v-model="months" aria-label="趋势周期" @change="load"><option :value="6">近 6 个月</option><option :value="12">近 12 个月</option></select></div><div v-if="summary" class="chart" role="img" aria-label="按 UTC 月份统计的新增和到期授权"><div v-for="month in summary.license_trend" :key="month.month" class="bar-group" :title="`${month.month}:新增 ${month.issued},到期 ${month.expired}`"><div class="bar issued" :style="{height:`${month.issued/maximum*100}%`}"></div><div class="bar expired" :style="{height:`${month.expired/maximum*100}%`}"></div><span>{{month.month.slice(5)}}月</span></div></div><p v-else class="empty-state">{{loading?'正在加载趋势…':'暂无统计数据'}}</p><div class="legend"><span><i></i>新增授权</span><span><i class="expired"></i>到期授权</span></div><p v-if="summary&&maximum===1&&!summary.license_trend.some(x=>x.issued||x.expired)" class="muted">该时间范围内暂无授权记录</p></section>
|
||||
<section class="panel"><div class="panel-head"><h2>近期到期</h2><router-link to="/licenses?status=expiring">查看全部 →</router-link></div><div v-for="license in summary?.upcoming_expirations??[]" :key="license.id" class="deadline"><button class="deadline-name" @click="emit('detail',license.id)">{{license.customer_name}}<small>{{license.product_name}}</small></button><span class="tag" :class="days(license.expires_at)<=7?'red':days(license.expires_at)<=24?'amber':'green'">{{days(license.expires_at)}} 天后</span></div><p v-if="summary&&!summary.upcoming_expirations.length" class="empty-state">未来 30 天暂无到期授权</p></section></div>
|
||||
<section class="panel table-panel"><div class="table-head"><h2>最近授权</h2><form class="filters" @submit.prevent="search"><input v-model="q" placeholder="搜索客户或 License" aria-label="搜索客户或 License"/><select v-model="status" aria-label="授权状态" @change="search"><option value="">全部状态</option><option value="active">有效</option><option value="expiring">即将到期</option><option value="pending">未开始</option><option value="expired">已到期</option><option value="revoked">已撤销</option></select><button class="search-button">搜索</button></form></div><p v-if="searchError" role="alert" class="error">{{searchError}}</p><div class="table-scroll" v-loading="searching"><table><thead><tr><th>License</th><th>客户</th><th>产品</th><th>类型</th><th>到期时间</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="license in rows" :key="license.id"><td class="license-code">{{license.license_key}}</td><td><span class="avatar">{{license.customer_name.slice(0,1)}}</span>{{license.customer_name}}</td><td>{{license.product_name}}</td><td>期限授权</td><td>{{formatDateTime(license.expires_at)}}</td><td><span class="tag" :class="statusClass(license)">{{statusLabel(license)}}</span></td><td><button class="action" @click="emit('detail',license.id)">查看详情</button></td></tr></tbody></table><p v-if="!rows.length&&!loading&&!searching" class="empty-state">没有匹配的授权记录</p></div></section><div class="footer-note">{{summary?'更新于 '+formatDateTime(summary.generated_at):'数据尚未加载'}} · <router-link to="/licenses">查看全部授权</router-link></div>
|
||||
</div>
|
||||
</template>
|
||||
27
frontend/src/views/IntegrationPanel.test.ts
Normal file
27
frontend/src/views/IntegrationPanel.test.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import ElementPlus from 'element-plus'
|
||||
const calls = vi.hoisted(() => ({getIntegrationKit:vi.fn()}))
|
||||
vi.mock('../admin-api', async importOriginal => ({...await importOriginal<typeof import('../admin-api')>(),...calls}))
|
||||
import IntegrationPanel from './IntegrationPanel.vue'
|
||||
const kit = {protocol_version:'license-v2 / lease-v2',platform_base_url:'https://license.yihuiyong.cn',language:'python',language_label:'Python 3.11+',mode:'service',mode_label:'常驻服务',endpoints:[{method:'POST',path:'/heartbeat',purpose:'刷新租约'}],security_rules:['不得泄露 secret'],prompt:'实现 LicenseClient',protocol:'DER signature',payload_example:{version:'lease-v2'}}
|
||||
beforeEach(() => {vi.resetAllMocks();calls.getIntegrationKit.mockResolvedValue({data:{data:kit}})})
|
||||
describe('IntegrationPanel',()=>{
|
||||
it('loads generated materials and exposes both download formats',async()=>{
|
||||
const wrapper=mount(IntegrationPanel,{global:{plugins:[ElementPlus]}});await flushPromises()
|
||||
expect(calls.getIntegrationKit).toHaveBeenCalledWith('python','service')
|
||||
expect(wrapper.text()).toContain('实现 LicenseClient');expect(wrapper.text()).toContain('不得泄露 secret')
|
||||
expect(wrapper.text()).toContain('https://license.yihuiyong.cn');expect(wrapper.text()).toContain('LICENSE_API_BASE_URL')
|
||||
expect(wrapper.find('a[href*="archive"]').attributes('href')).toContain('language=python&mode=service')
|
||||
expect(wrapper.find('a[href*="download"]').exists()).toBe(true)
|
||||
await wrapper.find('select[aria-label="目标语言"]').setValue('dotnet');await flushPromises()
|
||||
expect(calls.getIntegrationKit).toHaveBeenLastCalledWith('dotnet','service')
|
||||
expect(wrapper.find('a[href*="archive"]').attributes('href')).toContain('language=dotnet')
|
||||
wrapper.unmount()
|
||||
})
|
||||
it('shows API failures without retaining old content',async()=>{
|
||||
calls.getIntegrationKit.mockRejectedValueOnce(new Error('资料不可用'))
|
||||
const wrapper=mount(IntegrationPanel,{global:{plugins:[ElementPlus]}});await flushPromises()
|
||||
expect(wrapper.text()).toContain('资料不可用');expect(wrapper.find('.prompt-box').exists()).toBe(false);wrapper.unmount()
|
||||
})
|
||||
})
|
||||
62
frontend/src/views/IntegrationPanel.vue
Normal file
62
frontend/src/views/IntegrationPanel.vue
Normal file
@@ -0,0 +1,62 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { getIntegrationKit, type IntegrationKit, type IntegrationLanguage, type IntegrationMode } from '../admin-api'
|
||||
|
||||
const language = ref<IntegrationLanguage>('python')
|
||||
const mode = ref<IntegrationMode>('service')
|
||||
const kit = ref<IntegrationKit|null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
|
||||
const languages: {value:IntegrationLanguage;label:string}[] = [
|
||||
{value:'python',label:'Python'}, {value:'go',label:'Go'}, {value:'java',label:'Java'}, {value:'dotnet',label:'.NET'}, {value:'nodejs',label:'Node.js'},
|
||||
]
|
||||
const modes: {value:IntegrationMode;label:string}[] = [
|
||||
{value:'desktop',label:'桌面客户端'}, {value:'service',label:'常驻服务'}, {value:'container',label:'容器部署'},
|
||||
]
|
||||
const downloadURL = computed(() => `/api/v1/integration-kit/download?language=${language.value}&mode=${mode.value}`)
|
||||
|
||||
let requestSequence = 0
|
||||
async function load() {
|
||||
const sequence = ++requestSequence
|
||||
loading.value = true; error.value = ''; kit.value = null
|
||||
try { const result = await getIntegrationKit(language.value, mode.value); if (sequence === requestSequence) kit.value = result.data.data }
|
||||
catch (e) { if (sequence === requestSequence) error.value = e instanceof Error ? e.message : '接入资料加载失败' }
|
||||
finally { if (sequence === requestSequence) loading.value = false }
|
||||
}
|
||||
async function copyPrompt() {
|
||||
if (!kit.value) return
|
||||
try { await navigator.clipboard.writeText(kit.value.prompt); ElMessage.success('接入提示词已复制') }
|
||||
catch { ElMessage.error('复制失败,请手动选择提示词') }
|
||||
}
|
||||
watch([language, mode], load)
|
||||
onMounted(load)
|
||||
</script>
|
||||
<template>
|
||||
<section class="data-section integration-panel">
|
||||
<div class="section-heading"><div><h2>客户端接入包</h2><p>选择目标语言和运行方式,交付给外部工程团队实现客户端 SDK。</p></div><el-button :loading="loading" @click="load">刷新资料</el-button></div>
|
||||
<div class="integration-controls">
|
||||
<label>目标语言 <select v-model="language" aria-label="目标语言"><option v-for="item in languages" :key="item.value" :value="item.value">{{ item.label }}</option></select></label>
|
||||
<label>接入模式 <select v-model="mode" aria-label="接入模式"><option v-for="item in modes" :key="item.value" :value="item.value">{{ item.label }}</option></select></label>
|
||||
<a class="el-button el-button--primary" :href="`/api/v1/integration-kit/archive?language=${language}&mode=${mode}`" download>下载 ZIP 接入包</a>
|
||||
<a class="el-button" :href="downloadURL" download>下载 Markdown</a>
|
||||
</div>
|
||||
<p v-if="loading" class="muted" role="status">正在生成接入资料…</p><p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||
<template v-if="kit">
|
||||
<div class="integration-meta"><span>协议:{{ kit.protocol_version }}</span><span>目标:{{ kit.language_label }} / {{ kit.mode_label }}</span><span>默认平台地址:<code>{{ kit.platform_base_url }}</code></span></div>
|
||||
<p class="subheading">SDK 默认使用该根地址;部署可通过 <code>LICENSE_API_BASE_URL</code> 覆盖。配置中不要附加 <code>/api/v1</code>。</p>
|
||||
<h3>接口清单</h3>
|
||||
<div class="business-table"><el-table :data="kit.endpoints" empty-text="暂无接口"><el-table-column prop="method" label="方法" width="90"/><el-table-column prop="path" label="路径" min-width="360"/><el-table-column prop="purpose" label="用途" min-width="260"/></el-table></div>
|
||||
<h3>工程提示词</h3>
|
||||
<div class="prompt-box"><pre>{{ kit.prompt }}</pre><el-button title="复制提示词" @click="copyPrompt">复制</el-button></div>
|
||||
<h3>安全检查</h3>
|
||||
<ul class="integration-rules"><li v-for="rule in kit.security_rules" :key="rule">{{ rule }}</li></ul>
|
||||
<h3>完整协议</h3>
|
||||
<details><summary>查看协议与验收要求</summary><pre class="vector-box">{{ kit.protocol }}</pre></details>
|
||||
<h3>租约字段示例</h3>
|
||||
<pre class="vector-box">{{ JSON.stringify(kit.payload_example, null, 2) }}</pre>
|
||||
<p class="subheading">签名测试向量及独立测试公钥包含在 ZIP 中,禁止将测试公钥加入生产信任配置。</p>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
39
frontend/src/views/OrdersPanel.test.ts
Normal file
39
frontend/src/views/OrdersPanel.test.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import type { Customer, Product } from '../api'
|
||||
import ElementPlus from 'element-plus'
|
||||
import { defineComponent } from 'vue'
|
||||
const SelectStub = defineComponent({ name:'ElSelect', props:['modelValue'], emits:['update:modelValue'], template:'<select :value="modelValue" @change="$emit(\'update:modelValue\', Number($event.target.value))"><option value="1">客户</option><option value="2">产品</option></select>' })
|
||||
const calls = vi.hoisted(() => ({ listOrders:vi.fn(),getOrder:vi.fn(),createOrder:vi.fn(),confirmPayment:vi.fn(),issueOrder:vi.fn() }))
|
||||
vi.mock('../orders-api', () => calls)
|
||||
import OrdersPanel from './OrdersPanel.vue'
|
||||
const order = {id:42,order_no:'test-order',customer_id:1,customer_name:'测试客户',product_id:2,product_name:'测试产品',amount_cents:100,currency:'CNY',status:'paid',payment_reference:'BANK-001',license_id:null}
|
||||
const props: {customers: Customer[]; products: Product[]} = {customers:[{id:1,name:'测试客户',contact_email:'a@example.test',status:'active',created_at:'',updated_at:''}],products:[{id:2,code:'test',name:'测试产品',description:'',active:true,created_at:'',updated_at:''}]}
|
||||
function button(wrapper:ReturnType<typeof mount>,text:string) { return wrapper.findAll('button').find(item=>item.text()===text)! }
|
||||
beforeEach(()=>{vi.resetAllMocks();calls.listOrders.mockResolvedValue({data:{data:[order],meta:{total:1}}});calls.getOrder.mockResolvedValue({data:{data:order}})})
|
||||
describe('OrdersPanel',()=>{
|
||||
it('loads persisted orders and retrieves detail',async()=>{
|
||||
const wrapper=mount(OrdersPanel,{props,global:{plugins:[ElementPlus]}});await flushPromises()
|
||||
expect(wrapper.text()).toContain('test-order');expect(calls.listOrders).toHaveBeenCalledWith(1)
|
||||
await button(wrapper,'详情').trigger('click');await flushPromises();expect(calls.getOrder).toHaveBeenCalledWith(42)
|
||||
wrapper.unmount()
|
||||
})
|
||||
it('retains an unchanged create key after failure',async()=>{
|
||||
calls.createOrder.mockRejectedValueOnce(new Error('network')).mockResolvedValueOnce({})
|
||||
const wrapper=mount(OrdersPanel,{props,global:{plugins:[ElementPlus],stubs:{teleport:true,ElSelect:SelectStub}}});await flushPromises()
|
||||
await button(wrapper,'录入订单').trigger('click');await flushPromises()
|
||||
const selects=wrapper.findAllComponents({name:'ElSelect'})
|
||||
selects[0]!.vm.$emit('update:modelValue',1);selects[1]!.vm.$emit('update:modelValue',2);await flushPromises()
|
||||
await button(wrapper,'创建订单').trigger('click');await flushPromises()
|
||||
await button(wrapper,'创建订单').trigger('click');await flushPromises()
|
||||
expect(calls.createOrder).toHaveBeenCalledTimes(2)
|
||||
expect(calls.createOrder.mock.calls[0]![1]).toBe(calls.createOrder.mock.calls[1]![1])
|
||||
expect(calls.createOrder.mock.calls[0]![0]).toEqual({customer_id:1,product_id:2,amount_cents:100,currency:'CNY'})
|
||||
wrapper.unmount()
|
||||
})
|
||||
it('displays loading failures',async()=>{
|
||||
calls.listOrders.mockRejectedValue(new Error('订单接口失败'))
|
||||
const wrapper=mount(OrdersPanel,{props,global:{plugins:[ElementPlus]}});await flushPromises()
|
||||
expect(wrapper.get('[role="alert"]').text()).toBe('订单接口失败');wrapper.unmount()
|
||||
})
|
||||
})
|
||||
90
frontend/src/views/OrdersPanel.vue
Normal file
90
frontend/src/views/OrdersPanel.vue
Normal file
@@ -0,0 +1,90 @@
|
||||
<script setup lang="ts">
|
||||
import { formatDateTime } from '../date-format'
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { type Customer, type Product } from '../api'
|
||||
import { createOrder, confirmPayment, getOrder, issueOrder, listOrders, type Order } from '../orders-api'
|
||||
|
||||
const props = defineProps<{customers:Customer[];products:Product[]}>()
|
||||
const emit = defineEmits<{issued:[]}>()
|
||||
const orders = ref<Order[]>([]), total = ref(0), page = ref(1), loading = ref(false), busy = ref(false), error = ref('')
|
||||
const createOpen = ref(false), paymentOpen = ref(false), issueOpen = ref(false), detailOpen = ref(false)
|
||||
const selected = ref<Order|null>(null)
|
||||
const form = ref({customer_id:null as number|null,product_id:null as number|null,amount_cents:100,currency:'CNY'})
|
||||
const payment = ref({amount_cents:0,payment_reference:''})
|
||||
const period = ref({starts_at:new Date().toISOString(),expires_at:new Date(Date.now()+365*86400000).toISOString()})
|
||||
const pending = new Map<string,{body:string;key:string}>()
|
||||
function retryKey(operation:string,body:unknown) {
|
||||
const encoded = JSON.stringify(body)
|
||||
let value = pending.get(operation)
|
||||
if (!value || value.body !== encoded) { value = {body:encoded,key:crypto.randomUUID()}; pending.set(operation,value) }
|
||||
return value.key
|
||||
}
|
||||
async function refresh() {
|
||||
loading.value = true; error.value = ''
|
||||
try { const response = await listOrders(page.value); orders.value = response.data.data; total.value = response.data.meta.total }
|
||||
catch (e) { error.value = e instanceof Error ? e.message : '订单加载失败' }
|
||||
finally { loading.value = false }
|
||||
}
|
||||
async function detail(order:Order) {
|
||||
try { selected.value = (await getOrder(order.id)).data.data; detailOpen.value = true }
|
||||
catch(e) { ElMessage.error(e instanceof Error ? e.message : '详情加载失败') }
|
||||
}
|
||||
function openPayment(order:Order) { selected.value = order; payment.value = {amount_cents:order.amount_cents,payment_reference:''}; paymentOpen.value = true }
|
||||
function openIssue(order:Order) { selected.value = order; period.value = {starts_at:new Date().toISOString(),expires_at:new Date(Date.now()+365*86400000).toISOString()}; issueOpen.value = true }
|
||||
async function submit(operation:'create'|'payment'|'issue') {
|
||||
if (busy.value) return
|
||||
busy.value = true
|
||||
try {
|
||||
if (operation === 'create') {
|
||||
if (!form.value.customer_id || !form.value.product_id || !Number.isSafeInteger(form.value.amount_cents) || form.value.amount_cents < 1) throw new Error('请选择客户、产品并填写正整数金额')
|
||||
const body = {...form.value,customer_id:form.value.customer_id,product_id:form.value.product_id}
|
||||
await createOrder(body,retryKey('create',body)); pending.delete('create'); createOpen.value = false; page.value = 1
|
||||
} else {
|
||||
if (!selected.value) throw new Error('请选择订单')
|
||||
const id = selected.value.id, operationKey = `${operation}:${id}`
|
||||
if (operation === 'payment') {
|
||||
const body = {...payment.value,payment_reference:payment.value.payment_reference.trim()}
|
||||
if (!body.payment_reference) throw new Error('请填写收款凭据编号')
|
||||
await confirmPayment(id,body,retryKey(operationKey,body)); paymentOpen.value = false
|
||||
} else {
|
||||
const body = {starts_at:new Date(period.value.starts_at).toISOString(),expires_at:new Date(period.value.expires_at).toISOString()}
|
||||
if (body.expires_at <= body.starts_at) throw new Error('结束时间必须晚于开始时间')
|
||||
await issueOrder(id,body,retryKey(operationKey,body)); issueOpen.value = false; emit('issued')
|
||||
}
|
||||
pending.delete(operationKey)
|
||||
}
|
||||
ElMessage.success(operation === 'create' ? '订单已创建' : operation === 'payment' ? '收款已确认' : '授权已发放')
|
||||
await refresh()
|
||||
} catch(e) { ElMessage.error(e instanceof Error ? e.message : '订单操作失败') }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
function statusLabel(status:string) { return ({pending_payment:'待收款',paid:'已收款',issued:'已发放'} as Record<string,string>)[status] || status }
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
<template>
|
||||
<section class="data-section">
|
||||
<div class="section-heading"><div><h2>线下订单</h2><p>共 {{ total }} 条</p></div><div><el-button :loading="loading" @click="refresh">刷新订单</el-button><el-button type="primary" @click="createOpen = true">录入订单</el-button></div></div>
|
||||
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||
<el-table :data="orders" v-loading="loading" empty-text="暂无订单">
|
||||
<el-table-column prop="order_no" label="订单号" min-width="240"/><el-table-column prop="customer_name" label="客户" min-width="120"/><el-table-column prop="product_name" label="产品" min-width="120"/>
|
||||
<el-table-column label="金额" width="130"><template #default="scope">{{ (scope.row.amount_cents / 100).toFixed(2) }} {{ scope.row.currency }}</template></el-table-column>
|
||||
<el-table-column label="状态" width="100"><template #default="scope">{{ statusLabel(scope.row.status) }}</template></el-table-column>
|
||||
<el-table-column label="操作" width="240"><template #default="scope"><el-button link @click="detail(scope.row)">详情</el-button><el-button link :disabled="busy || scope.row.status !== 'pending_payment'" @click="openPayment(scope.row)">确认收款</el-button><el-button link type="primary" :disabled="busy || scope.row.status !== 'paid'" @click="openIssue(scope.row)">发放授权</el-button></template></el-table-column>
|
||||
</el-table>
|
||||
<el-pagination v-model:current-page="page" :total="total" :page-size="20" layout="prev, pager, next" @current-change="refresh"/>
|
||||
<el-dialog v-model="createOpen" title="录入线下订单" width="min(520px, 94vw)" :close-on-click-modal="!busy" :show-close="!busy">
|
||||
<el-form label-position="top"><el-form-item label="客户"><el-select v-model="form.customer_id" aria-label="订单客户"><el-option v-for="item in props.customers" :key="item.id" :value="item.id" :label="item.name" :disabled="item.status !== 'active'"/></el-select></el-form-item><el-form-item label="产品"><el-select v-model="form.product_id" aria-label="订单产品"><el-option v-for="item in props.products" :key="item.id" :value="item.id" :label="item.name" :disabled="!item.active"/></el-select></el-form-item><el-form-item label="订单金额(分 / CNY)"><el-input-number v-model="form.amount_cents" :min="1" :max="100000000000" :precision="0" aria-label="订单金额分"/></el-form-item></el-form>
|
||||
<template #footer><el-button :disabled="busy" @click="createOpen = false">取消</el-button><el-button type="primary" :loading="busy" @click="submit('create')">创建订单</el-button></template>
|
||||
</el-dialog>
|
||||
<el-dialog v-model="paymentOpen" title="确认线下收款" width="min(520px, 94vw)" :close-on-click-modal="!busy" :show-close="!busy">
|
||||
<el-form label-position="top"><el-form-item label="实收金额(分 / CNY)"><el-input-number v-model="payment.amount_cents" :min="1" :max="100000000000" :precision="0" aria-label="实收金额分"/></el-form-item><el-form-item label="收款凭据编号"><el-input v-model="payment.payment_reference" maxlength="190" aria-label="收款凭据编号"/></el-form-item></el-form>
|
||||
<template #footer><el-button :disabled="busy" @click="paymentOpen = false">取消</el-button><el-button type="primary" :loading="busy" @click="submit('payment')">确认收款</el-button></template>
|
||||
</el-dialog>
|
||||
<el-dialog v-model="issueOpen" title="发放订单授权" width="min(520px, 94vw)" :close-on-click-modal="!busy" :show-close="!busy">
|
||||
<el-form label-position="top"><el-form-item label="开始时间"><el-date-picker v-model="period.starts_at" type="datetime" value-format="YYYY-MM-DDTHH:mm:ssZ" aria-label="订单授权开始时间"/></el-form-item><el-form-item label="结束时间"><el-date-picker v-model="period.expires_at" type="datetime" value-format="YYYY-MM-DDTHH:mm:ssZ" aria-label="订单授权结束时间"/></el-form-item></el-form>
|
||||
<template #footer><el-button :disabled="busy" @click="issueOpen = false">取消</el-button><el-button type="primary" :loading="busy" @click="submit('issue')">确认发放</el-button></template>
|
||||
</el-dialog>
|
||||
<el-drawer v-model="detailOpen" title="订单详情" size="min(520px, 94vw)"><el-descriptions v-if="selected" :column="1" border><el-descriptions-item label="订单号">{{ selected.order_no }}</el-descriptions-item><el-descriptions-item label="客户">{{ selected.customer_name }} (#{{ selected.customer_id }})</el-descriptions-item><el-descriptions-item label="产品">{{ selected.product_name }} (#{{ selected.product_id }})</el-descriptions-item><el-descriptions-item label="金额">{{ (selected.amount_cents / 100).toFixed(2) }} {{ selected.currency }}</el-descriptions-item><el-descriptions-item label="状态">{{ statusLabel(selected.status) }}</el-descriptions-item><el-descriptions-item label="收款凭据">{{ selected.payment_reference || '未确认' }}</el-descriptions-item><el-descriptions-item label="收款时间">{{ formatDateTime(selected.paid_at, '未确认') }}</el-descriptions-item><el-descriptions-item label="授权ID">{{ selected.license_id || '未发放' }}</el-descriptions-item><el-descriptions-item label="创建时间">{{ formatDateTime(selected.created_at) }}</el-descriptions-item></el-descriptions></el-drawer>
|
||||
</section>
|
||||
</template>
|
||||
138
frontend/src/views/Overview.test.ts
Normal file
138
frontend/src/views/Overview.test.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { defineComponent } from 'vue'
|
||||
|
||||
const routeState = vi.hoisted(() => ({meta:{view:'licenses'},query:{}}))
|
||||
const routerMock = vi.hoisted(() => ({push:vi.fn(),replace:vi.fn()}))
|
||||
vi.mock('vue-router', () => ({useRoute:()=>routeState,useRouter:()=>routerMock}))
|
||||
const health = vi.hoisted(() => ({ checkApiHealth: vi.fn() }))
|
||||
vi.mock('../api-health', () => health)
|
||||
const business = vi.hoisted(() => ({ me: vi.fn(), listCustomers: vi.fn(), listProducts: vi.fn(), listLicenses: vi.fn(), issueLicense: vi.fn(), renewLicense: vi.fn(), listLicenseInstances: vi.fn() }))
|
||||
vi.mock('../api', () => business)
|
||||
const settingsApi = vi.hoisted(() => ({ getSettings: vi.fn() }))
|
||||
vi.mock('../admin-api', () => settingsApi)
|
||||
|
||||
vi.mock('./OrdersPanel.vue', () => ({ default: defineComponent({ template: '<section>线下订单</section>' }) }))
|
||||
import Overview from './Overview.vue'
|
||||
import { formatDateTime } from '../date-format'
|
||||
|
||||
const DrawerStub = defineComponent({ template: '<aside><slot /></aside>' })
|
||||
const ColumnStub = defineComponent({ props: ['label'], template: '<span>{{ label }}</span>' })
|
||||
const TableStub = defineComponent({ template: '<div><slot /></div>' })
|
||||
const ButtonStub = defineComponent({
|
||||
emits: ['click'],
|
||||
template: '<button @click="$emit(\'click\')"><slot /></button>',
|
||||
})
|
||||
|
||||
describe('Overview API status', () => {
|
||||
it('renews using a date picker, validates dates and reuses the key on retry', async () => {
|
||||
routeState.meta.view = 'licenses'
|
||||
health.checkApiHealth.mockResolvedValue('online')
|
||||
business.me.mockResolvedValue({ data: { data: { email: 'admin@example.test' } } })
|
||||
business.listCustomers.mockResolvedValue({ data: { data: [], meta: { total: 0 } } })
|
||||
business.listProducts.mockResolvedValue({ data: { data: [] } })
|
||||
const row = { id: 7, status: 'active', expires_at: '2027-01-02T00:03:04Z' }
|
||||
business.listLicenses.mockResolvedValue({ data: { data: [row], meta: { total: 1 } } })
|
||||
const Actions = defineComponent({ props: ['label'], setup: () => ({ row }), template: '<div v-if="label===\'操作\'"><slot :row="row" /></div>' })
|
||||
const Dialog = defineComponent({ props: ['modelValue', 'title'], template: '<section v-if="modelValue" :data-title="title"><slot/><slot name="footer"/></section>' })
|
||||
const Picker = defineComponent({ props: ['modelValue'], emits: ['update:modelValue'], template: '<input type="text" />' })
|
||||
const wrapper = mount(Overview, { global: { stubs: { 'router-link': true, 'el-dialog': Dialog, 'el-drawer': true, 'el-button': ButtonStub, 'el-input': true, 'el-form': true, 'el-table': TableStub, 'el-table-column': Actions, 'el-select': true, 'el-option': true, 'el-date-picker': Picker, 'el-pagination': true }, directives: { loading: () => {} } } })
|
||||
await flushPromises()
|
||||
await wrapper.findAll('button').find(button => button.text() === '续期')!.trigger('click')
|
||||
const dialog = wrapper.get('[data-title="续期授权"]')
|
||||
const picker = dialog.getComponent(Picker)
|
||||
expect(dialog.text()).toContain(formatDateTime(row.expires_at))
|
||||
picker.vm.$emit('update:modelValue', null)
|
||||
await dialog.findAll('button').find(button => button.text() === '确认续期')!.trigger('click')
|
||||
expect(business.renewLicense).not.toHaveBeenCalled()
|
||||
picker.vm.$emit('update:modelValue', new Date(row.expires_at))
|
||||
await dialog.findAll('button').find(button => button.text() === '确认续期')!.trigger('click')
|
||||
expect(dialog.text()).toContain('新的到期时间必须晚于当前到期时间')
|
||||
const chosen = new Date('2028-03-04T12:34:56+08:00')
|
||||
picker.vm.$emit('update:modelValue', chosen)
|
||||
business.renewLicense.mockRejectedValueOnce(new Error('网络错误')).mockResolvedValueOnce({})
|
||||
await dialog.findAll('button').find(button => button.text() === '确认续期')!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(dialog.text()).toContain('网络错误')
|
||||
const key = business.renewLicense.mock.calls[0][2]
|
||||
await dialog.findAll('button').find(button => button.text() === '确认续期')!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(business.renewLicense).toHaveBeenLastCalledWith(7, chosen.toISOString(), key)
|
||||
expect(wrapper.find('[data-title="续期授权"]').exists()).toBe(false)
|
||||
wrapper.unmount()
|
||||
})
|
||||
afterEach(() => vi.resetAllMocks())
|
||||
|
||||
it('checks on mount and supports manual retry', async () => {
|
||||
routeState.meta.view='dashboard'
|
||||
health.checkApiHealth.mockResolvedValueOnce('online').mockResolvedValueOnce('offline')
|
||||
business.me.mockRejectedValue(new Error('unauthorized'))
|
||||
const wrapper = mount(Overview, { global: { stubs: { 'el-button': ButtonStub, 'el-input': true, 'el-form': true, 'el-drawer': DrawerStub, 'el-table': true, 'el-table-column': true, 'el-select': true, 'el-option': true, 'el-date-picker': true, 'el-pagination': true }, directives: { loading: () => {} } } })
|
||||
expect(wrapper.get('[role="status"]').text()).toBe('检测中')
|
||||
await flushPromises()
|
||||
expect(wrapper.get('[role="status"]').text()).toBe('服务在线')
|
||||
await wrapper.get('button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.get('[role="status"]').text()).toBe('服务未连接')
|
||||
expect(health.checkApiHealth).toHaveBeenCalledTimes(2)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('displays persisted site settings after refresh and updates immediately on save', async () => {
|
||||
routeState.meta.view = 'settings'
|
||||
health.checkApiHealth.mockResolvedValue('online')
|
||||
business.me.mockResolvedValue({ data: { data: { role: 'admin' } } })
|
||||
business.listCustomers.mockResolvedValue({ data: { data: [], meta: { total: 0 } } })
|
||||
business.listProducts.mockResolvedValue({ data: { data: [] } })
|
||||
business.listLicenses.mockResolvedValue({ data: { data: [], meta: { total: 0 } } })
|
||||
settingsApi.getSettings.mockResolvedValue({ data: { data: { site_name: '已保存站点', announcement: '已保存公告', support_email: 'help@example.test', updated_at: null } } })
|
||||
const wrapper = mount(Overview, { global: { stubs: { SettingsPanel: true, 'router-link': true, 'el-dialog': true, 'el-drawer': true, 'el-button': ButtonStub, 'el-input': true, 'el-form': true, 'el-table': true, 'el-table-column': true, 'el-pagination': true }, directives: { loading: () => {} } } })
|
||||
await flushPromises()
|
||||
expect(settingsApi.getSettings).toHaveBeenCalledOnce()
|
||||
expect(wrapper.get('.brand').text()).toContain('已保存站点')
|
||||
expect(wrapper.get('[role="note"]').text()).toBe('已保存公告')
|
||||
expect(wrapper.find('a[href="mailto:help@example.test"]').exists()).toBe(true)
|
||||
wrapper.getComponent({ name: 'SettingsPanel' }).vm.$emit('saved', { site_name: '新站点', announcement: '新公告', support_email: '', updated_at: null })
|
||||
await flushPromises()
|
||||
expect(wrapper.get('.brand').text()).toContain('新站点')
|
||||
expect(wrapper.get('[role="note"]').text()).toBe('新公告')
|
||||
expect(wrapper.find('a[href^="mailto:"]').exists()).toBe(false)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('formats license start and end columns as local date times', async () => {
|
||||
routeState.meta.view = 'licenses'
|
||||
health.checkApiHealth.mockResolvedValue('online')
|
||||
business.me.mockResolvedValue({ data: { data: { email: 'admin@example.test' } } })
|
||||
business.listCustomers.mockResolvedValue({ data: { data: [], meta: { total: 0 } } })
|
||||
business.listProducts.mockResolvedValue({ data: { data: [] } })
|
||||
const row = { id: 1, starts_at: '2026-01-02T00:03:04Z', expires_at: '2027-01-02T00:03:04Z' }
|
||||
business.listLicenses.mockResolvedValue({ data: { data: [row], meta: { total: 1 } } })
|
||||
const DateColumn = defineComponent({ props: ['label'], setup: () => ({ row }), template: '<span v-if="label?.includes(\'本地时间\')"><slot :row="row" /></span>' })
|
||||
const wrapper = mount(Overview, { global: { stubs: { 'router-link': true, 'el-dialog': true, 'el-drawer': true, 'el-button': ButtonStub, 'el-input': true, 'el-form': true, 'el-table': TableStub, 'el-table-column': DateColumn, 'el-select': true, 'el-option': true, 'el-date-picker': true, 'el-pagination': true }, directives: { loading: () => {} } } })
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain(formatDateTime(row.starts_at))
|
||||
expect(wrapper.text()).toContain(formatDateTime(row.expires_at))
|
||||
expect(wrapper.text()).not.toContain(row.starts_at)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('loads real license list contract after session recovery', async () => {
|
||||
routeState.meta.view='licenses'
|
||||
health.checkApiHealth.mockResolvedValue('online')
|
||||
business.me.mockResolvedValue({ data: { data: { role: 'admin' } } })
|
||||
business.listCustomers.mockResolvedValue({ data: { data: [], meta: { total: 0 } } })
|
||||
business.listProducts.mockResolvedValue({ data: { data: [] } })
|
||||
business.listLicenses.mockResolvedValue({ data: { data: [], meta: { total: 1 } } })
|
||||
const wrapper = mount(Overview, { global: { stubs: { 'el-drawer': DrawerStub, 'el-button': ButtonStub, 'el-input': true, 'el-form': true, 'el-table': TableStub, 'el-table-column': ColumnStub, 'el-select': true, 'el-option': true, 'el-date-picker': true, 'el-pagination': true }, directives: { loading: () => {} } } })
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('期限授权')
|
||||
expect(wrapper.text()).toContain('共 1 条')
|
||||
expect(wrapper.text()).toContain('最后在线')
|
||||
expect(wrapper.text()).toContain('租约到期')
|
||||
expect(wrapper.text()).toContain('冻结状态')
|
||||
expect(wrapper.text()).toContain('已传播状态')
|
||||
expect(business.listLicenses).toHaveBeenCalledWith({ page: 1, q: '', status: '' })
|
||||
wrapper.unmount()
|
||||
})
|
||||
})
|
||||
@@ -1,37 +1,126 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
|
||||
type Connection = 'checking' | 'online' | 'offline'
|
||||
const connection = ref<Connection>('checking')
|
||||
|
||||
async function checkConnection() {
|
||||
connection.value = 'checking'
|
||||
try {
|
||||
const { data } = await axios.get<{ status: string }>('/api/v1/health/live', { timeout: 3000 })
|
||||
connection.value = data.status === 'ok' ? 'online' : 'offline'
|
||||
} catch {
|
||||
connection.value = 'offline'
|
||||
}
|
||||
import { formatDateTime } from '../date-format'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import DashboardPanel from './DashboardPanel.vue'
|
||||
import AuditPanel from './AuditPanel.vue'
|
||||
import SettingsPanel from './SettingsPanel.vue'
|
||||
import AdminsPanel from './AdminsPanel.vue'
|
||||
import IntegrationPanel from './IntegrationPanel.vue'
|
||||
import { getSettings, type SiteSettings } from '../admin-api'
|
||||
const siteSettings = ref<SiteSettings|null>(null)
|
||||
async function loadSiteSettings() { try { siteSettings.value = (await getSettings()).data.data } catch { siteSettings.value = null } }
|
||||
import { getLicense } from '../api'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { createCustomer, createProduct, deleteCustomer, deleteProduct, issueLicense, listCustomers, listLicenses, listProducts, login, logout, me, renewLicense, revokeLicense, type Customer, type License, type Product } from '../api'
|
||||
import { checkApiHealth, type Connection } from '../api-health'
|
||||
import OrdersPanel from './OrdersPanel.vue'
|
||||
import ReleasesPanel from './ReleasesPanel.vue'
|
||||
import { listLicenseInstances, setInstanceFrozen, type LicenseInstance } from '../api'
|
||||
const selectedLicenseID = ref<number | null>(null), changingInstance = ref('')
|
||||
const freezeRetries = new Map<string, { frozen: boolean; key: string }>()
|
||||
async function changeFreeze(instance: LicenseInstance) {
|
||||
if (changingInstance.value) return
|
||||
const frozen = instance.freeze_state !== 'frozen'
|
||||
try { await ElMessageBox.confirm(frozen ? '确认冻结该实例?离线旧租约不会立即失效。' : '确认恢复该实例?撤销的授权不会因此恢复。', frozen ? '冻结确认' : '恢复确认') } catch { return }
|
||||
const previous = freezeRetries.get(instance.instance_id)
|
||||
const retry = previous?.frozen === frozen ? previous : { frozen, key: crypto.randomUUID() }
|
||||
freezeRetries.set(instance.instance_id, retry)
|
||||
changingInstance.value = instance.instance_id
|
||||
try { await setInstanceFrozen(instance.instance_id, frozen, retry.key); freezeRetries.delete(instance.instance_id); if (selectedLicenseID.value !== null) await showInstances(selectedLicenseID.value) } catch (e) { instanceError.value = e instanceof Error ? e.message : '状态更新失败' } finally { changingInstance.value = '' }
|
||||
}
|
||||
const instanceDrawer = ref(false), instancesLoading = ref(false), instanceError = ref(''), instances = ref<LicenseInstance[]>([])
|
||||
async function showInstances(id:number) { selectedLicenseID.value = id; instanceDrawer.value = true; instancesLoading.value = true; instanceError.value = ''; instances.value = []; try { instances.value = (await listLicenseInstances(id)).data.data } catch (e) { instanceError.value = e instanceof Error ? e.message : '实例加载失败' } finally { instancesLoading.value = false } }
|
||||
|
||||
onMounted(checkConnection)
|
||||
const route = useRoute() || ({ meta: {}, query: {} } as ReturnType<typeof useRoute>)
|
||||
const router = useRouter() || ({ push: async () => undefined, replace: async () => undefined } as unknown as ReturnType<typeof useRouter>)
|
||||
const pageView = computed(() => route.meta.view as string || 'dashboard')
|
||||
const title=computed(()=>({dashboard:'仪表盘',licenses:'License 授权',customers:'客户管理',products:'产品目录',orders:'订单与套餐',releases:'版本管理',integration:'客户端接入',audit:'审计日志',settings:'系统设置',admins:'管理员账户'}[pageView.value] || '仪表盘'))
|
||||
const nav=[{view:'dashboard',path:'/',name:'仪表盘',icon:'▦'},{view:'licenses',path:'/licenses',name:'License 授权',icon:'◇'},{view:'customers',path:'/customers',name:'客户管理',icon:'♙'},{view:'products',path:'/products',name:'产品目录',icon:'◫'},{view:'orders',path:'/orders',name:'订单与套餐',icon:'▤'},{view:'releases',path:'/releases',name:'版本管理',icon:'↥'},{view:'integration',path:'/integration',name:'客户端接入',icon:'⌘'},{view:'audit',path:'/audit',name:'审计日志',icon:'≡'},{view:'settings',path:'/settings',name:'系统设置',icon:'⚙'},{view:'admins',path:'/admins',name:'管理员账户',icon:'♙'}]
|
||||
const adminEmail=ref('管理员'), detail=ref<License|null>(null),detailOpen=ref(false),detailLoading=ref(false),detailError=ref('')
|
||||
async function showDetail(id:number){detailOpen.value=true;detail.value=null;detailError.value='';detailLoading.value=true;try{detail.value=(await getLicense(id)).data.data}catch(e){detailError.value=e instanceof Error?e.message:'详情加载失败'}finally{detailLoading.value=false}}
|
||||
async function openIssue(){await router.push('/licenses');document.getElementById('license-issue')?.scrollIntoView({behavior:'smooth'})}
|
||||
watch(()=>route.query.status,(value)=>{licensePage.value=1;licenseStatus.value=String(value??'');if(loggedIn.value)refresh()})
|
||||
const loggedIn = ref(false), username = ref(''), password = ref(''), loading = ref(false), error = ref(''), connection = ref<Connection>('checking')
|
||||
const customers = ref<Customer[]>([]), products = ref<Product[]>([]), licenses = ref<License[]>([]), customerTotal = ref(0), licenseTotal = ref(0), query = ref(''), licenseQuery=ref(String(route.query.q??'')), licenseStatus=ref(String(route.query.status??'')), customerPage=ref(1)
|
||||
const issueForm = ref({ customer_id: null as number | null, product_id: null as number | null, starts_at: new Date().toISOString(), expires_at: new Date(Date.now() + 365 * 86400000).toISOString() })
|
||||
const issuing = ref(false), licensePage = ref(1)
|
||||
let pendingIssue: { body: string; key: string } | null = null
|
||||
const pendingLicenseOps = new Map<string, { body: string; key: string }>()
|
||||
const newCustomer = ref({ name: '', contact_email: '' }), newProduct = ref({ code: '', name: '', description: '' })
|
||||
async function refresh() { loading.value = true; error.value = ''; try { const [cs, ps, ls] = await Promise.all([listCustomers({ q: query.value, page:customerPage.value }), listProducts(), listLicenses({ page: licensePage.value, q:licenseQuery.value, status:String(route.query.status??licenseStatus.value) })]); customers.value = cs.data.data; customerTotal.value = cs.data.meta.total; products.value = ps.data.data; licenses.value = ls.data.data; licenseTotal.value = ls.data.meta.total } catch (e) { error.value = e instanceof Error ? e.message : '加载失败' } finally { loading.value = false } }
|
||||
async function checkConnection() { connection.value = 'checking'; connection.value = await checkApiHealth() }
|
||||
async function checkSession() { try { const session=await me(); adminEmail.value=session.data.data.username || session.data.data.email || '管理员'; loggedIn.value = true; await Promise.all([loadSiteSettings(), refresh()]) } catch { loggedIn.value = false } }
|
||||
async function signIn() { loading.value = true; error.value = ''; try { const session=await login(username.value, password.value); adminEmail.value=session.data.data.username; loggedIn.value = true; password.value = ''; await Promise.all([loadSiteSettings(), refresh()]) } catch (e) { error.value = e instanceof Error ? e.message : '登录失败' } finally { loading.value = false } }
|
||||
async function signOut() { await logout(); loggedIn.value = false; customers.value = []; products.value = [] }
|
||||
async function addCustomer() { try { await createCustomer(newCustomer.value); newCustomer.value = { name: '', contact_email: '' }; ElMessage.success('客户已创建'); await refresh() } catch (e) { ElMessage.error(e instanceof Error ? e.message : '创建失败') } }
|
||||
async function addProduct() { try { await createProduct(newProduct.value); newProduct.value = { code: '', name: '', description: '' }; ElMessage.success('产品已创建'); await refresh() } catch (e) { ElMessage.error(e instanceof Error ? e.message : '创建失败') } }
|
||||
async function issue() {
|
||||
if (issuing.value) return
|
||||
issuing.value = true
|
||||
try {
|
||||
if (!issueForm.value.customer_id || !issueForm.value.product_id) throw new Error('请选择客户和产品')
|
||||
const payload = { customer_id: issueForm.value.customer_id, product_id: issueForm.value.product_id, starts_at: new Date(issueForm.value.starts_at).toISOString(), expires_at: new Date(issueForm.value.expires_at).toISOString() }
|
||||
const body = JSON.stringify(payload)
|
||||
if (!pendingIssue || pendingIssue.body !== body) pendingIssue = { body, key: crypto.randomUUID() }
|
||||
await issueLicense(payload, pendingIssue.key)
|
||||
pendingIssue = null
|
||||
licensePage.value = 1
|
||||
ElMessage.success('授权已签发')
|
||||
await refresh()
|
||||
} catch (e) { ElMessage.error(e instanceof Error ? e.message : '签发失败') }
|
||||
finally { issuing.value = false }
|
||||
}
|
||||
async function removeCustomer(id:number) { await ElMessageBox.confirm('确认删除该客户?','删除确认'); await deleteCustomer(id); await refresh() }
|
||||
async function removeProduct(id:number) { await ElMessageBox.confirm('确认删除该产品?','删除确认'); await deleteProduct(id); await refresh() }
|
||||
async function revoke(id:number) {
|
||||
await ElMessageBox.confirm('撤销后仅保留后台记录,确认继续?','撤销确认')
|
||||
const operation = `revoke:${id}`, body = '{}', previous = pendingLicenseOps.get(operation)
|
||||
const retry = previous && previous.body === body ? previous : { body, key: crypto.randomUUID() }
|
||||
pendingLicenseOps.set(operation, retry)
|
||||
try { await revokeLicense(id, retry.key); pendingLicenseOps.delete(operation); ElMessage.success('授权已撤销'); await refresh() } catch (e) { ElMessage.error(e instanceof Error ? e.message : '撤销失败') }
|
||||
}
|
||||
const renewalLicense = ref<License|null>(null), renewalOpen = ref(false), renewing = ref(false)
|
||||
const renewalDate = ref<Date|null>(null), renewalError = ref('')
|
||||
function renew(license:License) {
|
||||
renewalLicense.value = license
|
||||
const initial = new Date(Math.max(Date.now(), new Date(license.expires_at).getTime()))
|
||||
initial.setFullYear(initial.getFullYear() + 1)
|
||||
renewalDate.value = initial
|
||||
renewalError.value = ''
|
||||
renewalOpen.value = true
|
||||
}
|
||||
function disabledRenewalDate(date:Date) {
|
||||
if (!renewalLicense.value) return false
|
||||
const earliest = new Date(renewalLicense.value.expires_at)
|
||||
earliest.setHours(0, 0, 0, 0)
|
||||
return date.getTime() < earliest.getTime()
|
||||
}
|
||||
async function submitRenewal() {
|
||||
if (renewing.value || !renewalLicense.value) return
|
||||
renewalError.value = ''
|
||||
const selected = renewalDate.value ? new Date(renewalDate.value) : null
|
||||
if (!selected || !Number.isFinite(selected.getTime())) { renewalError.value = '请选择新的到期时间'; return }
|
||||
if (selected.getTime() <= new Date(renewalLicense.value.expires_at).getTime()) { renewalError.value = '新的到期时间必须晚于当前到期时间'; return }
|
||||
const id = renewalLicense.value.id, expiresAt = selected.toISOString()
|
||||
const operation = `renew:${id}`, body = JSON.stringify({ expires_at: expiresAt }), previous = pendingLicenseOps.get(operation)
|
||||
const retry = previous && previous.body === body ? previous : { body, key: crypto.randomUUID() }
|
||||
pendingLicenseOps.set(operation, retry)
|
||||
renewing.value = true
|
||||
try { await renewLicense(id,expiresAt,retry.key); pendingLicenseOps.delete(operation); renewalOpen.value = false; ElMessage.success('授权已续期'); await refresh() } catch (e) { renewalError.value = e instanceof Error ? e.message : '续期失败' } finally { renewing.value = false }
|
||||
}
|
||||
onMounted(() => { checkConnection(); checkSession() })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="workspace">
|
||||
<header class="topbar"><span class="wordmark"><span class="mark">L</span>License Hub</span><span class="environment">开发环境</span></header>
|
||||
<main class="content">
|
||||
<div class="heading"><div><p class="eyebrow">工程状态</p><h1>授权管理平台</h1><p class="subheading">Web 服务器端软件授权 · 首阶段实施</p></div><el-button @click="checkConnection">重新检测</el-button></div>
|
||||
<section class="status-section" aria-labelledby="api-title">
|
||||
<div><h2 id="api-title">API 连通性</h2><p>检测 Gin 服务的存活端点,不代表数据库或授权业务已就绪。</p></div>
|
||||
<span class="status" :class="connection" role="status">{{ connection === 'checking' ? '检测中' : connection === 'online' ? '服务在线' : '服务未连接' }}</span>
|
||||
</section>
|
||||
<section class="scope" aria-labelledby="scope-title">
|
||||
<h2 id="scope-title">实施范围</h2>
|
||||
<dl><div><dt>首发对象</dt><dd>Web 服务器端软件</dd></div><div><dt>订单与存储</dt><dd>线下订单 · 本地文件</dd></div><div><dt>离线期限</dt><dd>最长连续 14 天</dd></div><div><dt>待确定</dt><dd>实例身份规则、部署拓扑与接入负责人</dd></div></dl>
|
||||
</section>
|
||||
<p class="footnote">当前仅完成工程骨架与存活检查。授权签发、登录和订单接口尚未实现。</p>
|
||||
<div class="workspace" :class="{'admin-workspace':loggedIn}"><aside v-if="loggedIn" class="sidebar"><div class="brand"><span class="brand-mark">L</span><div>{{siteSettings?.site_name || 'License Hub'}}<small>统一授权管理平台</small></div></div><nav class="nav" aria-label="管理台导航"><template v-for="(item,index) in nav" :key="item.path"><div v-if="index===0||index===1||index===6" class="nav-label">{{index===0?'工作台':index===1?'业务管理':'系统'}}</div><router-link :to="item.path" :class="{active:pageView===item.view}" :title="item.name"><span class="ico">{{item.icon}}</span><span>{{item.name}}</span></router-link></template></nav><div class="sidebar-footer"><span class="user-dot">{{adminEmail.slice(0,1).toUpperCase()}}</span><span>{{adminEmail}}</span></div></aside><div class="main"><header class="topbar"><span v-if="loggedIn" class="crumb">{{pageView==='dashboard'?'工作台':'管理台'}} <strong>/ {{title}}</strong></span><span v-else class="wordmark"><span class="mark">L</span>License Hub</span><span class="environment">内部管理台 <el-button v-if="loggedIn" link @click="signOut">退出</el-button></span></header>
|
||||
<main class="content" v-if="!loggedIn"><section class="status-section" aria-labelledby="api-title"><div><h2 id="api-title">API 连通性</h2><p>服务状态仅表示存活端点可访问。</p></div><div><span class="status" :class="connection" role="status">{{ connection === 'checking' ? '检测中' : connection === 'online' ? '服务在线' : '服务未连接' }}</span><el-button link @click="checkConnection">重新检测</el-button></div></section><section class="login-panel"><p class="eyebrow">内部管理员</p><h1>登录管理台</h1><p class="subheading">使用管理员用户名和密码登录。</p><el-form @submit.prevent="signIn"><el-input v-model="username" aria-label="用户名" placeholder="用户名" autocomplete="username"/><el-input v-model="password" type="password" show-password placeholder="密码" autocomplete="current-password" @keyup.enter="signIn"/><el-button type="primary" :loading="loading" @click="signIn">登录</el-button></el-form><p v-if="error" class="error">{{ error }}</p></section></main>
|
||||
<main class="content" v-else><p v-if="siteSettings?.announcement" class="site-announcement" role="note">{{siteSettings.announcement}}</p><p v-if="siteSettings?.support_email" class="subheading">支持联系:<a :href="`mailto:${siteSettings.support_email}`">{{siteSettings.support_email}}</a></p><DashboardPanel v-if="pageView==='dashboard'" @issue="openIssue" @detail="showDetail"/><div v-else class="heading"><div><p class="eyebrow">内部管理台</p><h1>{{title}}</h1><p class="subheading">{{pageView==='admins'?'管理后台账户、启停状态和密码':pageView==='audit'?'查看管理员操作记录':pageView==='settings'?'管理站点展示信息及管理员密码':'客户、订单、授权及实例状态'}}</p></div><el-button v-if="pageView!=='admins'&&pageView!=='audit'&&pageView!=='settings'" :loading="loading" @click="refresh">刷新</el-button></div><p v-if="error&&pageView!=='admins'&&pageView!=='audit'&&pageView!=='settings'" class="error">{{ error }}</p>
|
||||
<section v-if="pageView==='customers'" class="data-section"><div class="section-heading"><div><h2>客户档案</h2><p>共 {{ customerTotal }} 条</p></div><div class="inline-form"><el-input v-model="newCustomer.name" placeholder="客户名称"/><el-input v-model="newCustomer.contact_email" placeholder="联系邮箱"/><el-button type="primary" @click="addCustomer">新增客户</el-button></div></div><el-input v-model="query" placeholder="搜索客户" clearable @change="refresh"/><div class="business-table"><el-table :data="customers" v-loading="loading" empty-text="暂无客户"><el-table-column prop="name" label="名称"/><el-table-column prop="contact_email" label="邮箱"/><el-table-column prop="status" label="状态"/><el-table-column label="操作" width="90"><template #default="scope"><el-button link type="danger" @click="removeCustomer(scope.row.id)">删除</el-button></template></el-table-column></el-table></div></section>
|
||||
<section v-if="pageView==='products'" class="data-section"><div class="section-heading"><div><h2>产品目录</h2><p>可用于后续授权规则接入</p></div><div class="inline-form"><el-input v-model="newProduct.code" placeholder="产品编码"/><el-input v-model="newProduct.name" placeholder="产品名称"/><el-button type="primary" @click="addProduct">新增产品</el-button></div></div><div class="business-table"><el-table :data="products" v-loading="loading" empty-text="暂无产品"><el-table-column prop="code" label="编码" width="150"/><el-table-column prop="name" label="名称"/><el-table-column prop="description" label="说明"/><el-table-column label="操作" width="90"><template #default="scope"><el-button link type="danger" @click="removeProduct(scope.row.id)">删除</el-button></template></el-table-column></el-table></div></section>
|
||||
<section v-if="pageView==='licenses'" id="license-issue" class="data-section"><form class="filters" @submit.prevent="licensePage=1;router.replace({query:{...(route.query),q:licenseQuery||undefined}});refresh()"><input v-model="licenseQuery" placeholder="搜索客户或 License"/><select v-model="licenseStatus" @change="router.replace({query:{...(route.query),status:licenseStatus||undefined}})"><option value="">全部状态</option><option value="active">有效</option><option value="expiring">即将到期</option><option value="pending">未开始</option><option value="expired">已到期</option><option value="revoked">已撤销</option></select><button class="search-button">搜索</button></form><div class="section-heading"><div><h2>期限授权</h2><p>共 {{ licenseTotal }} 条,仅用于后台记录和后续协议接入</p></div><div class="inline-form license-form"><el-select v-model="issueForm.customer_id" placeholder="选择客户"><el-option v-for="item in customers" :key="item.id" :label="item.name" :value="item.id" :disabled="item.status !== 'active'"/></el-select><el-select v-model="issueForm.product_id" placeholder="选择产品"><el-option v-for="item in products" :key="item.id" :label="item.name" :value="item.id" :disabled="!item.active"/></el-select><el-date-picker v-model="issueForm.starts_at" type="datetime" value-format="YYYY-MM-DDTHH:mm:ssZ" placeholder="开始时间" aria-label="开始时间"/><el-date-picker v-model="issueForm.expires_at" type="datetime" value-format="YYYY-MM-DDTHH:mm:ssZ" placeholder="结束时间" aria-label="结束时间"/><el-button type="primary" :loading="issuing" @click="issue">签发授权</el-button></div></div><div class="business-table"><el-table :data="licenses" v-loading="loading" empty-text="暂无授权"><el-table-column prop="license_key" label="授权密钥" min-width="230"/><el-table-column prop="customer_name" label="客户"/><el-table-column prop="product_name" label="产品"/><el-table-column prop="status" label="状态"/><el-table-column label="开始(本地时间)" min-width="190"><template #default="scope">{{ formatDateTime(scope.row.starts_at) }}</template></el-table-column><el-table-column label="结束(本地时间)" min-width="190"><template #default="scope">{{ formatDateTime(scope.row.expires_at) }}</template></el-table-column><el-table-column label="操作" width="250"><template #default="scope"><el-button link @click="showDetail(scope.row.id)">详情</el-button><el-button link @click="showInstances(scope.row.id)">实例</el-button><el-button link @click="renew(scope.row)" :disabled="scope.row.status === 'revoked'">续期</el-button><el-button link type="danger" @click="revoke(scope.row.id)" :disabled="scope.row.status === 'revoked'">撤销</el-button></template></el-table-column></el-table><el-pagination v-model:current-page="licensePage" :total="licenseTotal" :page-size="20" layout="prev, pager, next" @current-change="refresh"/></div></section>
|
||||
<ReleasesPanel v-if="pageView==='releases'" :products="products"/>
|
||||
<OrdersPanel v-if="pageView==='orders'" :customers="customers" :products="products" @issued="refresh"/>
|
||||
<AdminsPanel v-if="pageView==='admins'" :current-username="adminEmail"/><IntegrationPanel v-if="pageView==='integration'"/><AuditPanel v-if="pageView==='audit'"/><SettingsPanel v-if="pageView==='settings'" @saved="siteSettings=$event"/><el-dialog v-model="renewalOpen" title="续期授权" width="min(480px, 95vw)" :close-on-click-modal="!renewing" :close-on-press-escape="!renewing" :show-close="!renewing"><template v-if="renewalLicense"><p>当前到期时间:{{ formatDateTime(renewalLicense.expires_at) }}</p><label for="renewal-date">新的到期时间(本地时间)</label><el-date-picker id="renewal-date" v-model="renewalDate" type="datetime" format="YYYY-MM-DD HH:mm:ss" placeholder="选择新的到期日期与时间" aria-label="新的到期时间" :disabled-date="disabledRenewalDate" :disabled="renewing" style="width:100%;margin-top:8px"/><p class="subheading">请选择晚于当前到期时间的日期和时间。</p><p v-if="renewalError" class="error" role="alert">{{ renewalError }}</p></template><template #footer><el-button :disabled="renewing" @click="renewalOpen=false">取消</el-button><el-button type="primary" :loading="renewing" @click="submitRenewal">确认续期</el-button></template></el-dialog><el-dialog v-model="detailOpen" title="授权详情" width="min(520px, 95vw)"><div v-loading="detailLoading"><p v-if="detailError" class="error" role="alert">{{detailError}}</p><dl v-if="detail" class="license-detail"><dt>License 密钥</dt><dd class="license-code">{{detail.license_key}}</dd><dt>客户</dt><dd>{{detail.customer_name}}</dd><dt>产品</dt><dd>{{detail.product_name}}</dd><dt>类型</dt><dd>期限授权</dd><dt>开始时间</dt><dd>{{formatDateTime(detail.starts_at)}}</dd><dt>到期时间</dt><dd>{{formatDateTime(detail.expires_at)}}</dd><dt>状态</dt><dd>{{detail.status}}</dd></dl><el-button v-if="detail" @click="showInstances(detail.id)">查看实例 / 冻结管理</el-button></div></el-dialog><el-drawer v-model="instanceDrawer" title="授权实例" size="min(100%, 680px)"><el-button :loading="instancesLoading" @click="selectedLicenseID !== null && showInstances(selectedLicenseID)">刷新状态</el-button><p v-if="instanceError" class="error">{{ instanceError }}</p><div class="business-table"><el-table :data="instances" v-loading="instancesLoading" empty-text="未绑定实例"><el-table-column prop="instance_id" label="实例 ID" min-width="290"/><el-table-column prop="status" label="激活状态"/><el-table-column prop="certificate_version" label="证书版本"/><el-table-column label="激活时间" min-width="200"><template #default="scope">{{ formatDateTime(scope.row.activated_at) }}</template></el-table-column><el-table-column label="最后在线" min-width="200"><template #default="scope">{{ formatDateTime(scope.row.last_seen_at) }}</template></el-table-column><el-table-column label="租约到期" min-width="200"><template #default="scope">{{ formatDateTime(scope.row.lease_expires_at) }}</template></el-table-column><el-table-column prop="freeze_state" label="冻结状态"/><el-table-column prop="entitlement_state" label="授权状态"/><el-table-column prop="observed_state" label="已传播状态"/><el-table-column label="管理" fixed="right" width="90"><template #default="scope"><el-button link :type="scope.row.freeze_state === 'frozen' ? 'primary' : 'danger'" :loading="changingInstance === scope.row.instance_id" :disabled="!!changingInstance" @click="changeFreeze(scope.row)">{{ scope.row.freeze_state === 'frozen' ? '恢复' : '冻结' }}</el-button></template></el-table-column></el-table></div></el-drawer>
|
||||
</main>
|
||||
</div>
|
||||
</div></div>
|
||||
</template>
|
||||
|
||||
13
frontend/src/views/ReleasesPanel.test.ts
Normal file
13
frontend/src/views/ReleasesPanel.test.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import ReleasesPanel from './ReleasesPanel.vue'
|
||||
|
||||
describe('ReleasesPanel', () => {
|
||||
it('shows validation error without sending an invalid publication', async () => {
|
||||
const wrapper = mount(ReleasesPanel, { props: { products: [] }, global: { stubs: { ElButton: { template: '<button @click="$emit(\'click\')"><slot /></button>' }, ElSelect: true, ElOption: true, ElInput: true, ElTable: true, ElTableColumn: true, ElPagination: true }, directives: { loading: () => {} } } })
|
||||
expect(wrapper.find('[role="alert"]').exists()).toBe(false)
|
||||
await wrapper.findAll('button')[1]!.trigger('click')
|
||||
expect(wrapper.find('[role="alert"]').text()).toContain('请选择产品')
|
||||
expect(wrapper.find('input[type="file"]').attributes('aria-label')).toBe('版本文件')
|
||||
})
|
||||
})
|
||||
43
frontend/src/views/ReleasesPanel.vue
Normal file
43
frontend/src/views/ReleasesPanel.vue
Normal file
@@ -0,0 +1,43 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import type { Product } from '../api'
|
||||
const props = defineProps<{ products: Product[] }>()
|
||||
const productID = ref<number | null>(null), version = ref(''), loading = ref(false), uploading = ref(false), error = ref(''), file = ref<File | null>(null), page = ref(1), total = ref(0)
|
||||
const releases = ref<{ id: number; version: string; sha256: string; size_bytes: number; published: boolean }[]>([])
|
||||
let loadSequence = 0
|
||||
async function responseJSON(response: Response) { const body = await response.json(); if (!response.ok) throw new Error(body.error?.message || '请求失败'); return body }
|
||||
async function load() {
|
||||
const sequence = ++loadSequence
|
||||
if (!productID.value) { releases.value = []; total.value = 0; return }
|
||||
loading.value = true; error.value = ''
|
||||
try { const body = await responseJSON(await fetch(`/api/v1/products/${productID.value}/releases?page=${page.value}`, { credentials: 'include' })); if (sequence === loadSequence) { releases.value = body.data; total.value = body.meta.total } }
|
||||
catch (e) { if (sequence === loadSequence) error.value = e instanceof Error ? e.message : '加载失败' }
|
||||
finally { if (sequence === loadSequence) loading.value = false }
|
||||
}
|
||||
watch(productID, () => { page.value = 1; releases.value = []; load() })
|
||||
function choose(event: Event) { file.value = (event.target as HTMLInputElement).files?.[0] || null }
|
||||
async function upload() {
|
||||
if (uploading.value) return
|
||||
error.value = ''
|
||||
if (!productID.value || !file.value || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(version.value)) { error.value = '请选择产品、文件并填写有效版本'; return }
|
||||
if (file.value.size === 0 || file.value.size > 64 * 1024 * 1024) { error.value = '文件必须为1字节至64 MiB'; return }
|
||||
uploading.value = true
|
||||
try { await responseJSON(await fetch(`/api/v1/products/${productID.value}/releases?version=${encodeURIComponent(version.value)}`, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/octet-stream' }, body: file.value })); version.value = ''; page.value = 1; await load() }
|
||||
catch (e) { error.value = e instanceof Error ? e.message : '上传失败' }
|
||||
finally { uploading.value = false }
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<section class="data-section" aria-labelledby="release-title">
|
||||
<div class="section-heading"><h2 id="release-title">产品版本</h2><el-button :loading="loading" :disabled="!productID || uploading" @click="load">刷新</el-button></div>
|
||||
<div class="inline-form">
|
||||
<el-select v-model="productID" placeholder="选择产品" :disabled="uploading"><el-option v-for="product in props.products" :key="product.id" :value="product.id" :label="product.name" :disabled="!product.active" /></el-select>
|
||||
<el-input v-model="version" placeholder="版本号" :disabled="uploading" />
|
||||
<input type="file" aria-label="版本文件" :disabled="uploading" @change="choose" />
|
||||
<el-button type="primary" :loading="uploading" @click="upload">发布版本</el-button>
|
||||
</div>
|
||||
<p v-if="error" role="alert" class="error">{{ error }}</p>
|
||||
<el-table :data="releases" v-loading="loading" empty-text="暂无版本"><el-table-column prop="version" label="版本" /><el-table-column prop="size_bytes" label="字节数" /><el-table-column prop="sha256" label="SHA-256" min-width="290" /><el-table-column prop="published" label="已发布" /></el-table>
|
||||
<el-pagination v-model:current-page="page" :total="total" :page-size="20" layout="prev, pager, next" @current-change="load" />
|
||||
</section>
|
||||
</template>
|
||||
53
frontend/src/views/SettingsPanel.test.ts
Normal file
53
frontend/src/views/SettingsPanel.test.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import ElementPlus, { ElMessageBox } from 'element-plus'
|
||||
const calls = vi.hoisted(() => ({getSettings:vi.fn(),saveSettings:vi.fn(),changePassword:vi.fn()}))
|
||||
vi.mock('../admin-api', async importOriginal => ({...await importOriginal<typeof import('../admin-api')>(),...calls}))
|
||||
import SettingsPanel from './SettingsPanel.vue'
|
||||
const settings = {site_name:'Persisted Site',support_email:'help@example.test',announcement:'真实公告',updated_at:null}
|
||||
const options = {global:{plugins:[ElementPlus]}}
|
||||
beforeEach(() => {vi.restoreAllMocks();vi.resetAllMocks();calls.getSettings.mockResolvedValue({data:{data:settings}})})
|
||||
async function passwords(wrapper:ReturnType<typeof mount>, next='a', confirm=next) {
|
||||
await wrapper.get('[aria-label="当前密码"]').setValue('old')
|
||||
await wrapper.get('[aria-label="新密码"]').setValue(next)
|
||||
await wrapper.get('[aria-label="确认新密码"]').setValue(confirm)
|
||||
}
|
||||
describe('SettingsPanel', () => {
|
||||
it('loads persisted settings, saves only editable fields and emits updated display data', async () => {
|
||||
const wrapper = mount(SettingsPanel,options); await flushPromises()
|
||||
expect((wrapper.get('[aria-label="站点名称"]').element as HTMLInputElement).value).toBe('Persisted Site')
|
||||
await wrapper.get('[aria-label="站点名称"]').setValue('Changed')
|
||||
calls.saveSettings.mockResolvedValue({data:{data:{...settings,site_name:'Changed',updated_at:'2026-10-09T00:00:00Z'}}})
|
||||
await wrapper.findAll('form')[0]!.trigger('submit'); await flushPromises()
|
||||
expect(calls.saveSettings).toHaveBeenCalledWith({site_name:'Changed',support_email:'help@example.test',announcement:'真实公告'})
|
||||
expect(wrapper.text()).toContain('设置已保存'); expect(wrapper.emitted('saved')?.[0]?.[0]).toMatchObject({site_name:'Changed'})
|
||||
calls.saveSettings.mockRejectedValueOnce(new Error('保存接口失败'))
|
||||
await wrapper.findAll('form')[0]!.trigger('submit'); await flushPromises()
|
||||
expect(wrapper.text()).toContain('保存接口失败'); expect(wrapper.text()).not.toContain('设置已保存'); wrapper.unmount()
|
||||
})
|
||||
it('blocks invalid settings and supports recovering from load failure', async () => {
|
||||
calls.getSettings.mockRejectedValueOnce(new Error('加载失败'))
|
||||
const wrapper = mount(SettingsPanel,options); await flushPromises()
|
||||
expect(wrapper.text()).toContain('加载失败'); expect(wrapper.find('[aria-label="站点名称"]').exists()).toBe(false)
|
||||
await wrapper.findAll('button').find(b=>b.text()==='重新加载设置')!.trigger('click'); await flushPromises()
|
||||
await wrapper.get('[aria-label="站点名称"]').setValue('')
|
||||
await wrapper.findAll('form')[0]!.trigger('submit'); await flushPromises()
|
||||
expect(calls.saveSettings).not.toHaveBeenCalled(); expect(wrapper.text()).toContain('站点名称须为'); wrapper.unmount()
|
||||
})
|
||||
it('requires matching passwords and confirmation, handles errors and clears secrets on success', async () => {
|
||||
const confirm = vi.spyOn(ElMessageBox,'confirm').mockRejectedValueOnce('cancel')
|
||||
const wrapper = mount(SettingsPanel,options); await flushPromises()
|
||||
await passwords(wrapper,'a','b'); await wrapper.findAll('form')[1]!.trigger('submit'); await flushPromises()
|
||||
expect(wrapper.text()).toContain('不一致'); expect(confirm).not.toHaveBeenCalled()
|
||||
await passwords(wrapper); await wrapper.findAll('form')[1]!.trigger('submit'); await flushPromises()
|
||||
expect(calls.changePassword).not.toHaveBeenCalled()
|
||||
confirm.mockResolvedValue('confirm' as Awaited<ReturnType<typeof ElMessageBox.confirm>>); calls.changePassword.mockRejectedValueOnce(new Error('当前密码错误')).mockResolvedValueOnce({status:204})
|
||||
await wrapper.findAll('form')[1]!.trigger('submit'); await flushPromises()
|
||||
expect(wrapper.text()).toContain('当前密码错误')
|
||||
await wrapper.findAll('form')[1]!.trigger('submit'); await flushPromises()
|
||||
expect(calls.changePassword).toHaveBeenLastCalledWith({current_password:'old',new_password:'a'})
|
||||
expect(wrapper.text()).toContain('当前会话保留')
|
||||
for (const label of ['当前密码','新密码','确认新密码']) expect((wrapper.get(`[aria-label="${label}"]`).element as HTMLInputElement).value).toBe('')
|
||||
wrapper.unmount()
|
||||
})
|
||||
})
|
||||
64
frontend/src/views/SettingsPanel.vue
Normal file
64
frontend/src/views/SettingsPanel.vue
Normal file
@@ -0,0 +1,64 @@
|
||||
<script setup lang="ts">
|
||||
import { formatDateTime } from '../date-format'
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import { changePassword, getSettings, saveSettings, validatePassword, validateSettings, type SettingsInput, type SiteSettings } from '../admin-api'
|
||||
const emit = defineEmits<{saved:[settings:SiteSettings]}>()
|
||||
const form = ref<SettingsInput>({site_name:'',support_email:'',announcement:''})
|
||||
const loaded = ref(false), loading = ref(false), saving = ref(false), changing = ref(false)
|
||||
const loadError = ref(''), saveError = ref(''), saveNotice = ref(''), passwordError = ref(''), passwordNotice = ref(''), updatedAt = ref<string|null>(null)
|
||||
const password = ref({current:'',next:'',confirmation:''})
|
||||
async function refresh() {
|
||||
if (loading.value || saving.value) return
|
||||
loading.value = true; loaded.value = false; loadError.value = ''; saveError.value = ''; saveNotice.value = ''
|
||||
try { const {data} = await getSettings(); form.value = {site_name:data.data.site_name,support_email:data.data.support_email,announcement:data.data.announcement}; updatedAt.value = data.data.updated_at; loaded.value = true }
|
||||
catch(e) { loadError.value = e instanceof Error ? e.message : '设置加载失败' }
|
||||
finally { loading.value = false }
|
||||
}
|
||||
async function save() {
|
||||
if (!loaded.value || saving.value) return
|
||||
saveNotice.value = ''; saveError.value = validateSettings(form.value)
|
||||
if (saveError.value) return
|
||||
const body = {...form.value}; saving.value = true
|
||||
try { const {data} = await saveSettings(body); form.value = {site_name:data.data.site_name,support_email:data.data.support_email,announcement:data.data.announcement}; updatedAt.value = data.data.updated_at; saveNotice.value = '设置已保存'; emit('saved',data.data) }
|
||||
catch(e) { saveError.value = e instanceof Error ? e.message : '保存失败' }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
async function updatePassword() {
|
||||
if (changing.value) return
|
||||
passwordNotice.value = ''; passwordError.value = validatePassword(password.value.current,password.value.next,password.value.confirmation)
|
||||
if (passwordError.value) return
|
||||
changing.value = true
|
||||
const body = {current_password:password.value.current,new_password:password.value.next}
|
||||
try {
|
||||
try { await ElMessageBox.confirm('确认修改密码?成功后其他会话将被撤销,当前会话会保留。','修改密码确认',{confirmButtonText:'确认修改',cancelButtonText:'取消',type:'warning'}) } catch { return }
|
||||
await changePassword(body); password.value = {current:'',next:'',confirmation:''}; passwordNotice.value = '密码已修改,其他会话已撤销,当前会话保留'
|
||||
} catch(e) { passwordError.value = e instanceof Error ? e.message : '密码修改失败' }
|
||||
finally { changing.value = false }
|
||||
}
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
<template>
|
||||
<section class="data-section">
|
||||
<div class="section-heading"><div><h2>站点展示信息</h2><p>管理站点名称、支持联系邮箱及公告展示内容</p></div><el-button :loading="loading" :disabled="saving" @click="refresh">重新加载设置</el-button></div>
|
||||
<p v-if="loading" role="status" class="muted">正在加载设置…</p><p v-if="loadError" class="error" role="alert">{{ loadError }}</p>
|
||||
<el-form v-if="loaded" label-position="top" :disabled="saving" @submit.prevent="save">
|
||||
<el-form-item label="站点名称(1–100 个字符)"><el-input v-model="form.site_name" aria-label="站点名称"/></el-form-item>
|
||||
<el-form-item label="支持联系邮箱(可留空,最多 254 个字符)"><el-input v-model="form.support_email" aria-label="支持联系邮箱" type="email"/></el-form-item>
|
||||
<el-form-item label="公告(最多 2000 个字符)"><el-input v-model="form.announcement" aria-label="公告" type="textarea" :rows="5"/></el-form-item>
|
||||
<p class="subheading">最后更新:{{ formatDateTime(updatedAt, '尚未更新') }}</p>
|
||||
<p v-if="saveError" class="error" role="alert">{{ saveError }}</p><p v-if="saveNotice" role="status">{{ saveNotice }}</p>
|
||||
<el-button type="primary" native-type="submit" :loading="saving">保存设置</el-button>
|
||||
</el-form>
|
||||
</section>
|
||||
<section class="data-section">
|
||||
<div class="section-heading"><div><h2>修改管理员密码</h2><p>新密码不能为空,最多 72 个 UTF-8 字节;修改后撤销其他会话,当前会话保留。</p></div></div>
|
||||
<el-form label-position="top" :disabled="changing" @submit.prevent="updatePassword">
|
||||
<el-form-item label="当前密码"><el-input v-model="password.current" aria-label="当前密码" type="password" autocomplete="current-password" show-password/></el-form-item>
|
||||
<el-form-item label="新密码"><el-input v-model="password.next" aria-label="新密码" type="password" autocomplete="new-password" show-password/></el-form-item>
|
||||
<el-form-item label="确认新密码"><el-input v-model="password.confirmation" aria-label="确认新密码" type="password" autocomplete="new-password" show-password/></el-form-item>
|
||||
<p v-if="passwordError" class="error" role="alert">{{ passwordError }}</p><p v-if="passwordNotice" role="status">{{ passwordNotice }}</p>
|
||||
<el-button type="primary" native-type="submit" :loading="changing">修改密码</el-button>
|
||||
</el-form>
|
||||
</section>
|
||||
</template>
|
||||
Reference in New Issue
Block a user