reports.js 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  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. const saved = LS.get('shanReports.columns.v1', null);
  348. const defaults = new Set(state.columns.filter((c) => !c.reserved).map((c) => c.key));
  349. if (Array.isArray(saved)) {
  350. const valid = new Set(state.columns.map((c) => c.key));
  351. state.visible = new Set(saved.filter((k) => valid.has(k)));
  352. } else {
  353. state.visible = defaults;
  354. }
  355. if (!state.visible.size) state.visible = defaults;
  356. }
  357. function renderColumnCfg() {
  358. const list = $('columnCfgList');
  359. list.innerHTML = '';
  360. for (const c of state.columns) {
  361. if (c.locked) continue;
  362. const label = document.createElement('label');
  363. label.className = 'colcfg-item';
  364. const checked = state.visible.has(c.key) ? 'checked' : '';
  365. label.innerHTML = `<input type="checkbox" value="${c.key}" ${checked}><span></span>${c.reserved ? '<em class="colcfg-reserved">预留</em>' : ''}`;
  366. label.querySelector('span').textContent = c.label;
  367. list.appendChild(label);
  368. }
  369. }
  370. function applyColumnCfg() {
  371. const picks = new Set();
  372. $('columnCfgList').querySelectorAll('input[type=checkbox]').forEach((cb) => {
  373. if (cb.checked) picks.add(cb.value);
  374. });
  375. state.visible = picks;
  376. LS.set('shanReports.columns.v1', Array.from(picks));
  377. $('modalReportColumns').hidden = true;
  378. renderTable();
  379. }
  380. // ---------- 同步 ----------
  381. function renderSyncProgress(st) {
  382. const pct = st.planTotal ? Math.round((st.done / st.planTotal) * 100) : 0;
  383. $('syncProgressBar').style.width = pct + '%';
  384. $('syncProgressText').textContent = `${st.done} / ${st.planTotal}`;
  385. $('syncStatAdded').textContent = `新增 ${st.added}`;
  386. $('syncStatUpdated').textContent = `更新 ${st.updated}`;
  387. $('syncStatFailed').textContent = `失败 ${st.failed}`;
  388. const steps = (st.steps || []).slice(-8);
  389. $('syncSteps').innerHTML = steps.map((s) => {
  390. const cls = s.ok ? 'ok' : 'fail';
  391. const detail = s.ok ? `+${s.added}/~${s.updated}` : (s.error || '失败').slice(0, 60);
  392. return `<div class="sync-step ${cls}"><span></span><em>${detail}</em></div>`;
  393. }).join('');
  394. const stepNames = $('syncSteps').querySelectorAll('.sync-step span');
  395. steps.forEach((s, i) => { stepNames[i].textContent = s.label; });
  396. $('btnSyncCancel').hidden = !st.running;
  397. $('btnStartSync').disabled = !!st.running;
  398. $('btnStartSync').textContent = st.running ? '同步中…' : '开始同步';
  399. }
  400. function pollSyncStatus() {
  401. if (state.syncPollTimer) clearInterval(state.syncPollTimer);
  402. state.syncPollTimer = setInterval(async () => {
  403. try {
  404. const st = await jsonFetch('/api/reports/sync/status');
  405. renderSyncProgress(st);
  406. if (!st.running) {
  407. clearInterval(state.syncPollTimer);
  408. state.syncPollTimer = null;
  409. if (st.error) showToast('同步出错:' + st.error, 'error');
  410. else showToast(st.cancelled ? '同步已取消' : `同步完成:新增 ${st.added},更新 ${st.updated}`);
  411. refreshConn().then(loadReport);
  412. }
  413. } catch { /* 轮询失败忽略 */ }
  414. }, 900);
  415. }
  416. async function openSyncModal() {
  417. $('modalReportSync').hidden = false;
  418. $('syncEntityBadge').textContent = '识别主体中…';
  419. $('syncEntityBadge').className = 'badge badge-info';
  420. $('syncShopPickWrap').hidden = true;
  421. $('syncProgressWrap').hidden = true;
  422. try {
  423. const tree = await jsonFetch('/api/reports/tree');
  424. const badge = $('syncEntityBadge');
  425. badge.textContent = `当前主体:${(tree.entity && tree.entity.name) || (tree.merchant && tree.merchant.name) || '未知'} · 门店 ${(tree.shops || []).length} 家`;
  426. badge.className = 'badge badge-ok';
  427. if (tree.entity && tree.entity.key && tree.entity.key !== state.entity) {
  428. state.entity = tree.entity.key;
  429. LS.set('shanReports.entity', tree.entity.key);
  430. }
  431. await refreshConn();
  432. renderSyncShopOptions(tree.shops || []);
  433. } catch (e) {
  434. const badge = $('syncEntityBadge');
  435. badge.textContent = '未连接客户端:' + e.message;
  436. badge.className = 'badge badge-fail';
  437. try {
  438. const st = await jsonFetch('/api/reports/status');
  439. const napos = st.napos || {};
  440. $('syncHint').textContent = [napos.hint, napos.selfCheckUrl ? `自检:客户端带参启动后,用浏览器打开 ${napos.selfCheckUrl} 应看到一段 JSON。` : '']
  441. .filter(Boolean).join(' ');
  442. } catch { /* 服务不可达时保留默认文案 */ }
  443. }
  444. }
  445. function renderSyncShopOptions(shops) {
  446. state.syncShops.clear();
  447. fillShopMenu($('syncShopMenu'), shops);
  448. renderDropdownSelection($('syncShopMenu'), state.syncShops, $('syncShopText'), '选择门店');
  449. }
  450. async function startSync() {
  451. const scope = $('syncScope').value;
  452. const days = Number($('syncRange').value) || 30;
  453. const body = { from: daysAgoYmd(days), to: daysAgoYmd(1), scope: scope === 'custom' ? 'shop' : scope };
  454. if (scope === 'custom') {
  455. const shops = Array.from(state.syncShops).filter((v) => v !== '__all__');
  456. if (!shops.length) { showToast('请先选择要同步的门店', 'error'); return; }
  457. body.shopIds = shops;
  458. }
  459. try {
  460. await jsonFetch('/api/reports/sync', {
  461. method: 'POST',
  462. headers: { 'Content-Type': 'application/json' },
  463. body: JSON.stringify(body),
  464. });
  465. $('syncProgressWrap').hidden = false;
  466. renderSyncProgress({ planTotal: 0, done: 0, added: 0, updated: 0, failed: 0, steps: [], running: true });
  467. pollSyncStatus();
  468. } catch (e) {
  469. showToast('同步启动失败:' + e.message, 'error');
  470. }
  471. }
  472. // ---------- 导出 ----------
  473. function exportCsv() {
  474. if (!state.entity) { showToast('暂无主体可导出', 'error'); return; }
  475. const { from, to } = currentRange();
  476. let url = `/api/reports/export?entity=${encodeURIComponent(state.entity)}&from=${from}&to=${to}`;
  477. if (state.mode !== 'detail') url += `&group=${state.mode}`;
  478. if (state.shopFilter.size) url += `&shops=${encodeURIComponent(Array.from(state.shopFilter).join(','))}`;
  479. if (state.q) url += `&q=${encodeURIComponent(state.q)}`;
  480. window.location.href = url;
  481. }
  482. function exportHtml() {
  483. if (!state.entity) { showToast('暂无主体可导出', 'error'); return; }
  484. const { from, to } = analysisRange();
  485. window.open(`/api/reports/report-html?entity=${encodeURIComponent(state.entity)}&from=${from}&to=${to}`, '_blank');
  486. }
  487. // ---------- 趋势图表 ----------
  488. function chartCol(key) {
  489. return state.columns.find((c) => c.key === key) || { key, label: key, type: 'num' };
  490. }
  491. function ensureChart(instanceKey, domId) {
  492. if (typeof echarts === 'undefined') return null;
  493. const dom = $(domId);
  494. if (!dom) return null;
  495. if (!chartInstances[instanceKey]) chartInstances[instanceKey] = echarts.init(dom);
  496. return chartInstances[instanceKey];
  497. }
  498. function metricColumnOptions() {
  499. return state.columns.filter((c) => ['int', 'money', 'pct', 'num'].includes(c.type) && !c.reserved);
  500. }
  501. function renderChartMetricSelect() {
  502. const sel = $('chartMetric');
  503. if (!sel) return;
  504. sel.innerHTML = '';
  505. for (const c of metricColumnOptions()) {
  506. const opt = document.createElement('option');
  507. opt.value = c.key;
  508. opt.textContent = c.label;
  509. if (c.key === chartMetric) opt.selected = true;
  510. sel.appendChild(opt);
  511. }
  512. if (!sel.value && sel.options.length) sel.value = sel.options[0].value;
  513. chartMetric = sel.value || 'grossAmt';
  514. }
  515. const AXIS_TXT = { axisLabel: { color: '#6b6560' }, axisLine: { lineStyle: { color: '#e8e4df' } } };
  516. const SPLIT_LINE = { lineStyle: { color: '#f0ede8' } };
  517. const ACCENT = '#ff6b35';
  518. async function ensureAnalysisData() {
  519. const { from, to } = analysisRange();
  520. const shopSuffix = state.analysisShopFilter.size
  521. ? `&shops=${encodeURIComponent(Array.from(state.analysisShopFilter).join(','))}`
  522. : '';
  523. const key = [state.entity, from, to, state.analysisShopFilter.size ? [...state.analysisShopFilter].sort().join(',') : ''].join('|');
  524. if (anaCache && anaCache.key === key) return anaCache;
  525. const fd = (s) => new Date(Number(String(s).slice(0, 4)), Number(String(s).slice(4, 6)) - 1, Number(String(s).slice(6, 8)));
  526. const spanDays = Math.max(1, Math.round((fd(to) - fd(from)) / 86400000) + 1);
  527. const prevToD = fd(from);
  528. prevToD.setDate(prevToD.getDate() - 1);
  529. const prevTo = ymdLocal(prevToD);
  530. const prevFromD = new Date(prevToD);
  531. prevFromD.setDate(prevFromD.getDate() - (spanDays - 1));
  532. const prevFrom = ymdLocal(prevFromD);
  533. const base = `/api/reports/aggregate?entity=${encodeURIComponent(state.entity)}`;
  534. const [byDate, byDatePrev, byShop, topDaily] = await Promise.all([
  535. jsonFetch(`${base}&from=${from}&to=${to}&group=date${shopSuffix}`).then((d) => d.rows || []),
  536. jsonFetch(`${base}&from=${prevFrom}&to=${prevTo}&group=date${shopSuffix}`).then((d) => d.rows || []),
  537. jsonFetch(`${base}&from=${from}&to=${to}&group=shop${shopSuffix}`).then((d) => d.rows || []),
  538. jsonFetch(`/api/reports/daily?entity=${encodeURIComponent(state.entity)}&from=${from}&to=${to}&scope=shop${shopSuffix}`).then((d) => d.rows || []),
  539. ]);
  540. anaCache = { key, from, to, prevFrom, prevTo, byDate, byDatePrev, byShop, topDaily };
  541. return anaCache;
  542. }
  543. function renderDeltas(data) {
  544. const wrap = $('analysisDeltas');
  545. if (!wrap) return;
  546. wrap.innerHTML = '';
  547. const sum = (rows, f) => rows.reduce((a, r) => a + (Number(r[f]) || 0), 0);
  548. const wAvg = (rows, f, wb) => {
  549. let num = 0, den = 0;
  550. for (const r of rows) { const wt = Number(r[wb]) || 0; num += (Number(r[f]) || 0) * wt; den += wt; }
  551. return den > 0 ? num / den : 0;
  552. };
  553. const curOrders = sum(data.byDate, 'validOrderCnt');
  554. const prevOrders = sum(data.byDatePrev, 'validOrderCnt');
  555. const items = [
  556. { label: '营业额', cur: sum(data.byDate, 'grossAmt'), prev: sum(data.byDatePrev, 'grossAmt'), fmt: fmtMoney },
  557. { label: '有效订单', cur: curOrders, prev: prevOrders, fmt: fmtNum },
  558. { label: '收入', cur: sum(data.byDate, 'incomeAmt'), prev: sum(data.byDatePrev, 'incomeAmt'), fmt: fmtMoney },
  559. { label: '曝光人数', cur: sum(data.byDate, 'expUv'), prev: sum(data.byDatePrev, 'expUv'), fmt: fmtNum },
  560. { label: '下单人数', cur: sum(data.byDate, 'orderUserCnt'), prev: sum(data.byDatePrev, 'orderUserCnt'), fmt: fmtNum },
  561. { label: '进店转化率', cur: wAvg(data.byDate, 'clkExpRate', 'expUv'), prev: wAvg(data.byDatePrev, 'clkExpRate', 'expUv'), fmt: fmtPct },
  562. { label: '客单价', cur: curOrders > 0 ? sum(data.byDate, 'grossAmt') / curOrders : 0, prev: prevOrders > 0 ? sum(data.byDatePrev, 'grossAmt') / prevOrders : 0, fmt: fmtMoney },
  563. ];
  564. for (const it of items) {
  565. const cur = Math.round(it.cur * 100) / 100;
  566. const div = document.createElement('div');
  567. div.className = 'delta-card';
  568. let deltaHtml;
  569. const delta = it.prev > 0 ? (it.cur - it.prev) / it.prev : null;
  570. if (delta == null || !Number.isFinite(delta)) deltaHtml = '<span class="delta-none">上期无数据</span>';
  571. else if (Math.abs(delta) < 0.0001) deltaHtml = '<span class="delta-flat">持平</span>';
  572. else {
  573. const up = delta > 0;
  574. deltaHtml = `<span class="delta ${up ? 'up' : 'down'}">${up ? '↑' : '↓'} ${Math.abs(delta * 100).toFixed(1)}%</span>`
  575. + `<span class="delta-sub">vs 上期 ${it.fmt(Math.round(it.prev * 100) / 100)}</span>`;
  576. }
  577. div.innerHTML = `<span class="delta-label"></span><span class="delta-value"></span><span class="delta-line">${deltaHtml}</span>`;
  578. div.querySelector('.delta-label').textContent = it.label;
  579. div.querySelector('.delta-value').textContent = it.fmt(cur);
  580. wrap.appendChild(div);
  581. }
  582. }
  583. async function renderCharts() {
  584. let data;
  585. try { data = await ensureAnalysisData(); } catch { return; }
  586. renderDeltas(data);
  587. const col = chartCol(chartMetric);
  588. const compareOn = $('anaComparePrev') && $('anaComparePrev').checked;
  589. const trend = ensureChart('trend', 'chartTrend');
  590. if (trend) {
  591. const cur = data.byDate.slice().sort((a, b) => (a.date < b.date ? -1 : 1));
  592. const prev = data.byDatePrev.slice().sort((a, b) => (a.date < b.date ? -1 : 1));
  593. const xData = cur.map((r) => ymdToDash(r.date));
  594. const series = [{
  595. name: `本期·${col.label}`, type: 'line', smooth: true, symbolSize: 5,
  596. data: cur.map((r) => Number(r[chartMetric]) || 0),
  597. itemStyle: { color: ACCENT }, lineStyle: { width: 2.5 },
  598. areaStyle: { color: 'rgba(255,107,53,.08)' },
  599. }];
  600. if (compareOn && prev.length) {
  601. series.push({
  602. name: '上期同期', type: 'line', smooth: true,
  603. data: xData.map((_, i) => (prev[i] ? Number(prev[i][chartMetric]) || 0 : 0)),
  604. itemStyle: { color: '#a5a09a' }, lineStyle: { type: 'dashed', width: 1.6 }, symbol: 'none',
  605. });
  606. }
  607. trend.setOption({
  608. tooltip: { trigger: 'axis', valueFormatter: (v) => fmtByCol(col, v) },
  609. legend: { data: series.map((x) => x.name), top: 0, icon: 'roundRect', itemWidth: 14, itemHeight: 4, textStyle: { color: '#6b6560' } },
  610. grid: { left: 64, right: 24, top: 36, bottom: 30 },
  611. xAxis: { type: 'category', boundaryGap: false, data: xData, ...AXIS_TXT },
  612. yAxis: { type: 'value', axisLabel: { color: '#6b6560' }, splitLine: SPLIT_LINE },
  613. series,
  614. }, true);
  615. const title = $('anaTrendTitle');
  616. if (title) title.textContent = `主指标趋势 · ${col.label}(${ymdToDash(data.from)} ~ ${ymdToDash(data.to)})`;
  617. }
  618. const rank = ensureChart('rank', 'chartRank');
  619. if (rank) {
  620. const top = data.byShop.slice()
  621. .sort((a, b) => (Number(b[chartMetric]) || 0) - (Number(a[chartMetric]) || 0))
  622. .slice(0, 10).reverse();
  623. rank.setOption({
  624. tooltip: { trigger: 'axis', valueFormatter: (v) => fmtByCol(col, v) },
  625. grid: { left: 10, right: 34, top: 10, bottom: 24, containLabel: true },
  626. xAxis: { type: 'value', axisLabel: { color: '#6b6560' }, splitLine: SPLIT_LINE },
  627. yAxis: {
  628. type: 'category', data: top.map((r) => r.shopName || r.shopId),
  629. axisLabel: { color: '#2b2a28', width: 130, overflow: 'truncate' },
  630. axisLine: { lineStyle: { color: '#e8e4df' } },
  631. },
  632. series: [{ type: 'bar', barMaxWidth: 18, data: top.map((r) => Number(r[chartMetric]) || 0), itemStyle: { color: ACCENT, borderRadius: [0, 6, 6, 0] } }],
  633. }, true);
  634. }
  635. const funnel = ensureChart('funnel', 'chartFunnel');
  636. if (funnel) {
  637. const sum = (f) => data.byDate.reduce((a, r) => a + (Number(r[f]) || 0), 0);
  638. const expUv = sum('expUv');
  639. const enter = data.byDate.reduce((a, r) => a + (Number(r.expUv) || 0) * (Number(r.clkExpRate) || 0), 0);
  640. const order = sum('orderUserCnt');
  641. funnel.setOption({
  642. tooltip: { trigger: 'item', formatter: (p) => `${p.name}:${fmtNum(Math.round(p.value))} 人` },
  643. series: [{
  644. type: 'funnel', left: '8%', width: '84%', top: 12, bottom: 8, minSize: '20%',
  645. label: { color: '#fff', fontWeight: 600, formatter: (p) => `${p.name} ${fmtNum(Math.round(p.value))}` },
  646. data: [
  647. { name: '曝光人数', value: Math.round(expUv), itemStyle: { color: '#ffb199' } },
  648. { name: '进店人数', value: Math.round(enter), itemStyle: { color: '#ff8a5c' } },
  649. { name: '下单人数', value: Math.round(order), itemStyle: { color: ACCENT } },
  650. ],
  651. }],
  652. }, true);
  653. }
  654. const compare = ensureChart('compare', 'chartCompare');
  655. if (compare) {
  656. const top5 = data.byShop.slice()
  657. .sort((a, b) => (Number(b[chartMetric]) || 0) - (Number(a[chartMetric]) || 0))
  658. .slice(0, 5);
  659. const dates = [...new Set(data.topDaily.map((r) => r.date))].sort();
  660. const palette = ['#ff6b35', '#2563eb', '#1a8a4c', '#b8860b', '#8b5cf6'];
  661. const series = top5.map((shop, i) => ({
  662. name: shop.shopName || shop.shopId,
  663. type: 'line', smooth: true, symbolSize: 4,
  664. data: dates.map((d) => {
  665. const r = data.topDaily.find((x) => x.date === d && String(x.shopId) === String(shop.shopId));
  666. return r ? (Number(r[chartMetric]) || 0) : 0;
  667. }),
  668. itemStyle: { color: palette[i % palette.length] }, lineStyle: { width: 2 },
  669. }));
  670. compare.setOption({
  671. tooltip: { trigger: 'axis', valueFormatter: (v) => fmtByCol(col, v) },
  672. legend: { top: 0, type: 'scroll', icon: 'roundRect', itemWidth: 14, itemHeight: 4, textStyle: { color: '#6b6560' } },
  673. grid: { left: 64, right: 24, top: 36, bottom: 30 },
  674. xAxis: { type: 'category', boundaryGap: false, data: dates.map(ymdToDash), ...AXIS_TXT },
  675. yAxis: { type: 'value', axisLabel: { color: '#6b6560' }, splitLine: SPLIT_LINE },
  676. series,
  677. }, true);
  678. const title = $('anaCompareTitle');
  679. if (title) title.textContent = `门店对比 · Top ${top5.length}(${col.label})`;
  680. }
  681. }
  682. // ---------- 智能问数 · 机器人(仅经营分析页面) ----------
  683. function chatVisibleFor(view) { return view === 'reports' || view === 'analysis'; }
  684. function setChatOpen(open) {
  685. state.chat.open = open;
  686. $('chatbotPanel').hidden = !open;
  687. $('chatbotFab').classList.toggle('active', open);
  688. if (open) {
  689. $('chatbotFab').hidden = false;
  690. setTimeout(() => $('chatbotInput').focus(), 60);
  691. scrollChatBottom();
  692. }
  693. }
  694. function scrollChatBottom() {
  695. const body = $('chatbotBody');
  696. body.scrollTop = body.scrollHeight;
  697. }
  698. function renderChatMessages() {
  699. const body = $('chatbotBody');
  700. [...body.querySelectorAll('.chatbot-msg:not(.static)')].forEach((n) => n.remove());
  701. body.querySelectorAll('.chatbot-chips').forEach((n) => { n.hidden = state.chat.messages.length > 0; });
  702. for (let i = 0; i < state.chat.messages.length; i++) {
  703. const m = state.chat.messages[i];
  704. const div = document.createElement('div');
  705. div.className = 'chatbot-msg ' + (m.role === 'user' ? 'user' : 'bot');
  706. if (m.pending) {
  707. div.innerHTML = '<div class="chatbot-bubble typing"><span></span><span></span><span></span></div>';
  708. } else {
  709. const bubble = document.createElement('div');
  710. bubble.className = 'chatbot-bubble';
  711. bubble.textContent = m.text || '';
  712. div.appendChild(bubble);
  713. if (m.chart && m.chart.type !== 'none' && m.rows && m.rows.length) {
  714. const chartWrap = document.createElement('div');
  715. chartWrap.className = 'chatbot-chart';
  716. chartWrap.dataset.idx = String(i);
  717. div.appendChild(chartWrap);
  718. const actions = document.createElement('div');
  719. actions.className = 'chatbot-msg-actions';
  720. const applyBtn = document.createElement('button');
  721. applyBtn.type = 'button';
  722. applyBtn.className = 'btn btn-ghost btn-small';
  723. applyBtn.textContent = '应用到报表';
  724. applyBtn.addEventListener('click', () => applyMsgQuery(i));
  725. actions.appendChild(applyBtn);
  726. div.appendChild(actions);
  727. }
  728. }
  729. body.appendChild(div);
  730. }
  731. scrollChatBottom();
  732. // 渲染消息内图表
  733. state.chat.messages.forEach((m, i) => {
  734. if (m.pending || !m.chart || m.chart.type === 'none' || !m.rows || !m.rows.length) return;
  735. const wrap = body.querySelector(`.chatbot-chart[data-idx="${i}"]`);
  736. if (!wrap) return;
  737. const col = (key) => (state.columns.find((c) => c.key === key) || { label: key, type: 'num' });
  738. const isDate = m.chart.x === 'date';
  739. const rows = m.rows.slice();
  740. if (isDate) rows.sort((a, b) => (String(a.date) < String(b.date) ? -1 : 1));
  741. const chart = echarts.init(wrap);
  742. chart.setOption({
  743. tooltip: { trigger: 'axis' },
  744. grid: { left: 56, right: 16, top: 20, bottom: m.chart.type === 'bar' && !isDate ? 52 : 24 },
  745. xAxis: {
  746. type: 'category',
  747. data: rows.map((r) => (isDate ? ymdToDash(r.date) : (r.shopName || r.shopId))),
  748. axisLabel: { color: '#6b6560', interval: 0, rotate: m.chart.type === 'bar' && !isDate ? 30 : 0, width: 80, overflow: 'truncate' },
  749. axisLine: { lineStyle: { color: '#e8e4df' } },
  750. },
  751. yAxis: { type: 'value', axisLabel: { color: '#6b6560' }, splitLine: { lineStyle: { color: '#f0ede8' } } },
  752. series: (m.chart.y || []).map((key, yi) => {
  753. const c = col(key);
  754. return {
  755. name: c.label || key,
  756. type: m.chart.type === 'line' ? 'line' : 'bar',
  757. smooth: true, barMaxWidth: 26,
  758. data: rows.map((r) => {
  759. const v = r[key];
  760. if (v == null || v === '') return 0;
  761. const n = Number(v);
  762. return c.type === 'pct' ? +(n * 100).toFixed(2) : n;
  763. }),
  764. itemStyle: { color: yi === 0 ? '#ff6b35' : '#2563eb' },
  765. };
  766. }),
  767. });
  768. setTimeout(() => chart.resize(), 40);
  769. });
  770. }
  771. function applyMsgQuery(idx) {
  772. const m = state.chat.messages[idx];
  773. const a = m && m.applied;
  774. if (!a) return;
  775. state.mode = ['detail', 'shop', 'date'].includes(a.mode) ? a.mode : 'shop';
  776. $('reportViewModes').querySelectorAll('button').forEach((b) => b.classList.toggle('active', b.dataset.mode === state.mode));
  777. state.preset = 'custom';
  778. $('reportRangePreset').value = 'custom';
  779. $('reportCustomRange').hidden = false;
  780. $('reportFromDate').value = ymdToDash(a.from);
  781. $('reportToDate').value = ymdToDash(a.to);
  782. state.shopFilter = new Set((a.shopIds || []).map(String));
  783. renderShopOptions();
  784. loadReport();
  785. const nav = document.querySelector('.nav-item[data-view="reports"]');
  786. if (nav) nav.click();
  787. }
  788. async function sendChat(text) {
  789. const q = String(text || '').trim();
  790. if (!q || state.chat.busy) return;
  791. state.chat.busy = true;
  792. state.chat.messages.push({ role: 'user', text: q });
  793. state.chat.messages.push({ role: 'assistant', pending: true });
  794. renderChatMessages();
  795. $('chatbotInput').value = '';
  796. try {
  797. const history = state.chat.messages
  798. .filter((m) => !m.pending && (m.role === 'user' || (m.role === 'assistant' && m.text)))
  799. .slice(0, -1)
  800. .slice(-8)
  801. .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 }));
  802. const result = await jsonFetch('/api/reports/ask', {
  803. method: 'POST',
  804. headers: { 'Content-Type': 'application/json' },
  805. body: JSON.stringify({ entity: state.entity, q, history }),
  806. });
  807. const pendingIdx = state.chat.messages.findIndex((m) => m.pending);
  808. const msg = {
  809. role: 'assistant',
  810. text: result.reply || '(模型未给出文字回答)',
  811. chart: result.chart,
  812. rows: result.rows,
  813. applied: result.applied,
  814. chartTitle: result.chartTitle,
  815. };
  816. if (pendingIdx >= 0) state.chat.messages.splice(pendingIdx, 1, msg);
  817. else state.chat.messages.push(msg);
  818. } catch (e) {
  819. const pendingIdx = state.chat.messages.findIndex((m) => m.pending);
  820. const errMsg = { role: 'assistant', text: '出错了:' + e.message, error: true };
  821. if (pendingIdx >= 0) state.chat.messages.splice(pendingIdx, 1, errMsg);
  822. else state.chat.messages.push(errMsg);
  823. } finally {
  824. state.chat.busy = false;
  825. renderChatMessages();
  826. }
  827. }
  828. // ---------- 事件绑定 ----------
  829. function bindEvents() {
  830. $('btnReportRefresh').addEventListener('click', async () => {
  831. await refreshConn();
  832. await loadReport();
  833. showToast('已刷新');
  834. });
  835. $('btnClientHelp').addEventListener('click', (event) => {
  836. event.stopPropagation();
  837. const pop = $('clientHelpPopover');
  838. pop.hidden = !pop.hidden;
  839. $('btnClientHelp').classList.toggle('active', !pop.hidden);
  840. $('btnClientHelp').setAttribute('aria-expanded', String(!pop.hidden));
  841. });
  842. document.addEventListener('click', (event) => {
  843. const pop = $('clientHelpPopover');
  844. if (!pop.hidden && !event.target.closest('.conn-help-wrap')) {
  845. pop.hidden = true;
  846. $('btnClientHelp').classList.remove('active');
  847. $('btnClientHelp').setAttribute('aria-expanded', 'false');
  848. }
  849. });
  850. $('btnOpenSync').addEventListener('click', openSyncModal);
  851. $('btnCloseSync').addEventListener('click', () => {
  852. $('modalReportSync').hidden = true;
  853. if (state.syncPollTimer) { clearInterval(state.syncPollTimer); state.syncPollTimer = null; }
  854. $('syncProgressWrap').hidden = true;
  855. });
  856. $('btnCancelSync').addEventListener('click', () => $('modalReportSync').hidden = true);
  857. $('btnStartSync').addEventListener('click', startSync);
  858. $('btnSyncCancel').addEventListener('click', async () => {
  859. try { await jsonFetch('/api/reports/sync/cancel', { method: 'POST' }); showToast('已请求取消,等待当前步骤结束…'); } catch { /* ignore */ }
  860. });
  861. $('syncScope').addEventListener('change', () => {
  862. $('syncShopPickWrap').hidden = $('syncScope').value !== 'custom';
  863. });
  864. $('syncShopTrigger').addEventListener('click', () => toggleDropdown('syncShopMenu', 'syncShopTrigger'));
  865. $('syncShopMenu').addEventListener('click', makeDropdownHandler($('syncShopMenu'), state.syncShops, $('syncShopText'), '选择门店'));
  866. document.addEventListener('click', (event) => {
  867. if (!$('syncShopDropdown').contains(event.target)) toggleDropdown('syncShopMenu', 'syncShopTrigger', false);
  868. });
  869. $('reportRangePreset').addEventListener('change', () => {
  870. state.preset = $('reportRangePreset').value;
  871. $('reportCustomRange').hidden = state.preset !== 'custom';
  872. loadReport();
  873. });
  874. $('reportFromDate').addEventListener('change', loadReport);
  875. $('reportToDate').addEventListener('change', loadReport);
  876. $('reportShopTrigger').addEventListener('click', () => toggleDropdown('reportShopMenu', 'reportShopTrigger'));
  877. $('reportShopMenu').addEventListener('click', makeDropdownHandler($('reportShopMenu'), state.shopFilter, $('reportShopText'), '全部门店', loadReport));
  878. document.addEventListener('click', (event) => {
  879. if (!$('reportShopDropdown').contains(event.target)) toggleDropdown('reportShopMenu', 'reportShopTrigger', false);
  880. });
  881. $('reportViewModes').addEventListener('click', (event) => {
  882. const btn = event.target.closest('button[data-mode]');
  883. if (!btn) return;
  884. state.mode = btn.dataset.mode;
  885. $('reportViewModes').querySelectorAll('button').forEach((b) => b.classList.toggle('active', b === btn));
  886. state.sortKey = state.mode === 'detail' ? 'date' : (state.mode === 'shop' ? 'shopName' : 'date');
  887. state.sortDir = 'desc';
  888. loadReport();
  889. });
  890. let searchTimer = null;
  891. $('reportSearch').addEventListener('input', () => {
  892. clearTimeout(searchTimer);
  893. searchTimer = setTimeout(() => {
  894. state.q = $('reportSearch').value.trim();
  895. loadReport();
  896. }, 300);
  897. });
  898. $('btnColumnCfg').addEventListener('click', () => {
  899. renderColumnCfg();
  900. $('modalReportColumns').hidden = false;
  901. });
  902. $('btnCloseColumnCfg').addEventListener('click', () => $('modalReportColumns').hidden = true);
  903. $('btnApplyColumns').addEventListener('click', applyColumnCfg);
  904. $('btnResetColumns').addEventListener('click', () => {
  905. state.visible = new Set(state.columns.filter((c) => !c.reserved).map((c) => c.key));
  906. LS.set('shanReports.columns.v1', Array.from(state.visible));
  907. renderColumnCfg();
  908. renderTable();
  909. });
  910. $('btnExportCsv').addEventListener('click', exportCsv);
  911. $('btnExportHtml').addEventListener('click', exportHtml);
  912. $('reportTableHead').addEventListener('click', (event) => {
  913. const th = event.target.closest('th[data-key]');
  914. if (!th) return;
  915. const key = th.dataset.key;
  916. if (state.sortKey === key) state.sortDir = state.sortDir === 'asc' ? 'desc' : 'asc';
  917. else { state.sortKey = key; state.sortDir = 'desc'; }
  918. renderTable();
  919. });
  920. // 趋势图表
  921. $('analysisRangePreset').addEventListener('change', () => {
  922. state.analysisPreset = $('analysisRangePreset').value;
  923. anaCache = null;
  924. renderCharts();
  925. });
  926. $('anaShopTrigger').addEventListener('click', () => toggleDropdown('anaShopMenu', 'anaShopTrigger'));
  927. $('anaShopMenu').addEventListener('click', makeDropdownHandler($('anaShopMenu'), state.analysisShopFilter, $('anaShopText'), '全部门店', () => {
  928. anaCache = null;
  929. renderCharts();
  930. }));
  931. document.addEventListener('click', (event) => {
  932. if (!$('anaShopDropdown').contains(event.target)) toggleDropdown('anaShopMenu', 'anaShopTrigger', false);
  933. });
  934. $('chartMetric').addEventListener('change', () => {
  935. chartMetric = $('chartMetric').value || 'grossAmt';
  936. LS.set('shanReports.chartMetric', chartMetric);
  937. renderCharts();
  938. });
  939. $('anaComparePrev').addEventListener('change', renderCharts);
  940. // 智能问数机器人
  941. $('chatbotFab').addEventListener('click', () => setChatOpen(!state.chat.open));
  942. $('btnChatClose').addEventListener('click', () => setChatOpen(false));
  943. $('btnChatClear').addEventListener('click', () => {
  944. state.chat.messages = [];
  945. renderChatMessages();
  946. });
  947. $('btnChatSend').addEventListener('click', () => sendChat($('chatbotInput').value));
  948. $('chatbotInput').addEventListener('keydown', (event) => {
  949. if (event.key === 'Enter') sendChat($('chatbotInput').value);
  950. });
  951. $('chatbotChips').addEventListener('click', (event) => {
  952. const chip = event.target.closest('[data-q]');
  953. if (chip) sendChat(chip.dataset.q);
  954. });
  955. window.addEventListener('resize', () => {
  956. Object.values(chartInstances).forEach((c) => { if (c) c.resize(); });
  957. });
  958. }
  959. // ---------- 初始化 ----------
  960. window.shanReportsInit = async function () {
  961. if (!state.inited) {
  962. state.inited = true;
  963. bindEvents();
  964. try {
  965. const data = await jsonFetch('/api/reports/columns');
  966. state.columns = data.columns || [];
  967. } catch { state.columns = []; }
  968. loadColumnPrefs();
  969. renderChartMetricSelect();
  970. }
  971. await refreshConn();
  972. await loadReport();
  973. };
  974. window.shanAnalysisActivate = async function () {
  975. await window.shanReportsInit();
  976. renderChartMetricSelect();
  977. await renderCharts();
  978. Object.values(chartInstances).forEach((c) => { if (c) c.resize(); });
  979. };
  980. window.shanSetAnalysisVisible = function (visible) {
  981. const fab = $('chatbotFab');
  982. if (!fab) return;
  983. fab.hidden = !visible;
  984. if (!visible) setChatOpen(false);
  985. };
  986. })();