| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620 |
- 'use strict';
- // 经营报告:同一份 Report JSON 渲染「图文报告 / 交互报告」,PDF 走浏览器打印样式。
- // 数据来自 GET /api/ops/report(后端算指标、规则打标,模型只负责文字)。
- (function () {
- const $ = (id) => document.getElementById(id);
- const COLORS = { main: '#ff6b35', soft: '#ffb08a', grey: '#c9c2ba', blue: '#7a9cc6', light: '#ffd6c2' };
- const state = {
- inited: false,
- loading: false,
- report: null,
- from: '',
- to: '',
- schools: [],
- shops: [],
- charts: {},
- };
- function esc(value) {
- const div = document.createElement('div');
- div.textContent = String(value == null ? '' : value);
- return div.innerHTML;
- }
- function moneyText(v) {
- if (v == null) return '–';
- const n = Number(v);
- return Number.isFinite(n) ? n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : '–';
- }
- function kpiText(kpi) {
- if (kpi.current == null) return '–';
- if (kpi.unit === '%') return kpi.current + '%';
- if (kpi.unit === '单' || kpi.unit === '人') return numText(kpi.current);
- return moneyText(kpi.current);
- }
- function numText(v) {
- if (v == null) return '–';
- const n = Number(v);
- return Number.isFinite(n) ? n.toLocaleString('zh-CN') : '–';
- }
- function deltaText(kpi) {
- if (kpi.change_pct == null) return '<span class="rp-delta muted">—</span>';
- const up = kpi.change_pct > 0;
- const cls = kpi.change_pct === 0 ? 'muted' : up ? 'up' : 'down';
- const unit = kpi.unit === '%' ? 'pp' : '%';
- return `<span class="rp-delta ${cls}">${up ? '↑' : '↓'} ${Math.abs(kpi.change_pct).toFixed(1)}${unit}</span>`;
- }
- async function api(url, options) {
- const res = await fetch(url, options);
- const body = await res.json().catch(() => null);
- return { res, body };
- }
- // ---------- 渲染 ----------
- function renderShell() {
- const root = $('reportRoot');
- if (!root) return;
- root.innerHTML = `
- <div class="rp-toolbar">
- <div class="rp-range">
- <input type="date" class="ops-input" id="rpFrom">
- <span class="ops-tilde">~</span>
- <input type="date" class="ops-input" id="rpTo">
- </div>
- <div class="ops-multi" id="rpSchool"></div>
- <div class="ops-multi" id="rpShop"></div>
- <div class="rp-actions">
- <button type="button" class="btn btn-ghost btn-small" id="rpArchive">历史报告</button>
- <button type="button" class="btn btn-ghost btn-small" id="rpSave" disabled>保存报告</button>
- <button type="button" class="btn btn-ghost btn-small" id="rpRefresh">重新生成</button>
- <button type="button" class="btn btn-primary btn-small" id="rpPrint">下载 PDF</button>
- </div>
- </div>
- <article class="rp-page" id="rpPage"></article>
- <div class="modal-overlay" id="rpHistoryModal" hidden>
- <div class="modal rp-history-modal">
- <div class="modal-header">
- <div class="modal-title"><span>历史报告</span></div>
- <button class="modal-close" id="rpHistoryClose" type="button" aria-label="关闭">×</button>
- </div>
- <div class="modal-body" id="rpHistoryList"></div>
- </div>
- </div>`;
- $('rpFrom').addEventListener('change', (e) => { state.from = String(e.target.value || '').replace(/-/g, ''); load(true); });
- $('rpTo').addEventListener('change', (e) => { state.to = String(e.target.value || '').replace(/-/g, ''); load(true); });
- $('rpRefresh').addEventListener('click', () => load(true));
- $('rpPrint').addEventListener('click', () => window.print());
- $('rpSave').addEventListener('click', saveReport);
- $('rpArchive').addEventListener('click', openHistory);
- $('rpHistoryClose').addEventListener('click', () => { $('rpHistoryModal').hidden = true; });
- }
- function renderCover(report) {
- const meta = report.meta || {};
- return `
- <header class="rp-cover">
- <div class="rp-cover-main">
- <div class="rp-kicker">AI 经营分析报告</div>
- <h1>${esc(meta.title || '经营分析报告')}</h1>
- <div class="rp-cover-sub">${esc(meta.organization || '')}${meta.organization ? ' · ' : ''}${esc(meta.period_start)} ~ ${esc(meta.period_end)}</div>
- </div>
- <div class="rp-cover-meta">
- <div><span>统计范围</span><b>${esc(meta.data_scope || '–')}</b></div>
- <div><span>数据来源</span><b>${esc((meta.source_files || []).join('、') || '平台导出明细')}</b></div>
- <div><span>生成时间</span><b>${esc(new Date(meta.generated_at).toLocaleString('zh-CN'))}</b></div>
- </div>
- </header>`;
- }
- function renderSummary(report) {
- const summary = report.executive_summary || {};
- const dot = { positive: 'ok', neutral: 'na', warning: 'warn', critical: 'bad' };
- const items = (summary.key_findings || []).map((f) => `
- <li>
- <span class="rp-dot ${dot[f.severity] || 'na'}"></span>
- <div>
- <b>${esc(f.finding)}</b>
- <p>${esc(f.interpretation || '')}</p>
- ${(f.evidence || []).length ? `<div class="rp-evidence">${f.evidence.map((e) => `<code>${esc(e)}</code>`).join('')}</div>` : ''}
- </div>
- </li>`).join('');
- return `
- <section class="rp-section rp-summary">
- <h2>管理层摘要</h2>
- <p class="rp-lead">${esc(summary.overall_assessment || '')}</p>
- <ul class="rp-findings">${items}</ul>
- </section>`;
- }
- function renderKpis(report) {
- return `
- <section class="rp-section">
- <h2>核心指标</h2>
- <div class="rp-kpis">
- ${(report.kpis || []).map((kpi) => `
- <div class="rp-kpi" title="${esc(kpi.definition)}">
- <div class="rp-kpi-label">${esc(kpi.label)}<span>${esc(kpi.unit === 'CNY' ? '元' : kpi.unit)}</span></div>
- <div class="rp-kpi-value">${kpiText(kpi)}</div>
- <div class="rp-kpi-foot">${deltaText(kpi)}<span class="rp-kpi-hint">较上期</span></div>
- </div>`).join('')}
- </div>
- <p class="rp-note">口径:${(report.kpis || []).map((k) => `${k.label}=${k.definition}`).join(';')}</p>
- </section>`;
- }
- function chartCard(id, title, subtitle) {
- return `<figure class="rp-figure">
- <figcaption><b>${esc(title)}</b><span>${esc(subtitle || '')}</span></figcaption>
- <div class="rp-chart" id="${id}"></div>
- </figure>`;
- }
- function renderSections(report) {
- const chartById = new Map((report.charts || []).map((c) => [c.id, c]));
- const tableById = new Map((report.tables || []).map((t) => [t.id, t]));
- return (report.sections || []).map((section, index) => {
- if (section.id === 'quality') return '';
- const charts = (section.chart_ids || []).map((id) => chartById.get(id)).filter(Boolean);
- const tables = (section.table_ids || []).map((id) => tableById.get(id)).filter(Boolean);
- return `
- <section class="rp-section">
- <h2><em>${String(index + 1).padStart(2, '0')}</em>${esc(section.title)}</h2>
- ${section.summary ? `<p class="rp-lead">${esc(section.summary)}</p>` : ''}
- ${(section.paragraphs || []).map((p) => `<p>${esc(p)}</p>`).join('')}
- ${charts.map((chart) => chartCard(`rpChart_${chart.id}`, chart.title, chart.description)).join('')}
- ${tables.map((table) => renderTable(table)).join('')}
- </section>`;
- }).join('');
- }
- function renderTable(table) {
- return `
- <div class="rp-table-wrap">
- <table class="rp-table">
- <thead><tr>${table.columns.map((c) => `<th>${esc(c.label)}</th>`).join('')}</tr></thead>
- <tbody>${(table.rows || []).map((row) => `<tr>${table.columns.map((c) => {
- const v = row[c.key];
- const text = c.key === 'revenue' ? moneyText(v) : c.key === 'share' ? (v == null ? '–' : v + '%') : (v == null ? '–' : esc(v));
- return `<td>${text}</td>`;
- }).join('')}</tr>`).join('')}</tbody>
- </table>
- ${table.footnote ? `<p class="rp-note">${esc(table.footnote)}</p>` : ''}
- </div>`;
- }
- function renderAlerts(report) {
- const alerts = report.alerts || [];
- const plan = report.action_plan || [];
- return `
- <section class="rp-section">
- <h2><em>05</em>风险与建议</h2>
- <div class="rp-alerts">
- ${alerts.map((a) => `
- <div class="rp-alert ${esc(a.severity)}">
- <div class="rp-alert-head"><span class="rp-badge">${esc(a.severity)}</span><b>${esc(a.title)}</b></div>
- <ul>${(a.evidence || []).map((e) => `<li>${esc(e)}</li>`).join('')}</ul>
- ${(a.hypotheses || []).length ? `<p class="rp-note">待验证:${a.hypotheses.map(esc).join('、')}</p>` : ''}
- </div>`).join('') || '<p class="rp-note">本期未触发风险规则。</p>'}
- </div>
- <h3 class="rp-h3">行动计划</h3>
- <table class="rp-table">
- <thead><tr><th>优先级</th><th>行动</th><th>负责人</th><th>时间窗</th><th>验收指标</th></tr></thead>
- <tbody>${plan.map((p) => `<tr>
- <td><span class="rp-badge">${esc(p.priority)}</span></td>
- <td>${esc(p.action)}</td>
- <td>${esc(p.owner_role)}</td>
- <td>${esc(p.time_horizon)}</td>
- <td>${esc(p.success_metric)}</td>
- </tr>`).join('')}</tbody>
- </table>
- </section>`;
- }
- function renderQuality(report) {
- const q = report.data_quality || {};
- return `
- <section class="rp-section rp-quality">
- <h2><em>06</em>数据质量与方法论</h2>
- <p><b>覆盖范围:</b>${esc(q.coverage || '–')}</p>
- <p><b>可比性:</b>${esc(q.comparability || '–')}</p>
- ${(q.warnings || []).length ? `<p><b>提示:</b>${q.warnings.map(esc).join(';')}</p>` : ''}
- ${(q.missing_metrics || []).length ? `<p><b>缺失指标:</b>${q.missing_metrics.map(esc).join(';')}</p>` : ''}
- <p><b>方法论:</b></p>
- <ul class="rp-method">${(report.methodology || []).map((m) => `<li>${esc(m)}</li>`).join('')}</ul>
- </section>`;
- }
- function renderReport(report) {
- const page = $('rpPage');
- const saveBtn = $('rpSave');
- if (saveBtn) saveBtn.disabled = false;
- page.innerHTML = [
- renderCover(report),
- renderSummary(report),
- renderKpis(report),
- renderSections(report),
- renderAlerts(report),
- renderQuality(report),
- `<footer class="rp-footer">${report.ai && report.ai.source === 'llm' ? `文字由 AI 生成(${esc(report.ai.model || '')})` : '当前为规则版文字'};数值均由后端按统一口径计算。${report.aiError ? ' ' + esc(report.aiError) : ''}</footer>`,
- ].join('');
- drawCharts(report);
- }
- // ---------- 图表 ----------
- function chartBase() {
- return {
- animation: true,
- tooltip: { trigger: 'axis' },
- };
- }
- function drawCharts(report) {
-
- const byId = new Map((report.charts || []).map((c) => [c.id, c]));
- Object.values(state.charts).forEach((chart) => chart && chart.dispose());
- state.charts = {};
- const mount = (chart) => {
- const el = $(`rpChart_${chart.id}`);
- if (!el) return null;
- const instance = echarts.init(el);
- state.charts[chart.id] = instance;
- return instance;
- };
- const trend = byId.get('chart_trend');
- if (trend) {
- const chart = mount(trend);
- chart && chart.setOption({
- ...chartBase(),
- grid: { left: 56, right: 48, top: 24, bottom: 30 },
- legend: { right: 0, top: 0, itemWidth: 10, itemHeight: 10, textStyle: { fontSize: 11 } },
- xAxis: { type: 'category', data: trend.data.map((d) => d.date.slice(4)), axisTick: { show: false }, axisLine: { lineStyle: { color: '#e5e0da' } } },
- yAxis: [{ type: 'value', splitLine: { lineStyle: { color: '#f2efea' } } }, { type: 'value', splitLine: { show: false } }],
- series: [
- { name: '营业额', type: 'bar', barMaxWidth: 22, itemStyle: { color: COLORS.main, borderRadius: [3, 3, 0, 0] }, data: trend.data.map((d) => d.revenue) },
- { name: '订单', type: 'line', yAxisIndex: 1, symbolSize: 5, lineStyle: { width: 2, color: COLORS.blue }, itemStyle: { color: COLORS.blue }, data: trend.data.map((d) => d.orders) },
- ],
- });
- }
- const rank = byId.get('chart_rank');
- if (rank) {
- const rows = rank.data.slice().reverse();
- const chart = mount(rank);
- chart && chart.setOption({
- ...chartBase(),
- grid: { left: 8, right: 60, top: 10, bottom: 10, containLabel: true },
- xAxis: { type: 'value', splitLine: { lineStyle: { color: '#f2efea' } } },
- yAxis: { type: 'category', data: rows.map((r) => r.shopName), axisTick: { show: false }, axisLine: { show: false }, axisLabel: { width: 140, overflow: 'truncate', fontSize: 11 } },
- 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) }],
- });
- }
- const funnel = byId.get('chart_funnel');
- if (funnel) {
- const f = funnel.data;
- const chart = mount(funnel);
- chart && chart.setOption({
- ...chartBase(),
- series: [{
- type: 'funnel', left: '10%', right: '10%', top: 12, bottom: 12, minSize: '30%', gap: 3,
- label: { show: true, position: 'inside', color: '#fff', fontSize: 11, formatter: (p) => `${p.name} ${Number(p.value).toLocaleString('zh-CN')}` },
- itemStyle: { borderWidth: 0 },
- color: [COLORS.main, '#ff9a70', COLORS.light],
- data: [{ name: '曝光', value: f.exposure }, { name: '进店', value: f.visit }, { name: '下单', value: f.order }],
- }],
- });
- }
- const structure = byId.get('chart_structure');
- if (structure) {
- const chart = mount(structure);
- chart && chart.setOption({
- ...chartBase(),
- grid: { left: 56, right: 20, top: 28, bottom: 30 },
- legend: { right: 0, top: 0, itemWidth: 10, itemHeight: 10, textStyle: { fontSize: 11 } },
- xAxis: { type: 'category', data: structure.data.map((d) => d.date.slice(4)), axisTick: { show: false }, axisLine: { lineStyle: { color: '#e5e0da' } } },
- yAxis: { type: 'value', splitLine: { lineStyle: { color: '#f2efea' } } },
- series: [
- { name: '收入', type: 'bar', barMaxWidth: 18, itemStyle: { color: COLORS.main }, data: structure.data.map((d) => d.income) },
- { name: '支出', type: 'bar', barMaxWidth: 18, itemStyle: { color: COLORS.grey }, data: structure.data.map((d) => d.expense) },
- { name: '补贴', type: 'bar', barMaxWidth: 18, itemStyle: { color: COLORS.light }, data: structure.data.map((d) => d.subsidy) },
- ],
- });
- }
- }
- // ---------- 报告中心 ----------
- async function saveReport() {
- const btn = $('rpSave');
- btn.disabled = true;
- btn.textContent = '保存中…';
- try {
- const { res, body } = await api('/api/ops/reports', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- from: state.from, to: state.to,
- schools: state.schools.join(','), shops: state.shops.join(','),
- report: state.report,
- }),
- });
- if (!res.ok) throw new Error((body && (body.detail || body.error)) || ('HTTP ' + res.status));
- btn.textContent = '已保存';
- setTimeout(() => { btn.textContent = '保存报告'; btn.disabled = false; }, 1500);
- } catch (e) {
- btn.textContent = '保存报告';
- btn.disabled = false;
- alert('保存失败:' + (e.message || e));
- }
- }
- async function openHistory() {
- $('rpHistoryModal').hidden = false;
- await renderHistory();
- }
- async function renderHistory() {
- const list = $('rpHistoryList');
- list.innerHTML = '<div class="rp-loading" style="padding:24px 0">加载中…</div>';
- const { res, body } = await api('/api/ops/reports');
- if (!res.ok) {
- list.innerHTML = `<div class="rp-loading">读取失败:${esc((body && (body.error || body.detail)) || res.status)}</div>`;
- return;
- }
- const reports = (body && body.reports) || [];
- if (!reports.length) {
- list.innerHTML = '<div class="rp-loading" style="padding:24px 0">还没有保存过报告</div>';
- return;
- }
- list.innerHTML = `<table class="rp-table">
- <thead><tr><th>保存时间</th><th>区间</th><th>学校</th><th>店铺</th><th>来源</th><th class="rp-col-actions">操作</th></tr></thead>
- <tbody>${reports.map((r) => `<tr>
- <td>${esc(new Date(r.createdAt).toLocaleString('zh-CN'))}</td>
- <td>${esc(r.from)} ~ ${esc(r.to)}</td>
- <td>${(r.schoolNames || []).length ? esc(r.schoolNames.join('、')) : '<span class="rp-muted">全部</span>'}</td>
- <td title="${esc((r.shopNames || []).join('、'))}">${(r.shopNames || []).length
- ? esc(r.shopNames.slice(0, 3).join('、')) + (r.shopNames.length > 3 ? ` 等 ${r.shopNames.length} 家` : '')
- : '<span class="rp-muted">全部</span>'}</td>
- <td>${r.source === 'llm' ? 'AI 生成' : '规则生成'}</td>
- <td class="rp-col-actions">
- <button type="button" class="btn btn-ghost btn-small" data-view="${esc(r.id)}">查看</button>
- <button type="button" class="btn btn-ghost btn-small" data-pdf="${esc(r.id)}">PDF</button>
- <button type="button" class="btn btn-ghost btn-small" data-json="${esc(r.id)}">JSON</button>
- <button type="button" class="btn btn-ghost btn-small" data-del="${esc(r.id)}">删除</button>
- </td>
- </tr>`).join('')}</tbody>
- </table>`;
- list.querySelectorAll('[data-view]').forEach((btn) => {
- btn.addEventListener('click', () => loadSaved(btn.dataset.view));
- });
- list.querySelectorAll('[data-pdf]').forEach((btn) => {
- btn.addEventListener('click', () => downloadSavedPdf(btn.dataset.pdf));
- });
- list.querySelectorAll('[data-json]').forEach((btn) => {
- btn.addEventListener('click', () => downloadSavedJson(btn.dataset.json));
- });
- list.querySelectorAll('[data-del]').forEach((btn) => {
- btn.addEventListener('click', async () => {
- if (!confirm('删除这份历史报告?')) return;
- btn.disabled = true;
- await api('/api/ops/reports/' + encodeURIComponent(btn.dataset.del), { method: 'DELETE' });
- renderHistory();
- });
- });
- }
- async function fetchSaved(id) {
- const { res, body } = await api('/api/ops/reports/' + encodeURIComponent(id));
- if (!res.ok || !body || !body.report) {
- alert('读取失败');
- return null;
- }
- return body.report;
- }
- async function downloadSavedPdf(id) {
- const report = await fetchSaved(id);
- if (!report) return;
- state.report = report;
- $('rpHistoryModal').hidden = true;
- renderReport(report);
- const meta = report.meta || {};
- const prevTitle = document.title;
- document.title = `经营分析报告_${String(meta.period_start || '').replace(/-/g, '')}-${String(meta.period_end || '').replace(/-/g, '')}`;
- setTimeout(() => {
- window.print();
- document.title = prevTitle;
- }, 500);
- }
- async function downloadSavedJson(id) {
- const report = await fetchSaved(id);
- if (!report) return;
- const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = `经营分析报告_${id}.json`;
- document.body.appendChild(a);
- a.click();
- a.remove();
- setTimeout(() => URL.revokeObjectURL(url), 1000);
- }
- async function loadSaved(id) {
- const { res, body } = await api('/api/ops/reports/' + encodeURIComponent(id));
- if (!res.ok || !body || !body.report) {
- alert('读取失败');
- return;
- }
- const report = body.report;
- state.report = report;
- const from = String(report.meta.period_start || '').replace(/-/g, '');
- const to = String(report.meta.period_end || '').replace(/-/g, '');
- state.from = from;
- state.to = to;
- $('rpFrom').value = String(report.meta.period_start || '');
- $('rpTo').value = String(report.meta.period_end || '');
- renderReport(report);
- $('rpHistoryModal').hidden = true;
- }
- // ---------- 数据 ----------
- function buildParams(force) {
- const params = new URLSearchParams();
- if (state.from) params.set('from', state.from);
- if (state.to) params.set('to', state.to);
- if (state.schools.length) params.set('schools', state.schools.join(','));
- if (state.shops.length) params.set('shops', state.shops.join(','));
- if (force) params.set('ai', '1');
- return params;
- }
- /** 先秒开已生成的报告,再在后台让 AI 重写一版(只尝试一次) */
- async function upgradeToAi(seq) {
- try {
- const params = buildParams(false);
- params.set('ai', '1');
- const { res, body } = await api('/api/ops/report?' + params.toString());
- if (!res.ok || !body || !body.report || seq !== state.loadSeq) return;
- const report = body.report;
- if (report.ai && report.ai.source === 'llm') {
- state.report = report;
- renderReport(report);
- }
- } catch { /* 后台升级失败保持规则版 */ }
- }
- async function load(force) {
- if (state.loading) { state.pending = true; return; }
- state.loading = true;
- const page = $('rpPage');
- if (page) page.classList.add('rp-stale');
- const saveBtn = $('rpSave');
- if (saveBtn) saveBtn.disabled = true;
- if (page && !state.report) page.innerHTML = '<div class="rp-loading">正在生成报告…</div>';
- try {
- const seq = ++state.loadSeq;
- const { res, body } = await api('/api/ops/report?' + buildParams(force).toString());
- if (!res.ok) throw new Error((body && (body.detail || body.error)) || ('HTTP ' + res.status));
- if (body.empty) {
- page.innerHTML = '<div class="rp-loading">所选范围没有数据,请先导入明细。</div>';
- return;
- }
- state.report = body.report;
- renderReport(state.report);
- if (!force && body.report.ai && body.report.ai.source !== 'llm' && !state.aiUpgradeTried) {
- state.aiUpgradeTried = true;
- upgradeToAi(seq);
- }
- } catch (e) {
- page.innerHTML = `<div class="rp-loading">报告生成失败:${esc(e.message || e)}</div>`;
- } finally {
- state.loading = false;
- if (page) page.classList.remove('rp-stale');
- if (state.pending) {
- state.pending = false;
- load(true);
- }
- }
- }
- async function initDates() {
- const search = new URLSearchParams(location.search);
- const qFrom = String(search.get('from') || '').replace(/\D/g, '');
- const qTo = String(search.get('to') || '').replace(/\D/g, '');
- state.shops = String(search.get('shops') || '').split(',').map((s) => s.trim()).filter(Boolean);
- state.schools = String(search.get('schools') || '').split(',').map((s) => s.trim()).filter(Boolean);
- const { body } = await api('/api/ops/summary');
- const summary = body || { schools: [], shops: [] };
- const coverage = summary.coverage;
- const toInput = (ymd) => `${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`;
- if (/^\d{8}$/.test(qFrom) && /^\d{8}$/.test(qTo)) {
- state.from = qFrom;
- state.to = qTo;
- } else if (coverage) {
- const to = coverage.to;
- const d = new Date(Date.UTC(Number(to.slice(0, 4)), Number(to.slice(4, 6)) - 1, Number(to.slice(6, 8)) - 6));
- const from = `${d.getUTCFullYear()}${String(d.getUTCMonth() + 1).padStart(2, '0')}${String(d.getUTCDate()).padStart(2, '0')}`;
- state.to = to;
- state.from = from < coverage.from ? coverage.from : from;
- }
- if (state.from && state.to) {
- $('rpFrom').value = toInput(state.from);
- $('rpTo').value = toInput(state.to);
- }
- mountFilters(summary);
- syncUrl();
- }
- function mountFilters(summary) {
- const schools = (summary.schools || []).map((s) => ({ key: s.name, label: s.name, hint: `${s.shopCount || 0} 家` }));
- window.createMultiSelect($('rpSchool'), {
- label: '学校',
- items: schools,
- selected: state.schools,
- allowEmpty: true,
- emptyLabel: '全部',
- onChange: (keys) => {
- state.schools = keys;
- syncUrl();
- load(true);
- },
- });
- const shops = (summary.shops || []).map((s) => ({
- key: String(s.key || s.shopId || ''),
- label: s.shopName || s.key,
- hint: s.school || '',
- })).filter((item) => item.key);
- window.createMultiSelect($('rpShop'), {
- label: '店铺',
- items: shops,
- selected: state.shops,
- allowEmpty: true,
- emptyLabel: '全部',
- onChange: (keys) => {
- state.shops = keys;
- syncUrl();
- load(true);
- },
- });
- window.bindMultiSelectDismiss();
- }
- function syncUrl() {
- const params = new URLSearchParams({ view: 'report' });
- if (state.from) params.set('from', state.from);
- if (state.to) params.set('to', state.to);
- if (state.schools.length) params.set('schools', state.schools.join(','));
- if (state.shops.length) params.set('shops', state.shops.join(','));
- history.replaceState(null, '', '/?' + params.toString());
- }
- window.shanReportInit = function () {
- if (!state.inited) {
- state.inited = true;
- renderShell();
- initDates().then(() => load());
- window.addEventListener('resize', () => {
- Object.values(state.charts).forEach((chart) => chart && chart.resize());
- });
- window.addEventListener('beforeprint', () => {
- Object.values(state.charts).forEach((chart) => chart && chart.resize());
- });
- }
- };
- })();
|