ops.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  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. }
  263. function cellValue(shop, metric, date) {
  264. const series = shop.series[metric] || {};
  265. return Object.prototype.hasOwnProperty.call(series, date) ? series[date] : null;
  266. }
  267. function metricCell(shop, metric, date) {
  268. const value = cellValue(shop, metric, date);
  269. const quality = (shop.quality || {})[date];
  270. const warn = quality && quality.length
  271. ? `<span class="ops-warn" title="${esc('解析标记:' + quality.join('、'))}">⚠</span>`
  272. : '';
  273. return `<td class="ops-num${value == null ? ' ops-null' : ''}">${fmtValue(value, metric)}${warn}</td>`;
  274. }
  275. /** 学校小计:数量/金额求和,转化率按曝光加权 */
  276. function subtotalValue(group, metric, date) {
  277. if (metric === 'click_rate') {
  278. let weight = 0;
  279. let acc = 0;
  280. for (const shop of group.shops) {
  281. const exposure = cellValue(shop, 'exposure', date);
  282. const rate = cellValue(shop, 'click_rate', date);
  283. if (typeof exposure === 'number' && exposure > 0 && typeof rate === 'number') {
  284. weight += exposure;
  285. acc += rate * exposure;
  286. }
  287. }
  288. return weight > 0 ? acc / weight : null;
  289. }
  290. let sum = 0;
  291. let seen = false;
  292. for (const shop of group.shops) {
  293. const v = cellValue(shop, metric, date);
  294. if (typeof v === 'number') { sum += v; seen = true; }
  295. }
  296. return seen ? sum : null;
  297. }
  298. function renderTables(data) {
  299. const metrics = state.metrics.filter((m) => META[m]);
  300. if (!metrics.length) return '<div class="empty-hint"><p>请至少选择一个指标</p></div>';
  301. const dates = data.dates || [];
  302. const colCount = metrics.length + 2;
  303. const head = `<tr>
  304. <th class="ops-shop-col">店铺</th>
  305. <th class="ops-date-col">日期</th>
  306. ${metrics.map((m) => `<th class="ops-metric-col">${META[m].label}</th>`).join('')}
  307. </tr>`;
  308. const body = data.groups.map((group) => {
  309. const schoolRow = `<tr class="ops-school-row"><td colspan="${colCount}">${esc(group.school)}<em>${group.shops.length} 家</em></td></tr>`;
  310. const shopRows = group.shops.map((shop) => {
  311. // 只展示该店有数据的日期(平台明细可能缺某天)
  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. return useDates.map((date, i) => `<tr>
  315. ${i === 0 ? `<td class="ops-shop-cell" rowspan="${useDates.length}" title="${esc(shop.shopName)}">${esc(shop.shopName)}${
  316. shop.status && shop.status !== '已上线' ? `<span class="badge badge-muted ops-status">${esc(shop.status)}</span>` : ''
  317. }</td>` : ''}
  318. <td class="ops-date-cell">${shortDate(date)}</td>
  319. ${metrics.map((m) => metricCell(shop, m, date)).join('')}
  320. </tr>`).join('');
  321. }).join('');
  322. const subtotalDates = dates.filter((d) => group.shops.some((shop) => metrics.some((m) => cellValue(shop, m, d) !== null)));
  323. const subtotalRows = subtotalDates.map((date) => `<tr class="ops-subtotal-row">
  324. <td class="ops-subtotal-label" colspan="2">${esc(group.school)} · 小计 · ${shortDate(date)}</td>
  325. ${metrics.map((m) => {
  326. const v = subtotalValue(group, m, date);
  327. return `<td class="ops-num ops-subtotal">${v == null ? '–' : fmtValue(v, m)}</td>`;
  328. }).join('')}
  329. </tr>`).join('');
  330. return schoolRow + shopRows + subtotalRows;
  331. }).join('');
  332. const shopCount = data.groups.reduce((n, g) => n + g.shops.length, 0);
  333. return `<section class="ops-block">
  334. <div class="ops-block-head"><h2>运营明细</h2><span>${shopCount} 家门店 · ${dates.length} 天 · ${metrics.length} 个指标</span></div>
  335. <div class="ops-table-wrap">
  336. <table class="ops-table ops-table-wide">
  337. <thead>${head}</thead>
  338. <tbody>${body}</tbody>
  339. </table>
  340. </div>
  341. </section>`;
  342. }
  343. function sparkline(shop, metric, dates) {
  344. const values = dates.map((d) => {
  345. const v = (shop.series[metric] || {})[d];
  346. return typeof v === 'number' ? v : null;
  347. });
  348. const nums = values.filter((v) => v != null);
  349. if (nums.length < 2) return '';
  350. const min = Math.min(...nums);
  351. const max = Math.max(...nums);
  352. const span = max - min || 1;
  353. const w = 160;
  354. const h = 34;
  355. const step = w / Math.max(values.length - 1, 1);
  356. const points = [];
  357. values.forEach((v, i) => {
  358. if (v == null) return;
  359. const x = (i * step).toFixed(1);
  360. const y = (h - ((v - min) / span) * (h - 6) - 3).toFixed(1);
  361. points.push(`${x},${y}`);
  362. });
  363. return `<svg class="ops-spark" viewBox="0 0 ${w} ${h}" preserveAspectRatio="none" aria-hidden="true"><polyline points="${points.join(' ')}" /></svg>`;
  364. }
  365. function renderCards(data) {
  366. const dates = data.dates || [];
  367. const metric = state.metrics[0];
  368. return `<div class="ops-cards">${data.groups.map((group) => `
  369. <section class="ops-card-group">
  370. <h3>${esc(group.school)}</h3>
  371. <div class="ops-card-grid">
  372. ${group.shops.map((shop) => `
  373. <article class="ops-card">
  374. <div class="ops-card-head">
  375. <span class="ops-card-name" title="${esc(shop.shopName)}">${esc(shop.shopName)}</span>
  376. ${shop.status && shop.status !== '已上线' ? `<span class="badge badge-muted">${esc(shop.status)}</span>` : ''}
  377. </div>
  378. <div class="ops-card-metrics">
  379. ${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('')}
  380. </div>
  381. ${sparkline(shop, metric, dates)}
  382. </article>`).join('')}
  383. </div>
  384. </section>`).join('')}</div>`;
  385. }
  386. function avgRate(shop, dates) {
  387. let weight = 0;
  388. let acc = 0;
  389. for (const date of dates) {
  390. const exposure = (shop.series.exposure || {})[date];
  391. const rate = (shop.series.click_rate || {})[date];
  392. if (typeof exposure === 'number' && exposure > 0 && typeof rate === 'number') {
  393. weight += exposure;
  394. acc += rate * exposure;
  395. }
  396. }
  397. return weight > 0 ? acc / weight : null;
  398. }
  399. // ---------- 上传 ----------
  400. async function refreshSchoolOptions() {
  401. const select = $('opsSchool');
  402. if (!select) return;
  403. // 已登记学校(校区地图里的学校注册表,含内置)
  404. const registered = [];
  405. try {
  406. const { res, body } = await api('/api/schools');
  407. if (res.ok) {
  408. for (const school of (body && body.schools) || []) {
  409. if (!school || !school.name) continue;
  410. registered.push({
  411. name: school.name,
  412. hint: [school.province, school.city].filter(Boolean).join(' · '),
  413. });
  414. }
  415. }
  416. } catch { /* 注册表取不到时回落到运营数据里的学校 */ }
  417. // 运营数据中出现过、但还没登记的学校
  418. const registeredNames = new Set(registered.map((x) => x.name));
  419. const fromOps = ((state.summary && state.summary.schools) || [])
  420. .map((x) => x.name)
  421. .filter((name) => name && !registeredNames.has(name));
  422. select.innerHTML = '<option value="">自动(读取表格里的「学校名称」列)</option>'
  423. + (registered.length
  424. ? `<optgroup label="已登记学校">${registered.map((x) => `<option value="${esc(x.name)}">${esc(x.name)}${x.hint ? '(' + esc(x.hint) + ')' : ''}</option>`).join('')}</optgroup>`
  425. : '')
  426. + (fromOps.length
  427. ? `<optgroup label="运营数据中的学校">${fromOps.map((name) => `<option value="${esc(name)}">${esc(name)}</option>`).join('')}</optgroup>`
  428. : '')
  429. + '<option value="__custom">手动输入…</option>';
  430. select.value = '';
  431. const custom = $('opsSchoolCustom');
  432. if (custom) {
  433. custom.value = '';
  434. custom.hidden = true;
  435. }
  436. }
  437. function selectedSchool() {
  438. const select = $('opsSchool');
  439. if (!select) return '';
  440. if (select.value === '__custom') return String(($('opsSchoolCustom') || {}).value || '').trim();
  441. return select.value;
  442. }
  443. function fileKey(f) {
  444. return f.name + '|' + f.size + '|' + (f.lastModified || 0);
  445. }
  446. function addFiles(fileList) {
  447. for (const f of Array.from(fileList || [])) {
  448. if (!/\.xlsx$/i.test(f.name)) continue;
  449. const key = fileKey(f);
  450. if (state.upload.files.some((x) => fileKey(x.file) === key)) continue;
  451. state.upload.files.push({ file: f, status: 'pending', message: '' });
  452. }
  453. renderFileList();
  454. }
  455. function renderFileList() {
  456. const box = $('opsFileList');
  457. if (!box) return;
  458. if (!state.upload.files.length) {
  459. box.innerHTML = '';
  460. return;
  461. }
  462. box.innerHTML = state.upload.files.map((item, i) => {
  463. const cls = item.status === 'error' ? 'ops-error'
  464. : item.status === 'done' ? 'ops-done-text'
  465. : item.status === 'duplicate' ? 'ops-muted' : '';
  466. const msg = item.message ? `<em class="${cls}">${esc(item.message)}</em>` : '';
  467. const removable = item.status !== 'uploading';
  468. return `<div class="ops-file-item">
  469. <span class="ops-file-name2" title="${esc(item.file.name)}">${esc(item.file.name)}</span>
  470. <span class="ops-file-size">${(item.file.size / 1024).toFixed(0)} KB</span>
  471. ${msg}
  472. ${removable ? `<button type="button" class="ops-file-del" data-idx="${i}" title="移除">×</button>` : ''}
  473. </div>`;
  474. }).join('');
  475. box.querySelectorAll('[data-idx]').forEach((btn) => {
  476. btn.addEventListener('click', () => {
  477. const i = Number(btn.dataset.idx);
  478. if (state.upload.files[i] && state.upload.files[i].status === 'uploading') return;
  479. state.upload.files.splice(i, 1);
  480. renderFileList();
  481. });
  482. });
  483. }
  484. async function openUpload() {
  485. const modal = $('opsUploadModal');
  486. if (!modal) return;
  487. state.upload.files = [];
  488. renderFileList();
  489. $('opsUploadResult').innerHTML = '';
  490. $('opsYear').value = String(new Date().getFullYear());
  491. await refreshSchoolOptions();
  492. if ($('opsForce')) $('opsForce').checked = false;
  493. $('opsUploadStart').disabled = false;
  494. modal.hidden = false;
  495. }
  496. function closeUpload() {
  497. const modal = $('opsUploadModal');
  498. if (modal) modal.hidden = true;
  499. }
  500. function readFileBase64(file) {
  501. return new Promise((resolve, reject) => {
  502. const reader = new FileReader();
  503. reader.onload = () => {
  504. const text = String(reader.result || '');
  505. resolve(text.slice(text.indexOf(',') + 1));
  506. };
  507. reader.onerror = () => reject(reader.error || new Error('读取文件失败'));
  508. reader.readAsDataURL(file);
  509. });
  510. }
  511. async function doUpload(forceOverride) {
  512. const items = state.upload.files;
  513. const result = $('opsUploadResult');
  514. if (!items.length) {
  515. result.innerHTML = '<span class="ops-error">请先选择 .xlsx 文件(可一次选多个)</span>';
  516. return;
  517. }
  518. if (items.length > 30) {
  519. result.innerHTML = '<span class="ops-error">一次最多 30 个文件</span>';
  520. return;
  521. }
  522. const year = Number($('opsYear').value) || new Date().getFullYear();
  523. const school = selectedSchool();
  524. const force = !!(forceOverride || ($('opsForce') && $('opsForce').checked));
  525. $('opsUploadStart').disabled = true;
  526. result.innerHTML = '<span class="ops-muted">正在逐个解析并入库…</span>';
  527. let okCount = 0;
  528. let skipCount = 0;
  529. let failCount = 0;
  530. for (const item of items) {
  531. if (item.status === 'done') continue;
  532. item.status = 'uploading';
  533. item.message = '导入中…';
  534. renderFileList();
  535. try {
  536. const base64 = await readFileBase64(item.file);
  537. const { res, body } = await api('/api/ops/upload', {
  538. method: 'POST',
  539. headers: { 'Content-Type': 'application/json' },
  540. body: JSON.stringify({ fileName: item.file.name, contentBase64: base64, year, school, force }),
  541. });
  542. if (res.status === 409) {
  543. item.status = 'duplicate';
  544. item.message = '已导入过(跳过)';
  545. skipCount += 1;
  546. } else if (!res.ok) {
  547. const detail = body && (body.detail ? body.error + ':' + body.detail : body.error);
  548. item.status = 'error';
  549. item.message = detail || ('失败 HTTP ' + res.status);
  550. failCount += 1;
  551. } else {
  552. const r = body.report || {};
  553. item.status = 'done';
  554. if (r.kind === 'platform-export') {
  555. const parts = ['新增 ' + r.newRows + ' 行'];
  556. if (r.identicalRows) parts.push('已存在 ' + r.identicalRows + ' 行');
  557. if (r.conflictRows) parts.push('冲突 ' + r.conflictRows + ' 行');
  558. item.message = parts.join(' · ');
  559. } else {
  560. item.message = r.rows + ' 行 · ' + r.shops + ' 家';
  561. }
  562. okCount += 1;
  563. }
  564. } catch (e) {
  565. item.status = 'error';
  566. item.message = e.message || String(e);
  567. failCount += 1;
  568. }
  569. renderFileList();
  570. }
  571. const parts = ['成功 ' + okCount + ' 个'];
  572. if (skipCount) parts.push('跳过 ' + skipCount + ' 个(已导入过)');
  573. if (failCount) parts.push('失败 ' + failCount + ' 个');
  574. result.innerHTML = `<div class="${failCount ? 'ops-error' : 'ops-ok'}">${parts.join(',')}${
  575. skipCount && !force ? '<br><small>已存在的文件可勾选下方「覆盖已导入的文件」后重新导入</small>' : ''
  576. }</div>`;
  577. $('opsUploadStart').disabled = false;
  578. if (okCount) {
  579. state.from = '';
  580. state.to = '';
  581. state.schools = null;
  582. await init(true);
  583. }
  584. }
  585. // ---------- 导入记录 ----------
  586. async function openRecords() {
  587. const modal = $('opsRecordsModal');
  588. if (!modal) return;
  589. modal.hidden = false;
  590. const list = $('opsRecordsList');
  591. list.innerHTML = '<div class="ops-muted" style="padding:16px">加载中…</div>';
  592. const { res, body } = await api('/api/ops/uploads');
  593. if (!res.ok) {
  594. list.innerHTML = `<div class="ops-error" style="padding:16px">${esc((body && (body.detail || body.error)) || ('HTTP ' + res.status))}</div>`;
  595. return;
  596. }
  597. const uploads = (body && body.uploads) || [];
  598. if (!uploads.length) {
  599. list.innerHTML = '<div class="ops-muted" style="padding:16px">还没有导入记录</div>';
  600. return;
  601. }
  602. list.innerHTML = `<table class="data-table">
  603. <thead><tr><th>文件名</th><th>上传时间</th><th>行数</th><th>门店</th><th>警告</th><th class="col-actions">操作</th></tr></thead>
  604. <tbody>${uploads.map((u) => `<tr>
  605. <td>${esc(u.originalName)}</td>
  606. <td>${esc(new Date(u.uploadedAt).toLocaleString('zh-CN'))}</td>
  607. <td>${u.rows || 0}</td>
  608. <td>${u.shops || 0}</td>
  609. <td>${u.warningCount || 0}</td>
  610. <td class="col-actions">
  611. <a class="btn btn-ghost btn-small" href="/api/ops/uploads/${esc(u.id)}/file">下载原件</a>
  612. <button type="button" class="btn btn-ghost btn-small" data-reparse="${esc(u.id)}">重新解析</button>
  613. </td>
  614. </tr>`).join('')}</tbody>
  615. </table>`;
  616. list.querySelectorAll('[data-reparse]').forEach((btn) => {
  617. btn.addEventListener('click', async () => {
  618. btn.disabled = true;
  619. btn.textContent = '解析中…';
  620. const { res, body: rep } = await api(`/api/ops/uploads/${btn.dataset.reparse}/reparse`, { method: 'POST' });
  621. btn.disabled = false;
  622. btn.textContent = '重新解析';
  623. if (!res.ok) {
  624. alert((rep && (rep.detail || rep.error)) || '重新解析失败');
  625. return;
  626. }
  627. await init(true);
  628. });
  629. });
  630. }
  631. // ---------- 初始化 ----------
  632. async function init(force) {
  633. if (state.inited && !force) return;
  634. state.inited = true;
  635. await loadSummary();
  636. renderBar();
  637. renderHeaderTools();
  638. renderBody();
  639. if (state.summary && state.summary.enabled && matrixCount(state.summary)) await loadRows();
  640. }
  641. function bindOnce() {
  642. const uploadBtn = $('btnOpsUpload');
  643. if (uploadBtn) uploadBtn.addEventListener('click', openUpload);
  644. const recordsBtn = $('btnOpsRecords');
  645. if (recordsBtn) recordsBtn.addEventListener('click', openRecords);
  646. const start = $('opsUploadStart');
  647. if (start) start.addEventListener('click', () => doUpload(false));
  648. const cancel = $('opsUploadCancel');
  649. if (cancel) cancel.addEventListener('click', closeUpload);
  650. const closeBtn = $('opsUploadClose');
  651. if (closeBtn) closeBtn.addEventListener('click', closeUpload);
  652. const schoolSelect = $('opsSchool');
  653. if (schoolSelect) {
  654. schoolSelect.addEventListener('change', () => {
  655. const custom = $('opsSchoolCustom');
  656. if (!custom) return;
  657. custom.hidden = schoolSelect.value !== '__custom';
  658. if (!custom.hidden) custom.focus();
  659. });
  660. }
  661. const file = $('opsFile');
  662. if (file) {
  663. file.addEventListener('change', () => {
  664. addFiles(file.files);
  665. file.value = '';
  666. });
  667. }
  668. const drop = $('opsDrop');
  669. if (drop) {
  670. ['dragover', 'dragenter'].forEach((ev) => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.add('on'); }));
  671. ['dragleave', 'drop'].forEach((ev) => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.remove('on'); }));
  672. drop.addEventListener('drop', (e) => {
  673. if (!e.dataTransfer || !e.dataTransfer.files) return;
  674. addFiles(e.dataTransfer.files);
  675. });
  676. drop.addEventListener('click', () => { const input = $('opsFile'); if (input) input.click(); });
  677. }
  678. const recordsClose = $('opsRecordsClose');
  679. if (recordsClose) recordsClose.addEventListener('click', () => { $('opsRecordsModal').hidden = true; });
  680. }
  681. window.shanOpsInit = function () {
  682. bindOnce();
  683. init(false);
  684. };
  685. })();