@finebi/finebi-cli 1.5.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.
- package/README.md +17 -3
- package/package.json +4 -3
- package/skills/finebi-cli-agent/SKILL.md +8 -4
- package/skills/finebi-cli-agent/references/command-workflows.md +8 -4
- package/skills/finebi-cli-agent/references/dashboard-data-result.md +191 -191
- package/skills/finebi-cli-agent/references/dashboard-dsl-api.md +8 -1018
- package/skills/finebi-cli-agent/references/dashboard-dsl-core.md +194 -0
- package/skills/finebi-cli-agent/references/dashboard-dsl-examples.md +378 -0
- package/skills/finebi-cli-agent/references/dashboard-dsl-items.md +456 -0
- package/skills/finebi-cli-agent/references/mapping-rules.md +14 -14
- package/skills/finebi-cli-agent/references/scenario-workflows.md +1 -1
- package/skills/finebi-cli-agent/references/web-app.md +17 -0
- package/skills/finebi-cli-agent/references/widget-dsl-api-examples.md +3 -4
- package/skills/finebi-cli-agent/references/widget-dsl-api.md +10 -1374
- package/skills/finebi-cli-agent/references/widget-dsl-contexts.md +142 -0
- package/skills/finebi-cli-agent/references/widget-dsl-core.md +374 -0
- package/skills/finebi-cli-agent/references/widget-dsl-encodings.md +457 -0
- package/skills/finebi-cli-agent/references/widget-dsl-styles.md +413 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/package.json +1 -1
- package/skills/finebi-cli-agent/scripts/finebi-cli/src/app.js +148 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/src/config.js +27 -27
- package/skills/finebi-cli-agent/scripts/finebi-cli/src/help.js +79 -55
- package/skills/finebi-cli-agent/scripts/finebi-cli/src/index.js +5 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/src/install-skill.js +89 -89
- package/skills/finebi-cli-agent/scripts/finebi-cli/src/profiles.js +158 -158
- package/skills/finebi-cli-agent/scripts/finebi-cli/src/skill-files.js +94 -94
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/AGENTS.md +30 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/README.md +36 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/docs/acceptance.md +67 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/docs/auth-and-deploy.md +17 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/docs/data-contract.md +38 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/docs/design.md +54 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/docs/filters.md +93 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/examples/cockpit.config.json +22 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/examples/retail.config.json +185 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/index.html +2 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/package-lock.json +2191 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/package.json +16 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/public/app-config.json +11 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/scripts/dev-proxy.mjs +57 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/App.tsx +56 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/cockpit.css +3 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/Chart.tsx +40 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/DataTable.tsx +21 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/FilterBar.tsx +48 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/Insights.tsx +17 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/MonthPicker.tsx +32 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/OptionFilter.tsx +7 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/RangeFilter.tsx +9 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/Widget.tsx +39 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/calendar-locales.ts +3 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/calendar.ts +14 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/charts/Bar.tsx +6 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/charts/Line.tsx +6 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/charts/Pie.tsx +6 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/components/month-picker.css +1 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/finebi/client.ts +42 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/finebi/config.d.ts +1 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/finebi/config.js +44 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/finebi/date.d.ts +1 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/finebi/date.js +5 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/finebi/filters.d.ts +4 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/finebi/filters.js +106 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/finebi/normalize.ts +77 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/finebi/types.ts +18 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/main.tsx +5 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/retail.css +13 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/services/presentation.ts +36 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/services/table-data.ts +47 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/services/view-data.ts +18 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/services/widget-queries.ts +18 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/src/styles.css +8 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/browser/fixtures.mjs +28 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/browser/index.html +16 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/browser/main.tsx +149 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/browser/test-page.css +4 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/browser/vite.config.mjs +13 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/bundle.test.mjs +19 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/calendar.test.mjs +25 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/cockpit.test.mjs +73 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/proxy.test.mjs +96 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/retail.test.mjs +31 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tests/runtime.test.mjs +136 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/tsconfig.json +4 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli/templates/web-app/vite.config.ts +15 -0
- package/skills/finebi-cli-agent/scripts/finebi-cli-runner.mjs +4 -4
- package/src/app.js +148 -0
- package/src/config.js +27 -27
- package/src/help.js +79 -55
- package/src/index.js +5 -0
- package/src/install-skill.js +89 -89
- package/src/profiles.js +158 -158
- package/src/skill-files.js +94 -94
- package/templates/web-app/AGENTS.md +30 -0
- package/templates/web-app/README.md +36 -0
- package/templates/web-app/docs/acceptance.md +67 -0
- package/templates/web-app/docs/auth-and-deploy.md +17 -0
- package/templates/web-app/docs/data-contract.md +38 -0
- package/templates/web-app/docs/design.md +54 -0
- package/templates/web-app/docs/filters.md +93 -0
- package/templates/web-app/examples/cockpit.config.json +22 -0
- package/templates/web-app/examples/retail.config.json +185 -0
- package/templates/web-app/index.html +2 -0
- package/templates/web-app/package-lock.json +2191 -0
- package/templates/web-app/package.json +16 -0
- package/templates/web-app/public/app-config.json +11 -0
- package/templates/web-app/scripts/dev-proxy.mjs +57 -0
- package/templates/web-app/src/App.tsx +56 -0
- package/templates/web-app/src/cockpit.css +3 -0
- package/templates/web-app/src/components/Chart.tsx +40 -0
- package/templates/web-app/src/components/DataTable.tsx +21 -0
- package/templates/web-app/src/components/FilterBar.tsx +48 -0
- package/templates/web-app/src/components/Insights.tsx +17 -0
- package/templates/web-app/src/components/MonthPicker.tsx +32 -0
- package/templates/web-app/src/components/OptionFilter.tsx +7 -0
- package/templates/web-app/src/components/RangeFilter.tsx +9 -0
- package/templates/web-app/src/components/Widget.tsx +39 -0
- package/templates/web-app/src/components/calendar-locales.ts +3 -0
- package/templates/web-app/src/components/calendar.ts +14 -0
- package/templates/web-app/src/components/charts/Bar.tsx +6 -0
- package/templates/web-app/src/components/charts/Line.tsx +6 -0
- package/templates/web-app/src/components/charts/Pie.tsx +6 -0
- package/templates/web-app/src/components/month-picker.css +1 -0
- package/templates/web-app/src/finebi/client.ts +42 -0
- package/templates/web-app/src/finebi/config.d.ts +1 -0
- package/templates/web-app/src/finebi/config.js +44 -0
- package/templates/web-app/src/finebi/date.d.ts +1 -0
- package/templates/web-app/src/finebi/date.js +5 -0
- package/templates/web-app/src/finebi/filters.d.ts +4 -0
- package/templates/web-app/src/finebi/filters.js +106 -0
- package/templates/web-app/src/finebi/normalize.ts +77 -0
- package/templates/web-app/src/finebi/types.ts +18 -0
- package/templates/web-app/src/main.tsx +5 -0
- package/templates/web-app/src/retail.css +13 -0
- package/templates/web-app/src/services/presentation.ts +36 -0
- package/templates/web-app/src/services/table-data.ts +47 -0
- package/templates/web-app/src/services/view-data.ts +18 -0
- package/templates/web-app/src/services/widget-queries.ts +18 -0
- package/templates/web-app/src/styles.css +8 -0
- package/templates/web-app/tests/browser/fixtures.mjs +28 -0
- package/templates/web-app/tests/browser/index.html +16 -0
- package/templates/web-app/tests/browser/main.tsx +149 -0
- package/templates/web-app/tests/browser/test-page.css +4 -0
- package/templates/web-app/tests/browser/vite.config.mjs +13 -0
- package/templates/web-app/tests/bundle.test.mjs +19 -0
- package/templates/web-app/tests/calendar.test.mjs +25 -0
- package/templates/web-app/tests/cockpit.test.mjs +73 -0
- package/templates/web-app/tests/proxy.test.mjs +96 -0
- package/templates/web-app/tests/retail.test.mjs +31 -0
- package/templates/web-app/tests/runtime.test.mjs +136 -0
- package/templates/web-app/tsconfig.json +4 -0
- package/templates/web-app/vite.config.ts +15 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "finebi-web-app",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"engines": {"node": ">=18.17"},
|
|
7
|
+
"scripts": {
|
|
8
|
+
"dev": "vite --host 127.0.0.1",
|
|
9
|
+
"build": "tsc --noEmit && vite build",
|
|
10
|
+
"preview": "vite preview --host 127.0.0.1",
|
|
11
|
+
"test": "node --test tests/*.test.mjs",
|
|
12
|
+
"test:browser": "vite --config tests/browser/vite.config.mjs"
|
|
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"},
|
|
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"}
|
|
16
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Development only: the browser never receives the developer's session token.
|
|
2
|
+
import {validateRefer} from '../src/finebi/filters.js';
|
|
3
|
+
export function createDevMiddleware(config, env = process.env, fetchImpl = fetch) {
|
|
4
|
+
const prefix = config.basePath.replace(/\/$/, '');
|
|
5
|
+
const queryPath = `${prefix}/v5/api/dashboard/report/${encodeURIComponent(config.dashboardId)}/widgets/query`;
|
|
6
|
+
let token = env.FINEBI_DEV_TOKEN || '';
|
|
7
|
+
let login;
|
|
8
|
+
const reply = (res, status, errorCode) => {res.writeHead(status, {'Content-Type':'application/json','Cache-Control':'no-store'});res.end(JSON.stringify({success:false,errorCode}));};
|
|
9
|
+
async function session() {
|
|
10
|
+
if (token) return token;
|
|
11
|
+
if (!env.FINEBI_DEV_USERNAME || !env.FINEBI_DEV_PASSWORD) throw new Error('AUTH_REQUIRED');
|
|
12
|
+
if (!login) login = (async()=>{
|
|
13
|
+
const response = await fetchImpl(`${env.FINEBI_DEV_BASE_URL.replace(/\/$/, '')}/login`, {method:'POST',redirect:'error',headers:{'Content-Type':'application/json'},body:JSON.stringify({username:env.FINEBI_DEV_USERNAME,password:env.FINEBI_DEV_PASSWORD,encrypted:false,tenantId:''}),signal:AbortSignal.timeout(30000)});
|
|
14
|
+
const body = await response.json();
|
|
15
|
+
if (!response.ok || typeof body?.data?.accessToken !== 'string' || !body.data.accessToken) throw new Error('AUTH_REQUIRED');
|
|
16
|
+
token=body.data.accessToken;
|
|
17
|
+
return token;
|
|
18
|
+
})().finally(()=>{login=undefined;});
|
|
19
|
+
return login;
|
|
20
|
+
}
|
|
21
|
+
return async (req, res, next) => {
|
|
22
|
+
const pathname = new URL(req.url, 'http://localhost').pathname;
|
|
23
|
+
if (!pathname.startsWith(prefix+'/') && pathname !== prefix) return next();
|
|
24
|
+
const host = req.headers.host || '';
|
|
25
|
+
const origin = req.headers.origin;
|
|
26
|
+
if (!/^(localhost|127\.0\.0\.1)(:\d+)?$/.test(host) || origin && origin !== `http://${host}` || req.headers['sec-fetch-site'] === 'cross-site') return reply(res,403,'PERMISSION_DENIED');
|
|
27
|
+
if (pathname !== queryPath || req.method !== 'POST' || req.headers['x-requested-with'] !== 'XMLHttpRequest') return reply(res,403,'PERMISSION_DENIED');
|
|
28
|
+
let body;
|
|
29
|
+
try {
|
|
30
|
+
let raw='';
|
|
31
|
+
for await (const chunk of req) {raw+=chunk.toString();if (raw.length>65536) throw new Error('BODY_TOO_LARGE');}
|
|
32
|
+
body=JSON.parse(raw);
|
|
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');
|
|
35
|
+
validateRefer(config.filters || [],body.refer);
|
|
36
|
+
} catch {return reply(res,400,'INVALID_REQUEST');}
|
|
37
|
+
if (!env.FINEBI_DEV_BASE_URL) return reply(res,401,'AUTH_REQUIRED');
|
|
38
|
+
try {
|
|
39
|
+
const target = new URL(env.FINEBI_DEV_BASE_URL);
|
|
40
|
+
if (!['http:','https:'].includes(target.protocol) || target.username || target.password || target.search || target.hash) throw new Error('INVALID_TARGET');
|
|
41
|
+
const auth=await session();
|
|
42
|
+
const response=await fetchImpl(`${target.href.replace(/\/$/, '')}/v5/api/dashboard/report/${encodeURIComponent(config.dashboardId)}/widgets/query`, {
|
|
43
|
+
method:'POST',redirect:'manual',signal:AbortSignal.timeout(30000),
|
|
44
|
+
headers:{'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest',Cookie:`fine_auth_token=${auth}`},
|
|
45
|
+
body:JSON.stringify({widgetIds:body.widgetIds,includeWidgetBean:true,pageLimit:body.pageLimit,refer:body.refer || {},...(config.directoryEntryId?{reportEntryId:config.directoryEntryId}:{})}),
|
|
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');}
|
|
48
|
+
if (response.status===403) return reply(res,403,'PERMISSION_DENIED');
|
|
49
|
+
const json=await response.json();
|
|
50
|
+
if (response.status===401 || ['TIME_OUT','JWT_EXPIRED','LOGIN_INFO_NOT_AVAILABLE','CANNOT_GET_TOKEN'].includes(json.errorCode)) {token='';return reply(res,401,'AUTH_REQUIRED');}
|
|
51
|
+
if (response.status===403) return reply(res,403,'PERMISSION_DENIED');
|
|
52
|
+
// Forward only the query envelope, never upstream headers or login payloads.
|
|
53
|
+
res.writeHead(response.status,{'Content-Type':'application/json','Cache-Control':'no-store'});
|
|
54
|
+
res.end(JSON.stringify(json.success===true ? {success:true,data:json.data} : {success:false,errorCode:json.errorCode || 'QUERY_FAILED'}));
|
|
55
|
+
} catch (error) {reply(res,error.message==='AUTH_REQUIRED'?401:502,error.message==='AUTH_REQUIRED'?'AUTH_REQUIRED':'UPSTREAM_UNAVAILABLE');}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
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})));
|
|
10
|
+
function Dashboard({config}: {config: AppConfig}) {
|
|
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();};
|
|
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;
|
|
36
|
+
return <div className={`app ${config.layout}`}>
|
|
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>
|
|
48
|
+
<footer>数据范围以当前查询结果为准 · 权限由 FineBI 服务端控制</footer></main>
|
|
49
|
+
</div>;
|
|
50
|
+
}
|
|
51
|
+
export default function App() {
|
|
52
|
+
const [config, setConfig] = useState<AppConfig>(); const [error, setError] = useState('');
|
|
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();},[]);
|
|
54
|
+
if(error)return <main className="state" role="alert"><h1>请完成应用配置</h1><p>{error}</p><p>在 public/app-config.json 中绑定 CLI 发现的仪表板实例与字段。</p></main>;
|
|
55
|
+
return config ? <Dashboard config={config}/> : <p className="state">正在加载应用…</p>;
|
|
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}}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import {useEffect, useRef, useState} from 'react';
|
|
2
|
+
import * as echarts from 'echarts/core';
|
|
3
|
+
import {TooltipComponent} from 'echarts/components';
|
|
4
|
+
import {CanvasRenderer} from 'echarts/renderers';
|
|
5
|
+
import type {Dataset, WidgetBinding} from '../finebi/types';
|
|
6
|
+
import {chartValues,displayCell} from '../services/view-data';
|
|
7
|
+
import {formatCategory} from '../services/presentation';
|
|
8
|
+
echarts.use([TooltipComponent, CanvasRenderer]);
|
|
9
|
+
export function Chart({dataset, binding}: {dataset: Dataset; binding: WidgetBinding}) {
|
|
10
|
+
const container = useRef<HTMLDivElement>(null);
|
|
11
|
+
const [order, setOrder] = useState('source');
|
|
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;
|
|
17
|
+
useEffect(() => {
|
|
18
|
+
if (!container.current) return;
|
|
19
|
+
const chart = echarts.init(container.current);
|
|
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));
|
|
26
|
+
chart.setOption({
|
|
27
|
+
color: palette,
|
|
28
|
+
tooltip: {trigger: binding.type === 'pie' ? 'item' : 'axis', renderMode: 'richText'},
|
|
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})),
|
|
35
|
+
});
|
|
36
|
+
const observer = new ResizeObserver(() => chart.resize()); observer.observe(container.current);
|
|
37
|
+
return () => {observer.disconnect(); chart.dispose();};
|
|
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></>;
|
|
40
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import {useState} from 'react';
|
|
2
|
+
import type {Dataset,WidgetBinding} from '../finebi/types';
|
|
3
|
+
import {displayCell} from '../services/view-data';
|
|
4
|
+
import {fieldIndex,tableCsv,tableDataset,tableRows} from '../services/table-data';
|
|
5
|
+
export function DataTable({dataset, pageSize,binding}: {dataset: Dataset; pageSize: number;binding:WidgetBinding}) {
|
|
6
|
+
const [search, setSearch] = useState('');
|
|
7
|
+
const [page, setPage] = useState(0);
|
|
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;
|
|
13
|
+
const pages = Math.max(1, Math.ceil(rows.length / pageSize));
|
|
14
|
+
const current = Math.min(page, pages - 1);
|
|
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>
|
|
19
|
+
{!rows.length && <p className="empty">没有匹配的数据</p>}
|
|
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></>;
|
|
21
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
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';
|
|
7
|
+
import zhCN from 'antd/locale/zh_CN';
|
|
8
|
+
import {encodeFilters} from '../finebi/filters.js';
|
|
9
|
+
import type {FilterBinding, FilterState, FilterValue} from '../finebi/types';
|
|
10
|
+
import {MonthPicker} from './MonthPicker';
|
|
11
|
+
|
|
12
|
+
const RangeFilter=lazy(()=>import('./RangeFilter'));
|
|
13
|
+
const OptionFilter=lazy(()=>import('./OptionFilter'));
|
|
14
|
+
|
|
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}) {
|
|
16
|
+
const id=useId();
|
|
17
|
+
const [draft,setDraft]=useState<FilterState>({});
|
|
18
|
+
const [applied,setApplied]=useState<FilterState>({});
|
|
19
|
+
const [error,setError]=useState('');
|
|
20
|
+
const update=(name:string,value:FilterValue)=>{setDraft(old=>({...old,[name]:value}));setError('');};
|
|
21
|
+
const apply=(state:FilterState)=>{
|
|
22
|
+
try {encodeFilters(bindings,state);setApplied(state);onApply(state);setError('');}
|
|
23
|
+
catch(e){setError((e as Error).message);}
|
|
24
|
+
};
|
|
25
|
+
const dirty=JSON.stringify(draft)!==JSON.stringify(applied);
|
|
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'}}}}>
|
|
27
|
+
<form className="filter-card" onSubmit={e=>{e.preventDefault();apply(draft);}}>
|
|
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>
|
|
29
|
+
<div className="filter-fields">{bindings.map((binding,index)=>{
|
|
30
|
+
const type=binding.type??'select', value=draft[binding.name], text=typeof value==='string'?value:'';
|
|
31
|
+
const isRange=type==='date-range'||type==='month-range';
|
|
32
|
+
const interval=value && typeof value==='object' && !Array.isArray(value)?value:{start:'',end:''};
|
|
33
|
+
const fieldId=`${id}-filter-${index}`;
|
|
34
|
+
return <div className={`filter-field ${isRange?'date-field':''}`} key={binding.name}>
|
|
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>
|
|
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)}/>}
|
|
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>)}
|
|
42
|
+
</div>;
|
|
43
|
+
})}</div>
|
|
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>
|
|
45
|
+
{error && <Alert title={error} type="error" showIcon className="filter-alert"/>}
|
|
46
|
+
</form>
|
|
47
|
+
</ConfigProvider>;
|
|
48
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import {Component, lazy, Suspense, type ReactNode} from 'react';
|
|
2
|
+
import type {QueryResult, WidgetBinding} from '../finebi/types';
|
|
3
|
+
import {displayCell, selectDataset} from '../services/view-data';
|
|
4
|
+
import {DataTable} from './DataTable';
|
|
5
|
+
import type {WidgetState} from '../services/widget-queries';
|
|
6
|
+
import {formatMetric} from '../services/presentation';
|
|
7
|
+
const charts={bar:lazy(()=>import('./charts/Bar')),line:lazy(()=>import('./charts/Line')),pie:lazy(()=>import('./charts/Pie'))};
|
|
8
|
+
export class Boundary extends Component<{children: ReactNode;onRetry?:()=>void}, {error: string}> {
|
|
9
|
+
state = {error: ''};
|
|
10
|
+
static getDerivedStateFromError(error: Error) {return {error: error.message};}
|
|
11
|
+
render() {return this.state.error ? <div role="alert"><p>{this.state.error}</p>{this.props.onRetry&&<button onClick={this.props.onRetry}>重试组件</button>}</div> : this.props.children;}
|
|
12
|
+
}
|
|
13
|
+
function Content({result, binding, pageSize}: {result: QueryResult; binding: WidgetBinding; pageSize: number}) {
|
|
14
|
+
const data = selectDataset(result, binding.datasetId);
|
|
15
|
+
if (!data.rows.length) return <p className="empty">当前查询没有数据</p>;
|
|
16
|
+
if (binding.type === 'table') return <DataTable dataset={data} pageSize={pageSize} binding={binding}/>;
|
|
17
|
+
if (binding.type === 'kpi') {
|
|
18
|
+
const index = data.columns.findIndex(c => c.fieldId === binding.valueFieldId);
|
|
19
|
+
if (data.rows.length !== 1 || index < 0) throw new Error('KPI 需要单行指标结果,不能自动累加图表行');
|
|
20
|
+
return <div className="kpi" title={displayCell(data.rows[0].cells[index])}>{formatMetric(data.rows[0].cells[index],binding.valueFormat)}</div>;
|
|
21
|
+
}
|
|
22
|
+
const Chart=charts[binding.type];
|
|
23
|
+
return <Suspense fallback={<p role="status">正在加载图表…</p>}><Chart dataset={data} binding={binding}/></Suspense>;
|
|
24
|
+
}
|
|
25
|
+
export function Widget({state,binding,pageSize,onRetry,compact=false}: {state:WidgetState; binding:WidgetBinding;pageSize:number;onRetry:()=>void;compact?:boolean}) {
|
|
26
|
+
const result=state.result;
|
|
27
|
+
const selected=result?.datasets.find(d=>binding.datasetId?d.id===binding.datasetId:result.datasets.length===1);
|
|
28
|
+
return <section className={`panel widget-${binding.type} ${binding.type==='table'?'wide':''}`}><div className="panel-heading"><h2>{binding.name}</h2><span className={`component-status ${state.error?'failed':''}`}>{state.loading?'加载中':state.error?'查询失败':state.at?`更新于 ${state.at}`:'等待查询'}</span></div>
|
|
29
|
+
{binding.description&&<p className="muted">{binding.description}</p>}
|
|
30
|
+
{!compact&&binding.filterNames&&<p className="filter-scope">控件覆盖:{binding.filterNames.length?binding.filterNames.join('、'):'沿用源组件条件'}</p>}
|
|
31
|
+
{state.loading&&<p className="empty" role="status">正在获取实时数据…</p>}
|
|
32
|
+
{state.error&&<div className="component-error" role="alert"><p>{'code' in state.error?String(state.error.code)+' · ':''}{state.error.message}</p><button onClick={onRetry}>重试组件</button></div>}
|
|
33
|
+
{result&&<>
|
|
34
|
+
{compact?<details className="query-details"><summary>查询范围{selected?` · ${selected.returnedRowCount} 行`:''}</summary><p>{result.range.mode} · {result.normalization} · 后续数据:{String(result.range.hasNext)}</p><p>筛选作用:{binding.filterNames?.join('、')||'沿用源组件条件'}</p></details>:<p className="result-range">{result.range.mode} · 本次{selected?` ${selected.returnedRowCount} 行`:'多个模型,需显式选择'}{result.range.total.value!==null?` · 查询总行数 ${result.range.total.value}`:''} · hasNext={String(result.range.hasNext)} · {result.normalization}</p>}
|
|
35
|
+
{(result.warnings.length>0||result.normalization!=='COMPLETE'||result.range.hasNext===true)&&<div className="notice" role="status">{result.range.hasNext||result.warnings.includes('NEXT_PAGE_UNSUPPORTED')?'当前仅展示首屏返回结果,本地分页不代表服务端续页。':'部分源图形未转换,当前展示已返回的数据模型。'}{compact?<details><summary>查看适配说明</summary><small>{result.normalization} · {result.warnings.join(' · ')}</small></details>:<small>{result.normalization} · {result.warnings.join(' · ')}</small>}</div>}
|
|
36
|
+
<Boundary key={state.at} onRetry={onRetry}><Content result={result} binding={binding} pageSize={pageSize}/></Boundary>
|
|
37
|
+
</>}
|
|
38
|
+
</section>;
|
|
39
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import dateFnsConfig from '@rc-component/picker/generate/dateFns';
|
|
2
|
+
import {isDateValue} from '../finebi/date.js';
|
|
3
|
+
|
|
4
|
+
// Keep the picker on the same 0001–9999 calendar range as the filter contract.
|
|
5
|
+
export const calendarConfig = dateFnsConfig;
|
|
6
|
+
export function calendarValue(value:string):Date|null {
|
|
7
|
+
const fullDate = value.length===7 ? value+'-01' : value;
|
|
8
|
+
if (!isDateValue(fullDate)) return null;
|
|
9
|
+
const [year,month,day] = fullDate.split('-').map(Number);
|
|
10
|
+
const date = new Date(0);
|
|
11
|
+
date.setHours(0,0,0,0);
|
|
12
|
+
date.setFullYear(year,month-1,day);
|
|
13
|
+
return date;
|
|
14
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
.month-picker{position:relative;--month-accent:#197a58;--month-soft:#eaf6ef}.month-trigger{display:flex;justify-content:space-between;align-items:center;width:100%;height:46px;padding:0 14px;border:1px solid #dce4df;border-radius:10px;text-align:left;color:#87978f;background:#fff}.month-trigger.has-value{color:#204c3c}.month-trigger:focus-visible,.month-popover button:focus-visible{outline:3px solid #a1d6bc;outline-offset:2px}.month-trigger[aria-expanded=true]{border-color:var(--month-accent)}.month-dismiss{position:fixed;inset:0;z-index:20}.month-popover{position:absolute;right:0;top:calc(100% + 8px);z-index:21;width:min(310px,calc(100vw - 48px));padding:15px;border:1px solid #dce8e1;border-radius:15px;background:#fff;box-shadow:0 14px 45px #153f2926;color:#264c3d;max-height:65vh;overflow:auto}.month-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}.month-popover button{border:0;background:transparent;border-radius:8px;padding:8px 12px}.month-head>button{font-size:19px}.month-head .month-year{font-size:14px;font-weight:700}.month-grid>[role=row]{display:grid;grid-template-columns:repeat(3,1fr);gap:6px;margin:6px 0}.month-grid button{height:41px}.month-popover button:hover{background:var(--month-soft)}.month-grid button.selected{background:var(--month-accent);color:#fff}.month-actions{display:flex;justify-content:space-between;gap:4px;border-top:1px solid #e9efeb;margin-top:13px;padding-top:10px}.month-actions button{font-size:12px;color:var(--month-accent);padding:7px}.month-popover p{font-size:11px;color:#87978f;margin:9px 0 0;text-align:center}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import {normalize} from './normalize';
|
|
2
|
+
import {encodeFilters} from './filters.js';
|
|
3
|
+
import {configErrors} from './config.js';
|
|
4
|
+
import type {AppConfig, QueryResult, FilterState, WidgetBinding} from './types';
|
|
5
|
+
export class FineBIError extends Error {
|
|
6
|
+
constructor(public code: string, message: string) {super(message); this.name = 'FineBIError';}
|
|
7
|
+
}
|
|
8
|
+
export function validateConfig(config: AppConfig) {
|
|
9
|
+
const errors=configErrors(config);
|
|
10
|
+
if(errors.length)throw new Error(errors.join(' '));
|
|
11
|
+
}
|
|
12
|
+
export async function queryWidgets(config: AppConfig, filters: FilterState = {}, signal?: AbortSignal, fetchImpl: typeof fetch = fetch, widgetIds?:string[]): Promise<Record<string, QueryResult>> {
|
|
13
|
+
validateConfig(config);
|
|
14
|
+
const refer = encodeFilters(config.filters,filters);
|
|
15
|
+
const ids = [...new Set(widgetIds ?? config.widgets.map(w => w.entryId))];
|
|
16
|
+
if(!ids.length||ids.some(id=>!config.widgets.some(w=>w.entryId===id)))throw new Error('组件不在配置范围内');
|
|
17
|
+
const response = await fetchImpl(`${config.basePath.replace(/\/$/, '')}/v5/api/dashboard/report/${encodeURIComponent(config.dashboardId)}/widgets/query`, {
|
|
18
|
+
method: 'POST', credentials: 'include', signal, redirect: 'manual',
|
|
19
|
+
headers: {'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest'},
|
|
20
|
+
body: JSON.stringify({widgetIds: ids, includeWidgetBean: true, pageLimit: config.maxRows, refer,...(config.directoryEntryId?{reportEntryId:config.directoryEntryId}:{})}),
|
|
21
|
+
});
|
|
22
|
+
if (response.status === 401 || response.type === 'opaqueredirect' || response.status >= 300 && response.status < 400) throw new FineBIError('AUTH_REQUIRED', '登录已失效,请登录 FineBI 后重试');
|
|
23
|
+
if (response.status === 403) throw new FineBIError('PERMISSION_DENIED', '当前用户没有访问权限');
|
|
24
|
+
if (response.headers.get('content-type')?.includes('text/html')) throw new FineBIError('AUTH_REQUIRED', '返回了登录页面,请重新登录 FineBI');
|
|
25
|
+
const body = await response.json().catch(() => {throw new FineBIError('INVALID_RESPONSE', 'FineBI 返回了无法解析的响应');});
|
|
26
|
+
const code = body.errorCode ?? body.code;
|
|
27
|
+
if (['TIME_OUT','JWT_EXPIRED','LOGIN_INFO_NOT_AVAILABLE','CANNOT_GET_TOKEN','AUTH_REQUIRED'].includes(code)) throw new FineBIError('AUTH_REQUIRED', '登录已失效,请登录 FineBI 后重试');
|
|
28
|
+
if (code === 'PERMISSION_DENIED') throw new FineBIError('PERMISSION_DENIED', '当前用户没有数据或字段权限');
|
|
29
|
+
if (!response.ok || body.success !== true) throw new FineBIError('QUERY_FAILED', 'FineBI 查询失败,请检查组件、控件绑定及访问权限');
|
|
30
|
+
const results: Record<string, QueryResult> = {};
|
|
31
|
+
for (const id of ids) {
|
|
32
|
+
if (!body.data?.[id]?.previewResult) throw new FineBIError('INVALID_RESPONSE', `接口未返回组件 ${id},不能视为空数据`);
|
|
33
|
+
results[id] = normalize(body.data[id]);
|
|
34
|
+
}
|
|
35
|
+
return results;
|
|
36
|
+
}
|
|
37
|
+
export async function queryWidget(config:AppConfig,binding:WidgetBinding,filters:FilterState={},signal?:AbortSignal,fetchImpl:typeof fetch=fetch):Promise<QueryResult> {
|
|
38
|
+
// Validate all draft names before projecting the verified component scope.
|
|
39
|
+
encodeFilters(config.filters,filters);
|
|
40
|
+
const scoped=binding.filterNames ? Object.fromEntries(Object.entries(filters).filter(([name])=>binding.filterNames!.includes(name))) : filters;
|
|
41
|
+
return (await queryWidgets(config,scoped,signal,fetchImpl,[binding.entryId]))[binding.entryId];
|
|
42
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function configErrors(config: unknown): string[];
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import {validateFilterBindings} from './filters.js';
|
|
2
|
+
const nonempty=value=>typeof value==='string'&&value.trim().length>0;
|
|
3
|
+
const record=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
|
|
4
|
+
export function configErrors(config) {
|
|
5
|
+
if(!record(config))return ['configuration must be a JSON object.'];
|
|
6
|
+
const errors=[];
|
|
7
|
+
const allowed=['schemaVersion','title','basePath','layout','dashboardId','directoryEntryId','maxRows','pageSize','widgets','filters','templateVersion','description','insights','dataNotes'];
|
|
8
|
+
for(const key of Object.keys(config))if(!allowed.includes(key))errors.push(`unsupported config field: ${key}.`);
|
|
9
|
+
if(config.schemaVersion!=='1')errors.push('schemaVersion must be "1".');
|
|
10
|
+
if(!nonempty(config.title))errors.push('title is required.');
|
|
11
|
+
if(!nonempty(config.basePath)||!/^\/(?!\/)[\w/-]+$/.test(config.basePath))errors.push('basePath must be a same-origin path.');
|
|
12
|
+
if(!['overview','workbench','cockpit','retail'].includes(config.layout))errors.push('layout must be overview, workbench, cockpit or retail.');
|
|
13
|
+
if(!nonempty(config.dashboardId))errors.push('project is not bound: dashboardId must be configured.');
|
|
14
|
+
if('directoryEntryId' in config&&!nonempty(config.directoryEntryId))errors.push('directoryEntryId must be a non-empty string.');
|
|
15
|
+
if(!Number.isSafeInteger(config.maxRows)||config.maxRows<1||config.maxRows>10000)errors.push('maxRows must be an integer from 1 to 10000.');
|
|
16
|
+
if(!Number.isSafeInteger(config.pageSize)||config.pageSize<1||config.pageSize>100)errors.push('pageSize must be an integer from 1 to 100.');
|
|
17
|
+
if('description' in config&&!nonempty(config.description))errors.push('description must be a non-empty string.');
|
|
18
|
+
if('insights' in config&&typeof config.insights!=='boolean')errors.push('insights must be boolean.');
|
|
19
|
+
if('dataNotes' in config&&(!Array.isArray(config.dataNotes)||config.dataNotes.some(v=>!nonempty(v))))errors.push('dataNotes must be text array.');
|
|
20
|
+
try{validateFilterBindings(config.filters);}catch(error){errors.push(error.message);}
|
|
21
|
+
if(!Array.isArray(config.widgets)||!config.widgets.length)return [...errors,'widgets must be a non-empty array.'];
|
|
22
|
+
for(const [i,w] of config.widgets.entries()) {
|
|
23
|
+
if(!record(w)){errors.push(`widgets[${i}] must be an object.`);continue;}
|
|
24
|
+
const fields=['entryId','name','type','datasetId','categoryFieldId','valueFieldId','series','description','filterNames','tableFieldIds','localFilterFieldIds','valueFormat','categoryFormat','categoryTimeZone'];
|
|
25
|
+
for(const field of Object.keys(w))if(!fields.includes(field))errors.push(`widgets[${i}].${field} is unsupported.`);
|
|
26
|
+
for(const field of ['entryId','name'])if(!nonempty(w[field]))errors.push(`widgets[${i}].${field} is required.`);
|
|
27
|
+
if(!['table','kpi','bar','line','pie'].includes(w.type))errors.push(`widgets[${i}].type is unsupported.`);
|
|
28
|
+
if('valueFormat' in w&&(w.type!=='kpi'||!['number','percent'].includes(w.valueFormat)))errors.push(`widgets[${i}].valueFormat requires a KPI and number or percent.`);
|
|
29
|
+
if('categoryFormat' in w||'categoryTimeZone' in w) {
|
|
30
|
+
if(!['line','bar'].includes(w.type)||w.categoryFormat!=='epoch-month'||!nonempty(w.categoryTimeZone))errors.push(`widgets[${i}].categoryFormat requires a line/bar, epoch-month and an explicit categoryTimeZone.`);
|
|
31
|
+
else try{new Intl.DateTimeFormat('en',{timeZone:w.categoryTimeZone});}catch{errors.push(`widgets[${i}].categoryTimeZone is invalid.`);}
|
|
32
|
+
}
|
|
33
|
+
for(const field of ['datasetId','categoryFieldId','valueFieldId','description'])if(field in w&&!nonempty(w[field]))errors.push(`widgets[${i}].${field} must be non-empty.`);
|
|
34
|
+
if(w.type!=='table'&&!nonempty(w.valueFieldId)&&!w.series)errors.push(`widgets[${i}].valueFieldId is required.`);
|
|
35
|
+
if(!['table','kpi'].includes(w.type)&&!nonempty(w.categoryFieldId))errors.push(`widgets[${i}].categoryFieldId is required.`);
|
|
36
|
+
if('series' in w&&(!['line','bar'].includes(w.type)||!Array.isArray(w.series)||!w.series.length||w.series.some(s=>!record(s)||Object.keys(s).some(k=>!['fieldId','label'].includes(k))||!nonempty(s.fieldId)||!nonempty(s.label))||new Set(w.series.map(s=>s?.fieldId)).size!==w.series.length))errors.push(`widgets[${i}].series is invalid.`);
|
|
37
|
+
for(const field of ['filterNames','tableFieldIds','localFilterFieldIds'])if(field in w) {
|
|
38
|
+
if(!Array.isArray(w[field])||w[field].some(v=>!nonempty(v))||new Set(w[field]).size!==w[field].length)errors.push(`widgets[${i}].${field} must be unique strings.`);
|
|
39
|
+
else if(field==='filterNames'&&w[field].some(name=>!Array.isArray(config.filters)||!config.filters.some(f=>f?.name===name)))errors.push(`widgets[${i}].filterNames references an unknown filter.`);
|
|
40
|
+
else if(field!=='filterNames'&&(w.type!=='table'||!w[field].length))errors.push(`widgets[${i}].${field} is only for tables and must be non-empty.`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return errors;
|
|
44
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function isDateValue(value: unknown): boolean;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type {FilterBinding, FilterState} from './types';
|
|
2
|
+
export function validateFilterBindings(bindings: unknown): void;
|
|
3
|
+
export function encodeFilters(bindings: FilterBinding[], state?: FilterState): Record<string,string[]>;
|
|
4
|
+
export function validateRefer(bindings: FilterBinding[], refer?: unknown): void;
|