report.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. 'use strict';
  2. // 经营报告:同一份 Report JSON 渲染「图文报告 / 交互报告」,PDF 走浏览器打印样式。
  3. // 数据来自 GET /api/ops/report(后端算指标、规则打标,模型只负责文字)。
  4. (function () {
  5. const $ = (id) => document.getElementById(id);
  6. const COLORS = { main: '#ff6b35', soft: '#ffb08a', grey: '#c9c2ba', blue: '#7a9cc6', light: '#ffd6c2' };
  7. const state = {
  8. inited: false,
  9. loading: false,
  10. report: null,
  11. from: '',
  12. to: '',
  13. schools: [],
  14. shops: [],
  15. charts: {},
  16. };
  17. function esc(value) {
  18. const div = document.createElement('div');
  19. div.textContent = String(value == null ? '' : value);
  20. return div.innerHTML;
  21. }
  22. function moneyText(v) {
  23. if (v == null) return '–';
  24. const n = Number(v);
  25. return Number.isFinite(n) ? n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : '–';
  26. }
  27. function kpiText(kpi) {
  28. if (kpi.current == null) return '–';
  29. if (kpi.unit === '%') return kpi.current + '%';
  30. if (kpi.unit === '单' || kpi.unit === '人') return numText(kpi.current);
  31. return moneyText(kpi.current);
  32. }
  33. function numText(v) {
  34. if (v == null) return '–';
  35. const n = Number(v);
  36. return Number.isFinite(n) ? n.toLocaleString('zh-CN') : '–';
  37. }
  38. function deltaText(kpi) {
  39. if (kpi.change_pct == null) return '<span class="rp-delta muted">—</span>';
  40. const up = kpi.change_pct > 0;
  41. const cls = kpi.change_pct === 0 ? 'muted' : up ? 'up' : 'down';
  42. const unit = kpi.unit === '%' ? 'pp' : '%';
  43. return `<span class="rp-delta ${cls}">${up ? '↑' : '↓'} ${Math.abs(kpi.change_pct).toFixed(1)}${unit}</span>`;
  44. }
  45. async function api(url, options) {
  46. const res = await fetch(url, options);
  47. const body = await res.json().catch(() => null);
  48. return { res, body };
  49. }
  50. // ---------- 渲染 ----------
  51. function renderShell() {
  52. const root = $('reportRoot');
  53. if (!root) return;
  54. root.innerHTML = `
  55. <div class="rp-toolbar">
  56. <div class="rp-range">
  57. <input type="date" class="ops-input" id="rpFrom">
  58. <span class="ops-tilde">~</span>
  59. <input type="date" class="ops-input" id="rpTo">
  60. </div>
  61. <div class="ops-multi" id="rpSchool"></div>
  62. <div class="ops-multi" id="rpShop"></div>
  63. <div class="rp-actions">
  64. <button type="button" class="btn btn-ghost btn-small" id="rpArchive">历史报告</button>
  65. <button type="button" class="btn btn-ghost btn-small" id="rpSave" disabled>保存报告</button>
  66. <button type="button" class="btn btn-ghost btn-small" id="rpRefresh">重新生成</button>
  67. <button type="button" class="btn btn-primary btn-small" id="rpPrint">下载 PDF</button>
  68. </div>
  69. </div>
  70. <article class="rp-page" id="rpPage"></article>
  71. <div class="modal-overlay" id="rpHistoryModal" hidden>
  72. <div class="modal rp-history-modal">
  73. <div class="modal-header">
  74. <div class="modal-title"><span>历史报告</span></div>
  75. <button class="modal-close" id="rpHistoryClose" type="button" aria-label="关闭">×</button>
  76. </div>
  77. <div class="modal-body" id="rpHistoryList"></div>
  78. </div>
  79. </div>`;
  80. $('rpFrom').addEventListener('change', (e) => { state.from = String(e.target.value || '').replace(/-/g, ''); load(true); });
  81. $('rpTo').addEventListener('change', (e) => { state.to = String(e.target.value || '').replace(/-/g, ''); load(true); });
  82. $('rpRefresh').addEventListener('click', () => load(true));
  83. $('rpPrint').addEventListener('click', () => window.print());
  84. $('rpSave').addEventListener('click', saveReport);
  85. $('rpArchive').addEventListener('click', openHistory);
  86. $('rpHistoryClose').addEventListener('click', () => { $('rpHistoryModal').hidden = true; });
  87. }
  88. function renderCover(report) {
  89. const meta = report.meta || {};
  90. return `
  91. <header class="rp-cover">
  92. <div class="rp-cover-main">
  93. <div class="rp-kicker">AI 经营分析报告</div>
  94. <h1>${esc(meta.title || '经营分析报告')}</h1>
  95. <div class="rp-cover-sub">${esc(meta.organization || '')}${meta.organization ? ' · ' : ''}${esc(meta.period_start)} ~ ${esc(meta.period_end)}</div>
  96. </div>
  97. <div class="rp-cover-meta">
  98. <div><span>统计范围</span><b>${esc(meta.data_scope || '–')}</b></div>
  99. <div><span>数据来源</span><b>${esc((meta.source_files || []).join('、') || '平台导出明细')}</b></div>
  100. <div><span>生成时间</span><b>${esc(new Date(meta.generated_at).toLocaleString('zh-CN'))}</b></div>
  101. </div>
  102. </header>`;
  103. }
  104. function renderSummary(report) {
  105. const summary = report.executive_summary || {};
  106. const dot = { positive: 'ok', neutral: 'na', warning: 'warn', critical: 'bad' };
  107. const items = (summary.key_findings || []).map((f) => `
  108. <li>
  109. <span class="rp-dot ${dot[f.severity] || 'na'}"></span>
  110. <div>
  111. <b>${esc(f.finding)}</b>
  112. <p>${esc(f.interpretation || '')}</p>
  113. ${(f.evidence || []).length ? `<div class="rp-evidence">${f.evidence.map((e) => `<code>${esc(e)}</code>`).join('')}</div>` : ''}
  114. </div>
  115. </li>`).join('');
  116. return `
  117. <section class="rp-section rp-summary">
  118. <h2>管理层摘要</h2>
  119. <p class="rp-lead">${esc(summary.overall_assessment || '')}</p>
  120. <ul class="rp-findings">${items}</ul>
  121. </section>`;
  122. }
  123. function renderKpis(report) {
  124. return `
  125. <section class="rp-section">
  126. <h2>核心指标</h2>
  127. <div class="rp-kpis">
  128. ${(report.kpis || []).map((kpi) => `
  129. <div class="rp-kpi" title="${esc(kpi.definition)}">
  130. <div class="rp-kpi-label">${esc(kpi.label)}<span>${esc(kpi.unit === 'CNY' ? '元' : kpi.unit)}</span></div>
  131. <div class="rp-kpi-value">${kpiText(kpi)}</div>
  132. <div class="rp-kpi-foot">${deltaText(kpi)}<span class="rp-kpi-hint">较上期</span></div>
  133. </div>`).join('')}
  134. </div>
  135. <p class="rp-note">口径:${(report.kpis || []).map((k) => `${k.label}=${k.definition}`).join(';')}</p>
  136. </section>`;
  137. }
  138. function chartCard(id, title, subtitle) {
  139. return `<figure class="rp-figure">
  140. <figcaption><b>${esc(title)}</b><span>${esc(subtitle || '')}</span></figcaption>
  141. <div class="rp-chart" id="${id}"></div>
  142. </figure>`;
  143. }
  144. function renderSections(report) {
  145. const chartById = new Map((report.charts || []).map((c) => [c.id, c]));
  146. const tableById = new Map((report.tables || []).map((t) => [t.id, t]));
  147. return (report.sections || []).map((section, index) => {
  148. if (section.id === 'quality') return '';
  149. const charts = (section.chart_ids || []).map((id) => chartById.get(id)).filter(Boolean);
  150. const tables = (section.table_ids || []).map((id) => tableById.get(id)).filter(Boolean);
  151. return `
  152. <section class="rp-section">
  153. <h2><em>${String(index + 1).padStart(2, '0')}</em>${esc(section.title)}</h2>
  154. ${section.summary ? `<p class="rp-lead">${esc(section.summary)}</p>` : ''}
  155. ${(section.paragraphs || []).map((p) => `<p>${esc(p)}</p>`).join('')}
  156. ${charts.map((chart) => chartCard(`rpChart_${chart.id}`, chart.title, chart.description)).join('')}
  157. ${tables.map((table) => renderTable(table)).join('')}
  158. </section>`;
  159. }).join('');
  160. }
  161. function renderTable(table) {
  162. return `
  163. <div class="rp-table-wrap">
  164. <table class="rp-table">
  165. <thead><tr>${table.columns.map((c) => `<th>${esc(c.label)}</th>`).join('')}</tr></thead>
  166. <tbody>${(table.rows || []).map((row) => `<tr>${table.columns.map((c) => {
  167. const v = row[c.key];
  168. const text = c.key === 'revenue' ? moneyText(v) : c.key === 'share' ? (v == null ? '–' : v + '%') : (v == null ? '–' : esc(v));
  169. return `<td>${text}</td>`;
  170. }).join('')}</tr>`).join('')}</tbody>
  171. </table>
  172. ${table.footnote ? `<p class="rp-note">${esc(table.footnote)}</p>` : ''}
  173. </div>`;
  174. }
  175. function renderAlerts(report) {
  176. const alerts = report.alerts || [];
  177. const plan = report.action_plan || [];
  178. return `
  179. <section class="rp-section">
  180. <h2><em>05</em>风险与建议</h2>
  181. <div class="rp-alerts">
  182. ${alerts.map((a) => `
  183. <div class="rp-alert ${esc(a.severity)}">
  184. <div class="rp-alert-head"><span class="rp-badge">${esc(a.severity)}</span><b>${esc(a.title)}</b></div>
  185. <ul>${(a.evidence || []).map((e) => `<li>${esc(e)}</li>`).join('')}</ul>
  186. ${(a.hypotheses || []).length ? `<p class="rp-note">待验证:${a.hypotheses.map(esc).join('、')}</p>` : ''}
  187. </div>`).join('') || '<p class="rp-note">本期未触发风险规则。</p>'}
  188. </div>
  189. <h3 class="rp-h3">行动计划</h3>
  190. <table class="rp-table">
  191. <thead><tr><th>优先级</th><th>行动</th><th>负责人</th><th>时间窗</th><th>验收指标</th></tr></thead>
  192. <tbody>${plan.map((p) => `<tr>
  193. <td><span class="rp-badge">${esc(p.priority)}</span></td>
  194. <td>${esc(p.action)}</td>
  195. <td>${esc(p.owner_role)}</td>
  196. <td>${esc(p.time_horizon)}</td>
  197. <td>${esc(p.success_metric)}</td>
  198. </tr>`).join('')}</tbody>
  199. </table>
  200. </section>`;
  201. }
  202. function renderQuality(report) {
  203. const q = report.data_quality || {};
  204. return `
  205. <section class="rp-section rp-quality">
  206. <h2><em>06</em>数据质量与方法论</h2>
  207. <p><b>覆盖范围:</b>${esc(q.coverage || '–')}</p>
  208. <p><b>可比性:</b>${esc(q.comparability || '–')}</p>
  209. ${(q.warnings || []).length ? `<p><b>提示:</b>${q.warnings.map(esc).join(';')}</p>` : ''}
  210. ${(q.missing_metrics || []).length ? `<p><b>缺失指标:</b>${q.missing_metrics.map(esc).join(';')}</p>` : ''}
  211. <p><b>方法论:</b></p>
  212. <ul class="rp-method">${(report.methodology || []).map((m) => `<li>${esc(m)}</li>`).join('')}</ul>
  213. </section>`;
  214. }
  215. function renderReport(report) {
  216. const page = $('rpPage');
  217. const saveBtn = $('rpSave');
  218. if (saveBtn) saveBtn.disabled = false;
  219. page.innerHTML = [
  220. renderCover(report),
  221. renderSummary(report),
  222. renderKpis(report),
  223. renderSections(report),
  224. renderAlerts(report),
  225. renderQuality(report),
  226. `<footer class="rp-footer">${report.ai && report.ai.source === 'llm' ? `文字由 AI 生成(${esc(report.ai.model || '')})` : '当前为规则版文字'};数值均由后端按统一口径计算。${report.aiError ? ' ' + esc(report.aiError) : ''}</footer>`,
  227. ].join('');
  228. drawCharts(report);
  229. }
  230. // ---------- 图表 ----------
  231. function chartBase() {
  232. return {
  233. animation: true,
  234. tooltip: { trigger: 'axis' },
  235. };
  236. }
  237. function drawCharts(report) {
  238. const byId = new Map((report.charts || []).map((c) => [c.id, c]));
  239. Object.values(state.charts).forEach((chart) => chart && chart.dispose());
  240. state.charts = {};
  241. const mount = (chart) => {
  242. const el = $(`rpChart_${chart.id}`);
  243. if (!el) return null;
  244. const instance = echarts.init(el);
  245. state.charts[chart.id] = instance;
  246. return instance;
  247. };
  248. const trend = byId.get('chart_trend');
  249. if (trend) {
  250. const chart = mount(trend);
  251. chart && chart.setOption({
  252. ...chartBase(),
  253. grid: { left: 56, right: 48, top: 24, bottom: 30 },
  254. legend: { right: 0, top: 0, itemWidth: 10, itemHeight: 10, textStyle: { fontSize: 11 } },
  255. xAxis: { type: 'category', data: trend.data.map((d) => d.date.slice(4)), axisTick: { show: false }, axisLine: { lineStyle: { color: '#e5e0da' } } },
  256. yAxis: [{ type: 'value', splitLine: { lineStyle: { color: '#f2efea' } } }, { type: 'value', splitLine: { show: false } }],
  257. series: [
  258. { name: '营业额', type: 'bar', barMaxWidth: 22, itemStyle: { color: COLORS.main, borderRadius: [3, 3, 0, 0] }, data: trend.data.map((d) => d.revenue) },
  259. { name: '订单', type: 'line', yAxisIndex: 1, symbolSize: 5, lineStyle: { width: 2, color: COLORS.blue }, itemStyle: { color: COLORS.blue }, data: trend.data.map((d) => d.orders) },
  260. ],
  261. });
  262. }
  263. const rank = byId.get('chart_rank');
  264. if (rank) {
  265. const rows = rank.data.slice().reverse();
  266. const chart = mount(rank);
  267. chart && chart.setOption({
  268. ...chartBase(),
  269. grid: { left: 8, right: 60, top: 10, bottom: 10, containLabel: true },
  270. xAxis: { type: 'value', splitLine: { lineStyle: { color: '#f2efea' } } },
  271. yAxis: { type: 'category', data: rows.map((r) => r.shopName), axisTick: { show: false }, axisLine: { show: false }, axisLabel: { width: 140, overflow: 'truncate', fontSize: 11 } },
  272. series: [{ type: 'bar', barMaxWidth: 14, itemStyle: { color: COLORS.soft, borderRadius: [0, 3, 3, 0] }, label: { show: true, position: 'right', fontSize: 10, color: '#6f6862' }, data: rows.map((r) => r.revenue) }],
  273. });
  274. }
  275. const funnel = byId.get('chart_funnel');
  276. if (funnel) {
  277. const f = funnel.data;
  278. const chart = mount(funnel);
  279. chart && chart.setOption({
  280. ...chartBase(),
  281. series: [{
  282. type: 'funnel', left: '10%', right: '10%', top: 12, bottom: 12, minSize: '30%', gap: 3,
  283. label: { show: true, position: 'inside', color: '#fff', fontSize: 11, formatter: (p) => `${p.name} ${Number(p.value).toLocaleString('zh-CN')}` },
  284. itemStyle: { borderWidth: 0 },
  285. color: [COLORS.main, '#ff9a70', COLORS.light],
  286. data: [{ name: '曝光', value: f.exposure }, { name: '进店', value: f.visit }, { name: '下单', value: f.order }],
  287. }],
  288. });
  289. }
  290. const structure = byId.get('chart_structure');
  291. if (structure) {
  292. const chart = mount(structure);
  293. chart && chart.setOption({
  294. ...chartBase(),
  295. grid: { left: 56, right: 20, top: 28, bottom: 30 },
  296. legend: { right: 0, top: 0, itemWidth: 10, itemHeight: 10, textStyle: { fontSize: 11 } },
  297. xAxis: { type: 'category', data: structure.data.map((d) => d.date.slice(4)), axisTick: { show: false }, axisLine: { lineStyle: { color: '#e5e0da' } } },
  298. yAxis: { type: 'value', splitLine: { lineStyle: { color: '#f2efea' } } },
  299. series: [
  300. { name: '收入', type: 'bar', barMaxWidth: 18, itemStyle: { color: COLORS.main }, data: structure.data.map((d) => d.income) },
  301. { name: '支出', type: 'bar', barMaxWidth: 18, itemStyle: { color: COLORS.grey }, data: structure.data.map((d) => d.expense) },
  302. { name: '补贴', type: 'bar', barMaxWidth: 18, itemStyle: { color: COLORS.light }, data: structure.data.map((d) => d.subsidy) },
  303. ],
  304. });
  305. }
  306. }
  307. // ---------- 报告中心 ----------
  308. async function saveReport() {
  309. const btn = $('rpSave');
  310. btn.disabled = true;
  311. btn.textContent = '保存中…';
  312. try {
  313. const { res, body } = await api('/api/ops/reports', {
  314. method: 'POST',
  315. headers: { 'Content-Type': 'application/json' },
  316. body: JSON.stringify({
  317. from: state.from, to: state.to,
  318. schools: state.schools.join(','), shops: state.shops.join(','),
  319. report: state.report,
  320. }),
  321. });
  322. if (!res.ok) throw new Error((body && (body.detail || body.error)) || ('HTTP ' + res.status));
  323. btn.textContent = '已保存';
  324. setTimeout(() => { btn.textContent = '保存报告'; btn.disabled = false; }, 1500);
  325. } catch (e) {
  326. btn.textContent = '保存报告';
  327. btn.disabled = false;
  328. alert('保存失败:' + (e.message || e));
  329. }
  330. }
  331. async function openHistory() {
  332. $('rpHistoryModal').hidden = false;
  333. await renderHistory();
  334. }
  335. async function renderHistory() {
  336. const list = $('rpHistoryList');
  337. list.innerHTML = '<div class="rp-loading" style="padding:24px 0">加载中…</div>';
  338. const { res, body } = await api('/api/ops/reports');
  339. if (!res.ok) {
  340. list.innerHTML = `<div class="rp-loading">读取失败:${esc((body && (body.error || body.detail)) || res.status)}</div>`;
  341. return;
  342. }
  343. const reports = (body && body.reports) || [];
  344. if (!reports.length) {
  345. list.innerHTML = '<div class="rp-loading" style="padding:24px 0">还没有保存过报告</div>';
  346. return;
  347. }
  348. list.innerHTML = `<table class="rp-table">
  349. <thead><tr><th>保存时间</th><th>区间</th><th>学校</th><th>店铺</th><th>来源</th><th class="rp-col-actions">操作</th></tr></thead>
  350. <tbody>${reports.map((r) => `<tr>
  351. <td>${esc(new Date(r.createdAt).toLocaleString('zh-CN'))}</td>
  352. <td>${esc(r.from)} ~ ${esc(r.to)}</td>
  353. <td>${(r.schoolNames || []).length ? esc(r.schoolNames.join('、')) : '<span class="rp-muted">全部</span>'}</td>
  354. <td title="${esc((r.shopNames || []).join('、'))}">${(r.shopNames || []).length
  355. ? esc(r.shopNames.slice(0, 3).join('、')) + (r.shopNames.length > 3 ? ` 等 ${r.shopNames.length} 家` : '')
  356. : '<span class="rp-muted">全部</span>'}</td>
  357. <td>${r.source === 'llm' ? 'AI 生成' : '规则生成'}</td>
  358. <td class="rp-col-actions">
  359. <button type="button" class="btn btn-ghost btn-small" data-view="${esc(r.id)}">查看</button>
  360. <button type="button" class="btn btn-ghost btn-small" data-pdf="${esc(r.id)}">PDF</button>
  361. <button type="button" class="btn btn-ghost btn-small" data-json="${esc(r.id)}">JSON</button>
  362. <button type="button" class="btn btn-ghost btn-small" data-del="${esc(r.id)}">删除</button>
  363. </td>
  364. </tr>`).join('')}</tbody>
  365. </table>`;
  366. list.querySelectorAll('[data-view]').forEach((btn) => {
  367. btn.addEventListener('click', () => loadSaved(btn.dataset.view));
  368. });
  369. list.querySelectorAll('[data-pdf]').forEach((btn) => {
  370. btn.addEventListener('click', () => downloadSavedPdf(btn.dataset.pdf));
  371. });
  372. list.querySelectorAll('[data-json]').forEach((btn) => {
  373. btn.addEventListener('click', () => downloadSavedJson(btn.dataset.json));
  374. });
  375. list.querySelectorAll('[data-del]').forEach((btn) => {
  376. btn.addEventListener('click', async () => {
  377. if (!confirm('删除这份历史报告?')) return;
  378. btn.disabled = true;
  379. await api('/api/ops/reports/' + encodeURIComponent(btn.dataset.del), { method: 'DELETE' });
  380. renderHistory();
  381. });
  382. });
  383. }
  384. async function fetchSaved(id) {
  385. const { res, body } = await api('/api/ops/reports/' + encodeURIComponent(id));
  386. if (!res.ok || !body || !body.report) {
  387. alert('读取失败');
  388. return null;
  389. }
  390. return body.report;
  391. }
  392. async function downloadSavedPdf(id) {
  393. const report = await fetchSaved(id);
  394. if (!report) return;
  395. state.report = report;
  396. $('rpHistoryModal').hidden = true;
  397. renderReport(report);
  398. const meta = report.meta || {};
  399. const prevTitle = document.title;
  400. document.title = `经营分析报告_${String(meta.period_start || '').replace(/-/g, '')}-${String(meta.period_end || '').replace(/-/g, '')}`;
  401. setTimeout(() => {
  402. window.print();
  403. document.title = prevTitle;
  404. }, 500);
  405. }
  406. async function downloadSavedJson(id) {
  407. const report = await fetchSaved(id);
  408. if (!report) return;
  409. const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' });
  410. const url = URL.createObjectURL(blob);
  411. const a = document.createElement('a');
  412. a.href = url;
  413. a.download = `经营分析报告_${id}.json`;
  414. document.body.appendChild(a);
  415. a.click();
  416. a.remove();
  417. setTimeout(() => URL.revokeObjectURL(url), 1000);
  418. }
  419. async function loadSaved(id) {
  420. const { res, body } = await api('/api/ops/reports/' + encodeURIComponent(id));
  421. if (!res.ok || !body || !body.report) {
  422. alert('读取失败');
  423. return;
  424. }
  425. const report = body.report;
  426. state.report = report;
  427. const from = String(report.meta.period_start || '').replace(/-/g, '');
  428. const to = String(report.meta.period_end || '').replace(/-/g, '');
  429. state.from = from;
  430. state.to = to;
  431. $('rpFrom').value = String(report.meta.period_start || '');
  432. $('rpTo').value = String(report.meta.period_end || '');
  433. renderReport(report);
  434. $('rpHistoryModal').hidden = true;
  435. }
  436. // ---------- 数据 ----------
  437. async function load(force) {
  438. if (state.loading) { state.pending = true; return; }
  439. state.loading = true;
  440. const page = $('rpPage');
  441. if (page) page.classList.add('rp-stale');
  442. const saveBtn = $('rpSave');
  443. if (saveBtn) saveBtn.disabled = true;
  444. if (page && !state.report) page.innerHTML = '<div class="rp-loading">正在生成报告…</div>';
  445. try {
  446. const params = new URLSearchParams();
  447. if (state.from) params.set('from', state.from);
  448. if (state.to) params.set('to', state.to);
  449. if (state.schools.length) params.set('schools', state.schools.join(','));
  450. if (state.shops.length) params.set('shops', state.shops.join(','));
  451. params.set('ai', '1'); // 默认走 AI,失败自动退回规则版
  452. const { res, body } = await api('/api/ops/report?' + params.toString());
  453. if (!res.ok) throw new Error((body && (body.detail || body.error)) || ('HTTP ' + res.status));
  454. if (body.empty) {
  455. page.innerHTML = '<div class="rp-loading">所选范围没有数据,请先导入明细。</div>';
  456. return;
  457. }
  458. state.report = body.report;
  459. renderReport(state.report);
  460. } catch (e) {
  461. page.innerHTML = `<div class="rp-loading">报告生成失败:${esc(e.message || e)}</div>`;
  462. } finally {
  463. state.loading = false;
  464. if (page) page.classList.remove('rp-stale');
  465. if (state.pending) {
  466. state.pending = false;
  467. load(true);
  468. }
  469. }
  470. }
  471. async function initDates() {
  472. const search = new URLSearchParams(location.search);
  473. const qFrom = String(search.get('from') || '').replace(/\D/g, '');
  474. const qTo = String(search.get('to') || '').replace(/\D/g, '');
  475. state.shops = String(search.get('shops') || '').split(',').map((s) => s.trim()).filter(Boolean);
  476. state.schools = String(search.get('schools') || '').split(',').map((s) => s.trim()).filter(Boolean);
  477. const { body } = await api('/api/ops/summary');
  478. const summary = body || { schools: [], shops: [] };
  479. const coverage = summary.coverage;
  480. const toInput = (ymd) => `${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`;
  481. if (/^\d{8}$/.test(qFrom) && /^\d{8}$/.test(qTo)) {
  482. state.from = qFrom;
  483. state.to = qTo;
  484. } else if (coverage) {
  485. const to = coverage.to;
  486. const d = new Date(Date.UTC(Number(to.slice(0, 4)), Number(to.slice(4, 6)) - 1, Number(to.slice(6, 8)) - 6));
  487. const from = `${d.getUTCFullYear()}${String(d.getUTCMonth() + 1).padStart(2, '0')}${String(d.getUTCDate()).padStart(2, '0')}`;
  488. state.to = to;
  489. state.from = from < coverage.from ? coverage.from : from;
  490. }
  491. if (state.from && state.to) {
  492. $('rpFrom').value = toInput(state.from);
  493. $('rpTo').value = toInput(state.to);
  494. }
  495. mountFilters(summary);
  496. syncUrl();
  497. }
  498. function mountFilters(summary) {
  499. const schools = (summary.schools || []).map((s) => ({ key: s.name, label: s.name, hint: `${s.shopCount || 0} 家` }));
  500. window.createMultiSelect($('rpSchool'), {
  501. label: '学校',
  502. items: schools,
  503. selected: state.schools,
  504. allowEmpty: true,
  505. emptyLabel: '全部',
  506. onChange: (keys) => {
  507. state.schools = keys;
  508. syncUrl();
  509. load(true);
  510. },
  511. });
  512. const shops = (summary.shops || []).map((s) => ({
  513. key: String(s.key || s.shopId || ''),
  514. label: s.shopName || s.key,
  515. hint: s.school || '',
  516. })).filter((item) => item.key);
  517. window.createMultiSelect($('rpShop'), {
  518. label: '店铺',
  519. items: shops,
  520. selected: state.shops,
  521. allowEmpty: true,
  522. emptyLabel: '全部',
  523. onChange: (keys) => {
  524. state.shops = keys;
  525. syncUrl();
  526. load(true);
  527. },
  528. });
  529. window.bindMultiSelectDismiss();
  530. }
  531. function syncUrl() {
  532. const params = new URLSearchParams({ view: 'report' });
  533. if (state.from) params.set('from', state.from);
  534. if (state.to) params.set('to', state.to);
  535. if (state.schools.length) params.set('schools', state.schools.join(','));
  536. if (state.shops.length) params.set('shops', state.shops.join(','));
  537. history.replaceState(null, '', '/?' + params.toString());
  538. }
  539. window.shanReportInit = function () {
  540. if (!state.inited) {
  541. state.inited = true;
  542. renderShell();
  543. initDates().then(() => load());
  544. window.addEventListener('resize', () => {
  545. Object.values(state.charts).forEach((chart) => chart && chart.resize());
  546. });
  547. window.addEventListener('beforeprint', () => {
  548. Object.values(state.charts).forEach((chart) => chart && chart.resize());
  549. });
  550. }
  551. };
  552. })();