report.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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">保存报告</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. page.innerHTML = [
  230. renderCover(report),
  231. renderSummary(report),
  232. renderKpis(report),
  233. renderSections(report),
  234. renderAlerts(report),
  235. renderQuality(report),
  236. `<footer class="rp-footer">${report.ai && report.ai.source === 'llm' ? `文字由 AI 生成(${esc(report.ai.model || '')})` : '当前为规则版文字'};数值均由后端按统一口径计算。${report.aiError ? ' ' + esc(report.aiError) : ''}</footer>`,
  237. ].join('');
  238. drawCharts(report);
  239. }
  240. // ---------- 图表 ----------
  241. function chartBase(interactive) {
  242. return {
  243. animation: !interactive,
  244. silent: !interactive,
  245. tooltip: interactive ? { trigger: 'axis' } : undefined,
  246. };
  247. }
  248. function drawCharts(report) {
  249. const interactive = state.mode === 'interactive';
  250. const byId = new Map((report.charts || []).map((c) => [c.id, c]));
  251. Object.values(state.charts).forEach((chart) => chart && chart.dispose());
  252. state.charts = {};
  253. const mount = (chart) => {
  254. const el = $(`rpChart_${chart.id}`);
  255. if (!el) return null;
  256. const instance = echarts.init(el);
  257. state.charts[chart.id] = instance;
  258. return instance;
  259. };
  260. const trend = byId.get('chart_trend');
  261. if (trend) {
  262. const chart = mount(trend);
  263. chart && chart.setOption({
  264. ...chartBase(interactive),
  265. grid: { left: 56, right: 48, top: 24, bottom: 30 },
  266. legend: { right: 0, top: 0, itemWidth: 10, itemHeight: 10, textStyle: { fontSize: 11 } },
  267. xAxis: { type: 'category', data: trend.data.map((d) => d.date.slice(4)), axisTick: { show: false }, axisLine: { lineStyle: { color: '#e5e0da' } } },
  268. yAxis: [{ type: 'value', splitLine: { lineStyle: { color: '#f2efea' } } }, { type: 'value', splitLine: { show: false } }],
  269. series: [
  270. { name: '营业额', type: 'bar', barMaxWidth: 22, itemStyle: { color: COLORS.main, borderRadius: [3, 3, 0, 0] }, data: trend.data.map((d) => d.revenue) },
  271. { name: '订单', type: 'line', yAxisIndex: 1, symbolSize: 5, lineStyle: { width: 2, color: COLORS.blue }, itemStyle: { color: COLORS.blue }, data: trend.data.map((d) => d.orders) },
  272. ],
  273. });
  274. }
  275. const rank = byId.get('chart_rank');
  276. if (rank) {
  277. const rows = rank.data.slice().reverse();
  278. const chart = mount(rank);
  279. chart && chart.setOption({
  280. ...chartBase(interactive),
  281. grid: { left: 8, right: 60, top: 10, bottom: 10, containLabel: true },
  282. xAxis: { type: 'value', splitLine: { lineStyle: { color: '#f2efea' } } },
  283. yAxis: { type: 'category', data: rows.map((r) => r.shopName), axisTick: { show: false }, axisLine: { show: false }, axisLabel: { width: 140, overflow: 'truncate', fontSize: 11 } },
  284. 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) }],
  285. });
  286. }
  287. const funnel = byId.get('chart_funnel');
  288. if (funnel) {
  289. const f = funnel.data;
  290. const chart = mount(funnel);
  291. chart && chart.setOption({
  292. ...chartBase(interactive),
  293. series: [{
  294. type: 'funnel', left: '10%', right: '10%', top: 12, bottom: 12, minSize: '30%', gap: 3,
  295. label: { show: true, position: 'inside', color: '#fff', fontSize: 11, formatter: (p) => `${p.name} ${Number(p.value).toLocaleString('zh-CN')}` },
  296. itemStyle: { borderWidth: 0 },
  297. color: [COLORS.main, '#ff9a70', COLORS.light],
  298. data: [{ name: '曝光', value: f.exposure }, { name: '进店', value: f.visit }, { name: '下单', value: f.order }],
  299. }],
  300. });
  301. }
  302. const structure = byId.get('chart_structure');
  303. if (structure) {
  304. const chart = mount(structure);
  305. chart && chart.setOption({
  306. ...chartBase(interactive),
  307. grid: { left: 56, right: 20, top: 28, bottom: 30 },
  308. legend: { right: 0, top: 0, itemWidth: 10, itemHeight: 10, textStyle: { fontSize: 11 } },
  309. xAxis: { type: 'category', data: structure.data.map((d) => d.date.slice(4)), axisTick: { show: false }, axisLine: { lineStyle: { color: '#e5e0da' } } },
  310. yAxis: { type: 'value', splitLine: { lineStyle: { color: '#f2efea' } } },
  311. series: [
  312. { name: '收入', type: 'bar', barMaxWidth: 18, itemStyle: { color: COLORS.main }, data: structure.data.map((d) => d.income) },
  313. { name: '支出', type: 'bar', barMaxWidth: 18, itemStyle: { color: COLORS.grey }, data: structure.data.map((d) => d.expense) },
  314. { name: '补贴', type: 'bar', barMaxWidth: 18, itemStyle: { color: COLORS.light }, data: structure.data.map((d) => d.subsidy) },
  315. ],
  316. });
  317. }
  318. }
  319. // ---------- 报告中心 ----------
  320. async function saveReport() {
  321. const btn = $('rpSave');
  322. btn.disabled = true;
  323. btn.textContent = '保存中…';
  324. try {
  325. const { res, body } = await api('/api/ops/reports', {
  326. method: 'POST',
  327. headers: { 'Content-Type': 'application/json' },
  328. body: JSON.stringify({ from: state.from, to: state.to, schools: state.schools.join(','), shops: state.shops.join(',') }),
  329. });
  330. if (!res.ok) throw new Error((body && (body.detail || body.error)) || ('HTTP ' + res.status));
  331. btn.textContent = '已保存';
  332. setTimeout(() => { btn.textContent = '保存报告'; btn.disabled = false; }, 1500);
  333. } catch (e) {
  334. btn.textContent = '保存报告';
  335. btn.disabled = false;
  336. alert('保存失败:' + (e.message || e));
  337. }
  338. }
  339. async function openHistory() {
  340. $('rpHistoryModal').hidden = false;
  341. await renderHistory();
  342. }
  343. async function renderHistory() {
  344. const list = $('rpHistoryList');
  345. list.innerHTML = '<div class="rp-loading" style="padding:24px 0">加载中…</div>';
  346. const { res, body } = await api('/api/ops/reports');
  347. if (!res.ok) {
  348. list.innerHTML = `<div class="rp-loading">读取失败:${esc((body && (body.error || body.detail)) || res.status)}</div>`;
  349. return;
  350. }
  351. const reports = (body && body.reports) || [];
  352. if (!reports.length) {
  353. list.innerHTML = '<div class="rp-loading" style="padding:24px 0">还没有保存过报告</div>';
  354. return;
  355. }
  356. list.innerHTML = `<table class="rp-table">
  357. <thead><tr><th>保存时间</th><th>区间</th><th>来源</th><th>关键指标</th><th class="rp-col-actions">操作</th></tr></thead>
  358. <tbody>${reports.map((r) => `<tr>
  359. <td>${esc(new Date(r.createdAt).toLocaleString('zh-CN'))}</td>
  360. <td>${esc(r.from)} ~ ${esc(r.to)}</td>
  361. <td>${r.source === 'llm' ? 'AI 生成' : '规则生成'}</td>
  362. <td class="rp-history-kpis">${(r.kpis || []).map((k) => `${esc(k.label)} ${esc(k.current)}`).join(' · ')}</td>
  363. <td class="rp-col-actions">
  364. <button type="button" class="btn btn-ghost btn-small" data-view="${esc(r.id)}">查看</button>
  365. <button type="button" class="btn btn-ghost btn-small" data-del="${esc(r.id)}">删除</button>
  366. </td>
  367. </tr>`).join('')}</tbody>
  368. </table>`;
  369. list.querySelectorAll('[data-view]').forEach((btn) => {
  370. btn.addEventListener('click', () => loadSaved(btn.dataset.view));
  371. });
  372. list.querySelectorAll('[data-del]').forEach((btn) => {
  373. btn.addEventListener('click', async () => {
  374. if (!confirm('删除这份历史报告?')) return;
  375. btn.disabled = true;
  376. await api('/api/ops/reports/' + encodeURIComponent(btn.dataset.del), { method: 'DELETE' });
  377. renderHistory();
  378. });
  379. });
  380. }
  381. async function loadSaved(id) {
  382. const { res, body } = await api('/api/ops/reports/' + encodeURIComponent(id));
  383. if (!res.ok || !body || !body.report) {
  384. alert('读取失败');
  385. return;
  386. }
  387. const report = body.report;
  388. state.report = report;
  389. const from = String(report.meta.period_start || '').replace(/-/g, '');
  390. const to = String(report.meta.period_end || '').replace(/-/g, '');
  391. state.from = from;
  392. state.to = to;
  393. $('rpFrom').value = String(report.meta.period_start || '');
  394. $('rpTo').value = String(report.meta.period_end || '');
  395. renderReport(report);
  396. $('rpHistoryModal').hidden = true;
  397. }
  398. // ---------- 数据 ----------
  399. async function load(force) {
  400. if (state.loading) return;
  401. state.loading = true;
  402. const page = $('rpPage');
  403. if (page && !state.report) page.innerHTML = '<div class="rp-loading">正在生成报告…</div>';
  404. try {
  405. const params = new URLSearchParams();
  406. if (state.from) params.set('from', state.from);
  407. if (state.to) params.set('to', state.to);
  408. if (state.schools.length) params.set('schools', state.schools.join(','));
  409. if (state.shops.length) params.set('shops', state.shops.join(','));
  410. params.set('ai', '1'); // 默认走 AI,失败自动退回规则版
  411. const { res, body } = await api('/api/ops/report?' + params.toString());
  412. if (!res.ok) throw new Error((body && (body.detail || body.error)) || ('HTTP ' + res.status));
  413. if (body.empty) {
  414. page.innerHTML = '<div class="rp-loading">所选范围没有数据,请先导入明细。</div>';
  415. return;
  416. }
  417. state.report = body.report;
  418. renderReport(state.report);
  419. } catch (e) {
  420. page.innerHTML = `<div class="rp-loading">报告生成失败:${esc(e.message || e)}</div>`;
  421. } finally {
  422. state.loading = false;
  423. }
  424. }
  425. function renderFilterChip() {
  426. const chip = $('rpFilterChip');
  427. if (!chip) return;
  428. const parts = [];
  429. if (state.schools.length) parts.push(state.schools.length === 1 ? state.schools[0] : `${state.schools.length} 个学校`);
  430. if (state.shops.length) parts.push(state.shops.length === 1 ? `1 家门店` : `${state.shops.length} 家门店`);
  431. if (!parts.length) {
  432. chip.hidden = true;
  433. chip.innerHTML = '';
  434. return;
  435. }
  436. chip.hidden = false;
  437. chip.innerHTML = `已按 ${parts.join(' · ')} 筛选 <button type="button" id="rpFilterClear">清除</button>`;
  438. $('rpFilterClear').addEventListener('click', () => {
  439. state.schools = [];
  440. state.shops = [];
  441. renderFilterChip();
  442. load(true);
  443. });
  444. }
  445. async function initDates() {
  446. const search = new URLSearchParams(location.search);
  447. const qFrom = String(search.get('from') || '').replace(/\D/g, '');
  448. const qTo = String(search.get('to') || '').replace(/\D/g, '');
  449. const qShops = String(search.get('shops') || '').split(',').map((s) => s.trim()).filter(Boolean);
  450. const qSchools = String(search.get('schools') || '').split(',').map((s) => s.trim()).filter(Boolean);
  451. state.shops = qShops;
  452. state.schools = qSchools;
  453. const toInput = (ymd) => `${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`;
  454. if (/^\d{8}$/.test(qFrom) && /^\d{8}$/.test(qTo)) {
  455. state.from = qFrom;
  456. state.to = qTo;
  457. $('rpFrom').value = toInput(qFrom);
  458. $('rpTo').value = toInput(qTo);
  459. renderFilterChip();
  460. return;
  461. }
  462. const { body } = await api('/api/ops/summary');
  463. const coverage = body && body.coverage;
  464. if (!coverage) return;
  465. const to = coverage.to;
  466. const d = new Date(Date.UTC(Number(to.slice(0, 4)), Number(to.slice(4, 6)) - 1, Number(to.slice(6, 8)) - 6));
  467. const from = `${d.getUTCFullYear()}${String(d.getUTCMonth() + 1).padStart(2, '0')}${String(d.getUTCDate()).padStart(2, '0')}`;
  468. state.to = to;
  469. state.from = from < coverage.from ? coverage.from : from;
  470. $('rpFrom').value = toInput(state.from);
  471. $('rpTo').value = toInput(state.to);
  472. renderFilterChip();
  473. }
  474. window.shanReportInit = function () {
  475. if (!state.inited) {
  476. state.inited = true;
  477. renderShell();
  478. initDates().then(() => load());
  479. window.addEventListener('resize', () => {
  480. Object.values(state.charts).forEach((chart) => chart && chart.resize());
  481. });
  482. window.addEventListener('beforeprint', () => {
  483. Object.values(state.charts).forEach((chart) => chart && chart.resize());
  484. });
  485. }
  486. };
  487. })();