From 77eb38b20e3c17523910b2c23347308c8eec49ee Mon Sep 17 00:00:00 2001 From: codex Date: Fri, 6 Nov 2026 13:58:53 +0800 Subject: [PATCH] fix(admin): replace compensation range ids with selectors --- .../Controllers/Admin/CloudPageController.php | 1 + .../cloud/admin-service-compensations.js | 181 ++++++++++++++++-- .../admin/cloud/service_compensations.tpl | 2 +- web/resources/views/venix/layout_assets.tpl | 2 +- ...inServiceCompensationScopeBehaviorTest.mjs | 60 ++++++ web/tests/CloudAssetVersionContractTest.php | 2 +- ...rviceCompensationAdminPageContractTest.php | 14 +- 7 files changed, 245 insertions(+), 17 deletions(-) create mode 100644 web/tests/AdminServiceCompensationScopeBehaviorTest.mjs diff --git a/web/app/Controllers/Admin/CloudPageController.php b/web/app/Controllers/Admin/CloudPageController.php index 276def98..a210c2be 100644 --- a/web/app/Controllers/Admin/CloudPageController.php +++ b/web/app/Controllers/Admin/CloudPageController.php @@ -313,6 +313,7 @@ final class CloudPageController extends AdminController ['options' => ['min_range' => 1]]); $payload = [ 'page' => (new CloudServiceCompensationService())->page($query), + 'catalog' => (new CloudMaintenanceNoticeService())->catalog(), 'prefill' => [ 'scope_type' => in_array($scopeType, [ 'instance', 'host', 'public_ip_pool', diff --git a/web/public/cloud/admin-service-compensations.js b/web/public/cloud/admin-service-compensations.js index 0a57550a..f131d66c 100644 --- a/web/public/cloud/admin-service-compensations.js +++ b/web/public/cloud/admin-service-compensations.js @@ -1,4 +1,33 @@ -const root = document.querySelector('[data-admin-service-compensations]'); +export function serviceCompensationScopeId(value) { + const text = String(value ?? '').trim(); + if (!/^[1-9][0-9]*$/.test(text)) return null; + const id = Number(text); + return Number.isSafeInteger(id) ? id : null; +} + +export function serviceCompensationScopeLabel(type, row = {}) { + if (type === 'host') { + return [row.name || `计算节点 #${row.id || '—'}`, row.region, + row.enabled === false ? '已停用' : ''].filter(Boolean).join(' · '); + } + if (type === 'public_ip_pool') { + return [row.host_name, row.address_family ? `IPv${row.address_family}` : '', + row.name || `地址池 #${row.id || '—'}`, row.cidr, + row.state && row.state !== 'active' ? row.state : ''].filter(Boolean).join(' · '); + } + const ip = row.public_ipv4 || row.public_ipv6 || row.public_ip || ''; + return [row.name || `实例 #${row.id || '—'}`, row.id ? `#${row.id}` : '', + ip, row.host_name, row.user_name].filter(Boolean).join(' · '); +} + +export function serviceCompensationInstanceQuery(query = '') { + const params = new URLSearchParams({ + q: String(query).trim(), page: '1', per_page: '20', + }); + return `/api/v1/admin/instances?${params.toString()}`; +} + +const root = globalThis.document?.querySelector?.('[data-admin-service-compensations]') || null; if (root) { const assetVersion = new URL(import.meta.url).searchParams.get('v'); @@ -28,10 +57,14 @@ if (root) { const actions = createAdminInstanceActions(); const state = { page: bootstrap.page || { page: 1, per_page: 20, total: 0, items: [] }, + catalog: bootstrap.catalog || { hosts: [], pools: [] }, prefill: bootstrap.prefill || {}, preview: null, + previewRequestSequence: 0, detail: null, mutationLocked: false, + instanceSearchSequence: 0, + instanceSearchTimer: null, }; const labels = { scopes: { @@ -103,14 +136,120 @@ if (root) { function scopeRequest() { const scopeType = byId('service-compensation-scope-type').value; - const scopeId = Number(byId('service-compensation-scope-id').value); + const scopeId = serviceCompensationScopeId( + byId('service-compensation-scope-id').value + ); if (!Object.prototype.hasOwnProperty.call(labels.scopes, scopeType) - || !Number.isInteger(scopeId) || scopeId < 1) { - throw new Error('请输入有效的实例、计算节点或公网地址池 ID。'); + || scopeId === null) { + throw new Error('请选择有效的实例、计算节点或公网地址池。'); } return { scope_type: scopeType, scope_id: scopeId }; } + function scopePlaceholder(text) { + const option = document.createElement('option'); + option.value = ''; + option.textContent = text; + option.selected = true; + option.disabled = true; + return option; + } + + function renderScopeOptions(type, rows, selectedId = '') { + const target = byId('service-compensation-scope-id'); + const selected = String(selectedId || ''); + target.replaceChildren(scopePlaceholder( + rows.length ? '请选择具体范围' : '没有可选择的范围' + )); + for (const row of rows) { + const id = serviceCompensationScopeId(row?.id); + if (id === null) continue; + const option = document.createElement('option'); + option.value = String(id); + option.textContent = serviceCompensationScopeLabel(type, row); + target.append(option); + } + if (selected && Array.from(target.options).some(option => option.value === selected)) { + target.value = selected; + } + target.disabled = target.options.length <= 1; + setMutationBusy(false); + } + + async function loadInstanceOptions(query = '', selectedId = '') { + if (byId('service-compensation-scope-type').value !== 'instance') return; + const requestSequence = ++state.instanceSearchSequence; + const target = byId('service-compensation-scope-id'); + target.disabled = true; + target.replaceChildren(scopePlaceholder('正在读取实例…')); + setMutationBusy(false); + try { + const payload = selectedId + ? await actions.read(`/api/v1/admin/instances/${encodeURIComponent(selectedId)}`) + : await actions.read(serviceCompensationInstanceQuery(query)); + if (requestSequence !== state.instanceSearchSequence + || byId('service-compensation-scope-type').value !== 'instance') return; + const rows = selectedId + ? (payload?.instance ? [payload.instance] : []) + : (Array.isArray(payload?.items) ? payload.items : []); + renderScopeOptions('instance', rows, selectedId); + byId('service-compensation-scope-help').textContent = rows.length + ? `已显示 ${rows.length} 个匹配实例;请选择后预览补偿范围。` + : '没有找到匹配实例,请更换名称、UUID、IP 或 ID。'; + } catch (error) { + if (requestSequence !== state.instanceSearchSequence) return; + target.replaceChildren(scopePlaceholder('实例读取失败')); + target.disabled = true; + byId('service-compensation-scope-help').textContent = + error.message || '实例目录读取失败,请稍后重试。'; + setMutationBusy(false); + } + } + + function configureScope(usePrefill = false) { + const type = byId('service-compensation-scope-type').value; + const searchWrap = byId('service-compensation-scope-search-wrap'); + const search = byId('service-compensation-scope-search'); + const selected = usePrefill && state.prefill.scope_type === type + ? String(state.prefill.scope_id || '') : ''; + searchWrap.hidden = type !== 'instance'; + search.disabled = type !== 'instance'; + if (type === 'instance') { + if (selected) search.value = selected; + byId('service-compensation-scope-help').textContent = + '按实例名称、UUID、公网 IP 或 ID 搜索,最多显示 20 个结果。'; + void loadInstanceOptions(selected || search.value, selected); + } else { + if (state.instanceSearchTimer !== null) { + clearTimeout(state.instanceSearchTimer); + state.instanceSearchTimer = null; + } + state.instanceSearchSequence += 1; + const rows = type === 'host' + ? state.catalog.hosts || [] : state.catalog.pools || []; + renderScopeOptions(type, rows, selected); + byId('service-compensation-scope-help').textContent = type === 'host' + ? '选择发生故障的计算节点,将预览该节点上符合条件的实例。' + : '选择发生故障的公网地址池,将预览当前持有该池地址且符合条件的实例。'; + } + if (usePrefill) state.prefill = {}; + } + + function queueInstanceSearch() { + if (byId('service-compensation-scope-type').value !== 'instance') return; + if (state.instanceSearchTimer !== null) clearTimeout(state.instanceSearchTimer); + state.instanceSearchSequence += 1; + invalidatePreview(); + const target = byId('service-compensation-scope-id'); + target.disabled = true; + target.replaceChildren(scopePlaceholder('等待搜索…')); + setMutationBusy(false); + state.instanceSearchTimer = setTimeout(() => { + state.instanceSearchTimer = null; + void loadInstanceOptions(byId('service-compensation-scope-search').value); + }, 250); + } + function compensationSeconds() { const value = Number(byId('service-compensation-value').value); const factor = Number(byId('service-compensation-unit').value); @@ -146,12 +285,17 @@ if (root) { } function setMutationBusy(busy) { - byId('service-compensation-preview').disabled = busy || state.mutationLocked || !canManage; + const scopeReady = serviceCompensationScopeId( + byId('service-compensation-scope-id')?.value + ) !== null; + byId('service-compensation-preview').disabled = busy || state.mutationLocked + || !canManage || !scopeReady; byId('service-compensation-create').disabled = busy || state.mutationLocked || !canManage || !state.preview; } function invalidatePreview() { + state.previewRequestSequence += 1; state.preview = null; byId('service-compensation-preview-card').hidden = true; byId('service-compensation-preview-items').replaceChildren(); @@ -355,16 +499,22 @@ if (root) { renderList(); if (canManage) { byId('service-compensation-scope-type').value = state.prefill.scope_type || 'instance'; - if (state.prefill.scope_id) { - byId('service-compensation-scope-id').value = String(state.prefill.scope_id); - } updateTimeSummary(); setMutationBusy(false); + configureScope(true); - for (const id of ['service-compensation-scope-type', 'service-compensation-scope-id']) { - byId(id).addEventListener('change', invalidatePreview); - byId(id).addEventListener('input', invalidatePreview); - } + byId('service-compensation-scope-type').addEventListener('change', () => { + byId('service-compensation-scope-search').value = ''; + state.prefill = {}; + invalidatePreview(); + configureScope(); + }); + byId('service-compensation-scope-search').addEventListener( + 'input', queueInstanceSearch + ); + byId('service-compensation-scope-id').addEventListener( + 'change', invalidatePreview + ); for (const id of ['service-compensation-value', 'service-compensation-unit', 'service-compensation-incident-start', 'service-compensation-incident-end']) { byId(id).addEventListener('change', updateTimeSummary); @@ -373,18 +523,23 @@ if (root) { byId('service-compensation-preview').addEventListener('click', async () => { if (state.mutationLocked) return; + const requestSequence = ++state.previewRequestSequence; setMutationBusy(true); notify('正在核对受影响实例与服务周期…'); try { const preview = await actions.commit( '/api/v1/admin/service-compensations/preview', scopeRequest() ); + if (requestSequence !== state.previewRequestSequence) return; renderPreview(preview); notify('受影响实例已预览。请核对结果后再创建补偿。'); } catch (error) { + if (requestSequence !== state.previewRequestSequence) return; if (!uncertain(error)) notify(error.message || '实例补偿预览失败。', true); } finally { - setMutationBusy(false); + if (requestSequence === state.previewRequestSequence) { + setMutationBusy(false); + } } }); diff --git a/web/resources/views/venix/admin/cloud/service_compensations.tpl b/web/resources/views/venix/admin/cloud/service_compensations.tpl index 256b60c9..79c8482c 100644 --- a/web/resources/views/venix/admin/cloud/service_compensations.tpl +++ b/web/resources/views/venix/admin/cloud/service_compensations.tpl @@ -27,7 +27,7 @@
- +
实例范围支持搜索;计算节点和公网地址池会显示可读名称。
diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index 0f325607..ff674d31 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026110602' scope='global'} +{assign var=venix_asset_version value='2026110603' scope='global'} diff --git a/web/tests/AdminServiceCompensationScopeBehaviorTest.mjs b/web/tests/AdminServiceCompensationScopeBehaviorTest.mjs new file mode 100644 index 00000000..a454414c --- /dev/null +++ b/web/tests/AdminServiceCompensationScopeBehaviorTest.mjs @@ -0,0 +1,60 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; + +globalThis.document = { querySelector: () => null }; + +const { + serviceCompensationInstanceQuery, + serviceCompensationScopeId, + serviceCompensationScopeLabel, +} = await import(new URL( + '../public/cloud/admin-service-compensations.js?scope-behavior-test', + import.meta.url, +)); + +assert.equal(serviceCompensationScopeId('17'), 17, + 'A selected positive decimal identifier must remain numeric at the API boundary.'); +for (const invalid of ['', '0', '-1', '01', '1e2', '0x10', '1.5', + String(Number.MAX_SAFE_INTEGER + 1)]) { + assert.equal(serviceCompensationScopeId(invalid), null, + `The selector accepted a non-canonical or unsafe identifier: ${invalid}`); +} + +assert.equal(serviceCompensationScopeLabel('host', { + id: 7, name: 'HKG-A', region: 'Hong Kong', enabled: true, +}), 'HKG-A · Hong Kong'); +assert.equal(serviceCompensationScopeLabel('public_ip_pool', { + id: 8, host_name: 'HKG-A', address_family: 6, + name: 'IPv6 Primary', cidr: '2404:c140:156:38::/64', state: 'active', +}), 'HKG-A · IPv6 · IPv6 Primary · 2404:c140:156:38::/64'); +assert.equal(serviceCompensationScopeLabel('instance', { + id: '19', name: 'vm-web', public_ipv4: '203.0.113.19', + host_name: 'HKG-B', user_name: 'alice', +}), 'vm-web · #19 · 203.0.113.19 · HKG-B · alice'); + +const search = new URL( + serviceCompensationInstanceQuery(' vm-web '), + 'https://panel.example', +); +assert.equal(search.pathname, '/api/v1/admin/instances'); +assert.equal(search.searchParams.get('q'), 'vm-web'); +assert.equal(search.searchParams.get('page'), '1'); +assert.equal(search.searchParams.get('per_page'), '20'); + +const source = await readFile(new URL( + '../public/cloud/admin-service-compensations.js', import.meta.url, +), 'utf8'); +assert.match(source, + /function queueInstanceSearch\(\)[\s\S]*state\.instanceSearchSequence \+= 1;[\s\S]*setTimeout/, + 'Typing a new query must invalidate an older in-flight instance response immediately.'); +assert.match(source, + /if \(state\.instanceSearchTimer !== null\) \{[\s\S]*clearTimeout\(state\.instanceSearchTimer\);[\s\S]*state\.instanceSearchTimer = null;/, + 'Switching away from instance search must cancel its pending debounce timer.'); +assert.match(source, + /function invalidatePreview\(\) \{[\s\S]*state\.previewRequestSequence \+= 1;/, + 'Changing the selected scope must invalidate an in-flight audience preview.'); +assert.match(source, + /const requestSequence = \+\+state\.previewRequestSequence;[\s\S]*requestSequence !== state\.previewRequestSequence/, + 'A stale audience response must not restore the preview for an older scope.'); + +console.log('Service compensation readable-scope selector behavior passed.'); diff --git a/web/tests/CloudAssetVersionContractTest.php b/web/tests/CloudAssetVersionContractTest.php index 45a72981..b7d144f1 100644 --- a/web/tests/CloudAssetVersionContractTest.php +++ b/web/tests/CloudAssetVersionContractTest.php @@ -15,7 +15,7 @@ $assert = static function (bool $condition, string $message): void { }; $assert(is_string($assets) - && str_contains($assets, "venix_asset_version value='2026110602'") + && str_contains($assets, "venix_asset_version value='2026110603'") && is_string($cloudShell) && str_contains($cloudShell, '/cloud/app.js?v={$venix_asset_version}'), 'The cloud application entry must use the shared Venix asset version.'); diff --git a/web/tests/CloudServiceCompensationAdminPageContractTest.php b/web/tests/CloudServiceCompensationAdminPageContractTest.php index 7f628089..d7ffc0d2 100644 --- a/web/tests/CloudServiceCompensationAdminPageContractTest.php +++ b/web/tests/CloudServiceCompensationAdminPageContractTest.php @@ -28,6 +28,8 @@ $assert(str_contains($routes, "'/service-compensations',\n 'App\\Controllers\\Admin\\CloudPageController:serviceCompensations'") && str_contains($controller, 'public function serviceCompensations(') && str_contains($controller, "if (!(\$actor['is_admin'] ?? false))") + && str_contains($controller, + "'catalog' => (new CloudMaintenanceNoticeService())->catalog()") && str_contains($controller, "'can_manage' => (bool)") && str_contains($controller, "'private, no-store'") && str_contains($controller, 'JSON_HEX_TAG | JSON_HEX_AMP'), @@ -42,6 +44,12 @@ $assert(str_contains($template, 'data-admin-service-compensations') && str_contains($template, '