cockpit.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. };
  25. function esc(value) {
  26. const div = document.createElement('div');
  27. div.textContent = String(value == null ? '' : value);
  28. return div.innerHTML;
  29. }
  30. function ymdToInput(ymd) {
  31. const s = String(ymd || '');
  32. return /^\d{8}$/.test(s) ? `${s.slice(0, 4)}-${s.slice(4, 6)}-${s.slice(6, 8)}` : '';
  33. }
  34. function inputToYmd(value) {
  35. return String(value || '').replace(/-/g, '');
  36. }
  37. function shortDate(ymd) {
  38. const s = String(ymd || '');
  39. return /^\d{8}$/.test(s) ? `${Number(s.slice(4, 6))}.${Number(s.slice(6, 8))}` : s;
  40. }
  41. function fmtValue(value, unit) {
  42. if (value === null || value === undefined) return '–';
  43. const n = Number(value);
  44. if (!Number.isFinite(n)) return '–';
  45. if (unit === 'rate') return (n * 100).toFixed(2) + '%';
  46. if (unit === 'num') return n.toFixed(2);
  47. if (unit === 'money') return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  48. return n.toLocaleString('zh-CN');
  49. }
  50. function fmtDelta(delta, unit) {
  51. if (delta === null || delta === undefined) return '<span class="ckpt-delta muted">—</span>';
  52. const up = delta > 0;
  53. const cls = delta === 0 ? 'muted' : (up ? 'up' : 'down');
  54. const arrow = delta === 0 ? '' : (up ? '↑' : '↓');
  55. const text = unit === 'pp' ? Math.abs(delta).toFixed(1) + 'pp' : Math.abs(delta).toFixed(1) + '%';
  56. return `<span class="ckpt-delta ${cls}">${arrow} ${text}</span>`;
  57. }
  58. async function api(url) {
  59. const res = await fetch(url);
  60. const body = await res.json().catch(() => null);
  61. return { res, body };
  62. }
  63. // ---------- 骨架 ----------
  64. function renderShell() {
  65. const root = $('cockpitRoot');
  66. if (!root) return;
  67. root.innerHTML = `
  68. <div class="ops-bar ckpt-bar">
  69. <div class="ops-bar-group">
  70. <span class="ops-bar-label">日期</span>
  71. <input type="date" class="ops-input" id="ckptFrom">
  72. <span class="ops-tilde">~</span>
  73. <input type="date" class="ops-input" id="ckptTo">
  74. </div>
  75. <div class="ops-bar-group"><span class="ops-bar-label">学校</span><div class="ops-multi" id="ckptSchool"></div></div>
  76. <div class="ops-bar-group"><span class="ops-bar-label">店铺</span><div class="ops-multi" id="ckptShop"></div></div>
  77. </div>
  78. <div class="ckpt-kpis" id="ckptKpis"></div>
  79. <div class="ckpt-grid">
  80. <section class="ckpt-card"><div class="ckpt-card-head"><h3>营业额 / 订单趋势</h3><span id="ckptTrendNote"></span></div><div class="ckpt-chart" id="ckptTrend"></div></section>
  81. <section class="ckpt-card"><div class="ckpt-card-head"><h3>门店营业额 Top 10</h3><span></span></div><div class="ckpt-chart" id="ckptRank"></div></section>
  82. <section class="ckpt-card"><div class="ckpt-card-head"><h3>转化漏斗</h3><span>曝光 → 进店 → 下单</span></div><div class="ckpt-chart" id="ckptFunnel"></div></section>
  83. <section class="ckpt-card"><div class="ckpt-card-head"><h3>收入结构</h3><span>收入 / 支出 / 补贴</span></div><div class="ckpt-chart" id="ckptStructure"></div></section>
  84. </div>
  85. <div class="ckpt-empty" id="ckptEmpty" hidden>
  86. <p>所选范围没有数据</p>
  87. <small>调整日期,或换一个学校 / 店铺</small>
  88. </div>`;
  89. $('ckptFrom').addEventListener('change', (e) => { state.from = inputToYmd(e.target.value); loadData(); });
  90. $('ckptTo').addEventListener('change', (e) => { state.to = inputToYmd(e.target.value); loadData(); });
  91. state.charts.trend = echarts.init($('ckptTrend'));
  92. state.charts.rank = echarts.init($('ckptRank'));
  93. state.charts.funnel = echarts.init($('ckptFunnel'));
  94. state.charts.structure = echarts.init($('ckptStructure'));
  95. window.bindMultiSelectDismiss();
  96. window.addEventListener('resize', () => {
  97. Object.values(state.charts).forEach((chart) => chart && chart.resize());
  98. });
  99. }
  100. function mountFilters(summary) {
  101. const schools = (summary.schools || []).map((s) => ({ key: s.name, label: s.name, hint: `${s.shopCount} 家` }));
  102. window.createMultiSelect($('ckptSchool'), {
  103. label: '学校',
  104. items: schools,
  105. selected: state.schools ? [...state.schools] : [],
  106. allowEmpty: true,
  107. emptyLabel: '全部',
  108. onChange: (keys) => { state.schools = keys.length ? new Set(keys) : null; loadData(); },
  109. });
  110. const shops = (summary.shops || []).map((s) => ({
  111. key: String(s.key || s.shopId || ''),
  112. label: s.shopName || s.key,
  113. hint: s.school || '',
  114. })).filter((i) => i.key);
  115. window.createMultiSelect($('ckptShop'), {
  116. label: '店铺',
  117. items: shops,
  118. selected: state.shops ? [...state.shops] : [],
  119. allowEmpty: true,
  120. emptyLabel: '全部',
  121. onChange: (keys) => { state.shops = keys.length ? new Set(keys) : null; loadData(); },
  122. });
  123. }
  124. // ---------- 渲染 ----------
  125. function renderKpis(kpis) {
  126. const box = $('ckptKpis');
  127. if (!box) return;
  128. if (!kpis) {
  129. box.innerHTML = '';
  130. return;
  131. }
  132. box.innerHTML = KPI_DEFS.map((def) => {
  133. const item = kpis[def.key] || { value: null, delta: null, unit: def.unit };
  134. return `<div class="ckpt-kpi">
  135. <div class="ckpt-kpi-label">${def.label}</div>
  136. <div class="ckpt-kpi-value">${fmtValue(item.value, def.unit)}</div>
  137. <div class="ckpt-kpi-foot">${fmtDelta(item.delta, def.unit)}<span class="ckpt-kpi-hint">较上期</span></div>
  138. </div>`;
  139. }).join('');
  140. }
  141. function renderTrend(data) {
  142. const chart = state.charts.trend;
  143. const dates = data.trend.map((t) => shortDate(t.date));
  144. chart.setOption({
  145. grid: { left: 56, right: 52, top: 24, bottom: 32 },
  146. tooltip: { trigger: 'axis' },
  147. legend: { right: 0, top: 0, itemWidth: 10, itemHeight: 10, textStyle: { fontSize: 11 } },
  148. xAxis: { type: 'category', data: dates, axisLine: { lineStyle: { color: '#e5e0da' } }, axisTick: { show: false }, axisLabel: { color: '#8f8880' } },
  149. yAxis: [
  150. { type: 'value', splitLine: { lineStyle: { color: '#f2efea' } }, axisLabel: { color: '#8f8880' } },
  151. { type: 'value', splitLine: { show: false }, axisLabel: { color: '#8f8880' } },
  152. ],
  153. series: [
  154. { name: '营业额', type: 'bar', barMaxWidth: 28, itemStyle: { color: COLORS.main, borderRadius: [4, 4, 0, 0] }, data: data.trend.map((t) => t.revenue) },
  155. { name: '订单', type: 'line', yAxisIndex: 1, smooth: true, symbolSize: 6, lineStyle: { width: 2, color: '#7a9cc6' }, itemStyle: { color: '#7a9cc6' }, data: data.trend.map((t) => t.orders) },
  156. ],
  157. }, true);
  158. }
  159. function renderRanking(data) {
  160. const rows = data.ranking.slice().reverse();
  161. state.charts.rank.setOption({
  162. grid: { left: 8, right: 48, top: 10, bottom: 10, containLabel: true },
  163. tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
  164. xAxis: { type: 'value', splitLine: { lineStyle: { color: '#f2efea' } }, axisLabel: { color: '#8f8880' } },
  165. yAxis: {
  166. type: 'category',
  167. data: rows.map((r) => r.shopName),
  168. axisLine: { show: false },
  169. axisTick: { show: false },
  170. axisLabel: { color: '#5f5852', width: 150, overflow: 'truncate', fontSize: 11 },
  171. },
  172. series: [{
  173. type: 'bar',
  174. barMaxWidth: 16,
  175. itemStyle: { color: COLORS.soft, borderRadius: [0, 4, 4, 0] },
  176. label: {
  177. show: true,
  178. position: 'right',
  179. fontSize: 11,
  180. color: '#6f6862',
  181. formatter: (p) => Number(p.value).toLocaleString('zh-CN', { maximumFractionDigits: 0 }),
  182. },
  183. data: rows.map((r) => r.revenue),
  184. }],
  185. }, true);
  186. }
  187. function renderFunnel(data) {
  188. const f = data.funnel;
  189. const stages = [
  190. { name: '曝光', value: f.exposure },
  191. { name: '进店', value: f.visit },
  192. { name: '下单', value: f.order },
  193. ];
  194. const rate = (a, b) => (b > 0 ? ((a / b) * 100).toFixed(1) + '%' : '—');
  195. state.charts.funnel.setOption({
  196. tooltip: { trigger: 'item', formatter: (p) => `${p.name}:${Number(p.value).toLocaleString('zh-CN')}` },
  197. series: [{
  198. type: 'funnel',
  199. left: '8%',
  200. right: '8%',
  201. top: 16,
  202. bottom: 16,
  203. minSize: '28%',
  204. sort: 'descending',
  205. gap: 4,
  206. label: {
  207. show: true,
  208. position: 'inside',
  209. color: '#fff',
  210. fontSize: 12,
  211. formatter: (p) => `${p.name} ${Number(p.value).toLocaleString('zh-CN')}`,
  212. },
  213. itemStyle: { borderWidth: 0 },
  214. color: [COLORS.main, '#ff9a70', '#ffc4a8'],
  215. data: stages,
  216. }],
  217. graphic: [
  218. { type: 'text', right: 10, top: 8, style: { text: `进店 ${rate(f.visit, f.exposure)}`, fill: '#8f8880', fontSize: 11 } },
  219. { type: 'text', right: 10, bottom: 8, style: { text: `下单 ${rate(f.order, f.visit)}`, fill: '#8f8880', fontSize: 11 } },
  220. ],
  221. }, true);
  222. }
  223. function renderStructure(data) {
  224. const dates = data.structure.map((s) => shortDate(s.date));
  225. state.charts.structure.setOption({
  226. grid: { left: 56, right: 20, top: 28, bottom: 32 },
  227. tooltip: { trigger: 'axis' },
  228. legend: { right: 0, top: 0, itemWidth: 10, itemHeight: 10, textStyle: { fontSize: 11 } },
  229. xAxis: { type: 'category', data: dates, axisLine: { lineStyle: { color: '#e5e0da' } }, axisTick: { show: false }, axisLabel: { color: '#8f8880' } },
  230. yAxis: { type: 'value', splitLine: { lineStyle: { color: '#f2efea' } }, axisLabel: { color: '#8f8880' } },
  231. series: [
  232. { name: '收入', type: 'bar', barMaxWidth: 22, itemStyle: { color: COLORS.main, borderRadius: [3, 3, 0, 0] }, data: data.structure.map((s) => s.income) },
  233. { name: '支出', type: 'bar', barMaxWidth: 22, itemStyle: { color: '#c9c2ba', borderRadius: [3, 3, 0, 0] }, data: data.structure.map((s) => s.expense) },
  234. { name: '补贴', type: 'bar', barMaxWidth: 22, itemStyle: { color: '#ffd6c2', borderRadius: [3, 3, 0, 0] }, data: data.structure.map((s) => s.subsidy) },
  235. ],
  236. }, true);
  237. }
  238. // ---------- 数据 ----------
  239. async function loadData() {
  240. if (state.loading) return;
  241. state.loading = true;
  242. const params = new URLSearchParams();
  243. if (state.from) params.set('from', state.from);
  244. if (state.to) params.set('to', state.to);
  245. if (state.schools && state.schools.size) params.set('schools', [...state.schools].join(','));
  246. if (state.shops && state.shops.size) params.set('shops', [...state.shops].join(','));
  247. try {
  248. const { res, body } = await api('/api/ops/dashboard?' + params.toString());
  249. if (!res.ok) throw new Error((body && (body.detail || body.error)) || ('HTTP ' + res.status));
  250. state.data = body;
  251. const empty = !body.kpis || !body.trend.length;
  252. $('ckptEmpty').hidden = !empty;
  253. $('ckptKpis').hidden = empty;
  254. document.querySelector('.ckpt-grid').hidden = empty;
  255. if (!empty) {
  256. state.from = body.from || state.from;
  257. state.to = body.to || state.to;
  258. $('ckptFrom').value = ymdToInput(state.from);
  259. $('ckptTo').value = ymdToInput(state.to);
  260. renderKpis(body.kpis);
  261. renderTrend(body);
  262. renderRanking(body);
  263. renderFunnel(body);
  264. renderStructure(body);
  265. $('ckptTrendNote').textContent = body.prev ? `对比 ${shortDate(body.prev.from)} ~ ${shortDate(body.prev.to)}` : '暂无上期可比';
  266. Object.values(state.charts).forEach((chart) => chart && chart.resize());
  267. }
  268. } catch (e) {
  269. $('ckptEmpty').hidden = false;
  270. $('ckptEmpty').querySelector('p').textContent = '驾驶舱加载失败';
  271. $('ckptEmpty').querySelector('small').textContent = e.message || String(e);
  272. } finally {
  273. state.loading = false;
  274. }
  275. }
  276. async function init() {
  277. if (state.inited) return;
  278. state.inited = true;
  279. renderShell();
  280. const { body } = await api('/api/ops/summary');
  281. const summary = body || { enabled: false, schools: [], shops: [] };
  282. if (summary.enabled) {
  283. if (summary.coverage) {
  284. state.from = summary.coverage.from || '';
  285. state.to = summary.coverage.to || '';
  286. $('ckptFrom').value = ymdToInput(state.from);
  287. $('ckptTo').value = ymdToInput(state.to);
  288. }
  289. mountFilters(summary);
  290. await loadData();
  291. } else {
  292. $('ckptEmpty').hidden = false;
  293. $('ckptEmpty').querySelector('p').textContent = '数据暂不可用';
  294. $('ckptEmpty').querySelector('small').textContent = summary.reason || '存储未连接';
  295. }
  296. }
  297. window.shanCockpitInit = function () {
  298. init();
  299. const refresh = $('btnCockpitRefresh');
  300. if (refresh && !refresh.dataset.bound) {
  301. refresh.dataset.bound = '1';
  302. refresh.addEventListener('click', () => loadData());
  303. }
  304. };
  305. })();