report.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. charts: {},
  15. };
  16. function esc(value) {
  17. const div = document.createElement('div');
  18. div.textContent = String(value == null ? '' : value);
  19. return div.innerHTML;
  20. }
  21. function moneyText(v) {
  22. if (v == null) return '–';
  23. const n = Number(v);
  24. return Number.isFinite(n) ? n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : '–';
  25. }
  26. function kpiText(kpi) {
  27. if (kpi.current == null) return '–';
  28. if (kpi.unit === '%') return kpi.current + '%';
  29. if (kpi.unit === '单' || kpi.unit === '人') return numText(kpi.current);
  30. return moneyText(kpi.current);
  31. }
  32. function numText(v) {
  33. if (v == null) return '–';
  34. const n = Number(v);
  35. return Number.isFinite(n) ? n.toLocaleString('zh-CN') : '–';
  36. }
  37. function deltaText(kpi) {
  38. if (kpi.change_pct == null) return '<span class="rp-delta muted">—</span>';
  39. const up = kpi.change_pct > 0;
  40. const cls = kpi.change_pct === 0 ? 'muted' : up ? 'up' : 'down';
  41. const unit = kpi.unit === '%' ? 'pp' : '%';
  42. return `<span class="rp-delta ${cls}">${up ? '↑' : '↓'} ${Math.abs(kpi.change_pct).toFixed(1)}${unit}</span>`;
  43. }
  44. async function api(url) {
  45. const res = await fetch(url);
  46. const body = await res.json().catch(() => null);
  47. return { res, body };
  48. }
  49. // ---------- 渲染 ----------
  50. function renderShell() {
  51. const root = $('reportRoot');
  52. if (!root) return;
  53. root.innerHTML = `
  54. <div class="rp-toolbar">
  55. <div class="rp-range">
  56. <input type="date" class="ops-input" id="rpFrom">
  57. <span class="ops-tilde">~</span>
  58. <input type="date" class="ops-input" id="rpTo">
  59. </div>
  60. <div class="rp-tabs" id="rpTabs">
  61. <button type="button" data-mode="text" class="on">图文报告</button>
  62. <button type="button" data-mode="interactive">交互报告</button>
  63. </div>
  64. <div class="rp-actions">
  65. <button type="button" class="btn btn-ghost btn-small" id="rpRefresh">重新生成</button>
  66. <button type="button" class="btn btn-primary btn-small" id="rpPrint">下载 PDF</button>
  67. </div>
  68. </div>
  69. <article class="rp-page" id="rpPage"></article>`;
  70. root.querySelectorAll('#rpTabs [data-mode]').forEach((btn) => {
  71. btn.addEventListener('click', () => {
  72. state.mode = btn.dataset.mode;
  73. root.querySelectorAll('#rpTabs [data-mode]').forEach((b) => b.classList.toggle('on', b === btn));
  74. $('rpPage').classList.toggle('interactive', state.mode === 'interactive');
  75. if (state.report) drawCharts(state.report);
  76. });
  77. });
  78. $('rpFrom').addEventListener('change', (e) => { state.from = String(e.target.value || '').replace(/-/g, ''); load(true); });
  79. $('rpTo').addEventListener('change', (e) => { state.to = String(e.target.value || '').replace(/-/g, ''); load(true); });
  80. $('rpRefresh').addEventListener('click', () => load(true));
  81. $('rpPrint').addEventListener('click', () => window.print());
  82. }
  83. function renderCover(report) {
  84. const meta = report.meta || {};
  85. return `
  86. <header class="rp-cover">
  87. <div class="rp-cover-main">
  88. <div class="rp-kicker">AI 经营分析报告</div>
  89. <h1>${esc(meta.title || '经营分析报告')}</h1>
  90. <div class="rp-cover-sub">${esc(meta.organization || '')}${meta.organization ? ' · ' : ''}${esc(meta.period_start)} ~ ${esc(meta.period_end)}</div>
  91. </div>
  92. <div class="rp-cover-meta">
  93. <div><span>统计范围</span><b>${esc(meta.data_scope || '–')}</b></div>
  94. <div><span>数据来源</span><b>${esc((meta.source_files || []).join('、') || '平台导出明细')}</b></div>
  95. <div><span>生成时间</span><b>${esc(new Date(meta.generated_at).toLocaleString('zh-CN'))}</b></div>
  96. </div>
  97. </header>`;
  98. }
  99. function renderSummary(report) {
  100. const summary = report.executive_summary || {};
  101. const dot = { positive: 'ok', neutral: 'na', warning: 'warn', critical: 'bad' };
  102. const items = (summary.key_findings || []).map((f) => `
  103. <li>
  104. <span class="rp-dot ${dot[f.severity] || 'na'}"></span>
  105. <div>
  106. <b>${esc(f.finding)}</b>
  107. <p>${esc(f.interpretation || '')}</p>
  108. ${(f.evidence || []).length ? `<div class="rp-evidence">${f.evidence.map((e) => `<code>${esc(e)}</code>`).join('')}</div>` : ''}
  109. </div>
  110. </li>`).join('');
  111. return `
  112. <section class="rp-section rp-summary">
  113. <h2>管理层摘要</h2>
  114. <p class="rp-lead">${esc(summary.overall_assessment || '')}</p>
  115. <ul class="rp-findings">${items}</ul>
  116. </section>`;
  117. }
  118. function renderKpis(report) {
  119. return `
  120. <section class="rp-section">
  121. <h2>核心指标</h2>
  122. <div class="rp-kpis">
  123. ${(report.kpis || []).map((kpi) => `
  124. <div class="rp-kpi" title="${esc(kpi.definition)}">
  125. <div class="rp-kpi-label">${esc(kpi.label)}<span>${esc(kpi.unit)}</span></div>
  126. <div class="rp-kpi-value">${kpiText(kpi)}</div>
  127. <div class="rp-kpi-foot">${deltaText(kpi)}<span class="rp-kpi-hint">较上期</span></div>
  128. </div>`).join('')}
  129. </div>
  130. <p class="rp-note">口径:${(report.kpis || []).map((k) => `${k.label}=${k.definition}`).join(';')}</p>
  131. </section>`;
  132. }
  133. function chartCard(id, title, subtitle) {
  134. return `<figure class="rp-figure">
  135. <figcaption><b>${esc(title)}</b><span>${esc(subtitle || '')}</span></figcaption>
  136. <div class="rp-chart" id="${id}"></div>
  137. </figure>`;
  138. }
  139. function renderSections(report) {
  140. const chartById = new Map((report.charts || []).map((c) => [c.id, c]));
  141. const tableById = new Map((report.tables || []).map((t) => [t.id, t]));
  142. return (report.sections || []).map((section, index) => {
  143. if (section.id === 'quality') return '';
  144. const charts = (section.chart_ids || []).map((id) => chartById.get(id)).filter(Boolean);
  145. const tables = (section.table_ids || []).map((id) => tableById.get(id)).filter(Boolean);
  146. return `
  147. <section class="rp-section">
  148. <h2><em>${String(index + 1).padStart(2, '0')}</em>${esc(section.title)}</h2>
  149. ${section.summary ? `<p class="rp-lead">${esc(section.summary)}</p>` : ''}
  150. ${(section.paragraphs || []).map((p) => `<p>${esc(p)}</p>`).join('')}
  151. ${charts.map((chart) => chartCard(`rpChart_${chart.id}`, chart.title, chart.description)).join('')}
  152. ${tables.map((table) => renderTable(table)).join('')}
  153. </section>`;
  154. }).join('');
  155. }
  156. function renderTable(table) {
  157. return `
  158. <div class="rp-table-wrap">
  159. <table class="rp-table">
  160. <thead><tr>${table.columns.map((c) => `<th>${esc(c.label)}</th>`).join('')}</tr></thead>
  161. <tbody>${(table.rows || []).map((row) => `<tr>${table.columns.map((c) => {
  162. const v = row[c.key];
  163. const text = c.key === 'revenue' ? moneyText(v) : c.key === 'share' ? (v == null ? '–' : v + '%') : (v == null ? '–' : esc(v));
  164. return `<td>${text}</td>`;
  165. }).join('')}</tr>`).join('')}</tbody>
  166. </table>
  167. ${table.footnote ? `<p class="rp-note">${esc(table.footnote)}</p>` : ''}
  168. </div>`;
  169. }
  170. function renderAlerts(report) {
  171. const alerts = report.alerts || [];
  172. const plan = report.action_plan || [];
  173. return `
  174. <section class="rp-section">
  175. <h2><em>05</em>风险与建议</h2>
  176. <div class="rp-alerts">
  177. ${alerts.map((a) => `
  178. <div class="rp-alert ${esc(a.severity)}">
  179. <div class="rp-alert-head"><span class="rp-badge">${esc(a.severity)}</span><b>${esc(a.title)}</b></div>
  180. <ul>${(a.evidence || []).map((e) => `<li>${esc(e)}</li>`).join('')}</ul>
  181. ${(a.hypotheses || []).length ? `<p class="rp-note">待验证:${a.hypotheses.map(esc).join('、')}</p>` : ''}
  182. </div>`).join('') || '<p class="rp-note">本期未触发风险规则。</p>'}
  183. </div>
  184. <h3 class="rp-h3">行动计划</h3>
  185. <table class="rp-table">
  186. <thead><tr><th>优先级</th><th>行动</th><th>负责人</th><th>时间窗</th><th>验收指标</th></tr></thead>
  187. <tbody>${plan.map((p) => `<tr>
  188. <td><span class="rp-badge">${esc(p.priority)}</span></td>
  189. <td>${esc(p.action)}</td>
  190. <td>${esc(p.owner_role)}</td>
  191. <td>${esc(p.time_horizon)}</td>
  192. <td>${esc(p.success_metric)}</td>
  193. </tr>`).join('')}</tbody>
  194. </table>
  195. </section>`;
  196. }
  197. function renderQuality(report) {
  198. const q = report.data_quality || {};
  199. return `
  200. <section class="rp-section rp-quality">
  201. <h2><em>06</em>数据质量与方法论</h2>
  202. <p><b>覆盖范围:</b>${esc(q.coverage || '–')}</p>
  203. <p><b>可比性:</b>${esc(q.comparability || '–')}</p>
  204. ${(q.warnings || []).length ? `<p><b>提示:</b>${q.warnings.map(esc).join(';')}</p>` : ''}
  205. ${(q.missing_metrics || []).length ? `<p><b>缺失指标:</b>${q.missing_metrics.map(esc).join(';')}</p>` : ''}
  206. <p><b>方法论:</b></p>
  207. <ul class="rp-method">${(report.methodology || []).map((m) => `<li>${esc(m)}</li>`).join('')}</ul>
  208. </section>`;
  209. }
  210. function renderReport(report) {
  211. const page = $('rpPage');
  212. page.innerHTML = [
  213. renderCover(report),
  214. renderSummary(report),
  215. renderKpis(report),
  216. renderSections(report),
  217. renderAlerts(report),
  218. renderQuality(report),
  219. `<footer class="rp-footer">本报告由系统按统一口径自动生成,数值均来自后端计算,模型仅参与文字表述。</footer>`,
  220. ].join('');
  221. drawCharts(report);
  222. }
  223. // ---------- 图表 ----------
  224. function chartBase(interactive) {
  225. return {
  226. animation: !interactive,
  227. silent: !interactive,
  228. tooltip: interactive ? { trigger: 'axis' } : undefined,
  229. };
  230. }
  231. function drawCharts(report) {
  232. const interactive = state.mode === 'interactive';
  233. const byId = new Map((report.charts || []).map((c) => [c.id, c]));
  234. Object.values(state.charts).forEach((chart) => chart && chart.dispose());
  235. state.charts = {};
  236. const mount = (chart) => {
  237. const el = $(`rpChart_${chart.id}`);
  238. if (!el) return null;
  239. const instance = echarts.init(el);
  240. state.charts[chart.id] = instance;
  241. return instance;
  242. };
  243. const trend = byId.get('chart_trend');
  244. if (trend) {
  245. const chart = mount(trend);
  246. chart && chart.setOption({
  247. ...chartBase(interactive),
  248. grid: { left: 56, right: 48, top: 24, bottom: 30 },
  249. legend: { right: 0, top: 0, itemWidth: 10, itemHeight: 10, textStyle: { fontSize: 11 } },
  250. xAxis: { type: 'category', data: trend.data.map((d) => d.date.slice(4)), axisTick: { show: false }, axisLine: { lineStyle: { color: '#e5e0da' } } },
  251. yAxis: [{ type: 'value', splitLine: { lineStyle: { color: '#f2efea' } } }, { type: 'value', splitLine: { show: false } }],
  252. series: [
  253. { name: '营业额', type: 'bar', barMaxWidth: 22, itemStyle: { color: COLORS.main, borderRadius: [3, 3, 0, 0] }, data: trend.data.map((d) => d.revenue) },
  254. { name: '订单', type: 'line', yAxisIndex: 1, symbolSize: 5, lineStyle: { width: 2, color: COLORS.blue }, itemStyle: { color: COLORS.blue }, data: trend.data.map((d) => d.orders) },
  255. ],
  256. });
  257. }
  258. const rank = byId.get('chart_rank');
  259. if (rank) {
  260. const rows = rank.data.slice().reverse();
  261. const chart = mount(rank);
  262. chart && chart.setOption({
  263. ...chartBase(interactive),
  264. grid: { left: 8, right: 60, top: 10, bottom: 10, containLabel: true },
  265. xAxis: { type: 'value', splitLine: { lineStyle: { color: '#f2efea' } } },
  266. yAxis: { type: 'category', data: rows.map((r) => r.shopName), axisTick: { show: false }, axisLine: { show: false }, axisLabel: { width: 140, overflow: 'truncate', fontSize: 11 } },
  267. 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) }],
  268. });
  269. }
  270. const funnel = byId.get('chart_funnel');
  271. if (funnel) {
  272. const f = funnel.data;
  273. const chart = mount(funnel);
  274. chart && chart.setOption({
  275. ...chartBase(interactive),
  276. series: [{
  277. type: 'funnel', left: '10%', right: '10%', top: 12, bottom: 12, minSize: '30%', gap: 3,
  278. label: { show: true, position: 'inside', color: '#fff', fontSize: 11, formatter: (p) => `${p.name} ${Number(p.value).toLocaleString('zh-CN')}` },
  279. itemStyle: { borderWidth: 0 },
  280. color: [COLORS.main, '#ff9a70', COLORS.light],
  281. data: [{ name: '曝光', value: f.exposure }, { name: '进店', value: f.visit }, { name: '下单', value: f.order }],
  282. }],
  283. });
  284. }
  285. const structure = byId.get('chart_structure');
  286. if (structure) {
  287. const chart = mount(structure);
  288. chart && chart.setOption({
  289. ...chartBase(interactive),
  290. grid: { left: 56, right: 20, top: 28, bottom: 30 },
  291. legend: { right: 0, top: 0, itemWidth: 10, itemHeight: 10, textStyle: { fontSize: 11 } },
  292. xAxis: { type: 'category', data: structure.data.map((d) => d.date.slice(4)), axisTick: { show: false }, axisLine: { lineStyle: { color: '#e5e0da' } } },
  293. yAxis: { type: 'value', splitLine: { lineStyle: { color: '#f2efea' } } },
  294. series: [
  295. { name: '收入', type: 'bar', barMaxWidth: 18, itemStyle: { color: COLORS.main }, data: structure.data.map((d) => d.income) },
  296. { name: '支出', type: 'bar', barMaxWidth: 18, itemStyle: { color: COLORS.grey }, data: structure.data.map((d) => d.expense) },
  297. { name: '补贴', type: 'bar', barMaxWidth: 18, itemStyle: { color: COLORS.light }, data: structure.data.map((d) => d.subsidy) },
  298. ],
  299. });
  300. }
  301. }
  302. // ---------- 数据 ----------
  303. async function load(force) {
  304. if (state.loading) return;
  305. state.loading = true;
  306. const page = $('rpPage');
  307. if (page && !state.report) page.innerHTML = '<div class="rp-loading">正在生成报告…</div>';
  308. try {
  309. const params = new URLSearchParams();
  310. if (state.from) params.set('from', state.from);
  311. if (state.to) params.set('to', state.to);
  312. const { res, body } = await api('/api/ops/report?' + params.toString());
  313. if (!res.ok) throw new Error((body && (body.detail || body.error)) || ('HTTP ' + res.status));
  314. if (body.empty) {
  315. page.innerHTML = '<div class="rp-loading">所选范围没有数据,请先导入明细。</div>';
  316. return;
  317. }
  318. state.report = body.report;
  319. renderReport(state.report);
  320. } catch (e) {
  321. page.innerHTML = `<div class="rp-loading">报告生成失败:${esc(e.message || e)}</div>`;
  322. } finally {
  323. state.loading = false;
  324. }
  325. }
  326. async function initDates() {
  327. const { body } = await api('/api/ops/summary');
  328. const coverage = body && body.coverage;
  329. if (!coverage) return;
  330. const to = coverage.to;
  331. const d = new Date(Date.UTC(Number(to.slice(0, 4)), Number(to.slice(4, 6)) - 1, Number(to.slice(6, 8)) - 6));
  332. const from = `${d.getUTCFullYear()}${String(d.getUTCMonth() + 1).padStart(2, '0')}${String(d.getUTCDate()).padStart(2, '0')}`;
  333. state.to = to;
  334. state.from = from < coverage.from ? coverage.from : from;
  335. const toInput = (ymd) => `${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`;
  336. $('rpFrom').value = toInput(state.from);
  337. $('rpTo').value = toInput(state.to);
  338. }
  339. window.shanReportInit = function () {
  340. if (!state.inited) {
  341. state.inited = true;
  342. renderShell();
  343. initDates().then(() => load());
  344. window.addEventListener('resize', () => {
  345. Object.values(state.charts).forEach((chart) => chart && chart.resize());
  346. });
  347. window.addEventListener('beforeprint', () => {
  348. Object.values(state.charts).forEach((chart) => chart && chart.resize());
  349. });
  350. }
  351. };
  352. })();