同步:完善质量分析工作台并更新主题字体

同步已上线的智能分析执行协议、来源查询、图表报告与管理页面配套代码。
补齐数据库迁移、运行依赖和回归测试,保留原有指标计算口径。
统一午夜黑及其他主题的控件细节、中文和业务数字字体。
排除本地业务数据、凭据、预览、发布与验收产物。

验证:生产构建通过,320项前端回归通过;本轮仅同步Git,不再次部署。
This commit is contained in:
2026-10-30 22:40:58 +08:00
parent edef747e3b
commit ff7bbe3e46
393 changed files with 62999 additions and 1783 deletions
+245
View File
@@ -0,0 +1,245 @@
"""Rank formal stage weights; all shares retain the full authorized denominator."""
from decimal import Decimal
import math
FIELDS = {'totalWeight':'投入重量', 'scrapWeight':'报废重量'}
DIMENSIONS = {'product':'产品规格', 'department':'产业部', 'group':'业务分组'}
def ranking_task(task):
return bool(_ranking_shape(task) and not task.get('comparisonPeriod')
and not task.get('comparisonRequired') and not task.get('trendRequired'))
def _ranking_shape(task):
"""Shared structural gate for weight-ranking tasks and compound requests."""
if not (task and task.get('period') and task.get('kind') in ('analysis','metrics','report')
and isinstance(task.get('dimensions'), list) and task['dimensions']
and set(task['dimensions']) <= set(DIMENSIONS)
and isinstance(task.get('fields'), list) and task['fields']
and set(task['fields']) <= set(FIELDS)
and task.get('visualType') in ('pareto','bar','column',None)):
return False
# A rank requires a concrete black/bright stage for every requested
# dimension. Empty dimensionStages denotes a combined view and cannot be
# silently converted into two stage-specific rankings.
from nao_agent_task import dimension_stages
return all((stages := dimension_stages(task, dimension, combined=False))
and all(stage in ('black', 'bright') for stage in stages)
for dimension in task['dimensions'])
def ranking_intent(task):
"""A structurally valid ranking request, including incompatible trend/compare asks."""
return _ranking_shape(task)
def source_period(coverage, period, stage):
from nao_period import expected_months
expected = expected_months(period)
months = coverage.get('sourceMonths') if isinstance(coverage,dict) else None
available = sorted({row['month'] for row in months or [] if isinstance(row,dict)
and row.get('year')==period['year'] and row.get('month') in expected
and isinstance(row.get(stage+'Rows'),int) and row[stage+'Rows']>0})
missing = [m for m in expected if m not in available]
internal = [m for m in missing if available and m <= available[-1]]
suffix = (str(available[0])+'月' if len(available)==1 else
str(available[0])+'—'+str(available[-1])+'月' if not internal else
'、'.join(map(str,available))+'月') if available else '无已发布月份'
return {'availableMonths':available,'missingMonths':missing,'internalMissingMonths':internal,
'complete':not missing,'label':str(period['year'])+'年'+suffix+'已发布数据'}
def rank_response(response, release, period, filters, dimension, stage, metric, limit):
from nao_quality_tools import _number, QualityToolError
rows = response.get('rows')
if not isinstance(rows,list) or len(rows)>100000:
raise QualityToolError('分组重量未取得完整有界结果,不能作为全量排名。')
if (response.get('context') or {}).get('rowCount',len(rows)) != len(rows):
raise QualityToolError('分组数据已被截断,不能以其生成全量排名。')
denominator = _number((response.get('summary',{}).get(stage) or {}).get(metric),minimum=Decimal(0))
if denominator is None or denominator<=0:
raise QualityToolError('所选阶段的正式重量总量不可用,不能计算占比。')
allow_signed_black_total = stage == 'black' and metric == 'totalWeight'
all_rows=[]
seen=set()
unavailable_groups=0
for row in rows:
if not isinstance(row, dict):
raise QualityToolError('分组行结构无效,不能生成全量排名。')
key=str(row.get('key') or '')
if not key or key in seen:raise QualityToolError('分组标识缺失或重复,不能生成全量排名。')
seen.add(key)
raw_value=_number((row.get(stage) or {}).get(metric))
if raw_value is not None and raw_value<0 and not allow_signed_black_total:
raise QualityToolError('除黑片投入重量负向修正外,分组重量不能为负。')
value=raw_value if allow_signed_black_total else _number((row.get(stage) or {}).get(metric),minimum=Decimal(0))
if value is None:
if (row.get('coverage') or {}).get(stage+'Rows')==0:
unavailable_groups+=1
continue
raise QualityToolError('分组重量有缺失或无效值,未将缺失补零。')
all_rows.append({'key':key,'label':str(row.get('label') or key),'weight':value})
grouped=sum((row['weight'] for row in all_rows),Decimal(0))
if abs(grouped-denominator)>max(Decimal('.00001'),abs(denominator)*Decimal('1e-10')):
raise QualityToolError('分组重量合计与同范围正式总量不一致,不能计算全量占比。')
all_rows.sort(key=lambda row:(-row['weight'],row['key']))
positive=[row for row in all_rows if row['weight']>0]
negative=[row for row in all_rows if row['weight']<0]
negative_weight=sum((row['weight'] for row in negative),Decimal(0))
selected=[]; cumulative=Decimal(0)
for index,row in enumerate(positive[:limit]):
cumulative+=row['weight']
selected.append({**row,'weight':float(row['weight']),'rank':index+1,
'share':float(row['weight']/denominator),'cumulativeShare':float(cumulative/denominator)})
coverage=response.get('coverage') or {}
result = {'kind':'quality_weight_ranking','release':release,'releaseId':release['id'],
'period':period,'filters':filters,'dimension':dimension,'stage':stage,'metric':metric,
'totalWeight':float(denominator),'rows':selected,'totalRows':len(positive),
'returnedRows':len(selected),'truncated':len(selected)<len(positive),
'rankingCoverage':{'sourceGroups':len(rows),'groups':len(all_rows),
'unavailableGroups':unavailable_groups,'positiveGroups':len(positive),
'negativeGroups':len(negative),'negativeWeight':float(negative_weight),
'negativeWeightMagnitude':float(abs(negative_weight)),'completeRanking':True},
'coverage':coverage,'periodCoverage':source_period(coverage,period,stage),
'shareBasis':'all_scope_weight',
'basis':'先读取同范围全部正式分组值,再按所选阶段重量降序选Top;占比和累计占比的分母均为同范围全量正式重量,Top末项不强制为100%。'}
if isinstance(response.get('protocolEvidence'), dict):
result['protocolEvidence'] = response['protocolEvidence']
return result
def matching_rankings(evidence,task,context):
from nao_evidence_report import _filters
return [d for d in evidence if d.get('result',{}).get('kind')=='quality_weight_ranking'
and d['result'].get('releaseId')==context.get('releaseId',d['result'].get('releaseId'))
and d['result'].get('period')==task.get('period')
and _filters(d['result'].get('filters'))==_filters(task.get('filters'))]
def ranking_gaps(evidence,task,context):
from nao_agent_task import dimension_stages
docs=matching_rankings(evidence,task,context);gaps=[]
for dimension in task['dimensions']:
for stage in dimension_stages(task, dimension, combined=False):
for metric in task['fields']:
candidates=[d['result'] for d in docs if d['result'].get('dimension')==dimension
and d['result'].get('stage')==stage and d['result'].get('metric')==metric]
def valid(result):
proof=result.get('rankingCoverage',{});period=source_period(result.get('coverage'),result['period'],stage)
rows=result.get('rows');denominator=result.get('totalWeight')
return (proof.get('completeRanking') is True and isinstance(rows,list) and bool(rows)
and isinstance(denominator,(int,float)) and not isinstance(denominator,bool)
and math.isfinite(denominator) and denominator>0
and period['availableMonths'] and not period['internalMissingMonths']
and (task.get('periodCoverage','available')!='complete' or period['complete']))
if not any(valid(r) for r in candidates):
gaps.append('未取得'+DIMENSIONS[dimension]+'级'+('黑片' if stage=='black' else '亮片')+FIELDS[metric]+'完整排名及同范围全量分母。')
return gaps
def _negative_correction_chart_limit(result):
if (result.get('stage') != 'black' or result.get('metric') != 'totalWeight'
or (result.get('rankingCoverage') or {}).get('negativeGroups', 0) <= 0):
return False
denominator=result.get('totalWeight');rows=result.get('rows')
if (not isinstance(denominator,(int,float)) or isinstance(denominator,bool)
or not math.isfinite(denominator) or not isinstance(rows,list)):
return False
weights=[row.get('weight') for row in rows[:10] if isinstance(row,dict)]
if any(not isinstance(value,(int,float)) or isinstance(value,bool) or not math.isfinite(value) for value in weights):
return False
return sum(weights)>denominator+max(.00001,abs(denominator)*1e-10)
def ranking_chart(document,turn_id,task):
from nao_agent_task import dimension_stages
from analysis_visuals import _chart,_chart_scope,_scope,_period
r=document.get('result',{})
if r.get('kind')!='quality_weight_ranking' or r.get('dimension') not in DIMENSIONS:return None
if r.get('stage') not in dimension_stages(task, r['dimension'], combined=False) or r.get('metric') not in task['fields']:return None
check={**task,'dimensions':[r['dimension']],'stages':[r['stage']],'fields':[r['metric']],
'dimensionStages':{r['dimension']:[r['stage']]}}
if ranking_gaps([document],check,{'releaseId':r.get('releaseId')}):return None
scope,_=_scope(r.get('filters'));period,_,_=_period(r.get('period'))
if scope is None or period is None:return None
rows=r['rows'][:10];weights=[row.get('weight') for row in rows];total=r['totalWeight']
if any(not isinstance(v,(int,float)) or isinstance(v,bool) or not math.isfinite(v) or v<0 for v in weights):return None
if sum(weights)>total+max(.00001,total*1e-10) or any(weights[i]>weights[i-1] for i in range(1,len(weights))):return None
metric=r['stage']+('_total_weight' if r['metric']=='totalWeight' else '_scrap_weight')
label=('黑片' if r['stage']=='black' else '亮片')+FIELDS[r['metric']]
source=source_period(r.get('coverage'),r['period'],r['stage'])
count=r['totalRows'];shown_count=len(rows);chart_type=task.get('visualType') or 'bar'
negative_groups=(r.get('rankingCoverage') or {}).get('negativeGroups',0)
negative_weight=(r.get('rankingCoverage') or {}).get('negativeWeight',0)
note='占比与累计占比=所列重量及累计重量÷同范围全部重量;Top末项可以低于100%。未发布月份不补零,不冒充完整全年。'
if r.get('stage')=='black' and r.get('metric')=='totalWeight' and negative_groups:
from nao_evidence_report import shown as format_shown
note+=f'黑片含{negative_groups}项负向投入重量修正,净额{format_shown(negative_weight)} kg仍计入正式净总重分母;图中仅展示正重量Top。'
return _chart(turn_id=turn_id,chart_type=chart_type,
title=DIMENSIONS[r['dimension']]+'级'+label+('柏拉图' if chart_type=='pareto' else '排名'),
subtitle=source['label']+';展示前'+str(shown_count)+'项,占比以同范围全部重量为分母。',
unit='kg',categories=[{'key':'item-'+str(i+1),'label':row['label']} for i,row in enumerate(rows)],
series=[{'key':metric,'label':label,'values':weights}],evidence_refs=[document['evidenceRef']],
required_fields=[metric],scope=_chart_scope(scope,r['releaseId'],r['period'],view=r['dimension'],stage=r['stage']),
period=period,stage=r['stage'],metric=metric,
coverage={'totalRows':count,'returnedRows':shown_count,'truncated':shown_count<count,
'shareBasis':'all_scope_weight','denominator':total},
section_key=r['dimension'],dimension=r['dimension'],note=note)
def missing_ranking_visuals(task,visuals,evidence=None):
if task.get('visualPreference') == 'none':return []
from nao_agent_task import dimension_stages
missing=[]
for dimension in task['dimensions']:
for stage in dimension_stages(task, dimension, combined=False):
for field in task['fields']:
metric=stage+('_total_weight' if field=='totalWeight' else '_scrap_weight')
if not any(v.get('dimension')==dimension and v.get('stage')==stage
and v.get('metric')==metric and v.get('type')==(task.get('visualType') or 'bar') for v in visuals):
label=DIMENSIONS[dimension]+'级'+('黑片' if stage=='black' else '亮片')+FIELDS[field]+'图'
if stage=='black' and field=='totalWeight':
limited=any(_negative_correction_chart_limit(d.get('result',{}))
and d.get('result',{}).get('dimension')==dimension
for d in (evidence or []) if isinstance(d,dict))
if limited:
label+='(负向修正使正重量Top合计超过黑片净总重,当前图表无法表达。)'
missing.append(label)
return missing
def ranking_report(evidence,task,context):
from nao_evidence_report import shown,cell,_scope_label
from nao_agent_task import dimension_stages
facts=[];sections=[];seen=set()
for document in matching_rankings(evidence,task,context):
r=document['result'];key=(r['dimension'],r['stage'],r['metric'])
if key in seen or r['dimension'] not in task['dimensions'] or r['stage'] not in dimension_stages(task, r['dimension'], combined=False) or r['metric'] not in task['fields']:continue
seen.add(key);ref=document['evidenceRef'];name=('黑片' if r['stage']=='black' else '亮片')+FIELDS[r['metric']]
p=source_period(r.get('coverage'),r['period'],r['stage']);scope=_scope_label(r['filters']);top=r['rows']
title=DIMENSIONS[r['dimension']]+'级'+name+' Top '+str(len(top))
table=['| 排名 | '+DIMENSIONS[r['dimension']]+' | '+name+'(kg) | 占全部重量 | 累计占全部重量 |','| --- | --- | --- | --- | --- |']
for row in top:
table.append('| '+' | '.join(cell(str(v)) for v in (row['rank'],row['label'],shown(row['weight']),shown(row['share'],percent=True),shown(row['cumulativeShare'],percent=True)))+' |')
negative_groups=(r.get('rankingCoverage') or {}).get('negativeGroups',0)
negative_weight=(r.get('rankingCoverage') or {}).get('negativeWeight',0)
correction_note=''
if r['stage']=='black' and r['metric']=='totalWeight' and negative_groups:
correction_note=(f'黑片存在{negative_groups}项负向投入重量修正,净额{shown(negative_weight)} kg仍计入正式净总重分母;'
'排名表只展示正重量Top。')
facts.append({'id':'F'+str(len(facts)+1),'kind':'overall','label':title,
'text':p['label']+';'+scope+';'+DIMENSIONS[r['dimension']]+'级'+name+'全量分母为'+shown(r['totalWeight'])+' kg,展示前'+str(len(top))+'项,累计占全部重量'+shown(top[-1]['cumulativeShare'],percent=True)+'。'+correction_note,'evidenceRef':ref})
for row in top[:3]:
facts.append({'id':'F'+str(len(facts)+1),'kind':r['dimension'],'label':row['label'],
'text':DIMENSIONS[r['dimension']]+':'+row['label']+';'+name+shown(row['weight'])+' kg,占全部重量'+shown(row['share'],percent=True)+'。','evidenceRef':ref,
'dimension':r['dimension'],'stage':r['stage']})
sections.append('### '+title+'\n\n'+p['label']+';'+scope+'。分母:全部'+name+shown(r['totalWeight'])+' kg。\n\n'+'\n'.join(table)
+('\n\n'+correction_note if correction_note else '')+'\n\n['+ref+']')
if not facts:raise ValueError('未取得与本轮阶段、期间和分组一致的重量排名')
missing=ranking_gaps(evidence,task,context)
return {'headline':'按已发布数据展示分组重量排名;Top之外的重量保留在占比分母中。',
'sections':sections,'facts':facts,'policy':'占比与累计占比均按同范围所有分组的正式重量计算;Top未覆盖全量时累计占比可低于100%。未发布月份不补零,图表不代表完整全年。',
'focusEnding':'按已发布月份展示。各项占比和累计占比均以同范围全部产品/组织的所选阶段重量为分母,Top之外的产品仍计入分母;不把未发布月份补零,末项累计占比不强制为100%。',
'missingEvidence':missing,'coverageSufficient':not missing,
'rawMetrics':[d['result'] for d in matching_rankings(evidence,task,context)]}