This commit is contained in:
@@ -37,6 +37,6 @@ export function DashboardPanels({data, drill}:{data:FaultDashboardResponse;drill
|
||||
</div>
|
||||
</>;
|
||||
}
|
||||
export function DashboardTicketTable({rows,updatedAt,drill}:{rows:FaultAnalysisRecord[];updatedAt:string;drill:DashboardDrill}) {
|
||||
return <div className="fd-table-scroll"><table className="fd-tickets"><thead><tr><th>车辆 / 故障单号</th><th>运维处置人</th><th>区域 / 客户</th><th>等级</th><th>当前状态</th><th>处置记录 / 故障描述</th><th>提报时间</th><th>操作</th></tr></thead><tbody>{rows.map(row=>{const overdue=['待处理','处理中'].includes(row.status)&&row.deadlineAt&&Date.parse(`${row.deadlineAt.replace(' ','T')}+08:00`)<Date.parse(updatedAt);return <tr key={row.id}><td><strong>{row.plate}</strong><small>{row.code}</small></td><td>{row.handlers.map(h=>h.label).join('、')}</td><td>{row.cell.region}<small>{row.customerLabel}</small></td><td><span className={`fd-grade fd-grade-${row.level?.slice(0,2)}`}>{row.level||'未标注'}</span></td><td><span className={row.status==='已归档'?'fd-green':'fd-orange'}>{row.status==='已归档'?'已闭环':row.status}</span>{overdue&&<small className="fd-overdue-tag">已逾期</small>}</td><td className="fd-description" title={row.progress||row.description}>{row.progress||row.description||'暂无处置记录'}</td><td>{row.reportedAt||'未记录'}</td><td><button onClick={()=>drill(`${row.plate} · ${row.code}`,'ledger',{id:row.id})}>查看</button></td></tr>})}</tbody></table>{!rows.length&&<p className="fd-empty">当前条件下暂无故障。</p>}</div>;
|
||||
export function DashboardTicketTable({rows,updatedAt,drill,emptyMessage='当前条件下暂无故障。'}:{rows:FaultAnalysisRecord[];updatedAt:string;drill:DashboardDrill;emptyMessage?:string}) {
|
||||
return <div className="fd-table-scroll"><table className="fd-tickets"><thead><tr><th>车辆 / 故障单号</th><th>运维处置人</th><th>区域 / 客户</th><th>等级</th><th>当前状态</th><th>处置记录 / 故障描述</th><th>提报时间</th><th>操作</th></tr></thead><tbody>{rows.map(row=>{const overdue=['待处理','处理中'].includes(row.status)&&row.deadlineAt&&Date.parse(`${row.deadlineAt.replace(' ','T')}+08:00`)<Date.parse(updatedAt);return <tr key={row.id}><td><strong>{row.plate}</strong><small>{row.code}</small></td><td>{row.handlers.map(h=>h.label).join('、')}</td><td>{row.cell.region}<small>{row.customerLabel}</small></td><td><span className={`fd-grade fd-grade-${row.level?.slice(0,2)}`}>{row.level||'未标注'}</span></td><td><span className={row.status==='已归档'?'fd-green':'fd-orange'}>{row.status==='已归档'?'已闭环':row.status}</span>{overdue&&<small className="fd-overdue-tag">已逾期</small>}</td><td className="fd-description" title={row.progress||row.description}>{row.progress||row.description||'暂无处置记录'}</td><td>{row.reportedAt||'未记录'}</td><td><button onClick={()=>drill(`${row.plate} · ${row.code}`,'ledger',{id:row.id})}>查看</button></td></tr>})}</tbody></table>{!rows.length&&<p className="fd-empty">{emptyMessage}</p>}</div>;
|
||||
}
|
||||
|
||||
@@ -24,13 +24,14 @@ export default function FaultManagement(){
|
||||
const query=new URLSearchParams({start:applied.start,end:applied.end,...applied.filters}).toString();
|
||||
useEffect(()=>{if(tab==='管理总览')return;const c=new AbortController();setLoading(true);setError('');fetchJson<FaultDashboardResponse>(`/api/asset-faults/dashboard?${query}`,{signal:c.signal}).then(d=>{if(!c.signal.aborted)setData(d);}).catch(e=>{if(!c.signal.aborted)setError(e instanceof Error?e.message:'加载失败');}).finally(()=>{if(!c.signal.aborted)setLoading(false);});return()=>c.abort();},[query,revision,tab]);
|
||||
useEffect(()=>{if(tab!=='故障明细')return;const c=new AbortController();setDetailData(null);setDetailError('');setDetailLoading(true);setLimit(50);fetchJson<FaultAnalysisResponse>(`/api/asset-faults/dashboard-analysis?${query}&scope=${detailScope}`,{signal:c.signal}).then(d=>{if(!c.signal.aborted)setDetailData(d);}).catch(()=>{if(!c.signal.aborted)setDetailError('故障明细加载失败,请重试。');}).finally(()=>{if(!c.signal.aborted)setDetailLoading(false);});return()=>c.abort();},[tab,query,detailScope,revision]);
|
||||
const drill:DashboardDrill=(title,scope='cohort',extra={})=>{if(loading||error||!data)return;const params=new URLSearchParams({start:data.start,end:data.end,...applied.filters,...extra,scope});setSource({url:`/api/asset-faults/dashboard-analysis?${params}`,title,periodLabel:scope==='cohort'?`${data.start} 至 ${data.end} · 按提报日期`:scope==='reported'||scope==='closed'?'北京时间今日':'全部提报日期 · 当前状态',defaultDimensions:extra.id?[]:['handler','faultStatus'],initialDetails:!!extra.id,definition:scope==='cohort'?'按提报日期筛选同批故障,已归档为已闭环,其余状态为未闭环。':scope==='overdue'?'逾期仅包含待处理、处理中且处置截止时间早于数据时间的故障;挂起、未设置截止时间不计入。':scope==='reported'?'按北京时间今日提报时间统计。':scope==='closed'?'按北京时间今日解决时间统计,不限制提报日期。':'不限制提报日期,按当前状态及已应用条件统计;当前在办 = 待处理 + 处理中。'});};
|
||||
const drill:DashboardDrill=(title,scope='cohort',extra={})=>{if(loading||error||!data)return;const params=new URLSearchParams({start:data.start,end:data.end,...applied.filters,...extra,scope});setSource({url:`/api/asset-faults/dashboard-analysis?${params}`,title,periodLabel:scope==='cohort'?`${data.start} 至 ${data.end} · 按提报日期`:scope==='reported'||scope==='closed'?'北京时间今日':'全部提报日期 · 当前状态',defaultDimensions:extra.id?[]:['handler','faultStatus'],initialDetails:!!extra.id,definition:scope==='focus'?'仅包含 L1-特急且未归档的故障(含待处理、处理中、挂起等状态),不限制提报日期。':scope==='cohort'?'按提报日期筛选同批故障,已归档为已闭环,其余状态为未闭环。':scope==='overdue'?'逾期仅包含待处理、处理中且处置截止时间早于数据时间的故障;挂起、未设置截止时间不计入。':scope==='reported'?'按北京时间今日提报时间统计。':scope==='closed'?'按北京时间今日解决时间统计,不限制提报日期。':'不限制提报日期,按当前状态及已应用条件统计;当前在办 = 待处理 + 处理中。'});};
|
||||
const t=data?.totals;
|
||||
const detailRows=(detailData?.rows||[]).filter(r=>`${r.code} ${r.plate} ${r.description} ${r.handlers.map(h=>h.label).join(' ')}`.toLowerCase().includes(search.trim().toLowerCase())).sort((a,b)=>(b.reportedAt||'').localeCompare(a.reportedAt||'')||b.id.localeCompare(a.id,'en',{numeric:true}));
|
||||
const dirty=range.start!==applied.start||range.end!==applied.end||JSON.stringify(filters)!==JSON.stringify(applied.filters);
|
||||
const count=(n?:number)=>loading?'—':n?.toLocaleString('zh-CN')??'—';
|
||||
const select=(key:FaultDashboardDimension)=><label className="fd-filter" key={key}><span>{FAULT_DASHBOARD_FILTERS[key]}</span><select aria-label={FAULT_DASHBOARD_FILTERS[key]} value={filters[key]||''} onChange={e=>setFilters(v=>({...v,[key]:e.target.value}))}><option value="">全部</option>{data?.options[key].map(o=><option key={o.value} value={o.value}>{o.label}</option>)}</select></label>;
|
||||
const showAllOpen=()=>{setDetailScope('open');setTab('故障明细');setSearch('');};
|
||||
const showAllFaults=()=>{setFilters({});setApplied({...range,filters:{}});setDetailScope('ledger');setTab('故障明细');setSearch('');};
|
||||
const navigation=<nav className="fd-tabs" aria-label="故障分析页面">{tabs.map(name=><button key={name} aria-current={tab===name?'page':undefined} onClick={()=>setTab(name)}>{name}</button>)}</nav>;
|
||||
if(tab==='管理总览')return <FaultOverview navigation={navigation}/>;
|
||||
return <div className="fault-page fd-page">
|
||||
@@ -41,12 +42,11 @@ export default function FaultManagement(){
|
||||
{error&&<div className="fault-message" role="alert">{error}<button onClick={()=>setRevision(v=>v+1)}>重试</button></div>}
|
||||
{!data&&loading?<div className="fd-loading" role="status"><RefreshCw className="animate-spin" size={20}/>正在汇总故障分析…</div>:data&&<div className={loading||error?'fd-content is-loading':'fd-content'} aria-busy={loading}>
|
||||
{tab==='多维分析'&&<>
|
||||
<section className="fd-kpis fd-kpis-five" aria-label="故障总统计">
|
||||
<article className="fd-kpi"><button disabled={loading||!!error} onClick={()=>drill('期间新增故障')}><ClipboardList className="fd-kpi-icon"/><span>期间新增故障</span><ArrowUpRight size={14}/><strong>{count(t?.reported)}<small>单</small></strong></button><p>对比上期 <b className={t?.change!=null&&t.change>0?'fd-orange':'fd-blue'}>{t?.change==null?'无可比基数':`${t.change>0?'+':''}${t.change.toFixed(1)}%`}</b><small>上期 {t?.previous} 单</small></p></article>
|
||||
<section className="fd-kpis" aria-label="故障总统计">
|
||||
<article className="fd-kpi fd-reported-kpi"><button disabled={loading||!!error} onClick={()=>drill('期间新增故障')}><ClipboardList className="fd-kpi-icon"/><span>期间新增故障</span><ArrowUpRight size={14}/><strong>{count(t?.reported)}<small>单</small></strong></button><p>对比上期 <b className={t?.change!=null&&t.change>0?'fd-orange':'fd-blue'}>{t?.change==null?'无可比基数':`${t.change>0?'+':''}${t.change.toFixed(1)}%`}</b><small>上期 {t?.previous} 单</small></p><div className="fd-kpi-parts fd-report-parts" aria-label="期间新增故障提报来源"><button disabled={loading||!!error} onClick={()=>drill('运维提报','cohort',{reportMethod:'operations'})}>运维提报 <b>{count(t?.operationsReported)}</b></button><span>+</span><button disabled={loading||!!error} onClick={()=>drill('AI提报','cohort',{reportMethod:'customer'})}>AI提报 <b>{count(t?.customerReported)}</b></button></div></article>
|
||||
<article className="fd-kpi"><button disabled={loading||!!error} onClick={()=>drill('受影响车辆对应故障')}><CarFront className="fd-kpi-icon fd-purple"/><span>受影响车辆</span><ArrowUpRight size={14}/><strong>{count(t?.vehicles)}<small>辆</small></strong></button><p>涉及 <b>{t?.customers}</b> 家已关联客户<small>按车辆去重</small></p></article>
|
||||
<article className="fd-kpi"><button disabled={loading||!!error} onClick={()=>drill('当前在办','open')}><Clock3 className="fd-kpi-icon fd-orange"/><span>当前在办</span><ArrowUpRight size={14}/><strong>{count(t?.open)}<small>单</small></strong></button><div className="fd-kpi-parts"><button disabled={loading||!!error} onClick={()=>drill('待处理','waiting')}>待处理 <b>{count(t?.waiting)}</b></button><span>+</span><button disabled={loading||!!error} onClick={()=>drill('处理中','processing')}>处理中 <b>{count(t?.processing)}</b></button></div></article>
|
||||
<article className="fd-kpi"><button disabled={loading||!!error} onClick={()=>drill('其中逾期','overdue')}><TriangleAlert className="fd-kpi-icon fd-danger"/><span>其中逾期</span><ArrowUpRight size={14}/><strong className="fd-danger">{count(t?.overdue)}<small>单</small></strong></button><p>最长逾期 <b className="fd-danger">{t?.longestOverdueDays} 天</b><small>在办子集</small></p></article>
|
||||
<article className="fd-kpi"><button disabled={loading||!!error} onClick={()=>drill('累计台账','ledger')}><ClipboardList className="fd-kpi-icon fd-purple"/><span>累计台账</span><ArrowUpRight size={14}/><strong>{count(t?.ledger)}<small>单</small></strong></button><p>全部有效故障台账<small>不限提报日期</small></p></article>
|
||||
<article className="fd-kpi"><button disabled={loading||!!error} onClick={()=>drill('逾期','overdue')}><TriangleAlert className="fd-kpi-icon fd-danger"/><span>逾期</span><ArrowUpRight size={14}/><strong className="fd-danger">{count(t?.overdue)}<small>单</small></strong></button><p>最长逾期 <b className="fd-danger">{t?.longestOverdueDays} 天</b><small>在办子集</small></p></article>
|
||||
</section>
|
||||
<div className="fd-today-stats"><span>实时统计</span><button onClick={()=>drill('今日新增','reported')}>今日新增 <b>{t?.todayReported}</b></button><button onClick={()=>drill('本日解决','closed')}>本日解决 <b>{t?.todayClosed}</b></button></div>
|
||||
<div className="fd-insight"><Info size={18}/><strong>{data.distributions.region[0]?`本期关注:${data.distributions.region[0].label}故障量最高,共 ${data.distributions.region[0].reported} 单;当前 ${t?.overdue} 单在办故障已逾期。`:'所选条件下暂无本期故障,可调整日期或筛选范围。'}</strong><span>按数量描述,不代表故障发生率。</span><button disabled={!t?.open} onClick={showAllOpen}>查看关联故障 <ArrowUpRight size={13}/></button></div>
|
||||
@@ -55,12 +55,12 @@ export default function FaultManagement(){
|
||||
<section className="fd-panel fd-focus" aria-label="重点故障跟进">
|
||||
<div className="fd-panel-title">
|
||||
<h2>重点故障跟进</h2>
|
||||
<span className="fd-chip fd-orange">当前在办 {t?.open}</span>
|
||||
<span className="fd-chip fd-danger">其中逾期 {t?.overdue}</span>
|
||||
<button onClick={showAllOpen}>查看全部 <ArrowUpRight size={13}/></button>
|
||||
<span className="fd-chip fd-orange">L1 未闭环 {data.focusTotals.total}</span>
|
||||
<span className="fd-chip fd-danger">逾期 {data.focusTotals.overdue}</span>
|
||||
<button onClick={showAllFaults} title="查看当前权限内的全部故障记录">查看全部 <ArrowUpRight size={13}/></button>
|
||||
</div>
|
||||
<DashboardTicketTable rows={data.focus} updatedAt={data.updatedAt} drill={drill}/>
|
||||
<p className="fd-caption">沿用当前业务筛选,不限制提报日期;优先展示逾期故障,同优先级按提报时间倒序,最多展示 5 单。完整明细见“查看全部”。</p>
|
||||
<DashboardTicketTable rows={data.focus} updatedAt={data.updatedAt} drill={drill} emptyMessage="当前筛选范围内暂无 L1 未闭环故障。"/>
|
||||
<p className="fd-caption">仅展示 L1-特急且未闭环(未归档)的故障;沿用当前业务筛选,不限制提报日期。逾期优先,同优先级按提报时间倒序,最多展示 5 单。“查看全部”进入当前权限内的全部故障台账,并清除业务筛选和搜索条件,不限等级、状态及提报日期。</p>
|
||||
</section>
|
||||
</>}
|
||||
{tab==='故障明细'&&<section className="fd-panel fd-details"><div className="fd-panel-title"><h2>故障明细</h2><span>按提报时间倒序 · {detailRows.length} 单</span><button onClick={()=>drill('故障明细多维分析',detailScope)}>多维分析 <ArrowUpRight size={13}/></button></div><div className="fd-detail-controls"><div className="fd-segment">{([['cohort','本期提报'],['open','当前在办'],['overdue','逾期故障'],['ledger','累计台账']] as const).map(([key,title])=><button key={key} aria-pressed={detailScope===key} onClick={()=>{setDetailScope(key);setSearch('');}}>{title}</button>)}</div><label><Search size={15}/><input placeholder="搜索车牌、单号、处置人" aria-label="搜索故障明细列表" value={search} onChange={e=>{setSearch(e.target.value);setLimit(50);}}/></label></div>{detailLoading?<p className="fd-loading" role="status">正在加载故障明细…</p>:detailError?<p role="alert" className="fault-message">{detailError}<button onClick={()=>setRevision(v=>v+1)}>重试</button></p>:<><DashboardTicketTable rows={detailRows.slice(0,limit)} updatedAt={detailData?.updatedAt||data.updatedAt} drill={drill}/>{detailRows.length>limit&&<button className="fd-load-more" onClick={()=>setLimit(v=>v+50)}>加载更多({Math.min(limit,detailRows.length)} / {detailRows.length})</button>}</>}</section>}
|
||||
|
||||
@@ -46,8 +46,8 @@ export function FaultOverview({ navigation }: { navigation: ReactNode }) {
|
||||
<p>{FAULT_DEFINITIONS[key]}</p><span className="fault-metric-link">查看分析与明细 →</span>
|
||||
</button>
|
||||
{key === 'open' && <>
|
||||
<button className="fault-overdue-subset" disabled={!data || loading || !!error} onClick={() => setMetric('overdue')} aria-label={`其中逾期 ${data?.totals.overdue ?? '加载中'} 单,查看分析`}>
|
||||
<span><span className="fault-overdue-prefix">其中</span>逾期</span><strong>{loading ? '—' : data?.totals.overdue?.toLocaleString('zh-CN') ?? '—'}</strong><small>单</small>
|
||||
<button className="fault-overdue-subset" disabled={!data || loading || !!error} onClick={() => setMetric('overdue')} aria-label={`逾期 ${data?.totals.overdue ?? '加载中'} 单,查看分析`}>
|
||||
<span>逾期</span><strong>{loading ? '—' : data?.totals.overdue?.toLocaleString('zh-CN') ?? '—'}</strong><small>单</small>
|
||||
</button>
|
||||
<div className="fault-open-breakdown" aria-label="当前在办等于待处理加处理中">
|
||||
{(['waiting', 'processing'] as const).map((part, index) => <Fragment key={part}>
|
||||
@@ -60,7 +60,7 @@ export function FaultOverview({ navigation }: { navigation: ReactNode }) {
|
||||
</>}
|
||||
</article>;
|
||||
})}</div>
|
||||
<p className="fault-summary-note">当前在办 = 待处理 + 处理中,其中逾期不重复累加;按处置截止时间统计,挂起停表,未设置截止时间不计入逾期。</p>
|
||||
<p className="fault-summary-note">当前在办 = 待处理 + 处理中,逾期为在办子集,不重复累加;按处置截止时间统计,挂起停表,未设置截止时间不计入逾期。</p>
|
||||
</section>
|
||||
<FaultTrendCard refresh={revision} />
|
||||
<FaultWeeklyReport refresh={revision} />
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { FaultDashboardResponse } from '../../../shared/assets/faults';
|
||||
export async function downloadDashboard(data:FaultDashboardResponse,filters:string) {
|
||||
const {default:ExcelJS}=await import('exceljs');const book=new ExcelJS.Workbook();book.creator='羚牛氢能 BI';
|
||||
const tables: {name:string;headers:string[];rows:(string|number)[][]}[]=[
|
||||
{name:'管理总览',headers:['指标','数量','口径'],rows:[['期间新增故障',data.totals.reported,'按提报日期'],['受影响车辆',data.totals.vehicles,'本期故障车辆去重'],['当前在办',data.totals.open,'全部待处理 + 处理中'],['其中逾期',data.totals.overdue,'当前在办中超过处置截止时间'],['待处理',data.totals.waiting,'全部待处理'],['处理中',data.totals.processing,'全部处理中'],['今日新增',data.totals.todayReported,'北京时间今日提报'],['本日解决',data.totals.todayClosed,'北京时间今日解决'],['累计台账',data.totals.ledger,'当前筛选范围的全部有效故障']]},
|
||||
{name:'管理总览',headers:['指标','数量','口径'],rows:[['期间新增故障',data.totals.reported,'按提报日期'],['运维提报',data.totals.operationsReported,'本期新增故障中的运维上报'],['AI提报',data.totals.customerReported,'本期新增故障中的客户上报'],['受影响车辆',data.totals.vehicles,'本期故障车辆去重'],['当前在办',data.totals.open,'全部待处理 + 处理中'],['逾期',data.totals.overdue,'当前在办中超过处置截止时间'],['待处理',data.totals.waiting,'全部待处理'],['处理中',data.totals.processing,'全部处理中'],['今日新增',data.totals.todayReported,'北京时间今日提报'],['本日解决',data.totals.todayClosed,'北京时间今日解决'],['累计台账',data.totals.ledger,'当前筛选范围的全部有效故障']]},
|
||||
...Object.entries(data.distributions).map(([key,rows])=>({name:({region:'区域分布',level:'故障程度',customer:'客户影响',model:'车型分布'} as Record<string,string>)[key],headers:['分组','本期故障','已闭环','未闭环','影响车辆','当前在办'],rows:rows.map(r=>[r.label,r.reported,r.closed,r.unclosed,r.vehicles,r.open])})),
|
||||
{name:'车型与部位',headers:['品牌车型','故障部位','故障数量'],rows:data.matrix.cells.filter(c=>c.count).map(c=>[c.model,c.category,c.count])},
|
||||
];
|
||||
|
||||
@@ -107,19 +107,27 @@
|
||||
.fault-overview-page .fault-trend-heading h2 { font-size:13px; }
|
||||
}
|
||||
.app-shell-content:has(>.fault-overview-page)>.fixed.top-0 { display:none; }
|
||||
.fd-kpis-five { grid-template-columns:repeat(5,minmax(0,1fr)); }
|
||||
.fd-kpis-five>.fd-kpi { display:flex; flex-direction:column; }
|
||||
.fd-kpis-five .fd-kpi>button { flex-shrink:0; }
|
||||
.fd-kpis-five .fd-kpi>p,
|
||||
.fd-kpis-five .fd-kpi-parts { margin-top:auto; min-height:24px; }
|
||||
.fd-kpis-five .fd-kpi>p { align-items:center; }
|
||||
.fd-kpis-five .fd-kpi-parts { gap:5px; }
|
||||
.fd-kpis-five .fd-kpi-parts button {
|
||||
.fd-kpis>.fd-kpi { display:flex; flex-direction:column; }
|
||||
.fd-kpis .fd-kpi>button { flex-shrink:0; }
|
||||
.fd-kpis .fd-kpi>p,
|
||||
.fd-kpis .fd-kpi-parts { margin-top:auto; min-height:24px; }
|
||||
.fd-kpis .fd-kpi>p { align-items:center; }
|
||||
.fd-kpis .fd-kpi-parts { gap:5px; }
|
||||
.fd-kpis .fd-kpi-parts button {
|
||||
height:24px; min-width:0; padding:3px 7px; line-height:18px; white-space:nowrap;
|
||||
}
|
||||
.fd-kpis-five .fd-kpi-parts b { line-height:18px; }
|
||||
.fd-kpis-five .fd-kpi-parts>span { line-height:24px; font-size:12px; }
|
||||
.fd-kpis .fd-kpi-parts b { line-height:18px; }
|
||||
.fd-kpis .fd-kpi-parts>span { line-height:24px; font-size:12px; }
|
||||
@media(max-width:1100px) {
|
||||
.fd-kpis-five { grid-template-columns:repeat(2,minmax(0,1fr)); }
|
||||
.fd-kpis-five>.fd-kpi:last-child { grid-column:1/-1; }
|
||||
.fd-kpis { grid-template-columns:repeat(2,minmax(0,1fr)); }
|
||||
}
|
||||
|
||||
/* Keep the report-source breakdown and comparison readable at both card widths. */
|
||||
.fd-kpis>.fd-kpi { height:148px; }
|
||||
.fd-kpis .fd-report-parts { margin-top:auto; }
|
||||
.fd-kpis .fd-reported-kpi>p { min-height:16px; margin-top:6px; }
|
||||
@media(max-width:767px) {
|
||||
.fd-kpis>.fd-kpi { height:142px; }
|
||||
.fd-kpis .fd-report-parts { gap:3px; }
|
||||
.fd-kpis .fd-report-parts button { padding:3px 4px; }
|
||||
}
|
||||
|
||||
@@ -40,3 +40,97 @@ test('dashboard and report endpoints enforce authentication, permissions, dates
|
||||
const trend=await(await app.request('/f/trend?start=2026-10-12&end=2026-10-13&level=未标注')).json();assert.equal(trend.totals.reported,0);
|
||||
const weekly=await(await app.request('/f/weekly-report?start=2026-10-12&end=2026-10-13&level=未标注')).json();assert.equal(weekly.totals.reported,0);
|
||||
});
|
||||
|
||||
test('focus contains only L1 unclosed faults across all dates and keeps totals and full drill consistent', () => {
|
||||
const focusRows = [
|
||||
fault('waiting', { reported_at: '2026-09-01 08:00:00' }),
|
||||
fault('processing', { handling_status: '处理中', deadline_at: '2026-10-12 15:00:00' }),
|
||||
fault('paused', { handling_status: '挂起', deadline_at: '2026-10-01 08:00:00' }),
|
||||
fault('review', { handling_status: '审核中' }),
|
||||
fault('unknown', { handling_status: '其他状态' }),
|
||||
fault('sixth'),
|
||||
fault('seventh'),
|
||||
fault('closed', { handling_status: '已归档' }),
|
||||
fault('l2-overdue', { fault_level: 2, deadline_at: '2026-10-01 08:00:00' }),
|
||||
fault('l3', { fault_level: 3 }),
|
||||
fault('l4', { fault_level: 4 }),
|
||||
fault('unmarked', { fault_level: null }),
|
||||
];
|
||||
const dashboard = faultDashboard(focusRows, q, updatedAt);
|
||||
assert.deepEqual(dashboard.focusTotals, { total: 7, overdue: 1 });
|
||||
assert.equal(dashboard.focus.length, 5);
|
||||
assert.equal(dashboard.focus[0].id, 'processing');
|
||||
assert.ok(dashboard.focus.every(row => row.level === 'L1-特急' && row.status !== '已归档'));
|
||||
const allFocus = dashboardAnalysis(focusRows, { ...q, scope: 'focus' }, updatedAt).rows;
|
||||
assert.equal(allFocus.length, dashboard.focusTotals.total);
|
||||
assert.ok(allFocus.some(row => row.id === 'waiting'));
|
||||
assert.ok(allFocus.some(row => row.id === 'paused'));
|
||||
assert.ok(allFocus.some(row => row.id === 'review'));
|
||||
assert.ok(allFocus.every(row => !('vehicleKey' in row) && !('managerId' in row)));
|
||||
assert.deepEqual(dashboardAnalysis(focusRows, { ...q, scope: 'focus', id: 'closed' }, updatedAt).rows, []);
|
||||
const filtered = faultDashboard(focusRows, { ...q, level: 'L2-紧急' }, updatedAt);
|
||||
assert.deepEqual(filtered.focus, []);
|
||||
assert.deepEqual(filtered.focusTotals, { total: 0, overdue: 0 });
|
||||
assert.deepEqual(dashboardAnalysis(focusRows, { ...q, scope: 'focus', level: 'L2-紧急' }, updatedAt).rows, []);
|
||||
});
|
||||
test('focus dashboard and full drill enforce permissions and business filters before selecting L1 faults', async () => {
|
||||
const scopedRows = [fault('allowed'), fault('outside', { business_dept: '部门B' }), fault('closed', { handling_status: '已归档' }), fault('lower', { fault_level: 2 })];
|
||||
const user: AuthUser = { userId: 'test', loginName: 'test', userName: '测试', roles: [], permissionLevel: 'department', depName: '部门A', depCode: 'a' };
|
||||
const app = new Hono<{ Variables: { user: AuthUser } }>();
|
||||
app.use('*', async (c, next) => { c.set('user', user); await next(); });
|
||||
app.route('/f', createFaultRouter(async () => ({ rows: scopedRows, updatedAt })));
|
||||
const report = await (await app.request('/f/dashboard?start=2026-10-12&end=2026-10-13')).json();
|
||||
assert.deepEqual(report.focus.map((row: { id: string }) => row.id), ['allowed']);
|
||||
assert.deepEqual(report.focusTotals, { total: 1, overdue: 0 });
|
||||
const response = await app.request('/f/dashboard-analysis?start=2026-10-12&end=2026-10-13&scope=focus');
|
||||
assert.equal(response.status, 200);
|
||||
const detail = await response.json();
|
||||
assert.deepEqual(detail.rows.map((row: { id: string }) => row.id), ['allowed']);
|
||||
const empty = await (await app.request('/f/dashboard-analysis?scope=focus&department=不存在')).json();
|
||||
assert.deepEqual(empty.rows, []);
|
||||
});
|
||||
|
||||
test('report source follows explicit OneOS report method before legacy task linkage', () => {
|
||||
const cases: [Record<string, unknown>, 'operations' | 'customer'][] = [
|
||||
[{ report_method: '运维上报', source_work_order_id: '9007199254740993' }, 'operations'],
|
||||
[{ report_method: '客户上报', source_work_order_id: null }, 'customer'],
|
||||
[{ report_method: ' 客户上报 ', source_work_order_id: '123' }, 'customer'],
|
||||
[{ report_method: null, source_work_order_id: '9007199254740993' }, 'customer'],
|
||||
[{ report_method: '', source_work_order_id: null }, 'operations'],
|
||||
[{ report_method: null, source_work_order_id: null, fault_source: 6 }, 'operations'],
|
||||
];
|
||||
for (const [raw, expected] of cases) assert.equal(fault('source', raw).reportMethod, expected);
|
||||
});
|
||||
test('reported source counts reconcile with cohort, filtered drills, permissions and export labels', async () => {
|
||||
const sourceRows = [
|
||||
fault('ops-linked', { report_method: '运维上报', source_work_order_id: '123' }),
|
||||
fault('ai-explicit', { report_method: '客户上报', source_work_order_id: null }),
|
||||
fault('ai-legacy', { report_method: null, source_work_order_id: '9007199254740993', handling_status: '已归档' }),
|
||||
fault('ops-legacy', { report_method: null, source_work_order_id: null }),
|
||||
fault('previous-ai', { report_method: '客户上报', reported_at: '2026-10-10 10:00:00' }),
|
||||
fault('hidden-ai', { report_method: '客户上报', business_dept: '部门B' }),
|
||||
];
|
||||
const user: AuthUser = { userId: 'test', loginName: 'test', userName: '测试', roles: [], permissionLevel: 'department', depName: '部门A', depCode: 'a' };
|
||||
const app = new Hono<{ Variables: { user: AuthUser } }>();
|
||||
app.use('*', async (c, next) => { c.set('user', user); await next(); });
|
||||
app.route('/f', createFaultRouter(async () => ({ rows: sourceRows, updatedAt })));
|
||||
const query = new URLSearchParams(q);
|
||||
const report = await (await app.request(`/f/dashboard?${query}`)).json();
|
||||
assert.equal(report.totals.reported, 4);
|
||||
assert.equal(report.totals.operationsReported, 2);
|
||||
assert.equal(report.totals.customerReported, 2);
|
||||
assert.equal(report.totals.operationsReported + report.totals.customerReported, report.totals.reported);
|
||||
assert.equal(report.options.reportMethod.find((o: { value: string }) => o.value === 'customer').label, 'AI提报');
|
||||
assert.equal(report.options.reportMethod.find((o: { value: string }) => o.value === 'operations').label, '运维提报');
|
||||
for (const [method, expected] of [['operations', ['ops-linked', 'ops-legacy']], ['customer', ['ai-explicit', 'ai-legacy']]] as const) {
|
||||
const response = await app.request(`/f/dashboard-analysis?${query}&scope=cohort&reportMethod=${method}`);
|
||||
assert.equal(response.status, 200);
|
||||
const detail = await response.json();
|
||||
assert.deepEqual(detail.rows.map((row: { id: string }) => row.id).sort(), [...expected].sort());
|
||||
const filtered = await (await app.request(`/f/dashboard?${query}&reportMethod=${method}`)).json();
|
||||
assert.equal(filtered.totals.reported, expected.length);
|
||||
assert.equal(filtered.totals.operationsReported + filtered.totals.customerReported, filtered.totals.reported);
|
||||
}
|
||||
const empty = await (await app.request(`/f/dashboard?${query}®ion=不存在`)).json();
|
||||
assert.equal(empty.totals.operationsReported, 0); assert.equal(empty.totals.customerReported, 0);
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FAULT_DASHBOARD_FILTERS, type FaultDashboardDimension, type FaultDashboardResponse, type FaultDashboardScope } from '../../../shared/assets/faults.js';
|
||||
import { FAULT_REPORT_METHODS, FAULT_DASHBOARD_FILTERS, type FaultDashboardDimension, type FaultDashboardResponse, type FaultDashboardScope } from '../../../shared/assets/faults.js';
|
||||
import { faultAnalysis, faultOverview, isOverdueFault, type ScopedFault } from './model.js';
|
||||
import { parseFaultTrendQuery, selectFaultCohort } from './trend.js';
|
||||
|
||||
@@ -7,9 +7,11 @@ export function dashboardValues(row: ScopedFault, key: FaultDashboardDimension):
|
||||
if (key === 'level') return [row.level || '未标注'];
|
||||
if (key === 'category') return row.categories?.length ? row.categories : ['未标注'];
|
||||
if (key === 'inventory') return [row.inventory];
|
||||
if (key === 'reportMethod') return [row.reportMethod || 'operations'];
|
||||
return [row.assetCell[key]];
|
||||
}
|
||||
function label(row: ScopedFault, key: FaultDashboardDimension, value: string) {
|
||||
if (key === 'reportMethod') return FAULT_REPORT_METHODS[value as keyof typeof FAULT_REPORT_METHODS] || value;
|
||||
return key === 'customer' ? row.customerLabel : key === 'handler' ? row.handlers.find(h => h.value === value)?.label || value : value;
|
||||
}
|
||||
export function filterDashboardRows(rows: ScopedFault[], params: Record<string, string>) {
|
||||
@@ -18,15 +20,19 @@ export function filterDashboardRows(rows: ScopedFault[], params: Record<string,
|
||||
export function parseDashboardQuery(params: Record<string, string>) {
|
||||
const query = parseFaultTrendQuery({ start: params.start, end: params.end });
|
||||
const scope = params.scope || 'cohort';
|
||||
if (!['cohort', 'open', 'waiting', 'processing', 'overdue', 'ledger', 'reported', 'closed'].includes(scope)) throw new Error('无效统计范围');
|
||||
if (!['focus', 'cohort', 'open', 'waiting', 'processing', 'overdue', 'ledger', 'reported', 'closed'].includes(scope)) throw new Error('无效统计范围');
|
||||
return { ...query, scope: scope as FaultDashboardScope };
|
||||
}
|
||||
function selectFocusFaults(rows: ScopedFault[]) {
|
||||
return rows.filter(row => row.level === 'L1-特急' && row.status !== '已归档');
|
||||
}
|
||||
export function dashboardAnalysis(rows: ScopedFault[], params: Record<string, string>, updatedAt: string) {
|
||||
const query = parseDashboardQuery(params);
|
||||
let selected = filterDashboardRows(rows, params);
|
||||
if (params.id) selected = selected.filter(row => row.id === params.id);
|
||||
if (query.scope === 'cohort') selected = selectFaultCohort(selected, query);
|
||||
return faultAnalysis(selected, query.scope === 'cohort' ? 'ledger' : query.scope, updatedAt);
|
||||
if (query.scope === 'focus') selected = selectFocusFaults(selected);
|
||||
return faultAnalysis(selected, query.scope === 'cohort' || query.scope === 'focus' ? 'ledger' : query.scope, updatedAt);
|
||||
}
|
||||
export function faultDashboard(visible: ScopedFault[], params: Record<string, string>, updatedAt: string): FaultDashboardResponse {
|
||||
const query = parseDashboardQuery(params);
|
||||
@@ -56,9 +62,11 @@ export function faultDashboard(visible: ScopedFault[], params: Record<string, st
|
||||
const duration = Date.parse(query.end) - Date.parse(query.start) + 86400000;
|
||||
const previousStart = new Date(Date.parse(query.start) - duration).toISOString().slice(0,10);
|
||||
const previous = all.filter(r => r.reportedAt && r.reportedAt.slice(0,10) >= previousStart && r.reportedAt.slice(0,10) < query.start).length;
|
||||
const focus = faultAnalysis([...open].sort((a,b)=> Number(isOverdueFault(b,updatedAt))-Number(isOverdueFault(a,updatedAt)) || (b.reportedAt||'').localeCompare(a.reportedAt||'')).slice(0,5), 'ledger', updatedAt).rows;
|
||||
return { start:query.start,end:query.end,updatedAt,options,distributions,matrix,focus,
|
||||
totals: { reported:cohort.length,vehicles:vehicles(cohort),customers:new Set(cohort.filter(r=>!['unlinked','inventory-unlinked'].includes(r.customer)).map(r=>r.customer)).size,
|
||||
const focusRows = selectFocusFaults(all);
|
||||
const focusTotals = { total: focusRows.length, overdue: focusRows.filter(row => isOverdueFault(row, updatedAt)).length };
|
||||
const focus = faultAnalysis([...focusRows].sort((a,b)=> Number(isOverdueFault(b,updatedAt))-Number(isOverdueFault(a,updatedAt)) || (b.reportedAt||'').localeCompare(a.reportedAt||'')).slice(0,5), 'ledger', updatedAt).rows;
|
||||
return { start:query.start,end:query.end,updatedAt,options,distributions,matrix,focus,focusTotals,
|
||||
totals: { reported:cohort.length,operationsReported:cohort.filter(r=>r.reportMethod!=='customer').length,customerReported:cohort.filter(r=>r.reportMethod==='customer').length,vehicles:vehicles(cohort),customers:new Set(cohort.filter(r=>!['unlinked','inventory-unlinked'].includes(r.customer)).map(r=>r.customer)).size,
|
||||
previous,change:previous ? (cohort.length-previous)/previous*100 : null,open:overview.open,waiting:overview.waiting,processing:overview.processing,overdue:overview.overdue,
|
||||
longestOverdueDays:Math.max(0,...overdue.map(r=>Math.ceil((Date.parse(updatedAt)-Date.parse(`${r.deadlineAt!.replace(' ','T')}+08:00`))/86400000))),
|
||||
todayReported:overview.reported,todayClosed:overview.closed,ledger:all.length },
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { FAULT_DIMENSIONS, FAULT_OVERVIEW_METRICS, type FaultDimension, type FaultOption, type FaultRecord, type FaultQuery, type FaultResponse } from '../../../shared/assets/faults.js';
|
||||
import { FAULT_DIMENSIONS, FAULT_OVERVIEW_METRICS, type FaultDimension, type FaultOption, type FaultRecord, type FaultQuery, type FaultResponse, type FaultReportMethod } from '../../../shared/assets/faults.js';
|
||||
import type { AuthUser } from '../../auth/types.js';
|
||||
import { filterByPermission, maskCustomerName } from '../../auth/permissions.js';
|
||||
import type { AssetAnalysisCell } from '../../../shared/assets/analytics.js';
|
||||
@@ -28,6 +28,13 @@ function array(value: unknown, preserveIds = false): unknown[] {
|
||||
}
|
||||
const text = (value: unknown) => String(value ?? '').trim();
|
||||
const positiveId = (value: unknown) => /^[1-9]\d*$/.test(text(value));
|
||||
// Match OneOS reportMethod: explicit source wins, task linkage is a legacy fallback.
|
||||
export function faultReportMethod(row: RawFault): FaultReportMethod {
|
||||
const method = text(row.report_method);
|
||||
if (method === '运维上报') return 'operations';
|
||||
if (method === '客户上报') return 'customer';
|
||||
return positiveId(row.source_work_order_id) ? 'customer' : 'operations';
|
||||
}
|
||||
export function faultHandlers(row: RawFault, directory: Map<string, string>): FaultOption[] {
|
||||
const candidates = [
|
||||
[array(row.work_ids, true), array(row.work_names)],
|
||||
@@ -81,7 +88,7 @@ export function mapFault(row: RawFault, directory: Map<string, string>): ScopedF
|
||||
vehicleKey: text(row.matched_vehicle_id) || (text(row.plate_number) ? `plate:${text(row.plate_number)}` : ''),
|
||||
level: text(row.level_label) || ({ '1': 'L1-特急', '2': 'L2-紧急', '3': 'L3-一般', '4': 'L4-提示' } as Record<string, string>)[text(row.fault_level)] || '未标注',
|
||||
categories: [...new Set(text(row.fault_categories).split(/[,,、;;]/).map(v => v.trim()).filter(Boolean))],
|
||||
progress: text(row.solve_process),
|
||||
progress: text(row.solve_process), reportMethod: faultReportMethod(row),
|
||||
id: text(row.id), code: text(row.fault_code), plate: text(row.plate_number) || '未关联车辆',
|
||||
description: text(row.fault_desc), reportedAt: text(row.reported_at) || null, archivedAt: text(row.archived_at) || null, deadlineAt: text(row.deadline_at) || null, receivedAt: text(row.received_at) || null,
|
||||
city, status: normalizeFaultStatus(row.handling_status), assetCell,
|
||||
|
||||
@@ -4,7 +4,8 @@ import { mapFault, type RawFault } from './model.js';
|
||||
|
||||
// OneOS fault ledger: latest delivery first; do not reuse the active-asset WHERE clause.
|
||||
export const FAULT_SQL = `SELECT
|
||||
f.fault_level, f.fault_categories, f.solve_process,
|
||||
f.fault_level, f.fault_categories, f.solve_process, f.report_method,
|
||||
CAST(f.source_work_order_id AS CHAR) source_work_order_id,
|
||||
CAST(f.id AS CHAR) id, f.fault_code, f.plate_number, f.fault_desc, f.handling_status,
|
||||
DATE_FORMAT(f.fault_report_time, '%Y-%m-%d %H:%i:%s') reported_at,
|
||||
DATE_FORMAT(f.archived_at, '%Y-%m-%d %H:%i:%s') archived_at,
|
||||
|
||||
@@ -8,13 +8,15 @@ export type FaultDimension = keyof typeof FAULT_DIMENSIONS;
|
||||
export type FaultMetric = 'reported' | 'closed' | 'open';
|
||||
export interface FaultOption { value: string; label: string }
|
||||
export interface FaultCounts { reported: number; closed: number; open: number }
|
||||
export const FAULT_REPORT_METHODS = { operations: '运维提报', customer: 'AI提报' } as const;
|
||||
export type FaultReportMethod = keyof typeof FAULT_REPORT_METHODS;
|
||||
export interface FaultRecord {
|
||||
id: string; code: string; plate: string; description: string;
|
||||
reportedAt: string | null; archivedAt: string | null; deadlineAt: string | null; receivedAt: string | null;
|
||||
city: string; status: string; inventory: string;
|
||||
customer: string; customerLabel: string; department: string;
|
||||
handlers: FaultOption[];
|
||||
level?: string; categories?: string[]; progress?: string;
|
||||
level?: string; categories?: string[]; progress?: string; reportMethod?: FaultReportMethod;
|
||||
}
|
||||
export interface FaultQuery {
|
||||
start: string; end: string; groupBy: FaultDimension;
|
||||
@@ -65,17 +67,18 @@ export interface FaultWeeklyResponse {
|
||||
days: (Record<FaultWeeklyMetric, number> & { date: string })[];
|
||||
}
|
||||
|
||||
export const FAULT_DASHBOARD_FILTERS = { region: '区域', customer: '客户', model: '品牌车型', city: '城市', department: '业务部门', handler: '运维处置人', level: '故障程度', category: '故障部位', inventory: '库存状态' } as const;
|
||||
export const FAULT_DASHBOARD_FILTERS = { region: '区域', customer: '客户', model: '品牌车型', city: '城市', department: '业务部门', handler: '运维处置人', level: '故障程度', category: '故障部位', inventory: '库存状态', reportMethod: '提报来源' } as const;
|
||||
export type FaultDashboardDimension = keyof typeof FAULT_DASHBOARD_FILTERS;
|
||||
export type FaultDashboardFilters = Partial<Record<FaultDashboardDimension, string>>;
|
||||
export type FaultDashboardScope = 'cohort' | 'open' | 'waiting' | 'processing' | 'overdue' | 'ledger' | 'reported' | 'closed';
|
||||
export type FaultDashboardScope = 'focus' | 'cohort' | 'open' | 'waiting' | 'processing' | 'overdue' | 'ledger' | 'reported' | 'closed';
|
||||
export interface FaultDistribution { value: string; label: string; reported: number; closed: number; unclosed: number; vehicles: number; open: number }
|
||||
export interface FaultDashboardResponse {
|
||||
start: string; end: string; updatedAt: string;
|
||||
totals: { reported: number; vehicles: number; customers: number; previous: number; change: number | null; open: number; waiting: number; processing: number; overdue: number; longestOverdueDays: number; todayReported: number; todayClosed: number; ledger: number };
|
||||
totals: { reported: number; operationsReported: number; customerReported: number; vehicles: number; customers: number; previous: number; change: number | null; open: number; waiting: number; processing: number; overdue: number; longestOverdueDays: number; todayReported: number; todayClosed: number; ledger: number };
|
||||
options: Record<FaultDashboardDimension, FaultOption[]>;
|
||||
distributions: Record<'region' | 'level' | 'customer' | 'model', FaultDistribution[]>;
|
||||
matrix: { models: FaultOption[]; categories: FaultOption[]; cells: { model: string; category: string; count: number }[]; totals: Record<string, number> };
|
||||
focus: FaultAnalysisRecord[];
|
||||
focusTotals: { total: number; overdue: number };
|
||||
quality: { missingLevel: number; missingCategory: number; missingVehicle: number; missingDeadline: number; missingReport: number };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user