/* 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 = ``; $('#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(`

请确认

${esc(message)}

`); $('[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) => `${esc(STATUS_LABEL[s] || s)}`; 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 = `共 ${total} 条 · 第 ${page}/${pages} 页 `; $('[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 = '
加载中…
'; const d = await api('GET', '/api/dashboard/summary'); const lowRows = d.low_stock.length ? d.low_stock.map((s) => `${esc(s.sku_code)}${esc(s.sku_name)} ${fmtQty(s.qty_on_hand)} ${esc(s.unit)} ${fmtQty(s.safety_stock)}低库存`).join('') : '暂无低库存预警'; const recentRows = (list, kind) => list.map((o) => ` ${esc(o.master_name)}${badge(o.status)} ${fmtMoney(o.total_amount)}${esc(o.order_date)}`).join('') || '暂无单据'; sec.innerHTML = `
启用供应商
${d.master.supplier_active}
启用客户
${d.master.customer_active}
启用 SKU
${d.master.sku_active}
有库存 SKU
${d.master.stock_sku}
累计采购入库金额
¥${fmtMoney(d.purchase.received_amount_total)}
本月 ¥${fmtMoney(d.purchase.received_amount_month)} · 已入库 ${d.purchase.received} 张
累计销售出库金额
¥${fmtMoney(d.sales.shipped_amount_total)}
本月 ¥${fmtMoney(d.sales.shipped_amount_month)} · 已出库 ${d.sales.shipped} 张

单据状态分布

类型草稿已确认已执行已作废
采购单${d.purchase.draft}${d.purchase.confirmed} ${d.purchase.received}(已入库)${d.purchase.cancelled}
销售单${d.sales.draft}${d.sales.confirmed} ${d.sales.shipped}(已出库)${d.sales.cancelled}

低库存预警现存量 < 安全库存

${lowRows}
SKU名称现存量安全库存预警

最近采购单

${recentRows(d.recent_purchase, 'purchase')}
单号供应商状态金额日期

最近销售单

${recentRows(d.recent_sales, 'sales')}
单号客户状态金额日期
`; $$('[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 = `
单号日期${cfg.masterLabel}状态 金额(元)经办人创建时间操作
加载中…
`; $('#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) => ` ${esc(o.order_date)} ${esc(o.master_name)} ${badge(o.status)} ${fmtMoney(o.total_amount)} ${esc(o.handler)} ${esc(o.created_at)} `).join('') : '暂无单据,点击右上角新建'; $$('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) => ` ${it.line_no}${esc(it.sku_code)}${esc(it.sku_name)} ${esc(it.unit)}${fmtQty(it.qty)} ${fmtMoney(it.price)}${fmtMoney(it.amount)}`).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(`

${cfg.title}详情 · ${esc(o.order_no)} ${badge(o.status)}

${cfg.masterLabel}
${esc(o.master_name)}(${esc(o.master_code)})
单据日期
${esc(o.order_date)}
经办人
${esc(o.handler)}
${cfg.executeLabel}时间
${esc(o.executed_at || '—')}
创建时间
${esc(o.created_at)}
备注
${esc(o.remark || '—')}
${itemRows}
行号SKU名称单位数量单价金额
合计金额:¥${fmtMoney(o.total_amount)}
`, { 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(`

${existing ? '编辑' : '新建'}${cfg.title}${existing ? ` · ${esc(existing.order_no)}` : ''}

明细行

SKU数量单价(元)金额
合计:¥0.00
`, { wide: true }); const tbody = $('#of-items', m.box); function addRow(it = null) { const tr = document.createElement('tr'); tr.innerHTML = ` 0.00 `; 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 = `
`; $$('[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 = `
SKU名称分类单位现存量安全库存状态最近变动
加载中…
`; 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) => ` ${esc(s.sku_code)}${esc(s.sku_name)}${esc(s.category || '—')} ${esc(s.unit)}${fmtQty(s.qty_on_hand)} ${fmtQty(s.safety_stock)} ${s.low_stock ? '低库存' : '正常'} ${esc(s.updated_at)}`).join('') : '暂无库存记录'; 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 = `
时间SKU类型来源单号变动结存备注
加载中…
`; 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) => ` ${esc(f.created_at)} ${esc(f.sku_code)} ${esc(BIZ_LABEL[f.biz_type] || f.biz_type)} ${esc(f.biz_order_no || '—')} ${f.qty_delta >= 0 ? '+' : ''}${fmtQty(f.qty_delta)} ${fmtQty(f.qty_after)} ${esc(f.remark || '—')}`).join('') : '暂无流水'; 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 = `
${MASTER_TABS.map(([k, label]) => ``).join('')}
`; $$('[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 = `
治理规则:编码唯一且创建后不可修改;已被业务引用的记录禁止物理删除,只能停用/作废;作废为终态。
${isSku ? '' : ''}
编码名称分类规格单位采购价销售价安全库存状态操作编码名称联系人电话(脱敏)状态备注操作
加载中…
`; 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) => ` ${esc(r.code)}${esc(r.name)} ${isSku ? `${esc(r.category || '—')}${esc(r.spec || '—')}${esc(r.unit)} ${fmtMoney(r.purchase_price)}${fmtMoney(r.sale_price)} ${fmtQty(r.safety_stock)}` : `${esc(r.contact_person || '—')}${esc(r.contact_phone || '—')}`} ${badge(r.status)} ${isSku ? '' : `${esc(r.remark || '—')}`} ${r.status === 'ACTIVE' ? `` : ''} ${r.status === 'DISABLED' ? `` : ''} ${r.status !== 'VOID' ? `` : ''} `).join('') : '暂无记录'; $$('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(`

${existing ? '编辑' : '新建'}${label}${existing ? ` · ${v('code')}` : ''}

${isSku ? `
` : `
`}
${!isSku && existing ? '
出于敏感字段保护,编辑时电话输入框不回显原值:填写新号码则覆盖,留空则清除该字段。
' : ''} `, { 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 = `
别名映射用于跨系统主数据对齐(旧 ERP 编码、CRM 简称、Excel 台账名称等),是数据编织时实体解析的依据。
实体类型实体别名来源系统备注创建时间操作
加载中…
`; $('#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) => ` ${esc(a.entity_type)} ${a.entity_code ? `${esc(a.entity_code)} ${esc(a.entity_name)}` : `孤儿 #${a.entity_id}`} ${esc(a.alias)}${esc(a.source_system)} ${esc(a.remark || '—')}${esc(a.created_at)} `).join('') : '暂无映射'; $$('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(`

新建别名映射

`); 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) => ``).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 = `
本页对应架构中的「集成与编织衔接层」:轻量质量稽核(dq_check)+ 库表元数据浏览。 敏感字段(联系电话)在所有 API 输出中统一脱敏;稽核结果可通过 POST /api/governance/dq-check 供 Dify/智能体调用。

数据质量稽核

点击右上角运行稽核…

库表元数据来自 information_schema,字段注释即数据字典活文档

加载中…
`; $('#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) => `
${esc(t.table_name)}${esc(t.table_comment || '')} · ${t.columns.length} 个字段
${t.columns.map((c) => ``).join('')}
字段类型可空默认值注释
${esc(c.name)}${esc(c.type)} ${c.nullable ? '是' : '否'}${esc(c.default ?? '—')}${esc(c.comment || '—')}
`).join(''); } async function runDq(box) { box.innerHTML = '稽核运行中…'; try { const r = await api('POST', '/api/governance/dq-check'); box.innerHTML = `
规则总数
${r.total_rules}
通过
${r.passed}
失败(ERROR)
${r.failed}
警告(WARN)
${r.warned}
检查时间:${esc(r.checked_at)} · 总体结论:${r.healthy ? '健康(无 ERROR 级问题)' : '存在 ERROR 级问题'}
${r.results.map((x) => ``).join('')}
编号规则级别结果问题数示例
${x.id}${esc(x.name)} ${x.level} ${x.passed ? 'PASS' : x.level === 'WARN' ? 'WARN' : 'FAIL'} ${x.issue_count} ${x.samples.map(esc).join('
') || '—'}
`; } catch (e) { box.innerHTML = `稽核失败:${esc(e.message)}`; } } /* ---------- 路由 ---------- */ 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');