reports.js 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  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. // 明细浏览已挪到数据中台页,应用后跳到中台
  887. const nav = document.querySelector('.nav-item[data-view="lake"]');
  888. if (nav) nav.click();
  889. }
  890. async function sendChat(text) {
  891. const q = String(text || '').trim();
  892. if (!q || state.chat.busy) return;
  893. state.chat.busy = true;
  894. state.chat.messages.push({ role: 'user', text: q });
  895. state.chat.messages.push({ role: 'assistant', pending: true });
  896. renderChatMessages();
  897. $('chatbotInput').value = '';
  898. try {
  899. const history = state.chat.messages
  900. .filter((m) => !m.pending && (m.role === 'user' || (m.role === 'assistant' && m.text)))
  901. .slice(0, -1)
  902. .slice(-8)
  903. .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 }));
  904. const result = await jsonFetch('/api/reports/ask', {
  905. method: 'POST',
  906. headers: { 'Content-Type': 'application/json' },
  907. body: JSON.stringify({ entity: state.entity, q, history }),
  908. });
  909. const pendingIdx = state.chat.messages.findIndex((m) => m.pending);
  910. const msg = {
  911. role: 'assistant',
  912. text: result.reply || '(模型未给出文字回答)',
  913. chart: result.chart,
  914. rows: result.rows,
  915. applied: result.applied,
  916. chartTitle: result.chartTitle,
  917. };
  918. if (pendingIdx >= 0) state.chat.messages.splice(pendingIdx, 1, msg);
  919. else state.chat.messages.push(msg);
  920. saveChatForEntity();
  921. } catch (e) {
  922. const pendingIdx = state.chat.messages.findIndex((m) => m.pending);
  923. const errMsg = { role: 'assistant', text: '出错了:' + e.message, error: true };
  924. if (pendingIdx >= 0) state.chat.messages.splice(pendingIdx, 1, errMsg);
  925. else state.chat.messages.push(errMsg);
  926. } finally {
  927. state.chat.busy = false;
  928. renderChatMessages();
  929. }
  930. }
  931. // ---------- 事件绑定 ----------
  932. function bindEvents() {
  933. $('btnReportRefresh').addEventListener('click', async () => {
  934. await refreshConn();
  935. await loadReport();
  936. showToast('已刷新');
  937. });
  938. $('btnClientHelp').addEventListener('click', (event) => {
  939. event.stopPropagation();
  940. const pop = $('clientHelpPopover');
  941. pop.hidden = !pop.hidden;
  942. $('btnClientHelp').classList.toggle('active', !pop.hidden);
  943. $('btnClientHelp').setAttribute('aria-expanded', String(!pop.hidden));
  944. });
  945. document.addEventListener('click', (event) => {
  946. const pop = $('clientHelpPopover');
  947. if (!pop.hidden && !event.target.closest('.conn-help-wrap')) {
  948. pop.hidden = true;
  949. $('btnClientHelp').classList.remove('active');
  950. $('btnClientHelp').setAttribute('aria-expanded', 'false');
  951. }
  952. });
  953. $('btnOpenSync').addEventListener('click', openSyncModal);
  954. $('btnCloseSync').addEventListener('click', () => {
  955. $('modalReportSync').hidden = true;
  956. if (state.syncPollTimer) { clearInterval(state.syncPollTimer); state.syncPollTimer = null; }
  957. $('syncProgressWrap').hidden = true;
  958. });
  959. $('btnCancelSync').addEventListener('click', () => $('modalReportSync').hidden = true);
  960. $('btnStartSync').addEventListener('click', startSync);
  961. $('btnSyncCancel').addEventListener('click', async () => {
  962. try { await jsonFetch('/api/reports/sync/cancel', { method: 'POST' }); showToast('已请求取消,等待当前步骤结束…'); } catch { /* ignore */ }
  963. });
  964. $('syncScope').addEventListener('change', () => {
  965. $('syncShopPickWrap').hidden = $('syncScope').value !== 'custom';
  966. });
  967. $('autoSyncEnabled').addEventListener('change', saveAutoSyncPrefs);
  968. $('autoSyncTime').addEventListener('change', saveAutoSyncPrefs);
  969. $('syncShopTrigger').addEventListener('click', () => toggleDropdown('syncShopMenu', 'syncShopTrigger'));
  970. $('syncShopMenu').addEventListener('click', makeDropdownHandler($('syncShopMenu'), state.syncShops, $('syncShopText'), '选择门店'));
  971. document.addEventListener('click', (event) => {
  972. if (!$('syncShopDropdown').contains(event.target)) toggleDropdown('syncShopMenu', 'syncShopTrigger', false);
  973. });
  974. $('reportRangePreset').addEventListener('change', () => {
  975. state.preset = $('reportRangePreset').value;
  976. $('reportCustomRange').hidden = state.preset !== 'custom';
  977. loadReport();
  978. });
  979. $('reportFromDate').addEventListener('change', loadReport);
  980. $('reportToDate').addEventListener('change', loadReport);
  981. $('reportShopTrigger').addEventListener('click', () => toggleDropdown('reportShopMenu', 'reportShopTrigger'));
  982. $('reportShopMenu').addEventListener('click', makeDropdownHandler($('reportShopMenu'), state.shopFilter, $('reportShopText'), '全部门店', loadReport));
  983. document.addEventListener('click', (event) => {
  984. if (!$('reportShopDropdown').contains(event.target)) toggleDropdown('reportShopMenu', 'reportShopTrigger', false);
  985. });
  986. $('reportViewModes').addEventListener('click', (event) => {
  987. const btn = event.target.closest('button[data-mode]');
  988. if (!btn) return;
  989. state.mode = btn.dataset.mode;
  990. $('reportViewModes').querySelectorAll('button').forEach((b) => b.classList.toggle('active', b === btn));
  991. state.sortKey = state.mode === 'detail' ? 'date' : (state.mode === 'shop' ? 'shopName' : 'date');
  992. state.sortDir = 'desc';
  993. loadReport();
  994. });
  995. // 字段模式:报表列(语义列)/ 全部字段(明细 + 全部原始字段;聚合视图无 raw,自动回明细)
  996. $('reportFieldModes').addEventListener('click', (event) => {
  997. const btn = event.target.closest('button[data-fields]');
  998. if (!btn) return;
  999. state.rawView = btn.dataset.fields === 'all';
  1000. $('reportFieldModes').querySelectorAll('button').forEach((b) => b.classList.toggle('active', b === btn));
  1001. if (state.rawView && state.mode !== 'detail') {
  1002. state.mode = 'detail';
  1003. state.sortKey = 'date';
  1004. state.sortDir = 'desc';
  1005. $('reportViewModes').querySelectorAll('button').forEach((b) => b.classList.toggle('active', b.dataset.mode === 'detail'));
  1006. }
  1007. $('reportViewModes').querySelectorAll('button').forEach((b) => { b.disabled = state.rawView; });
  1008. $('btnColumnCfg').hidden = state.rawView; // 列设置只作用于报表列模式
  1009. state.sortKey = state.rawView ? 'date' : state.sortKey;
  1010. renderTable();
  1011. });
  1012. let searchTimer = null;
  1013. $('reportSearch').addEventListener('input', () => {
  1014. clearTimeout(searchTimer);
  1015. searchTimer = setTimeout(() => {
  1016. state.q = $('reportSearch').value.trim();
  1017. loadReport();
  1018. }, 300);
  1019. });
  1020. $('btnColumnCfg').addEventListener('click', () => {
  1021. renderColumnCfg();
  1022. $('modalReportColumns').hidden = false;
  1023. });
  1024. $('btnCloseColumnCfg').addEventListener('click', () => $('modalReportColumns').hidden = true);
  1025. $('btnApplyColumns').addEventListener('click', applyColumnCfg);
  1026. $('btnResetColumns').addEventListener('click', () => {
  1027. state.visible = new Set(state.columns.filter((c) => !c.reserved).map((c) => c.key));
  1028. LS.set('shanReports.columns.v2', Array.from(state.visible));
  1029. renderColumnCfg();
  1030. renderTable();
  1031. });
  1032. $('btnExportCsv').addEventListener('click', exportCsv);
  1033. $('btnExportHtml').addEventListener('click', exportHtml);
  1034. $('reportTableHead').addEventListener('click', (event) => {
  1035. const th = event.target.closest('th[data-key]');
  1036. if (!th) return;
  1037. const key = th.dataset.key;
  1038. if (state.sortKey === key) state.sortDir = state.sortDir === 'asc' ? 'desc' : 'asc';
  1039. else { state.sortKey = key; state.sortDir = 'desc'; }
  1040. renderTable();
  1041. });
  1042. // 趋势图表
  1043. $('analysisRangePreset').addEventListener('change', () => {
  1044. state.analysisPreset = $('analysisRangePreset').value;
  1045. anaCache = null;
  1046. renderCharts();
  1047. });
  1048. $('anaShopTrigger').addEventListener('click', () => toggleDropdown('anaShopMenu', 'anaShopTrigger'));
  1049. $('anaShopMenu').addEventListener('click', makeDropdownHandler($('anaShopMenu'), state.analysisShopFilter, $('anaShopText'), '全部门店', () => {
  1050. anaCache = null;
  1051. renderCharts();
  1052. }));
  1053. document.addEventListener('click', (event) => {
  1054. if (!$('anaShopDropdown').contains(event.target)) toggleDropdown('anaShopMenu', 'anaShopTrigger', false);
  1055. });
  1056. $('chartMetric').addEventListener('change', () => {
  1057. chartMetric = $('chartMetric').value || 'grossAmt';
  1058. LS.set('shanReports.chartMetric', chartMetric);
  1059. renderCharts();
  1060. });
  1061. $('anaComparePrev').addEventListener('change', renderCharts);
  1062. // 智能问数机器人
  1063. $('chatbotFab').addEventListener('click', () => setChatOpen(!state.chat.open));
  1064. $('btnChatClose').addEventListener('click', () => setChatOpen(false));
  1065. $('btnChatClear').addEventListener('click', () => {
  1066. state.chat.messages = [];
  1067. const all = LS.get(CHAT_LS_KEY, {});
  1068. delete all[state.entity || '_'];
  1069. LS.set(CHAT_LS_KEY, all);
  1070. renderChatMessages();
  1071. });
  1072. $('btnChatSend').addEventListener('click', () => sendChat($('chatbotInput').value));
  1073. $('chatbotInput').addEventListener('keydown', (event) => {
  1074. if (event.key === 'Enter') sendChat($('chatbotInput').value);
  1075. });
  1076. $('chatbotChips').addEventListener('click', (event) => {
  1077. const chip = event.target.closest('[data-q]');
  1078. if (chip) sendChat(chip.dataset.q);
  1079. });
  1080. window.addEventListener('resize', () => {
  1081. Object.values(chartInstances).forEach((c) => { if (c) c.resize(); });
  1082. });
  1083. }
  1084. // ---------- 同步历史(数据采集页) ----------
  1085. function renderSyncHistory() {
  1086. const tbody = $('syncHistoryRows');
  1087. if (!tbody) return;
  1088. if (!state.entity) {
  1089. tbody.innerHTML = '<tr><td colspan="7" class="empty-cell">暂无主体</td></tr>';
  1090. return;
  1091. }
  1092. jsonFetch(`/api/reports/syncs?entity=${encodeURIComponent(state.entity)}`)
  1093. .then((data) => {
  1094. const runs = (data.runs || []).slice(0, 8);
  1095. if (!runs.length) {
  1096. tbody.innerHTML = '<tr><td colspan="7" class="empty-cell">暂无同步记录</td></tr>';
  1097. return;
  1098. }
  1099. const SCOPE_LABEL = { all: '全主体', chain: '按连锁', shop: '按门店' };
  1100. tbody.innerHTML = runs.map((r) => {
  1101. const warn = (r.steps || []).filter((s) => !s.ok).length;
  1102. const note = r.cancelled ? '已取消' : (r.failed ? `${r.failed} 失败` : (warn ? `${warn} 步骤告警(含全零)` : '成功'));
  1103. const cls = r.cancelled || r.failed ? 'badge-fail' : (warn ? 'badge-warn' : 'badge-ok');
  1104. const t = r.at ? new Date(r.at) : null;
  1105. const ts = t ? `${t.getMonth() + 1}/${t.getDate()} ${String(t.getHours()).padStart(2, '0')}:${String(t.getMinutes()).padStart(2, '0')}` : '–';
  1106. return `<tr>
  1107. <td>${ts}</td>
  1108. <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>
  1109. <td>${SCOPE_LABEL[r.scope] || r.scope || '–'}</td>
  1110. <td class="num">${r.added ?? 0}</td>
  1111. <td class="num">${r.updated ?? 0}</td>
  1112. <td class="num">${r.failed ?? 0}</td>
  1113. <td><span class="badge ${cls}">${note}</span></td>
  1114. </tr>`;
  1115. }).join('');
  1116. })
  1117. .catch(() => {
  1118. tbody.innerHTML = '<tr><td colspan="7" class="empty-cell">同步历史加载失败</td></tr>';
  1119. });
  1120. }
  1121. // ---------- 初始化 ----------
  1122. // 数据采集页工具栏:推送当前主体到云端(本地湖 → 钉钉 AI 表格)
  1123. async function pushCurrentEntity() {
  1124. const badge = $('reportPushBadge');
  1125. const entity = state.entity || (state.entities[0] || {}).key;
  1126. if (!entity) {
  1127. badge.textContent = '暂无主体';
  1128. badge.className = 'badge badge-fail';
  1129. return;
  1130. }
  1131. if (window.shanAitableAction) {
  1132. try {
  1133. await window.shanAitableAction('push', 'reportPushBadge', { entity });
  1134. } catch { /* 徽标已由 aitableAction 写入 */ }
  1135. }
  1136. }
  1137. async function refreshPushBadge() {
  1138. const badge = $('reportPushBadge');
  1139. if (!badge) return;
  1140. try {
  1141. const res = await fetch('/api/reports/aitable/status');
  1142. const data = await res.json();
  1143. if (!data.enabled) {
  1144. badge.textContent = '云端未启用';
  1145. badge.className = 'badge badge-info';
  1146. } else if (!data.configured) {
  1147. badge.textContent = '云端配置不完整';
  1148. badge.className = 'badge badge-fail';
  1149. } else {
  1150. badge.textContent = '云端就绪';
  1151. badge.className = 'badge badge-ok';
  1152. }
  1153. } catch { /* 状态刷新失败不打扰 */ }
  1154. }
  1155. window.shanReportsInit = async function () {
  1156. if (!state.inited) {
  1157. state.inited = true;
  1158. bindEvents();
  1159. $('btnReportPush').addEventListener('click', pushCurrentEntity);
  1160. try {
  1161. const data = await jsonFetch('/api/reports/columns');
  1162. state.columns = data.columns || [];
  1163. } catch { state.columns = []; }
  1164. loadColumnPrefs();
  1165. renderChartMetricSelect();
  1166. }
  1167. await refreshConn();
  1168. refreshPushBadge();
  1169. renderSyncHistory();
  1170. await loadReport();
  1171. };
  1172. window.shanAnalysisActivate = async function () {
  1173. await window.shanReportsInit();
  1174. renderChartMetricSelect();
  1175. await renderCharts();
  1176. Object.values(chartInstances).forEach((c) => { if (c) c.resize(); });
  1177. };
  1178. window.shanSetAnalysisVisible = function (visible) {
  1179. const fab = $('chatbotFab');
  1180. if (!fab) return;
  1181. fab.hidden = !visible;
  1182. if (!visible) setChatOpen(false);
  1183. };
  1184. })();