reports.js 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  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. shopFilter: new Set(),
  84. q: '',
  85. columns: [],
  86. visible: new Set(),
  87. sortKey: 'date',
  88. sortDir: 'desc',
  89. rows: [],
  90. summary: null,
  91. conn: null,
  92. syncShops: new Set(),
  93. syncPollTimer: null,
  94. reportAbort: null,
  95. analysisShopFilter: new Set(),
  96. analysisPreset: '30',
  97. comparePrev: true,
  98. chat: { open: false, busy: false, messages: [] },
  99. };
  100. let chartMetric = LS.get('shanReports.chartMetric', 'grossAmt');
  101. const chartInstances = {};
  102. let anaCache = null;
  103. let lastAskApply = null;
  104. const $ = (id) => document.getElementById(id);
  105. // ---------- 日期区间 ----------
  106. function currentRange() {
  107. if (state.preset === 'custom') {
  108. const from = dashToYmd($('reportFromDate').value);
  109. const to = dashToYmd($('reportToDate').value);
  110. if (from && to && from <= to) return { from, to };
  111. return { from: daysAgoYmd(30), to: daysAgoYmd(0) };
  112. }
  113. const days = Number(state.preset) || 30;
  114. return { from: daysAgoYmd(days), to: daysAgoYmd(0) };
  115. }
  116. function analysisRange() {
  117. const sel = $('analysisRangePreset');
  118. const days = Number(sel && sel.value) || 30;
  119. return { from: daysAgoYmd(days), to: daysAgoYmd(0) };
  120. }
  121. // ---------- 主体 tabs(数据采集 / 趋势图表 共用选中) ----------
  122. function activeEntity() {
  123. return state.entities.find((e) => e.key === state.entity) || null;
  124. }
  125. function renderEntityTabs() {
  126. for (const containerId of ['entityTabs', 'analysisEntityTabs']) {
  127. const wrap = $(containerId);
  128. if (!wrap) continue;
  129. wrap.innerHTML = '';
  130. if (!state.entities.length) {
  131. const empty = document.createElement('div');
  132. empty.className = 'entity-tabs-empty';
  133. empty.textContent = '暂无主体 —— 请先在商家客户端登录并完成一次「同步数据」';
  134. wrap.appendChild(empty);
  135. continue;
  136. }
  137. for (const e of state.entities) {
  138. const btn = document.createElement('button');
  139. btn.type = 'button';
  140. btn.className = 'entity-tab' + (e.key === state.entity ? ' active' : '');
  141. btn.innerHTML = `<span class="entity-name"></span><span class="entity-meta"></span>`;
  142. btn.querySelector('.entity-name').textContent = e.name || e.key;
  143. const shopCount = (e.shops || []).length || e.shopCount || 0;
  144. btn.querySelector('.entity-meta').textContent = shopCount ? `${shopCount} 家门店` : '主体';
  145. btn.addEventListener('click', () => {
  146. if (state.entity === e.key) return;
  147. state.entity = e.key;
  148. state.shopFilter = new Set();
  149. state.analysisShopFilter = new Set();
  150. state.sortKey = 'date'; state.sortDir = 'desc';
  151. LS.set('shanReports.entity', e.key);
  152. anaCache = null;
  153. renderEntityTabs();
  154. renderShopOptions();
  155. loadReport();
  156. renderCharts();
  157. });
  158. wrap.appendChild(btn);
  159. }
  160. }
  161. }
  162. // ---------- 门店多选下拉(数据采集 / 同步 / 趋势图表 三处) ----------
  163. function toggleDropdown(menuId, triggerId, open) {
  164. const trigger = $(triggerId);
  165. const menu = menuId ? $(menuId) : null;
  166. const shouldOpen = open === undefined ? (menu ? menu.hidden : false) : open;
  167. if (menu) menu.hidden = !shouldOpen;
  168. if (trigger) trigger.setAttribute('aria-expanded', String(shouldOpen));
  169. }
  170. function fillShopMenu(menu, shops) {
  171. menu.innerHTML = '';
  172. const all = document.createElement('button');
  173. all.type = 'button';
  174. all.className = 'scan-dropdown-item';
  175. all.dataset.value = '__all__';
  176. all.setAttribute('role', 'option');
  177. 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>';
  178. menu.appendChild(all);
  179. const sorted = shops.slice().sort((a, b) => String(a.shopName).localeCompare(String(b.shopName), 'zh-CN'));
  180. for (const s of sorted) {
  181. const item = document.createElement('button');
  182. item.type = 'button';
  183. item.className = 'scan-dropdown-item';
  184. item.dataset.value = String(s.shopId);
  185. item.setAttribute('role', 'option');
  186. 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>';
  187. item.lastElementChild.textContent = s.shopName;
  188. menu.appendChild(item);
  189. }
  190. }
  191. function renderDropdownSelection(menu, selection, textEl, allLabel) {
  192. menu.querySelectorAll('.scan-dropdown-item').forEach((node) => {
  193. const selected = selection.has(node.dataset.value);
  194. node.classList.toggle('selected', selected);
  195. node.setAttribute('aria-selected', String(selected));
  196. });
  197. const picked = Array.from(selection).filter((v) => v !== '__all__');
  198. textEl.textContent = picked.length ? `已选 ${picked.length} 家门店` : allLabel;
  199. }
  200. function renderShopOptions() {
  201. const entity = activeEntity();
  202. const shops = (entity && entity.shops) || [];
  203. const menus = [
  204. { menu: $('reportShopMenu'), sel: state.shopFilter, text: $('reportShopText'), label: '全部门店' },
  205. { menu: $('syncShopMenu'), sel: state.syncShops, text: $('syncShopText'), label: '选择门店' },
  206. { menu: $('anaShopMenu'), sel: state.analysisShopFilter, text: $('anaShopText'), label: '全部门店' },
  207. ];
  208. for (const m of menus) {
  209. if (!m.menu) continue;
  210. fillShopMenu(m.menu, shops);
  211. renderDropdownSelection(m.menu, m.sel, m.text, m.label);
  212. }
  213. }
  214. function makeDropdownHandler(menu, selection, textEl, allLabel, onChange) {
  215. return (event) => {
  216. const item = event.target.closest('[data-value]');
  217. if (!item) return;
  218. const value = item.dataset.value;
  219. if (value === '__all__') selection.clear();
  220. else if (selection.has(value)) selection.delete(value);
  221. else selection.add(value);
  222. renderDropdownSelection(menu, selection, textEl, allLabel);
  223. if (onChange) onChange();
  224. };
  225. }
  226. // ---------- KPI 卡片(数据采集页) ----------
  227. function renderKpis() {
  228. const wrap = $('reportKpis');
  229. wrap.innerHTML = '';
  230. const s = state.summary || {};
  231. const cards = [
  232. { label: '营业额(元)', value: fmtMoney(s.grossAmt), cls: 'accent' },
  233. { label: '收入(元)', value: fmtMoney(s.incomeAmt), cls: 'ok' },
  234. { label: '有效订单', value: fmtNum(s.validOrderCnt), cls: 'accent' },
  235. { label: '曝光人数', value: fmtNum(s.expUv), cls: '' },
  236. { label: '下单人数', value: fmtNum(s.orderUserCnt), cls: '' },
  237. { label: '进店转化率', value: fmtPct(s.clkExpRate), cls: 'warn', rate: 'clkExpRate' },
  238. { label: '客单价(元)', value: fmtMoney(s.perActualPay), cls: 'ok' },
  239. ];
  240. for (const c of cards) {
  241. const div = document.createElement('div');
  242. div.className = 'metric ' + (c.cls || '');
  243. 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>`;
  244. div.querySelector('.metric-label').textContent = c.label;
  245. div.querySelector('.metric-value').textContent = c.value;
  246. wrap.appendChild(div);
  247. }
  248. }
  249. // ---------- 报表表格(数据采集页) ----------
  250. function metricColumns() {
  251. return state.columns.filter((c) => c.key !== 'date' && c.key !== 'shopName' && state.visible.has(c.key));
  252. }
  253. function tableColumns() {
  254. const metricCols = metricColumns();
  255. if (state.mode === 'shop') return [{ key: 'shopName', label: '门店名称', type: 'text' }, ...metricCols];
  256. if (state.mode === 'date') return [{ key: 'date', label: '日期', type: 'date' }, ...metricCols];
  257. return [{ key: 'date', label: '日期', type: 'date' }, { key: 'shopName', label: '门店名称', type: 'text' }, ...metricCols];
  258. }
  259. function sortedRows() {
  260. return state.rows.slice().sort((a, b) => {
  261. const av = a[state.sortKey], bv = b[state.sortKey];
  262. if (av == null || av === '') return 1;
  263. if (bv == null || bv === '') return -1;
  264. if (typeof av === 'number' && typeof bv === 'number') return (av - bv) * (state.sortDir === 'asc' ? 1 : -1);
  265. return String(av).localeCompare(String(bv), 'zh-CN') * (state.sortDir === 'asc' ? 1 : -1);
  266. });
  267. }
  268. function renderTable() {
  269. const cols = tableColumns();
  270. const thead = $('reportTableHead');
  271. const tbody = $('reportTableBody');
  272. $('reportRowCount').textContent = `${state.rows.length} 行`;
  273. const empty = $('reportEmpty');
  274. if (!state.rows.length) {
  275. thead.innerHTML = '';
  276. tbody.innerHTML = '';
  277. empty.hidden = false;
  278. return;
  279. }
  280. empty.hidden = true;
  281. thead.innerHTML = '<tr>' + cols.map((c) => {
  282. const active = state.sortKey === c.key;
  283. const arrow = active ? (state.sortDir === 'asc' ? ' ↑' : ' ↓') : '';
  284. return `<th class="col-${c.type}${['money', 'int', 'pct', 'num'].includes(c.type) ? ' col-num' : ''}" data-key="${c.key}">${c.label}${arrow}</th>`;
  285. }).join('') + '</tr>';
  286. tbody.innerHTML = sortedRows().map((r) => '<tr>' + cols.map((c) => {
  287. const isNum = ['money', 'int', 'pct', 'num'].includes(c.type);
  288. const cls = `col-${c.type}${isNum ? ' col-num' : ''}${c.type === 'pct' ? ' ' + rateClass(c.key, r[c.key]) : ''}`;
  289. return `<td class="${cls}">${fmtCell(c, r[c.key])}</td>`;
  290. }).join('') + '</tr>').join('');
  291. }
  292. // ---------- 数据加载(数据采集页) ----------
  293. async function loadReport() {
  294. const entity = state.entity;
  295. if (!entity) {
  296. state.rows = []; state.summary = null;
  297. renderTable(); renderKpis();
  298. return;
  299. }
  300. if (state.reportAbort) state.reportAbort.abort();
  301. const ctrl = new AbortController();
  302. state.reportAbort = ctrl;
  303. const { from, to } = currentRange();
  304. try {
  305. let url = state.mode === 'detail'
  306. ? `/api/reports/daily?entity=${encodeURIComponent(entity)}&from=${from}&to=${to}&scope=shop`
  307. : `/api/reports/aggregate?entity=${encodeURIComponent(entity)}&from=${from}&to=${to}&group=${state.mode}`;
  308. if (state.shopFilter.size) url += `&shops=${encodeURIComponent(Array.from(state.shopFilter).join(','))}`;
  309. if (state.q) url += `&q=${encodeURIComponent(state.q)}`;
  310. const data = await jsonFetch(url, { signal: ctrl.signal });
  311. if (state.entity !== entity) return;
  312. state.rows = data.rows || [];
  313. state.summary = data.summary || null;
  314. renderKpis();
  315. renderTable();
  316. } catch (e) {
  317. if (e.name === 'AbortError') return;
  318. showToast('报表加载失败:' + e.message, 'error');
  319. }
  320. }
  321. // ---------- 连接状态 ----------
  322. async function refreshConn() {
  323. const badge = $('reportConnBadge');
  324. try {
  325. const data = await jsonFetch('/api/reports/status');
  326. state.conn = data.napos || null;
  327. state.entities = data.entities || [];
  328. if (!state.entity || !state.entities.some((e) => e.key === state.entity)) {
  329. const saved = LS.get('shanReports.entity', null);
  330. state.entity = (saved && state.entities.some((e) => e.key === saved)) ? saved : (state.entities[0] ? state.entities[0].key : null);
  331. }
  332. renderEntityTabs();
  333. renderShopOptions();
  334. const ok = state.conn && state.conn.connected;
  335. badge.textContent = ok ? '客户端已连接' : '客户端未连接';
  336. badge.className = 'badge ' + (ok ? 'badge-ok' : 'badge-fail');
  337. badge.title = ok
  338. ? `调试端口 ${state.conn.port}`
  339. : [state.conn && state.conn.error, state.conn && state.conn.hint].filter(Boolean).join('\n') || '未检测到调试端口';
  340. } catch {
  341. badge.textContent = '状态检测失败';
  342. badge.className = 'badge badge-fail';
  343. }
  344. }
  345. // ---------- 列设置 ----------
  346. function loadColumnPrefs() {
  347. // 默认只展示原始/主指标列(营业时长、异常关店时长、商品销售额为预留列,数据源接入后自动回填);
  348. // 下单转化率、客单价、支出、活动订单、活动补贴、推广ROI、30日复购率等派生指标默认隐藏,可在列设置打开。
  349. const DEFAULT_VISIBLE_COLS = new Set([
  350. 'bizHours', 'abnormalCloseHours', 'validOrderCnt', 'incomeAmt', 'grossAmt',
  351. 'goodsSaleAmt', 'expUv', 'orderUserCnt', 'clkExpRate',
  352. ]);
  353. const saved = LS.get('shanReports.columns.v2', null);
  354. const defaults = new Set(state.columns.filter((c) => DEFAULT_VISIBLE_COLS.has(c.key)).map((c) => c.key));
  355. if (Array.isArray(saved)) {
  356. const valid = new Set(state.columns.map((c) => c.key));
  357. state.visible = new Set(saved.filter((k) => valid.has(k)));
  358. } else {
  359. state.visible = defaults;
  360. }
  361. if (!state.visible.size) state.visible = defaults;
  362. }
  363. function renderColumnCfg() {
  364. const list = $('columnCfgList');
  365. list.innerHTML = '';
  366. for (const c of state.columns) {
  367. if (c.locked) continue;
  368. const label = document.createElement('label');
  369. label.className = 'colcfg-item';
  370. const checked = state.visible.has(c.key) ? 'checked' : '';
  371. label.innerHTML = `<input type="checkbox" value="${c.key}" ${checked}><span></span>${c.reserved ? '<em class="colcfg-reserved">预留</em>' : ''}`;
  372. label.querySelector('span').textContent = c.label;
  373. list.appendChild(label);
  374. }
  375. }
  376. function applyColumnCfg() {
  377. const picks = new Set();
  378. $('columnCfgList').querySelectorAll('input[type=checkbox]').forEach((cb) => {
  379. if (cb.checked) picks.add(cb.value);
  380. });
  381. state.visible = picks;
  382. LS.set('shanReports.columns.v2', Array.from(picks));
  383. $('modalReportColumns').hidden = true;
  384. renderTable();
  385. }
  386. // ---------- 同步 ----------
  387. function renderSyncProgress(st) {
  388. const pct = st.planTotal ? Math.round((st.done / st.planTotal) * 100) : 0;
  389. $('syncProgressBar').style.width = pct + '%';
  390. $('syncProgressText').textContent = `${st.done} / ${st.planTotal}`;
  391. $('syncStatAdded').textContent = `新增 ${st.added}`;
  392. $('syncStatUpdated').textContent = `更新 ${st.updated}`;
  393. $('syncStatFailed').textContent = `失败 ${st.failed}`;
  394. const steps = (st.steps || []).slice(-8);
  395. $('syncSteps').innerHTML = steps.map((s) => {
  396. const cls = s.ok ? 'ok' : 'fail';
  397. const detail = s.ok
  398. ? `+${s.added}/~${s.updated}` + (s.rows != null ? ` · ${s.rows}行` : '') + (s.nonZero === 0 && s.rows > 0 ? ' · ⚠全零' : '')
  399. : (s.error || '失败').slice(0, 60);
  400. return `<div class="sync-step ${cls}"><span></span><em>${detail}</em></div>`;
  401. }).join('');
  402. const stepNames = $('syncSteps').querySelectorAll('.sync-step span');
  403. steps.forEach((s, i) => { stepNames[i].textContent = s.label; });
  404. $('btnSyncCancel').hidden = !st.running;
  405. $('btnStartSync').disabled = !!st.running;
  406. $('btnStartSync').textContent = st.running ? '同步中…' : '开始同步';
  407. }
  408. function pollSyncStatus() {
  409. if (state.syncPollTimer) clearInterval(state.syncPollTimer);
  410. state.syncPollTimer = setInterval(async () => {
  411. try {
  412. const st = await jsonFetch('/api/reports/sync/status');
  413. renderSyncProgress(st);
  414. if (!st.running) {
  415. clearInterval(state.syncPollTimer);
  416. state.syncPollTimer = null;
  417. if (st.error) showToast('同步出错:' + st.error, 'error');
  418. else showToast(st.cancelled ? '同步已取消' : `同步完成:新增 ${st.added},更新 ${st.updated}`);
  419. refreshConn().then(loadReport);
  420. }
  421. } catch { /* 轮询失败忽略 */ }
  422. }, 900);
  423. }
  424. async function loadAutoSyncPrefs() {
  425. try {
  426. const s = await jsonFetch('/api/settings');
  427. $('autoSyncEnabled').checked = !!s.autoSyncEnabled;
  428. if (s.autoSyncTime) $('autoSyncTime').value = s.autoSyncTime;
  429. } catch { /* 设置读取失败时保留默认值 */ }
  430. }
  431. async function saveAutoSyncPrefs() {
  432. try {
  433. await jsonFetch('/api/settings', {
  434. method: 'POST',
  435. headers: { 'Content-Type': 'application/json' },
  436. body: JSON.stringify({ autoSyncEnabled: $('autoSyncEnabled').checked, autoSyncTime: $('autoSyncTime').value }),
  437. });
  438. showToast('自动同步设置已保存');
  439. } catch (e) {
  440. showToast('自动同步设置保存失败:' + e.message, 'error');
  441. }
  442. }
  443. async function openSyncModal() {
  444. $('modalReportSync').hidden = false;
  445. $('syncEntityBadge').textContent = '识别主体中…';
  446. $('syncEntityBadge').className = 'badge badge-info';
  447. $('syncShopPickWrap').hidden = true;
  448. $('syncProgressWrap').hidden = true;
  449. loadAutoSyncPrefs();
  450. try {
  451. const tree = await jsonFetch('/api/reports/tree');
  452. const badge = $('syncEntityBadge');
  453. badge.textContent = `当前主体:${(tree.entity && tree.entity.name) || (tree.merchant && tree.merchant.name) || '未知'} · 门店 ${(tree.shops || []).length} 家`;
  454. badge.className = 'badge badge-ok';
  455. if (tree.entity && tree.entity.key && tree.entity.key !== state.entity) {
  456. state.entity = tree.entity.key;
  457. LS.set('shanReports.entity', tree.entity.key);
  458. }
  459. await refreshConn();
  460. renderSyncShopOptions(tree.shops || []);
  461. } catch (e) {
  462. const badge = $('syncEntityBadge');
  463. badge.textContent = '未连接客户端:' + e.message;
  464. badge.className = 'badge badge-fail';
  465. try {
  466. const st = await jsonFetch('/api/reports/status');
  467. const napos = st.napos || {};
  468. $('syncHint').textContent = [napos.hint, napos.selfCheckUrl ? `自检:客户端带参启动后,用浏览器打开 ${napos.selfCheckUrl} 应看到一段 JSON。` : '']
  469. .filter(Boolean).join(' ');
  470. } catch { /* 服务不可达时保留默认文案 */ }
  471. }
  472. }
  473. function renderSyncShopOptions(shops) {
  474. state.syncShops.clear();
  475. fillShopMenu($('syncShopMenu'), shops);
  476. renderDropdownSelection($('syncShopMenu'), state.syncShops, $('syncShopText'), '选择门店');
  477. }
  478. async function startSync() {
  479. const scope = $('syncScope').value;
  480. const days = Number($('syncRange').value) || 30;
  481. const body = { from: daysAgoYmd(days), to: daysAgoYmd(1), scope: scope === 'custom' ? 'shop' : scope };
  482. if (scope === 'custom') {
  483. const shops = Array.from(state.syncShops).filter((v) => v !== '__all__');
  484. if (!shops.length) { showToast('请先选择要同步的门店', 'error'); return; }
  485. body.shopIds = shops;
  486. }
  487. try {
  488. await jsonFetch('/api/reports/sync', {
  489. method: 'POST',
  490. headers: { 'Content-Type': 'application/json' },
  491. body: JSON.stringify(body),
  492. });
  493. $('syncProgressWrap').hidden = false;
  494. renderSyncProgress({ planTotal: 0, done: 0, added: 0, updated: 0, failed: 0, steps: [], running: true });
  495. pollSyncStatus();
  496. } catch (e) {
  497. showToast('同步启动失败:' + e.message, 'error');
  498. }
  499. }
  500. // ---------- 导出 ----------
  501. function exportCsv() {
  502. if (!state.entity) { showToast('暂无主体可导出', 'error'); return; }
  503. const { from, to } = currentRange();
  504. let url = `/api/reports/export?entity=${encodeURIComponent(state.entity)}&from=${from}&to=${to}`;
  505. if (state.mode !== 'detail') url += `&group=${state.mode}`;
  506. if (state.shopFilter.size) url += `&shops=${encodeURIComponent(Array.from(state.shopFilter).join(','))}`;
  507. if (state.q) url += `&q=${encodeURIComponent(state.q)}`;
  508. window.location.href = url;
  509. }
  510. function exportHtml() {
  511. if (!state.entity) { showToast('暂无主体可导出', 'error'); return; }
  512. const { from, to } = analysisRange();
  513. window.open(`/api/reports/report-html?entity=${encodeURIComponent(state.entity)}&from=${from}&to=${to}`, '_blank');
  514. }
  515. // ---------- 趋势图表 ----------
  516. function chartCol(key) {
  517. return state.columns.find((c) => c.key === key) || { key, label: key, type: 'num' };
  518. }
  519. function ensureChart(instanceKey, domId) {
  520. if (typeof echarts === 'undefined') return null;
  521. const dom = $(domId);
  522. if (!dom) return null;
  523. if (!chartInstances[instanceKey]) chartInstances[instanceKey] = echarts.init(dom);
  524. return chartInstances[instanceKey];
  525. }
  526. function metricColumnOptions() {
  527. return state.columns.filter((c) => ['int', 'money', 'pct', 'num'].includes(c.type) && !c.reserved);
  528. }
  529. function renderChartMetricSelect() {
  530. const sel = $('chartMetric');
  531. if (!sel) return;
  532. sel.innerHTML = '';
  533. for (const c of metricColumnOptions()) {
  534. const opt = document.createElement('option');
  535. opt.value = c.key;
  536. opt.textContent = c.label;
  537. if (c.key === chartMetric) opt.selected = true;
  538. sel.appendChild(opt);
  539. }
  540. if (!sel.value && sel.options.length) sel.value = sel.options[0].value;
  541. chartMetric = sel.value || 'grossAmt';
  542. }
  543. const AXIS_TXT = { axisLabel: { color: '#6b6560' }, axisLine: { lineStyle: { color: '#e8e4df' } } };
  544. const SPLIT_LINE = { lineStyle: { color: '#f0ede8' } };
  545. const ACCENT = '#ff6b35';
  546. async function ensureAnalysisData() {
  547. const { from, to } = analysisRange();
  548. const shopSuffix = state.analysisShopFilter.size
  549. ? `&shops=${encodeURIComponent(Array.from(state.analysisShopFilter).join(','))}`
  550. : '';
  551. const key = [state.entity, from, to, state.analysisShopFilter.size ? [...state.analysisShopFilter].sort().join(',') : ''].join('|');
  552. if (anaCache && anaCache.key === key) return anaCache;
  553. const fd = (s) => new Date(Number(String(s).slice(0, 4)), Number(String(s).slice(4, 6)) - 1, Number(String(s).slice(6, 8)));
  554. const spanDays = Math.max(1, Math.round((fd(to) - fd(from)) / 86400000) + 1);
  555. const prevToD = fd(from);
  556. prevToD.setDate(prevToD.getDate() - 1);
  557. const prevTo = ymdLocal(prevToD);
  558. const prevFromD = new Date(prevToD);
  559. prevFromD.setDate(prevFromD.getDate() - (spanDays - 1));
  560. const prevFrom = ymdLocal(prevFromD);
  561. const base = `/api/reports/aggregate?entity=${encodeURIComponent(state.entity)}`;
  562. const [byDate, byDatePrev, byShop, topDaily] = await Promise.all([
  563. jsonFetch(`${base}&from=${from}&to=${to}&group=date${shopSuffix}`).then((d) => d.rows || []),
  564. jsonFetch(`${base}&from=${prevFrom}&to=${prevTo}&group=date${shopSuffix}`).then((d) => d.rows || []),
  565. jsonFetch(`${base}&from=${from}&to=${to}&group=shop${shopSuffix}`).then((d) => d.rows || []),
  566. jsonFetch(`/api/reports/daily?entity=${encodeURIComponent(state.entity)}&from=${from}&to=${to}&scope=shop${shopSuffix}`).then((d) => d.rows || []),
  567. ]);
  568. anaCache = { key, from, to, prevFrom, prevTo, byDate, byDatePrev, byShop, topDaily };
  569. return anaCache;
  570. }
  571. function renderDeltas(data) {
  572. const wrap = $('analysisDeltas');
  573. if (!wrap) return;
  574. wrap.innerHTML = '';
  575. const sum = (rows, f) => rows.reduce((a, r) => a + (Number(r[f]) || 0), 0);
  576. const wAvg = (rows, f, wb) => {
  577. let num = 0, den = 0;
  578. for (const r of rows) { const wt = Number(r[wb]) || 0; num += (Number(r[f]) || 0) * wt; den += wt; }
  579. return den > 0 ? num / den : 0;
  580. };
  581. const curOrders = sum(data.byDate, 'validOrderCnt');
  582. const prevOrders = sum(data.byDatePrev, 'validOrderCnt');
  583. const items = [
  584. { label: '营业额', cur: sum(data.byDate, 'grossAmt'), prev: sum(data.byDatePrev, 'grossAmt'), fmt: fmtMoney },
  585. { label: '有效订单', cur: curOrders, prev: prevOrders, fmt: fmtNum },
  586. { label: '收入', cur: sum(data.byDate, 'incomeAmt'), prev: sum(data.byDatePrev, 'incomeAmt'), fmt: fmtMoney },
  587. { label: '曝光人数', cur: sum(data.byDate, 'expUv'), prev: sum(data.byDatePrev, 'expUv'), fmt: fmtNum },
  588. { label: '下单人数', cur: sum(data.byDate, 'orderUserCnt'), prev: sum(data.byDatePrev, 'orderUserCnt'), fmt: fmtNum },
  589. { label: '进店转化率', cur: wAvg(data.byDate, 'clkExpRate', 'expUv'), prev: wAvg(data.byDatePrev, 'clkExpRate', 'expUv'), fmt: fmtPct },
  590. { label: '客单价', cur: curOrders > 0 ? sum(data.byDate, 'grossAmt') / curOrders : 0, prev: prevOrders > 0 ? sum(data.byDatePrev, 'grossAmt') / prevOrders : 0, fmt: fmtMoney },
  591. ];
  592. for (const it of items) {
  593. const cur = Math.round(it.cur * 100) / 100;
  594. const div = document.createElement('div');
  595. div.className = 'delta-card';
  596. let deltaHtml;
  597. const delta = it.prev > 0 ? (it.cur - it.prev) / it.prev : null;
  598. if (delta == null || !Number.isFinite(delta)) deltaHtml = '<span class="delta-none">上期无数据</span>';
  599. else if (Math.abs(delta) < 0.0001) deltaHtml = '<span class="delta-flat">持平</span>';
  600. else {
  601. const up = delta > 0;
  602. deltaHtml = `<span class="delta ${up ? 'up' : 'down'}">${up ? '↑' : '↓'} ${Math.abs(delta * 100).toFixed(1)}%</span>`
  603. + `<span class="delta-sub">vs 上期 ${it.fmt(Math.round(it.prev * 100) / 100)}</span>`;
  604. }
  605. div.innerHTML = `<span class="delta-label"></span><span class="delta-value"></span><span class="delta-line">${deltaHtml}</span>`;
  606. div.querySelector('.delta-label').textContent = it.label;
  607. div.querySelector('.delta-value').textContent = it.fmt(cur);
  608. wrap.appendChild(div);
  609. }
  610. }
  611. async function renderCharts() {
  612. let data;
  613. try { data = await ensureAnalysisData(); } catch { return; }
  614. renderDeltas(data);
  615. const col = chartCol(chartMetric);
  616. const compareOn = $('anaComparePrev') && $('anaComparePrev').checked;
  617. const trend = ensureChart('trend', 'chartTrend');
  618. if (trend) {
  619. const cur = data.byDate.slice().sort((a, b) => (a.date < b.date ? -1 : 1));
  620. const prev = data.byDatePrev.slice().sort((a, b) => (a.date < b.date ? -1 : 1));
  621. const xData = cur.map((r) => ymdToDash(r.date));
  622. const series = [{
  623. name: `本期·${col.label}`, type: 'line', smooth: true, symbolSize: 5,
  624. data: cur.map((r) => Number(r[chartMetric]) || 0),
  625. itemStyle: { color: ACCENT }, lineStyle: { width: 2.5 },
  626. areaStyle: { color: 'rgba(255,107,53,.08)' },
  627. }];
  628. if (compareOn && prev.length) {
  629. series.push({
  630. name: '上期同期', type: 'line', smooth: true,
  631. data: xData.map((_, i) => (prev[i] ? Number(prev[i][chartMetric]) || 0 : 0)),
  632. itemStyle: { color: '#a5a09a' }, lineStyle: { type: 'dashed', width: 1.6 }, symbol: 'none',
  633. });
  634. }
  635. trend.setOption({
  636. tooltip: { trigger: 'axis', valueFormatter: (v) => fmtByCol(col, v) },
  637. legend: { data: series.map((x) => x.name), top: 0, icon: 'roundRect', itemWidth: 14, itemHeight: 4, textStyle: { color: '#6b6560' } },
  638. grid: { left: 64, right: 24, top: 36, bottom: 30 },
  639. xAxis: { type: 'category', boundaryGap: false, data: xData, ...AXIS_TXT },
  640. yAxis: { type: 'value', axisLabel: { color: '#6b6560' }, splitLine: SPLIT_LINE },
  641. series,
  642. }, true);
  643. const title = $('anaTrendTitle');
  644. if (title) title.textContent = `主指标趋势 · ${col.label}(${ymdToDash(data.from)} ~ ${ymdToDash(data.to)})`;
  645. }
  646. const rank = ensureChart('rank', 'chartRank');
  647. if (rank) {
  648. const top = data.byShop.slice()
  649. .sort((a, b) => (Number(b[chartMetric]) || 0) - (Number(a[chartMetric]) || 0))
  650. .slice(0, 10).reverse();
  651. rank.setOption({
  652. tooltip: { trigger: 'axis', valueFormatter: (v) => fmtByCol(col, v) },
  653. grid: { left: 10, right: 34, top: 10, bottom: 24, containLabel: true },
  654. xAxis: { type: 'value', axisLabel: { color: '#6b6560' }, splitLine: SPLIT_LINE },
  655. yAxis: {
  656. type: 'category', data: top.map((r) => r.shopName || r.shopId),
  657. axisLabel: { color: '#2b2a28', width: 130, overflow: 'truncate' },
  658. axisLine: { lineStyle: { color: '#e8e4df' } },
  659. },
  660. series: [{ type: 'bar', barMaxWidth: 18, data: top.map((r) => Number(r[chartMetric]) || 0), itemStyle: { color: ACCENT, borderRadius: [0, 6, 6, 0] } }],
  661. }, true);
  662. }
  663. const funnel = ensureChart('funnel', 'chartFunnel');
  664. if (funnel) {
  665. const sum = (f) => data.byDate.reduce((a, r) => a + (Number(r[f]) || 0), 0);
  666. const expUv = sum('expUv');
  667. const enter = data.byDate.reduce((a, r) => a + (Number(r.expUv) || 0) * (Number(r.clkExpRate) || 0), 0);
  668. const order = sum('orderUserCnt');
  669. funnel.setOption({
  670. tooltip: { trigger: 'item', formatter: (p) => `${p.name}:${fmtNum(Math.round(p.value))} 人` },
  671. series: [{
  672. type: 'funnel', left: '8%', width: '84%', top: 12, bottom: 8, minSize: '20%',
  673. label: { color: '#fff', fontWeight: 600, formatter: (p) => `${p.name} ${fmtNum(Math.round(p.value))}` },
  674. data: [
  675. { name: '曝光人数', value: Math.round(expUv), itemStyle: { color: '#ffb199' } },
  676. { name: '进店人数', value: Math.round(enter), itemStyle: { color: '#ff8a5c' } },
  677. { name: '下单人数', value: Math.round(order), itemStyle: { color: ACCENT } },
  678. ],
  679. }],
  680. }, true);
  681. }
  682. const compare = ensureChart('compare', 'chartCompare');
  683. if (compare) {
  684. const top5 = data.byShop.slice()
  685. .sort((a, b) => (Number(b[chartMetric]) || 0) - (Number(a[chartMetric]) || 0))
  686. .slice(0, 5);
  687. const dates = [...new Set(data.topDaily.map((r) => r.date))].sort();
  688. const palette = ['#ff6b35', '#2563eb', '#1a8a4c', '#b8860b', '#8b5cf6'];
  689. const series = top5.map((shop, i) => ({
  690. name: shop.shopName || shop.shopId,
  691. type: 'line', smooth: true, symbolSize: 4,
  692. data: dates.map((d) => {
  693. const r = data.topDaily.find((x) => x.date === d && String(x.shopId) === String(shop.shopId));
  694. return r ? (Number(r[chartMetric]) || 0) : 0;
  695. }),
  696. itemStyle: { color: palette[i % palette.length] }, lineStyle: { width: 2 },
  697. }));
  698. compare.setOption({
  699. tooltip: { trigger: 'axis', valueFormatter: (v) => fmtByCol(col, v) },
  700. legend: { top: 0, type: 'scroll', icon: 'roundRect', itemWidth: 14, itemHeight: 4, textStyle: { color: '#6b6560' } },
  701. grid: { left: 64, right: 24, top: 36, bottom: 30 },
  702. xAxis: { type: 'category', boundaryGap: false, data: dates.map(ymdToDash), ...AXIS_TXT },
  703. yAxis: { type: 'value', axisLabel: { color: '#6b6560' }, splitLine: SPLIT_LINE },
  704. series,
  705. }, true);
  706. const title = $('anaCompareTitle');
  707. if (title) title.textContent = `门店对比 · Top ${top5.length}(${col.label})`;
  708. }
  709. }
  710. // ---------- 智能问数 · 机器人(仅经营分析页面) ----------
  711. // 对话历史按主体持久化到 localStorage,刷新/重开后可继续追问
  712. const CHAT_LS_KEY = 'shanReports.chat.v1';
  713. const chatStoreKey = () => state.entity || '_';
  714. function loadChatForEntity() {
  715. const all = LS.get(CHAT_LS_KEY, {});
  716. state.chat.messages = Array.isArray(all[chatStoreKey()]) ? all[chatStoreKey()] : [];
  717. if (state.chat.open) renderChatMessages();
  718. }
  719. function saveChatForEntity() {
  720. const key = chatStoreKey();
  721. const all = LS.get(CHAT_LS_KEY, {});
  722. const trimmed = state.chat.messages.filter((m) => !m.pending).slice(-20);
  723. const attempt = (payload) => {
  724. try { localStorage.setItem(CHAT_LS_KEY, JSON.stringify(payload)); return true; } catch { return false; }
  725. };
  726. if (attempt({ ...all, [key]: trimmed })) return;
  727. // 图表行数据可能撑爆配额 → 退化为只存文字与图表配置
  728. const slim = { ...all, [key]: trimmed.map((m) => ({ ...m, rows: undefined })) };
  729. if (!(attempt(slim) || attempt({ [key]: slim[key].slice(-10) }))) { /* 配额不足则放弃持久化 */ }
  730. }
  731. function chatVisibleFor(view) { return view === 'reports' || view === 'analysis'; }
  732. function setChatOpen(open) {
  733. state.chat.open = open;
  734. $('chatbotPanel').hidden = !open;
  735. $('chatbotFab').classList.toggle('active', open);
  736. if (open) {
  737. loadChatForEntity();
  738. $('chatbotFab').hidden = false;
  739. setTimeout(() => $('chatbotInput').focus(), 60);
  740. scrollChatBottom();
  741. }
  742. }
  743. function scrollChatBottom() {
  744. const body = $('chatbotBody');
  745. body.scrollTop = body.scrollHeight;
  746. }
  747. function renderChatMessages() {
  748. const body = $('chatbotBody');
  749. [...body.querySelectorAll('.chatbot-msg:not(.static)')].forEach((n) => n.remove());
  750. body.querySelectorAll('.chatbot-chips').forEach((n) => { n.hidden = state.chat.messages.length > 0; });
  751. for (let i = 0; i < state.chat.messages.length; i++) {
  752. const m = state.chat.messages[i];
  753. const div = document.createElement('div');
  754. div.className = 'chatbot-msg ' + (m.role === 'user' ? 'user' : 'bot');
  755. if (m.pending) {
  756. div.innerHTML = '<div class="chatbot-bubble typing"><span></span><span></span><span></span></div>';
  757. } else {
  758. const bubble = document.createElement('div');
  759. bubble.className = 'chatbot-bubble';
  760. bubble.textContent = m.text || '';
  761. div.appendChild(bubble);
  762. if (m.chart && m.chart.type !== 'none' && m.rows && m.rows.length) {
  763. const chartWrap = document.createElement('div');
  764. chartWrap.className = 'chatbot-chart';
  765. chartWrap.dataset.idx = String(i);
  766. div.appendChild(chartWrap);
  767. const actions = document.createElement('div');
  768. actions.className = 'chatbot-msg-actions';
  769. const applyBtn = document.createElement('button');
  770. applyBtn.type = 'button';
  771. applyBtn.className = 'btn btn-ghost btn-small';
  772. applyBtn.textContent = '应用到报表';
  773. applyBtn.addEventListener('click', () => applyMsgQuery(i));
  774. actions.appendChild(applyBtn);
  775. div.appendChild(actions);
  776. }
  777. }
  778. body.appendChild(div);
  779. }
  780. scrollChatBottom();
  781. // 渲染消息内图表
  782. state.chat.messages.forEach((m, i) => {
  783. if (m.pending || !m.chart || m.chart.type === 'none' || !m.rows || !m.rows.length) return;
  784. const wrap = body.querySelector(`.chatbot-chart[data-idx="${i}"]`);
  785. if (!wrap) return;
  786. const col = (key) => (state.columns.find((c) => c.key === key) || { label: key, type: 'num' });
  787. const isDate = m.chart.x === 'date';
  788. const rows = m.rows.slice();
  789. if (isDate) rows.sort((a, b) => (String(a.date) < String(b.date) ? -1 : 1));
  790. const chart = echarts.init(wrap);
  791. chart.setOption({
  792. tooltip: { trigger: 'axis' },
  793. grid: { left: 56, right: 16, top: 20, bottom: m.chart.type === 'bar' && !isDate ? 52 : 24 },
  794. xAxis: {
  795. type: 'category',
  796. data: rows.map((r) => (isDate ? ymdToDash(r.date) : (r.shopName || r.shopId))),
  797. axisLabel: { color: '#6b6560', interval: 0, rotate: m.chart.type === 'bar' && !isDate ? 30 : 0, width: 80, overflow: 'truncate' },
  798. axisLine: { lineStyle: { color: '#e8e4df' } },
  799. },
  800. yAxis: { type: 'value', axisLabel: { color: '#6b6560' }, splitLine: { lineStyle: { color: '#f0ede8' } } },
  801. series: (m.chart.y || []).map((key, yi) => {
  802. const c = col(key);
  803. return {
  804. name: c.label || key,
  805. type: m.chart.type === 'line' ? 'line' : 'bar',
  806. smooth: true, barMaxWidth: 26,
  807. data: rows.map((r) => {
  808. const v = r[key];
  809. if (v == null || v === '') return 0;
  810. const n = Number(v);
  811. return c.type === 'pct' ? +(n * 100).toFixed(2) : n;
  812. }),
  813. itemStyle: { color: yi === 0 ? '#ff6b35' : '#2563eb' },
  814. };
  815. }),
  816. });
  817. setTimeout(() => chart.resize(), 40);
  818. });
  819. }
  820. function applyMsgQuery(idx) {
  821. const m = state.chat.messages[idx];
  822. const a = m && m.applied;
  823. if (!a) return;
  824. state.mode = ['detail', 'shop', 'date'].includes(a.mode) ? a.mode : 'shop';
  825. $('reportViewModes').querySelectorAll('button').forEach((b) => b.classList.toggle('active', b.dataset.mode === state.mode));
  826. state.preset = 'custom';
  827. $('reportRangePreset').value = 'custom';
  828. $('reportCustomRange').hidden = false;
  829. $('reportFromDate').value = ymdToDash(a.from);
  830. $('reportToDate').value = ymdToDash(a.to);
  831. state.shopFilter = new Set((a.shopIds || []).map(String));
  832. renderShopOptions();
  833. loadReport();
  834. const nav = document.querySelector('.nav-item[data-view="reports"]');
  835. if (nav) nav.click();
  836. }
  837. async function sendChat(text) {
  838. const q = String(text || '').trim();
  839. if (!q || state.chat.busy) return;
  840. state.chat.busy = true;
  841. state.chat.messages.push({ role: 'user', text: q });
  842. state.chat.messages.push({ role: 'assistant', pending: true });
  843. renderChatMessages();
  844. $('chatbotInput').value = '';
  845. try {
  846. const history = state.chat.messages
  847. .filter((m) => !m.pending && (m.role === 'user' || (m.role === 'assistant' && m.text)))
  848. .slice(0, -1)
  849. .slice(-8)
  850. .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 }));
  851. const result = await jsonFetch('/api/reports/ask', {
  852. method: 'POST',
  853. headers: { 'Content-Type': 'application/json' },
  854. body: JSON.stringify({ entity: state.entity, q, history }),
  855. });
  856. const pendingIdx = state.chat.messages.findIndex((m) => m.pending);
  857. const msg = {
  858. role: 'assistant',
  859. text: result.reply || '(模型未给出文字回答)',
  860. chart: result.chart,
  861. rows: result.rows,
  862. applied: result.applied,
  863. chartTitle: result.chartTitle,
  864. };
  865. if (pendingIdx >= 0) state.chat.messages.splice(pendingIdx, 1, msg);
  866. else state.chat.messages.push(msg);
  867. saveChatForEntity();
  868. } catch (e) {
  869. const pendingIdx = state.chat.messages.findIndex((m) => m.pending);
  870. const errMsg = { role: 'assistant', text: '出错了:' + e.message, error: true };
  871. if (pendingIdx >= 0) state.chat.messages.splice(pendingIdx, 1, errMsg);
  872. else state.chat.messages.push(errMsg);
  873. } finally {
  874. state.chat.busy = false;
  875. renderChatMessages();
  876. }
  877. }
  878. // ---------- 事件绑定 ----------
  879. function bindEvents() {
  880. $('btnReportRefresh').addEventListener('click', async () => {
  881. await refreshConn();
  882. await loadReport();
  883. showToast('已刷新');
  884. });
  885. $('btnClientHelp').addEventListener('click', (event) => {
  886. event.stopPropagation();
  887. const pop = $('clientHelpPopover');
  888. pop.hidden = !pop.hidden;
  889. $('btnClientHelp').classList.toggle('active', !pop.hidden);
  890. $('btnClientHelp').setAttribute('aria-expanded', String(!pop.hidden));
  891. });
  892. document.addEventListener('click', (event) => {
  893. const pop = $('clientHelpPopover');
  894. if (!pop.hidden && !event.target.closest('.conn-help-wrap')) {
  895. pop.hidden = true;
  896. $('btnClientHelp').classList.remove('active');
  897. $('btnClientHelp').setAttribute('aria-expanded', 'false');
  898. }
  899. });
  900. $('btnOpenSync').addEventListener('click', openSyncModal);
  901. $('btnCloseSync').addEventListener('click', () => {
  902. $('modalReportSync').hidden = true;
  903. if (state.syncPollTimer) { clearInterval(state.syncPollTimer); state.syncPollTimer = null; }
  904. $('syncProgressWrap').hidden = true;
  905. });
  906. $('btnCancelSync').addEventListener('click', () => $('modalReportSync').hidden = true);
  907. $('btnStartSync').addEventListener('click', startSync);
  908. $('btnSyncCancel').addEventListener('click', async () => {
  909. try { await jsonFetch('/api/reports/sync/cancel', { method: 'POST' }); showToast('已请求取消,等待当前步骤结束…'); } catch { /* ignore */ }
  910. });
  911. $('syncScope').addEventListener('change', () => {
  912. $('syncShopPickWrap').hidden = $('syncScope').value !== 'custom';
  913. });
  914. $('autoSyncEnabled').addEventListener('change', saveAutoSyncPrefs);
  915. $('autoSyncTime').addEventListener('change', saveAutoSyncPrefs);
  916. $('syncShopTrigger').addEventListener('click', () => toggleDropdown('syncShopMenu', 'syncShopTrigger'));
  917. $('syncShopMenu').addEventListener('click', makeDropdownHandler($('syncShopMenu'), state.syncShops, $('syncShopText'), '选择门店'));
  918. document.addEventListener('click', (event) => {
  919. if (!$('syncShopDropdown').contains(event.target)) toggleDropdown('syncShopMenu', 'syncShopTrigger', false);
  920. });
  921. $('reportRangePreset').addEventListener('change', () => {
  922. state.preset = $('reportRangePreset').value;
  923. $('reportCustomRange').hidden = state.preset !== 'custom';
  924. loadReport();
  925. });
  926. $('reportFromDate').addEventListener('change', loadReport);
  927. $('reportToDate').addEventListener('change', loadReport);
  928. $('reportShopTrigger').addEventListener('click', () => toggleDropdown('reportShopMenu', 'reportShopTrigger'));
  929. $('reportShopMenu').addEventListener('click', makeDropdownHandler($('reportShopMenu'), state.shopFilter, $('reportShopText'), '全部门店', loadReport));
  930. document.addEventListener('click', (event) => {
  931. if (!$('reportShopDropdown').contains(event.target)) toggleDropdown('reportShopMenu', 'reportShopTrigger', false);
  932. });
  933. $('reportViewModes').addEventListener('click', (event) => {
  934. const btn = event.target.closest('button[data-mode]');
  935. if (!btn) return;
  936. state.mode = btn.dataset.mode;
  937. $('reportViewModes').querySelectorAll('button').forEach((b) => b.classList.toggle('active', b === btn));
  938. state.sortKey = state.mode === 'detail' ? 'date' : (state.mode === 'shop' ? 'shopName' : 'date');
  939. state.sortDir = 'desc';
  940. loadReport();
  941. });
  942. let searchTimer = null;
  943. $('reportSearch').addEventListener('input', () => {
  944. clearTimeout(searchTimer);
  945. searchTimer = setTimeout(() => {
  946. state.q = $('reportSearch').value.trim();
  947. loadReport();
  948. }, 300);
  949. });
  950. $('btnColumnCfg').addEventListener('click', () => {
  951. renderColumnCfg();
  952. $('modalReportColumns').hidden = false;
  953. });
  954. $('btnCloseColumnCfg').addEventListener('click', () => $('modalReportColumns').hidden = true);
  955. $('btnApplyColumns').addEventListener('click', applyColumnCfg);
  956. $('btnResetColumns').addEventListener('click', () => {
  957. state.visible = new Set(state.columns.filter((c) => !c.reserved).map((c) => c.key));
  958. LS.set('shanReports.columns.v2', Array.from(state.visible));
  959. renderColumnCfg();
  960. renderTable();
  961. });
  962. $('btnExportCsv').addEventListener('click', exportCsv);
  963. $('btnExportHtml').addEventListener('click', exportHtml);
  964. $('reportTableHead').addEventListener('click', (event) => {
  965. const th = event.target.closest('th[data-key]');
  966. if (!th) return;
  967. const key = th.dataset.key;
  968. if (state.sortKey === key) state.sortDir = state.sortDir === 'asc' ? 'desc' : 'asc';
  969. else { state.sortKey = key; state.sortDir = 'desc'; }
  970. renderTable();
  971. });
  972. // 趋势图表
  973. $('analysisRangePreset').addEventListener('change', () => {
  974. state.analysisPreset = $('analysisRangePreset').value;
  975. anaCache = null;
  976. renderCharts();
  977. });
  978. $('anaShopTrigger').addEventListener('click', () => toggleDropdown('anaShopMenu', 'anaShopTrigger'));
  979. $('anaShopMenu').addEventListener('click', makeDropdownHandler($('anaShopMenu'), state.analysisShopFilter, $('anaShopText'), '全部门店', () => {
  980. anaCache = null;
  981. renderCharts();
  982. }));
  983. document.addEventListener('click', (event) => {
  984. if (!$('anaShopDropdown').contains(event.target)) toggleDropdown('anaShopMenu', 'anaShopTrigger', false);
  985. });
  986. $('chartMetric').addEventListener('change', () => {
  987. chartMetric = $('chartMetric').value || 'grossAmt';
  988. LS.set('shanReports.chartMetric', chartMetric);
  989. renderCharts();
  990. });
  991. $('anaComparePrev').addEventListener('change', renderCharts);
  992. // 智能问数机器人
  993. $('chatbotFab').addEventListener('click', () => setChatOpen(!state.chat.open));
  994. $('btnChatClose').addEventListener('click', () => setChatOpen(false));
  995. $('btnChatClear').addEventListener('click', () => {
  996. state.chat.messages = [];
  997. const all = LS.get(CHAT_LS_KEY, {});
  998. delete all[state.entity || '_'];
  999. LS.set(CHAT_LS_KEY, all);
  1000. renderChatMessages();
  1001. });
  1002. $('btnChatSend').addEventListener('click', () => sendChat($('chatbotInput').value));
  1003. $('chatbotInput').addEventListener('keydown', (event) => {
  1004. if (event.key === 'Enter') sendChat($('chatbotInput').value);
  1005. });
  1006. $('chatbotChips').addEventListener('click', (event) => {
  1007. const chip = event.target.closest('[data-q]');
  1008. if (chip) sendChat(chip.dataset.q);
  1009. });
  1010. window.addEventListener('resize', () => {
  1011. Object.values(chartInstances).forEach((c) => { if (c) c.resize(); });
  1012. });
  1013. }
  1014. // ---------- 初始化 ----------
  1015. window.shanReportsInit = async function () {
  1016. if (!state.inited) {
  1017. state.inited = true;
  1018. bindEvents();
  1019. try {
  1020. const data = await jsonFetch('/api/reports/columns');
  1021. state.columns = data.columns || [];
  1022. } catch { state.columns = []; }
  1023. loadColumnPrefs();
  1024. renderChartMetricSelect();
  1025. }
  1026. await refreshConn();
  1027. await loadReport();
  1028. };
  1029. window.shanAnalysisActivate = async function () {
  1030. await window.shanReportsInit();
  1031. renderChartMetricSelect();
  1032. await renderCharts();
  1033. Object.values(chartInstances).forEach((c) => { if (c) c.resize(); });
  1034. };
  1035. window.shanSetAnalysisVisible = function (visible) {
  1036. const fab = $('chatbotFab');
  1037. if (!fab) return;
  1038. fab.hidden = !visible;
  1039. if (!visible) setChatOpen(false);
  1040. };
  1041. })();