cockpit.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. 'use strict';
  2. // 经营驾驶舱:KPI + 趋势 / 门店排行 / 转化漏斗 / 收入结构
  3. // 数据来自 GET /api/ops/dashboard(服务端已按统一口径聚合)
  4. (function () {
  5. const $ = (id) => document.getElementById(id);
  6. const COLORS = { main: '#ff6b35', soft: '#ffb08a', grey: '#b8b2ad', green: '#2e7d4f', red: '#c0392b' };
  7. const KPI_DEFS = [
  8. { key: 'revenue', label: '营业额', unit: 'money' },
  9. { key: 'orders', label: '有效订单', unit: 'int' },
  10. { key: 'avgTicket', label: '客单价', unit: 'money' },
  11. { key: 'exposure', label: '曝光人数', unit: 'int' },
  12. { key: 'conversion', label: '进店转化率', unit: 'rate' },
  13. { key: 'rating', label: '店铺评分', unit: 'num' },
  14. ];
  15. const state = {
  16. inited: false,
  17. loading: false,
  18. data: null,
  19. from: '',
  20. to: '',
  21. schools: null,
  22. shops: null,
  23. charts: {},
  24. insightPoints: [],
  25. };
  26. function esc(value) {
  27. const div = document.createElement('div');
  28. div.textContent = String(value == null ? '' : value);
  29. return div.innerHTML;
  30. }
  31. function ymdToInput(ymd) {
  32. const s = String(ymd || '');
  33. return /^\d{8}$/.test(s) ? `${s.slice(0, 4)}-${s.slice(4, 6)}-${s.slice(6, 8)}` : '';
  34. }
  35. function inputToYmd(value) {
  36. return String(value || '').replace(/-/g, '');
  37. }
  38. function shortDate(ymd) {
  39. const s = String(ymd || '');
  40. return /^\d{8}$/.test(s) ? `${Number(s.slice(4, 6))}.${Number(s.slice(6, 8))}` : s;
  41. }
  42. function fmtValue(value, unit) {
  43. if (value === null || value === undefined) return '–';
  44. const n = Number(value);
  45. if (!Number.isFinite(n)) return '–';
  46. if (unit === 'rate') return (n * 100).toFixed(2) + '%';
  47. if (unit === 'num') return n.toFixed(2);
  48. if (unit === 'money') return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  49. return n.toLocaleString('zh-CN');
  50. }
  51. function fmtDelta(delta, unit) {
  52. if (delta === null || delta === undefined) return '<span class="ckpt-delta muted">—</span>';
  53. const up = delta > 0;
  54. const cls = delta === 0 ? 'muted' : (up ? 'up' : 'down');
  55. const arrow = delta === 0 ? '' : (up ? '↑' : '↓');
  56. const text = unit === 'pp' ? Math.abs(delta).toFixed(1) + 'pp' : Math.abs(delta).toFixed(1) + '%';
  57. return `<span class="ckpt-delta ${cls}">${arrow} ${text}</span>`;
  58. }
  59. async function api(url, options) {
  60. const res = await fetch(url, options);
  61. const body = await res.json().catch(() => null);
  62. return { res, body };
  63. }
  64. // ---------- 骨架 ----------
  65. function renderShell() {
  66. const root = $('cockpitRoot');
  67. if (!root) return;
  68. root.innerHTML = `
  69. <div class="ops-bar ckpt-bar">
  70. <div class="ops-bar-group">
  71. <span class="ops-bar-label">日期</span>
  72. <input type="date" class="ops-input" id="ckptFrom">
  73. <span class="ops-tilde">~</span>
  74. <input type="date" class="ops-input" id="ckptTo">
  75. </div>
  76. <div class="ops-bar-group"><span class="ops-bar-label">学校</span><div class="ops-multi" id="ckptSchool"></div></div>
  77. <div class="ops-bar-group"><span class="ops-bar-label">店铺</span><div class="ops-multi" id="ckptShop"></div></div>
  78. </div>
  79. <section class="ckpt-ai" id="ckptAi">
  80. <div class="ckpt-ai-head">
  81. <div class="ckpt-ai-title"><span class="ckpt-ai-badge">AI</span><h3>经营解读</h3><span class="ckpt-ai-meta" id="ckptAiMeta"></span></div>
  82. <div class="ckpt-ai-actions">
  83. <button class="btn btn-ghost btn-small" id="ckptAiCopy" hidden>复制</button>
  84. <button class="btn btn-primary btn-small" id="ckptAiBtn">生成解读</button>
  85. </div>
  86. </div>
  87. <div class="ckpt-ai-body" id="ckptAiBody">点击「生成解读」,模型会根据当前筛选范围的数据给出结论与建议。</div>
  88. </section>
  89. <div class="ckpt-kpis" id="ckptKpis"></div>
  90. <div class="ckpt-grid">
  91. <section class="ckpt-card"><div class="ckpt-card-head"><h3>营业额 / 订单趋势</h3><span id="ckptTrendNote"></span></div><div class="ckpt-chart" id="ckptTrend"></div></section>
  92. <section class="ckpt-card"><div class="ckpt-card-head"><h3>门店营业额 Top 10</h3><span></span></div><div class="ckpt-chart" id="ckptRank"></div></section>
  93. <section class="ckpt-card"><div class="ckpt-card-head"><h3>转化漏斗</h3><span>曝光 → 进店 → 下单</span></div><div class="ckpt-chart" id="ckptFunnel"></div></section>
  94. <section class="ckpt-card"><div class="ckpt-card-head"><h3>收入结构</h3><span>收入 / 支出 / 补贴</span></div><div class="ckpt-chart" id="ckptStructure"></div></section>
  95. </div>
  96. <div class="ckpt-empty" id="ckptEmpty" hidden>
  97. <p>所选范围没有数据</p>
  98. <small>调整日期,或换一个学校 / 店铺</small>
  99. </div>`;
  100. $('ckptAiBtn').addEventListener('click', () => requestInsight(true));
  101. $('ckptAiCopy').addEventListener('click', () => {
  102. const text = state.insightPoints.join('\n');
  103. if (!text) return;
  104. navigator.clipboard.writeText(text).then(() => {
  105. const btn = $('ckptAiCopy');
  106. btn.textContent = '已复制';
  107. setTimeout(() => { btn.textContent = '复制'; }, 1500);
  108. }).catch(() => {});
  109. });
  110. $('ckptFrom').addEventListener('change', (e) => { state.from = inputToYmd(e.target.value); loadData(); });
  111. $('ckptTo').addEventListener('change', (e) => { state.to = inputToYmd(e.target.value); loadData(); });
  112. state.charts.trend = echarts.init($('ckptTrend'));
  113. state.charts.rank = echarts.init($('ckptRank'));
  114. state.charts.funnel = echarts.init($('ckptFunnel'));
  115. state.charts.structure = echarts.init($('ckptStructure'));
  116. window.bindMultiSelectDismiss();
  117. window.addEventListener('resize', () => {
  118. Object.values(state.charts).forEach((chart) => chart && chart.resize());
  119. });
  120. }
  121. function mountFilters(summary) {
  122. const schools = (summary.schools || []).map((s) => ({ key: s.name, label: s.name, hint: `${s.shopCount} 家` }));
  123. window.createMultiSelect($('ckptSchool'), {
  124. label: '学校',
  125. items: schools,
  126. selected: state.schools ? [...state.schools] : [],
  127. allowEmpty: true,
  128. emptyLabel: '全部',
  129. onChange: (keys) => { state.schools = keys.length ? new Set(keys) : null; loadData(); },
  130. });
  131. const shops = (summary.shops || []).map((s) => ({
  132. key: String(s.key || s.shopId || ''),
  133. label: s.shopName || s.key,
  134. hint: s.school || '',
  135. })).filter((i) => i.key);
  136. window.createMultiSelect($('ckptShop'), {
  137. label: '店铺',
  138. items: shops,
  139. selected: state.shops ? [...state.shops] : [],
  140. allowEmpty: true,
  141. emptyLabel: '全部',
  142. onChange: (keys) => { state.shops = keys.length ? new Set(keys) : null; loadData(); },
  143. });
  144. }
  145. // ---------- 渲染 ----------
  146. function renderKpis(kpis) {
  147. const box = $('ckptKpis');
  148. if (!box) return;
  149. if (!kpis) {
  150. box.innerHTML = '';
  151. return;
  152. }
  153. box.innerHTML = KPI_DEFS.map((def) => {
  154. const item = kpis[def.key] || { value: null, delta: null, unit: def.unit };
  155. return `<div class="ckpt-kpi">
  156. <div class="ckpt-kpi-label">${def.label}</div>
  157. <div class="ckpt-kpi-value">${fmtValue(item.value, def.unit)}</div>
  158. <div class="ckpt-kpi-foot">${fmtDelta(item.delta, def.unit)}<span class="ckpt-kpi-hint">较上期</span></div>
  159. </div>`;
  160. }).join('');
  161. }
  162. function renderTrend(data) {
  163. const chart = state.charts.trend;
  164. const dates = data.trend.map((t) => shortDate(t.date));
  165. chart.setOption({
  166. grid: { left: 56, right: 52, top: 24, bottom: 32 },
  167. tooltip: { trigger: 'axis' },
  168. legend: { right: 0, top: 0, itemWidth: 10, itemHeight: 10, textStyle: { fontSize: 11 } },
  169. xAxis: { type: 'category', data: dates, axisLine: { lineStyle: { color: '#e5e0da' } }, axisTick: { show: false }, axisLabel: { color: '#8f8880' } },
  170. yAxis: [
  171. { type: 'value', splitLine: { lineStyle: { color: '#f2efea' } }, axisLabel: { color: '#8f8880' } },
  172. { type: 'value', splitLine: { show: false }, axisLabel: { color: '#8f8880' } },
  173. ],
  174. series: [
  175. { name: '营业额', type: 'bar', barMaxWidth: 28, itemStyle: { color: COLORS.main, borderRadius: [4, 4, 0, 0] }, data: data.trend.map((t) => t.revenue) },
  176. { name: '订单', type: 'line', yAxisIndex: 1, smooth: true, symbolSize: 6, lineStyle: { width: 2, color: '#7a9cc6' }, itemStyle: { color: '#7a9cc6' }, data: data.trend.map((t) => t.orders) },
  177. ],
  178. }, true);
  179. }
  180. function renderRanking(data) {
  181. const rows = data.ranking.slice().reverse();
  182. state.charts.rank.setOption({
  183. grid: { left: 8, right: 48, top: 10, bottom: 10, containLabel: true },
  184. tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
  185. xAxis: { type: 'value', splitLine: { lineStyle: { color: '#f2efea' } }, axisLabel: { color: '#8f8880' } },
  186. yAxis: {
  187. type: 'category',
  188. data: rows.map((r) => r.shopName),
  189. axisLine: { show: false },
  190. axisTick: { show: false },
  191. axisLabel: { color: '#5f5852', width: 150, overflow: 'truncate', fontSize: 11 },
  192. },
  193. series: [{
  194. type: 'bar',
  195. barMaxWidth: 16,
  196. itemStyle: { color: COLORS.soft, borderRadius: [0, 4, 4, 0] },
  197. label: {
  198. show: true,
  199. position: 'right',
  200. fontSize: 11,
  201. color: '#6f6862',
  202. formatter: (p) => Number(p.value).toLocaleString('zh-CN', { maximumFractionDigits: 0 }),
  203. },
  204. data: rows.map((r) => r.revenue),
  205. }],
  206. }, true);
  207. }
  208. function renderFunnel(data) {
  209. const f = data.funnel;
  210. const stages = [
  211. { name: '曝光', value: f.exposure },
  212. { name: '进店', value: f.visit },
  213. { name: '下单', value: f.order },
  214. ];
  215. const rate = (a, b) => (b > 0 ? ((a / b) * 100).toFixed(1) + '%' : '—');
  216. state.charts.funnel.setOption({
  217. tooltip: { trigger: 'item', formatter: (p) => `${p.name}:${Number(p.value).toLocaleString('zh-CN')}` },
  218. series: [{
  219. type: 'funnel',
  220. left: '8%',
  221. right: '8%',
  222. top: 16,
  223. bottom: 16,
  224. minSize: '28%',
  225. sort: 'descending',
  226. gap: 4,
  227. label: {
  228. show: true,
  229. position: 'inside',
  230. color: '#fff',
  231. fontSize: 12,
  232. formatter: (p) => `${p.name} ${Number(p.value).toLocaleString('zh-CN')}`,
  233. },
  234. itemStyle: { borderWidth: 0 },
  235. color: [COLORS.main, '#ff9a70', '#ffc4a8'],
  236. data: stages,
  237. }],
  238. graphic: [
  239. { type: 'text', right: 10, top: 8, style: { text: `进店 ${rate(f.visit, f.exposure)}`, fill: '#8f8880', fontSize: 11 } },
  240. { type: 'text', right: 10, bottom: 8, style: { text: `下单 ${rate(f.order, f.visit)}`, fill: '#8f8880', fontSize: 11 } },
  241. ],
  242. }, true);
  243. }
  244. function renderStructure(data) {
  245. const dates = data.structure.map((s) => shortDate(s.date));
  246. state.charts.structure.setOption({
  247. grid: { left: 56, right: 20, top: 28, bottom: 32 },
  248. tooltip: { trigger: 'axis' },
  249. legend: { right: 0, top: 0, itemWidth: 10, itemHeight: 10, textStyle: { fontSize: 11 } },
  250. xAxis: { type: 'category', data: dates, axisLine: { lineStyle: { color: '#e5e0da' } }, axisTick: { show: false }, axisLabel: { color: '#8f8880' } },
  251. yAxis: { type: 'value', splitLine: { lineStyle: { color: '#f2efea' } }, axisLabel: { color: '#8f8880' } },
  252. series: [
  253. { name: '收入', type: 'bar', barMaxWidth: 22, itemStyle: { color: COLORS.main, borderRadius: [3, 3, 0, 0] }, data: data.structure.map((s) => s.income) },
  254. { name: '支出', type: 'bar', barMaxWidth: 22, itemStyle: { color: '#c9c2ba', borderRadius: [3, 3, 0, 0] }, data: data.structure.map((s) => s.expense) },
  255. { name: '补贴', type: 'bar', barMaxWidth: 22, itemStyle: { color: '#ffd6c2', borderRadius: [3, 3, 0, 0] }, data: data.structure.map((s) => s.subsidy) },
  256. ],
  257. }, true);
  258. }
  259. // ---------- AI 解读 ----------
  260. async function requestInsight(refresh) {
  261. const body = $('ckptAiBody');
  262. const btn = $('ckptAiBtn');
  263. if (!body || !btn) return;
  264. btn.disabled = true;
  265. btn.textContent = '分析中…';
  266. body.innerHTML = '<span class="ckpt-ai-loading">AI 正在读取数据并生成结论…</span>';
  267. $('ckptAiMeta').textContent = '';
  268. $('ckptAiCopy').hidden = true;
  269. const payload = {
  270. from: state.from,
  271. to: state.to,
  272. schools: state.schools ? [...state.schools].join(',') : '',
  273. shops: state.shops ? [...state.shops].join(',') : '',
  274. refresh: !!refresh,
  275. };
  276. try {
  277. const { res, body: data } = await api('/api/ops/insights', {
  278. method: 'POST',
  279. headers: { 'Content-Type': 'application/json' },
  280. body: JSON.stringify(payload),
  281. });
  282. if (!res.ok) throw new Error((data && (data.detail || data.error)) || ('HTTP ' + res.status));
  283. if (data && data.enabled === false) {
  284. body.innerHTML = '未配置对话模型。请到「系统设置 → API 设置」选择对话模型并填写 Key,然后回到这里重新生成。';
  285. return;
  286. }
  287. if (data && data.note) {
  288. body.textContent = data.note;
  289. return;
  290. }
  291. const points = (data && data.points) || [];
  292. if (!points.length) {
  293. body.textContent = '模型没有返回有效结论,请稍后重试。';
  294. return;
  295. }
  296. state.insightPoints = points;
  297. body.innerHTML = `<ul class="ckpt-ai-list">${points.map((point) => `<li>${esc(point)}</li>`).join('')}</ul>`;
  298. const time = data.generatedAt ? new Date(data.generatedAt).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }) : '';
  299. $('ckptAiMeta').textContent = [data.model, time, data.cached ? '缓存' : ''].filter(Boolean).join(' · ');
  300. $('ckptAiCopy').hidden = false;
  301. } catch (e) {
  302. body.innerHTML = `<span class="ckpt-ai-error">生成失败:${esc(e.message || e)}</span>`;
  303. } finally {
  304. btn.disabled = false;
  305. btn.textContent = refresh ? '重新生成' : '生成解读';
  306. }
  307. }
  308. // ---------- 数据 ----------
  309. async function loadData() {
  310. if (state.loading) return;
  311. state.loading = true;
  312. const params = new URLSearchParams();
  313. if (state.from) params.set('from', state.from);
  314. if (state.to) params.set('to', state.to);
  315. if (state.schools && state.schools.size) params.set('schools', [...state.schools].join(','));
  316. if (state.shops && state.shops.size) params.set('shops', [...state.shops].join(','));
  317. try {
  318. const { res, body } = await api('/api/ops/dashboard?' + params.toString());
  319. if (!res.ok) throw new Error((body && (body.detail || body.error)) || ('HTTP ' + res.status));
  320. state.data = body;
  321. const empty = !body.kpis || !body.trend.length;
  322. $('ckptEmpty').hidden = !empty;
  323. $('ckptKpis').hidden = empty;
  324. document.querySelector('.ckpt-grid').hidden = empty;
  325. if (!empty) {
  326. state.from = body.from || state.from;
  327. state.to = body.to || state.to;
  328. $('ckptFrom').value = ymdToInput(state.from);
  329. $('ckptTo').value = ymdToInput(state.to);
  330. renderKpis(body.kpis);
  331. renderTrend(body);
  332. renderRanking(body);
  333. renderFunnel(body);
  334. renderStructure(body);
  335. $('ckptTrendNote').textContent = body.prev ? `对比 ${shortDate(body.prev.from)} ~ ${shortDate(body.prev.to)}` : '暂无上期可比';
  336. if (state.insightPoints.length) {
  337. state.insightPoints = [];
  338. $('ckptAiBody').innerHTML = '筛选范围已变化,点击「生成解读」重新分析。';
  339. $('ckptAiMeta').textContent = '';
  340. $('ckptAiCopy').hidden = true;
  341. }
  342. Object.values(state.charts).forEach((chart) => chart && chart.resize());
  343. }
  344. } catch (e) {
  345. $('ckptEmpty').hidden = false;
  346. $('ckptEmpty').querySelector('p').textContent = '驾驶舱加载失败';
  347. $('ckptEmpty').querySelector('small').textContent = e.message || String(e);
  348. } finally {
  349. state.loading = false;
  350. }
  351. }
  352. async function init() {
  353. if (state.inited) return;
  354. state.inited = true;
  355. renderShell();
  356. const { body } = await api('/api/ops/summary');
  357. const summary = body || { enabled: false, schools: [], shops: [] };
  358. if (summary.enabled) {
  359. if (summary.coverage) {
  360. state.from = summary.coverage.from || '';
  361. state.to = summary.coverage.to || '';
  362. $('ckptFrom').value = ymdToInput(state.from);
  363. $('ckptTo').value = ymdToInput(state.to);
  364. }
  365. mountFilters(summary);
  366. await loadData();
  367. } else {
  368. $('ckptEmpty').hidden = false;
  369. $('ckptEmpty').querySelector('p').textContent = '数据暂不可用';
  370. $('ckptEmpty').querySelector('small').textContent = summary.reason || '存储未连接';
  371. }
  372. }
  373. window.shanCockpitInit = function () {
  374. init();
  375. const refresh = $('btnCockpitRefresh');
  376. if (refresh && !refresh.dataset.bound) {
  377. refresh.dataset.bound = '1';
  378. refresh.addEventListener('click', () => loadData());
  379. }
  380. };
  381. })();