@finebi/finebi-cli 1.6.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +8 -4
  2. package/package.json +1 -1
  3. package/skills/finebi-cli-agent/references/command-workflows.md +1 -1
  4. package/skills/finebi-cli-agent/references/web-app.md +9 -5
  5. package/skills/finebi-cli-agent/scripts/finebi-cli/package.json +1 -1
  6. package/skills/finebi-cli-agent/scripts/finebi-cli/src/app.js +8 -49
  7. package/skills/finebi-cli-agent/scripts/finebi-cli/src/help.js +2 -1
  8. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/AGENTS.md +8 -5
  9. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/README.md +8 -2
  10. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/docs/acceptance.md +67 -0
  11. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/docs/auth-and-deploy.md +2 -2
  12. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/docs/data-contract.md +38 -21
  13. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/docs/design.md +43 -2
  14. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/docs/filters.md +4 -0
  15. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/examples/cockpit.config.json +22 -0
  16. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/examples/retail.config.json +185 -0
  17. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/package-lock.json +2 -2
  18. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/package.json +3 -2
  19. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/scripts/dev-proxy.mjs +2 -1
  20. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/App.tsx +45 -20
  21. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/cockpit.css +3 -0
  22. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/Chart.tsx +24 -15
  23. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/DataTable.tsx +12 -5
  24. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/FilterBar.tsx +16 -10
  25. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/Insights.tsx +17 -0
  26. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/MonthPicker.tsx +32 -0
  27. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/OptionFilter.tsx +7 -0
  28. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/RangeFilter.tsx +9 -0
  29. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/Widget.tsx +23 -12
  30. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/calendar-locales.ts +3 -0
  31. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/charts/Bar.tsx +6 -0
  32. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/charts/Line.tsx +6 -0
  33. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/charts/Pie.tsx +6 -0
  34. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/month-picker.css +1 -0
  35. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/finebi/client.ts +15 -10
  36. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/finebi/config.d.ts +1 -0
  37. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/finebi/config.js +44 -0
  38. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/finebi/types.ts +2 -2
  39. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/retail.css +13 -0
  40. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/services/presentation.ts +36 -0
  41. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/services/table-data.ts +47 -0
  42. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/services/widget-queries.ts +18 -0
  43. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/browser/fixtures.mjs +28 -0
  44. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/browser/index.html +16 -0
  45. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/browser/main.tsx +149 -0
  46. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/browser/test-page.css +4 -0
  47. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/browser/vite.config.mjs +13 -0
  48. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/bundle.test.mjs +19 -0
  49. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/cockpit.test.mjs +73 -0
  50. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/proxy.test.mjs +12 -0
  51. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/retail.test.mjs +31 -0
  52. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/runtime.test.mjs +1 -1
  53. package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/vite.config.ts +2 -0
  54. package/src/app.js +8 -49
  55. package/src/help.js +2 -1
  56. package/templates/web-app/AGENTS.md +8 -5
  57. package/templates/web-app/README.md +8 -2
  58. package/templates/web-app/docs/acceptance.md +67 -0
  59. package/templates/web-app/docs/auth-and-deploy.md +2 -2
  60. package/templates/web-app/docs/data-contract.md +38 -21
  61. package/templates/web-app/docs/design.md +43 -2
  62. package/templates/web-app/docs/filters.md +4 -0
  63. package/templates/web-app/examples/cockpit.config.json +22 -0
  64. package/templates/web-app/examples/retail.config.json +185 -0
  65. package/templates/web-app/package-lock.json +2 -2
  66. package/templates/web-app/package.json +3 -2
  67. package/templates/web-app/scripts/dev-proxy.mjs +2 -1
  68. package/templates/web-app/src/App.tsx +45 -20
  69. package/templates/web-app/src/cockpit.css +3 -0
  70. package/templates/web-app/src/components/Chart.tsx +24 -15
  71. package/templates/web-app/src/components/DataTable.tsx +12 -5
  72. package/templates/web-app/src/components/FilterBar.tsx +16 -10
  73. package/templates/web-app/src/components/Insights.tsx +17 -0
  74. package/templates/web-app/src/components/MonthPicker.tsx +32 -0
  75. package/templates/web-app/src/components/OptionFilter.tsx +7 -0
  76. package/templates/web-app/src/components/RangeFilter.tsx +9 -0
  77. package/templates/web-app/src/components/Widget.tsx +23 -12
  78. package/templates/web-app/src/components/calendar-locales.ts +3 -0
  79. package/templates/web-app/src/components/charts/Bar.tsx +6 -0
  80. package/templates/web-app/src/components/charts/Line.tsx +6 -0
  81. package/templates/web-app/src/components/charts/Pie.tsx +6 -0
  82. package/templates/web-app/src/components/month-picker.css +1 -0
  83. package/templates/web-app/src/finebi/client.ts +15 -10
  84. package/templates/web-app/src/finebi/config.d.ts +1 -0
  85. package/templates/web-app/src/finebi/config.js +44 -0
  86. package/templates/web-app/src/finebi/types.ts +2 -2
  87. package/templates/web-app/src/retail.css +13 -0
  88. package/templates/web-app/src/services/presentation.ts +36 -0
  89. package/templates/web-app/src/services/table-data.ts +47 -0
  90. package/templates/web-app/src/services/widget-queries.ts +18 -0
  91. package/templates/web-app/tests/browser/fixtures.mjs +28 -0
  92. package/templates/web-app/tests/browser/index.html +16 -0
  93. package/templates/web-app/tests/browser/main.tsx +149 -0
  94. package/templates/web-app/tests/browser/test-page.css +4 -0
  95. package/templates/web-app/tests/browser/vite.config.mjs +13 -0
  96. package/templates/web-app/tests/bundle.test.mjs +19 -0
  97. package/templates/web-app/tests/cockpit.test.mjs +73 -0
  98. package/templates/web-app/tests/proxy.test.mjs +12 -0
  99. package/templates/web-app/tests/retail.test.mjs +31 -0
  100. package/templates/web-app/tests/runtime.test.mjs +1 -1
  101. package/templates/web-app/vite.config.ts +2 -0
