reports.js 61 KB

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