report.js 25 KB

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