feat: add signed client upgrade policies
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
@@ -1,3 +1,25 @@
|
||||
// Element Plus datetime pickers use local Date fields. Map those fields to UTC explicitly.
|
||||
export function utcPickerToISO(value: Date | null): string {
|
||||
if (!value || !Number.isFinite(value.getTime())) return ''
|
||||
const utc = new Date(0)
|
||||
utc.setUTCFullYear(value.getFullYear(), value.getMonth(), value.getDate())
|
||||
utc.setUTCHours(value.getHours(), value.getMinutes(), value.getSeconds(), 0)
|
||||
return utc.toISOString()
|
||||
}
|
||||
export function isoToUTCPicker(value: string): Date | null {
|
||||
if (!value) return null
|
||||
const utc = new Date(value)
|
||||
if (!Number.isFinite(utc.getTime())) return null
|
||||
const local = new Date(0)
|
||||
local.setFullYear(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate())
|
||||
local.setHours(utc.getUTCHours(), utc.getUTCMinutes(), utc.getUTCSeconds(), 0)
|
||||
return local
|
||||
}
|
||||
export function formatUTCDateTime(value: string): string {
|
||||
const date = new Date(value)
|
||||
return value && Number.isFinite(date.getTime()) ? `${date.toISOString().replace('T', ' ').replace(/\.\d{3}Z$/, '')} UTC` : '—'
|
||||
}
|
||||
|
||||
const formatter = new Intl.DateTimeFormat('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
|
||||
39
frontend/src/releases-api.test.ts
Normal file
39
frontend/src/releases-api.test.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { compareStableVersions, isStableSemVer, validateUpdatePolicy, type Release, type UpdatePolicy } from './releases-api'
|
||||
import { formatUTCDateTime, isoToUTCPicker, utcPickerToISO } from './date-format'
|
||||
const target:Release = {id:9, product_id:7, version:'2.10.0', published:true, sha256:'hash', size_bytes:1, product_name:'甲', product_code:'a'}
|
||||
const policy:UpdatePolicy = {platform:'windows', arch:'x64', channel:'stable', enabled:false, release_id:9, minimum_supported_version:'', enforce_after:'', message:''}
|
||||
describe('update policy validation', () => {
|
||||
it('accepts stable SemVer only and compares numerically without precision loss', () => {
|
||||
for (const value of ['01.2.3','1.02.3','1.2.03','1.2','v1.2.3','1.2.3-beta','1.2.3+build']) expect(isStableSemVer(value)).toBe(false)
|
||||
expect(isStableSemVer('0.0.0')).toBe(true)
|
||||
expect(compareStableVersions('2.9.0','2.10.0')).toBe(-1)
|
||||
expect(compareStableVersions('99999999999999999999.0.0','99999999999999999998.0.0')).toBe(1)
|
||||
})
|
||||
it('requires a published target of the same product', () => {
|
||||
expect(validateUpdatePolicy(policy,target,7)).toBe('')
|
||||
expect(validateUpdatePolicy(policy,undefined,7)).toContain('已发布')
|
||||
expect(validateUpdatePolicy(policy,{...target,published:false},7)).toContain('已发布')
|
||||
expect(validateUpdatePolicy(policy,target,8)).toContain('当前产品')
|
||||
})
|
||||
it('enforces minimum version, dependent date and message limits', () => {
|
||||
expect(validateUpdatePolicy({...policy,minimum_supported_version:'2.11.0'},target,7)).toContain('不能高于')
|
||||
expect(validateUpdatePolicy({...policy,minimum_supported_version:'1.0.0'},target,7)).toContain('UTC')
|
||||
expect(validateUpdatePolicy({...policy,minimum_supported_version:'1.0.0',enforce_after:'invalid'},target,7)).toContain('UTC')
|
||||
expect(validateUpdatePolicy({...policy,enforce_after:'2026-10-12T15:00:00Z'},target,7)).toContain('清空')
|
||||
expect(validateUpdatePolicy({...policy,minimum_supported_version:'2.10.0',enforce_after:'2026-10-12T15:00:00Z'},target,7)).toBe('')
|
||||
expect(validateUpdatePolicy({...policy,message:'😀'.repeat(2000)},target,7)).toBe('')
|
||||
expect(validateUpdatePolicy({...policy,message:'😀'.repeat(2001)},target,7)).toContain('2000')
|
||||
})
|
||||
it('maps UTC picker fields without applying the browser timezone twice', () => {
|
||||
const picker = new Date(2026,9,12,22,49,5)
|
||||
expect(utcPickerToISO(picker)).toBe('2026-10-12T22:49:05.000Z')
|
||||
const restored = isoToUTCPicker('2026-10-12T22:49:05Z')!
|
||||
expect(restored.getHours()).toBe(22)
|
||||
expect(restored.getDate()).toBe(12)
|
||||
expect(utcPickerToISO(restored)).toBe('2026-10-12T22:49:05.000Z')
|
||||
expect(formatUTCDateTime('2026-10-12T22:49:05Z')).toBe('2026-10-12 22:49:05 UTC')
|
||||
expect(isoToUTCPicker('')).toBeNull()
|
||||
expect(utcPickerToISO(null)).toBe('')
|
||||
})
|
||||
})
|
||||
35
frontend/src/releases-api.ts
Normal file
35
frontend/src/releases-api.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
export type Release = { id:number; product_id:number; version:string; sha256:string; size_bytes:number; published:boolean; product_name:string; product_code:string }
|
||||
export type UpdatePolicy = {
|
||||
platform:'windows'|'linux'|'macos'; arch:'x64'|'arm64'; channel:'stable'|'beta'; enabled:boolean
|
||||
release_id:number; minimum_supported_version:string; enforce_after:string; message:string
|
||||
}
|
||||
export type SavedUpdatePolicy = UpdatePolicy & { product_id:number; revision:number; recommended_version:string }
|
||||
export async function releaseResponse(response:Response) {
|
||||
const body = await response.json()
|
||||
if (!response.ok) throw new Error(body.error?.message || '请求失败')
|
||||
return body
|
||||
}
|
||||
export async function listUpdatePolicies(productID:number):Promise<SavedUpdatePolicy[]> {
|
||||
const body = await releaseResponse(await fetch(`/api/v1/products/${productID}/update-policies`, {credentials:'include'}))
|
||||
return body.data
|
||||
}
|
||||
export async function saveUpdatePolicy(productID:number, policy:UpdatePolicy):Promise<SavedUpdatePolicy> {
|
||||
const body = await releaseResponse(await fetch(`/api/v1/products/${productID}/update-policies`, {method:'PUT', credentials:'include', headers:{'Content-Type':'application/json'}, body:JSON.stringify(policy)}))
|
||||
return body.data
|
||||
}
|
||||
export function isStableSemVer(value:string):boolean { return /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value) }
|
||||
export function compareStableVersions(left:string, right:string):number {
|
||||
const a = left.split('.').map(BigInt), b = right.split('.').map(BigInt)
|
||||
for (let i = 0; i < 3; i++) { if (a[i]! < b[i]!) return -1; if (a[i]! > b[i]!) return 1 }
|
||||
return 0
|
||||
}
|
||||
export function validateUpdatePolicy(policy:UpdatePolicy, target:Release|undefined, productID:number):string {
|
||||
if (!target || target.product_id !== productID || !target.published || !isStableSemVer(target.version)) return '请选择当前产品已发布的正式 SemVer 版本'
|
||||
if (policy.minimum_supported_version) {
|
||||
if (!isStableSemVer(policy.minimum_supported_version)) return '最低支持版本须为正式 SemVer(x.y.z,不含前导零)'
|
||||
if (compareStableVersions(policy.minimum_supported_version, target.version) > 0) return '最低支持版本不能高于目标版本'
|
||||
if (!policy.enforce_after || !Number.isFinite(Date.parse(policy.enforce_after))) return '设置最低支持版本时必须选择 UTC 生效时间'
|
||||
} else if (policy.enforce_after) return '未设置最低支持版本时请清空生效时间'
|
||||
if (Array.from(policy.message).length > 2000) return '更新说明最多 2000 个字符'
|
||||
return ''
|
||||
}
|
||||
@@ -1,23 +1,104 @@
|
||||
import { mount, flushPromises } from '@vue/test-utils'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import type { Product } from '../api'
|
||||
import type { SavedUpdatePolicy } from '../releases-api'
|
||||
import ReleasesPanel from './ReleasesPanel.vue'
|
||||
|
||||
describe('ReleasesPanel', () => {
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
it('loads all products by default', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: [], meta: { total: 0 } }) })
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const wrapper = mount(ReleasesPanel, { props: { products: [] }, global: { stubs: { ElButton: true, ElSelect: true, ElOption: true, ElInput: true, ElTable: { template: '<div><slot /></div>' }, ElTableColumn: true, ElPagination: true }, directives: { loading: () => {} } } })
|
||||
await flushPromises()
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/releases?page=1', { credentials: 'include' })
|
||||
expect(wrapper.findAll('el-table-column-stub').map(c => c.attributes('label'))).toContain('产品')
|
||||
const stubs = {
|
||||
ElButton: {template:'<button :disabled="disabled" @click="$emit(\'click\')"><slot /></button>', props:['disabled']},
|
||||
ElSelect: {template:'<div><slot /></div>', props:['modelValue']}, ElOption:true,
|
||||
ElInput: {template:'<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />', props:['modelValue']},
|
||||
ElDatePicker: {template:'<input />', props:['modelValue']}, ElSwitch: {template:'<input />', props:['modelValue']},
|
||||
ElTable:{template:'<div><slot /></div>',props:['data']}, ElTableColumn:true, ElPagination:true,
|
||||
}
|
||||
const products = [{id:7,name:'产品甲',code:'a',active:true},{id:8,name:'产品乙',code:'b',active:true}] as Product[]
|
||||
const saved:SavedUpdatePolicy = {product_id:7,revision:3,platform:'windows',arch:'x64',channel:'stable',enabled:true,release_id:9,minimum_supported_version:'1.0.0',enforce_after:'2026-10-12T15:00:00Z',message:'请更新',recommended_version:'2.0.0'}
|
||||
const target = {id:9,product_id:7,version:'2.0.0',published:true,sha256:'hash',size_bytes:1,product_name:'产品甲',product_code:'a'}
|
||||
const response = (body:unknown, ok = true) => ({ok,json:async()=>body})
|
||||
function setup(policyList:SavedUpdatePolicy[] = [saved]) {
|
||||
const fetchMock = vi.fn(async (url:string, options?:RequestInit) => {
|
||||
if (options?.method === 'PUT') return response({data:{...JSON.parse(options.body as string),product_id:7,revision:4,recommended_version:'2.0.0'}})
|
||||
if (url.includes('update-policies')) return response({data:policyList})
|
||||
if (url.includes('product_id=7')) return url.includes('page=2') ? response({data:[target],meta:{total:2}}) : response({data:[{...target,id:10,version:'2.1.0-beta'}],meta:{total:2}})
|
||||
return response({data:[],meta:{total:0}})
|
||||
})
|
||||
it('shows validation error without sending an invalid publication', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: [], meta: { total: 0 } }) }))
|
||||
const wrapper = mount(ReleasesPanel, { props: { products: [] }, global: { stubs: { ElButton: { template: '<button @click="$emit(\'click\')"><slot /></button>' }, ElSelect: true, ElOption: true, ElInput: true, ElTable: { template: '<div><slot /></div>' }, ElTableColumn: true, ElPagination: true }, directives: { loading: () => {} } } })
|
||||
expect(wrapper.find('[role="alert"]').exists()).toBe(false)
|
||||
vi.stubGlobal('fetch',fetchMock)
|
||||
const wrapper = mount(ReleasesPanel,{props:{products},global:{stubs,directives:{loading:()=>{}}}})
|
||||
return {wrapper,fetchMock}
|
||||
}
|
||||
describe('ReleasesPanel',()=>{
|
||||
afterEach(()=>{vi.unstubAllGlobals();vi.restoreAllMocks()})
|
||||
it('loads all products by default and preserves publication validation',async()=>{
|
||||
const {wrapper,fetchMock} = setup()
|
||||
await flushPromises()
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/releases?page=1',{credentials:'include'})
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
expect(wrapper.findAll('el-table-column-stub').map(c=>c.attributes('label'))).toContain('产品')
|
||||
await wrapper.findAll('button')[1]!.trigger('click')
|
||||
expect(wrapper.find('[role="alert"]').text()).toContain('请选择产品')
|
||||
expect(wrapper.find('input[type="file"]').attributes('aria-label')).toBe('版本文件')
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
it('loads scope, paginates targets and excludes unpublished/prerelease versions',async()=>{
|
||||
const {wrapper,fetchMock} = setup()
|
||||
wrapper.findComponent<typeof stubs.ElSelect>('[aria-label="策略产品"]').vm.$emit('update:modelValue',7)
|
||||
await flushPromises()
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/releases?page=2&product_id=7',{credentials:'include'})
|
||||
const options = wrapper.findComponent<typeof stubs.ElSelect>('[aria-label="策略目标版本"]').findAll('el-option-stub')
|
||||
expect(options).toHaveLength(1)
|
||||
expect(options[0]!.attributes('label')).toBe('2.0.0')
|
||||
expect(wrapper.find('[aria-label="最低支持版本"]').element).toHaveProperty('value','1.0.0')
|
||||
expect(wrapper.text()).toContain('修订 3')
|
||||
expect(wrapper.findAllComponents(stubs.ElTable)[0]!.props('data')).toEqual([saved])
|
||||
wrapper.findComponent<typeof stubs.ElSelect>('[aria-label="策略架构"]').vm.$emit('update:modelValue','arm64')
|
||||
await flushPromises()
|
||||
expect(wrapper.find('[aria-label="最低支持版本"]').element).toHaveProperty('value','')
|
||||
expect(wrapper.text()).toContain('windows / arm64 / stable')
|
||||
wrapper.findComponent<typeof stubs.ElSelect>('[aria-label="策略架构"]').vm.$emit('update:modelValue','x64')
|
||||
await flushPromises()
|
||||
expect(wrapper.find('[aria-label="最低支持版本"]').element).toHaveProperty('value','1.0.0')
|
||||
})
|
||||
it('confirms mandatory enable, cancels without PUT, saves UTC and displays server errors',async()=>{
|
||||
const {wrapper,fetchMock} = setup()
|
||||
const confirm = vi.spyOn(ElMessageBox,'confirm').mockRejectedValueOnce('cancel')
|
||||
wrapper.findComponent<typeof stubs.ElSelect>('[aria-label="策略产品"]').vm.$emit('update:modelValue',7)
|
||||
await flushPromises()
|
||||
const button = () => wrapper.findAll('button').find(item=>item.text()==='保存更新策略')!
|
||||
await button().trigger('click'); await flushPromises()
|
||||
expect(confirm).toHaveBeenCalledWith(expect.stringContaining('2026-10-12 15:00:00 UTC'),'启用强制更新策略',expect.any(Object))
|
||||
expect(fetchMock.mock.calls.some(([,options])=>options?.method==='PUT')).toBe(false)
|
||||
confirm.mockResolvedValue('confirm' as Awaited<ReturnType<typeof ElMessageBox.confirm>>)
|
||||
await button().trigger('click'); await flushPromises()
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/products/7/update-policies',expect.objectContaining({method:'PUT',credentials:'include',body:JSON.stringify({...saved,product_id:undefined,revision:undefined,recommended_version:undefined,enforce_after:'2026-10-12T15:00:00.000Z'})}))
|
||||
expect(wrapper.find('[role="status"]').text()).toContain('修订 4')
|
||||
fetchMock.mockResolvedValueOnce(response({error:{message:'目标版本已撤回'}},false))
|
||||
await button().trigger('click'); await flushPromises()
|
||||
expect(wrapper.find('[role="alert"]').text()).toContain('目标版本已撤回')
|
||||
})
|
||||
it('saves optional disabled scope without mandatory confirmation and keeps version filter independent',async()=>{
|
||||
const {wrapper,fetchMock} = setup([])
|
||||
const confirm = vi.spyOn(ElMessageBox,'confirm')
|
||||
wrapper.findComponent<typeof stubs.ElSelect>('[aria-label="策略产品"]').vm.$emit('update:modelValue',7)
|
||||
await flushPromises()
|
||||
wrapper.findComponent<typeof stubs.ElSelect>('[aria-label="策略目标版本"]').vm.$emit('update:modelValue',9)
|
||||
await wrapper.findAll('button').find(item=>item.text()==='保存更新策略')!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(confirm).not.toHaveBeenCalled()
|
||||
const put = fetchMock.mock.calls.find(([,options])=>options?.method==='PUT')!
|
||||
expect(JSON.parse(put[1]!.body as string)).toMatchObject({enabled:false,minimum_supported_version:'',enforce_after:'',release_id:9})
|
||||
expect(fetchMock.mock.calls.filter(([url])=>url==='/api/v1/releases?page=1')).toHaveLength(1)
|
||||
})
|
||||
it('shows load failures and ignores stale product responses',async()=>{
|
||||
const {wrapper,fetchMock} = setup()
|
||||
let resolveOld!:(value:ReturnType<typeof response>)=>void
|
||||
fetchMock.mockImplementationOnce(()=>new Promise(resolve=>{resolveOld=resolve}))
|
||||
wrapper.findComponent<typeof stubs.ElSelect>('[aria-label="策略产品"]').vm.$emit('update:modelValue',7)
|
||||
await flushPromises()
|
||||
fetchMock.mockResolvedValueOnce(response({error:{message:'策略加载失败'}},false))
|
||||
wrapper.findComponent<typeof stubs.ElSelect>('[aria-label="策略产品"]').vm.$emit('update:modelValue',8)
|
||||
await flushPromises()
|
||||
expect(wrapper.find('[role="alert"]').text()).toContain('策略加载失败')
|
||||
resolveOld(response({data:[saved]})); await flushPromises()
|
||||
expect(wrapper.text()).not.toContain('修订 3')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,10 +1,73 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import type { Product } from '../api'
|
||||
import { isStableSemVer, listUpdatePolicies, releaseResponse, saveUpdatePolicy, validateUpdatePolicy, type Release, type SavedUpdatePolicy, type UpdatePolicy } from '../releases-api'
|
||||
import { formatUTCDateTime, isoToUTCPicker, utcPickerToISO } from '../date-format'
|
||||
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 filterProductID = ref<number | null>(null)
|
||||
const releases = ref<{ id: number; version: string; sha256: string; size_bytes: number; published: boolean; product_name: string; product_code: string }[]>([])
|
||||
const releases = ref<Release[]>([])
|
||||
const policyProductID = ref<number | null>(null), policyLoading = ref(false), policySaving = ref(false), policyError = ref(''), policyNotice = ref('')
|
||||
const policies = ref<SavedUpdatePolicy[]>([]), targets = ref<Release[]>([]), enforceDate = ref<Date | null>(null)
|
||||
const policy = reactive<UpdatePolicy>({platform:'windows', arch:'x64', channel:'stable', enabled:false, release_id:0, minimum_supported_version:'', enforce_after:'', message:''})
|
||||
const scope = computed(() => `${policy.platform} / ${policy.arch} / ${policy.channel}`)
|
||||
const selectedPolicy = computed(() => policies.value.find(item => item.platform === policy.platform && item.arch === policy.arch && item.channel === policy.channel))
|
||||
let policySequence = 0
|
||||
function applyScope() {
|
||||
const saved = selectedPolicy.value
|
||||
Object.assign(policy, {enabled:saved?.enabled ?? false, release_id:saved?.release_id ?? 0, minimum_supported_version:saved?.minimum_supported_version ?? '', enforce_after:saved?.enforce_after ?? '', message:saved?.message ?? ''})
|
||||
enforceDate.value = isoToUTCPicker(saved?.enforce_after ?? '')
|
||||
policyError.value = ''; policyNotice.value = ''
|
||||
}
|
||||
watch(() => [policy.platform, policy.arch, policy.channel], applyScope)
|
||||
async function loadPolicies() {
|
||||
const sequence = ++policySequence, id = policyProductID.value
|
||||
policies.value = []; targets.value = []; applyScope(); policyLoading.value = !!id
|
||||
if (!id) return
|
||||
try {
|
||||
const [saved, published] = await Promise.all([listUpdatePolicies(id), loadTargets(id)])
|
||||
if (sequence !== policySequence) return
|
||||
policies.value = saved; targets.value = published; applyScope()
|
||||
} catch (e) { if (sequence === policySequence) policyError.value = e instanceof Error ? e.message : '更新策略加载失败' }
|
||||
finally { if (sequence === policySequence) policyLoading.value = false }
|
||||
}
|
||||
async function loadTargets(id:number):Promise<Release[]> {
|
||||
const result:Release[] = []
|
||||
let targetPage = 1
|
||||
while (true) {
|
||||
const body = await releaseResponse(await fetch(`/api/v1/releases?page=${targetPage}&product_id=${id}`, {credentials:'include'}))
|
||||
result.push(...body.data)
|
||||
if (!body.data.length || result.length >= body.meta.total) break
|
||||
targetPage++
|
||||
}
|
||||
return result.filter(item => item.product_id === id && item.published && isStableSemVer(item.version))
|
||||
}
|
||||
watch(policyProductID, loadPolicies)
|
||||
function editPolicy(item:SavedUpdatePolicy) {
|
||||
policy.platform = item.platform; policy.arch = item.arch; policy.channel = item.channel
|
||||
applyScope()
|
||||
}
|
||||
async function savePolicy() {
|
||||
if (policySaving.value || policyLoading.value) return
|
||||
policyError.value = ''; policyNotice.value = ''
|
||||
const id = policyProductID.value
|
||||
if (!id) { policyError.value = '请选择更新策略的产品'; return }
|
||||
const input:UpdatePolicy = {...policy, enforce_after:utcPickerToISO(enforceDate.value)}
|
||||
const validation = validateUpdatePolicy(input, targets.value.find(item => item.id === input.release_id), id)
|
||||
if (validation) { policyError.value = validation; return }
|
||||
policySaving.value = true
|
||||
try {
|
||||
if (input.enabled && input.minimum_supported_version) {
|
||||
try { await ElMessageBox.confirm(`产品:${props.products.find(item => item.id === id)?.name || id};范围:${scope.value}。低于 ${input.minimum_supported_version} 的客户端将在 ${formatUTCDateTime(input.enforce_after)} 起需要强制更新至 ${targets.value.find(item => item.id === input.release_id)?.version}。确认启用?`, '启用强制更新策略', {type:'warning', confirmButtonText:'确认启用', cancelButtonText:'取消'}) } catch (e) { if (e === 'cancel' || e === 'close') return; throw e }
|
||||
}
|
||||
const saved = await saveUpdatePolicy(id, input)
|
||||
const index = policies.value.findIndex(item => item.platform === saved.platform && item.arch === saved.arch && item.channel === saved.channel)
|
||||
if (index < 0) policies.value.push(saved); else policies.value[index] = saved
|
||||
applyScope(); policyNotice.value = `策略已保存(修订 ${saved.revision})`
|
||||
} catch (e) { policyError.value = e instanceof Error ? e.message : '更新策略保存失败' }
|
||||
finally { policySaving.value = false }
|
||||
}
|
||||
const selectedFileName = computed(() => file.value?.name || '选择安装包文件')
|
||||
const uploadProductName = computed(() => props.products.find(product => product.id === productID.value)?.name || '')
|
||||
let loadSequence = 0
|
||||
@@ -26,7 +89,7 @@ async function upload() {
|
||||
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() }
|
||||
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(); if (policyProductID.value) await loadPolicies() }
|
||||
catch (e) { error.value = e instanceof Error ? e.message : '上传失败' }
|
||||
finally { uploading.value = false }
|
||||
}
|
||||
@@ -49,6 +112,40 @@ async function upload() {
|
||||
<p v-if="error" role="alert" class="release-error">{{ error }}</p>
|
||||
</section>
|
||||
|
||||
<section class="release-publish release-policy" aria-labelledby="policy-title">
|
||||
<div class="release-subheading"><div><h3 id="policy-title">更新策略</h3><p>按产品、操作系统、架构及通道保存;未设置最低支持版本时仅推荐更新。</p></div><el-button :disabled="!policyProductID || policySaving" :loading="policyLoading" @click="loadPolicies">刷新策略</el-button></div>
|
||||
<label class="release-field policy-product"><span>策略产品</span><el-select v-model="policyProductID" clearable placeholder="选择策略产品" aria-label="策略产品" :disabled="policySaving"><el-option v-for="product in props.products" :key="product.id" :value="product.id" :label="`${product.name}(${product.code})`" /></el-select></label>
|
||||
<p v-if="!policyProductID" class="release-description">请选择产品以加载已有策略及可用版本。</p>
|
||||
<template v-else>
|
||||
<fieldset class="policy-fields" :disabled="policyLoading || policySaving">
|
||||
<legend>策略范围:{{ scope }}</legend>
|
||||
<div class="policy-form">
|
||||
<label class="release-field"><span>操作系统</span><el-select v-model="policy.platform" aria-label="策略操作系统" :disabled="policyLoading || policySaving"><el-option v-for="os in ['windows','linux','macos']" :key="os" :value="os" :label="os" /></el-select></label>
|
||||
<label class="release-field"><span>架构</span><el-select v-model="policy.arch" aria-label="策略架构" :disabled="policyLoading || policySaving"><el-option v-for="arch in ['x64','arm64']" :key="arch" :value="arch" :label="arch" /></el-select></label>
|
||||
<label class="release-field"><span>通道</span><el-select v-model="policy.channel" aria-label="策略通道" :disabled="policyLoading || policySaving"><el-option value="stable" label="stable" /><el-option value="beta" label="beta" /></el-select></label>
|
||||
<label class="release-field"><span>目标已发布版本</span><el-select v-model="policy.release_id" placeholder="选择正式版本" aria-label="策略目标版本" :disabled="policyLoading || policySaving"><el-option v-for="target in targets" :key="target.id" :value="target.id" :label="target.version" /></el-select></label>
|
||||
<label class="release-field"><span>最低支持版本(可选)</span><el-input v-model="policy.minimum_supported_version" placeholder="例如 1.0.0" aria-label="最低支持版本" :disabled="policyLoading || policySaving" /></label>
|
||||
<label class="release-field"><span>强制更新生效时间(UTC)</span><el-date-picker v-model="enforceDate" type="datetime" format="YYYY-MM-DD HH:mm:ss" placeholder="按 UTC 选择日期和时间" aria-label="策略生效时间 UTC" :disabled="policyLoading || policySaving" /></label>
|
||||
<label class="release-field policy-message"><span>更新说明(最多 2000 字符)</span><el-input v-model="policy.message" type="textarea" :rows="3" aria-label="更新说明" :disabled="policyLoading || policySaving" /></label>
|
||||
</div>
|
||||
<p class="release-description">{{ selectedPolicy ? `正在编辑已有策略 · 修订 ${selectedPolicy.revision}` : '此范围尚无策略,保存后创建。' }} 设置最低支持版本时须填写生效时间;清空最低版本时也须清空时间。</p>
|
||||
<div class="policy-actions"><el-switch v-model="policy.enabled" active-text="启用策略" aria-label="启用策略" :disabled="policyLoading || policySaving" /><el-button type="primary" :loading="policySaving" :disabled="policyLoading || !!policyError && !targets.length" @click="savePolicy">保存更新策略</el-button></div>
|
||||
</fieldset>
|
||||
<p v-if="!policyLoading && !policyError && !targets.length" class="release-description">暂无已发布的正式 SemVer(x.y.z)版本,请先发布版本。</p>
|
||||
<div class="release-table-wrap policy-table"><el-table :data="policies" v-loading="policyLoading" empty-text="此产品暂无更新策略">
|
||||
<el-table-column label="范围" min-width="220"><template #default="{ row }"><code>{{ row.platform }} / {{ row.arch }} / {{ row.channel }}</code></template></el-table-column>
|
||||
<el-table-column label="状态" width="100"><template #default="{ row }">{{ row.enabled ? '已启用' : '已停用' }}</template></el-table-column>
|
||||
<el-table-column prop="recommended_version" label="推荐版本" width="120" />
|
||||
<el-table-column label="最低支持版本" width="140"><template #default="{ row }">{{ row.minimum_supported_version || '仅推荐' }}</template></el-table-column>
|
||||
<el-table-column label="生效时间(UTC)" min-width="230"><template #default="{ row }">{{ formatUTCDateTime(row.enforce_after) }}</template></el-table-column>
|
||||
<el-table-column prop="message" label="更新说明" min-width="180" />
|
||||
<el-table-column prop="revision" label="修订" width="80" />
|
||||
<el-table-column label="操作" width="80"><template #default="{ row }"><el-button link :disabled="policyLoading || policySaving" @click="editPolicy(row)">编辑</el-button></template></el-table-column>
|
||||
</el-table></div>
|
||||
</template>
|
||||
<p v-if="policyError" role="alert" class="release-error">{{ policyError }}</p><p v-if="policyNotice" role="status" class="policy-notice">{{ policyNotice }}</p>
|
||||
</section>
|
||||
|
||||
<section class="release-list" aria-label="版本列表">
|
||||
<div class="release-list-toolbar">
|
||||
<div class="release-list-title"><h3>版本列表</h3><span class="release-count">{{ total }} 个版本</span></div>
|
||||
@@ -69,6 +166,7 @@ async function upload() {
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.policy-product{max-width:360px;margin-top:17px}.policy-fields{border:0;padding:0;margin:18px 0 0;min-width:0}.policy-fields legend{font-size:13px;font-weight:600;margin-bottom:12px}.policy-form{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}.policy-message{grid-column:1/-1}.policy-actions{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-top:15px}.policy-table{margin-top:18px;background:#fff}.policy-notice{color:#16845b;font-size:13px}.policy-form :deep(.el-date-editor){width:100%}@media(max-width:900px){.policy-form{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:620px){.policy-form{grid-template-columns:minmax(0,1fr)}.policy-actions{flex-wrap:wrap}}
|
||||
.release-workspace{--release-line:#e5eaf0;--release-muted:#687586;--release-ink:#17202b;--release-blue:#1769e0;color:var(--release-ink)}
|
||||
.release-heading{display:flex;justify-content:space-between;align-items:center;gap:18px;padding-bottom:21px;border-bottom:1px solid var(--release-line)}
|
||||
.release-eyebrow{margin:0 0 5px;color:var(--release-blue);font-size:11px;font-weight:700}
|
||||
|
||||
Reference in New Issue
Block a user