reports.js 58 KB

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