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.
virt/web/public/cloud/admin-instance-detail.js

335 lines
16 KiB
JavaScript

const tabs = ['overview', 'service', 'configuration', 'backups', 'jobs'];
function el(tag, className = '', text) {
const node = document.createElement(tag);
node.className = className;
if (text !== undefined) node.textContent = String(text);
return node;
}
function text(...values) {
return values.find(value => value !== null && value !== undefined && String(value).trim() !== '') ?? '—';
}
function date(value) {
if (!value) return '未记录';
const numeric = Number(value);
const timestamp = Number.isFinite(numeric) ? numeric * (numeric < 1e12 ? 1000 : 1) : Date.parse(value);
const parsed = new Date(timestamp);
if (!Number.isFinite(parsed.getTime())) return '未记录';
return parsed.toLocaleString('zh-CN', { hour12: false });
}
function bytes(value) {
const number = Number(value);
if (value === null || value === undefined || !Number.isFinite(number) || number < 0) return '未记录';
if (number === 0) return '0 B';
const exponent = Math.min(4, Math.floor(Math.log(number) / Math.log(1024)));
return `${(number / 1024 ** exponent).toLocaleString('zh-CN', { maximumFractionDigits: 2 })} ${['B', 'KiB', 'MiB', 'GiB', 'TiB'][exponent]}`;
}
function safeLink(value, label, className = '') {
try {
const url = new URL(value, location.origin);
if (url.origin !== location.origin || !/^https?:$/.test(url.protocol)) throw new Error('Unsafe URL');
const link = el('a', className, label);
link.href = url.pathname + url.search + url.hash;
return link;
} catch { return el('span', className, label); }
}
function copyButton(value, label = '复制') {
const button = el('button', 'btn btn-light btn-sm');
button.type = 'button'; button.dataset.copy = String(value);
button.setAttribute('aria-label', `${label} ${value}`);
const icon = el('i', 'mdi mdi-content-copy'); icon.setAttribute('aria-hidden', 'true');
button.append(icon); return button;
}
function infoList(entries) {
const list = el('dl', 'admin-instance-details');
for (const [label, value] of entries) {
list.append(el('dt', '', label));
const dd = el('dd');
dd.append(value instanceof Node ? value : document.createTextNode(String(text(value))));
list.append(dd);
}
return list;
}
function jobStatus(task) {
if (task?.completed === false && task.status === 'active') return '执行中';
if (task?.completed === true) {
if (task.recovery?.pending === true) {
const code = String(task.recovery?.code || task.finalization_error_code || '');
if (code === 'recovery_dispatch_ledger_conflict' || task.dispatch_state === 'invalid') {
return '派发账本异常 · 待修复';
}
if (task.dispatch_state === 'not_dispatched') return 'PHP 本地账本收尾中';
return task.status === 'failed' ? '已失败 · 持续恢复中' : '安全恢复中';
}
return ({ succeeded: '已成功', failed: '已失败' })[task.status] || '任务状态协议无效';
}
return '任务状态协议无效';
}
export function createAdminInstanceDetail({
byId,
read,
renderConfiguration,
cancelConfiguration,
loadBackups,
cancelBackups,
onSelectionChange,
onPublicNetworkChange,
onCopy,
} = {}) {
if (typeof byId !== 'function' || typeof read !== 'function') {
throw new TypeError('Instance detail dependencies are incomplete');
}
const state = {
request: null, id: null, closing: false, opener: null, scroll: null, started: false,
};
const dialog = byId('instance-detail');
function notice(message, error = false) {
const node = byId('instance-detail-notice');
node.textContent = message;
node.hidden = !message;
node.className = `alert alert-${error ? 'danger' : 'info'}`;
node.setAttribute('role', error ? 'alert' : 'status');
}
function chooseTab(name, focus = false) {
tabs.forEach(tab => {
const button = byId(`instance-tab-${tab}`);
button.setAttribute('aria-selected', String(tab === name));
button.tabIndex = tab === name ? 0 : -1;
byId(`instance-panel-${tab}`).hidden = tab !== name;
});
if (focus) byId(`instance-tab-${name}`).focus();
if (name === 'backups' && state.id) loadBackups?.(state.id);
}
function render(payload) {
const vm = payload.instance;
if (!vm || String(vm.id) !== state.id) throw new Error('实例详情与请求不一致,请重新打开。');
byId('instance-detail-title').textContent = text(vm.name, `实例 #${vm.id}`);
const uuid = el('span', 'admin-instance-ip text-break');
uuid.append(el('span', 'admin-mono', text(vm.uuid)));
if (vm.uuid) uuid.append(copyButton(vm.uuid, '复制 UUID'));
const overview = byId('instance-panel-overview');
const configuration = typeof renderConfiguration === 'function'
? renderConfiguration(vm) : [];
overview.replaceChildren(infoList([
['实例编号', `#${vm.id}`], ['UUID', uuid], ['Agent 标识', text(vm.agent_name, '未记录')],
['生命周期', vm.display?.lifecycle], ['所属用户', text(vm.user_name, `用户 #${vm.user_id}`)],
['用户 ID', vm.user_id], ['宿主机', text(vm.host_name)], ['地区', text(vm.region, '未记录')],
['操作系统', text(vm.os_name, '未记录')], ['配置', vm.display?.configuration],
['公网 IPv4', text(vm.public_ipv4_cidr, vm.public_ipv4, '未记录')],
['IPv4 网关', text(vm.ipv4_gateway, '未记录')],
['公网 IPv6', text(vm.public_ipv6_cidr, vm.public_ipv6, '未记录')],
['IPv6 网关', text(vm.ipv6_gateway, '未记录')],
['DNS', Array.isArray(vm.dns_servers) ? text(vm.dns_servers.join('、'), '未记录') : text(vm.dns_servers, '未记录')],
['带宽上限', vm.bandwidth_mbps ? `${vm.bandwidth_mbps} Mbps` : '未记录'],
['创建时间', date(vm.created_at)],
]));
byId('instance-panel-configuration').replaceChildren(...configuration);
const service = byId('instance-panel-service');
service.replaceChildren(infoList([
['套餐', text(vm.plan_name, '无关联套餐')], ['服务状态', vm.display?.service], ['网络状态', vm.display?.network],
['服务到期', vm.service_status === 'exempt' ? '免计费' : date(vm.service_expires_at)],
['剩余期限', vm.display?.expiry], ['本周期用量', vm.display?.traffic],
['下载流量', Number(vm.traffic_synced_at) > 0 ? bytes(vm.traffic_download_bytes) : '未采集'],
['上传流量', Number(vm.traffic_synced_at) > 0 ? bytes(vm.traffic_upload_bytes) : '未采集'],
['采集时间', date(vm.traffic_synced_at)], ['当前周期开始', date(vm.current_period_started_at)],
['当前周期结束', date(vm.current_period_ends_at)],
['续费价格', vm.renewal_price !== null && vm.renewal_price !== undefined ? `$${Number(vm.renewal_price).toFixed(2)}` : '不适用'],
['续费周期', 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');
body.append(el('h3', 'h6', `#${job.id} · ${text(job.kind_label || job.action_label || job.kind, '操作任务')} · ${jobStatus(job)}`),
infoList([['尝试次数', job.attempts ?? 0], ['阶段', text(job.phase, '未记录')],
['开始时间', date(job.created_at)], ['更新时间', date(job.updated_at)]]));
if (job.error) body.append(el('p', 'text-danger text-break mb-0', job.error));
card.append(body); jobs.append(card);
}
if (!payload.jobs?.length) jobs.append(el('p', 'text-muted py-3', '暂无任务记录。'));
if (payload.jobs_truncated) jobs.append(el('p', 'text-muted fs-12', '仅展示最近的任务记录。'));
const invoiceSection = el('section', 'admin-instance-invoices mt-4 pt-4 border-top');
invoiceSection.append(el('div', 'd-flex align-items-center justify-content-between gap-2 mb-3'));
invoiceSection.firstChild.append(el('h3', 'h6 fw-semibold mb-0', '关联账单'),
el('span', 'badge text-bg-light', `${(payload.invoices || []).length} 笔`));
const invoices = el('div');
for (const invoice of payload.invoices || []) {
const card = el('article', 'card mb-3'); const body = el('div', 'card-body');
const purpose = ({ provision: '实例开通', renewal: '实例续费', upgrade: '实例升级' })[invoice.purpose]
|| text(invoice.purpose, '账单');
const status = ({ open: '待支付', paid: '已支付', overdue: '已逾期', refunded: '已退款', expired: '已失效', void: '已作废' })[invoice.status]
|| text(invoice.status);
body.append(el('h3', 'h6', `账单 #${invoice.id} · ${purpose}`),
el('p', 'mb-2', `$${Number(invoice.amount).toFixed(2)} · ${status}`),
el('p', 'text-muted fs-12', date(invoice.created_at)));
if (invoice.detail_url) body.append(safeLink(invoice.detail_url, '查看账单', 'btn btn-light btn-sm'));
card.append(body); invoices.append(card);
}
if (!payload.invoices?.length) invoices.append(el('p', 'text-muted py-3', '暂无关联账单;导入或免计费实例可能没有开通账单。'));
if (payload.invoices_truncated) invoices.append(el('p', 'text-muted fs-12', '仅展示最近的关联账单。'));
invoiceSection.append(invoices); service.append(invoiceSection);
const control = byId('instance-control-link');
if (control instanceof HTMLAnchorElement && vm.detail_url) {
const link = safeLink(vm.detail_url, '');
if (link instanceof HTMLAnchorElement) { control.href = link.href; control.hidden = false; }
}
onPublicNetworkChange?.(vm.id, {
public_ipv4: vm.public_ipv4,
public_ipv4_cidr: vm.public_ipv4_cidr,
public_ipv6: vm.public_ipv6,
public_ipv6_cidr: vm.public_ipv6_cidr,
});
}
async function refresh(id = state.id) {
if (state.id !== String(id)) return false;
state.request?.abort('refresh');
const controller = new AbortController(); state.request = controller;
notice('正在刷新实例详情…');
try {
const payload = await read(`/api/v1/admin/instances/${encodeURIComponent(id)}`, controller);
if (controller.signal.aborted || state.id !== String(id)) return false;
cancelConfiguration?.('detail-refresh'); render(payload); notice(''); return true;
} catch (error) {
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return false;
if (state.id === String(id)) notice(`${error.message} 当前任务结果请在任务记录中核对。`, true);
return false;
} finally {
if (state.request === controller) state.request = null;
}
}
function lockScroll() {
state.scroll = { x: window.scrollX, y: window.scrollY };
document.body.style.setProperty('--admin-instance-scroll-top', `${-state.scroll.y}px`);
document.documentElement.classList.add('admin-instance-detail-open');
}
function finishClose() {
state.closing = false;
document.documentElement.classList.remove('admin-instance-detail-open');
document.body.style.removeProperty('--admin-instance-scroll-top');
if (state.scroll) {
window.scrollTo({ left: state.scroll.x, top: state.scroll.y, behavior: 'instant' });
state.scroll = null;
}
if (state.opener?.isConnected) state.opener.focus({ preventScroll: true });
state.opener = null;
}
function close() {
if (state.closing || !dialog?.open) return;
state.request?.abort(); state.request = null;
cancelConfiguration?.('closed'); cancelBackups?.('closed');
state.id = null; onSelectionChange?.(null); state.closing = true;
void window.VenixDrawerMotion.closeDrawerWithMotion(dialog).then(closed => {
if (closed) finishClose(); else state.closing = false;
});
}
async function open(id, opener) {
if (!/^[1-9][0-9]*$/.test(String(id)) || state.closing) return;
state.request?.abort(); cancelConfiguration?.('detail-switch'); cancelBackups?.('detail-switch');
state.id = String(id); onSelectionChange?.(state.id); state.opener = opener;
const drawerBody = dialog.querySelector('.admin-instance-drawer-body');
if (drawerBody) drawerBody.scrollTop = 0;
const controller = new AbortController(); state.request = controller;
byId('instance-detail-title').textContent = `实例 #${id}`;
const control = byId('instance-control-link'); if (control) control.hidden = true;
tabs.forEach(tab => byId(`instance-panel-${tab}`).replaceChildren());
chooseTab('overview'); notice('正在读取详情…');
if (!dialog.open) { lockScroll(); window.VenixDrawerMotion.openDrawerWithMotion(dialog); }
try {
const payload = await read(`/api/v1/admin/instances/${id}`, controller);
if (controller.signal.aborted || state.id !== String(id)) return;
render(payload); notice('');
} catch (error) {
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
if (state.id === String(id)) notice(`${error.message} 请关闭后重试。`, true);
} finally {
if (state.request === controller) state.request = null;
}
}
const handlers = {
close,
cancel: event => { event.preventDefault(); close(); },
click: event => {
if (event.target === dialog) {
const rect = dialog.getBoundingClientRect();
if (event.clientX < rect.left || event.clientX > rect.right
|| event.clientY < rect.top || event.clientY > rect.bottom) close();
}
const tab = event.target.closest('[data-instance-tab]');
if (tab) chooseTab(tab.dataset.instanceTab);
const button = event.target.closest('[data-copy]');
if (button) onCopy?.(button.dataset.copy);
const link = event.target.closest('a[href]');
if (link && !event.defaultPrevented && event.button === 0 && !event.ctrlKey && !event.metaKey
&& !event.shiftKey && !event.altKey && (!link.target || link.target === '_self')) close();
},
keydown: event => {
if (!event.target.matches('[data-instance-tab]')) return;
const index = tabs.indexOf(event.target.dataset.instanceTab);
const next = ({ ArrowRight: (index + 1) % tabs.length,
ArrowLeft: (index + tabs.length - 1) % tabs.length,
Home: 0, End: tabs.length - 1 })[event.key];
if (next !== undefined) { event.preventDefault(); chooseTab(tabs[next], true); }
},
popstate: close,
pagehide: () => {
state.request?.abort(); cancelConfiguration?.('pagehide'); cancelBackups?.('pagehide');
},
pageshow: event => { if (event.persisted) close(); },
};
function start() {
if (state.started) return;
state.started = true;
byId('instance-detail-close').addEventListener('click', handlers.close);
dialog.addEventListener('cancel', handlers.cancel);
dialog.addEventListener('click', handlers.click);
dialog.addEventListener('keydown', handlers.keydown);
window.addEventListener('popstate', handlers.popstate);
window.addEventListener('pagehide', handlers.pagehide);
window.addEventListener('pageshow', handlers.pageshow);
}
function dispose() {
if (!state.started) return;
close(); state.started = false;
byId('instance-detail-close').removeEventListener('click', handlers.close);
dialog.removeEventListener('cancel', handlers.cancel);
dialog.removeEventListener('click', handlers.click);
dialog.removeEventListener('keydown', handlers.keydown);
window.removeEventListener('popstate', handlers.popstate);
window.removeEventListener('pagehide', handlers.pagehide);
window.removeEventListener('pageshow', handlers.pageshow);
}
return Object.freeze({ start, open, close, refresh, notice, isOpen: () => dialog.open, dispose });
}