fix(admin): make operation summaries actionable

go
codex 2 weeks ago
parent 9fa30d659e
commit 548b4b8218

@ -23,25 +23,32 @@ final class CloudAdminOperationsService
// request and no mutation replay can occur here.
CloudWorkerService::expireDueJobs(100);
$filters = self::filters($input);
$query = self::query();
self::applyFilters($query, $filters);
$scope = self::query();
self::applyScopeFilters($scope, $filters);
$lockedSql = self::resourceLockedSql('cloud_jobs');
$summaryRow = (clone $query)->selectRaw(
$attentionSql = self::attentionSql('cloud_jobs');
$summaryRow = (clone $scope)->selectRaw(
"COUNT(*) AS total, "
. "COALESCE(SUM(CASE WHEN cloud_jobs.phase <> 'terminal' THEN 1 ELSE 0 END), 0) AS active, "
. "COALESCE(SUM(CASE WHEN cloud_jobs.phase = 'terminal' AND cloud_jobs.outcome = 'succeeded' THEN 1 ELSE 0 END), 0) AS succeeded, "
. "COALESCE(SUM(CASE WHEN cloud_jobs.phase = 'terminal' AND cloud_jobs.outcome = 'failed' THEN 1 ELSE 0 END), 0) AS failed, "
. 'COALESCE(SUM(CASE WHEN ' . $attentionSql
. ' THEN 1 ELSE 0 END), 0) AS attention, '
. 'COALESCE(SUM(CASE WHEN ' . $lockedSql
. ' THEN 1 ELSE 0 END), 0) AS unresolved_effect'
. ' THEN 1 ELSE 0 END), 0) AS locked'
)->first();
$summary = [];
foreach (['total', 'active', 'succeeded', 'failed',
'unresolved_effect'] as $key) {
foreach (['total', 'active', 'succeeded', 'failed', 'attention',
'locked'] as $key) {
$summary[$key] = max(0, (int) ($summaryRow?->$key ?? 0));
}
$pages = max(1, (int) ceil($summary['total']
$selectedTotal = $summary[$filters['status'] === 'all'
? 'total' : $filters['status']];
$pages = max(1, (int) ceil($selectedTotal
/ $filters['per_page']));
$filters['page'] = min($filters['page'], $pages);
$query = clone $scope;
self::applyStatusFilter($query, $filters['status']);
$records = self::select($query)->orderByDesc('cloud_jobs.id')
->offset(($filters['page'] - 1) * $filters['per_page'])
->limit($filters['per_page'])->get();
@ -59,19 +66,20 @@ final class CloudAdminOperationsService
'region' => (string) $host->region,
];
}
$from = $summary['total'] === 0 ? 0
$from = $selectedTotal === 0 ? 0
: ($filters['page'] - 1) * $filters['per_page'] + 1;
return [
'items' => $items,
'pagination' => [
'page' => $filters['page'],
'per_page' => $filters['per_page'],
'total' => $summary['total'],
'total' => $selectedTotal,
'total_pages' => $pages,
'from' => $from,
'to' => $from === 0 ? 0 : $from + count($items) - 1,
],
'summary' => $summary,
'summary_links' => self::summaryLinks($filters),
'filters' => $filters,
'hosts' => $hosts,
'kinds' => CloudOperationCatalog::kindOptions(),
@ -364,25 +372,22 @@ final class CloudAdminOperationsService
);
}
private static function applyFilters($query, array $filters): void
private static function applyStatusFilter($query, string $status): void
{
if ($filters['status'] === 'locked') {
if ($status === 'locked') {
$query->whereRaw(self::resourceLockedSql('cloud_jobs'));
} elseif ($filters['status'] === 'attention') {
$query->where(static function ($attention): void {
$attention->where(static function ($failed): void {
$failed->where('cloud_jobs.phase', 'terminal')
->where('cloud_jobs.outcome', 'failed');
})->orWhereRaw(
CloudJobRecoverySql::pendingSql('cloud_jobs')
);
});
} elseif ($filters['status'] === 'active') {
} elseif ($status === 'attention') {
$query->whereRaw(self::attentionSql('cloud_jobs'));
} elseif ($status === 'active') {
$query->where('cloud_jobs.phase', '<>', 'terminal');
} elseif ($filters['status'] !== 'all') {
} elseif ($status !== 'all') {
$query->where('cloud_jobs.phase', 'terminal')
->where('cloud_jobs.outcome', $filters['status']);
->where('cloud_jobs.outcome', $status);
}
}
private static function applyScopeFilters($query, array $filters): void
{
if ($filters['kind'] !== '') {
$query->where('cloud_jobs.kind', $filters['kind']);
}
@ -413,6 +418,41 @@ final class CloudAdminOperationsService
}
}
private static function attentionSql(string $table): string
{
if (preg_match('/^[a-z_][a-z0-9_]*$/D', $table) !== 1) {
throw new \InvalidArgumentException('Invalid task table alias');
}
return '((' . $table . ".phase = 'terminal' AND "
. $table . ".outcome = 'failed') OR "
. CloudJobRecoverySql::pendingSql($table) . ')';
}
/** @return array<string,string> */
private static function summaryLinks(array $filters): array
{
$base = [];
foreach (['q', 'kind', 'host_id'] as $key) {
if ($filters[$key] !== null && $filters[$key] !== '') {
$base[$key] = (string) $filters[$key];
}
}
if ($filters['per_page'] !== 20) {
$base['per_page'] = (string) $filters['per_page'];
}
$links = [];
foreach (['all', 'active', 'attention', 'failed', 'locked'] as $status) {
$query = $base;
if ($status !== 'all') {
$query = ['status' => $status] + $query;
}
$encoded = http_build_query($query, '', '&', PHP_QUERY_RFC3986);
$links[$status] = '/admin/operations'
. ($encoded === '' ? '' : '?' . $encoded);
}
return $links;
}
private static function row($job, bool $canManage = false): array
{
$completed = (string) $job->phase === 'terminal';

@ -173,7 +173,10 @@ function payloadUrl(page) {
function shownFilters() {
if (!state.page) return '尚未读取任务数据。';
const filters = state.page.filters || {};
const labels = [({ all: '全部状态', active: '执行中', failed: '已失败', succeeded: '已成功' })[filters.status] || filters.status];
const labels = [({
all: '全部状态', attention: '需要处理', locked: '资源已锁定',
active: '执行中', failed: '已失败', succeeded: '已成功',
})[filters.status] || filters.status];
if (filters.kind) labels.push((state.page.kinds || []).find(item => item.value === filters.kind)?.label || filters.kind);
if (filters.host_id) labels.push((state.page.hosts || []).find(item => String(item.id) === String(filters.host_id))?.name || `宿主机 #${filters.host_id}`);
if (filters.q) labels.push(`关键词「${filters.q}」`);
@ -254,21 +257,41 @@ function renderPagination() {
}
function summaryValue(summary, key) {
const field = key === 'locked' ? 'unresolved_effect' : key;
const value = summary[field];
const value = summary[key];
const number = Number(value);
return Number.isFinite(number) && number >= 0 ? number.toLocaleString('zh-CN') : '—';
}
function summaryHref(page, status) {
const fallback = new URL('/admin/operations', location.origin);
if (status !== 'all') fallback.searchParams.set('status', status);
try {
const candidate = new URL(page.summary_links?.[status] || fallback.href, location.origin);
if (candidate.origin === location.origin && candidate.pathname === '/admin/operations') {
return candidate.pathname + candidate.search;
}
} catch {}
return fallback.pathname + fallback.search;
}
function applyPage(page, replaceRows = true) {
if (!Array.isArray(page?.items) || !page.pagination || !page.filters || !page.summary) {
if (!Array.isArray(page?.items) || !page.pagination || !page.filters
|| !page.summary || !page.summary_links) {
throw new Error('任务数据格式无效,请刷新。');
}
state.page = page; state.loadedUrl = payloadUrl(page);
syncOptions(page); readForm(state.loadedUrl);
for (const key of ['total', 'active', 'failed', 'locked']) {
for (const key of ['total', 'active', 'attention', 'failed', 'locked']) {
byId(`operations-summary-${key}`).textContent = summaryValue(page.summary, key);
}
for (const link of root.querySelectorAll('[data-operation-summary-status]')) {
const status = link.dataset.operationSummaryStatus;
const active = status === page.filters.status;
link.href = summaryHref(page, status);
link.classList.toggle('is-active', active);
if (active) link.setAttribute('aria-current', 'page');
else link.removeAttribute('aria-current');
}
if (replaceRows) renderRows();
byId('operations-shown-filters').textContent = shownFilters();
renderPagination();
@ -777,6 +800,13 @@ if (root) {
});
}
root.addEventListener('click', event => {
const summary = event.target.closest('[data-operation-summary-status]');
if (summary && event.button === 0 && !event.ctrlKey && !event.metaKey
&& !event.shiftKey && !event.altKey && !event.defaultPrevented) {
event.preventDefault();
void loadPage(new URL(summary.href, location.origin));
return;
}
const button = event.target.closest('[data-operation-detail]');
if (button) void openDetail(button.dataset.operationDetail, button);
});

@ -393,6 +393,26 @@ html.admin-sidebar-scroll-locked {
min-height: 116px;
}
[data-admin-operations] .admin-operations-summary-link {
color: inherit;
text-decoration: none;
transition: border-color .16s ease, box-shadow .16s ease, transform .16s ease;
}
[data-admin-operations] .admin-operations-summary-link:hover,
[data-admin-operations] .admin-operations-summary-link:focus-visible {
border-color: rgba(24, 168, 127, .45);
box-shadow: 0 10px 24px rgba(0, 32, 48, .08);
color: inherit;
outline: 0;
transform: translateY(-1px);
}
[data-admin-operations] .admin-operations-summary-link.is-active {
border-color: #18a87f;
box-shadow: 0 0 0 3px rgba(24, 168, 127, .12);
}
/* VM inventory keeps the Venix visual language while exposing common filters first. */
[data-admin-instances] .admin-instance-summary-card {
appearance: none;

@ -1,24 +1,24 @@
{assign var=admin_title value='系统运行与任务记录'}
{assign var=admin_title value='系统运行与异常任务'}
{assign var=admin_active value='cloud-operations'}
{include file='admin/static_header.tpl'}
{assign var=operations_filters value=$operations_page.filters|default:[]}
{assign var=operations_statuses value=['all'=>'全部状态','locked'=>'资源已锁定','active'=>'执行中','succeeded'=>'已成功','failed'=>'已失败']}
{assign var=operations_statuses value=['all'=>'全部状态','attention'=>'需要处理','locked'=>'资源已锁定','active'=>'执行中','succeeded'=>'已成功','failed'=>'已失败']}
<main data-admin-operations 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">任务只展示执行中、成功或失败。失败且效果尚未确认时,资源保持安全锁定;支持恢复的 Agent 任务会持续自动核对,且绝不会重放原操作。</p></div>
<div class="flex-grow-1"><h1 class="fs-20 fw-semibold mb-1">系统运行与异常任务</h1><p class="text-muted mb-0">任务只展示执行中、成功或失败。失败且效果尚未确认时,资源保持安全锁定;支持恢复的 Agent 任务会持续自动核对,且绝不会重放原操作。</p></div>
<div class="admin-checkout-actions"><span class="admin-config-status {if $operations_error|default:''}is-error{else}is-success{/if}" id="operations-notice" role="status" aria-live="polite">{if $operations_error|default:''}{$operations_error|escape}{else}已读取 {$operations_page.pagination.total|default:0|escape} 条任务{/if}</span><button class="btn btn-light" id="operations-refresh" type="button"><i class="mdi mdi-refresh me-1" aria-hidden="true"></i>刷新任务</button></div>
</div>
<section class="card mb-3" aria-labelledby="operations-health-title">
<div class="card-header d-flex justify-content-between align-items-center gap-2 flex-wrap"><div><h2 class="h5 card-title mb-1" id="operations-health-title">运行状态</h2><p class="text-muted fs-13 mb-0" id="operations-health-state" role="status" aria-live="polite">尚未检查。运行状态单独加载,不影响任务列表。</p></div><button class="btn btn-light btn-sm" id="operations-health-refresh" type="button">检查状态</button></div>
<div class="card-body"><div class="row g-3" id="operations-health-body"><p class="text-muted mb-0">Agent API 连通不代表所有宿主机正常;未收到的后台心跳会标为未知。</p></div></div>
</section>
<section class="row g-3 mb-3 admin-billing-summary" aria-label="当前筛选任务摘要">
{foreach ['total'=>['任务总数','mdi-format-list-bulleted','primary'],'active'=>['执行中','mdi-progress-clock','primary'],'failed'=>['失败任务','mdi-alert-circle-outline','danger'],'locked'=>['资源已锁定','mdi-lock-alert-outline','warning']] as $key=>$card}
<div class="col-6 col-xl-3"><article class="card admin-stat-card"><div class="card-body d-flex align-items-center justify-content-between gap-2"><div><h2 class="text-muted fs-14 fw-normal mb-1">{$card[0]}</h2><strong class="admin-stat-value" id="operations-summary-{$key}">{if !$operations_page}—{elseif $key == 'locked'}{$operations_page.summary.unresolved_effect|default:0|escape}{else}{$operations_page.summary[$key]|default:0|escape}{/if}</strong></div><span class="admin-stat-icon text-{$card[2]}"><i class="mdi {$card[1]}" aria-hidden="true"></i></span></div></article></div>
<section class="row g-3 mb-3 admin-billing-summary" aria-label="当前范围任务状态摘要">
{foreach ['total'=>['all','全部任务','mdi-format-list-bulleted','primary'],'active'=>['active','执行中','mdi-progress-clock','primary'],'attention'=>['attention','需要处理','mdi-alert-circle-outline','danger'],'failed'=>['failed','已失败','mdi-close-circle-outline','danger'],'locked'=>['locked','资源已锁定','mdi-lock-alert-outline','warning']] as $key=>$card}
<div class="col-6 col-xl"><a class="card admin-stat-card admin-operations-summary-link{if $operations_filters.status|default:'all' == $card[0]} is-active{/if}" data-operation-summary-status="{$card[0]|escape}" href="{if $operations_page}{$operations_page.summary_links[$card[0]]|escape}{elseif $card[0] == 'all'}/admin/operations{else}/admin/operations?status={$card[0]|escape}{/if}" {if $operations_filters.status|default:'all' == $card[0]}aria-current="page"{/if}><span class="card-body d-flex align-items-center justify-content-between gap-2"><span><span class="text-muted fs-14 fw-normal mb-1 d-block">{$card[1]}</span><strong class="admin-stat-value" id="operations-summary-{$key}">{if !$operations_page}—{else}{$operations_page.summary[$key]|default:0|escape}{/if}</strong></span><span class="admin-stat-icon text-{$card[3]}"><i class="mdi {$card[2]}" aria-hidden="true"></i></span></span></a></div>
{/foreach}
</section>
<section class="card mb-3 admin-billing-filter" aria-labelledby="operations-filter-title">
<div class="card-header"><h2 class="h5 card-title mb-1" id="operations-filter-title">查找任务</h2><p class="text-muted fs-13 mb-0">摘要和列表均按筛选条件统计。自动核对只读取原任务证据,不会重新提交原操作。</p></div>
<div class="card-header"><h2 class="h5 card-title mb-1" id="operations-filter-title">查找任务</h2><p class="text-muted fs-13 mb-0">摘要保留关键词、任务类型和宿主机范围,并按状态分别统计;列表只显示当前选中的状态。自动核对只读取原任务证据,不会重新提交原操作。</p></div>
<div class="card-body"><form class="row g-2 align-items-end" id="operations-filter" method="get" action="/admin/operations">
<label class="col-xl-4 col-lg-6" for="operations-query"><span class="form-label d-block">关键词</span><input class="form-control" type="search" id="operations-query" name="q" maxlength="80" value="{$operations_filters.q|default:''|escape}" placeholder="任务 ID / 操作标识 / 实例名称或 UUID"></label>
<label class="col-xl-2 col-lg-3 col-6" for="operations-status"><span class="form-label d-block">任务状态</span><select class="form-select" id="operations-status" name="status">{foreach $operations_statuses as $value=>$label}<option value="{$value|escape}" {if $operations_filters.status|default:'all' == $value}selected{/if}>{$label|escape}</option>{/foreach}</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='2026103121' scope='global'}
{assign var=venix_asset_version value='2026103122' scope='global'}

@ -78,7 +78,7 @@ $assert(str_contains($combined, "request.open('PUT', parsed.href, true)")
"'/api/v1/admin/cloud-template-imports'")
&& !str_contains($combined, '/admin/cloud-templates/upload?'),
'The cloud-template file upload must use credential-free direct multipart PUT.');
$assert(preg_match("/venix_asset_version value='2026103121'/", $assets) === 1,
$assert(preg_match("/venix_asset_version value='2026103122'/", $assets) === 1,
'Shared administrator assets must use the current cache version.');
echo "Administrator shared action runtime contract passed.\n";

@ -26,7 +26,11 @@ assert.match(source, /task\.completed === true/);
assert.match(source, /new Set\(\['succeeded', 'failed'\]\)/);
assert.match(source, /label: '协议错误'/);
assert.match(source, /effect_may_have_applied === true/);
assert.match(source, /unresolved_effect/);
assert.match(source, /\['total', 'active', 'attention', 'failed', 'locked'\]/);
assert.match(source, /data-operation-summary-status/);
assert.match(source, /summaryHref\(page, status\)/);
assert.match(template, /'attention'=>'需要处理'/);
assert.match(template, /系统运行与异常任务/);
assert.match(source, /资源已安全锁定,需管理员人工处理/);
assert.match(source, /job\.kind === 'host_storage_configure'/);
assert.match(source, /job\.effect_scope === 'partial'/);

@ -78,7 +78,14 @@ $page = [
'items' => $items,
'pagination' => ['page' => 1, 'per_page' => 20, 'total' => 44, 'total_pages' => 3, 'from' => 1, 'to' => 4],
'summary' => ['total' => 44, 'active' => 1, 'succeeded' => 20,
'failed' => 22, 'unresolved_effect' => 1],
'failed' => 22, 'attention' => 24, 'locked' => 1],
'summary_links' => [
'all' => '/admin/operations',
'active' => '/admin/operations?status=active',
'attention' => '/admin/operations?status=attention',
'failed' => '/admin/operations?status=failed',
'locked' => '/admin/operations?status=locked',
],
'filters' => ['status' => 'all', 'kind' => '', 'host_id' => null, 'q' => '', 'page' => 1, 'per_page' => 20],
'hosts' => [['id' => '7', 'name' => '香港宿主机 A', 'region' => 'HongKong']],
'kinds' => [['value' => 'create', 'label' => '创建实例'], ['value' => 'reinstall', 'label' => '重装系统'], ['value' => 'expiry_delete', 'label' => '到期清理']],
@ -152,6 +159,12 @@ $assert($xpath->query('//select[@name="status"]/option[@value="all" and @selecte
'The default task list must expose all active and terminal receipts.');
$assert($xpath->query('//select[@name="status"]/option[@value="locked" and contains(.,"资源已锁定")]')->length === 1,
'The task list must expose the exact resource-locked filter.');
$assert($xpath->query('//select[@name="status"]/option[@value="attention" and contains(.,"需要处理")]')->length === 1,
'The task list must expose the actionable attention filter.');
$assert($xpath->query('//*[@data-operation-summary-status]')->length === 5
&& $xpath->query('//*[@data-operation-summary-status="all" and @aria-current="page" and @href="/admin/operations"]')->length === 1
&& $xpath->query('//*[@data-operation-summary-status="attention" and @href="/admin/operations?status=attention"]')->length === 1,
'Task summaries must be progressively enhanced links with one active state.');
$assert($xpath->query('//dialog[@data-admin-instance-drawer and @id="operation-detail"]')->length === 1,
'Task detail must reuse the existing drawer.');
$assert($xpath->query('//*[@id="operations-health-body"]//p')->length === 1
@ -173,12 +186,22 @@ $smarty->assign('admin_can_manage', true);
$filtered = $page;
$filtered['filters'] = array_replace($page['filters'], ['status' => 'failed', 'kind' => 'create', 'host_id' => '7', 'q' => 'sample']);
$filtered['pagination']['per_page'] = 50;
$filtered['summary_links'] = [
'all' => '/admin/operations?q=sample&kind=create&host_id=7&per_page=50',
'active' => '/admin/operations?status=active&q=sample&kind=create&host_id=7&per_page=50',
'attention' => '/admin/operations?status=attention&q=sample&kind=create&host_id=7&per_page=50',
'failed' => '/admin/operations?status=failed&q=sample&kind=create&host_id=7&per_page=50',
'locked' => '/admin/operations?status=locked&q=sample&kind=create&host_id=7&per_page=50',
];
$dom->loadHTML('<?xml encoding="UTF-8">' . $render($filtered));
$xpath = new DOMXPath($dom);
foreach (['status' => 'failed', 'kind' => 'create', 'host_id' => '7', 'per_page' => '50'] as $name => $value) {
$assert($xpath->query('//select[@name="' . $name . '"]/option[@value="' . $value . '" and @selected]')->length === 1,
'SSR filter selection missing: ' . $name);
}
$assert($xpath->query('//*[@data-operation-summary-status="failed" and @aria-current="page"]')->length === 1
&& $xpath->query('//*[@data-operation-summary-status="attention" and contains(@href,"status=attention") and contains(@href,"q=sample")]')->length === 1,
'Filtered summary navigation lost its active state or scope filters.');
$unsafe = $page;
$unsafe['items'][0]['instance_name'] = '</script><img src=x onerror=alert(1)>';

@ -217,7 +217,7 @@ namespace {
$assert($ids($all['items']) === [6, 5, 4, 3, 2, 1]
&& $all['summary'] === [
'total' => 6, 'active' => 1, 'succeeded' => 1,
'failed' => 4, 'unresolved_effect' => 1,
'failed' => 4, 'attention' => 4, 'locked' => 1,
], 'Operations inventory did not expose active and terminal states exactly.');
foreach ([
'active' => [1], 'succeeded' => [2],
@ -225,7 +225,9 @@ namespace {
'locked' => [3],
] as $status => $expected) {
$page = Operations::page($admin, ['status' => $status]);
$assert($ids($page['items']) === $expected,
$assert($ids($page['items']) === $expected
&& $page['summary'] === $all['summary']
&& $page['pagination']['total'] === count($expected),
'Status filter diverged from task receipt state: ' . $status);
}
$unsafeIncident = array_values(array_filter(
@ -243,6 +245,19 @@ namespace {
['status' => 'all', 'q' => $search])['summary']['total'] === 5,
'Bound task search failed for ' . $search);
}
$linked = Operations::page($admin, [
'status' => 'failed', 'kind' => 'create', 'host_id' => '1',
'q' => "tenant's", 'per_page' => 50, 'page' => 3,
]);
parse_str((string) parse_url(
$linked['summary_links']['attention'], PHP_URL_QUERY
), $linkedQuery);
$assert($linkedQuery === [
'status' => 'attention', 'q' => "tenant's", 'kind' => 'create',
'host_id' => '1', 'per_page' => '50',
]
&& !array_key_exists('page', $linkedQuery),
'Summary navigation did not preserve scope filters and reset pagination.');
$assert(Operations::page($admin,
['status' => 'all', 'q' => "' OR 1=1 --"])['items'] === [],
'Task search accepted SQL injection text as a predicate.');
@ -356,7 +371,7 @@ namespace {
$recoveryInventory = Operations::page($admin, ['status' => 'all']);
$assert($recoveryInventory['summary'] === [
'total' => 12, 'active' => 1, 'succeeded' => 6,
'failed' => 5, 'unresolved_effect' => 7,
'failed' => 5, 'attention' => 10, 'locked' => 7,
]
&& $ids(Operations::page($admin, ['status' => 'attention'])['items'])
=== [12, 11, 10, 9, 8, 7, 6, 5, 4, 3]

Loading…
Cancel
Save