fix(admin): replace compensation range ids with selectors

go
codex 2 weeks ago
parent 34d3184f53
commit 77eb38b20e

@ -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',

@ -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);
}
}
});

@ -27,7 +27,7 @@
<fieldset>
<div class="row g-3">
<label class="col-lg-4" for="service-compensation-scope-type"><span class="form-label d-block">补偿范围</span><select class="form-select" id="service-compensation-scope-type" required><option value="instance">单个实例</option><option value="host">计算节点全部实例</option><option value="public_ip_pool">公网地址池持有实例</option></select></label>
<label class="col-lg-8" for="service-compensation-scope-id"><span class="form-label d-block">范围 ID</span><input class="form-control" id="service-compensation-scope-id" type="text" inputmode="numeric" pattern="[1-9][0-9]*" maxlength="18" required autocomplete="off" placeholder="输入实例、计算节点或公网地址池 ID"><span class="form-text">范围 ID 可从虚拟机、计算节点或地址池页面的快捷入口自动带入。</span></label>
<div class="col-lg-8"><label class="form-label d-block" for="service-compensation-scope-id">具体范围</label><div class="mb-2" id="service-compensation-scope-search-wrap"><label class="visually-hidden" for="service-compensation-scope-search">搜索实例</label><input class="form-control" id="service-compensation-scope-search" type="search" maxlength="80" autocomplete="off" placeholder="按实例名称、UUID、公网 IP 或 ID 搜索"></div><select class="form-select" id="service-compensation-scope-id" required><option value="">请选择具体范围</option></select><span class="form-text" id="service-compensation-scope-help">实例范围支持搜索;计算节点和公网地址池会显示可读名称。</span></div>
<label class="col-lg-5" for="service-compensation-incident-key"><span class="form-label d-block">事故编号</span><input class="form-control" id="service-compensation-incident-key" maxlength="128" required autocomplete="off" spellcheck="false" placeholder="例如 incident-hkg-network-20261106"><span class="form-text">同一事故不能重复补偿同一实例。</span></label>
<label class="col-lg-4" for="service-compensation-value"><span class="form-label d-block">补偿时长</span><input class="form-control" id="service-compensation-value" type="number" min="1" max="527040" step="1" required value="60"></label>
<label class="col-lg-3" for="service-compensation-unit"><span class="form-label d-block">时长单位</span><select class="form-select" id="service-compensation-unit"><option value="60">分钟</option><option value="3600">小时</option><option value="86400">天</option></select></label>

@ -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'}

@ -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.');

@ -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.');

@ -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, '<option value="instance">')
&& str_contains($template, '<option value="host">')
&& str_contains($template, '<option value="public_ip_pool">')
&& str_contains($template,
'id="service-compensation-scope-search" type="search"')
&& str_contains($template,
'<select class="form-select" id="service-compensation-scope-id" required>')
&& !str_contains($template,
'id="service-compensation-scope-id" type="text"')
&& str_contains($template, 'id="service-compensation-incident-key"')
&& str_contains($template, 'id="service-compensation-value"')
&& str_contains($template, 'id="service-compensation-unit"')
@ -60,6 +68,10 @@ $assert(str_contains($template, 'data-admin-service-compensations')
$assert(str_contains($script, "import(versionedModuleUrl('./admin-instance-actions.js'))")
&& str_contains($script, 'createAdminInstanceActions(')
&& str_contains($script, 'serviceCompensationScopeLabel(')
&& str_contains($script, 'serviceCompensationScopeId(')
&& str_contains($script, 'serviceCompensationInstanceQuery(')
&& str_contains($script, 'state.instanceSearchSequence')
&& str_contains($script, 'actions.commit(')
&& str_contains($script,
"'/api/v1/admin/service-compensations/preview'")
@ -82,7 +94,7 @@ $assert(str_contains($instanceDetail, '补偿可用时间')
'The instance service and billing surface lost its scoped compensation shortcut.');
$assert(str_contains($assets,
"venix_asset_version value='2026110602'"),
"venix_asset_version value='2026110603'"),
'The compensation administrator assets must publish the requested cache version.');
echo "Service compensation administrator page contracts passed.\n";

Loading…
Cancel
Save