@@ -0,0 +1,185 @@
1
+ {
2
+ "schemaVersion": "1",
3
+ "templateVersion": "0.3.0",
4
+ "title": "零售经营简报",
5
+ "description": "请根据同一来源的真实指标、字段和控件替换绑定。",
6
+ "basePath": "/webroot/decision",
7
+ "layout": "retail",
8
+ "dashboardId": "REPLACE_DASHBOARD_ID",
9
+ "directoryEntryId": "REPLACE_DIRECTORY_ENTRY_ID",
10
+ "maxRows": 1000,
11
+ "pageSize": 8,
12
+ "insights": false,
13
+ "widgets": [
14
+ {
15
+ "entryId": "REPLACE_ENTRY_1",
16
+ "name": "销售额",
17
+ "type": "kpi",
18
+ "description": "替换为已核实的源指标口径与范围。",
19
+ "filterNames": [],
20
+ "valueFieldId": "REPLACE_VALUE_1",
21
+ "valueFormat": "number"
22
+ },
23
+ {
24
+ "entryId": "REPLACE_ENTRY_2",
25
+ "name": "毛利",
26
+ "type": "kpi",
27
+ "description": "替换为已核实的源指标口径与范围。",
28
+ "filterNames": [],
29
+ "valueFieldId": "REPLACE_VALUE_2",
30
+ "valueFormat": "number"
31
+ },
32
+ {
33
+ "entryId": "REPLACE_ENTRY_3",
34
+ "name": "比率指标",
35
+ "type": "kpi",
36
+ "description": "替换为已核实的源指标口径与范围。",
37
+ "filterNames": [],
38
+ "valueFieldId": "REPLACE_VALUE_3",
39
+ "valueFormat": "percent"
40
+ },
41
+ {
42
+ "entryId": "REPLACE_ENTRY_4",
43
+ "name": "计数指标",
44
+ "type": "kpi",
45
+ "description": "替换为已核实的源指标口径与范围。",
46
+ "filterNames": [],
47
+ "valueFieldId": "REPLACE_VALUE_4",
48
+ "valueFormat": "number"
49
+ },
50
+ {
51
+ "entryId": "REPLACE_ENTRY_5",
52
+ "name": "销售与毛利趋势",
53
+ "type": "line",
54
+ "description": "替换为已核实的源指标口径与范围。",
55
+ "filterNames": [],
56
+ "categoryFieldId": "REPLACE_CATEGORY_5",
57
+ "valueFieldId": "REPLACE_VALUE_5",
58
+ "categoryFormat": "epoch-month",
59
+ "categoryTimeZone": "Asia/Shanghai",
60
+ "series": [
61
+ {
62
+ "fieldId": "REPLACE_SERIES_5_1",
63
+ "label": "销售额"
64
+ },
65
+ {
66
+ "fieldId": "REPLACE_SERIES_5_2",
67
+ "label": "毛利"
68
+ }
69
+ ]
70
+ },
71
+ {
72
+ "entryId": "REPLACE_ENTRY_6",
73
+ "name": "销售额 TOP10 门店",
74
+ "type": "bar",
75
+ "description": "替换为已核实的源指标口径与范围。",
76
+ "filterNames": [],
77
+ "categoryFieldId": "REPLACE_CATEGORY_6",
78
+ "valueFieldId": "REPLACE_VALUE_6"
79
+ },
80
+ {
81
+ "entryId": "REPLACE_ENTRY_7",
82
+ "name": "区域销售构成",
83
+ "type": "pie",
84
+ "description": "替换为已核实的源指标口径与范围。",
85
+ "filterNames": [],
86
+ "categoryFieldId": "REPLACE_CATEGORY_7",
87
+ "valueFieldId": "REPLACE_VALUE_7"
88
+ },
89
+ {
90
+ "entryId": "REPLACE_ENTRY_8",
91
+ "name": "品类销售额",
92
+ "type": "bar",
93
+ "description": "替换为已核实的源指标口径与范围。",
94
+ "filterNames": [],
95
+ "categoryFieldId": "REPLACE_CATEGORY_8",
96
+ "valueFieldId": "REPLACE_VALUE_8"
97
+ },
98
+ {
99
+ "entryId": "REPLACE_ENTRY_9",
100
+ "name": "自有店 / 管理店销售趋势",
101
+ "type": "line",
102
+ "description": "替换为已核实的源指标口径与范围。",
103
+ "filterNames": [],
104
+ "categoryFieldId": "REPLACE_CATEGORY_9",
105
+ "valueFieldId": "REPLACE_VALUE_9",
106
+ "categoryFormat": "epoch-month",
107
+ "categoryTimeZone": "Asia/Shanghai",
108
+ "series": [
109
+ {
110
+ "fieldId": "REPLACE_SERIES_9_1",
111
+ "label": "自有店"
112
+ },
113
+ {
114
+ "fieldId": "REPLACE_SERIES_9_2",
115
+ "label": "管理店"
116
+ }
117
+ ]
118
+ },
119
+ {
120
+ "entryId": "REPLACE_ENTRY_10",
121
+ "name": "生活馆 / 时尚馆销售趋势",
122
+ "type": "line",
123
+ "description": "替换为已核实的源指标口径与范围。",
124
+ "filterNames": [],
125
+ "categoryFieldId": "REPLACE_CATEGORY_10",
126
+ "valueFieldId": "REPLACE_VALUE_10",
127
+ "categoryFormat": "epoch-month",
128
+ "categoryTimeZone": "Asia/Shanghai",
129
+ "series": [
130
+ {
131
+ "fieldId": "REPLACE_SERIES_10_1",
132
+ "label": "生活馆"
133
+ },
134
+ {
135
+ "fieldId": "REPLACE_SERIES_10_2",
136
+ "label": "时尚馆"
137
+ }
138
+ ]
139
+ },
140
+ {
141
+ "entryId": "REPLACE_ENTRY_11",
142
+ "name": "门店风格构成",
143
+ "type": "pie",
144
+ "description": "替换为已核实的源指标口径与范围。",
145
+ "filterNames": [],
146
+ "categoryFieldId": "REPLACE_CATEGORY_11",
147
+ "valueFieldId": "REPLACE_VALUE_11"
148
+ },
149
+ {
150
+ "entryId": "REPLACE_ENTRY_12",
151
+ "name": "门店性质构成",
152
+ "type": "pie",
153
+ "description": "替换为已核实的源指标口径与范围。",
154
+ "filterNames": [],
155
+ "categoryFieldId": "REPLACE_CATEGORY_12",
156
+ "valueFieldId": "REPLACE_VALUE_12"
157
+ },
158
+ {
159
+ "entryId": "REPLACE_ENTRY_13",
160
+ "name": "门店经营明细",
161
+ "type": "table",
162
+ "description": "替换为已核实的源指标口径与范围。",
163
+ "filterNames": [],
164
+ "tableFieldIds": [
165
+ "REPLACE_TABLE_FIELD_1",
166
+ "REPLACE_TABLE_FIELD_2",
167
+ "REPLACE_TABLE_FIELD_3",
168
+ "REPLACE_TABLE_FIELD_4"
169
+ ],
170
+ "localFilterFieldIds": [
171
+ "REPLACE_TABLE_FIELD_1"
172
+ ]
173
+ }
174
+ ],
175
+ "filters": [
176
+ {
177
+ "name": "REPLACE_STORE_CONTROL",
178
+ "label": "店名(精确匹配)",
179
+ "type": "text"
180
+ }
181
+ ],
182
+ "dataNotes": [
183
+ "请填写已核实的来源、单位、期间、门店计数口径与控件作用范围。未确认公式时保留源指标名称。"
184
+ ]
185
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "finebi-web-app",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "finebi-web-app",
9
- "version": "0.2.0",
9
+ "version": "0.3.0",
10
10
  "dependencies": {
11
11
  "@rc-component/picker": "1.12.2",
12
12
  "antd": "6.6.7",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "finebi-web-app",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "engines": {"node": ">=18.17"},
@@ -8,7 +8,8 @@
8
8
  "dev": "vite --host 127.0.0.1",
9
9
  "build": "tsc --noEmit && vite build",
10
10
  "preview": "vite preview --host 127.0.0.1",
11
- "test": "node --test tests/*.test.mjs"
11
+ "test": "node --test tests/*.test.mjs",
12
+ "test:browser": "vite --config tests/browser/vite.config.mjs"
12
13
  },
13
14
  "dependencies": {"@rc-component/picker": "1.12.2", "antd": "6.6.7", "date-fns": "4.1.0", "echarts": "5.6.0", "react": "18.3.1", "react-dom": "18.3.1"},
14
15
  "devDependencies": {"@types/node": "22.13.10", "@types/react": "18.3.18", "@types/react-dom": "18.3.5", "typescript": "5.8.3", "vite": "5.4.21"}
@@ -31,6 +31,7 @@ export function createDevMiddleware(config, env = process.env, fetchImpl = fetch
31
31
  for await (const chunk of req) {raw+=chunk.toString();if (raw.length>65536) throw new Error('BODY_TOO_LARGE');}
32
32
  body=JSON.parse(raw);
33
33
  if (!Array.isArray(body.widgetIds) || !body.widgetIds.length || body.widgetIds.some(id=>!config.widgets.some(w=>w.entryId===id)) || !Number.isSafeInteger(body.pageLimit) || body.pageLimit<1 || body.pageLimit>config.maxRows) throw new Error('INVALID_REQUEST');
34
+ if(body.reportEntryId!==config.directoryEntryId)throw new Error('INVALID_SOURCE');
34
35
  validateRefer(config.filters || [],body.refer);
35
36
  } catch {return reply(res,400,'INVALID_REQUEST');}
36
37
  if (!env.FINEBI_DEV_BASE_URL) return reply(res,401,'AUTH_REQUIRED');
@@ -41,7 +42,7 @@ export function createDevMiddleware(config, env = process.env, fetchImpl = fetch
41
42
  const response=await fetchImpl(`${target.href.replace(/\/$/, '')}/v5/api/dashboard/report/${encodeURIComponent(config.dashboardId)}/widgets/query`, {
42
43
  method:'POST',redirect:'manual',signal:AbortSignal.timeout(30000),
43
44
  headers:{'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest',Cookie:`fine_auth_token=${auth}`},
44
- body:JSON.stringify({widgetIds:body.widgetIds,includeWidgetBean:true,pageLimit:body.pageLimit,refer:body.refer || {}}),
45
+ body:JSON.stringify({widgetIds:body.widgetIds,includeWidgetBean:true,pageLimit:body.pageLimit,refer:body.refer || {},...(config.directoryEntryId?{reportEntryId:config.directoryEntryId}:{})}),
45
46
  });
46
47
  if (response.status===401 || response.status>=300 && response.status<400 || response.headers.get('content-type')?.includes('text/html')) {token='';return reply(res,401,'AUTH_REQUIRED');}
47
48
  if (response.status===403) return reply(res,403,'PERMISSION_DENIED');
@@ -1,31 +1,56 @@
1
- import {useEffect, useState} from 'react';
2
- import {FineBIError, queryWidgets, validateConfig} from './finebi/client';
3
- import type {AppConfig, QueryResult, FilterState} from './finebi/types';
4
- import {Widget} from './components/Widget';
5
- import {FilterBar} from './components/FilterBar';
1
+ import {lazy,Suspense,useEffect,useRef,useState} from 'react';
2
+ import {queryWidget,validateConfig} from './finebi/client';
3
+ import type {AppConfig,FilterState,WidgetBinding} from './finebi/types';
4
+ import {Boundary,Widget} from './components/Widget';
5
+ import {Insights} from './components/Insights';
6
+ import {loadWidgets,widgetKey,type WidgetState} from './services/widget-queries';
7
+ import './cockpit.css';
8
+ import './retail.css';
9
+ const FilterBar=lazy(()=>import('./components/FilterBar').then(module=>({default:module.FilterBar})));
6
10
  function Dashboard({config}: {config: AppConfig}) {
7
- const [filters, setFilters] = useState<FilterState>({});
8
- const [refresh, setRefresh] = useState(0);
9
- const [state, setState] = useState<{loading:boolean; results?:Record<string,QueryResult>; error?:Error; at?:string}>({loading:true});
10
- useEffect(() => {
11
- const controller = new AbortController(); let current = true;
12
- setState({loading:true});
13
- queryWidgets(config, filters, controller.signal).then(results => {if(current) setState({loading:false,results,at:new Date().toLocaleTimeString()});}).catch(error => {if(current) setState({loading:false,error});});
14
- return () => {current=false;controller.abort();};
11
+ const [filters,setFilters]=useState<FilterState>({}),[refresh,setRefresh]=useState(0);
12
+ const [states,setStates]=useState<Record<string,WidgetState>>({});
13
+ const generation=useRef(0),retries=useRef(new Map<string,AbortController>());
14
+ useEffect(()=>{
15
+ const controller=new AbortController();generation.current++;setStates({});
16
+ void loadWidgets(config,filters,controller.signal,(key,state)=>setStates(old=>({...old,[key]:state})));
17
+ return ()=>{controller.abort();retries.current.forEach(c=>c.abort());retries.current.clear();};
15
18
  },[config,filters,refresh]);
19
+ const retry=async(binding:WidgetBinding,index:number)=>{
20
+ const key=widgetKey(binding,index),current=generation.current,controller=new AbortController();
21
+ retries.current.get(key)?.abort();retries.current.set(key,controller);
22
+ setStates(old=>({...old,[key]:{loading:true}}));
23
+ try {const result=await queryWidget(config,binding,filters,controller.signal);if(current===generation.current&&!controller.signal.aborted)setStates(old=>({...old,[key]:{loading:false,result,at:new Date().toLocaleTimeString()}}));}
24
+ catch(error){if(current===generation.current&&!controller.signal.aborted)setStates(old=>({...old,[key]:{loading:false,error:error as Error}}));}
25
+ };
26
+ const complete=Object.values(states).filter(s=>s.result).length,failed=Object.values(states).filter(s=>s.error).length;
27
+ const scope=Object.fromEntries(config.filters.map(filter=>{
28
+ const known=config.widgets.filter(w=>w.filterNames?.includes(filter.name)).map(w=>w.name);
29
+ const unknown=config.widgets.some(w=>w.filterNames===undefined);
30
+ return [filter.name,`${known.length?known.join('、'):'无已确认组件'}${unknown?';未映射组件由源看板决定':''}`];
31
+ }));
32
+ const retail=config.layout==='retail';
33
+ const card=(binding:WidgetBinding,index:number)=><Widget key={`${refresh}-${JSON.stringify(filters)}-${index}`} binding={binding} state={states[widgetKey(binding,index)]??{loading:true}} pageSize={config.pageSize} onRetry={()=>void retry(binding,index)} compact={retail}/>;
34
+ const cockpit=config.layout==='cockpit';
35
+ const separateKpis=cockpit||retail;
16
36
  return <div className={`app ${config.layout}`}>
17
- {config.layout==='workbench' && <aside><strong>FineBI</strong><a href="#dashboard">数据概览</a></aside>}
18
- <main id="dashboard"><header><div><span className="eyebrow">FINEBI · LIVE DATA</span><h1>{config.title}</h1><p className="muted">{state.at ? `最近更新 ${state.at}` : '连接 FineBI 数据'} · {config.widgets.length} 个展示组件</p></div><button onClick={()=>setRefresh(n=>n+1)}>刷新</button></header>
19
- {config.filters.length>0 && <FilterBar bindings={config.filters} onApply={setFilters}/>}
20
- {state.loading && <p className="state" role="status">正在获取实时数据…</p>}
21
- {state.error && <div className="state error" role="alert"><h2>{state.error instanceof FineBIError && state.error.code==='AUTH_REQUIRED'?'需要登录 FineBI':'数据暂不可用'}</h2><p>{state.error.message}</p><a href={config.basePath} target="_blank" rel="noreferrer">打开 FineBI</a><button onClick={()=>setRefresh(n=>n+1)}>重试</button></div>}
22
- {state.results && <><p className="live" role="status">实时数据已更新</p><div className="grid">{config.widgets.map((binding,i)=><Widget key={`${refresh}-${JSON.stringify(filters)}-${i}`} result={state.results![binding.entryId]} binding={binding} pageSize={config.pageSize}/>)}</div></>}
37
+ {retail&&<nav className="retail-nav" aria-label="页面导航"><a className="retail-brand" href="#dashboard"><b>F.</b><span>FineBI <small>经营简报</small></span></a><div><a href="#dashboard">经营概览</a><a href="#components">销售分析</a><a href="#data-notes">口径说明</a></div><span className="retail-live">动态数据</span></nav>}
38
+ {config.layout!=='overview'&&!retail&&<aside><strong>FineBI<span>数据应用</span></strong><nav><a href="#dashboard">数据概览</a><a href="#components">分析组件</a>{config.insights&&<a href="#observations">经营观察</a>}<a href="#data-notes">数据口径</a></nav><p className="source-label">{config.directoryEntryId?'目录发布来源':'分析主题来源'}<br/>访问者权限由 FineBI 控制</p></aside>}
39
+ <main id="dashboard"><header><div><span className="eyebrow">FINEBI · LIVE DATA</span><h1>{config.title}</h1><p className="muted">{config.description??'基于源看板的实时数据,按当前访问权限呈现'}</p></div><div className="header-actions"><a href={retail?'#data-notes':config.basePath} target={retail?undefined:'_blank'} rel="noreferrer">{retail?'口径说明':'打开 FineBI'}</a><button onClick={()=>setRefresh(n=>n+1)}>刷新数据</button></div></header>
40
+ {config.filters.length>0&&<Boundary><Suspense fallback={<p role="status">正在加载筛选控件…</p>}><FilterBar bindings={config.filters} onApply={setFilters} cockpit={cockpit} scope={scope} compact={retail}/></Suspense></Boundary>}
41
+ <p className="live query-status" role="status">{config.widgets.length} 个展示组件 · 已返回 {complete} · 失败 {failed} · 其余加载中或等待查询</p>
42
+ {retail&&<div className="section-heading"><span>01 / OVERVIEW</span><h2>经营概览</h2><p>源看板当前条件 · 随查询更新</p></div>}
43
+ {separateKpis&&<div className="kpi-grid">{config.widgets.map((binding,i)=>binding.type==='kpi'?card(binding,i):null)}</div>}
44
+ {config.insights&&<Insights config={config} states={states}/>}
45
+ {retail&&<div className="section-heading" id="components"><span>02 / PERFORMANCE</span><h2>销售表现</h2><p>趋势、构成与门店表现</p></div>}
46
+ <div className="grid" id={retail?undefined:'components'}>{config.widgets.map((binding,i)=>!separateKpis||binding.type!=='kpi'?card(binding,i):null)}</div>
47
+ <details className="data-notes" id="data-notes"><summary>数据口径与范围</summary><p>当前仅消费单次返回结果;COMPLETE 表示本次转换完整,不保证全量。搜索、排序、筛选、分页和 CSV 仅作用于已加载数据。UNKNOWN 行不自动累加,受限值与空值不补零。</p>{config.dataNotes?.map((note,i)=><p key={i}>{note}</p>)}<p>{config.directoryEntryId?'目录入口已绑定;查询失败不会切换到其他来源。':'来源为当前配置的分析看板。'}</p></details>
23
48
  <footer>数据范围以当前查询结果为准 · 权限由 FineBI 服务端控制</footer></main>
24
49
  </div>;
25
50
  }
26
51
  export default function App() {
27
52
  const [config, setConfig] = useState<AppConfig>(); const [error, setError] = useState('');
28
- useEffect(()=>{const controller=new AbortController(); fetch('./app-config.json',{signal:controller.signal,cache:'no-store'}).then(r=>{if(!r.ok)throw Error('应用配置加载失败');return r.json();}).then(c=>{validateConfig(c);if(!Number.isSafeInteger(c.pageSize)||c.pageSize<1||c.pageSize>100)throw Error('pageSize 必须在 1–100 范围内');if(!Array.isArray(c.filters))throw Error('filters 必须为数组');setConfig(c);}).catch(e=>{if(!controller.signal.aborted)setError(e.message);});return()=>controller.abort();},[]);
53
+ useEffect(()=>{const controller=new AbortController(); fetch('./app-config.json',{signal:controller.signal,cache:'no-store'}).then(r=>{if(!r.ok)throw Error('应用配置加载失败');return r.json();}).then(c=>{validateConfig(c);setConfig(c);}).catch(e=>{if(!controller.signal.aborted)setError(e.message);});return()=>controller.abort();},[]);
29
54
  if(error)return <main className="state" role="alert"><h1>请完成应用配置</h1><p>{error}</p><p>在 public/app-config.json 中绑定 CLI 发现的仪表板实例与字段。</p></main>;
30
55
  return config ? <Dashboard config={config}/> : <p className="state">正在加载应用…</p>;
31
56
  }
@@ -0,0 +1,3 @@
1
+ .panel-heading{display:flex;align-items:start;justify-content:space-between;gap:12px}.panel-heading h2{margin-bottom:6px}.component-status{font-size:10px;color:#71867d;white-space:nowrap}.component-status.failed{color:#bd534f}.result-range,.filter-scope{font-size:11px;color:#84928b;overflow-wrap:anywhere}.filter-scope{margin:4px 0 10px}.component-error{padding:14px 0;color:#af4e46;overflow-wrap:anywhere}.component-error button{color:#8f5044}.header-actions{display:flex;gap:18px;align-items:center;white-space:nowrap}.insight-panel{display:grid;grid-template-columns:220px minmax(0,1fr);gap:28px;background:#edf6f1;border:1px solid #dbece2;border-radius:15px;padding:24px;margin:24px 0}.insight-panel h2{margin:8px 0}.insight-panel p{font-size:12px;color:#6b8576}.insight-panel ul{margin:0;padding-left:18px;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px 24px;font-size:12px;color:#37604a}.data-notes{background:#fff;padding:20px 24px;border:1px solid #e2e8e3;border-radius:12px;margin-top:24px;font-size:12px}.sort-column{border:0;background:transparent;padding:0;font-weight:600;font-size:inherit}.local-filters,.series-controls{display:flex;flex-wrap:wrap;gap:14px;align-items:center;margin-bottom:16px}.local-filters label{font-size:12px;color:#64748b}.local-filters select{margin-left:8px;max-width:220px}.series-controls{font-size:12px}.series-controls label{display:flex;gap:6px;align-items:center}.workbench aside strong span{display:block;font-size:12px;font-weight:400}.source-label{font-size:11px;line-height:1.9;opacity:.65;margin-top:45px}
2
+ .cockpit{display:grid;grid-template-columns:208px minmax(0,1fr);min-height:100vh;background:#f3f6f3;color:#253f33}.cockpit aside{background:#123d2c;color:#e0ece4;padding:38px 24px;position:sticky;top:0;height:100vh;min-height:0;display:flex;flex-direction:column}.cockpit aside strong{font-size:27px;letter-spacing:-1px}.cockpit aside strong span{display:block;font-size:11px;letter-spacing:3px;font-weight:400;margin-top:3px;color:#b1c6b8}.cockpit aside nav{margin-top:48px}.cockpit aside a{display:block;font-size:13px;margin:8px -8px;padding:12px 16px;color:#c5d5ca;border-radius:8px;transition:background .15s}.cockpit aside a:hover{background:#ffffff10;color:white}.cockpit aside a:first-child{background:#ffffff13;color:#fff}.cockpit .source-label{margin-top:auto;padding-top:40px}.cockpit main{width:100%;max-width:1640px;padding:38px 40px}.cockpit header{padding-bottom:22px;border-bottom:1px solid #dfe8df;margin-bottom:26px}.cockpit h1{font-size:29px;letter-spacing:-.8px;margin:8px 0}.cockpit h2{font-size:15px;font-weight:650}.cockpit .eyebrow{font-size:10px;color:#659476;letter-spacing:2.5px}.cockpit .muted{font-size:12px;color:#839186}.cockpit a{color:#35775a}.cockpit button:hover{border-color:#197a58}.cockpit .header-actions>button{background:#197a58;border-color:#197a58;color:white;padding:10px 18px}.cockpit .grid{gap:20px}.cockpit .panel{border:1px solid #e0e8df;border-radius:14px;padding:24px;box-shadow:0 3px 12px #193f2103}.cockpit .kpi-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:18px}.cockpit .widget-kpi{position:relative;overflow:hidden}.cockpit .widget-kpi:before{content:'';position:absolute;top:0;left:0;right:0;height:3px;background:#448b64}.cockpit .widget-kpi:nth-child(2):before{background:#588db2}.cockpit .widget-kpi:nth-child(3):before{background:#d2ad60}.cockpit .widget-kpi:nth-child(4):before{background:#8f7db0}.cockpit .widget-kpi .panel-heading{display:block}.cockpit .widget-kpi .component-status{font-size:9px}.cockpit .kpi{font-size:clamp(22px,2.3vw,36px);color:#24533b;font-variant-numeric:tabular-nums;overflow-wrap:anywhere;margin:15px 0 6px}.cockpit .widget-kpi .result-range{font-size:9px}.cockpit .filter-card{border-color:#dfe8df;border-radius:14px}.cockpit .filter-symbol{color:#377d57;background:#edf5ef}.cockpit .filter-heading h2,.cockpit .filter-label-row label{color:#35533f}.cockpit .query-status{margin:18px 0;color:#6a8976;font-size:11px}.cockpit footer{font-size:11px;color:#8b9b8f}.cockpit .notice{border-radius:5px;font-size:11px}.cockpit .chart{height:290px}.cockpit th{background:#f5f8f4;color:#54725d}.cockpit tbody tr:hover{background:#f5f8f4}.cockpit .table-tools{font-size:11px;flex-wrap:wrap}.cockpit .table-tools input{max-width:220px}.cockpit .pager{font-size:12px}.cockpit .data-notes{color:#6d8171}
3
+ @media(min-width:1500px){.cockpit main{padding:42px 54px}}@media(max-width:1150px){.cockpit{grid-template-columns:170px minmax(0,1fr)}.cockpit main{padding:28px 24px}.cockpit .kpi-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.insight-panel{grid-template-columns:1fr;gap:8px}}@media(max-width:800px){.cockpit{grid-template-columns:1fr}.cockpit aside{display:none}.cockpit main{padding:24px 18px}.cockpit .grid{grid-template-columns:1fr}.cockpit header{align-items:flex-start;gap:20px;flex-direction:column}.cockpit h1{font-size:25px}.cockpit .filter-card{padding:20px 18px}.insight-panel ul{grid-template-columns:1fr}.cockpit .panel{padding:20px}.header-actions{font-size:12px}.local-filters{align-items:stretch;flex-direction:column}.cockpit .kpi-grid{gap:12px}.cockpit .kpi-grid .panel{padding:17px 14px}.cockpit .kpi{font-size:24px}.table-tools input{max-width:180px}.panel-heading{flex-wrap:wrap}.component-status{white-space:normal}}@media(prefers-reduced-motion:reduce){.cockpit *{transition:none!important;scroll-behavior:auto!important}}
@@ -1,31 +1,40 @@
1
1
  import {useEffect, useRef, useState} from 'react';
2
2
  import * as echarts from 'echarts/core';
3
- import {BarChart, LineChart, PieChart} from 'echarts/charts';
4
- import {GridComponent, TooltipComponent, LegendComponent} from 'echarts/components';
3
+ import {TooltipComponent} from 'echarts/components';
5
4
  import {CanvasRenderer} from 'echarts/renderers';
6
5
  import type {Dataset, WidgetBinding} from '../finebi/types';
7
- import {chartValues} from '../services/view-data';
8
- echarts.use([BarChart, LineChart, PieChart, GridComponent, TooltipComponent, LegendComponent, CanvasRenderer]);
6
+ import {chartValues,displayCell} from '../services/view-data';
7
+ import {formatCategory} from '../services/presentation';
8
+ echarts.use([TooltipComponent, CanvasRenderer]);
9
9
  export function Chart({dataset, binding}: {dataset: Dataset; binding: WidgetBinding}) {
10
10
  const container = useRef<HTMLDivElement>(null);
11
11
  const [order, setOrder] = useState('source');
12
- const values = chartValues(dataset, binding);
12
+ const [metric,setMetric]=useState(0),[hidden,setHidden]=useState<string[]>([]);
13
+ const series=binding.series??[{fieldId:binding.valueFieldId!,label:binding.name}];
14
+ const all=series.map(s=>({...s,values:chartValues(dataset,{categoryFieldId:binding.categoryFieldId,valueFieldId:s.fieldId})}));
15
+ const active=binding.type==='bar'?[all[metric]??all[0]]:all.filter(s=>!hidden.includes(s.fieldId));
16
+ const values=all[0].values;
13
17
  useEffect(() => {
14
18
  if (!container.current) return;
15
19
  const chart = echarts.init(container.current);
16
- const data = [...values];
17
- if (order !== 'source') data.sort((a, b) => a.value === null ? 1 : b.value === null ? -1 : (a.value - b.value) * (order === 'asc' ? 1 : -1));
20
+ const style=getComputedStyle(container.current);
21
+ const palette=['#197a58','#4988bd','#d6aa4e','#8b75b5','#ec4899'].map((color,i)=>style.getPropertyValue(`--chart-${i+1}`).trim()||color);
22
+ const categoryIndex=dataset.columns.findIndex(c=>c.fieldId===binding.categoryFieldId);
23
+ const categoryNames=dataset.rows.map(row=>formatCategory(row.cells[categoryIndex],binding));
24
+ const indices=values.map((_,i)=>i),ordered=active[0]?.values??values;
25
+ if(order!=='source')indices.sort((i,j)=>ordered[i].value===null?1:ordered[j].value===null?-1:(ordered[i].value!-ordered[j].value!)*(order==='asc'?1:-1));
18
26
  chart.setOption({
19
- color: ['#2563eb','#14b8a6','#f59e0b','#8b5cf6','#ec4899'],
27
+ color: palette,
20
28
  tooltip: {trigger: binding.type === 'pie' ? 'item' : 'axis', renderMode: 'richText'},
21
- legend: binding.type === 'pie' ? {bottom: 0} : undefined,
22
- grid: {left: 65, right: 24, top: 24, bottom: 65},
23
- xAxis: binding.type === 'pie' ? undefined : {type: 'category', data: data.map(d => d.name), axisLabel: {rotate: data.length > 8 ? 30 : 0}},
24
- yAxis: binding.type === 'pie' ? undefined : {type: 'value'},
25
- series: [{type: binding.type, data: binding.type === 'pie' ? data : data.map(d => d.value), radius: binding.type === 'pie' ? ['42%','67%'] : undefined}],
29
+ ...(binding.type === 'pie' ? {legend:{bottom:0}} : {
30
+ grid:{left:24,right:24,top:24,bottom:24,containLabel:true},
31
+ xAxis:{type:'category',data:indices.map(i=>categoryNames[i]),axisLabel:{rotate:values.length>8?30:0}},
32
+ yAxis:{type:'value'},
33
+ }),
34
+ series: active.map(s=>({name:s.label,type:binding.type,connectNulls:false,data:indices.map(i=>binding.type==='pie'?s.values[i]:s.values[i].value),radius:binding.type==='pie'?['42%','67%']:undefined})),
26
35
  });
27
36
  const observer = new ResizeObserver(() => chart.resize()); observer.observe(container.current);
28
37
  return () => {observer.disconnect(); chart.dispose();};
29
- }, [dataset, binding, order]);
30
- return <><label className="chart-sort">显示顺序 <select aria-label={`${binding.name}显示顺序`} value={order} onChange={e => setOrder(e.target.value)}><option value="source">查询顺序</option><option value="desc">已返回值降序</option><option value="asc">已返回值升序</option></select></label><div className="chart" ref={container} role="img" aria-label={binding.name}/><details><summary>查看图表数据</summary><table><tbody>{values.map((v,i) => <tr key={i}><td>{v.name}</td><td>{v.value ?? '不可用'}</td></tr>)}</tbody></table></details></>;
38
+ }, [dataset, binding, order,metric,hidden]);
39
+ return <>{all.length>1&&<div className="series-controls">{binding.type==='bar'?<label>显示指标 <select aria-label={`${binding.name}指标`} value={metric} onChange={e=>setMetric(Number(e.target.value))}>{all.map((s,i)=><option key={s.fieldId} value={i}>{s.label}</option>)}</select></label>:all.map(s=><label key={s.fieldId}><input type="checkbox" checked={!hidden.includes(s.fieldId)} onChange={e=>setHidden(old=>e.target.checked?old.filter(id=>id!==s.fieldId):[...old,s.fieldId])}/>{s.label}</label>)}</div>}<label className="chart-sort">显示顺序 <select aria-label={`${binding.name}显示顺序`} value={order} onChange={e => setOrder(e.target.value)}><option value="source">查询顺序</option><option value="desc">已返回值降序</option><option value="asc">已返回值升序</option></select></label><div className="chart" ref={container} role="img" aria-label={binding.name}/><details><summary>查看图表原始显示值(已加载结果)</summary><div className="table-scroll"><table><thead><tr>{dataset.columns.map(c=><th key={c.key}>{c.name}</th>)}</tr></thead><tbody>{dataset.rows.map((row,i)=><tr key={i}>{row.cells.map((cell,j)=><td key={j}>{displayCell(cell)}</td>)}</tr>)}</tbody></table></div></details></>;
31
40
  }
@@ -1,14 +1,21 @@
1
1
  import {useState} from 'react';
2
- import type {Dataset} from '../finebi/types';
2
+ import type {Dataset,WidgetBinding} from '../finebi/types';
3
3
  import {displayCell} from '../services/view-data';
4
- export function DataTable({dataset, pageSize}: {dataset: Dataset; pageSize: number}) {
4
+ import {fieldIndex,tableCsv,tableDataset,tableRows} from '../services/table-data';
5
+ export function DataTable({dataset, pageSize,binding}: {dataset: Dataset; pageSize: number;binding:WidgetBinding}) {
5
6
  const [search, setSearch] = useState('');
6
7
  const [page, setPage] = useState(0);
7
- const rows = dataset.rows.filter(row => row.cells.some(c => displayCell(c).toLocaleLowerCase().includes(search.toLocaleLowerCase())));
8
+ const [sort,setSort]=useState<{fieldId:string;direction:'asc'|'desc'}>();
9
+ const [filters,setFilters]=useState<Record<string,string>>({});
10
+ const visible=tableDataset(dataset,binding);
11
+ const rows=tableRows(dataset,{search,sort,filters});
12
+ const shown=tableDataset({...dataset,rows},binding).rows;
8
13
  const pages = Math.max(1, Math.ceil(rows.length / pageSize));
9
14
  const current = Math.min(page, pages - 1);
10
- return <><div className="table-tools"><label>搜索已加载数据 <input placeholder="搜索已加载数据" value={search} onChange={e => {setSearch(e.target.value);setPage(0);}}/></label><span>已加载 {dataset.returnedRowCount} 行 · 匹配 {rows.length} 行</span></div>
11
- <div className="table-scroll"><table><thead><tr><th>序号</th>{dataset.columns.map(c => <th key={c.key}>{c.name}</th>)}</tr></thead><tbody>{rows.slice(current * pageSize, (current + 1) * pageSize).map((row,i) => <tr key={current * pageSize + i}><td>{current * pageSize + i + 1}</td>{row.cells.map((c,j) => <td key={dataset.columns[j].key}>{displayCell(c)}</td>)}</tr>)}</tbody></table></div>
15
+ const download=()=>{const url=URL.createObjectURL(new Blob([tableCsv(visible,shown)],{type:'text/csv;charset=utf-8'}));const link=document.createElement('a');link.href=url;link.download='loaded-results.csv';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
16
+ return <><div className="table-tools"><label>搜索已加载数据 <input placeholder="搜索已加载数据" value={search} onChange={e => {setSearch(e.target.value);setPage(0);}}/></label><span>已加载 {dataset.returnedRowCount} 行 · 匹配 {rows.length} 行</span><button onClick={download}>导出匹配结果 CSV</button></div>
17
+ {(binding.localFilterFieldIds?.length??0)>0&&<div className="local-filters">{binding.localFilterFieldIds!.map(id=>{const index=fieldIndex(dataset,id);return <label key={id}>{dataset.columns[index].name}(已加载值)<select value={filters[id]??''} onChange={e=>{setFilters(old=>({...old,[id]:e.target.value}));setPage(0);}}><option value="">全部已加载值</option>{[...new Set(dataset.rows.map(row=>displayCell(row.cells[index])))].filter(Boolean).map(value=><option key={value}>{value}</option>)}</select></label>;})}</div>}
18
+ <div className="table-scroll"><table><thead><tr><th>序号</th>{visible.columns.map(c => <th key={c.key} aria-sort={sort?.fieldId===c.fieldId?(sort.direction==='asc'?'ascending':'descending'):'none'}><button className="sort-column" onClick={()=>{setSort({fieldId:c.fieldId,direction:sort?.fieldId===c.fieldId&&sort.direction==='asc'?'desc':'asc'});setPage(0);}}>{c.name} {sort?.fieldId===c.fieldId?(sort.direction==='asc'?'↑':'↓'):'↕'}</button></th>)}<th>行类型</th></tr></thead><tbody>{shown.slice(current * pageSize, (current + 1) * pageSize).map((row,i) => <tr key={current * pageSize + i}><td>{current * pageSize + i + 1}</td>{row.cells.map((c,j) => <td key={visible.columns[j].key}>{displayCell(c)}</td>)}<td>{row.kind==='DATA'?'数据':'UNKNOWN'}</td></tr>)}</tbody></table></div>
12
19
  {!rows.length && <p className="empty">没有匹配的数据</p>}
13
20
  <nav className="pager" aria-label="已加载数据分页"><button disabled={current===0} onClick={()=>setPage(current-1)}>上一页</button><span>{current+1} / {pages}</span><button disabled={current===pages-1} onClick={()=>setPage(current+1)}>下一页</button></nav></>;
14
21
  }
@@ -1,13 +1,18 @@
1
- import {useId, useState} from 'react';
2
- import {Alert, Button, Checkbox, ConfigProvider, DatePicker, Input, Select} from 'antd';
1
+ import {lazy, Suspense, useId, useState} from 'react';
2
+ import Alert from 'antd/es/alert';
3
+ import Button from 'antd/es/button';
4
+ import Checkbox from 'antd/es/checkbox';
5
+ import ConfigProvider from 'antd/es/config-provider';
6
+ import Input from 'antd/es/input';
3
7
  import zhCN from 'antd/locale/zh_CN';
4
- import {calendarConfig, calendarValue} from './calendar';
5
8
  import {encodeFilters} from '../finebi/filters.js';
6
9
  import type {FilterBinding, FilterState, FilterValue} from '../finebi/types';
10
+ import {MonthPicker} from './MonthPicker';
7
11
 
8
- const CalendarPicker = DatePicker.generatePicker<Date>(calendarConfig);
12
+ const RangeFilter=lazy(()=>import('./RangeFilter'));
13
+ const OptionFilter=lazy(()=>import('./OptionFilter'));
9
14
 
10
- export function FilterBar({bindings,onApply}: {bindings:FilterBinding[];onApply:(state:FilterState)=>void}) {
15
+ export function FilterBar({bindings,onApply,cockpit=false,scope,compact=false}: {bindings:FilterBinding[];onApply:(state:FilterState)=>void;cockpit?:boolean;scope?:Record<string,string>;compact?:boolean}) {
11
16
  const id=useId();
12
17
  const [draft,setDraft]=useState<FilterState>({});
13
18
  const [applied,setApplied]=useState<FilterState>({});
@@ -18,7 +23,7 @@ export function FilterBar({bindings,onApply}: {bindings:FilterBinding[];onApply:
18
23
  catch(e){setError((e as Error).message);}
19
24
  };
20
25
  const dirty=JSON.stringify(draft)!==JSON.stringify(applied);
21
- return <ConfigProvider locale={zhCN} theme={{token:{colorPrimary:'#2563eb',colorText:'#253858',colorBorder:'#dce4ef',borderRadius:10,controlHeightLG:46,fontFamily:'Inter,"Microsoft YaHei",system-ui,sans-serif'},components:{Select:{optionSelectedBg:'#edf4ff'},DatePicker:{cellActiveWithRangeBg:'#edf4ff'}}}}>
26
+ return <ConfigProvider locale={zhCN} theme={{token:{colorPrimary:cockpit?'#197a58':'#2563eb',colorText:'#253858',colorBorder:'#dce4ef',borderRadius:10,controlHeightLG:46,fontFamily:'Inter,"Microsoft YaHei",system-ui,sans-serif'},components:{Select:{optionSelectedBg:cockpit?'#eaf6ef':'#edf4ff'},DatePicker:{cellActiveWithRangeBg:cockpit?'#eaf6ef':'#edf4ff'}}}}>
22
27
  <form className="filter-card" onSubmit={e=>{e.preventDefault();apply(draft);}}>
23
28
  <div className="filter-heading"><div className="filter-heading-title"><span className="filter-symbol" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><path d="M4 7h16M7 12h10M10 17h4"/></svg></span><div><h2>筛选条件</h2><p>选择筛选条件,查看对应的数据</p></div></div><span className={`filter-status ${dirty?'pending':''}`}>{dirty?'待应用':'当前条件已应用'}</span></div>
24
29
  <div className="filter-fields">{bindings.map((binding,index)=>{
@@ -26,13 +31,14 @@ export function FilterBar({bindings,onApply}: {bindings:FilterBinding[];onApply:
26
31
  const isRange=type==='date-range'||type==='month-range';
27
32
  const interval=value && typeof value==='object' && !Array.isArray(value)?value:{start:'',end:''};
28
33
  const fieldId=`${id}-filter-${index}`;
29
- const updateRange=(_dates:unknown,strings:[string,string]|null)=>update(binding.name,{start:strings?.[0]||'',end:strings?.[1]||''});
30
34
  return <div className={`filter-field ${isRange?'date-field':''}`} key={binding.name}>
31
35
  <div className="filter-label-row"><label htmlFor={isRange?fieldId+'-start':fieldId}>{binding.label}<span>{type==='multi-select'?'可多选':type==='month-range'?'按起止月份筛选':isRange?'按起止日期筛选':''}</span></label><button className="field-reset" type="button" aria-label={`恢复${binding.label}默认`} onClick={()=>update(binding.name,'')}>重置</button></div>
32
- {isRange ? <><label className="sr-only" htmlFor={fieldId+'-start'}>{binding.label}开始日期</label><label className="sr-only" htmlFor={fieldId+'-end'}>{binding.label}结束日期</label><CalendarPicker.RangePicker size="large" className="filter-date-range" id={{start:fieldId+'-start',end:fieldId+'-end'}} picker={type==='month-range'?'month':'date'} format={type==='month-range'?'YYYY-MM':'YYYY-MM-DD'} placeholder={type==='month-range'?['开始月份','结束月份']:['开始日期','结束日期']} allowEmpty={[true,true]} allowClear value={[calendarValue(interval.start),calendarValue(interval.end)]} minDate={calendarValue('0001-01-01')!} maxDate={calendarValue('9999-12-31')!} onCalendarChange={updateRange} onChange={updateRange} onKeyDown={e=>{if(e.key==='Enter')e.preventDefault();}}/></>
33
- : binding.options ? <Select id={fieldId} aria-label={binding.label} size="large" className="filter-select" mode={type==='multi-select'?'multiple':undefined} allowClear showSearch={{optionFilterProp:'label'}} maxTagCount="responsive" placeholder={`选择${binding.label},支持搜索`} options={binding.options} disabled={value===null} value={type==='multi-select'?(Array.isArray(value)?value:[]):text||undefined} onChange={selected=>update(binding.name,selected??'')} notFoundContent={`没有匹配的${binding.label}`}/>
34
- : <Input id={fieldId} aria-label={binding.label} size="large" type={type==='date'?'date':type==='month'?'month':'text'} min={type==='date'?'0001-01-01':type==='month'?'0001-01':undefined} max={type==='date'?'9999-12-31':type==='month'?'9999-12':undefined} inputMode={type==='number'?'decimal':undefined} placeholder={type==='quarter'?'YYYY-Q,例如 2026-3':type==='year'?'YYYY':type==='text'?'输入精确匹配值':undefined} disabled={value===null} value={text} onChange={e=>update(binding.name,e.target.value)}/>}
36
+ {isRange ? <><label className="sr-only" htmlFor={fieldId+'-start'}>{binding.label}开始日期</label><label className="sr-only" htmlFor={fieldId+'-end'}>{binding.label}结束日期</label><Suspense fallback={<span role="status">正在加载日期控件…</span>}><RangeFilter id={fieldId} month={type==='month-range'} value={interval} onChange={value=>update(binding.name,value)}/></Suspense></>
37
+ : binding.options ? <Suspense fallback={<span role="status">正在加载选项…</span>}><OptionFilter id={fieldId} binding={binding} value={value} onChange={value=>update(binding.name,value)}/></Suspense>
38
+ : type==='month'?<MonthPicker id={fieldId} label={binding.label} value={text} onChange={value=>update(binding.name,value)}/>
39
+ : <Input id={fieldId} aria-label={binding.label} size="large" type={type==='date'?'date':'text'} min={type==='date'?'0001-01-01':undefined} max={type==='date'?'9999-12-31':undefined} inputMode={type==='number'?'decimal':undefined} placeholder={type==='quarter'?'YYYY-Q,例如 2026-3':type==='year'?'YYYY':type==='text'?'输入精确匹配值':undefined} disabled={value===null} value={text} onChange={e=>update(binding.name,e.target.value)}/>}
35
40
  <div className="field-hint">{binding.allowNull ? <Checkbox checked={value===null} onChange={e=>update(binding.name,e.target.checked?null:'')}>仅筛选空值</Checkbox> : isRange ? <span>可只填一端;全部留空沿用默认条件</span> : <span>留空沿用默认条件</span>}</div>
41
+ {scope&&(compact?<details className="filter-scope"><summary>查看筛选作用范围</summary>{scope[binding.name]}</details>:<p className="filter-scope">作用范围:{scope[binding.name]}</p>)}
36
42
  </div>;
37
43
  })}</div>
38
44
  <div className="filter-bottom"><p className={dirty?'unsaved-note':''}>{dirty?'条件已修改,点击「应用筛选」更新数据':'未设置的条件沿用看板保存值'}</p><div className="filter-buttons"><Button size="large" onClick={()=>{setDraft({});apply({});}}>恢复全部默认</Button><Button size="large" type="primary" htmlType="submit">应用筛选</Button></div></div>
@@ -0,0 +1,17 @@
1
+ import type {AppConfig} from '../finebi/types';
2
+ import type {WidgetState} from '../services/widget-queries';
3
+ import {widgetKey} from '../services/widget-queries';
4
+ import {displayCell,selectDataset} from '../services/view-data';
5
+ export function Insights({config,states}:{config:AppConfig;states:Record<string,WidgetState>}) {
6
+ const notes=config.widgets.map((binding,index)=>{
7
+ const state=states[widgetKey(binding,index)];
8
+ if(!state||state.loading)return `${binding.name}:等待当前查询`;
9
+ if(state.error)return `${binding.name}:查询失败,未参与观察`;
10
+ try {
11
+ const result=state.result!,data=selectDataset(result,binding.datasetId);
12
+ if(binding.type==='kpi'&&data.rows.length===1){const i=data.columns.findIndex(c=>c.fieldId===binding.valueFieldId);if(i<0)throw Error();return `${binding.name}:${displayCell(data.rows[0].cells[i])}(${result.normalization})`;}
13
+ return `${binding.name}:已返回 ${data.returnedRowCount} 行,${result.normalization}${result.range.hasNext?',还有后续数据':''}${data.rows.some(r=>r.kind==='UNKNOWN')?';含 UNKNOWN 行,不自动汇总':''}`;
14
+ } catch{return `${binding.name}:绑定或适配不可用,未参与观察`;}
15
+ });
16
+ return <section className="insight-panel" id="observations"><div><span className="eyebrow">CURRENT QUERY</span><h2>经营观察</h2><p>根据当前组件返回动态生成,范围以各组件提示为准。</p></div><ul>{notes.map((note,i)=><li key={i}>{note}</li>)}</ul></section>;
17
+ }
@@ -0,0 +1,32 @@
1
+ import {useId,useLayoutEffect,useRef,useState} from 'react';
2
+ import './month-picker.css';
3
+ const clamp=(n:number,min:number,max:number)=>Math.max(min,Math.min(max,n));
4
+ const pad=(n:number)=>String(n).padStart(4,'0');
5
+ export function MonthPicker({id,label,value,onChange}:{id:string;label:string;value:string;onChange:(value:string)=>void}) {
6
+ const popupId=useId(),root=useRef<HTMLDivElement>(null),trigger=useRef<HTMLButtonElement>(null),grid=useRef<HTMLDivElement>(null);
7
+ const now=new Date(),initialYear=value?Number(value.slice(0,4)):now.getFullYear();
8
+ const [open,setOpen]=useState(false),[mode,setMode]=useState<'months'|'years'>('months');
9
+ const [year,setYear]=useState(initialYear),[cursor,setCursor]=useState(0),[focusTick,setFocusTick]=useState(0);
10
+ const base=clamp(Math.floor((year-1)/12)*12+1,1,9988);
11
+ const focusGrid=()=>setFocusTick(n=>n+1);
12
+ useLayoutEffect(()=>{if(open&&focusTick)grid.current?.querySelector<HTMLButtonElement>(`[data-cell="${cursor}"]`)?.focus();},[focusTick,open,cursor,mode,year]);
13
+ const close=(restore=false)=>{setOpen(false);if(restore)trigger.current?.focus();};
14
+ const show=(focus=false)=>{setYear(initialYear);setMode('months');setCursor(value?Number(value.slice(5))-1:now.getMonth());setOpen(true);if(focus)focusGrid();};
15
+ const choose=(next:string)=>{onChange(next);close(true);};
16
+ const navigate=(delta:number)=>{setYear(y=>clamp(y+delta*(mode==='months'?1:12),1,9999));};
17
+ const keyDown=(e:React.KeyboardEvent)=>{
18
+ if(e.key==='Escape'){e.preventDefault();e.stopPropagation();close(true);return;}
19
+ const delta={ArrowLeft:-1,ArrowRight:1,ArrowUp:-3,ArrowDown:3}[e.key];
20
+ if(delta!==undefined){e.preventDefault();setCursor(c=>clamp(c+delta,0,11));focusGrid();}
21
+ else if(e.key==='Home'||e.key==='End'){e.preventDefault();setCursor(e.key==='Home'?0:11);focusGrid();}
22
+ else if(e.key==='PageUp'||e.key==='PageDown'){e.preventDefault();navigate(e.key==='PageUp'?-1:1);focusGrid();}
23
+ };
24
+ return <div ref={root} className="month-picker" onBlur={e=>{if(e.relatedTarget&&!e.currentTarget.contains(e.relatedTarget))close();}}>
25
+ <button id={id} ref={trigger} type="button" className={`month-trigger ${value?'has-value':''}`} aria-label={label} aria-haspopup="dialog" aria-expanded={open} aria-controls={popupId} onClick={()=>open?close():show()} onKeyDown={e=>{if(e.key==='ArrowDown'){e.preventDefault();show(true);}}}><span>{value?`${value.slice(0,4)}年${value.slice(5)}月`:'源看板默认'}</span><span aria-hidden="true">▦</span></button>
26
+ {open&&<><div className="month-dismiss" onPointerDown={()=>close()}/><div className="month-popover" role="dialog" aria-label={`${label}选择面板`} id={popupId} onKeyDown={e=>{if(e.key==='Escape'){e.preventDefault();e.stopPropagation();close(true);}}}>
27
+ <div className="month-head"><button type="button" aria-label={mode==='months'?'上一年':'上一组年份'} disabled={year===1} onClick={()=>navigate(-1)}>‹</button><button type="button" className="month-year" aria-label={mode==='months'?'选择年份':'返回月份'} onClick={()=>{setMode(mode==='months'?'years':'months');setCursor(mode==='months'?year-base:0);focusGrid();}}>{mode==='months'?`${pad(year)}年`:`${pad(base)} — ${pad(base+11)}`}</button><button type="button" aria-label={mode==='months'?'下一年':'下一组年份'} disabled={year===9999} onClick={()=>navigate(1)}>›</button></div>
28
+ <div ref={grid} className="month-grid" role="grid" aria-label={mode==='months'?'月份':'年份'} onKeyDown={keyDown}>{Array.from({length:4},(_,row)=><div role="row" key={row}>{Array.from({length:3},(_,column)=>{const i=row*3+column,selected=mode==='months'?value===`${pad(year)}-${String(i+1).padStart(2,'0')}`:Number(value.slice(0,4))===base+i;return <button key={i} type="button" role="gridcell" data-cell={i} tabIndex={cursor===i?0:-1} aria-selected={selected} className={selected?'selected':''} onFocus={()=>setCursor(i)} onClick={()=>{if(mode==='months')choose(`${pad(year)}-${String(i+1).padStart(2,'0')}`);else{setYear(base+i);setMode('months');setCursor(value?Number(value.slice(5))-1:0);focusGrid();}}}>{mode==='months'?`${i+1}月`:pad(base+i)}</button>;})}</div>)}</div>
29
+ <div className="month-actions"><button type="button" onClick={()=>choose('')}>默认条件</button><button type="button" onClick={()=>choose(`${pad(now.getFullYear())}-${String(now.getMonth()+1).padStart(2,'0')}`)}>本月</button><button type="button" onClick={()=>choose('')}>清除</button></div><p>选择后点击「应用筛选」取数</p>
30
+ </div></>}
31
+ </div>;
32
+ }
@@ -0,0 +1,7 @@
1
+ import Select from 'antd/es/select';
2
+ import type {FilterBinding,FilterValue} from '../finebi/types';
3
+
4
+ export default function OptionFilter({id,binding,value,onChange}:{id:string;binding:FilterBinding;value:FilterValue;onChange:(value:FilterValue)=>void}) {
5
+ const type=binding.type??'select',text=typeof value==='string'?value:'';
6
+ return <Select id={id} aria-label={binding.label} size="large" className="filter-select" mode={type==='multi-select'?'multiple':undefined} allowClear showSearch={{optionFilterProp:'label'}} maxTagCount="responsive" placeholder={`选择${binding.label},支持搜索`} options={binding.options} disabled={value===null} value={type==='multi-select'?(Array.isArray(value)?value:[]):text||undefined} onChange={selected=>onChange(selected??'')} notFoundContent={`没有匹配的${binding.label}`}/>;
7
+ }
@@ -0,0 +1,9 @@
1
+ import generatePicker from 'antd/es/date-picker/generatePicker';
2
+ import {calendarConfig, calendarValue} from './calendar';
3
+
4
+ const CalendarPicker=generatePicker<Date>(calendarConfig);
5
+ type Interval={start:string;end:string};
6
+ export default function RangeFilter({id,month,value,onChange}:{id:string;month:boolean;value:Interval;onChange:(value:Interval)=>void}) {
7
+ const update=(_dates:unknown,strings:[string,string]|null)=>onChange({start:strings?.[0]||'',end:strings?.[1]||''});
8
+ return <CalendarPicker.RangePicker size="large" className="filter-date-range" id={{start:id+'-start',end:id+'-end'}} picker={month?'month':'date'} format={month?'YYYY-MM':'YYYY-MM-DD'} placeholder={month?['开始月份','结束月份']:['开始日期','结束日期']} allowEmpty={[true,true]} allowClear value={[calendarValue(value.start),calendarValue(value.end)]} minDate={calendarValue('0001-01-01')!} maxDate={calendarValue('9999-12-31')!} onCalendarChange={update} onChange={update} onKeyDown={e=>{if(e.key==='Enter')e.preventDefault();}}/>;
9
+ }