feat(admin): add service compensation page

go
codex 2 weeks ago
parent 4e7533deb4
commit c01e2dc72e

@ -14,6 +14,7 @@ use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudMaintenanceNoticeService;
use App\Services\Cloud\CloudPlatformDefaultNetworkPolicy;
use App\Services\Cloud\CloudPlatformTestNetworkPolicy;
use App\Services\Cloud\CloudServiceCompensationService;
/** Admin pages use local or database-only first paints; JSON APIs repeat authorisation. */
final class CloudPageController extends AdminController
@ -283,6 +284,68 @@ final class CloudPageController extends AdminController
->withHeader('Cache-Control', 'private, no-store');
}
public function serviceCompensations($request, $response, $args)
{
try {
$actor = CloudAccess::actor(false);
} catch (CloudError $exception) {
return $response->withStatus($exception->httpStatus)
->withHeader('Cache-Control', 'private, no-store');
}
if (!($actor['is_admin'] ?? false)) {
return $response->withStatus(403)
->withHeader('Cache-Control', 'private, no-store');
}
$payload = null;
$error = '';
$status = 200;
try {
$query = $request->getQueryParams();
$scopeType = trim((string) ($query['scope_type'] ?? ''));
$scopeId = $query['scope_id'] ?? match ($scopeType) {
'instance' => $query['instance_id'] ?? null,
'host' => $query['host_id'] ?? null,
'public_ip_pool' => $query['pool_id'] ?? null,
default => null,
};
$scopeId = filter_var($scopeId, FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]);
$payload = [
'page' => (new CloudServiceCompensationService())->page($query),
'prefill' => [
'scope_type' => in_array($scopeType, [
'instance', 'host', 'public_ip_pool',
], true) ? $scopeType : '',
'scope_id' => $scopeId === false ? null : (int) $scopeId,
],
'can_manage' => (bool) ($actor['can_manage'] ?? false),
];
} catch (CloudError $exception) {
$error = $exception->getMessage();
$status = $exception->httpStatus;
} catch (\Throwable $exception) {
error_log('Admin service compensation snapshot failed: '
. get_class($exception));
$error = '实例补偿数据暂时无法读取,请稍后重试。';
$status = 503;
}
$json = json_encode($payload,
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
| JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE
| JSON_THROW_ON_ERROR);
$smarty = $this->view()->assign([
'service_compensation_page' => $payload,
'service_compensation_error' => $error,
'service_compensation_bootstrap_json' => $json,
]);
$response->getBody()->write(
$smarty->fetch('admin/cloud/service_compensations.tpl')
);
return $response->withStatus($status)
->withHeader('Cache-Control', 'private, no-store');
}
public function platformDefaultPolicy($request, $response, $args)
{
try {

@ -194,6 +194,8 @@ $app->group('/admin', function () {
$this->get('/operations', 'App\Controllers\Admin\CloudPageController:operations');
$this->get('/maintenance-notices',
'App\Controllers\Admin\CloudPageController:maintenanceNotices');
$this->get('/service-compensations',
'App\Controllers\Admin\CloudPageController:serviceCompensations');
$this->get('/system-logs', 'App\Controllers\Admin\CloudPageController:systemLogs');
$this->get('/platform-default-policy', 'App\Controllers\Admin\CloudPageController:platformDefaultPolicy');
// Telegram administration is rendered inside the ticket system; these

@ -148,6 +148,18 @@ export function createAdminInstanceDetail({
['续费周期', vm.renewal_days ? `${vm.renewal_days} 天` : '不适用'],
['续费流量', vm.service_status === 'exempt' ? '不适用' : bytes(vm.renewal_traffic_bytes)],
]));
if (vm.service_status !== 'exempt') {
const compensation = el('section', 'd-flex align-items-center justify-content-between gap-3 flex-wrap mt-4 pt-4 border-top');
const copy = el('div');
copy.append(el('h3', 'h6 fw-semibold mb-1', '可用时间补偿'),
el('p', 'text-muted fs-13 mb-0', '为故障影响创建可审计的服务期限补偿,不修改余额或流量额度。'));
compensation.append(copy, safeLink(
`/admin/service-compensations?scope_type=instance&instance_id=${encodeURIComponent(vm.id)}`,
'补偿可用时间',
'btn btn-light btn-sm'
));
service.append(compensation);
}
const jobs = byId('instance-panel-jobs'); jobs.replaceChildren();
for (const job of payload.jobs || []) {
const card = el('article', 'card mb-3'); const body = el('div', 'card-body');

@ -0,0 +1,446 @@
const root = document.querySelector('[data-admin-service-compensations]');
if (root) {
const assetVersion = new URL(import.meta.url).searchParams.get('v');
function versionedModuleUrl(path) {
const url = new URL(path, import.meta.url);
if (assetVersion) url.searchParams.set('v', assetVersion);
return url.href;
}
const { createAdminInstanceActions } = await import(versionedModuleUrl('./admin-instance-actions.js'));
const byId = id => document.getElementById(id);
const element = (tag, className = '', text = '') => {
const node = document.createElement(tag);
if (className) node.className = className;
if (text !== '') node.textContent = text;
return node;
};
const parseBootstrap = () => {
try {
return JSON.parse(byId('admin-service-compensation-bootstrap')?.textContent || 'null');
} catch (error) {
return null;
}
};
const bootstrap = parseBootstrap() || {};
const canManage = root.dataset.canManage === '1' && bootstrap.can_manage === true;
const actions = createAdminInstanceActions();
const state = {
page: bootstrap.page || { page: 1, per_page: 20, total: 0, items: [] },
prefill: bootstrap.prefill || {},
preview: null,
detail: null,
mutationLocked: false,
};
const labels = {
scopes: {
instance: '单个实例',
host: '计算节点',
public_ip_pool: '公网地址池',
},
states: {
pending: '待执行',
applying: '执行中',
completed: '已完成',
partial: '部分完成',
attention: '需核对',
},
itemStates: {
pending: '待执行', applying: '执行中', deferred: '稍后重试',
applied: '已补偿', rejected: '不符合条件', attention: '需核对',
cancelled: '已取消',
},
eligibility: {
eligible: '可补偿', rejected: '不符合条件', attention: '需核对',
},
};
function notify(message, error = false) {
const node = byId('service-compensation-status');
node.textContent = message;
node.classList.toggle('is-error', error);
node.classList.toggle('is-success', !error);
}
function localDateTime(value) {
const seconds = Number(value || 0);
if (!Number.isFinite(seconds) || seconds <= 0) return '—';
const date = new Date(seconds * 1000);
return Number.isFinite(date.getTime()) ? date.toLocaleString() : '—';
}
function inputTimestamp(value) {
if (!value) return null;
const milliseconds = new Date(value).getTime();
return Number.isFinite(milliseconds) && milliseconds > 0
? Math.floor(milliseconds / 1000) : null;
}
function durationText(seconds) {
const value = Math.max(0, Number(seconds || 0));
if (value > 0 && value % 86400 === 0) return `${value / 86400} 天`;
if (value > 0 && value % 3600 === 0) return `${value / 3600} 小时`;
if (value > 0 && value % 60 === 0) return `${value / 60} 分钟`;
return `${value} 秒`;
}
function scopeLabel(scope, fallbackType = '', fallbackId = '') {
const model = scope && typeof scope === 'object' ? scope : {};
const type = String(model.type || fallbackType || '');
const id = model.id || fallbackId || '—';
return `${labels.scopes[type] || '补偿范围'} · ${model.label || `#${id}`}`;
}
function toneBadge(status, type = 'batch') {
const map = type === 'item' ? labels.itemStates : labels.states;
const tone = ['completed', 'applied'].includes(status) ? 'success'
: ['attention', 'rejected'].includes(status) ? 'danger'
: ['partial', 'deferred'].includes(status) ? 'warning'
: status === 'cancelled' ? 'secondary' : 'primary';
return element('span', `badge text-bg-${tone}`, map[status] || status || '未知');
}
function scopeRequest() {
const scopeType = byId('service-compensation-scope-type').value;
const scopeId = Number(byId('service-compensation-scope-id').value);
if (!Object.prototype.hasOwnProperty.call(labels.scopes, scopeType)
|| !Number.isInteger(scopeId) || scopeId < 1) {
throw new Error('请输入有效的实例、计算节点或公网地址池 ID。');
}
return { scope_type: scopeType, scope_id: scopeId };
}
function compensationSeconds() {
const value = Number(byId('service-compensation-value').value);
const factor = Number(byId('service-compensation-unit').value);
const seconds = value * factor;
if (!Number.isInteger(value) || value < 1
|| ![60, 3600, 86400].includes(factor)
|| !Number.isSafeInteger(seconds) || seconds > 31622400) {
throw new Error('补偿时长必须大于 0,且最长为 366 天。');
}
return seconds;
}
function incidentWindow() {
const starts = inputTimestamp(byId('service-compensation-incident-start').value);
const ends = inputTimestamp(byId('service-compensation-incident-end').value);
if ((starts === null) !== (ends === null)
|| (starts !== null && ends <= starts)) {
throw new Error('事故开始和结束时间需要同时填写,且结束时间晚于开始时间。');
}
return { incident_starts_at: starts, incident_ends_at: ends };
}
function updateTimeSummary() {
let duration = '补偿时长无效';
try { duration = `补偿 ${durationText(compensationSeconds())}`; }
catch (error) { duration = error.message; }
const starts = inputTimestamp(byId('service-compensation-incident-start').value);
const ends = inputTimestamp(byId('service-compensation-incident-end').value);
const windowText = starts && ends
? `事故时间 ${localDateTime(starts)} 至 ${localDateTime(ends)}`
: '未填写事故时间';
byId('service-compensation-time-summary').textContent = `${duration};${windowText}。`;
}
function setMutationBusy(busy) {
byId('service-compensation-preview').disabled = busy || state.mutationLocked || !canManage;
byId('service-compensation-create').disabled = busy || state.mutationLocked
|| !canManage || !state.preview;
}
function invalidatePreview() {
state.preview = null;
byId('service-compensation-preview-card').hidden = true;
byId('service-compensation-preview-items').replaceChildren();
setMutationBusy(false);
}
function eligibilityBadge(eligibility) {
const model = eligibility && typeof eligibility === 'object' ? eligibility : {};
const stateName = String(model.state || 'attention');
const tone = stateName === 'eligible' ? 'success'
: stateName === 'rejected' ? 'secondary' : 'danger';
const wrapper = element('div');
wrapper.append(element('span', `badge text-bg-${tone}`,
labels.eligibility[stateName] || stateName));
if (model.code) wrapper.append(element('span', 'd-block text-muted fs-12 mt-1', String(model.code)));
return wrapper;
}
function renderPreview(payload) {
state.preview = payload;
const summary = `${scopeLabel(payload.scope)} · ${Number(payload.instance_count || 0)} 台实例`
+ ` · ${Number(payload.eligible_count || 0)} 台可补偿`
+ ` · ${Number(payload.rejected_count || 0)} 台不符合条件`
+ ` · ${Number(payload.attention_count || 0)} 台需核对`
+ ` · ${Number(payload.recipient_count || 0)} 位可通知用户`;
byId('service-compensation-preview-summary').textContent = summary;
const body = byId('service-compensation-preview-items');
body.replaceChildren();
for (const instance of payload.instances || []) {
const row = document.createElement('tr');
const name = element('td');
name.append(element('strong', 'd-block', instance.name || `实例 #${instance.id}`),
element('span', 'text-muted fs-12', `#${instance.id}`));
const owner = element('td');
owner.append(element('span', 'd-block', `用户 #${instance.user_id || '—'}`),
element('span', 'text-muted fs-12', `宿主机 #${instance.host_id || '—'}`));
const tail = instance.tail_period || {};
row.append(name, owner, element('td', '', localDateTime(instance.expires_at)),
element('td', '', tail.id ? `#${tail.id} · ${localDateTime(tail.ends_at)}` : '—'),
element('td'));
row.lastElementChild.append(eligibilityBadge(instance.eligibility));
body.append(row);
}
byId('service-compensation-preview-card').hidden = false;
setMutationBusy(false);
}
function renderList() {
const body = byId('service-compensation-list');
body.replaceChildren();
const items = Array.isArray(state.page.items) ? state.page.items : [];
if (!items.length) {
const row = document.createElement('tr');
const cell = element('td', 'text-muted text-center py-4', '当前没有实例补偿批次。');
cell.colSpan = 5;
row.append(cell);
body.append(row);
}
for (const item of items) {
const row = document.createElement('tr');
const incident = element('td');
incident.append(element('strong', 'd-block', item.incident_key || '未命名事故'),
element('span', 'text-muted fs-13', scopeLabel(item.scope)));
const duration = element('td');
duration.append(element('span', 'd-block', durationText(item.compensation_seconds)),
element('span', 'text-muted fs-12', localDateTime(item.created_at)));
const result = element('td');
result.append(element('span', 'd-block', `${Number(item.applied_count || 0)} / ${Number(item.instance_count || 0)} 台已补偿`),
element('span', 'text-muted fs-12', `延后 ${Number(item.deferred_count || 0)} · 拒绝 ${Number(item.rejected_count || 0)} · 核对 ${Number(item.attention_count || 0)}`));
const status = element('td');
status.append(toneBadge(item.state));
if (item.last_error_code) status.append(element('span', 'd-block text-danger fs-12 mt-1', item.last_error_code));
const action = element('td');
const detail = element('button', 'btn btn-sm btn-light', '查看详情');
detail.type = 'button';
detail.addEventListener('click', () => { void openDetail(item.compensation_key); });
action.append(detail);
row.append(incident, duration, result, status, action);
body.append(row);
}
const perPage = Math.max(1, Number(state.page.per_page || 20));
const current = Math.max(1, Number(state.page.page || 1));
const total = Math.max(0, Number(state.page.total || 0));
const totalPages = Math.max(1, Math.ceil(total / perPage));
byId('service-compensation-pagination').hidden = total <= perPage;
byId('service-compensation-page-label').textContent = `第 ${current} / ${totalPages} 页 · 共 ${total} 条`;
byId('service-compensation-previous').disabled = current <= 1;
byId('service-compensation-next').disabled = current >= totalPages;
}
async function loadPage(page = 1) {
const params = new URLSearchParams({ page: String(page), per_page: '20' });
const status = byId('service-compensation-state-filter').value;
if (status) params.set('state', status);
notify('正在刷新实例补偿批次…');
try {
state.page = await actions.read(`/api/v1/admin/service-compensations?${params.toString()}`);
renderList();
notify(state.mutationLocked
? `已读取 ${Number(state.page.total || 0)} 个补偿批次;本页面写操作仍锁定,请核对后重新打开页面。`
: `已读取 ${Number(state.page.total || 0)} 个补偿批次。`, state.mutationLocked);
} catch (error) {
notify(error.message || '实例补偿批次读取失败。', true);
}
}
function appendFact(list, label, value) {
list.append(element('dt', '', label), element('dd', '', String(value ?? '—')));
}
function detailTable(title, columns, rows) {
const section = element('section', 'mt-4');
section.append(element('h3', 'h6', title));
const wrap = element('div', 'table-responsive');
const table = element('table', 'table table-sm align-middle');
const head = document.createElement('thead');
const headRow = document.createElement('tr');
for (const column of columns) headRow.append(element('th', '', column));
head.append(headRow);
const body = document.createElement('tbody');
for (const values of rows) {
const row = document.createElement('tr');
for (const value of values) row.append(element('td', '', String(value ?? '—')));
body.append(row);
}
table.append(head, body);
wrap.append(table);
section.append(wrap);
return section;
}
function renderDetail(detail) {
state.detail = detail;
byId('service-compensation-detail-title').textContent = detail.incident_key || '补偿批次';
byId('service-compensation-detail-state').replaceChildren(
toneBadge(detail.state),
element('span', 'ms-2', scopeLabel(detail.scope, detail.scope_type, detail.scope_id))
);
const body = byId('service-compensation-detail-body');
body.replaceChildren();
const facts = element('dl', 'admin-instance-details');
appendFact(facts, '批次编号', detail.compensation_key);
appendFact(facts, '补偿时长', durationText(detail.compensation_seconds));
appendFact(facts, '事故时间', detail.incident_starts_at
? `${localDateTime(detail.incident_starts_at)} 至 ${localDateTime(detail.incident_ends_at)}` : '未记录');
appendFact(facts, '创建时间', localDateTime(detail.created_at));
appendFact(facts, '用户通知', detail.notify_users
? `${Number(detail.recipient_count || 0)} 位收件人` : '未启用');
appendFact(facts, '执行结果', `${Number(detail.applied_count || 0)} 台成功 · ${Number(detail.deferred_count || 0)} 台延后 · ${Number(detail.rejected_count || 0)} 台拒绝 · ${Number(detail.attention_count || 0)} 台需核对`);
body.append(facts, element('h3', 'h6 mt-4', '补偿原因'),
element('p', 'text-break', detail.reason_text || '—'));
body.append(detailTable('实例结果', ['实例', '用户 / 宿主机', '到期时间变化', '状态'],
(detail.items || []).map(item => [
`${item.instance_name || `实例 #${item.instance_id}`} · #${item.instance_id}`,
`用户 #${item.user_id} / 宿主机 #${item.host_id}`,
`${localDateTime(item.before_expires_at)} → ${localDateTime(item.after_expires_at)}`,
`${labels.itemStates[item.state] || item.state}${item.last_error_code ? ` · ${item.last_error_code}` : ''}`,
])));
if (detail.notify_users) {
body.append(detailTable('通知结果', ['用户', '邮箱', '实例数', '状态'],
(detail.recipients || []).map(recipient => [
`#${recipient.user_id}`, recipient.email || '—',
recipient.instance_count || 0,
`${recipient.status || '未知'}${recipient.last_error_code ? ` · ${recipient.last_error_code}` : ''}`,
])));
}
}
async function openDetail(key) {
const dialog = byId('service-compensation-detail');
if (!dialog.open) {
window.VenixDrawerMotion?.openDrawerWithMotion(dialog) || dialog.showModal();
}
byId('service-compensation-detail-title').textContent = '补偿批次';
byId('service-compensation-detail-state').textContent = '正在读取补偿详情…';
byId('service-compensation-detail-body').replaceChildren();
try {
renderDetail(await actions.read(`/api/v1/admin/service-compensations/${encodeURIComponent(key)}`));
} catch (error) {
byId('service-compensation-detail-state').textContent = error.message || '补偿详情读取失败。';
}
}
async function closeDetail() {
const dialog = byId('service-compensation-detail');
if (window.VenixDrawerMotion) {
await window.VenixDrawerMotion.closeDrawerWithMotion(dialog);
} else if (dialog.open) {
dialog.close();
}
}
function uncertain(error) {
if (!error?.mutationMayHaveApplied) return false;
state.mutationLocked = true;
setMutationBusy(false);
notify('操作结果无法确认,请刷新批次列表核对;当前页面不会重复提交。', true);
return true;
}
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);
for (const id of ['service-compensation-scope-type', 'service-compensation-scope-id']) {
byId(id).addEventListener('change', invalidatePreview);
byId(id).addEventListener('input', invalidatePreview);
}
for (const id of ['service-compensation-value', 'service-compensation-unit',
'service-compensation-incident-start', 'service-compensation-incident-end']) {
byId(id).addEventListener('change', updateTimeSummary);
byId(id).addEventListener('input', updateTimeSummary);
}
byId('service-compensation-preview').addEventListener('click', async () => {
if (state.mutationLocked) return;
setMutationBusy(true);
notify('正在核对受影响实例与服务周期…');
try {
const preview = await actions.commit(
'/api/v1/admin/service-compensations/preview', scopeRequest()
);
renderPreview(preview);
notify('受影响实例已预览。请核对结果后再创建补偿。');
} catch (error) {
if (!uncertain(error)) notify(error.message || '实例补偿预览失败。', true);
} finally {
setMutationBusy(false);
}
});
byId('service-compensation-form').addEventListener('submit', async event => {
event.preventDefault();
if (state.mutationLocked || !state.preview) return;
setMutationBusy(true);
notify('正在创建实例补偿批次…');
try {
const incidentKey = byId('service-compensation-incident-key').value.trim().toLowerCase();
const reason = byId('service-compensation-reason').value.trim();
if (!/^[a-z0-9][a-z0-9._:-]{0,127}$/.test(incidentKey)) {
throw new Error('事故编号只允许小写字母、数字、点、下划线、冒号和短横线。');
}
if (!reason || reason.length > 500) throw new Error('请填写不超过 500 个字符的补偿原因。');
const payload = {
...scopeRequest(),
...incidentWindow(),
incident_key: incidentKey,
reason_text: reason,
compensation_seconds: compensationSeconds(),
notify_users: byId('service-compensation-notify').checked,
audience_digest: state.preview.audience_digest,
};
const detail = await actions.commit('/api/v1/admin/service-compensations', payload);
invalidatePreview();
notify(`事故“${detail.incident_key}”的补偿批次已创建。`);
await loadPage(1);
await openDetail(detail.compensation_key);
} catch (error) {
if (!uncertain(error)) {
if (Number(error.status || 0) === 409) invalidatePreview();
notify(error.message || '实例补偿批次创建失败。', true);
}
} finally {
setMutationBusy(false);
}
});
}
byId('service-compensation-refresh').addEventListener('click', () => {
if (canManage) {
setMutationBusy(false);
}
void loadPage(state.page.page || 1);
});
byId('service-compensation-state-filter').addEventListener('change', () => { void loadPage(1); });
byId('service-compensation-previous').addEventListener('click', () => {
void loadPage(Math.max(1, Number(state.page.page || 1) - 1));
});
byId('service-compensation-next').addEventListener('click', () => {
void loadPage(Number(state.page.page || 1) + 1);
});
byId('service-compensation-detail-close').addEventListener('click', () => { void closeDetail(); });
byId('service-compensation-detail').addEventListener('cancel', event => {
event.preventDefault();
void closeDetail();
});
}

@ -0,0 +1,74 @@
{assign var=admin_title value='实例补偿'}
{assign var=admin_active value='service-compensations'}
{include file='admin/static_header.tpl'}
<link rel="stylesheet" href="/cloud/admin.css?v={$venix_asset_version}">
<main data-admin-service-compensations data-can-manage="{if $admin_can_manage|default:false}1{else}0{/if}">
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column gap-3">
<div class="flex-grow-1">
<h1 class="fs-20 fw-semibold mb-1">实例可用时间补偿</h1>
<p class="text-muted mb-0">按单实例、计算节点或公网地址池补偿服务期限。补偿只延长现有服务和已付权益窗口,不增加余额、流量额度或未购买的自动备份。</p>
</div>
<div class="admin-checkout-actions">
<span class="admin-config-status {if $service_compensation_error|default:''}is-error{else}is-success{/if}" id="service-compensation-status" role="status" aria-live="polite">{if $service_compensation_error|default:''}{$service_compensation_error|escape}{else}已读取 {$service_compensation_page.page.total|default:0|escape} 个批次{/if}</span>
<button class="btn btn-light" id="service-compensation-refresh" type="button"><i class="mdi mdi-refresh me-1" aria-hidden="true"></i>刷新</button>
</div>
</div>
{if !$admin_can_manage|default:false}
<p class="alert alert-info">当前管理员为只读模式,可查看补偿批次和脱敏结果,不能预览范围或创建补偿。</p>
{else}
<section class="card mb-3" aria-labelledby="service-compensation-create-title">
<div class="card-header">
<h2 class="h5 card-title mb-1" id="service-compensation-create-title">创建补偿批次</h2>
<p class="text-muted fs-13 mb-0">必须先预览受影响实例。预览后范围发生变化时,服务端会拒绝旧摘要,防止错补或漏补。</p>
</div>
<div class="card-body">
<form id="service-compensation-form" novalidate>
<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>
<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>
<label class="col-12" for="service-compensation-reason"><span class="form-label d-block">补偿原因</span><textarea class="form-control" id="service-compensation-reason" rows="4" maxlength="500" required placeholder="说明故障、影响和补偿依据,不要填写密码或密钥。"></textarea></label>
<label class="col-lg-6" for="service-compensation-incident-start"><span class="form-label d-block">事故开始(可选,浏览器本地时间)</span><input class="form-control" id="service-compensation-incident-start" type="datetime-local"></label>
<label class="col-lg-6" for="service-compensation-incident-end"><span class="form-label d-block">事故结束(可选,浏览器本地时间)</span><input class="form-control" id="service-compensation-incident-end" type="datetime-local"></label>
<label class="col-12 d-flex align-items-start gap-2" for="service-compensation-notify"><input class="form-check-input mt-1" id="service-compensation-notify" type="checkbox" checked><span><strong class="d-block">补偿完成后通知用户</strong><span class="text-muted fs-13">只向实际补偿成功的用户发送一封汇总邮件;邮件投递效果未知时不会盲目重发。</span></span></label>
</div>
<p class="alert alert-light border mt-3 mb-0" id="service-compensation-time-summary">补偿 60 分钟;未填写事故时间。</p>
<div class="admin-form-actions mt-3"><button class="btn btn-light" id="service-compensation-preview" type="button"><i class="mdi mdi-account-search-outline me-1" aria-hidden="true"></i>预览受影响实例</button><button class="btn btn-primary" id="service-compensation-create" type="submit" disabled><i class="mdi mdi-clock-plus-outline me-1" aria-hidden="true"></i>确认创建补偿</button></div>
</fieldset>
</form>
</div>
</section>
{/if}
{if $admin_can_manage|default:false}
<section class="card mb-3" id="service-compensation-preview-card" aria-labelledby="service-compensation-preview-title" hidden>
<div class="card-header"><h2 class="h5 card-title mb-1" id="service-compensation-preview-title">补偿范围预览</h2><p class="text-muted fs-13 mb-0" id="service-compensation-preview-summary"></p></div>
<div class="card-body"><div class="table-responsive"><table class="table table-hover align-middle mb-0"><thead><tr><th>实例</th><th>用户 / 宿主机</th><th>当前到期</th><th>当前尾周期</th><th>资格</th></tr></thead><tbody id="service-compensation-preview-items"></tbody></table></div></div>
</section>
{/if}
<section class="card" aria-labelledby="service-compensation-list-title">
<div class="card-header d-flex justify-content-between align-items-center gap-3 flex-wrap">
<div><h2 class="h5 card-title mb-1" id="service-compensation-list-title">补偿批次</h2><p class="text-muted fs-13 mb-0">需核对表示没有自动重放;请根据批次明细和实例任务记录处理异常。</p></div>
<label class="d-flex align-items-center gap-2 mb-0" for="service-compensation-state-filter"><span class="text-muted text-nowrap">状态</span><select class="form-select" id="service-compensation-state-filter"><option value="">全部</option><option value="pending">待执行</option><option value="applying">执行中</option><option value="completed">已完成</option><option value="partial">部分完成</option><option value="attention">需核对</option></select></label>
</div>
<div class="card-body">
<div class="table-responsive"><table class="table table-hover align-middle mb-0"><thead><tr><th>事故与范围</th><th>补偿时长</th><th>执行结果</th><th>状态</th><th>操作</th></tr></thead><tbody id="service-compensation-list"></tbody></table></div>
<nav class="admin-user-pagination mt-3" id="service-compensation-pagination" aria-label="实例补偿分页" hidden><button class="btn btn-light" id="service-compensation-previous" type="button">上一页</button><span id="service-compensation-page-label"></span><button class="btn btn-light" id="service-compensation-next" type="button">下一页</button></nav>
</div>
</section>
<noscript><p class="alert alert-info mt-3">启用 JavaScript 后可预览实例、创建补偿并查看执行明细。</p></noscript>
</main>
<dialog data-admin-instance-drawer id="service-compensation-detail" aria-labelledby="service-compensation-detail-title">
<header class="admin-instance-drawer-header"><div><p class="text-muted fs-13 mb-1">实例补偿详情</p><h2 class="h4 fw-semibold mb-0" id="service-compensation-detail-title">补偿批次</h2></div><button class="admin-modal-close position-static flex-shrink-0" id="service-compensation-detail-close" type="button" aria-label="关闭补偿详情"><i class="mdi mdi-close" aria-hidden="true"></i></button></header>
<div class="admin-instance-drawer-body"><p class="alert alert-info" id="service-compensation-detail-state" role="status" aria-live="polite">正在读取补偿详情…</p><div id="service-compensation-detail-body"></div></div>
<footer class="admin-instance-drawer-footer"><span class="text-muted fs-12">补偿记录为审计账本;效果未知或投影冲突不会自动重复加时。</span><a class="btn btn-light" href="/admin/operations">查看任务中心</a></footer>
</dialog>
<script id="admin-service-compensation-bootstrap" type="application/json">{$service_compensation_bootstrap_json|default:'null' nofilter}</script>
<script type="module" src="/cloud/admin-service-compensations.js?v={$venix_asset_version}"></script>
{include file='admin/static_footer.tpl'}

@ -170,6 +170,7 @@
<li><a class="{if $admin_active|default:'' == 'cloud-rescue'}active{/if}" href="/admin/cloud/rescue"><i class="mdi mdi-lifebuoy"></i><span>救援镜像</span></a></li>
<li><a class="{if $admin_active|default:'' == 'cloud-instances'}active{/if}" href="/admin/cloud/instances"><i class="mdi mdi-server"></i><span>虚拟机管理</span></a></li>
<li><a class="{if $admin_active|default:'' == 'maintenance-notices'}active{/if}" href="/admin/maintenance-notices"><i class="mdi mdi-email-alert-outline"></i><span>维护通知</span></a></li>
<li><a class="{if $admin_active|default:'' == 'service-compensations'}active{/if}" href="/admin/service-compensations"><i class="mdi mdi-clock-plus-outline"></i><span>实例补偿</span></a></li>
<li><a class="{if $admin_active|default:'' == 'cloud-operations'}active{/if}" href="/admin/operations"><i class="mdi mdi-clipboard-pulse-outline"></i><span>系统运行与异常任务</span></a></li>

@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
{assign var=venix_asset_version value='2026110601' scope='global'}
{assign var=venix_asset_version value='2026110602' scope='global'}

@ -15,7 +15,7 @@ $assert = static function (bool $condition, string $message): void {
};
$assert(is_string($assets)
&& str_contains($assets, "venix_asset_version value='2026110601'")
&& str_contains($assets, "venix_asset_version value='2026110602'")
&& is_string($cloudShell)
&& str_contains($cloudShell, '/cloud/app.js?v={$venix_asset_version}'),
'The cloud application entry must use the shared Venix asset version.');

@ -0,0 +1,88 @@
<?php
$root = dirname(__DIR__);
$read = static function (string $path) use ($root): string {
$source = file_get_contents($root . '/' . $path);
if (!is_string($source)) {
throw new RuntimeException('Unable to read ' . $path);
}
return $source;
};
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$routes = $read('config/routes.php');
$controller = $read('app/Controllers/Admin/CloudPageController.php');
$template = $read(
'resources/views/venix/admin/cloud/service_compensations.tpl'
);
$sidebar = $read('resources/views/venix/admin/static_header.tpl');
$assets = $read('resources/views/venix/layout_assets.tpl');
$script = $read('public/cloud/admin-service-compensations.js');
$instanceDetail = $read('public/cloud/admin-instance-detail.js');
$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, "'can_manage' => (bool)")
&& str_contains($controller, "'private, no-store'")
&& str_contains($controller, 'JSON_HEX_TAG | JSON_HEX_AMP'),
'The compensation page route lost administrator access, capability, or private-bootstrap boundaries.');
$assert(str_contains($template, 'data-admin-service-compensations')
&& str_contains($template, 'data-can-manage=')
&& str_contains($template,
'{else}' . "\n" . ' <section class="card mb-3"')
&& str_contains($template, '<fieldset>')
&& str_contains($template, 'id="service-compensation-scope-type"')
&& 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-incident-key"')
&& str_contains($template, 'id="service-compensation-value"')
&& str_contains($template, 'id="service-compensation-unit"')
&& str_contains($template, 'id="service-compensation-reason"')
&& str_contains($template, 'id="service-compensation-incident-start"')
&& str_contains($template, 'id="service-compensation-incident-end"')
&& str_contains($template, 'id="service-compensation-notify"')
&& str_contains($template, 'id="service-compensation-preview"')
&& str_contains($template, 'id="service-compensation-create"')
&& str_contains($template, 'admin-service-compensation-bootstrap')
&& str_contains($template, ' nofilter}</script>')
&& str_contains($template,
'/cloud/admin-service-compensations.js?v={$venix_asset_version}')
&& str_contains($sidebar, 'href="/admin/service-compensations"'),
'The compensation page lost its reviewed scope form, read-only capability gate, bootstrap, or navigation entry.');
$assert(str_contains($script, "import(versionedModuleUrl('./admin-instance-actions.js'))")
&& str_contains($script, 'createAdminInstanceActions(')
&& str_contains($script, 'actions.commit(')
&& str_contains($script,
"'/api/v1/admin/service-compensations/preview'")
&& str_contains($script,
"'/api/v1/admin/service-compensations'")
&& str_contains($script, 'audience_digest: state.preview.audience_digest')
&& str_contains($script, 'mutationMayHaveApplied')
&& str_contains($script, 'textContent')
&& str_contains($script, 'replaceChildren')
&& !str_contains($script, 'innerHTML')
&& !str_contains($script, 'window.confirm')
&& preg_match('/(?<![A-Za-z0-9_.])confirm\s*\(/', $script) !== 1
&& !preg_match('/\bfetch\s*\(/', $script),
'Compensation mutations must use the shared idempotent runtime and text-only DOM rendering.');
$assert(str_contains($instanceDetail, '补偿可用时间')
&& str_contains($instanceDetail,
'/admin/service-compensations?scope_type=instance&instance_id=')
&& str_contains($instanceDetail, 'encodeURIComponent(vm.id)'),
'The instance service and billing surface lost its scoped compensation shortcut.');
$assert(str_contains($assets,
"venix_asset_version value='2026110602'"),
'The compensation administrator assets must publish the requested cache version.');
echo "Service compensation administrator page contracts passed.\n";
Loading…
Cancel
Save