883 lines
45 KiB
JavaScript
883 lines
45 KiB
JavaScript
/* mini-erp-fabric-demo 前端逻辑(原生 JS,无构建步骤) */
|
||
|
||
const $ = (sel, root = document) => root.querySelector(sel);
|
||
const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));
|
||
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({
|
||
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
|
||
}[c]));
|
||
|
||
async function api(method, path, body) {
|
||
const opt = { method };
|
||
if (body !== undefined) {
|
||
opt.headers = { 'Content-Type': 'application/json' };
|
||
opt.body = JSON.stringify(body);
|
||
}
|
||
const res = await fetch(path, opt);
|
||
let data = null;
|
||
try { data = await res.json(); } catch (e) { /* 无 JSON body */ }
|
||
if (!res.ok) {
|
||
let msg = data && data.detail;
|
||
if (Array.isArray(msg)) msg = msg.map((m) => m.msg).join('; ');
|
||
throw new Error(msg || `请求失败(HTTP ${res.status})`);
|
||
}
|
||
return data;
|
||
}
|
||
|
||
function toast(msg, type = 'info') {
|
||
const t = document.createElement('div');
|
||
t.className = `toast ${type}`;
|
||
t.textContent = msg;
|
||
$('#toast-root').appendChild(t);
|
||
setTimeout(() => t.remove(), 4000);
|
||
}
|
||
|
||
/* ---------- 模态框 ---------- */
|
||
const modalStack = [];
|
||
function openModal(html, { wide = false } = {}) {
|
||
const overlay = document.createElement('div');
|
||
overlay.className = 'overlay';
|
||
overlay.innerHTML = `<div class="modal ${wide ? 'wide' : ''}"><button class="close-x" title="关闭">×</button>${html}</div>`;
|
||
$('#modal-root').appendChild(overlay);
|
||
const close = () => {
|
||
overlay.remove();
|
||
const i = modalStack.indexOf(close);
|
||
if (i >= 0) modalStack.splice(i, 1);
|
||
};
|
||
modalStack.push(close);
|
||
overlay.addEventListener('mousedown', (e) => { if (e.target === overlay) close(); });
|
||
$('.close-x', overlay).onclick = close;
|
||
return { overlay, close, box: $('.modal', overlay) };
|
||
}
|
||
function closeAllModals() { while (modalStack.length) modalStack[modalStack.length - 1](); }
|
||
document.addEventListener('keydown', (e) => {
|
||
if (e.key === 'Escape' && modalStack.length) modalStack[modalStack.length - 1]();
|
||
});
|
||
function confirmDialog(message, okLabel = '确定') {
|
||
return new Promise((resolve) => {
|
||
const m = openModal(`<h2>请确认</h2><p>${esc(message)}</p>
|
||
<div class="modal-actions">
|
||
<button class="btn" data-x="no">取消</button>
|
||
<button class="btn primary" data-x="yes">${esc(okLabel)}</button>
|
||
</div>`);
|
||
$('[data-x=no]', m.box).onclick = () => { m.close(); resolve(false); };
|
||
$('[data-x=yes]', m.box).onclick = () => { m.close(); resolve(true); };
|
||
});
|
||
}
|
||
|
||
/* ---------- 展示辅助 ---------- */
|
||
const STATUS_LABEL = {
|
||
DRAFT: '草稿', CONFIRMED: '已确认', RECEIVED: '已入库', SHIPPED: '已出库', CANCELLED: '已作废',
|
||
ACTIVE: '启用', DISABLED: '停用', VOID: '作废',
|
||
};
|
||
const STATUS_CLASS = {
|
||
DRAFT: 'gray', CONFIRMED: 'blue', RECEIVED: 'green', SHIPPED: 'green', CANCELLED: 'red',
|
||
ACTIVE: 'green', DISABLED: 'orange', VOID: 'gray',
|
||
};
|
||
const badge = (s) => `<span class="badge ${STATUS_CLASS[s] || 'gray'}">${esc(STATUS_LABEL[s] || s)}</span>`;
|
||
const fmtMoney = (v) => Number(v).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||
const fmtQty = (v) => Number(v).toLocaleString('zh-CN', { maximumFractionDigits: 2 });
|
||
const BIZ_LABEL = { INIT: '期初', PO_RECEIVE: '采购入库', SO_SHIP: '销售出库', ADJUST: '库存调整' };
|
||
function todayStr() {
|
||
const d = new Date();
|
||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
||
}
|
||
function renderPager(el, total, page, pageSize, cb) {
|
||
const pages = Math.max(1, Math.ceil(total / pageSize));
|
||
el.innerHTML = `<span>共 ${total} 条 · 第 ${page}/${pages} 页</span>
|
||
<button class="btn small" data-pg="prev" ${page <= 1 ? 'disabled' : ''}>上一页</button>
|
||
<button class="btn small" data-pg="next" ${page >= pages ? 'disabled' : ''}>下一页</button>`;
|
||
$('[data-pg=prev]', el).onclick = () => cb(page - 1);
|
||
$('[data-pg=next]', el).onclick = () => cb(page + 1);
|
||
}
|
||
|
||
const ORDER_KINDS = {
|
||
purchase: {
|
||
api: '/api/purchase-orders', masterKind: 'supplier', masterLabel: '供应商', title: '采购单',
|
||
executeAction: 'receive', executeLabel: '入库', executedStatus: 'RECEIVED',
|
||
statuses: ['DRAFT', 'CONFIRMED', 'RECEIVED', 'CANCELLED'], priceField: 'purchase_price',
|
||
},
|
||
sales: {
|
||
api: '/api/sales-orders', masterKind: 'customer', masterLabel: '客户', title: '销售单',
|
||
executeAction: 'ship', executeLabel: '出库', executedStatus: 'SHIPPED',
|
||
statuses: ['DRAFT', 'CONFIRMED', 'SHIPPED', 'CANCELLED'], priceField: 'sale_price',
|
||
},
|
||
};
|
||
|
||
const state = {
|
||
purchase: { page: 1, order_no: '', status: '' },
|
||
sales: { page: 1, order_no: '', status: '' },
|
||
inventory: { sub: 'balance', page: 1, q: '', low_only: false },
|
||
flows: { page: 1, sku_id: '', biz_type: '', biz_order_no: '' },
|
||
master: {
|
||
sub: 'supplier',
|
||
page: { supplier: 1, customer: 1, sku: 1, alias: 1 },
|
||
q: { supplier: '', customer: '', sku: '' },
|
||
status: { supplier: '', customer: '', sku: '' },
|
||
aliasType: '',
|
||
},
|
||
};
|
||
|
||
/* ---------- 概览 ---------- */
|
||
async function renderDashboard() {
|
||
const sec = $('#tab-dashboard');
|
||
sec.innerHTML = '<div class="panel">加载中…</div>';
|
||
const d = await api('GET', '/api/dashboard/summary');
|
||
const lowRows = d.low_stock.length
|
||
? d.low_stock.map((s) => `<tr><td class="mono">${esc(s.sku_code)}</td><td>${esc(s.sku_name)}</td>
|
||
<td class="num">${fmtQty(s.qty_on_hand)} ${esc(s.unit)}</td>
|
||
<td class="num">${fmtQty(s.safety_stock)}</td><td><span class="badge orange">低库存</span></td></tr>`).join('')
|
||
: '<tr><td colspan="5" class="empty">暂无低库存预警</td></tr>';
|
||
const recentRows = (list, kind) => list.map((o) => `<tr>
|
||
<td><button class="link-btn" data-view="${kind}" data-id="${o.id}">${esc(o.order_no)}</button></td>
|
||
<td>${esc(o.master_name)}</td><td>${badge(o.status)}</td>
|
||
<td class="num">${fmtMoney(o.total_amount)}</td><td>${esc(o.order_date)}</td></tr>`).join('')
|
||
|| '<tr><td colspan="5" class="empty">暂无单据</td></tr>';
|
||
|
||
sec.innerHTML = `
|
||
<div class="cards">
|
||
<div class="card"><div class="label">启用供应商</div><div class="value">${d.master.supplier_active}</div></div>
|
||
<div class="card"><div class="label">启用客户</div><div class="value">${d.master.customer_active}</div></div>
|
||
<div class="card"><div class="label">启用 SKU</div><div class="value">${d.master.sku_active}</div></div>
|
||
<div class="card"><div class="label">有库存 SKU</div><div class="value">${d.master.stock_sku}</div></div>
|
||
<div class="card money"><div class="label">累计采购入库金额</div><div class="value">¥${fmtMoney(d.purchase.received_amount_total)}</div>
|
||
<div class="extra">本月 ¥${fmtMoney(d.purchase.received_amount_month)} · 已入库 ${d.purchase.received} 张</div></div>
|
||
<div class="card money"><div class="label">累计销售出库金额</div><div class="value">¥${fmtMoney(d.sales.shipped_amount_total)}</div>
|
||
<div class="extra">本月 ¥${fmtMoney(d.sales.shipped_amount_month)} · 已出库 ${d.sales.shipped} 张</div></div>
|
||
</div>
|
||
<div class="panel">
|
||
<h3>单据状态分布</h3>
|
||
<div class="table-wrap"><table>
|
||
<tr><th>类型</th><th class="num">草稿</th><th class="num">已确认</th><th class="num">已执行</th><th class="num">已作废</th></tr>
|
||
<tr><td>采购单</td><td class="num">${d.purchase.draft}</td><td class="num">${d.purchase.confirmed}</td>
|
||
<td class="num">${d.purchase.received}(已入库)</td><td class="num">${d.purchase.cancelled}</td></tr>
|
||
<tr><td>销售单</td><td class="num">${d.sales.draft}</td><td class="num">${d.sales.confirmed}</td>
|
||
<td class="num">${d.sales.shipped}(已出库)</td><td class="num">${d.sales.cancelled}</td></tr>
|
||
</table></div>
|
||
</div>
|
||
<div class="grid-2">
|
||
<div class="panel"><h3>低库存预警<span class="hint">现存量 < 安全库存</span></h3>
|
||
<div class="table-wrap"><table>
|
||
<tr><th>SKU</th><th>名称</th><th class="num">现存量</th><th class="num">安全库存</th><th>预警</th></tr>
|
||
${lowRows}
|
||
</table></div>
|
||
</div>
|
||
<div class="panel"><h3>最近采购单</h3>
|
||
<div class="table-wrap"><table>
|
||
<tr><th>单号</th><th>供应商</th><th>状态</th><th class="num">金额</th><th>日期</th></tr>
|
||
${recentRows(d.recent_purchase, 'purchase')}
|
||
</table></div>
|
||
</div>
|
||
</div>
|
||
<div class="panel"><h3>最近销售单</h3>
|
||
<div class="table-wrap"><table>
|
||
<tr><th>单号</th><th>客户</th><th>状态</th><th class="num">金额</th><th>日期</th></tr>
|
||
${recentRows(d.recent_sales, 'sales')}
|
||
</table></div>
|
||
</div>`;
|
||
$$('[data-view]', sec).forEach((b) => {
|
||
b.onclick = () => openOrderDetail(b.dataset.view, Number(b.dataset.id)).catch((e) => toast(e.message, 'error'));
|
||
});
|
||
}
|
||
|
||
/* ---------- 采购/销售列表 ---------- */
|
||
async function renderOrders(kind) {
|
||
const cfg = ORDER_KINDS[kind];
|
||
const st = state[kind];
|
||
const sec = $('#tab-' + kind);
|
||
sec.innerHTML = `
|
||
<div class="panel">
|
||
<div class="toolbar">
|
||
<input id="f-no" placeholder="按单号搜索" value="${esc(st.order_no)}">
|
||
<select id="f-status">
|
||
<option value="">全部状态</option>
|
||
${cfg.statuses.map((s) => `<option value="${s}" ${st.status === s ? 'selected' : ''}>${STATUS_LABEL[s]}</option>`).join('')}
|
||
</select>
|
||
<button class="btn" id="btn-search">查询</button>
|
||
<div class="spacer"></div>
|
||
<button class="btn primary" id="btn-new">+ 新建${cfg.title}</button>
|
||
</div>
|
||
<div class="table-wrap"><table>
|
||
<thead><tr><th>单号</th><th>日期</th><th>${cfg.masterLabel}</th><th>状态</th>
|
||
<th class="num">金额(元)</th><th>经办人</th><th>创建时间</th><th>操作</th></tr></thead>
|
||
<tbody id="rows"><tr><td colspan="8" class="empty">加载中…</td></tr></tbody>
|
||
</table></div>
|
||
<div class="pager" id="pager"></div>
|
||
</div>`;
|
||
$('#btn-search', sec).onclick = () => {
|
||
st.order_no = $('#f-no', sec).value.trim();
|
||
st.status = $('#f-status', sec).value;
|
||
st.page = 1;
|
||
renderOrders(kind).catch((e) => toast(e.message, 'error'));
|
||
};
|
||
$('#f-no', sec).addEventListener('keydown', (e) => { if (e.key === 'Enter') $('#btn-search', sec).click(); });
|
||
$('#btn-new', sec).onclick = () => openOrderForm(kind).catch((e) => toast(e.message, 'error'));
|
||
|
||
const params = new URLSearchParams({ page: st.page, page_size: 20 });
|
||
if (st.order_no) params.set('order_no', st.order_no);
|
||
if (st.status) params.set('status', st.status);
|
||
const d = await api('GET', cfg.api + '?' + params);
|
||
$('#rows', sec).innerHTML = d.items.length
|
||
? d.items.map((o) => `<tr>
|
||
<td><button class="link-btn mono" data-id="${o.id}">${esc(o.order_no)}</button></td>
|
||
<td>${esc(o.order_date)}</td>
|
||
<td title="${esc(o.master_code)}">${esc(o.master_name)}</td>
|
||
<td>${badge(o.status)}</td>
|
||
<td class="num">${fmtMoney(o.total_amount)}</td>
|
||
<td>${esc(o.handler)}</td>
|
||
<td class="muted">${esc(o.created_at)}</td>
|
||
<td><button class="btn small" data-id="${o.id}">查看</button></td>
|
||
</tr>`).join('')
|
||
: '<tr><td colspan="8" class="empty">暂无单据,点击右上角新建</td></tr>';
|
||
$$('button[data-id]', sec).forEach((b) => {
|
||
b.onclick = () => openOrderDetail(kind, Number(b.dataset.id)).catch((e) => toast(e.message, 'error'));
|
||
});
|
||
renderPager($('#pager', sec), d.total, d.page, d.page_size, (p) => {
|
||
st.page = p;
|
||
renderOrders(kind).catch((e) => toast(e.message, 'error'));
|
||
});
|
||
}
|
||
|
||
/* ---------- 单据详情 ---------- */
|
||
async function openOrderDetail(kind, id) {
|
||
const cfg = ORDER_KINDS[kind];
|
||
const o = await api('GET', `${cfg.api}/${id}`);
|
||
const itemRows = o.items.map((it) => `<tr>
|
||
<td>${it.line_no}</td><td class="mono">${esc(it.sku_code)}</td><td>${esc(it.sku_name)}</td>
|
||
<td>${esc(it.unit)}</td><td class="num">${fmtQty(it.qty)}</td>
|
||
<td class="num">${fmtMoney(it.price)}</td><td class="num">${fmtMoney(it.amount)}</td></tr>`).join('');
|
||
const actions = [];
|
||
if (o.status === 'DRAFT') {
|
||
actions.push(['edit', '编辑', 'btn'], ['confirm', '确认', 'btn primary'],
|
||
['cancel', '作废', 'btn danger'], ['delete', '删除草稿', 'btn danger']);
|
||
} else if (o.status === 'CONFIRMED') {
|
||
actions.push(['execute', cfg.executeLabel, 'btn primary'], ['cancel', '作废', 'btn danger']);
|
||
}
|
||
const m = openModal(`
|
||
<h2>${cfg.title}详情 · <span class="mono">${esc(o.order_no)}</span> ${badge(o.status)}</h2>
|
||
<div class="kv">
|
||
<div class="item"><div class="k">${cfg.masterLabel}</div><div class="v">${esc(o.master_name)}(${esc(o.master_code)})</div></div>
|
||
<div class="item"><div class="k">单据日期</div><div class="v">${esc(o.order_date)}</div></div>
|
||
<div class="item"><div class="k">经办人</div><div class="v">${esc(o.handler)}</div></div>
|
||
<div class="item"><div class="k">${cfg.executeLabel}时间</div><div class="v">${esc(o.executed_at || '—')}</div></div>
|
||
<div class="item"><div class="k">创建时间</div><div class="v">${esc(o.created_at)}</div></div>
|
||
<div class="item"><div class="k">备注</div><div class="v">${esc(o.remark || '—')}</div></div>
|
||
</div>
|
||
<div class="table-wrap"><table>
|
||
<tr><th>行号</th><th>SKU</th><th>名称</th><th>单位</th><th class="num">数量</th><th class="num">单价</th><th class="num">金额</th></tr>
|
||
${itemRows}
|
||
</table></div>
|
||
<div class="total-line">合计金额:<b>¥${fmtMoney(o.total_amount)}</b></div>
|
||
<div class="modal-actions">
|
||
${actions.map(([a, label, cls]) => `<button class="${cls}" data-act="${a}">${label}</button>`).join('')}
|
||
<button class="btn" data-act="close">关闭</button>
|
||
</div>`, { wide: true });
|
||
|
||
const doAction = async (act) => {
|
||
try {
|
||
if (act === 'edit') { m.close(); await openOrderForm(kind, o); return; }
|
||
if (act === 'confirm') {
|
||
if (!await confirmDialog(`确认${cfg.title} ${o.order_no}?确认后不会变动库存,可随时作废。`, '确认')) return;
|
||
await api('POST', `${cfg.api}/${id}/confirm`);
|
||
toast(`${cfg.title}已确认`, 'success');
|
||
} else if (act === 'execute') {
|
||
const tip = kind === 'purchase'
|
||
? `确认入库 ${o.order_no}?将按明细增加库存并生成入库流水。`
|
||
: `确认出库 ${o.order_no}?将校验库存充足后扣减库存并生成出库流水,库存不足会失败。`;
|
||
if (!await confirmDialog(tip, `确认${cfg.executeLabel}`)) return;
|
||
await api('POST', `${cfg.api}/${id}/${cfg.executeAction}`);
|
||
toast(`${cfg.executeLabel}完成,库存已联动`, 'success');
|
||
} else if (act === 'cancel') {
|
||
if (!await confirmDialog(`作废 ${o.order_no}?作废后不可恢复,不影响库存。`, '作废')) return;
|
||
await api('POST', `${cfg.api}/${id}/cancel`);
|
||
toast('单据已作废', 'success');
|
||
} else if (act === 'delete') {
|
||
if (!await confirmDialog(`物理删除草稿 ${o.order_no}?仅草稿允许删除。`, '删除')) return;
|
||
await api('DELETE', `${cfg.api}/${id}`);
|
||
toast('草稿已删除', 'success');
|
||
}
|
||
closeAllModals();
|
||
refreshCurrent();
|
||
} catch (e) {
|
||
toast(e.message, 'error');
|
||
}
|
||
};
|
||
$$('[data-act]', m.box).forEach((b) => {
|
||
b.onclick = () => (b.dataset.act === 'close' ? m.close() : doAction(b.dataset.act));
|
||
});
|
||
}
|
||
|
||
/* ---------- 开单/编辑表单 ---------- */
|
||
async function openOrderForm(kind, existing = null) {
|
||
const cfg = ORDER_KINDS[kind];
|
||
const [masters, skuResp] = await Promise.all([
|
||
api('GET', `/api/${cfg.masterKind}s/options`),
|
||
api('GET', '/api/skus?page_size=100'),
|
||
]);
|
||
const masterOpts = masters.filter((x) => x.status === 'ACTIVE');
|
||
const skuOpts = skuResp.items.filter((x) => x.status === 'ACTIVE');
|
||
const skuById = Object.fromEntries(skuOpts.map((s) => [s.id, s]));
|
||
const fk = cfg.masterKind === 'supplier' ? 'supplier_id' : 'customer_id';
|
||
|
||
const m = openModal(`
|
||
<h2>${existing ? '编辑' : '新建'}${cfg.title}${existing ? ` · <span class="mono">${esc(existing.order_no)}</span>` : ''}</h2>
|
||
<div class="form-grid">
|
||
<div class="field"><label>${cfg.masterLabel}(仅启用)</label>
|
||
<select id="of-master">
|
||
<option value="">请选择</option>
|
||
${masterOpts.map((x) => `<option value="${x.id}" ${existing && existing.master_id === x.id ? 'selected' : ''}>${esc(x.code)} ${esc(x.name)}</option>`).join('')}
|
||
</select></div>
|
||
<div class="field"><label>单据日期</label><input type="date" id="of-date" value="${existing ? existing.order_date : todayStr()}"></div>
|
||
<div class="field"><label>经办人</label><input id="of-handler" value="${esc(existing ? existing.handler : 'demo')}" maxlength="64"></div>
|
||
<div class="field"><label>备注</label><input id="of-remark" value="${esc(existing ? existing.remark || '' : '')}" maxlength="255"></div>
|
||
</div>
|
||
<h3 style="margin:16px 0 8px">明细行</h3>
|
||
<div class="table-wrap"><table class="items-table">
|
||
<thead><tr><th style="width:40%">SKU</th><th>数量</th><th>单价(元)</th><th class="num">金额</th><th></th></tr></thead>
|
||
<tbody id="of-items"></tbody>
|
||
</table></div>
|
||
<div style="margin-top:8px"><button class="btn small" id="of-add">+ 添加行</button></div>
|
||
<div class="total-line">合计:<b id="of-total">¥0.00</b></div>
|
||
<div class="modal-actions">
|
||
<button class="btn" id="of-cancel">取消</button>
|
||
<button class="btn primary" id="of-save">保存草稿</button>
|
||
</div>`, { wide: true });
|
||
|
||
const tbody = $('#of-items', m.box);
|
||
function addRow(it = null) {
|
||
const tr = document.createElement('tr');
|
||
tr.innerHTML = `
|
||
<td><select class="sku-select">
|
||
<option value="">选择 SKU</option>
|
||
${skuOpts.map((s) => `<option value="${s.id}" ${it && it.sku_id === s.id ? 'selected' : ''}>${esc(s.code)} ${esc(s.name)}(${esc(s.unit)})</option>`).join('')}
|
||
</select></td>
|
||
<td><input type="number" class="qty" min="0.01" step="0.01" value="${it ? it.qty : ''}"></td>
|
||
<td><input type="number" class="price" min="0" step="0.01" value="${it ? it.price : ''}"></td>
|
||
<td class="num amount">0.00</td>
|
||
<td><button class="link-btn danger of-del">删除</button></td>`;
|
||
tbody.appendChild(tr);
|
||
$('.sku-select', tr).onchange = () => {
|
||
const s = skuById[Number($('.sku-select', tr).value)];
|
||
if (s) $('.price', tr).value = s[cfg.priceField];
|
||
recalc();
|
||
};
|
||
$('.qty', tr).oninput = recalc;
|
||
$('.price', tr).oninput = recalc;
|
||
$('.of-del', tr).onclick = () => { tr.remove(); recalc(); };
|
||
recalc();
|
||
}
|
||
function recalc() {
|
||
let total = 0;
|
||
$$('tr', tbody).forEach((tr) => {
|
||
const qty = Number($('.qty', tr).value) || 0;
|
||
const price = Number($('.price', tr).value) || 0;
|
||
const amount = Math.round(qty * price * 100) / 100;
|
||
$('.amount', tr).textContent = fmtMoney(amount);
|
||
total += amount;
|
||
});
|
||
$('#of-total', m.box).textContent = '¥' + fmtMoney(total);
|
||
}
|
||
$('#of-add', m.box).onclick = () => addRow();
|
||
$('#of-cancel', m.box).onclick = m.close;
|
||
if (existing) existing.items.forEach(addRow); else addRow();
|
||
|
||
$('#of-save', m.box).onclick = async () => {
|
||
const masterId = Number($('#of-master', m.box).value);
|
||
if (!masterId) return toast(`请选择${cfg.masterLabel}`, 'error');
|
||
const items = $$('tr', tbody).map((tr) => ({
|
||
sku_id: Number($('.sku-select', tr).value),
|
||
qty: Number($('.qty', tr).value),
|
||
price: Number($('.price', tr).value),
|
||
})).filter((x) => x.sku_id);
|
||
if (!items.length) return toast('至少需要一行有效明细', 'error');
|
||
if (items.some((x) => !(x.qty > 0))) return toast('数量必须大于 0', 'error');
|
||
if (items.some((x) => !(x.price >= 0) || Number.isNaN(x.price))) return toast('单价不能为负', 'error');
|
||
const payload = {
|
||
[fk]: masterId,
|
||
order_date: $('#of-date', m.box).value || todayStr(),
|
||
handler: $('#of-handler', m.box).value.trim() || 'demo',
|
||
remark: $('#of-remark', m.box).value.trim() || null,
|
||
items,
|
||
};
|
||
try {
|
||
if (existing) await api('PUT', `${cfg.api}/${existing.id}`, payload);
|
||
else await api('POST', cfg.api, payload);
|
||
toast(existing ? '草稿已更新' : `${cfg.title}已保存为草稿`, 'success');
|
||
closeAllModals();
|
||
refreshCurrent();
|
||
} catch (e) {
|
||
toast(e.message, 'error');
|
||
}
|
||
};
|
||
}
|
||
|
||
/* ---------- 库存 ---------- */
|
||
async function renderInventory() {
|
||
const sec = $('#tab-inventory');
|
||
const st = state.inventory;
|
||
sec.innerHTML = `
|
||
<div class="subtabs">
|
||
<button data-sub="balance" class="${st.sub === 'balance' ? 'active' : ''}">库存余额</button>
|
||
<button data-sub="flows" class="${st.sub === 'flows' ? 'active' : ''}">库存流水</button>
|
||
</div>
|
||
<div id="inv-body"></div>`;
|
||
$$('[data-sub]', sec).forEach((b) => {
|
||
b.onclick = () => { st.sub = b.dataset.sub; renderInventory().catch((e) => toast(e.message, 'error')); };
|
||
});
|
||
if (st.sub === 'balance') await renderStockBalance($('#inv-body', sec));
|
||
else await renderStockFlows($('#inv-body', sec));
|
||
}
|
||
|
||
async function renderStockBalance(body) {
|
||
const st = state.inventory;
|
||
body.innerHTML = `<div class="panel">
|
||
<div class="toolbar">
|
||
<input id="s-q" placeholder="按 SKU 编码/名称搜索" value="${esc(st.q)}">
|
||
<label class="check"><input type="checkbox" id="s-low" ${st.low_only ? 'checked' : ''}> 只看低库存</label>
|
||
<button class="btn" id="s-search">查询</button>
|
||
</div>
|
||
<div class="table-wrap"><table>
|
||
<thead><tr><th>SKU</th><th>名称</th><th>分类</th><th>单位</th><th class="num">现存量</th><th class="num">安全库存</th><th>状态</th><th>最近变动</th></tr></thead>
|
||
<tbody id="s-rows"><tr><td colspan="8" class="empty">加载中…</td></tr></tbody>
|
||
</table></div>
|
||
<div class="pager" id="s-pager"></div>
|
||
</div>`;
|
||
const search = () => {
|
||
st.q = $('#s-q', body).value.trim();
|
||
st.low_only = $('#s-low', body).checked;
|
||
st.page = 1;
|
||
renderStockBalance(body).catch((e) => toast(e.message, 'error'));
|
||
};
|
||
$('#s-search', body).onclick = search;
|
||
$('#s-q', body).addEventListener('keydown', (e) => { if (e.key === 'Enter') search(); });
|
||
$('#s-low', body).onchange = search;
|
||
const params = new URLSearchParams({ page: st.page, page_size: 20 });
|
||
if (st.q) params.set('q', st.q);
|
||
if (st.low_only) params.set('low_only', 'true');
|
||
const d = await api('GET', '/api/stock?' + params);
|
||
$('#s-rows', body).innerHTML = d.items.length
|
||
? d.items.map((s) => `<tr>
|
||
<td class="mono">${esc(s.sku_code)}</td><td>${esc(s.sku_name)}</td><td>${esc(s.category || '—')}</td>
|
||
<td>${esc(s.unit)}</td><td class="num"><b>${fmtQty(s.qty_on_hand)}</b></td>
|
||
<td class="num">${fmtQty(s.safety_stock)}</td>
|
||
<td>${s.low_stock ? '<span class="badge orange">低库存</span>' : '<span class="badge green">正常</span>'}</td>
|
||
<td class="muted">${esc(s.updated_at)}</td></tr>`).join('')
|
||
: '<tr><td colspan="8" class="empty">暂无库存记录</td></tr>';
|
||
renderPager($('#s-pager', body), d.total, d.page, d.page_size, (p) => {
|
||
st.page = p;
|
||
renderStockBalance(body).catch((e) => toast(e.message, 'error'));
|
||
});
|
||
}
|
||
|
||
async function renderStockFlows(body) {
|
||
const st = state.flows;
|
||
const skuResp = await api('GET', '/api/skus?page_size=100');
|
||
body.innerHTML = `<div class="panel">
|
||
<div class="toolbar">
|
||
<select id="f-sku"><option value="">全部 SKU</option>
|
||
${skuResp.items.map((s) => `<option value="${s.id}" ${String(st.sku_id) === String(s.id) ? 'selected' : ''}>${esc(s.code)} ${esc(s.sku_name)}</option>`).join('')}
|
||
</select>
|
||
<select id="f-biz"><option value="">全部类型</option>
|
||
${Object.entries(BIZ_LABEL).map(([k, v]) => `<option value="${k}" ${st.biz_type === k ? 'selected' : ''}>${v}</option>`).join('')}
|
||
</select>
|
||
<input id="f-orderno" placeholder="来源单号" value="${esc(st.biz_order_no)}">
|
||
<button class="btn" id="f-search">查询</button>
|
||
</div>
|
||
<div class="table-wrap"><table>
|
||
<thead><tr><th>时间</th><th>SKU</th><th>类型</th><th>来源单号</th><th class="num">变动</th><th class="num">结存</th><th>备注</th></tr></thead>
|
||
<tbody id="f-rows"><tr><td colspan="7" class="empty">加载中…</td></tr></tbody>
|
||
</table></div>
|
||
<div class="pager" id="f-pager"></div>
|
||
</div>`;
|
||
const search = () => {
|
||
st.sku_id = $('#f-sku', body).value;
|
||
st.biz_type = $('#f-biz', body).value;
|
||
st.biz_order_no = $('#f-orderno', body).value.trim();
|
||
st.page = 1;
|
||
renderStockFlows(body).catch((e) => toast(e.message, 'error'));
|
||
};
|
||
$('#f-search', body).onclick = search;
|
||
$('#f-sku', body).onchange = search;
|
||
$('#f-biz', body).onchange = search;
|
||
const params = new URLSearchParams({ page: st.page, page_size: 20 });
|
||
if (st.sku_id) params.set('sku_id', st.sku_id);
|
||
if (st.biz_type) params.set('biz_type', st.biz_type);
|
||
if (st.biz_order_no) params.set('biz_order_no', st.biz_order_no);
|
||
const d = await api('GET', '/api/stock/flows?' + params);
|
||
$('#f-rows', body).innerHTML = d.items.length
|
||
? d.items.map((f) => `<tr>
|
||
<td class="muted">${esc(f.created_at)}</td>
|
||
<td class="mono" title="${esc(f.sku_name)}">${esc(f.sku_code)}</td>
|
||
<td>${esc(BIZ_LABEL[f.biz_type] || f.biz_type)}</td>
|
||
<td class="mono">${esc(f.biz_order_no || '—')}</td>
|
||
<td class="num" style="color:${f.qty_delta >= 0 ? 'var(--green)' : 'var(--red)'}">${f.qty_delta >= 0 ? '+' : ''}${fmtQty(f.qty_delta)}</td>
|
||
<td class="num">${fmtQty(f.qty_after)}</td>
|
||
<td class="muted" style="white-space:normal;max-width:260px">${esc(f.remark || '—')}</td></tr>`).join('')
|
||
: '<tr><td colspan="7" class="empty">暂无流水</td></tr>';
|
||
renderPager($('#f-pager', body), d.total, d.page, d.page_size, (p) => {
|
||
st.page = p;
|
||
renderStockFlows(body).catch((e) => toast(e.message, 'error'));
|
||
});
|
||
}
|
||
|
||
/* ---------- 主数据 ---------- */
|
||
const MASTER_TABS = [
|
||
['supplier', '供应商'], ['customer', '客户'], ['sku', '商品 SKU'], ['alias', '别名映射'],
|
||
];
|
||
|
||
async function renderMaster() {
|
||
const sec = $('#tab-master');
|
||
const st = state.master;
|
||
sec.innerHTML = `
|
||
<div class="subtabs">
|
||
${MASTER_TABS.map(([k, label]) => `<button data-sub="${k}" class="${st.sub === k ? 'active' : ''}">${label}</button>`).join('')}
|
||
</div>
|
||
<div id="md-body"></div>`;
|
||
$$('[data-sub]', sec).forEach((b) => {
|
||
b.onclick = () => { st.sub = b.dataset.sub; renderMaster().catch((e) => toast(e.message, 'error')); };
|
||
});
|
||
const body = $('#md-body', sec);
|
||
if (st.sub === 'alias') await renderAliases(body);
|
||
else await renderMasterList(body, st.sub);
|
||
}
|
||
|
||
async function renderMasterList(body, kind) {
|
||
const st = state.master;
|
||
const isSku = kind === 'sku';
|
||
const label = MASTER_TABS.find(([k]) => k === kind)[1];
|
||
body.innerHTML = `<div class="panel">
|
||
<div class="toolbar">
|
||
<input id="m-q" placeholder="按编码/名称搜索" value="${esc(st.q[kind])}">
|
||
<select id="m-status">
|
||
<option value="">全部状态</option>
|
||
${['ACTIVE', 'DISABLED', 'VOID'].map((s) => `<option value="${s}" ${st.status[kind] === s ? 'selected' : ''}>${STATUS_LABEL[s]}</option>`).join('')}
|
||
</select>
|
||
<button class="btn" id="m-search">查询</button>
|
||
<div class="spacer"></div>
|
||
<button class="btn primary" id="m-new">+ 新建${label}</button>
|
||
</div>
|
||
<div class="note">治理规则:编码唯一且创建后不可修改;已被业务引用的记录禁止物理删除,只能停用/作废;作废为终态。</div>
|
||
<div class="table-wrap"><table>
|
||
<thead><tr>${isSku
|
||
? '<th>编码</th><th>名称</th><th>分类</th><th>规格</th><th>单位</th><th class="num">采购价</th><th class="num">销售价</th><th class="num">安全库存</th><th>状态</th><th>操作</th>'
|
||
: '<th>编码</th><th>名称</th><th>联系人</th><th>电话(脱敏)</th><th>状态</th><th>备注</th><th>操作</th>'}</tr></thead>
|
||
<tbody id="m-rows"><tr><td colspan="10" class="empty">加载中…</td></tr></tbody>
|
||
</table></div>
|
||
<div class="pager" id="m-pager"></div>
|
||
</div>`;
|
||
const search = () => {
|
||
st.q[kind] = $('#m-q', body).value.trim();
|
||
st.status[kind] = $('#m-status', body).value;
|
||
st.page[kind] = 1;
|
||
renderMasterList(body, kind).catch((e) => toast(e.message, 'error'));
|
||
};
|
||
$('#m-search', body).onclick = search;
|
||
$('#m-q', body).addEventListener('keydown', (e) => { if (e.key === 'Enter') search(); });
|
||
$('#m-new', body).onclick = () => openMasterForm(kind).catch((e) => toast(e.message, 'error'));
|
||
|
||
const params = new URLSearchParams({ page: st.page[kind], page_size: 20 });
|
||
if (st.q[kind]) params.set('q', st.q[kind]);
|
||
if (st.status[kind]) params.set('status', st.status[kind]);
|
||
const d = await api('GET', `/api/${kind}s?` + params);
|
||
$('#m-rows', body).innerHTML = d.items.length
|
||
? d.items.map((r) => `<tr>
|
||
<td class="mono">${esc(r.code)}</td><td>${esc(r.name)}</td>
|
||
${isSku
|
||
? `<td>${esc(r.category || '—')}</td><td>${esc(r.spec || '—')}</td><td>${esc(r.unit)}</td>
|
||
<td class="num">${fmtMoney(r.purchase_price)}</td><td class="num">${fmtMoney(r.sale_price)}</td>
|
||
<td class="num">${fmtQty(r.safety_stock)}</td>`
|
||
: `<td>${esc(r.contact_person || '—')}</td><td class="mono">${esc(r.contact_phone || '—')}</td>`}
|
||
<td>${badge(r.status)}</td>
|
||
${isSku ? '' : `<td class="muted" style="white-space:normal;max-width:200px">${esc(r.remark || '—')}</td>`}
|
||
<td style="white-space:normal">
|
||
<button class="link-btn" data-act="edit" data-id="${r.id}">编辑</button>
|
||
${r.status === 'ACTIVE' ? `<button class="link-btn" data-act="disable" data-id="${r.id}">停用</button>` : ''}
|
||
${r.status === 'DISABLED' ? `<button class="link-btn" data-act="enable" data-id="${r.id}">启用</button>` : ''}
|
||
${r.status !== 'VOID' ? `<button class="link-btn danger" data-act="void" data-id="${r.id}">作废</button>` : ''}
|
||
<button class="link-btn danger" data-act="delete" data-id="${r.id}">删除</button>
|
||
</td></tr>`).join('')
|
||
: '<tr><td colspan="10" class="empty">暂无记录</td></tr>';
|
||
$$('button[data-act]', body).forEach((b) => {
|
||
b.onclick = () => masterAction(kind, Number(b.dataset.id), b.dataset.act, d.items);
|
||
});
|
||
renderPager($('#m-pager', body), d.total, d.page, d.page_size, (p) => {
|
||
st.page[kind] = p;
|
||
renderMasterList(body, kind).catch((e) => toast(e.message, 'error'));
|
||
});
|
||
}
|
||
|
||
async function masterAction(kind, id, act, rows) {
|
||
const row = rows.find((r) => r.id === id);
|
||
const name = row ? `${row.code} ${row.name}` : `#${id}`;
|
||
try {
|
||
if (act === 'edit') { await openMasterForm(kind, row); return; }
|
||
if (act === 'disable') {
|
||
if (!await confirmDialog(`停用 ${name}?停用后不可用于新单据,历史单据不受影响。`, '停用')) return;
|
||
await api('POST', `/api/${kind}s/${id}/status`, { status: 'DISABLED' });
|
||
toast('已停用', 'success');
|
||
} else if (act === 'enable') {
|
||
await api('POST', `/api/${kind}s/${id}/status`, { status: 'ACTIVE' });
|
||
toast('已启用', 'success');
|
||
} else if (act === 'void') {
|
||
if (!await confirmDialog(`作废 ${name}?作废为终态,不可恢复,也不允许再修改。`, '作废')) return;
|
||
await api('POST', `/api/${kind}s/${id}/status`, { status: 'VOID' });
|
||
toast('已作废', 'success');
|
||
} else if (act === 'delete') {
|
||
if (!await confirmDialog(`物理删除 ${name}?仅未被任何业务引用的记录允许删除。`, '删除')) return;
|
||
await api('DELETE', `/api/${kind}s/${id}`);
|
||
toast('已删除', 'success');
|
||
}
|
||
refreshCurrent();
|
||
} catch (e) {
|
||
toast(e.message, 'error');
|
||
}
|
||
}
|
||
|
||
async function openMasterForm(kind, existing = null) {
|
||
const label = MASTER_TABS.find(([k]) => k === kind)[1];
|
||
const isSku = kind === 'sku';
|
||
const codeField = kind === 'supplier' ? 'supplier_code' : kind === 'customer' ? 'customer_code' : 'sku_code';
|
||
const nameField = kind === 'supplier' ? 'supplier_name' : kind === 'customer' ? 'customer_name' : 'sku_name';
|
||
const v = (k) => esc(existing ? (existing[k] ?? '') : '');
|
||
const m = openModal(`
|
||
<h2>${existing ? '编辑' : '新建'}${label}${existing ? ` · <span class="mono">${v('code')}</span>` : ''}</h2>
|
||
<div class="form-grid">
|
||
<div class="field"><label>编码(唯一,创建后不可改)</label>
|
||
<input id="mf-code" value="${v('code')}" ${existing ? 'disabled' : ''} maxlength="32" placeholder="${kind === 'supplier' ? 'SUP0007' : kind === 'customer' ? 'CUS0007' : 'SKU0013'}"></div>
|
||
<div class="field"><label>名称</label><input id="mf-name" value="${v('name')}" maxlength="128"></div>
|
||
${isSku ? `
|
||
<div class="field"><label>分类</label><input id="mf-category" value="${v('category')}" maxlength="64"></div>
|
||
<div class="field"><label>规格型号</label><input id="mf-spec" value="${v('spec')}" maxlength="128"></div>
|
||
<div class="field"><label>单位</label><input id="mf-unit" value="${existing ? esc(existing.unit) : '件'}" maxlength="16"></div>
|
||
<div class="field"><label>参考采购价</label><input type="number" id="mf-pp" min="0" step="0.01" value="${existing ? existing.purchase_price : 0}"></div>
|
||
<div class="field"><label>参考销售价</label><input type="number" id="mf-sp" min="0" step="0.01" value="${existing ? existing.sale_price : 0}"></div>
|
||
<div class="field"><label>安全库存</label><input type="number" id="mf-safety" min="0" step="0.01" value="${existing ? existing.safety_stock : 0}"></div>
|
||
` : `
|
||
<div class="field"><label>联系人</label><input id="mf-person" value="${v('contact_person')}" maxlength="64"></div>
|
||
<div class="field"><label>联系电话(输出脱敏)</label><input id="mf-phone" value="" maxlength="32" placeholder="${existing ? '留空则清除该字段' : '13800000000'}"></div>
|
||
<div class="field full"><label>地址</label><input id="mf-addr" value="${v('address')}" maxlength="255"></div>
|
||
`}
|
||
<div class="field full"><label>备注</label><input id="mf-remark" value="${v('remark')}" maxlength="255"></div>
|
||
</div>
|
||
${!isSku && existing ? '<div class="note">出于敏感字段保护,编辑时电话输入框不回显原值:填写新号码则覆盖,留空则清除该字段。</div>' : ''}
|
||
<div class="modal-actions">
|
||
<button class="btn" id="mf-cancel">取消</button>
|
||
<button class="btn primary" id="mf-save">保存</button>
|
||
</div>`, { wide: isSku });
|
||
$('#mf-cancel', m.box).onclick = m.close;
|
||
$('#mf-save', m.box).onclick = async () => {
|
||
const name = $('#mf-name', m.box).value.trim();
|
||
if (!name) return toast('名称不能为空', 'error');
|
||
let payload;
|
||
if (isSku) {
|
||
payload = {
|
||
sku_name: name,
|
||
category: $('#mf-category', m.box).value.trim() || null,
|
||
spec: $('#mf-spec', m.box).value.trim() || null,
|
||
unit: $('#mf-unit', m.box).value.trim() || '件',
|
||
purchase_price: Number($('#mf-pp', m.box).value) || 0,
|
||
sale_price: Number($('#mf-sp', m.box).value) || 0,
|
||
safety_stock: Number($('#mf-safety', m.box).value) || 0,
|
||
remark: $('#mf-remark', m.box).value.trim() || null,
|
||
};
|
||
} else {
|
||
payload = {
|
||
[nameField]: name,
|
||
contact_person: $('#mf-person', m.box).value.trim() || null,
|
||
contact_phone: $('#mf-phone', m.box).value.trim() || null,
|
||
address: $('#mf-addr', m.box).value.trim() || null,
|
||
remark: $('#mf-remark', m.box).value.trim() || null,
|
||
};
|
||
}
|
||
try {
|
||
if (existing) {
|
||
await api('PUT', `/api/${kind}s/${existing.id}`, payload);
|
||
} else {
|
||
const code = $('#mf-code', m.box).value.trim();
|
||
if (!code) return toast('编码不能为空', 'error');
|
||
payload[codeField] = code;
|
||
await api('POST', `/api/${kind}s`, payload);
|
||
}
|
||
toast('保存成功', 'success');
|
||
closeAllModals();
|
||
refreshCurrent();
|
||
} catch (e) {
|
||
toast(e.message, 'error');
|
||
}
|
||
};
|
||
}
|
||
|
||
async function renderAliases(body) {
|
||
const st = state.master;
|
||
body.innerHTML = `<div class="panel">
|
||
<div class="toolbar">
|
||
<select id="a-type">
|
||
<option value="">全部实体类型</option>
|
||
${['SUPPLIER', 'CUSTOMER', 'SKU'].map((t) => `<option value="${t}" ${st.aliasType === t ? 'selected' : ''}>${t}</option>`).join('')}
|
||
</select>
|
||
<div class="spacer"></div>
|
||
<button class="btn primary" id="a-new">+ 新建映射</button>
|
||
</div>
|
||
<div class="note">别名映射用于跨系统主数据对齐(旧 ERP 编码、CRM 简称、Excel 台账名称等),是数据编织时实体解析的依据。</div>
|
||
<div class="table-wrap"><table>
|
||
<thead><tr><th>实体类型</th><th>实体</th><th>别名</th><th>来源系统</th><th>备注</th><th>创建时间</th><th>操作</th></tr></thead>
|
||
<tbody id="a-rows"><tr><td colspan="7" class="empty">加载中…</td></tr></tbody>
|
||
</table></div>
|
||
<div class="pager" id="a-pager"></div>
|
||
</div>`;
|
||
$('#a-type', body).onchange = () => {
|
||
st.aliasType = $('#a-type', body).value;
|
||
st.page.alias = 1;
|
||
renderAliases(body).catch((e) => toast(e.message, 'error'));
|
||
};
|
||
$('#a-new', body).onclick = () => openAliasForm().catch((e) => toast(e.message, 'error'));
|
||
const params = new URLSearchParams({ page: st.page.alias, page_size: 20 });
|
||
if (st.aliasType) params.set('entity_type', st.aliasType);
|
||
const d = await api('GET', '/api/aliases?' + params);
|
||
$('#a-rows', body).innerHTML = d.items.length
|
||
? d.items.map((a) => `<tr>
|
||
<td>${esc(a.entity_type)}</td>
|
||
<td>${a.entity_code ? `<span class="mono">${esc(a.entity_code)}</span> ${esc(a.entity_name)}` : `<span class="badge red">孤儿 #${a.entity_id}</span>`}</td>
|
||
<td>${esc(a.alias)}</td><td class="mono">${esc(a.source_system)}</td>
|
||
<td class="muted">${esc(a.remark || '—')}</td><td class="muted">${esc(a.created_at)}</td>
|
||
<td><button class="link-btn danger" data-id="${a.id}">删除</button></td></tr>`).join('')
|
||
: '<tr><td colspan="7" class="empty">暂无映射</td></tr>';
|
||
$$('button[data-id]', body).forEach((b) => {
|
||
b.onclick = async () => {
|
||
if (!await confirmDialog('删除该别名映射?映射可物理删除(不属于业务单据)。', '删除')) return;
|
||
try {
|
||
await api('DELETE', `/api/aliases/${b.dataset.id}`);
|
||
toast('已删除', 'success');
|
||
renderAliases(body).catch((e) => toast(e.message, 'error'));
|
||
} catch (e) { toast(e.message, 'error'); }
|
||
};
|
||
});
|
||
renderPager($('#a-pager', body), d.total, d.page, d.page_size, (p) => {
|
||
st.page.alias = p;
|
||
renderAliases(body).catch((e) => toast(e.message, 'error'));
|
||
});
|
||
}
|
||
|
||
async function openAliasForm() {
|
||
const entityCache = {};
|
||
const m = openModal(`
|
||
<h2>新建别名映射</h2>
|
||
<div class="form-grid">
|
||
<div class="field"><label>实体类型</label>
|
||
<select id="af-type"><option value="SUPPLIER">SUPPLIER(供应商)</option>
|
||
<option value="CUSTOMER">CUSTOMER(客户)</option><option value="SKU">SKU(商品)</option></select></div>
|
||
<div class="field"><label>主数据实体</label><select id="af-entity"></select></div>
|
||
<div class="field"><label>别名(外部编码/历史名称)</label><input id="af-alias" maxlength="128"></div>
|
||
<div class="field"><label>来源系统</label><input id="af-source" maxlength="64" placeholder="legacy_erp / legacy_crm / excel_import"></div>
|
||
<div class="field full"><label>备注</label><input id="af-remark" maxlength="255"></div>
|
||
</div>
|
||
<div class="modal-actions">
|
||
<button class="btn" id="af-cancel">取消</button>
|
||
<button class="btn primary" id="af-save">保存</button>
|
||
</div>`);
|
||
const loadEntities = async () => {
|
||
const t = $('#af-type', m.box).value;
|
||
const kind = t.toLowerCase();
|
||
if (!entityCache[kind]) entityCache[kind] = await api('GET', `/api/${kind}s/options`);
|
||
$('#af-entity', m.box).innerHTML = entityCache[kind]
|
||
.map((x) => `<option value="${x.id}">${esc(x.code)} ${esc(x.name)}${x.status !== 'ACTIVE' ? '(' + STATUS_LABEL[x.status] + ')' : ''}</option>`).join('');
|
||
};
|
||
$('#af-type', m.box).onchange = () => loadEntities().catch((e) => toast(e.message, 'error'));
|
||
await loadEntities();
|
||
$('#af-cancel', m.box).onclick = m.close;
|
||
$('#af-save', m.box).onclick = async () => {
|
||
const alias = $('#af-alias', m.box).value.trim();
|
||
const source = $('#af-source', m.box).value.trim();
|
||
if (!alias || !source) return toast('别名与来源系统不能为空', 'error');
|
||
try {
|
||
await api('POST', '/api/aliases', {
|
||
entity_type: $('#af-type', m.box).value,
|
||
entity_id: Number($('#af-entity', m.box).value),
|
||
alias, source_system: source,
|
||
remark: $('#af-remark', m.box).value.trim() || null,
|
||
});
|
||
toast('映射已创建', 'success');
|
||
closeAllModals();
|
||
refreshCurrent();
|
||
} catch (e) { toast(e.message, 'error'); }
|
||
};
|
||
}
|
||
|
||
/* ---------- 治理稽核 ---------- */
|
||
async function renderGovernance() {
|
||
const sec = $('#tab-governance');
|
||
sec.innerHTML = `
|
||
<div class="note">本页对应架构中的「集成与编织衔接层」:轻量质量稽核(dq_check)+ 库表元数据浏览。
|
||
敏感字段(联系电话)在所有 API 输出中统一脱敏;稽核结果可通过 <span class="mono">POST /api/governance/dq-check</span> 供 Dify/智能体调用。</div>
|
||
<div class="panel">
|
||
<div class="toolbar">
|
||
<h3 style="margin:0">数据质量稽核</h3>
|
||
<div class="spacer"></div>
|
||
<button class="btn primary" id="dq-run">运行稽核</button>
|
||
</div>
|
||
<div id="dq-result" class="muted">点击右上角运行稽核…</div>
|
||
</div>
|
||
<div class="panel">
|
||
<h3>库表元数据<span class="hint">来自 information_schema,字段注释即数据字典活文档</span></h3>
|
||
<div id="meta-list" class="muted">加载中…</div>
|
||
</div>`;
|
||
$('#dq-run', sec).onclick = () => runDq($('#dq-result', sec));
|
||
await runDq($('#dq-result', sec));
|
||
const meta = await api('GET', '/api/governance/tables');
|
||
$('#meta-list', sec).innerHTML = meta.tables.map((t) => `
|
||
<details class="meta-table">
|
||
<summary><span class="mono">${esc(t.table_name)}</span><span class="cmt">${esc(t.table_comment || '')} · ${t.columns.length} 个字段</span></summary>
|
||
<div class="table-wrap"><table>
|
||
<tr><th>字段</th><th>类型</th><th>可空</th><th>默认值</th><th>注释</th></tr>
|
||
${t.columns.map((c) => `<tr><td class="mono">${esc(c.name)}</td><td class="mono">${esc(c.type)}</td>
|
||
<td>${c.nullable ? '是' : '否'}</td><td class="mono">${esc(c.default ?? '—')}</td><td>${esc(c.comment || '—')}</td></tr>`).join('')}
|
||
</table></div>
|
||
</details>`).join('');
|
||
}
|
||
|
||
async function runDq(box) {
|
||
box.innerHTML = '<span class="muted">稽核运行中…</span>';
|
||
try {
|
||
const r = await api('POST', '/api/governance/dq-check');
|
||
box.innerHTML = `
|
||
<div class="cards" style="margin:12px 0">
|
||
<div class="card"><div class="label">规则总数</div><div class="value">${r.total_rules}</div></div>
|
||
<div class="card"><div class="label">通过</div><div class="value rule-pass">${r.passed}</div></div>
|
||
<div class="card"><div class="label">失败(ERROR)</div><div class="value ${r.failed ? 'rule-fail' : ''}">${r.failed}</div></div>
|
||
<div class="card"><div class="label">警告(WARN)</div><div class="value ${r.warned ? 'rule-warn' : ''}">${r.warned}</div></div>
|
||
</div>
|
||
<div class="muted" style="margin-bottom:8px">检查时间:${esc(r.checked_at)} · 总体结论:${r.healthy ? '<span class="rule-pass">健康(无 ERROR 级问题)</span>' : '<span class="rule-fail">存在 ERROR 级问题</span>'}</div>
|
||
<div class="table-wrap"><table>
|
||
<tr><th>编号</th><th>规则</th><th>级别</th><th>结果</th><th class="num">问题数</th><th>示例</th></tr>
|
||
${r.results.map((x) => `<tr>
|
||
<td class="mono">${x.id}</td><td style="white-space:normal">${esc(x.name)}</td>
|
||
<td>${x.level}</td>
|
||
<td>${x.passed ? '<span class="rule-pass">PASS</span>' : x.level === 'WARN' ? '<span class="rule-warn">WARN</span>' : '<span class="rule-fail">FAIL</span>'}</td>
|
||
<td class="num">${x.issue_count}</td>
|
||
<td class="samples">${x.samples.map(esc).join('<br>') || '—'}</td></tr>`).join('')}
|
||
</table></div>`;
|
||
} catch (e) {
|
||
box.innerHTML = `<span class="rule-fail">稽核失败:${esc(e.message)}</span>`;
|
||
}
|
||
}
|
||
|
||
/* ---------- 路由 ---------- */
|
||
let currentTab = 'dashboard';
|
||
const renderers = {
|
||
dashboard: renderDashboard,
|
||
purchase: () => renderOrders('purchase'),
|
||
sales: () => renderOrders('sales'),
|
||
inventory: renderInventory,
|
||
master: renderMaster,
|
||
governance: renderGovernance,
|
||
};
|
||
function refreshCurrent() {
|
||
renderers[currentTab]().catch((e) => toast(e.message, 'error'));
|
||
}
|
||
function switchTab(name) {
|
||
currentTab = name;
|
||
$$('#nav button').forEach((b) => b.classList.toggle('active', b.dataset.tab === name));
|
||
$$('.tab').forEach((s) => s.classList.toggle('active', s.id === 'tab-' + name));
|
||
refreshCurrent();
|
||
}
|
||
$$('#nav button').forEach((b) => { b.onclick = () => switchTab(b.dataset.tab); });
|
||
switchTab('dashboard'); |