reports.js 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404
  1. 'use strict';
  2. /**
  3. * 数据采集 + 趋势图表 · 前端逻辑
  4. * 数据采集:多主体 tab / 同步 / 筛选 / BI 表格 / CSV 导出
  5. * 趋势图表:环比指标条 / 主趋势 / 门店排行 / 转化漏斗 / 门店对比 / 周报导出
  6. * 智能问数:右下角机器人(仅经营分析页面显示),弹窗对话,支持上下文追问
  7. */
  8. (function () {
  9. // ---------- 工具 ----------
  10. function showToast(msg, type) {
  11. const wrap = document.getElementById('toast-wrap');
  12. const node = document.createElement('div');
  13. node.className = 'toast toast-' + (type || 'success');
  14. node.textContent = msg;
  15. wrap.appendChild(node);
  16. setTimeout(() => { node.style.opacity = '0'; node.style.transition = 'opacity 0.3s'; }, 2600);
  17. setTimeout(() => { if (node.parentNode) wrap.removeChild(node); }, 3000);
  18. }
  19. async function jsonFetch(url, opts) {
  20. const r = await fetch(url, opts);
  21. const data = await r.json().catch(() => ({}));
  22. if (!r.ok) throw new Error(data.error || `HTTP ${r.status}`);
  23. return data;
  24. }
  25. const z2 = (n) => String(n).padStart(2, '0');
  26. function ymdLocal(d) { return `${d.getFullYear()}${z2(d.getMonth() + 1)}${z2(d.getDate())}`; }
  27. function daysAgoYmd(n) { return ymdLocal(new Date(Date.now() - n * 86400000)); }
  28. function ymdToDash(s) { return /^\d{8}$/.test(String(s)) ? `${s.slice(0, 4)}-${s.slice(4, 6)}-${s.slice(6, 8)}` : String(s || ''); }
  29. function dashToYmd(s) { return /^\d{4}-\d{2}-\d{2}$/.test(String(s)) ? s.replace(/-/g, '') : ''; }
  30. function fmtNum(v) {
  31. if (v == null || v === '') return '—';
  32. const n = Number(v);
  33. return Number.isFinite(n) ? n.toLocaleString('zh-CN', { maximumFractionDigits: 0 }) : String(v);
  34. }
  35. function fmtMoney(v) {
  36. if (v == null || v === '') return '—';
  37. const n = Number(v);
  38. return Number.isFinite(n) ? n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : String(v);
  39. }
  40. function fmtPct(v) {
  41. if (v == null || v === '') return '—';
  42. const n = Number(v);
  43. return Number.isFinite(n) ? (n * 100).toFixed(2) + '%' : String(v);
  44. }
  45. function fmtCell(col, v) {
  46. if (col.type === 'pct') return fmtPct(v);
  47. if (col.type === 'money') return fmtMoney(v);
  48. if (col.type === 'int') return fmtNum(v);
  49. if (col.type === 'num') return v == null || v === '' ? '—' : Number(v).toFixed(2);
  50. if (col.type === 'date') return v ? ymdToDash(v) : '—';
  51. return v == null || v === '' ? '—' : String(v);
  52. }
  53. function fmtByCol(col, v) {
  54. if (v == null || v === '') return '—';
  55. if (!col) return String(v);
  56. if (col.type === 'pct') return fmtPct(v);
  57. if (col.type === 'money') return fmtMoney(v);
  58. if (col.type === 'int') return fmtNum(v);
  59. if (col.type === 'num') return Number(v).toFixed(2);
  60. return String(v);
  61. }
  62. const RATE_THRESHOLDS = { clkExpRate: { good: 0.09, bad: 0.06 }, ordClkRate: { good: 0.025, bad: 0.02 } };
  63. function rateClass(key, v) {
  64. const t = RATE_THRESHOLDS[key];
  65. if (!t || v == null || v === '') return '';
  66. const n = Number(v);
  67. if (!Number.isFinite(n)) return '';
  68. if (n >= t.good) return 'val-good';
  69. if (n < t.bad) return 'val-bad';
  70. return 'val-warn';
  71. }
  72. const LS = {
  73. get(k, fallback) { try { const v = localStorage.getItem(k); return v == null ? fallback : JSON.parse(v); } catch { return fallback; } },
  74. set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch { /* ignore */ } },
  75. };
  76. // ---------- 状态 ----------
  77. const state = {
  78. inited: false,
  79. entities: [],
  80. entity: null,
  81. preset: '30',
  82. mode: 'detail',
  83. rawView: false,
  84. page: 1,
  85. pageSize: 200,
  86. total: 0,
  87. pages: 1,
  88. shopFilter: new Set(),
  89. q: '',
  90. columns: [],
  91. visible: new Set(),
  92. sortKey: 'date',
  93. sortDir: 'desc',
  94. rows: [],
  95. summary: null,
  96. conn: null,
  97. syncShops: new Set(),
  98. syncPollTimer: null,
  99. reportAbort: null,
  100. analysisShopFilter: new Set(),
  101. analysisPreset: '30',
  102. comparePrev: true,
  103. chat: { open: false, busy: false, messages: [] },
  104. };
  105. let chartMetric = LS.get('shanReports.chartMetric', 'grossAmt');
  106. const chartInstances = {};
  107. let anaCache = null;
  108. let lastAskApply = null;
  109. const $ = (id) => document.getElementById(id);
  110. // ---------- 日期区间 ----------
  111. function currentRange() {
  112. if (state.preset === 'custom') {
  113. const from = dashToYmd($('reportFromDate').value);
  114. const to = dashToYmd($('reportToDate').value);
  115. if (from && to && from <= to) return { from, to };
  116. return { from: daysAgoYmd(30), to: daysAgoYmd(0) };
  117. }
  118. const days = Number(state.preset) || 30;
  119. return { from: daysAgoYmd(days), to: daysAgoYmd(0) };
  120. }
  121. function analysisRange() {
  122. const sel = $('analysisRangePreset');
  123. const days = Number(sel && sel.value) || 30;
  124. return { from: daysAgoYmd(days), to: daysAgoYmd(0) };
  125. }
  126. // ---------- 主体 tabs(数据采集 / 趋势图表 共用选中) ----------
  127. function activeEntity() {
  128. return state.entities.find((e) => e.key === state.entity) || null;
  129. }
  130. function renderEntityTabs() {
  131. for (const containerId of ['entityTabs', 'analysisEntityTabs', 'lakeEntityTabs']) {
  132. const wrap = $(containerId);
  133. if (!wrap) continue;
  134. wrap.innerHTML = '';
  135. if (!state.entities.length) {
  136. const empty = document.createElement('div');
  137. empty.className = 'entity-tabs-empty';
  138. empty.textContent = '暂无主体 —— 请先在商家客户端登录并完成一次「同步数据」';
  139. wrap.appendChild(empty);
  140. continue;
  141. }
  142. for (const e of state.entities) {
  143. const btn = document.createElement('button');
  144. btn.type = 'button';
  145. btn.className = 'entity-tab' + (e.key === state.entity ? ' active' : '');
  146. btn.innerHTML = `<span class="entity-name"></span><span class="entity-meta"></span>`;
  147. btn.querySelector('.entity-name').textContent = e.name || e.key;
  148. const shopCount = (e.shops || []).length || e.shopCount || 0;
  149. btn.querySelector('.entity-meta').textContent = shopCount ? `${shopCount} 家门店` : '主体';
  150. btn.addEventListener('click', () => {
  151. if (state.entity === e.key) return;
  152. state.entity = e.key;
  153. state.shopFilter = new Set();
  154. state.analysisShopFilter = new Set();
  155. state.sortKey = 'date'; state.sortDir = 'desc';
  156. LS.set('shanReports.entity', e.key);
  157. anaCache = null;
  158. renderEntityTabs();
  159. renderShopOptions();
  160. reloadReport();
  161. renderCharts();
  162. });
  163. wrap.appendChild(btn);
  164. }
  165. }
  166. }
  167. // ---------- 门店多选下拉(数据采集 / 同步 / 趋势图表 三处) ----------
  168. function toggleDropdown(menuId, triggerId, open) {
  169. const trigger = $(triggerId);
  170. const menu = menuId ? $(menuId) : null;
  171. const shouldOpen = open === undefined ? (menu ? menu.hidden : false) : open;
  172. if (menu) menu.hidden = !shouldOpen;
  173. if (trigger) trigger.setAttribute('aria-expanded', String(shouldOpen));
  174. }
  175. function fillShopMenu(menu, shops) {
  176. menu.innerHTML = '';
  177. const all = document.createElement('button');
  178. all.type = 'button';
  179. all.className = 'scan-dropdown-item';
  180. all.dataset.value = '__all__';
  181. all.setAttribute('role', 'option');
  182. all.innerHTML = '<span class="scan-check"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12.5l4.5 4.5L19 7.5"/></svg></span><span>全部门店</span>';
  183. menu.appendChild(all);
  184. const sorted = shops.slice().sort((a, b) => String(a.shopName).localeCompare(String(b.shopName), 'zh-CN'));
  185. for (const s of sorted) {
  186. const item = document.createElement('button');
  187. item.type = 'button';
  188. item.className = 'scan-dropdown-item';
  189. item.dataset.value = String(s.shopId);
  190. item.setAttribute('role', 'option');
  191. item.innerHTML = '<span class="scan-check"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12.5l4.5 4.5L19 7.5"/></svg></span><span></span>';
  192. item.lastElementChild.textContent = s.shopName;
  193. menu.appendChild(item);
  194. }
  195. }
  196. function renderDropdownSelection(menu, selection, textEl, allLabel) {
  197. menu.querySelectorAll('.scan-dropdown-item').forEach((node) => {
  198. const selected = selection.has(node.dataset.value);
  199. node.classList.toggle('selected', selected);
  200. node.setAttribute('aria-selected', String(selected));
  201. });
  202. const picked = Array.from(selection).filter((v) => v !== '__all__');
  203. textEl.textContent = picked.length ? `已选 ${picked.length} 家门店` : allLabel;
  204. }
  205. function renderShopOptions() {
  206. const entity = activeEntity();
  207. const shops = (entity && entity.shops) || [];
  208. const menus = [
  209. { menu: $('reportShopMenu'), sel: state.shopFilter, text: $('reportShopText'), label: '全部门店' },
  210. { menu: $('syncShopMenu'), sel: state.syncShops, text: $('syncShopText'), label: '选择门店' },
  211. { menu: $('anaShopMenu'), sel: state.analysisShopFilter, text: $('anaShopText'), label: '全部门店' },
  212. ];
  213. for (const m of menus) {
  214. if (!m.menu) continue;
  215. fillShopMenu(m.menu, shops);
  216. renderDropdownSelection(m.menu, m.sel, m.text, m.label);
  217. }
  218. }
  219. function makeDropdownHandler(menu, selection, textEl, allLabel, onChange) {
  220. return (event) => {
  221. const item = event.target.closest('[data-value]');
  222. if (!item) return;
  223. const value = item.dataset.value;
  224. if (value === '__all__') selection.clear();
  225. else if (selection.has(value)) selection.delete(value);
  226. else selection.add(value);
  227. renderDropdownSelection(menu, selection, textEl, allLabel);
  228. if (onChange) onChange();
  229. };
  230. }
  231. // ---------- KPI 卡片(数据采集页) ----------
  232. function renderKpis() {
  233. const wrap = $('reportKpis');
  234. wrap.innerHTML = '';
  235. const s = state.summary || {};
  236. const cards = [
  237. { label: '营业额(元)', value: fmtMoney(s.grossAmt), cls: 'accent' },
  238. { label: '收入(元)', value: fmtMoney(s.incomeAmt), cls: 'ok' },
  239. { label: '有效订单', value: fmtNum(s.validOrderCnt), cls: 'accent' },
  240. { label: '曝光人数', value: fmtNum(s.expUv), cls: '' },
  241. { label: '下单人数', value: fmtNum(s.orderUserCnt), cls: '' },
  242. { label: '进店转化率', value: fmtPct(s.clkExpRate), cls: 'warn', rate: 'clkExpRate' },
  243. { label: '客单价(元)', value: fmtMoney(s.perActualPay), cls: 'ok' },
  244. ];
  245. for (const c of cards) {
  246. const div = document.createElement('div');
  247. div.className = 'metric ' + (c.cls || '');
  248. div.innerHTML = `<span class="metric-body"><span class="metric-label"></span><span class="metric-value ${c.rate ? rateClass(c.rate, s[c.rate]) : ''}"></span></span>`;
  249. div.querySelector('.metric-label').textContent = c.label;
  250. div.querySelector('.metric-value').textContent = c.value;
  251. wrap.appendChild(div);
  252. }
  253. }
  254. // ---------- 报表表格(数据采集页) ----------
  255. function metricColumns() {
  256. return state.columns.filter((c) => c.key !== 'date' && c.key !== 'shopName' && c.key !== 'account' && state.visible.has(c.key));
  257. }
  258. function tableColumns() {
  259. // 全部字段模式(数据中台):固定业务列 + 从首行 raw 发现的全部原始字段(原始 API 字段名)
  260. if (state.rawView) {
  261. const base = [
  262. { key: 'account', label: '账号名', type: 'text' },
  263. { key: 'date', label: '日期', type: 'date' },
  264. { key: 'scope', label: '维度', type: 'text' },
  265. { key: 'shopId', label: '门店ID', type: 'text' },
  266. { key: 'shopName', label: '门店名称', type: 'text' },
  267. ];
  268. const rawCols = [];
  269. const seen = new Set(base.map((c) => c.label));
  270. for (const r of state.rows) {
  271. const raw = r && r.raw;
  272. if (!raw || typeof raw !== 'object') continue;
  273. for (const k of Object.keys(raw)) {
  274. if (seen.has(k)) continue;
  275. seen.add(k);
  276. const sample = raw[k];
  277. const isNum = typeof sample === 'number' || (typeof sample === 'string' && sample !== '' && Number.isFinite(Number(sample)));
  278. rawCols.push({ key: `raw.${k}`, label: k, type: isNum ? 'num' : 'text', raw: true });
  279. }
  280. }
  281. return [...base, ...rawCols];
  282. }
  283. const metricCols = metricColumns();
  284. const accountCol = { key: 'account', label: '账号名', type: 'text' };
  285. if (state.mode === 'shop') return [accountCol, { key: 'shopName', label: '门店名称', type: 'text' }, ...metricCols];
  286. if (state.mode === 'date') return [accountCol, { key: 'date', label: '日期', type: 'date' }, ...metricCols];
  287. return [accountCol, { key: 'date', label: '日期', type: 'date' }, { key: 'shopName', label: '门店名称', type: 'text' }, ...metricCols];
  288. }
  289. // 取单元格值:raw. 前缀深入原始字段对象;对象/数组序列化展示
  290. function cellValue(r, key) {
  291. if (!key.startsWith('raw.')) return r[key];
  292. const raw = r && r.raw;
  293. if (!raw || typeof raw !== 'object') return undefined;
  294. return raw[key.slice(4)];
  295. }
  296. function sortedRows() {
  297. return state.rows.slice().sort((a, b) => {
  298. const av = cellValue(a, state.sortKey), bv = cellValue(b, state.sortKey);
  299. if (av == null || av === '') return 1;
  300. if (bv == null || bv === '') return -1;
  301. if (typeof av === 'number' && typeof bv === 'number') return (av - bv) * (state.sortDir === 'asc' ? 1 : -1);
  302. return String(av).localeCompare(String(bv), 'zh-CN') * (state.sortDir === 'asc' ? 1 : -1);
  303. });
  304. }
  305. function renderTable() {
  306. const cols = tableColumns();
  307. const thead = $('reportTableHead');
  308. const tbody = $('reportTableBody');
  309. $('reportRowCount').textContent = `${state.rows.length} 行`;
  310. const empty = $('reportEmpty');
  311. if (!state.rows.length) {
  312. thead.innerHTML = '';
  313. tbody.innerHTML = '';
  314. empty.hidden = false;
  315. return;
  316. }
  317. empty.hidden = true;
  318. thead.innerHTML = '<tr>' + cols.map((c) => {
  319. const active = state.sortKey === c.key;
  320. const arrow = active ? (state.sortDir === 'asc' ? ' ↑' : ' ↓') : '';
  321. return `<th class="col-${c.type}${['money', 'int', 'pct', 'num'].includes(c.type) ? ' col-num' : ''}" data-key="${c.key}">${c.label}${arrow}</th>`;
  322. }).join('') + '</tr>';
  323. tbody.innerHTML = sortedRows().map((r) => '<tr>' + cols.map((c) => {
  324. const isNum = ['money', 'int', 'pct', 'num'].includes(c.type);
  325. const v = cellValue(r, c.key);
  326. const display = (v != null && typeof v === 'object') ? JSON.stringify(v) : v;
  327. const cls = `col-${c.type}${isNum ? ' col-num' : ''}${c.type === 'pct' ? ' ' + rateClass(c.key, v) : ''}`;
  328. return `<td class="${cls}">${fmtCell(c, display)}</td>`;
  329. }).join('') + '</tr>').join('');
  330. }
  331. // ---------- 数据加载(数据采集页) ----------
  332. async function loadReport() {
  333. const entity = state.entity;
  334. if (!entity) {
  335. state.rows = []; state.summary = null;
  336. renderTable(); renderKpis();
  337. return;
  338. }
  339. if (state.reportAbort) state.reportAbort.abort();
  340. const ctrl = new AbortController();
  341. state.reportAbort = ctrl;
  342. const { from, to } = currentRange();
  343. try {
  344. let url = state.mode === 'detail'
  345. ? `/api/reports/daily?entity=${encodeURIComponent(entity)}&from=${from}&to=${to}${state.rawView ? '' : '&scope=shop'}&page=${state.page}&pageSize=${state.pageSize}`
  346. : `/api/reports/aggregate?entity=${encodeURIComponent(entity)}&from=${from}&to=${to}&group=${state.mode}`;
  347. if (state.shopFilter.size) url += `&shops=${encodeURIComponent(Array.from(state.shopFilter).join(','))}`;
  348. if (state.q) url += `&q=${encodeURIComponent(state.q)}`;
  349. const data = await jsonFetch(url, { signal: ctrl.signal });
  350. if (state.entity !== entity) return;
  351. state.rows = data.rows || [];
  352. state.summary = data.summary || null;
  353. state.total = state.mode === 'detail' ? (data.total ?? state.rows.length) : state.rows.length;
  354. state.pages = state.mode === 'detail' ? (data.pages ?? 1) : 1;
  355. renderKpis();
  356. renderTable();
  357. renderPager();
  358. loadTrend();
  359. } catch (e) {
  360. if (e.name === 'AbortError') return;
  361. showToast('报表加载失败:' + e.message, 'error');
  362. }
  363. }
  364. // 筛选/主体/视图等变化:回到第一页再加载
  365. function reloadReport() {
  366. state.page = 1;
  367. loadReport();
  368. }
  369. // 分页条:明细模式服务端分页(排序作用于当前页);聚合模式行数少不分页
  370. function renderPager() {
  371. const el = $('reportPager');
  372. if (!el) return;
  373. if (state.mode !== 'detail' || state.pages <= 1) {
  374. el.innerHTML = state.mode === 'detail' ? `<span class="pager-info">共 ${state.total} 行</span>` : '';
  375. return;
  376. }
  377. const from = (state.page - 1) * state.pageSize + 1;
  378. const to = Math.min(state.total, state.page * state.pageSize);
  379. const btn = (label, target, disabled) =>
  380. `<button type="button" class="pager-btn" data-page="${target}" ${disabled ? 'disabled' : ''}>${label}</button>`;
  381. el.innerHTML = `
  382. ${btn('‹ 上一页', state.page - 1, state.page <= 1)}
  383. <span class="pager-info">第 ${state.page} / ${state.pages} 页 · ${from}-${to} 行 · 共 ${state.total} 行</span>
  384. ${btn('下一页 ›', state.page + 1, state.page >= state.pages)}
  385. <span class="pager-info pager-note">列排序作用于当前页</span>
  386. `;
  387. }
  388. function changePage(page) {
  389. if (page < 1 || page > state.pages || page === state.page) return;
  390. state.page = page;
  391. loadReport();
  392. const wrap = $('reportTableWrap');
  393. if (wrap && wrap.scrollIntoView) wrap.scrollIntoView({ block: 'nearest' });
  394. }
  395. // ---------- 连接状态 ----------
  396. async function refreshConn() {
  397. const badge = $('reportConnBadge');
  398. try {
  399. const data = await jsonFetch('/api/reports/status');
  400. state.conn = data.napos || null;
  401. state.entities = data.entities || [];
  402. if (!state.entity || !state.entities.some((e) => e.key === state.entity)) {
  403. const saved = LS.get('shanReports.entity', null);
  404. state.entity = (saved && state.entities.some((e) => e.key === saved)) ? saved : (state.entities[0] ? state.entities[0].key : null);
  405. }
  406. renderEntityTabs();
  407. renderShopOptions();
  408. const ok = state.conn && state.conn.connected;
  409. badge.textContent = ok ? '客户端已连接' : '客户端未连接';
  410. badge.className = 'badge ' + (ok ? 'badge-ok' : 'badge-fail');
  411. badge.title = ok
  412. ? `调试端口 ${state.conn.port}`
  413. : [state.conn && state.conn.error, state.conn && state.conn.hint].filter(Boolean).join('\n') || '未检测到调试端口';
  414. } catch {
  415. badge.textContent = '状态检测失败';
  416. badge.className = 'badge badge-fail';
  417. }
  418. }
  419. // ---------- 列设置 ----------
  420. function loadColumnPrefs() {
  421. // 默认只展示原始/主指标列(营业时长、异常关店时长、商品销售额为预留列,数据源接入后自动回填);
  422. // 下单转化率、客单价、支出、活动订单、活动补贴、推广ROI、30日复购率等派生指标默认隐藏,可在列设置打开。
  423. const DEFAULT_VISIBLE_COLS = new Set([
  424. 'bizHours', 'abnormalCloseHours', 'validOrderCnt', 'incomeAmt', 'grossAmt',
  425. 'goodsSaleAmt', 'expUv', 'orderUserCnt', 'clkExpRate',
  426. ]);
  427. const saved = LS.get('shanReports.columns.v2', null);
  428. const defaults = new Set(state.columns.filter((c) => DEFAULT_VISIBLE_COLS.has(c.key)).map((c) => c.key));
  429. if (Array.isArray(saved)) {
  430. const valid = new Set(state.columns.map((c) => c.key));
  431. state.visible = new Set(saved.filter((k) => valid.has(k)));
  432. } else {
  433. state.visible = defaults;
  434. }
  435. if (!state.visible.size) state.visible = defaults;
  436. }
  437. function renderColumnCfg() {
  438. const list = $('columnCfgList');
  439. list.innerHTML = '';
  440. for (const c of state.columns) {
  441. if (c.locked) continue;
  442. const label = document.createElement('label');
  443. label.className = 'colcfg-item';
  444. const checked = state.visible.has(c.key) ? 'checked' : '';
  445. label.innerHTML = `<input type="checkbox" value="${c.key}" ${checked}><span></span>${c.reserved ? '<em class="colcfg-reserved">预留</em>' : ''}`;
  446. label.querySelector('span').textContent = c.label;
  447. list.appendChild(label);
  448. }
  449. }
  450. function applyColumnCfg() {
  451. const picks = new Set();
  452. $('columnCfgList').querySelectorAll('input[type=checkbox]').forEach((cb) => {
  453. if (cb.checked) picks.add(cb.value);
  454. });
  455. state.visible = picks;
  456. LS.set('shanReports.columns.v2', Array.from(picks));
  457. $('modalReportColumns').hidden = true;
  458. renderTable();
  459. }
  460. // ---------- 同步 ----------
  461. function renderSyncProgress(st) {
  462. const pct = st.planTotal ? Math.round((st.done / st.planTotal) * 100) : 0;
  463. $('syncProgressBar').style.width = pct + '%';
  464. $('syncProgressText').textContent = `${st.done} / ${st.planTotal}`;
  465. $('syncStatAdded').textContent = `新增 ${st.added}`;
  466. $('syncStatUpdated').textContent = `更新 ${st.updated}`;
  467. $('syncStatFailed').textContent = `失败 ${st.failed}`;
  468. const steps = (st.steps || []).slice(-8);
  469. $('syncSteps').innerHTML = steps.map((s) => {
  470. const cls = s.ok ? 'ok' : 'fail';
  471. const detail = s.ok
  472. ? `+${s.added}/~${s.updated}` + (s.rows != null ? ` · ${s.rows}行` : '') + (s.nonZero === 0 && s.rows > 0 ? ' · ⚠全零' : '')
  473. : (s.error || '失败').slice(0, 60);
  474. return `<div class="sync-step ${cls}"><span></span><em>${detail}</em></div>`;
  475. }).join('');
  476. const stepNames = $('syncSteps').querySelectorAll('.sync-step span');
  477. steps.forEach((s, i) => { stepNames[i].textContent = s.label; });
  478. $('btnSyncCancel').hidden = !st.running;
  479. $('btnStartSync').disabled = !!st.running;
  480. $('btnStartSync').textContent = st.running ? '同步中…' : '开始同步';
  481. }
  482. function pollSyncStatus() {
  483. if (state.syncPollTimer) clearInterval(state.syncPollTimer);
  484. state.syncPollTimer = setInterval(async () => {
  485. try {
  486. const st = await jsonFetch('/api/reports/sync/status');
  487. renderSyncProgress(st);
  488. if (!st.running) {
  489. clearInterval(state.syncPollTimer);
  490. state.syncPollTimer = null;
  491. if (st.error) showToast('同步出错:' + st.error, 'error');
  492. else showToast(st.cancelled ? '同步已取消' : `同步完成:新增 ${st.added},更新 ${st.updated}`);
  493. refreshConn().then(loadReport);
  494. }
  495. } catch { /* 轮询失败忽略 */ }
  496. }, 900);
  497. }
  498. async function loadAutoSyncPrefs() {
  499. try {
  500. const s = await jsonFetch('/api/settings');
  501. $('autoSyncEnabled').checked = !!s.autoSyncEnabled;
  502. if (s.autoSyncTime) $('autoSyncTime').value = s.autoSyncTime;
  503. } catch { /* 设置读取失败时保留默认值 */ }
  504. }
  505. async function saveAutoSyncPrefs() {
  506. try {
  507. await jsonFetch('/api/settings', {
  508. method: 'POST',
  509. headers: { 'Content-Type': 'application/json' },
  510. body: JSON.stringify({ autoSyncEnabled: $('autoSyncEnabled').checked, autoSyncTime: $('autoSyncTime').value }),
  511. });
  512. showToast('自动同步设置已保存');
  513. } catch (e) {
  514. showToast('自动同步设置保存失败:' + e.message, 'error');
  515. }
  516. }
  517. async function openSyncModal() {
  518. $('modalReportSync').hidden = false;
  519. $('syncEntityBadge').textContent = '识别主体中…';
  520. $('syncEntityBadge').className = 'badge badge-info';
  521. $('syncShopPickWrap').hidden = true;
  522. $('syncProgressWrap').hidden = true;
  523. loadAutoSyncPrefs();
  524. try {
  525. const tree = await jsonFetch('/api/reports/tree');
  526. const badge = $('syncEntityBadge');
  527. badge.textContent = `当前主体:${(tree.entity && tree.entity.name) || (tree.merchant && tree.merchant.name) || '未知'} · 门店 ${(tree.shops || []).length} 家`;
  528. badge.className = 'badge badge-ok';
  529. if (tree.entity && tree.entity.key && tree.entity.key !== state.entity) {
  530. state.entity = tree.entity.key;
  531. LS.set('shanReports.entity', tree.entity.key);
  532. }
  533. await refreshConn();
  534. renderSyncShopOptions(tree.shops || []);
  535. } catch (e) {
  536. const badge = $('syncEntityBadge');
  537. badge.textContent = '未连接客户端:' + e.message;
  538. badge.className = 'badge badge-fail';
  539. try {
  540. const st = await jsonFetch('/api/reports/status');
  541. const napos = st.napos || {};
  542. $('syncHint').textContent = [napos.hint, napos.selfCheckUrl ? `自检:客户端带参启动后,用浏览器打开 ${napos.selfCheckUrl} 应看到一段 JSON。` : '']
  543. .filter(Boolean).join(' ');
  544. } catch { /* 服务不可达时保留默认文案 */ }
  545. }
  546. }
  547. function renderSyncShopOptions(shops) {
  548. state.syncShops.clear();
  549. fillShopMenu($('syncShopMenu'), shops);
  550. renderDropdownSelection($('syncShopMenu'), state.syncShops, $('syncShopText'), '选择门店');
  551. }
  552. async function startSync() {
  553. const scope = $('syncScope').value;
  554. const days = Number($('syncRange').value) || 30;
  555. const body = { from: daysAgoYmd(days), to: daysAgoYmd(1), scope: scope === 'custom' ? 'shop' : scope };
  556. if (scope === 'custom') {
  557. const shops = Array.from(state.syncShops).filter((v) => v !== '__all__');
  558. if (!shops.length) { showToast('请先选择要同步的门店', 'error'); return; }
  559. body.shopIds = shops;
  560. }
  561. try {
  562. await jsonFetch('/api/reports/sync', {
  563. method: 'POST',
  564. headers: { 'Content-Type': 'application/json' },
  565. body: JSON.stringify(body),
  566. });
  567. $('syncProgressWrap').hidden = false;
  568. renderSyncProgress({ planTotal: 0, done: 0, added: 0, updated: 0, failed: 0, steps: [], running: true });
  569. pollSyncStatus();
  570. } catch (e) {
  571. showToast('同步启动失败:' + e.message, 'error');
  572. }
  573. }
  574. // ---------- 导出 ----------
  575. function exportCsv() {
  576. if (!state.entity) { showToast('暂无主体可导出', 'error'); return; }
  577. // 全部字段模式:行数据只在客户端(raw 列由前端发现),就地生成 CSV
  578. if (state.rawView) {
  579. const cols = tableColumns();
  580. const cell = (v) => {
  581. const s = (v == null || typeof v !== 'object') ? String(v ?? '') : JSON.stringify(v);
  582. return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
  583. };
  584. const lines = [cols.map((c) => cell(c.label)).join(',')];
  585. for (const r of sortedRows()) lines.push(cols.map((c) => cell(cellValue(r, c.key))).join(','));
  586. const blob = new Blob(['\ufeff' + lines.join('\n')], { type: 'text/csv;charset=utf-8' });
  587. const a = document.createElement('a');
  588. a.href = URL.createObjectURL(blob);
  589. a.download = `湖明细-全部字段-${state.entity}.csv`;
  590. a.click();
  591. URL.revokeObjectURL(a.href);
  592. return;
  593. }
  594. const { from, to } = currentRange();
  595. let url = `/api/reports/export?entity=${encodeURIComponent(state.entity)}&from=${from}&to=${to}`;
  596. if (state.mode !== 'detail') url += `&group=${state.mode}`;
  597. if (state.shopFilter.size) url += `&shops=${encodeURIComponent(Array.from(state.shopFilter).join(','))}`;
  598. if (state.q) url += `&q=${encodeURIComponent(state.q)}`;
  599. window.location.href = url;
  600. }
  601. function exportHtml() {
  602. if (!state.entity) { showToast('暂无主体可导出', 'error'); return; }
  603. const { from, to } = analysisRange();
  604. window.open(`/api/reports/report-html?entity=${encodeURIComponent(state.entity)}&from=${from}&to=${to}`, '_blank');
  605. }
  606. // ---------- 趋势图表 ----------
  607. function chartCol(key) {
  608. return state.columns.find((c) => c.key === key) || { key, label: key, type: 'num' };
  609. }
  610. function ensureChart(instanceKey, domId) {
  611. if (typeof echarts === 'undefined') return null;
  612. const dom = $(domId);
  613. if (!dom) return null;
  614. if (!chartInstances[instanceKey]) chartInstances[instanceKey] = echarts.init(dom);
  615. return chartInstances[instanceKey];
  616. }
  617. function metricColumnOptions() {
  618. return state.columns.filter((c) => ['int', 'money', 'pct', 'num'].includes(c.type) && !c.reserved);
  619. }
  620. function renderChartMetricSelect() {
  621. const sel = $('chartMetric');
  622. if (!sel) return;
  623. sel.innerHTML = '';
  624. for (const c of metricColumnOptions()) {
  625. const opt = document.createElement('option');
  626. opt.value = c.key;
  627. opt.textContent = c.label;
  628. if (c.key === chartMetric) opt.selected = true;
  629. sel.appendChild(opt);
  630. }
  631. if (!sel.value && sel.options.length) sel.value = sel.options[0].value;
  632. chartMetric = sel.value || 'grossAmt';
  633. }
  634. const AXIS_TXT = { axisLabel: { color: '#6b6560' }, axisLine: { lineStyle: { color: '#e8e4df' } } };
  635. const SPLIT_LINE = { lineStyle: { color: '#f0ede8' } };
  636. const ACCENT = '#ff6b35';
  637. async function ensureAnalysisData() {
  638. const { from, to } = analysisRange();
  639. const shopSuffix = state.analysisShopFilter.size
  640. ? `&shops=${encodeURIComponent(Array.from(state.analysisShopFilter).join(','))}`
  641. : '';
  642. const key = [state.entity, from, to, state.analysisShopFilter.size ? [...state.analysisShopFilter].sort().join(',') : ''].join('|');
  643. if (anaCache && anaCache.key === key) return anaCache;
  644. const fd = (s) => new Date(Number(String(s).slice(0, 4)), Number(String(s).slice(4, 6)) - 1, Number(String(s).slice(6, 8)));
  645. const spanDays = Math.max(1, Math.round((fd(to) - fd(from)) / 86400000) + 1);
  646. const prevToD = fd(from);
  647. prevToD.setDate(prevToD.getDate() - 1);
  648. const prevTo = ymdLocal(prevToD);
  649. const prevFromD = new Date(prevToD);
  650. prevFromD.setDate(prevFromD.getDate() - (spanDays - 1));
  651. const prevFrom = ymdLocal(prevFromD);
  652. const base = `/api/reports/aggregate?entity=${encodeURIComponent(state.entity)}`;
  653. const [byDate, byDatePrev, byShop, topDaily] = await Promise.all([
  654. jsonFetch(`${base}&from=${from}&to=${to}&group=date${shopSuffix}`).then((d) => d.rows || []),
  655. jsonFetch(`${base}&from=${prevFrom}&to=${prevTo}&group=date${shopSuffix}`).then((d) => d.rows || []),
  656. jsonFetch(`${base}&from=${from}&to=${to}&group=shop${shopSuffix}`).then((d) => d.rows || []),
  657. jsonFetch(`/api/reports/daily?entity=${encodeURIComponent(state.entity)}&from=${from}&to=${to}&scope=shop${shopSuffix}`).then((d) => d.rows || []),
  658. ]);
  659. anaCache = { key, from, to, prevFrom, prevTo, byDate, byDatePrev, byShop, topDaily };
  660. return anaCache;
  661. }
  662. function renderDeltas(data) {
  663. const wrap = $('analysisDeltas');
  664. if (!wrap) return;
  665. wrap.innerHTML = '';
  666. const sum = (rows, f) => rows.reduce((a, r) => a + (Number(r[f]) || 0), 0);
  667. const wAvg = (rows, f, wb) => {
  668. let num = 0, den = 0;
  669. for (const r of rows) { const wt = Number(r[wb]) || 0; num += (Number(r[f]) || 0) * wt; den += wt; }
  670. return den > 0 ? num / den : 0;
  671. };
  672. const curOrders = sum(data.byDate, 'validOrderCnt');
  673. const prevOrders = sum(data.byDatePrev, 'validOrderCnt');
  674. const items = [
  675. { label: '营业额', cur: sum(data.byDate, 'grossAmt'), prev: sum(data.byDatePrev, 'grossAmt'), fmt: fmtMoney },
  676. { label: '有效订单', cur: curOrders, prev: prevOrders, fmt: fmtNum },
  677. { label: '收入', cur: sum(data.byDate, 'incomeAmt'), prev: sum(data.byDatePrev, 'incomeAmt'), fmt: fmtMoney },
  678. { label: '曝光人数', cur: sum(data.byDate, 'expUv'), prev: sum(data.byDatePrev, 'expUv'), fmt: fmtNum },
  679. { label: '下单人数', cur: sum(data.byDate, 'orderUserCnt'), prev: sum(data.byDatePrev, 'orderUserCnt'), fmt: fmtNum },
  680. { label: '进店转化率', cur: wAvg(data.byDate, 'clkExpRate', 'expUv'), prev: wAvg(data.byDatePrev, 'clkExpRate', 'expUv'), fmt: fmtPct },
  681. { label: '客单价', cur: curOrders > 0 ? sum(data.byDate, 'grossAmt') / curOrders : 0, prev: prevOrders > 0 ? sum(data.byDatePrev, 'grossAmt') / prevOrders : 0, fmt: fmtMoney },
  682. ];
  683. for (const it of items) {
  684. const cur = Math.round(it.cur * 100) / 100;
  685. const div = document.createElement('div');
  686. div.className = 'delta-card';
  687. let deltaHtml;
  688. const delta = it.prev > 0 ? (it.cur - it.prev) / it.prev : null;
  689. if (delta == null || !Number.isFinite(delta)) deltaHtml = '<span class="delta-none">上期无数据</span>';
  690. else if (Math.abs(delta) < 0.0001) deltaHtml = '<span class="delta-flat">持平</span>';
  691. else {
  692. const up = delta > 0;
  693. deltaHtml = `<span class="delta ${up ? 'up' : 'down'}">${up ? '↑' : '↓'} ${Math.abs(delta * 100).toFixed(1)}%</span>`
  694. + `<span class="delta-sub">vs 上期 ${it.fmt(Math.round(it.prev * 100) / 100)}</span>`;
  695. }
  696. div.innerHTML = `<span class="delta-label"></span><span class="delta-value"></span><span class="delta-line">${deltaHtml}</span>`;
  697. div.querySelector('.delta-label').textContent = it.label;
  698. div.querySelector('.delta-value').textContent = it.fmt(cur);
  699. wrap.appendChild(div);
  700. }
  701. }
  702. async function renderCharts() {
  703. let data;
  704. try { data = await ensureAnalysisData(); } catch { return; }
  705. renderDeltas(data);
  706. const col = chartCol(chartMetric);
  707. const compareOn = $('anaComparePrev') && $('anaComparePrev').checked;
  708. const trend = ensureChart('trend', 'chartTrend');
  709. if (trend) {
  710. const cur = data.byDate.slice().sort((a, b) => (a.date < b.date ? -1 : 1));
  711. const prev = data.byDatePrev.slice().sort((a, b) => (a.date < b.date ? -1 : 1));
  712. const xData = cur.map((r) => ymdToDash(r.date));
  713. const series = [{
  714. name: `本期·${col.label}`, type: 'line', smooth: true, symbolSize: 5,
  715. data: cur.map((r) => Number(r[chartMetric]) || 0),
  716. itemStyle: { color: ACCENT }, lineStyle: { width: 2.5 },
  717. areaStyle: { color: 'rgba(255,107,53,.08)' },
  718. }];
  719. if (compareOn && prev.length) {
  720. series.push({
  721. name: '上期同期', type: 'line', smooth: true,
  722. data: xData.map((_, i) => (prev[i] ? Number(prev[i][chartMetric]) || 0 : 0)),
  723. itemStyle: { color: '#a5a09a' }, lineStyle: { type: 'dashed', width: 1.6 }, symbol: 'none',
  724. });
  725. }
  726. trend.setOption({
  727. tooltip: { trigger: 'axis', valueFormatter: (v) => fmtByCol(col, v) },
  728. legend: { data: series.map((x) => x.name), top: 0, icon: 'roundRect', itemWidth: 14, itemHeight: 4, textStyle: { color: '#6b6560' } },
  729. grid: { left: 64, right: 24, top: 36, bottom: 30 },
  730. xAxis: { type: 'category', boundaryGap: false, data: xData, ...AXIS_TXT },
  731. yAxis: { type: 'value', axisLabel: { color: '#6b6560' }, splitLine: SPLIT_LINE },
  732. series,
  733. }, true);
  734. const title = $('anaTrendTitle');
  735. if (title) title.textContent = `主指标趋势 · ${col.label}(${ymdToDash(data.from)} ~ ${ymdToDash(data.to)})`;
  736. }
  737. const rank = ensureChart('rank', 'chartRank');
  738. if (rank) {
  739. const top = data.byShop.slice()
  740. .sort((a, b) => (Number(b[chartMetric]) || 0) - (Number(a[chartMetric]) || 0))
  741. .slice(0, 10).reverse();
  742. rank.setOption({
  743. tooltip: { trigger: 'axis', valueFormatter: (v) => fmtByCol(col, v) },
  744. grid: { left: 10, right: 34, top: 10, bottom: 24, containLabel: true },
  745. xAxis: { type: 'value', axisLabel: { color: '#6b6560' }, splitLine: SPLIT_LINE },
  746. yAxis: {
  747. type: 'category', data: top.map((r) => r.shopName || r.shopId),
  748. axisLabel: { color: '#2b2a28', width: 130, overflow: 'truncate' },
  749. axisLine: { lineStyle: { color: '#e8e4df' } },
  750. },
  751. series: [{ type: 'bar', barMaxWidth: 18, data: top.map((r) => Number(r[chartMetric]) || 0), itemStyle: { color: ACCENT, borderRadius: [0, 6, 6, 0] } }],
  752. }, true);
  753. }
  754. const funnel = ensureChart('funnel', 'chartFunnel');
  755. if (funnel) {
  756. const sum = (f) => data.byDate.reduce((a, r) => a + (Number(r[f]) || 0), 0);
  757. const expUv = sum('expUv');
  758. const enter = data.byDate.reduce((a, r) => a + (Number(r.expUv) || 0) * (Number(r.clkExpRate) || 0), 0);
  759. const order = sum('orderUserCnt');
  760. funnel.setOption({
  761. tooltip: { trigger: 'item', formatter: (p) => `${p.name}:${fmtNum(Math.round(p.value))} 人` },
  762. series: [{
  763. type: 'funnel', left: '8%', width: '84%', top: 12, bottom: 8, minSize: '20%',
  764. label: { color: '#fff', fontWeight: 600, formatter: (p) => `${p.name} ${fmtNum(Math.round(p.value))}` },
  765. data: [
  766. { name: '曝光人数', value: Math.round(expUv), itemStyle: { color: '#ffb199' } },
  767. { name: '进店人数', value: Math.round(enter), itemStyle: { color: '#ff8a5c' } },
  768. { name: '下单人数', value: Math.round(order), itemStyle: { color: ACCENT } },
  769. ],
  770. }],
  771. }, true);
  772. }
  773. const compare = ensureChart('compare', 'chartCompare');
  774. if (compare) {
  775. const top5 = data.byShop.slice()
  776. .sort((a, b) => (Number(b[chartMetric]) || 0) - (Number(a[chartMetric]) || 0))
  777. .slice(0, 5);
  778. const dates = [...new Set(data.topDaily.map((r) => r.date))].sort();
  779. const palette = ['#ff6b35', '#2563eb', '#1a8a4c', '#b8860b', '#8b5cf6'];
  780. const series = top5.map((shop, i) => ({
  781. name: shop.shopName || shop.shopId,
  782. type: 'line', smooth: true, symbolSize: 4,
  783. data: dates.map((d) => {
  784. const r = data.topDaily.find((x) => x.date === d && String(x.shopId) === String(shop.shopId));
  785. return r ? (Number(r[chartMetric]) || 0) : 0;
  786. }),
  787. itemStyle: { color: palette[i % palette.length] }, lineStyle: { width: 2 },
  788. }));
  789. compare.setOption({
  790. tooltip: { trigger: 'axis', valueFormatter: (v) => fmtByCol(col, v) },
  791. legend: { top: 0, type: 'scroll', icon: 'roundRect', itemWidth: 14, itemHeight: 4, textStyle: { color: '#6b6560' } },
  792. grid: { left: 64, right: 24, top: 36, bottom: 30 },
  793. xAxis: { type: 'category', boundaryGap: false, data: dates.map(ymdToDash), ...AXIS_TXT },
  794. yAxis: { type: 'value', axisLabel: { color: '#6b6560' }, splitLine: SPLIT_LINE },
  795. series,
  796. }, true);
  797. const title = $('anaCompareTitle');
  798. if (title) title.textContent = `门店对比 · Top ${top5.length}(${col.label})`;
  799. }
  800. }
  801. // ---------- 智能问数 · 机器人(仅经营分析页面) ----------
  802. // 对话历史按主体持久化到 localStorage,刷新/重开后可继续追问
  803. const CHAT_LS_KEY = 'shanReports.chat.v1';
  804. const chatStoreKey = () => state.entity || '_';
  805. function loadChatForEntity() {
  806. const all = LS.get(CHAT_LS_KEY, {});
  807. state.chat.messages = Array.isArray(all[chatStoreKey()]) ? all[chatStoreKey()] : [];
  808. if (state.chat.open) renderChatMessages();
  809. }
  810. function saveChatForEntity() {
  811. const key = chatStoreKey();
  812. const all = LS.get(CHAT_LS_KEY, {});
  813. const trimmed = state.chat.messages.filter((m) => !m.pending).slice(-20);
  814. const attempt = (payload) => {
  815. try { localStorage.setItem(CHAT_LS_KEY, JSON.stringify(payload)); return true; } catch { return false; }
  816. };
  817. if (attempt({ ...all, [key]: trimmed })) return;
  818. // 图表行数据可能撑爆配额 → 退化为只存文字与图表配置
  819. const slim = { ...all, [key]: trimmed.map((m) => ({ ...m, rows: undefined })) };
  820. if (!(attempt(slim) || attempt({ [key]: slim[key].slice(-10) }))) { /* 配额不足则放弃持久化 */ }
  821. }
  822. function chatVisibleFor(view) { return view === 'reports' || view === 'analysis'; }
  823. function setChatOpen(open) {
  824. state.chat.open = open;
  825. $('chatbotPanel').hidden = !open;
  826. $('chatbotFab').classList.toggle('active', open);
  827. if (open) {
  828. loadChatForEntity();
  829. $('chatbotFab').hidden = false;
  830. setTimeout(() => $('chatbotInput').focus(), 60);
  831. scrollChatBottom();
  832. }
  833. }
  834. function scrollChatBottom() {
  835. const body = $('chatbotBody');
  836. body.scrollTop = body.scrollHeight;
  837. }
  838. function renderChatMessages() {
  839. const body = $('chatbotBody');
  840. [...body.querySelectorAll('.chatbot-msg:not(.static)')].forEach((n) => n.remove());
  841. body.querySelectorAll('.chatbot-chips').forEach((n) => { n.hidden = state.chat.messages.length > 0; });
  842. for (let i = 0; i < state.chat.messages.length; i++) {
  843. const m = state.chat.messages[i];
  844. const div = document.createElement('div');
  845. div.className = 'chatbot-msg ' + (m.role === 'user' ? 'user' : 'bot');
  846. if (m.pending) {
  847. div.innerHTML = '<div class="chatbot-bubble typing"><span></span><span></span><span></span></div>';
  848. } else {
  849. const bubble = document.createElement('div');
  850. bubble.className = 'chatbot-bubble';
  851. bubble.textContent = m.text || '';
  852. div.appendChild(bubble);
  853. if (m.chart && m.chart.type !== 'none' && m.rows && m.rows.length) {
  854. const chartWrap = document.createElement('div');
  855. chartWrap.className = 'chatbot-chart';
  856. chartWrap.dataset.idx = String(i);
  857. div.appendChild(chartWrap);
  858. const actions = document.createElement('div');
  859. actions.className = 'chatbot-msg-actions';
  860. const applyBtn = document.createElement('button');
  861. applyBtn.type = 'button';
  862. applyBtn.className = 'btn btn-ghost btn-small';
  863. applyBtn.textContent = '应用到报表';
  864. applyBtn.addEventListener('click', () => applyMsgQuery(i));
  865. actions.appendChild(applyBtn);
  866. div.appendChild(actions);
  867. }
  868. }
  869. body.appendChild(div);
  870. }
  871. scrollChatBottom();
  872. // 渲染消息内图表
  873. state.chat.messages.forEach((m, i) => {
  874. if (m.pending || !m.chart || m.chart.type === 'none' || !m.rows || !m.rows.length) return;
  875. const wrap = body.querySelector(`.chatbot-chart[data-idx="${i}"]`);
  876. if (!wrap) return;
  877. const col = (key) => (state.columns.find((c) => c.key === key) || { label: key, type: 'num' });
  878. const isDate = m.chart.x === 'date';
  879. const rows = m.rows.slice();
  880. if (isDate) rows.sort((a, b) => (String(a.date) < String(b.date) ? -1 : 1));
  881. const chart = echarts.init(wrap);
  882. chart.setOption({
  883. tooltip: { trigger: 'axis' },
  884. grid: { left: 56, right: 16, top: 20, bottom: m.chart.type === 'bar' && !isDate ? 52 : 24 },
  885. xAxis: {
  886. type: 'category',
  887. data: rows.map((r) => (isDate ? ymdToDash(r.date) : (r.shopName || r.shopId))),
  888. axisLabel: { color: '#6b6560', interval: 0, rotate: m.chart.type === 'bar' && !isDate ? 30 : 0, width: 80, overflow: 'truncate' },
  889. axisLine: { lineStyle: { color: '#e8e4df' } },
  890. },
  891. yAxis: { type: 'value', axisLabel: { color: '#6b6560' }, splitLine: { lineStyle: { color: '#f0ede8' } } },
  892. series: (m.chart.y || []).map((key, yi) => {
  893. const c = col(key);
  894. return {
  895. name: c.label || key,
  896. type: m.chart.type === 'line' ? 'line' : 'bar',
  897. smooth: true, barMaxWidth: 26,
  898. data: rows.map((r) => {
  899. const v = r[key];
  900. if (v == null || v === '') return 0;
  901. const n = Number(v);
  902. return c.type === 'pct' ? +(n * 100).toFixed(2) : n;
  903. }),
  904. itemStyle: { color: yi === 0 ? '#ff6b35' : '#2563eb' },
  905. };
  906. }),
  907. });
  908. setTimeout(() => chart.resize(), 40);
  909. });
  910. }
  911. function applyMsgQuery(idx) {
  912. const m = state.chat.messages[idx];
  913. const a = m && m.applied;
  914. if (!a) return;
  915. state.mode = ['detail', 'shop', 'date'].includes(a.mode) ? a.mode : 'shop';
  916. $('reportViewModes').querySelectorAll('button').forEach((b) => b.classList.toggle('active', b.dataset.mode === state.mode));
  917. state.preset = 'custom';
  918. $('reportRangePreset').value = 'custom';
  919. $('reportCustomRange').hidden = false;
  920. $('reportFromDate').value = ymdToDash(a.from);
  921. $('reportToDate').value = ymdToDash(a.to);
  922. state.shopFilter = new Set((a.shopIds || []).map(String));
  923. renderShopOptions();
  924. state.page = 1;
  925. loadReport();
  926. // 明细浏览在数据中台页:先切到明细 tab,再导航过去
  927. if (window.shanLakeShowDetail) window.shanLakeShowDetail();
  928. const nav = document.querySelector('.nav-item[data-view="lake"]');
  929. if (nav) nav.click();
  930. }
  931. async function sendChat(text) {
  932. const q = String(text || '').trim();
  933. if (!q || state.chat.busy) return;
  934. state.chat.busy = true;
  935. state.chat.messages.push({ role: 'user', text: q });
  936. state.chat.messages.push({ role: 'assistant', pending: true });
  937. renderChatMessages();
  938. $('chatbotInput').value = '';
  939. try {
  940. const history = state.chat.messages
  941. .filter((m) => !m.pending && (m.role === 'user' || (m.role === 'assistant' && m.text)))
  942. .slice(0, -1)
  943. .slice(-8)
  944. .map((m) => ({ role: m.role, content: m.role === 'assistant' ? `${m.text}${m.applied ? `(已查询:mode=${m.applied.mode} ${m.applied.from}~${m.applied.to}${m.applied.shopIds && m.applied.shopIds.length ? ' 门店 ' + m.applied.shopIds.join(',') : ''})` : ''}` : m.text }));
  945. const result = await jsonFetch('/api/reports/ask', {
  946. method: 'POST',
  947. headers: { 'Content-Type': 'application/json' },
  948. body: JSON.stringify({ entity: state.entity, q, history }),
  949. });
  950. const pendingIdx = state.chat.messages.findIndex((m) => m.pending);
  951. const msg = {
  952. role: 'assistant',
  953. text: result.reply || '(模型未给出文字回答)',
  954. chart: result.chart,
  955. rows: result.rows,
  956. applied: result.applied,
  957. chartTitle: result.chartTitle,
  958. };
  959. if (pendingIdx >= 0) state.chat.messages.splice(pendingIdx, 1, msg);
  960. else state.chat.messages.push(msg);
  961. saveChatForEntity();
  962. } catch (e) {
  963. const pendingIdx = state.chat.messages.findIndex((m) => m.pending);
  964. const errMsg = { role: 'assistant', text: '出错了:' + e.message, error: true };
  965. if (pendingIdx >= 0) state.chat.messages.splice(pendingIdx, 1, errMsg);
  966. else state.chat.messages.push(errMsg);
  967. } finally {
  968. state.chat.busy = false;
  969. renderChatMessages();
  970. }
  971. }
  972. // ---------- 事件绑定 ----------
  973. function bindEvents() {
  974. $('btnReportRefresh').addEventListener('click', async () => {
  975. await refreshConn();
  976. await loadReport();
  977. showToast('已刷新');
  978. });
  979. $('btnClientHelp').addEventListener('click', (event) => {
  980. event.stopPropagation();
  981. const pop = $('clientHelpPopover');
  982. pop.hidden = !pop.hidden;
  983. $('btnClientHelp').classList.toggle('active', !pop.hidden);
  984. $('btnClientHelp').setAttribute('aria-expanded', String(!pop.hidden));
  985. });
  986. document.addEventListener('click', (event) => {
  987. const pop = $('clientHelpPopover');
  988. if (!pop.hidden && !event.target.closest('.conn-help-wrap')) {
  989. pop.hidden = true;
  990. $('btnClientHelp').classList.remove('active');
  991. $('btnClientHelp').setAttribute('aria-expanded', 'false');
  992. }
  993. });
  994. $('btnOpenSync').addEventListener('click', openSyncModal);
  995. $('btnCloseSync').addEventListener('click', () => {
  996. $('modalReportSync').hidden = true;
  997. if (state.syncPollTimer) { clearInterval(state.syncPollTimer); state.syncPollTimer = null; }
  998. $('syncProgressWrap').hidden = true;
  999. });
  1000. $('btnCancelSync').addEventListener('click', () => $('modalReportSync').hidden = true);
  1001. $('btnStartSync').addEventListener('click', startSync);
  1002. $('btnSyncCancel').addEventListener('click', async () => {
  1003. try { await jsonFetch('/api/reports/sync/cancel', { method: 'POST' }); showToast('已请求取消,等待当前步骤结束…'); } catch { /* ignore */ }
  1004. });
  1005. $('syncScope').addEventListener('change', () => {
  1006. $('syncShopPickWrap').hidden = $('syncScope').value !== 'custom';
  1007. });
  1008. $('autoSyncEnabled').addEventListener('change', saveAutoSyncPrefs);
  1009. $('autoSyncTime').addEventListener('change', saveAutoSyncPrefs);
  1010. $('syncShopTrigger').addEventListener('click', () => toggleDropdown('syncShopMenu', 'syncShopTrigger'));
  1011. $('syncShopMenu').addEventListener('click', makeDropdownHandler($('syncShopMenu'), state.syncShops, $('syncShopText'), '选择门店'));
  1012. document.addEventListener('click', (event) => {
  1013. if (!$('syncShopDropdown').contains(event.target)) toggleDropdown('syncShopMenu', 'syncShopTrigger', false);
  1014. });
  1015. $('reportRangePreset').addEventListener('change', () => {
  1016. state.preset = $('reportRangePreset').value;
  1017. $('reportCustomRange').hidden = state.preset !== 'custom';
  1018. reloadReport();
  1019. });
  1020. $('reportFromDate').addEventListener('change', loadReport);
  1021. $('reportToDate').addEventListener('change', loadReport);
  1022. $('reportShopTrigger').addEventListener('click', () => toggleDropdown('reportShopMenu', 'reportShopTrigger'));
  1023. $('reportShopMenu').addEventListener('click', makeDropdownHandler($('reportShopMenu'), state.shopFilter, $('reportShopText'), '全部门店', reloadReport));
  1024. document.addEventListener('click', (event) => {
  1025. if (!$('reportShopDropdown').contains(event.target)) toggleDropdown('reportShopMenu', 'reportShopTrigger', false);
  1026. });
  1027. $('reportViewModes').addEventListener('click', (event) => {
  1028. const btn = event.target.closest('button[data-mode]');
  1029. if (!btn) return;
  1030. state.mode = btn.dataset.mode;
  1031. $('reportViewModes').querySelectorAll('button').forEach((b) => b.classList.toggle('active', b === btn));
  1032. state.sortKey = state.mode === 'detail' ? 'date' : (state.mode === 'shop' ? 'shopName' : 'date');
  1033. state.sortDir = 'desc';
  1034. reloadReport();
  1035. });
  1036. // 字段模式:报表列(语义列)/ 全部字段(明细 + 全部原始字段;聚合视图无 raw,自动回明细)
  1037. $('reportFieldModes').addEventListener('click', (event) => {
  1038. const btn = event.target.closest('button[data-fields]');
  1039. if (!btn) return;
  1040. state.rawView = btn.dataset.fields === 'all';
  1041. $('reportFieldModes').querySelectorAll('button').forEach((b) => b.classList.toggle('active', b === btn));
  1042. if (state.rawView && state.mode !== 'detail') {
  1043. state.mode = 'detail';
  1044. state.sortKey = 'date';
  1045. state.sortDir = 'desc';
  1046. $('reportViewModes').querySelectorAll('button').forEach((b) => b.classList.toggle('active', b.dataset.mode === 'detail'));
  1047. }
  1048. $('reportViewModes').querySelectorAll('button').forEach((b) => { b.disabled = state.rawView; });
  1049. $('btnColumnCfg').hidden = state.rawView; // 列设置只作用于报表列模式
  1050. state.sortKey = state.rawView ? 'date' : state.sortKey;
  1051. renderTable();
  1052. });
  1053. let searchTimer = null;
  1054. $('reportSearch').addEventListener('input', () => {
  1055. clearTimeout(searchTimer);
  1056. searchTimer = setTimeout(() => {
  1057. state.q = $('reportSearch').value.trim();
  1058. reloadReport();
  1059. }, 300);
  1060. });
  1061. $('btnColumnCfg').addEventListener('click', () => {
  1062. renderColumnCfg();
  1063. $('modalReportColumns').hidden = false;
  1064. });
  1065. $('btnCloseColumnCfg').addEventListener('click', () => $('modalReportColumns').hidden = true);
  1066. $('btnApplyColumns').addEventListener('click', applyColumnCfg);
  1067. $('btnResetColumns').addEventListener('click', () => {
  1068. state.visible = new Set(state.columns.filter((c) => !c.reserved).map((c) => c.key));
  1069. LS.set('shanReports.columns.v2', Array.from(state.visible));
  1070. renderColumnCfg();
  1071. renderTable();
  1072. });
  1073. $('btnExportCsv').addEventListener('click', exportCsv);
  1074. $('btnExportHtml').addEventListener('click', exportHtml);
  1075. $('reportTableHead').addEventListener('click', (event) => {
  1076. const th = event.target.closest('th[data-key]');
  1077. if (!th) return;
  1078. const key = th.dataset.key;
  1079. if (state.sortKey === key) state.sortDir = state.sortDir === 'asc' ? 'desc' : 'asc';
  1080. else { state.sortKey = key; state.sortDir = 'desc'; }
  1081. renderTable();
  1082. });
  1083. // 趋势图表
  1084. $('analysisRangePreset').addEventListener('change', () => {
  1085. state.analysisPreset = $('analysisRangePreset').value;
  1086. anaCache = null;
  1087. renderCharts();
  1088. });
  1089. $('anaShopTrigger').addEventListener('click', () => toggleDropdown('anaShopMenu', 'anaShopTrigger'));
  1090. $('anaShopMenu').addEventListener('click', makeDropdownHandler($('anaShopMenu'), state.analysisShopFilter, $('anaShopText'), '全部门店', () => {
  1091. anaCache = null;
  1092. renderCharts();
  1093. }));
  1094. document.addEventListener('click', (event) => {
  1095. if (!$('anaShopDropdown').contains(event.target)) toggleDropdown('anaShopMenu', 'anaShopTrigger', false);
  1096. });
  1097. $('chartMetric').addEventListener('change', () => {
  1098. chartMetric = $('chartMetric').value || 'grossAmt';
  1099. LS.set('shanReports.chartMetric', chartMetric);
  1100. renderCharts();
  1101. });
  1102. $('anaComparePrev').addEventListener('change', renderCharts);
  1103. // 智能问数机器人
  1104. $('chatbotFab').addEventListener('click', () => setChatOpen(!state.chat.open));
  1105. $('btnChatClose').addEventListener('click', () => setChatOpen(false));
  1106. $('btnChatClear').addEventListener('click', () => {
  1107. state.chat.messages = [];
  1108. const all = LS.get(CHAT_LS_KEY, {});
  1109. delete all[state.entity || '_'];
  1110. LS.set(CHAT_LS_KEY, all);
  1111. renderChatMessages();
  1112. });
  1113. $('btnChatSend').addEventListener('click', () => sendChat($('chatbotInput').value));
  1114. $('chatbotInput').addEventListener('keydown', (event) => {
  1115. if (event.key === 'Enter') sendChat($('chatbotInput').value);
  1116. });
  1117. $('chatbotChips').addEventListener('click', (event) => {
  1118. const chip = event.target.closest('[data-q]');
  1119. if (chip) sendChat(chip.dataset.q);
  1120. });
  1121. window.addEventListener('resize', () => {
  1122. Object.values(chartInstances).forEach((c) => { if (c) c.resize(); });
  1123. });
  1124. }
  1125. // ---------- 同步历史(数据采集页,含云端推送状态) ----------
  1126. function renderSyncHistory() {
  1127. const tbody = $('syncHistoryRows');
  1128. if (!tbody) return;
  1129. if (!state.entity) {
  1130. tbody.innerHTML = '<tr><td colspan="8" class="empty-cell">暂无主体</td></tr>';
  1131. return;
  1132. }
  1133. const entityKey = encodeURIComponent(state.entity);
  1134. Promise.all([
  1135. jsonFetch(`/api/reports/syncs?entity=${entityKey}`),
  1136. jsonFetch(`/api/reports/aitable/status?entity=${entityKey}`).catch(() => null),
  1137. ])
  1138. .then(([data, cloud]) => {
  1139. const runs = (data.runs || []).slice(0, 8);
  1140. if (!runs.length) {
  1141. tbody.innerHTML = '<tr><td colspan="8" class="empty-cell">暂无同步记录</td></tr>';
  1142. return;
  1143. }
  1144. const lastPush = cloud && cloud.lastPush ? cloud.lastPush : null;
  1145. const pushAt = lastPush ? new Date(lastPush.at || lastPush.lastPushedAt || 0).getTime() : 0;
  1146. const SCOPE_LABEL = { all: '全主体', chain: '按连锁', shop: '按门店' };
  1147. tbody.innerHTML = runs.map((r) => {
  1148. const warn = (r.steps || []).filter((s) => !s.ok).length;
  1149. const note = r.cancelled ? '已取消' : (r.failed ? `${r.failed} 失败` : (warn ? `${warn} 步骤告警(含全零)` : '成功'));
  1150. const cls = r.cancelled || r.failed ? 'badge-fail' : (warn ? 'badge-warn' : 'badge-ok');
  1151. const t = r.at ? new Date(r.at) : null;
  1152. const ts = t ? `${t.getMonth() + 1}/${t.getDate()} ${String(t.getHours()).padStart(2, '0')}:${String(t.getMinutes()).padStart(2, '0')}` : '–';
  1153. // 该次同步之后是否推送过云端(以最近一次推送时间为准;更早的同步被其覆盖归档)
  1154. const pushed = pushAt && t && pushAt >= t.getTime();
  1155. const cloudCell = !cloud || !cloud.enabled
  1156. ? '<span class="badge">未启用</span>'
  1157. : (pushed ? `<span class="badge badge-ok">已推 ${lastPush.pushedRows || 0} 行</span>` : '<span class="badge badge-info">未推送</span>');
  1158. return `<tr>
  1159. <td>${ts}</td>
  1160. <td>${(r.from || '–').replace(/^(\d{4})(\d{2})(\d{2})$/, '$1-$2-$3')} ~ ${(r.to || '–').replace(/^(\d{4})(\d{2})(\d{2})$/, '$1-$2-$3')}</td>
  1161. <td>${SCOPE_LABEL[r.scope] || r.scope || '–'}</td>
  1162. <td class="num">${r.added ?? 0}</td>
  1163. <td class="num">${r.updated ?? 0}</td>
  1164. <td class="num">${r.failed ?? 0}</td>
  1165. <td><span class="badge ${cls}">${note}</span></td>
  1166. <td>${cloudCell}</td>
  1167. </tr>`;
  1168. }).join('');
  1169. })
  1170. .catch(() => {
  1171. tbody.innerHTML = '<tr><td colspan="8" class="empty-cell">同步历史加载失败</td></tr>';
  1172. });
  1173. }
  1174. // ---------- 主指标趋势(明细 tab 顶部,BI 图表层) ----------
  1175. // 数据独立于表格分页:按日聚合全区间(行数=天数,轻量);懒 init——容器隐藏时 ECharts 拿不到宽高
  1176. let trendChart = null;
  1177. let trendRows = [];
  1178. function buildTrendMetricOptions() {
  1179. const sel = $('reportTrendMetric');
  1180. if (!sel) return;
  1181. const current = sel.value || 'grossAmt';
  1182. const cols = metricColumns().filter((c) => ['money', 'int', 'num', 'pct'].includes(c.type));
  1183. sel.innerHTML = cols.map((c) => `<option value="${c.key}" ${c.key === current ? 'selected' : ''}>${c.label}</option>`).join('');
  1184. }
  1185. async function loadTrend() {
  1186. const entity = state.entity;
  1187. const el = $('reportTrendChart');
  1188. if (!el || !entity) { trendRows = []; return; }
  1189. const { from, to } = currentRange();
  1190. let shops = '';
  1191. if (state.shopFilter.size) shops = `&shops=${encodeURIComponent(Array.from(state.shopFilter).join(','))}`;
  1192. try {
  1193. const data = await jsonFetch(`/api/reports/aggregate?entity=${encodeURIComponent(entity)}&from=${from}&to=${to}&group=date${shops}`);
  1194. if (state.entity !== entity) return;
  1195. trendRows = data.rows || [];
  1196. buildTrendMetricOptions();
  1197. renderTrend();
  1198. } catch { /* 趋势图失败不打扰表格 */ }
  1199. }
  1200. function renderTrend() {
  1201. const el = $('reportTrendChart');
  1202. if (!el || !el.offsetWidth) return; // 容器隐藏(tab 未激活):等激活后再画
  1203. if (!trendRows.length) { if (trendChart) trendChart.clear(); return; }
  1204. if (!trendChart) {
  1205. trendChart = echarts.init(el);
  1206. window.addEventListener('resize', () => { if (trendChart) trendChart.resize(); });
  1207. }
  1208. const metric = $('reportTrendMetric').value || 'grossAmt';
  1209. const col = state.columns.find((c) => c.key === metric) || {};
  1210. const rows = trendRows.slice().sort((a, b) => (a.date < b.date ? -1 : 1));
  1211. const isRate = col.type === 'pct';
  1212. trendChart.setOption({
  1213. grid: { left: 56, right: 20, top: 24, bottom: 36 },
  1214. tooltip: { trigger: 'axis' },
  1215. xAxis: { type: 'category', data: rows.map((r) => String(r.date).replace(/^(\d{4})(\d{2})(\d{2})$/, '$2/$3')) },
  1216. yAxis: { type: 'value', axisLabel: { formatter: (v) => (isRate ? (v * 100).toFixed(0) + '%' : v >= 10000 ? (v / 10000) + '万' : v) } },
  1217. series: [{
  1218. type: 'line', smooth: true, symbolSize: 5, data: rows.map((r) => r[metric]),
  1219. lineStyle: { width: 2.2 }, areaStyle: { opacity: 0.08 },
  1220. tooltip: { valueFormatter: (v) => (v == null ? '—' : isRate ? (v * 100).toFixed(2) + '%' : String(v)) },
  1221. }],
  1222. }, { notMerge: true });
  1223. trendChart.resize();
  1224. }
  1225. // ---------- 初始化 ----------
  1226. // 数据采集页工具栏:推送当前主体到云端(本地湖 → 钉钉 AI 表格)
  1227. async function pushCurrentEntity() {
  1228. const badge = $('reportPushBadge');
  1229. const entity = state.entity || (state.entities[0] || {}).key;
  1230. if (!entity) {
  1231. badge.textContent = '暂无主体';
  1232. badge.className = 'badge badge-fail';
  1233. return;
  1234. }
  1235. if (window.shanAitableAction) {
  1236. try {
  1237. await window.shanAitableAction('push', 'reportPushBadge', { entity });
  1238. } catch { /* 徽标已由 aitableAction 写入 */ }
  1239. }
  1240. }
  1241. async function refreshPushBadge() {
  1242. const badge = $('reportPushBadge');
  1243. if (!badge) return;
  1244. try {
  1245. const res = await fetch('/api/reports/aitable/status');
  1246. const data = await res.json();
  1247. if (!data.enabled) {
  1248. badge.textContent = '云端未启用';
  1249. badge.className = 'badge badge-info';
  1250. } else if (!data.configured) {
  1251. badge.textContent = '云端配置不完整';
  1252. badge.className = 'badge badge-fail';
  1253. } else {
  1254. badge.textContent = '云端就绪';
  1255. badge.className = 'badge badge-ok';
  1256. }
  1257. } catch { /* 状态刷新失败不打扰 */ }
  1258. }
  1259. window.shanReportsInit = async function () {
  1260. if (!state.inited) {
  1261. state.inited = true;
  1262. bindEvents();
  1263. $('btnReportPush').addEventListener('click', async () => {
  1264. await pushCurrentEntity();
  1265. renderSyncHistory(); // 云端推送状态列随推送结果刷新
  1266. });
  1267. $('reportPager').addEventListener('click', (event) => {
  1268. const btn = event.target.closest('button[data-page]');
  1269. if (btn) changePage(Number(btn.dataset.page));
  1270. });
  1271. $('reportTrendMetric').addEventListener('change', renderTrend);
  1272. try {
  1273. const data = await jsonFetch('/api/reports/columns');
  1274. state.columns = data.columns || [];
  1275. } catch { state.columns = []; }
  1276. loadColumnPrefs();
  1277. renderChartMetricSelect();
  1278. }
  1279. await refreshConn();
  1280. refreshPushBadge();
  1281. renderSyncHistory();
  1282. await loadReport();
  1283. };
  1284. window.shanAnalysisActivate = async function () {
  1285. await window.shanReportsInit();
  1286. renderChartMetricSelect();
  1287. await renderCharts();
  1288. Object.values(chartInstances).forEach((c) => { if (c) c.resize(); });
  1289. };
  1290. window.shanSetAnalysisVisible = function (visible) {
  1291. const fab = $('chatbotFab');
  1292. if (!fab) return;
  1293. fab.hidden = !visible;
  1294. if (!visible) setChatOpen(false);
  1295. };
  1296. })();