ops.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. 'use strict';
  2. // 店铺运营页:上传人工统计表 → 按学校/店铺/日期看指标矩阵或卡片。
  3. // 数据来自 /api/ops/*;原件存服务端存储(默认本地 SQLite),页面只做展示与上传。
  4. (function () {
  5. const $ = (id) => document.getElementById(id);
  6. const META = {
  7. order_cnt: { label: '订单量', type: 'int' },
  8. revenue: { label: '营收', type: 'money' },
  9. exposure: { label: '曝光量', type: 'int' },
  10. click_rate: { label: '进店转化率', type: 'rate' },
  11. };
  12. const ALL_METRICS = Object.keys(META);
  13. const DEFAULT_METRICS = ALL_METRICS.slice();
  14. function loadJSON(key, fallback) {
  15. try {
  16. const raw = localStorage.getItem(key);
  17. if (!raw) return fallback;
  18. const v = JSON.parse(raw);
  19. return Array.isArray(v) && v.length ? v.filter((x) => ALL_METRICS.includes(x)) : fallback;
  20. } catch {
  21. return fallback;
  22. }
  23. }
  24. const state = {
  25. inited: false,
  26. loading: false,
  27. summary: null,
  28. data: null,
  29. schools: null, // null = 全选
  30. metrics: loadJSON('ops.metrics', DEFAULT_METRICS),
  31. view: localStorage.getItem('ops.view') === 'cards' ? 'cards' : 'table',
  32. from: '',
  33. to: '',
  34. upload: { files: [], busy: false },
  35. };
  36. function esc(value) {
  37. const div = document.createElement('div');
  38. div.textContent = String(value == null ? '' : value);
  39. return div.innerHTML;
  40. }
  41. function ymdToInput(ymd) {
  42. const s = String(ymd || '');
  43. return /^\d{8}$/.test(s) ? `${s.slice(0, 4)}-${s.slice(4, 6)}-${s.slice(6, 8)}` : '';
  44. }
  45. function inputToYmd(value) {
  46. return String(value || '').replace(/-/g, '');
  47. }
  48. function shortDate(ymd) {
  49. const s = String(ymd || '');
  50. return /^\d{8}$/.test(s) ? `${Number(s.slice(4, 6))}.${Number(s.slice(6, 8))}` : s;
  51. }
  52. function fmtValue(value, metric) {
  53. if (value === null || value === undefined) return '–';
  54. const n = Number(value);
  55. if (!Number.isFinite(n)) return '–';
  56. if (META[metric].type === 'rate') return (n * 100).toFixed(1) + '%';
  57. if (META[metric].type === 'money') return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  58. return n.toLocaleString('zh-CN');
  59. }
  60. function selectedSchools() {
  61. if (!state.summary) return [];
  62. const all = state.summary.schools.map((s) => s.name);
  63. return state.schools === null ? all : all.filter((name) => state.schools.has(name));
  64. }
  65. async function api(url, options) {
  66. const res = await fetch(url, options);
  67. const isJson = /application\/json/.test(res.headers.get('content-type') || '');
  68. const body = isJson ? await res.json().catch(() => null) : null;
  69. return { res, body };
  70. }
  71. // ---------- 概览 / 数据 ----------
  72. async function loadSummary() {
  73. const { body } = await api('/api/ops/summary');
  74. state.summary = body || { enabled: false, reason: 'storage-unreachable' };
  75. if (state.summary.enabled && state.summary.coverage) {
  76. if (!state.from) state.from = state.summary.coverage.from;
  77. if (!state.to) state.to = state.summary.coverage.to;
  78. }
  79. return state.summary;
  80. }
  81. async function loadRows() {
  82. if (!state.summary || !state.summary.enabled) return;
  83. if (state.schools !== null && state.schools.size === 0) {
  84. state.data = null;
  85. state.loading = false;
  86. renderBody();
  87. return;
  88. }
  89. state.loading = true;
  90. renderBody();
  91. const params = new URLSearchParams();
  92. if (state.from) params.set('from', state.from);
  93. if (state.to) params.set('to', state.to);
  94. const schools = state.schools === null ? [] : [...state.schools];
  95. if (schools.length && schools.length !== (state.summary.schools || []).length) params.set('schools', schools.join(','));
  96. params.set('metrics', state.metrics.join(','));
  97. const { res, body } = await api('/api/ops/rows?' + params.toString());
  98. state.loading = false;
  99. if (!res.ok) {
  100. state.data = null;
  101. state.error = (body && (body.detail || body.error)) || `HTTP ${res.status}`;
  102. } else {
  103. state.data = body;
  104. state.error = null;
  105. }
  106. renderBody();
  107. }
  108. // ---------- 工具条 ----------
  109. function renderBar() {
  110. const bar = $('opsBar');
  111. if (!bar) return;
  112. const summary = state.summary;
  113. const matrixRows = matrixCount(summary);
  114. if (!summary || !summary.enabled || !matrixRows) {
  115. bar.innerHTML = '';
  116. return;
  117. }
  118. const schools = summary.schools || [];
  119. const chosen = state.schools === null ? new Set(schools.map((s) => s.name)) : state.schools;
  120. bar.innerHTML = `
  121. <div class="ops-bar">
  122. <div class="ops-bar-group">
  123. <span class="ops-bar-label">学校</span>
  124. <div class="ops-chips" id="opsSchoolChips">
  125. ${schools.map((s) => `<button type="button" class="ops-chip${chosen.has(s.name) ? ' on' : ''}" data-school="${esc(s.name)}">${esc(s.name)}<em>${s.shopCount}</em></button>`).join('')}
  126. </div>
  127. </div>
  128. <div class="ops-bar-group">
  129. <span class="ops-bar-label">日期</span>
  130. <input type="date" class="ops-input" id="opsFrom" value="${ymdToInput(state.from)}">
  131. <span class="ops-tilde">~</span>
  132. <input type="date" class="ops-input" id="opsTo" value="${ymdToInput(state.to)}">
  133. </div>
  134. <div class="ops-bar-group">
  135. <span class="ops-bar-label">指标</span>
  136. <div class="ops-chips" id="opsMetricChips">
  137. ${ALL_METRICS.map((k) => `<button type="button" class="ops-chip${state.metrics.includes(k) ? ' on' : ''}" data-metric="${k}">${META[k].label}</button>`).join('')}
  138. </div>
  139. </div>
  140. </div>`;
  141. renderHeaderTools();
  142. bar.querySelectorAll('[data-school]').forEach((btn) => {
  143. btn.addEventListener('click', () => {
  144. const name = btn.dataset.school;
  145. const current = state.schools === null ? new Set(schools.map((s) => s.name)) : new Set(state.schools);
  146. if (current.has(name)) current.delete(name); else current.add(name);
  147. state.schools = current.size === schools.length ? null : current;
  148. if (!current.size) state.schools = new Set();
  149. renderBar();
  150. loadRows();
  151. });
  152. });
  153. bar.querySelectorAll('[data-metric]').forEach((btn) => {
  154. btn.addEventListener('click', () => {
  155. const key = btn.dataset.metric;
  156. if (state.metrics.includes(key)) {
  157. if (state.metrics.length === 1) return; // 至少保留一个指标
  158. state.metrics = state.metrics.filter((k) => k !== key);
  159. } else {
  160. state.metrics = ALL_METRICS.filter((k) => key === k || state.metrics.includes(k));
  161. }
  162. localStorage.setItem('ops.metrics', JSON.stringify(state.metrics));
  163. renderBar();
  164. renderBody();
  165. });
  166. });
  167. $('opsFrom').addEventListener('change', (e) => { state.from = inputToYmd(e.target.value); loadRows(); });
  168. $('opsTo').addEventListener('change', (e) => { state.to = inputToYmd(e.target.value); loadRows(); });
  169. }
  170. function matrixCount(summary) {
  171. if (!summary) return 0;
  172. return Number(summary.matrixRowCount != null ? summary.matrixRowCount : summary.rowCount) || 0;
  173. }
  174. function renderHeaderTools() {
  175. const el = $('opsHeaderTools');
  176. if (!el) return;
  177. const summary = state.summary;
  178. if (!summary || !summary.enabled || !matrixCount(summary)) {
  179. el.innerHTML = '';
  180. return;
  181. }
  182. el.innerHTML = `<div class="ops-seg" id="opsViewSeg">
  183. <button type="button" data-mode="table" class="${state.view === 'table' ? 'on' : ''}">报表</button>
  184. <button type="button" data-mode="cards" class="${state.view === 'cards' ? 'on' : ''}">卡片</button>
  185. </div>
  186. <button type="button" class="btn btn-ghost btn-small" id="opsExport">导出 CSV</button>`;
  187. el.querySelectorAll('#opsViewSeg [data-mode]').forEach((btn) => {
  188. btn.addEventListener('click', () => {
  189. state.view = btn.dataset.mode;
  190. localStorage.setItem('ops.view', state.view);
  191. renderHeaderTools();
  192. renderBody();
  193. });
  194. });
  195. $('opsExport').addEventListener('click', () => {
  196. const params = new URLSearchParams();
  197. if (state.from) params.set('from', state.from);
  198. if (state.to) params.set('to', state.to);
  199. if (state.schools !== null && state.schools.size) params.set('schools', [...state.schools].join(','));
  200. params.set('metrics', state.metrics.join(','));
  201. window.open('/api/ops/export?' + params.toString(), '_blank');
  202. });
  203. }
  204. // ---------- 内容区 ----------
  205. function renderBody() {
  206. const body = $('opsBody');
  207. if (!body) return;
  208. const summary = state.summary;
  209. if (!summary) {
  210. body.innerHTML = '<div class="empty-hint"><p>正在加载…</p></div>';
  211. return;
  212. }
  213. if (!summary.enabled) {
  214. const reasonText = {
  215. 'storage-not-configured': '未配置存储(config.json → storage)',
  216. 'storage-unreachable': '存储连接失败',
  217. 'pg-not-installed': '未安装 pg 依赖',
  218. 'sqlite-unavailable': '当前 Node 版本不支持内置 SQLite(需要 22.5+)',
  219. }[summary.reason] || '存储不可用';
  220. body.innerHTML = `
  221. <div class="empty-hint ops-empty">
  222. <p>店铺运营数据暂不可用</p>
  223. <small>${esc(reasonText)}${summary.detail ? ':' + esc(summary.detail) : ''}</small>
  224. <button type="button" class="btn btn-ghost btn-small" id="opsRetry" style="margin-top:14px">重试</button>
  225. </div>`;
  226. $('opsRetry').addEventListener('click', () => init(true));
  227. return;
  228. }
  229. const matrixRows = matrixCount(summary);
  230. if (!matrixRows) {
  231. const platformRows = Number(summary.platformRowCount) || 0;
  232. body.innerHTML = platformRows > 0
  233. ? `<div class="empty-hint ops-empty">
  234. <p>已导入 ${platformRows} 行平台明细</p>
  235. <small>平台全字段数据已入库(可在「导入记录」查看原件与行数);<br>上报人工统计表后,这里会显示指标矩阵</small>
  236. <button type="button" class="btn btn-primary btn-small" id="opsEmptyUpload" style="margin-top:14px">上传文件</button>
  237. </div>`
  238. : `<div class="empty-hint ops-empty">
  239. <p>还没有店铺运营数据</p>
  240. <small>上传商家后台导出的人工统计表(.xlsx),解析后按学校 / 店铺 / 日期查看</small>
  241. <button type="button" class="btn btn-primary btn-small" id="opsEmptyUpload" style="margin-top:14px">上传文件</button>
  242. </div>`;
  243. $('opsEmptyUpload').addEventListener('click', openUpload);
  244. return;
  245. }
  246. if (state.error) {
  247. body.innerHTML = `<div class="empty-hint ops-empty"><p>数据加载失败</p><small>${esc(state.error)}</small>
  248. <button type="button" class="btn btn-ghost btn-small" id="opsReload" style="margin-top:14px">重试</button></div>`;
  249. $('opsReload').addEventListener('click', loadRows);
  250. return;
  251. }
  252. if (state.loading && !state.data) {
  253. body.innerHTML = '<div class="empty-hint"><p>正在加载…</p></div>';
  254. return;
  255. }
  256. if (state.schools !== null && state.schools.size === 0) {
  257. body.innerHTML = '<div class="empty-hint ops-empty"><p>请至少选择一个学校</p></div>';
  258. return;
  259. }
  260. if (!state.data) return;
  261. body.innerHTML = state.view === 'cards' ? renderCards(state.data) : renderTables(state.data);
  262. if (state.view === 'table') bindRowHover();
  263. }
  264. function cellValue(shop, metric, date) {
  265. const series = shop.series[metric] || {};
  266. return Object.prototype.hasOwnProperty.call(series, date) ? series[date] : null;
  267. }
  268. function metricCell(shop, metric, date) {
  269. const value = cellValue(shop, metric, date);
  270. const quality = (shop.quality || {})[date];
  271. const warn = quality && quality.length
  272. ? `<span class="ops-warn" title="${esc('解析标记:' + quality.join('、'))}">⚠</span>`
  273. : '';
  274. return `<td class="ops-num${value == null ? ' ops-null' : ''}">${fmtValue(value, metric)}${warn}</td>`;
  275. }
  276. /** 学校小计:数量/金额求和,转化率按曝光加权 */
  277. function subtotalValue(group, metric, date) {
  278. if (metric === 'click_rate') {
  279. let weight = 0;
  280. let acc = 0;
  281. for (const shop of group.shops) {
  282. const exposure = cellValue(shop, 'exposure', date);
  283. const rate = cellValue(shop, 'click_rate', date);
  284. if (typeof exposure === 'number' && exposure > 0 && typeof rate === 'number') {
  285. weight += exposure;
  286. acc += rate * exposure;
  287. }
  288. }
  289. return weight > 0 ? acc / weight : null;
  290. }
  291. let sum = 0;
  292. let seen = false;
  293. for (const shop of group.shops) {
  294. const v = cellValue(shop, metric, date);
  295. if (typeof v === 'number') { sum += v; seen = true; }
  296. }
  297. return seen ? sum : null;
  298. }
  299. function renderTables(data) {
  300. const metrics = state.metrics.filter((m) => META[m]);
  301. if (!metrics.length) return '<div class="empty-hint"><p>请至少选择一个指标</p></div>';
  302. const dates = data.dates || [];
  303. const colCount = metrics.length + 2;
  304. const head = `<tr>
  305. <th class="ops-shop-col">店铺</th>
  306. <th class="ops-date-col">日期</th>
  307. ${metrics.map((m) => `<th class="ops-metric-col">${META[m].label}</th>`).join('')}
  308. </tr>`;
  309. const body = data.groups.map((group, groupIdx) => {
  310. const schoolRow = `<tr class="ops-school-row"><td colspan="${colCount}">${esc(group.school)}<em>${group.shops.length} 家</em></td></tr>`;
  311. const shopRows = group.shops.map((shop, shopIdx) => {
  312. const shopDates = dates.filter((d) => metrics.some((m) => cellValue(shop, m, d) !== null));
  313. const useDates = shopDates.length ? shopDates : dates.slice(0, 1);
  314. // 每个店铺一个色块与悬停组,日期行共用同一个 block key
  315. const blockKey = `b${groupIdx}-${shopIdx}`;
  316. const alt = shopIdx % 2 === 1 ? ' ops-block-alt' : '';
  317. return useDates.map((date, i) => `<tr data-block="${blockKey}" class="ops-shop-row${i === 0 ? ' ops-block-start' : ''}${alt}">
  318. ${i === 0 ? `<td class="ops-shop-cell" rowspan="${useDates.length}" title="${esc(shop.shopName)}">${esc(shop.shopName)}${
  319. shop.status && shop.status !== '已上线' ? `<span class="badge badge-muted ops-status">${esc(shop.status)}</span>` : ''
  320. }</td>` : ''}
  321. <td class="ops-date-cell">${shortDate(date)}</td>
  322. ${metrics.map((m) => metricCell(shop, m, date)).join('')}
  323. </tr>`).join('');
  324. }).join('');
  325. const subtotalDates = dates.filter((d) => group.shops.some((shop) => metrics.some((m) => cellValue(shop, m, d) !== null)));
  326. const subtotalRows = subtotalDates.map((date) => `<tr class="ops-subtotal-row">
  327. <td class="ops-subtotal-label" colspan="2">${esc(group.school)} · 小计 · ${shortDate(date)}</td>
  328. ${metrics.map((m) => {
  329. const v = subtotalValue(group, m, date);
  330. return `<td class="ops-num ops-subtotal">${v == null ? '–' : fmtValue(v, m)}</td>`;
  331. }).join('')}
  332. </tr>`).join('');
  333. return schoolRow + shopRows + subtotalRows;
  334. }).join('');
  335. const shopCount = data.groups.reduce((n, g) => n + g.shops.length, 0);
  336. return `<section class="ops-block">
  337. <div class="ops-block-head"><h2>运营明细</h2><span>${shopCount} 家门店 · ${dates.length} 天 · ${metrics.length} 个指标</span></div>
  338. <div class="ops-table-wrap">
  339. <table class="ops-table ops-table-wide">
  340. <thead>${head}</thead>
  341. <tbody>${body}</tbody>
  342. </table>
  343. </div>
  344. </section>`;
  345. }
  346. /** 悬停时整块高亮(同一店铺的多天一起亮),避免分不清行属于哪家店 */
  347. function bindRowHover() {
  348. document.querySelectorAll('.ops-table-wide tbody').forEach((tbody) => {
  349. if (tbody.dataset.hoverBound === '1') return;
  350. tbody.dataset.hoverBound = '1';
  351. const clear = () => tbody.querySelectorAll('tr.ops-hover').forEach((tr) => tr.classList.remove('ops-hover'));
  352. tbody.addEventListener('mouseover', (e) => {
  353. const tr = e.target.closest('tr[data-block]');
  354. if (!tr) return;
  355. if (tr.classList.contains('ops-hover')) return;
  356. clear();
  357. tbody.querySelectorAll(`tr[data-block="${tr.dataset.block}"]`).forEach((row) => row.classList.add('ops-hover'));
  358. });
  359. tbody.addEventListener('mouseleave', clear);
  360. });
  361. }
  362. function sparkline(shop, metric, dates) {
  363. const values = dates.map((d) => {
  364. const v = (shop.series[metric] || {})[d];
  365. return typeof v === 'number' ? v : null;
  366. });
  367. const nums = values.filter((v) => v != null);
  368. if (nums.length < 2) return '';
  369. const min = Math.min(...nums);
  370. const max = Math.max(...nums);
  371. const span = max - min || 1;
  372. const w = 160;
  373. const h = 34;
  374. const step = w / Math.max(values.length - 1, 1);
  375. const points = [];
  376. values.forEach((v, i) => {
  377. if (v == null) return;
  378. const x = (i * step).toFixed(1);
  379. const y = (h - ((v - min) / span) * (h - 6) - 3).toFixed(1);
  380. points.push(`${x},${y}`);
  381. });
  382. return `<svg class="ops-spark" viewBox="0 0 ${w} ${h}" preserveAspectRatio="none" aria-hidden="true"><polyline points="${points.join(' ')}" /></svg>`;
  383. }
  384. function renderCards(data) {
  385. const dates = data.dates || [];
  386. const metric = state.metrics[0];
  387. return `<div class="ops-cards">${data.groups.map((group) => `
  388. <section class="ops-card-group">
  389. <h3>${esc(group.school)}</h3>
  390. <div class="ops-card-grid">
  391. ${group.shops.map((shop) => `
  392. <article class="ops-card">
  393. <div class="ops-card-head">
  394. <span class="ops-card-name" title="${esc(shop.shopName)}">${esc(shop.shopName)}</span>
  395. ${shop.status && shop.status !== '已上线' ? `<span class="badge badge-muted">${esc(shop.status)}</span>` : ''}
  396. </div>
  397. <div class="ops-card-metrics">
  398. ${state.metrics.map((m) => `<div class="ops-card-metric"><span>${META[m].label}</span><b>${m === 'click_rate' ? fmtValue(avgRate(shop, dates), m) : fmtValue(shop.totals && shop.totals[m], m)}</b></div>`).join('')}
  399. </div>
  400. ${sparkline(shop, metric, dates)}
  401. </article>`).join('')}
  402. </div>
  403. </section>`).join('')}</div>`;
  404. }
  405. function avgRate(shop, dates) {
  406. let weight = 0;
  407. let acc = 0;
  408. for (const date of dates) {
  409. const exposure = (shop.series.exposure || {})[date];
  410. const rate = (shop.series.click_rate || {})[date];
  411. if (typeof exposure === 'number' && exposure > 0 && typeof rate === 'number') {
  412. weight += exposure;
  413. acc += rate * exposure;
  414. }
  415. }
  416. return weight > 0 ? acc / weight : null;
  417. }
  418. // ---------- 上传 ----------
  419. async function refreshSchoolOptions() {
  420. const select = $('opsSchool');
  421. if (!select) return;
  422. // 已登记学校(校区地图里的学校注册表,含内置)
  423. const registered = [];
  424. try {
  425. const { res, body } = await api('/api/schools');
  426. if (res.ok) {
  427. for (const school of (body && body.schools) || []) {
  428. if (!school || !school.name) continue;
  429. registered.push({
  430. name: school.name,
  431. hint: [school.province, school.city].filter(Boolean).join(' · '),
  432. });
  433. }
  434. }
  435. } catch { /* 注册表取不到时回落到运营数据里的学校 */ }
  436. // 运营数据中出现过、但还没登记的学校
  437. const registeredNames = new Set(registered.map((x) => x.name));
  438. const fromOps = ((state.summary && state.summary.schools) || [])
  439. .map((x) => x.name)
  440. .filter((name) => name && !registeredNames.has(name));
  441. select.innerHTML = '<option value="">自动(读取表格里的「学校名称」列)</option>'
  442. + (registered.length
  443. ? `<optgroup label="已登记学校">${registered.map((x) => `<option value="${esc(x.name)}">${esc(x.name)}${x.hint ? '(' + esc(x.hint) + ')' : ''}</option>`).join('')}</optgroup>`
  444. : '')
  445. + (fromOps.length
  446. ? `<optgroup label="运营数据中的学校">${fromOps.map((name) => `<option value="${esc(name)}">${esc(name)}</option>`).join('')}</optgroup>`
  447. : '')
  448. + '<option value="__custom">手动输入…</option>';
  449. select.value = '';
  450. const custom = $('opsSchoolCustom');
  451. if (custom) {
  452. custom.value = '';
  453. custom.hidden = true;
  454. }
  455. }
  456. function selectedSchool() {
  457. const select = $('opsSchool');
  458. if (!select) return '';
  459. if (select.value === '__custom') return String(($('opsSchoolCustom') || {}).value || '').trim();
  460. return select.value;
  461. }
  462. function fileKey(f) {
  463. return f.name + '|' + f.size + '|' + (f.lastModified || 0);
  464. }
  465. function addFiles(fileList) {
  466. for (const f of Array.from(fileList || [])) {
  467. if (!/\.xlsx$/i.test(f.name)) continue;
  468. const key = fileKey(f);
  469. if (state.upload.files.some((x) => fileKey(x.file) === key)) continue;
  470. state.upload.files.push({ file: f, status: 'pending', message: '' });
  471. }
  472. renderFileList();
  473. }
  474. function renderFileList() {
  475. const box = $('opsFileList');
  476. if (!box) return;
  477. if (!state.upload.files.length) {
  478. box.innerHTML = '';
  479. return;
  480. }
  481. box.innerHTML = state.upload.files.map((item, i) => {
  482. const cls = item.status === 'error' ? 'ops-error'
  483. : item.status === 'done' ? 'ops-done-text'
  484. : item.status === 'duplicate' ? 'ops-muted' : '';
  485. const msg = item.message ? `<em class="${cls}">${esc(item.message)}</em>` : '';
  486. const removable = item.status !== 'uploading';
  487. return `<div class="ops-file-item">
  488. <span class="ops-file-name2" title="${esc(item.file.name)}">${esc(item.file.name)}</span>
  489. <span class="ops-file-size">${(item.file.size / 1024).toFixed(0)} KB</span>
  490. ${msg}
  491. ${removable ? `<button type="button" class="ops-file-del" data-idx="${i}" title="移除">×</button>` : ''}
  492. </div>`;
  493. }).join('');
  494. box.querySelectorAll('[data-idx]').forEach((btn) => {
  495. btn.addEventListener('click', () => {
  496. const i = Number(btn.dataset.idx);
  497. if (state.upload.files[i] && state.upload.files[i].status === 'uploading') return;
  498. state.upload.files.splice(i, 1);
  499. renderFileList();
  500. });
  501. });
  502. }
  503. async function openUpload() {
  504. const modal = $('opsUploadModal');
  505. if (!modal) return;
  506. state.upload.files = [];
  507. renderFileList();
  508. $('opsUploadResult').innerHTML = '';
  509. $('opsYear').value = String(new Date().getFullYear());
  510. await refreshSchoolOptions();
  511. if ($('opsForce')) $('opsForce').checked = false;
  512. $('opsUploadStart').disabled = false;
  513. modal.hidden = false;
  514. }
  515. function closeUpload() {
  516. const modal = $('opsUploadModal');
  517. if (modal) modal.hidden = true;
  518. }
  519. function readFileBase64(file) {
  520. return new Promise((resolve, reject) => {
  521. const reader = new FileReader();
  522. reader.onload = () => {
  523. const text = String(reader.result || '');
  524. resolve(text.slice(text.indexOf(',') + 1));
  525. };
  526. reader.onerror = () => reject(reader.error || new Error('读取文件失败'));
  527. reader.readAsDataURL(file);
  528. });
  529. }
  530. async function doUpload(forceOverride) {
  531. const items = state.upload.files;
  532. const result = $('opsUploadResult');
  533. if (!items.length) {
  534. result.innerHTML = '<span class="ops-error">请先选择 .xlsx 文件(可一次选多个)</span>';
  535. return;
  536. }
  537. if (items.length > 30) {
  538. result.innerHTML = '<span class="ops-error">一次最多 30 个文件</span>';
  539. return;
  540. }
  541. const year = Number($('opsYear').value) || new Date().getFullYear();
  542. const school = selectedSchool();
  543. const force = !!(forceOverride || ($('opsForce') && $('opsForce').checked));
  544. $('opsUploadStart').disabled = true;
  545. result.innerHTML = '<span class="ops-muted">正在逐个解析并入库…</span>';
  546. let okCount = 0;
  547. let skipCount = 0;
  548. let failCount = 0;
  549. for (const item of items) {
  550. if (item.status === 'done') continue;
  551. item.status = 'uploading';
  552. item.message = '导入中…';
  553. renderFileList();
  554. try {
  555. const base64 = await readFileBase64(item.file);
  556. const { res, body } = await api('/api/ops/upload', {
  557. method: 'POST',
  558. headers: { 'Content-Type': 'application/json' },
  559. body: JSON.stringify({ fileName: item.file.name, contentBase64: base64, year, school, force }),
  560. });
  561. if (res.status === 409) {
  562. item.status = 'duplicate';
  563. item.message = '已导入过(跳过)';
  564. skipCount += 1;
  565. } else if (!res.ok) {
  566. const detail = body && (body.detail ? body.error + ':' + body.detail : body.error);
  567. item.status = 'error';
  568. item.message = detail || ('失败 HTTP ' + res.status);
  569. failCount += 1;
  570. } else {
  571. const r = body.report || {};
  572. item.status = 'done';
  573. if (r.kind === 'platform-export') {
  574. const parts = ['新增 ' + r.newRows + ' 行'];
  575. if (r.identicalRows) parts.push('已存在 ' + r.identicalRows + ' 行');
  576. if (r.conflictRows) parts.push('冲突 ' + r.conflictRows + ' 行');
  577. item.message = parts.join(' · ');
  578. } else {
  579. item.message = r.rows + ' 行 · ' + r.shops + ' 家';
  580. }
  581. okCount += 1;
  582. }
  583. } catch (e) {
  584. item.status = 'error';
  585. item.message = e.message || String(e);
  586. failCount += 1;
  587. }
  588. renderFileList();
  589. }
  590. const parts = ['成功 ' + okCount + ' 个'];
  591. if (skipCount) parts.push('跳过 ' + skipCount + ' 个(已导入过)');
  592. if (failCount) parts.push('失败 ' + failCount + ' 个');
  593. result.innerHTML = `<div class="${failCount ? 'ops-error' : 'ops-ok'}">${parts.join(',')}${
  594. skipCount && !force ? '<br><small>已存在的文件可勾选下方「覆盖已导入的文件」后重新导入</small>' : ''
  595. }</div>`;
  596. $('opsUploadStart').disabled = false;
  597. if (okCount) {
  598. state.from = '';
  599. state.to = '';
  600. state.schools = null;
  601. await init(true);
  602. }
  603. }
  604. // ---------- 导入记录 ----------
  605. async function openRecords() {
  606. const modal = $('opsRecordsModal');
  607. if (!modal) return;
  608. modal.hidden = false;
  609. const list = $('opsRecordsList');
  610. list.innerHTML = '<div class="ops-muted" style="padding:16px">加载中…</div>';
  611. const { res, body } = await api('/api/ops/uploads');
  612. if (!res.ok) {
  613. list.innerHTML = `<div class="ops-error" style="padding:16px">${esc((body && (body.detail || body.error)) || ('HTTP ' + res.status))}</div>`;
  614. return;
  615. }
  616. const uploads = (body && body.uploads) || [];
  617. if (!uploads.length) {
  618. list.innerHTML = '<div class="ops-muted" style="padding:16px">还没有导入记录</div>';
  619. return;
  620. }
  621. list.innerHTML = `<table class="data-table">
  622. <thead><tr><th>文件名</th><th>上传时间</th><th>行数</th><th>门店</th><th>警告</th><th class="col-actions">操作</th></tr></thead>
  623. <tbody>${uploads.map((u) => `<tr>
  624. <td>${esc(u.originalName)}</td>
  625. <td>${esc(new Date(u.uploadedAt).toLocaleString('zh-CN'))}</td>
  626. <td>${u.rows || 0}</td>
  627. <td>${u.shops || 0}</td>
  628. <td>${u.warningCount || 0}</td>
  629. <td class="col-actions">
  630. <a class="btn btn-ghost btn-small" href="/api/ops/uploads/${esc(u.id)}/file">下载原件</a>
  631. <button type="button" class="btn btn-ghost btn-small" data-reparse="${esc(u.id)}">重新解析</button>
  632. </td>
  633. </tr>`).join('')}</tbody>
  634. </table>`;
  635. list.querySelectorAll('[data-reparse]').forEach((btn) => {
  636. btn.addEventListener('click', async () => {
  637. btn.disabled = true;
  638. btn.textContent = '解析中…';
  639. const { res, body: rep } = await api(`/api/ops/uploads/${btn.dataset.reparse}/reparse`, { method: 'POST' });
  640. btn.disabled = false;
  641. btn.textContent = '重新解析';
  642. if (!res.ok) {
  643. alert((rep && (rep.detail || rep.error)) || '重新解析失败');
  644. return;
  645. }
  646. await init(true);
  647. });
  648. });
  649. }
  650. // ---------- 初始化 ----------
  651. async function init(force) {
  652. if (state.inited && !force) return;
  653. state.inited = true;
  654. await loadSummary();
  655. renderBar();
  656. renderHeaderTools();
  657. renderBody();
  658. if (state.summary && state.summary.enabled && matrixCount(state.summary)) await loadRows();
  659. }
  660. function bindOnce() {
  661. const uploadBtn = $('btnOpsUpload');
  662. if (uploadBtn) uploadBtn.addEventListener('click', openUpload);
  663. const recordsBtn = $('btnOpsRecords');
  664. if (recordsBtn) recordsBtn.addEventListener('click', openRecords);
  665. const start = $('opsUploadStart');
  666. if (start) start.addEventListener('click', () => doUpload(false));
  667. const cancel = $('opsUploadCancel');
  668. if (cancel) cancel.addEventListener('click', closeUpload);
  669. const closeBtn = $('opsUploadClose');
  670. if (closeBtn) closeBtn.addEventListener('click', closeUpload);
  671. const schoolSelect = $('opsSchool');
  672. if (schoolSelect) {
  673. schoolSelect.addEventListener('change', () => {
  674. const custom = $('opsSchoolCustom');
  675. if (!custom) return;
  676. custom.hidden = schoolSelect.value !== '__custom';
  677. if (!custom.hidden) custom.focus();
  678. });
  679. }
  680. const file = $('opsFile');
  681. if (file) {
  682. file.addEventListener('change', () => {
  683. addFiles(file.files);
  684. file.value = '';
  685. });
  686. }
  687. const drop = $('opsDrop');
  688. if (drop) {
  689. ['dragover', 'dragenter'].forEach((ev) => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.add('on'); }));
  690. ['dragleave', 'drop'].forEach((ev) => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.remove('on'); }));
  691. drop.addEventListener('drop', (e) => {
  692. if (!e.dataTransfer || !e.dataTransfer.files) return;
  693. addFiles(e.dataTransfer.files);
  694. });
  695. drop.addEventListener('click', () => { const input = $('opsFile'); if (input) input.click(); });
  696. }
  697. const recordsClose = $('opsRecordsClose');
  698. if (recordsClose) recordsClose.addEventListener('click', () => { $('opsRecordsModal').hidden = true; });
  699. }
  700. window.shanOpsInit = function () {
  701. bindOnce();
  702. init(false);
  703. };
  704. })();