|
|
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');
|
|
|
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: [] },
|
|
|
catalog: bootstrap.catalog || { hosts: [], pools: [] },
|
|
|
prefill: bootstrap.prefill || {},
|
|
|
preview: null,
|
|
|
previewRequestSequence: 0,
|
|
|
detail: null,
|
|
|
mutationLocked: false,
|
|
|
instanceSearchSequence: 0,
|
|
|
instanceSearchTimer: null,
|
|
|
};
|
|
|
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 = serviceCompensationScopeId(
|
|
|
byId('service-compensation-scope-id').value
|
|
|
);
|
|
|
if (!Object.prototype.hasOwnProperty.call(labels.scopes, scopeType)
|
|
|
|| 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);
|
|
|
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) {
|
|
|
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();
|
|
|
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';
|
|
|
updateTimeSummary();
|
|
|
setMutationBusy(false);
|
|
|
configureScope(true);
|
|
|
|
|
|
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);
|
|
|
byId(id).addEventListener('input', updateTimeSummary);
|
|
|
}
|
|
|
|
|
|
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 {
|
|
|
if (requestSequence === state.previewRequestSequence) {
|
|
|
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();
|
|
|
});
|
|
|
}
|