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

验证:生产构建通过,320项前端回归通过;本轮仅同步Git,不再次部署。
2026-10-30 22:40:58 +08:00

250 lines
16 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Read and present a server-ranked, bounded formal comparison.
The backend aggregates both periods and sorts the complete authorized population;
only the selected rows cross the model boundary. No per-entity reads or KPI math.
"""
from __future__ import annotations
import copy
import base64
import json
import re
from decimal import Decimal
def diagnostic_intent(question):
return bool(re.search(r'原因|成因|为什么|为何|归因|\bwhy\b|\bcause\b', question or '',re.I))
def performance_intent(question):
return bool(re.search(r'表现|关注|重点|最差|\bworst\b|\bperformance\b',question or '',re.I)
and not re.search(r'合格率.{0,5}(?:最低|排名)|按.{0,8}合格率',question or ''))
def selection_contains(parent, member):
"""The backend SelectionValues contract; exact text, never fuzzy matching."""
if not isinstance(parent,str) or not isinstance(member,str) or not member:
return False
if not parent.startswith('~qv1~'):
return parent == member
encoded = parent[5:]
if not encoded or len(parent) > 16384:
return False
try:
values=json.loads(base64.b64decode(encoded+'='*((-len(encoded))%4), altchars=b'-_',validate=True))
return (isinstance(values,list) and 1 <= len(values) <= 50
and all(isinstance(value,str) and value for value in values) and member in values)
except (ValueError,TypeError,UnicodeError):
return False
def validate_changes(result, task, release_id):
from nao_evidence_report import _filters
from nao_period import normalize_period
query = task.get('changeQuery') or {}
if (not isinstance(result, dict) or result.get('kind') != 'quality_changes'
or result.get('releaseId') != release_id
or normalize_period(result.get('currentPeriod')) != normalize_period(task.get('period'))
or normalize_period(result.get('comparisonPeriod')) != normalize_period(task.get('comparisonPeriod'))
or _filters(result.get('filters')) != _filters(task.get('filters'))
or result.get('dimension') != query.get('dimension')
or result.get('sort') != query.get('sort')
or result.get('stage') != ((task.get('stages') or [None])[0])
or result.get('completeRanking') is not True):
raise ValueError('批量对比结果没有确认完整排名、期间和服务器授权范围')
rows = result.get('rows')
total = result.get('totalRows')
if (not isinstance(rows, list) or type(total) is not int or total < len(rows)
or len(rows) > query.get('limit', 0)
or len(rows) != min(total, query.get('limit', 0))
or len({row.get('key') for row in rows if isinstance(row, dict)}) != len(rows)):
raise ValueError('批量对比Top行数或唯一对象与完整排序回执不一致')
for index, row in enumerate(rows, 1):
if (not isinstance(row, dict) or row.get('rank') != index
or not isinstance(row.get('key'), str) or not row['key']
or not isinstance(row.get('current'), dict)
or not isinstance(row.get('comparison'), dict)):
raise ValueError('批量对比的对象和两期正式值结构无效')
for side_name in ('current','comparison'):
if (row.get('present') or {}).get(side_name) is False:
continue
side = row[side_name]
weighted_fields = set(task.get('fields') or []) & {'totalWeight','scrapWeight'}
sourced_stages = 0
for stage in task.get('stages') or ('black','bright'):
# rateSupport concerns rate measurability (positive input),
# not whether requested weight fields exist. A zero-input
# baseline can have valid zero weights and an unavailable rate.
block=side.get(stage) or {}
if (not task.get('stages') and (side.get('rateSupport') or {}).get(stage+'Measured') is not True
and not any(isinstance(block.get(field),(int,float,Decimal)) for field in
('rate','qualifiedWeight','totalWeight','scrapWeight'))):
continue
sourced_stages += 1
for field in weighted_fields:
value = block.get(field)
if (not isinstance(value,(int,float,Decimal)) or isinstance(value,bool)
or not Decimal(str(value)).is_finite() or value < 0):
raise ValueError('批量对比缺少用户要求的正式'+stage+'.'+field+',不能认定完整')
if weighted_fields and not sourced_stages:
raise ValueError('批量对比缺少用户要求的正式重量及来源阶段,不能认定完整')
return result
def read_changes(api, arguments, task, tools):
body = {key: copy.deepcopy(arguments[key]) for key in
('releaseId', 'period', 'comparisonPeriod', 'filters', 'dimension', 'sort', 'limit')}
body['fields'] = copy.deepcopy(task.get('fields') or [])
body['stage'] = arguments.get('stage')
if 'columnFilters' in arguments:
body['filters']['columnFilters'] = copy.deepcopy(arguments['columnFilters'])
result = api.call('/api/analysis/changes', payload=body, method='POST')
validate_changes(result, task, arguments['releaseId'])
tools._calls.append({'method':'POST', 'path':'/api/analysis/changes', 'payload':body})
evidence_id, evidence_path = tools._write_evidence(result, 'changes')
return {**result, 'evidenceId':evidence_id, 'evidencePath':evidence_path,
'evidenceRef':tools._evidence_ref(evidence_id)}
def changes_report(documents, task, release_id):
from nao_evidence_report import shown, period, cell
facts, sections, gaps, required = [], [], [], []
sort = (task.get('changeQuery') or {}).get('sort')
dimension = (task.get('changeQuery') or {}).get('dimension')
diagnostic = diagnostic_intent(task.get('question'))
performance = dimension=='product' and sort=='current_rate' and performance_intent(task.get('question'))
noun = {'group':'业务分组','department':'产业部','product':'产品规格'}.get(dimension, '对象')
kind = {'group':'group','department':'group','product':'product'}.get(dimension, 'group')
for document in documents:
q, ref = document['result'], document['evidenceRef']
try:
validate_changes(q, task, release_id)
except (ValueError, TypeError):
gaps.append('批量正式对比未取得同范围、同期间且完整排序的证据。')
continue
a, b = period(q['comparisonPeriod']), period(q['currentPeriod'])
stage = q.get('stage')
rate_label = {'black':'黑片','bright':'亮片'}.get(stage, '综合')+'合格率'
order_label = {'rate_drop':'合格率降幅','current_rate':'本期合格率由低到高',
'scrap_delta':'报废增量','current_scrap':'本期报废重量'}.get(sort, sort)
body = []
for row in q['rows']:
now, old = row['current'], row['comparison']
rank_label = ('本期率最低候选' if performance else
{'scrap_delta':'报废增量候选','current_scrap':'本期报废重量候选'}.get(sort,noun))
text = f"{rank_label}第{row['rank']}项:{row.get('label') or row['key']};{rate_label}({a}→{b}):{shown(old.get('rate'),percent=True)}→{shown(now.get('rate'),percent=True)}"
drop = row.get('rateDrop')
if isinstance(drop, (float, int, Decimal)) and not isinstance(drop, bool):
points = Decimal(str(drop))*100
text += (',下降' if points > 0 else ',上升' if points < 0 else ',持平')
if points: text += shown(abs(points))+'个百分点'
else:
text += ';两期合格率不可比'
for side_name, side_label in (('current', '本期'), ('comparison', '基期')):
if (row.get('present') or {}).get(side_name) is False:
continue
support = (row.get(side_name) or {}).get('rateSupport') or {}
missing = [name for name in support.get('missingStages') or []
if name in ('black', 'bright') and (not stage or name == stage)]
if missing:
text += ';' + side_label + '、'.join({'black': '黑片', 'bright': '亮片'}[name] for name in missing) + '阶段率未实测,缺失阶段不视为实测满值'
core = {'id':'F'+str(len(facts)+1), 'kind':kind, 'label':str(row.get('label') or row['key']),
'text':text+'。', 'evidenceRef':ref, 'rank':row['rank'],
'rateDrop':row.get('rateDrop'), 'scrapDelta':row.get('scrapDelta')}
facts.append(core)
# The requested ordering is authoritative. Scale signals may explain
# materiality, but cannot replace the actual lowest-rate products.
if sort == 'current_rate' or not diagnostic or row['rank']==1:
required.append(core['id'])
scale = str(row.get('label') or row['key'])
input_cells = []
scrap_cells = []
for st, label in ((stage, {'black':'黑片','bright':'亮片'}.get(stage, '')),) if stage else (('black','黑片'),('bright','亮片')):
def input_weight(side):
block = side.get(st)
return block.get('totalWeight') if isinstance(block,dict) else side.get(st+'InputWeight')
scale += f";{label}投入 {shown(input_weight(old))}→{shown(input_weight(now))} kg"
input_cells.append(label+' '+shown(input_weight(old))+'→'+shown(input_weight(now)))
def scrap_weight(side):
block = side.get(st)
return block.get('scrapWeight') if isinstance(block, dict) else None
if 'scrapWeight' in (task.get('fields') or []) and any(scrap_weight(side) is not None for side in (old, now)):
scale += f";{label}报废重量 {shown(scrap_weight(old))}→{shown(scrap_weight(now))} kg"
scrap_cells.append(label+' '+shown(scrap_weight(old))+'→'+shown(scrap_weight(now)))
scale += f";报废重量 {shown(old.get('scrapWeight'))}→{shown(now.get('scrapWeight'))} kg"
if row.get('scrapDelta') is not None:
scale += ',增量'+shown(row['scrapDelta'])+' kg'
if row.get('changeType') in ('new', 'exit'):
scale += ';'+('本期新增' if row['changeType']=='new' else '本期退出')+',不能据缺失期间判断率下降'
if dimension == 'product':
scale += ';应结合两期投入与报废增量判断,小批量率变化仅作线索'
if dimension == 'product' or set(task.get('fields') or []) - {'rate'}:
facts.append({'id':'F'+str(len(facts)+1), 'kind':'supporting',
'label':str(row.get('label') or row['key'])+'规模依据',
'text':scale+'。', 'evidenceRef':ref})
if set(task.get('fields') or []) - {'rate'} and (sort == 'current_rate' or not diagnostic or row['rank']==1):
required.append(facts[-1]['id'])
cells=[str(row['rank']),str(row.get('label') or row['key'])]
if 'rate' in task.get('fields',[]):
cells += [shown(old.get('rate'),percent=True),shown(now.get('rate'),percent=True)]
if 'scrapWeight' in task.get('fields',[]):
cells += [shown(old.get('scrapWeight')),shown(now.get('scrapWeight'))]
if scrap_cells:
cells[-2:] = [';'.join(cell.split('→')[0] for cell in scrap_cells),
';'.join(cell.split(' ')[0]+' '+cell.split('→')[1] for cell in scrap_cells)]
if 'totalWeight' in task.get('fields',[]):
cells.append(';'.join(input_cells))
body.append(cells)
if not q['rows']:
facts.append({'id':'F'+str(len(facts)+1),'kind':kind,'label':'无匹配对象',
'text':f'{a}与{b}的已授权{noun}范围内没有匹配对象。','evidenceRef':ref})
required.append(facts[-1]['id'])
headers=['序号','对象']
if 'rate' in task.get('fields',[]):headers += ['基期合格率','本期合格率']
if 'scrapWeight' in task.get('fields',[]):headers += ['基期报废 kg','本期报废 kg']
if 'totalWeight' in task.get('fields',[]):headers += ['两期投入 kg']
sections.append(f"### {noun}两期对比\n\n按{order_label}对全部 {q['totalRows']} 项排序,展示前 {len(q['rows'])} 项;基期{a},本期{b}。\n\n"
+'| '+' | '.join(headers)+' |\n| '+' | '.join('---' for _ in headers)+' |\n'
+'\n'.join('| '+' | '.join(cell(v) for v in row)+' |' for row in body)+f'\n\n[{ref}]')
if performance:
signals=q.get('prioritySignals') or {}
candidates=[('本期报废重量靠前',row) for row in (signals.get('currentScrap') or [])[:2]]
candidates += [('报废增量靠前',row) for row in (signals.get('scrapIncrease') or [])[:1]]
seen=set();priority_lines=[]
for signal,row in candidates:
if row.get('key') in seen:continue
seen.add(row.get('key'));now,old=row.get('current') or {},row.get('comparison') or {}
text=(signal+':'+str(row.get('label') or row.get('key'))+';'+rate_label+'('+a+'→'+b+')'
+shown(old.get('rate'),percent=True)+'→'+shown(now.get('rate'),percent=True)
+';报废重量'+shown(old.get('scrapWeight'))+'→'+shown(now.get('scrapWeight'))+' kg'
+',增量'+shown(row.get('scrapDelta'))+' kg')
for st,label in (('black','黑片'),('bright','亮片')):
text+=';'+label+'投入'+shown(old.get(st+'InputWeight'))+'→'+shown(now.get(st+'InputWeight'))+' kg'
text+='。'
fact={'id':'F'+str(len(facts)+1),'kind':'supporting','label':str(row.get('label') or row.get('key')),
'text':text,'evidenceRef':ref}
facts.append(fact);priority_lines.append(text+f'[{ref}]')
if priority_lines:
sections.append('### 产品规模与变化依据\n\n'+'\n\n'.join(priority_lines))
elif q['rows']:
required.extend(fact['id'] for fact in facts if fact.get('rank') is not None)
for key,label in (('currentScrap','本期报废重量'),('scrapIncrease','报废增量'),('rateDrop','合格率降幅')):
signal_rows=signals.get(key) or []
if not signal_rows:continue
table=['| 序号 | 产品 | 两期综合率 | 两期黑片投入 kg | 两期亮片投入 kg | 两期报废 kg | 报废增量 kg |',
'| --- | --- | --- | --- | --- | --- | --- |']
for index,row in enumerate(signal_rows,1):
old,now=row.get('comparison') or {},row.get('current') or {}
cells=[str(index),str(row.get('label') or row.get('key')),
shown(old.get('rate'),percent=True)+'→'+shown(now.get('rate'),percent=True),
shown(old.get('blackInputWeight'))+'→'+shown(now.get('blackInputWeight')),
shown(old.get('brightInputWeight'))+'→'+shown(now.get('brightInputWeight')),
shown(old.get('scrapWeight'))+'→'+shown(now.get('scrapWeight')),shown(row.get('scrapDelta'))]
table.append('| '+' | '.join(cell(value) for value in cells)+' |')
sections.append('### '+label+'线索完整候选\n\n'+'\n'.join(table)+f'\n\n[{ref}]')
return {'headline':f'{noun}正式批量对比。','sections':sections,'facts':facts,
'requiredFactIds':required,
'missingEvidence':gaps,'coverageSufficient':bool(facts) and not gaps,
'policy':'各对象的降幅与报废增量是定位线索,不能直接视为对总体下降的贡献或生产根因。',
'rawMetrics':[]}