You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
314 lines
12 KiB
JavaScript
314 lines
12 KiB
JavaScript
const filterNames = ['q', 'status', 'kind', 'host_id', 'per_page'];
|
|
const columns = ['任务', '关联实例', '用户', '宿主机', '状态', '执行信息', '更新与异常', '操作'];
|
|
|
|
export function mountOperationsDirectory({ root, transport, presentation, onOpenDetail }) {
|
|
const { presentOperation, operationFailureText, operationText, operationDate } = presentation;
|
|
const byId = id => document.getElementById(id);
|
|
const state = {
|
|
page: null,
|
|
loadedUrl: null,
|
|
request: null,
|
|
serial: 0,
|
|
loading: false,
|
|
};
|
|
|
|
function el(tag, className = '', content) {
|
|
const node = document.createElement(tag);
|
|
node.className = className;
|
|
if (content !== undefined) node.textContent = String(content);
|
|
return node;
|
|
}
|
|
|
|
function stack(primary, ...secondary) {
|
|
const node = el('span', 'admin-checkout-user');
|
|
node.append(primary instanceof Node ? primary : el('strong', '', primary));
|
|
for (const value of secondary.filter(Boolean)) {
|
|
node.append(value instanceof Node ? value : el('span', '', value));
|
|
}
|
|
return node;
|
|
}
|
|
|
|
function notify(message, error = false) {
|
|
const node = byId('operations-notice');
|
|
node.textContent = message;
|
|
node.className = `admin-config-status ${error ? 'is-error' : 'is-success'}`;
|
|
node.setAttribute('role', error ? 'alert' : 'status');
|
|
}
|
|
|
|
function historyData(changes = {}) {
|
|
return {
|
|
...(history.state && typeof history.state === 'object' ? history.state : {}),
|
|
...changes,
|
|
};
|
|
}
|
|
|
|
function listUrl(input = new URL(location.href)) {
|
|
const url = new URL('/admin/operations', location.origin);
|
|
for (const key of [...filterNames, 'page']) {
|
|
const value = input.searchParams.get(key);
|
|
if (value && !(key === 'status' && value === 'all')
|
|
&& !(key === 'page' && value === '1')) {
|
|
url.searchParams.set(key, value);
|
|
}
|
|
}
|
|
return url;
|
|
}
|
|
|
|
function formUrl() {
|
|
const url = new URL('/admin/operations', location.origin);
|
|
const form = byId('operations-filter');
|
|
for (const key of filterNames) {
|
|
const value = form.elements.namedItem(key).value.trim();
|
|
if (value && !(key === 'status' && value === 'all')) {
|
|
url.searchParams.set(key, value);
|
|
}
|
|
}
|
|
return url;
|
|
}
|
|
|
|
function readForm(url) {
|
|
const form = byId('operations-filter');
|
|
for (const key of filterNames) {
|
|
const control = form.elements.namedItem(key);
|
|
const value = url.searchParams.get(key)
|
|
|| ({ status: 'all', per_page: '20' })[key] || '';
|
|
if (control instanceof HTMLSelectElement && value
|
|
&& !Array.from(control.options).some(option => option.value === value)) {
|
|
control.add(new Option(value, value));
|
|
}
|
|
control.value = value;
|
|
}
|
|
}
|
|
|
|
function syncOptions(page) {
|
|
const kind = byId('operations-kind');
|
|
kind.replaceChildren(new Option('全部类型', ''));
|
|
for (const item of page.kinds || []) kind.add(new Option(item.label, item.value));
|
|
const host = byId('operations-host');
|
|
host.replaceChildren(new Option('全部宿主机', ''));
|
|
for (const item of page.hosts || []) {
|
|
host.add(new Option(`${item.name}${item.region ? ` · ${item.region}` : ''}`, item.id));
|
|
}
|
|
}
|
|
|
|
function payloadUrl(page) {
|
|
const url = new URL('/admin/operations', location.origin);
|
|
for (const key of [...filterNames, 'page']) {
|
|
const value = key === 'page' || key === 'per_page'
|
|
? page.pagination[key] : page.filters?.[key];
|
|
if (value !== null && value !== undefined && value !== '') {
|
|
url.searchParams.set(key, String(value));
|
|
}
|
|
}
|
|
return listUrl(url);
|
|
}
|
|
|
|
function shownFilters() {
|
|
if (!state.page) return '尚未读取任务数据。';
|
|
const filters = state.page.filters || {};
|
|
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}」`);
|
|
return `已显示:${labels.filter(Boolean).join(' · ')} · 第 ${state.page.pagination.page} 页。`;
|
|
}
|
|
|
|
function renderRows() {
|
|
const body = byId('operations-body');
|
|
body.replaceChildren();
|
|
for (const job of state.page.items) {
|
|
const view = presentOperation(job);
|
|
const tr = el('tr');
|
|
tr.dataset.operationId = String(job.id || '');
|
|
const detailButton = el('button', 'btn btn-primary btn-sm', '查看详情');
|
|
detailButton.type = 'button';
|
|
detailButton.dataset.operationDetail = String(job.id || '');
|
|
const actions = el('div', 'd-flex flex-wrap gap-1');
|
|
actions.append(detailButton);
|
|
const warning = operationFailureText(job, view);
|
|
const cells = [
|
|
stack(`#${operationText(job.id)} · ${operationText(job.kind_label || job.title || job.display?.kind || job.kind, '后台任务')}`, job.created_at ? `创建 ${operationDate(job.created_at)}` : ''),
|
|
stack(operationText(job.instance_name, '无关联实例'), job.instance_id ? `实例 #${job.instance_id}` : '', job.order_id ? `订单 #${job.order_id}` : ''),
|
|
stack(`操作人:${operationText(job.actor_name)}${job.actor_id ? ` #${job.actor_id}` : ''}`, job.owner_id ? `所属:${operationText(job.owner_name)} #${job.owner_id}` : ''),
|
|
stack(operationText(job.host_name), operationText(job.region, '地区未记录')),
|
|
stack(el('strong', view.tone, view.label), warning ? el('span', 'text-danger', warning) : ''),
|
|
stack(operationText(job.operation_id, '无操作标识'), operationText(job.phase, view.terminal ? '已终结' : '后台执行中')),
|
|
stack(job.updated_at ? operationDate(job.updated_at) : '更新时间未记录', job.error && view.status === 'failed' ? el('span', 'text-danger', job.error) : ''),
|
|
actions,
|
|
];
|
|
cells.forEach((content, index) => {
|
|
const cell = el('td');
|
|
cell.dataset.label = columns[index];
|
|
cell.append(content);
|
|
tr.append(cell);
|
|
});
|
|
body.append(tr);
|
|
}
|
|
if (!state.page.items.length) {
|
|
const row = el('tr');
|
|
const cell = el('td', 'text-center text-muted py-4', '没有符合条件的任务。');
|
|
cell.colSpan = columns.length;
|
|
row.append(cell);
|
|
body.append(row);
|
|
}
|
|
}
|
|
|
|
function renderPagination() {
|
|
const page = state.page?.pagination;
|
|
byId('operations-count').textContent = page ? `共 ${page.total} 条` : '数据未获取';
|
|
byId('operations-pagination').hidden = !page || !page.total;
|
|
byId('operations-page-label').textContent = page
|
|
? `第 ${page.page} / ${page.total_pages} 页 · 共 ${page.total} 条`
|
|
: '任务数据暂不可用';
|
|
byId('operations-previous').disabled = state.loading || !page || page.page <= 1;
|
|
byId('operations-next').disabled = state.loading || !page
|
|
|| page.page >= page.total_pages;
|
|
byId('operations-refresh').disabled = state.loading;
|
|
byId('operations-body').setAttribute('aria-busy', String(state.loading));
|
|
}
|
|
|
|
function summaryValue(summary, key) {
|
|
const number = Number(summary[key]);
|
|
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 || !page.summary_links) {
|
|
throw new Error('任务数据格式无效,请刷新。');
|
|
}
|
|
state.page = page;
|
|
state.loadedUrl = payloadUrl(page);
|
|
syncOptions(page);
|
|
readForm(state.loadedUrl);
|
|
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();
|
|
}
|
|
|
|
async function loadPage(input, historyMode = 'push') {
|
|
const url = listUrl(input);
|
|
state.request?.abort('replaced');
|
|
const controller = new AbortController();
|
|
state.request = controller;
|
|
const serial = ++state.serial;
|
|
state.loading = true;
|
|
renderPagination();
|
|
notify('正在读取任务记录…');
|
|
try {
|
|
const payload = await transport.read(`/api/v1/admin/operations${url.search}`, {
|
|
signal: controller.signal,
|
|
timeoutMs: 15000,
|
|
});
|
|
if (controller.signal.aborted || serial !== state.serial) return;
|
|
applyPage(payload);
|
|
if (historyMode === 'push' && state.loadedUrl.href !== location.href) {
|
|
history.pushState(historyData(), '', state.loadedUrl);
|
|
}
|
|
notify(`已读取 ${payload.pagination.total} 条任务${payload.generated_at ? ` · ${operationDate(payload.generated_at)}` : ''}`);
|
|
} catch (error) {
|
|
if ((controller.signal.aborted && controller.signal.reason !== 'timeout')
|
|
|| serial !== state.serial) return;
|
|
notify(`${error.message}${state.page ? ' 已保留上次读取的任务记录。' : ''}`, true);
|
|
} finally {
|
|
if (serial === state.serial) {
|
|
state.loading = false;
|
|
state.request = null;
|
|
renderPagination();
|
|
}
|
|
}
|
|
}
|
|
|
|
function refresh() {
|
|
return loadPage(listUrl(), 'none');
|
|
}
|
|
|
|
function restore() {
|
|
const url = listUrl();
|
|
readForm(url);
|
|
return loadPage(url, 'none');
|
|
}
|
|
|
|
function abort(reason) {
|
|
state.request?.abort(reason);
|
|
}
|
|
|
|
try {
|
|
const payload = JSON.parse(byId('admin-operations-bootstrap').textContent);
|
|
if (payload) applyPage(payload);
|
|
else readForm(listUrl());
|
|
} catch {
|
|
notify('初始任务数据无效,请点击刷新。', true);
|
|
readForm(listUrl());
|
|
}
|
|
|
|
byId('operations-filter').addEventListener('submit', event => {
|
|
event.preventDefault();
|
|
void loadPage(formUrl());
|
|
});
|
|
byId('operations-reset').addEventListener('click', event => {
|
|
if (event.button !== 0 || event.ctrlKey || event.metaKey
|
|
|| event.shiftKey || event.altKey) return;
|
|
event.preventDefault();
|
|
const url = new URL('/admin/operations', location.origin);
|
|
readForm(url);
|
|
void loadPage(url);
|
|
});
|
|
byId('operations-refresh').addEventListener('click', () => { void refresh(); });
|
|
for (const [id, delta] of [['operations-previous', -1], ['operations-next', 1]]) {
|
|
byId(id).addEventListener('click', () => {
|
|
if (!state.page) return;
|
|
const url = new URL(state.loadedUrl);
|
|
url.searchParams.set('page', state.page.pagination.page + delta);
|
|
void loadPage(url);
|
|
});
|
|
}
|
|
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) onOpenDetail(button.dataset.operationDetail, button);
|
|
});
|
|
|
|
renderPagination();
|
|
|
|
return Object.freeze({ abort, notify, refresh, restore });
|
|
}
|