reports.js 47 KB

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