reports.js 55 KB

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