131 lines
8.3 KiB
TypeScript
131 lines
8.3 KiB
TypeScript
import { parseAnalysisVisuals, analysisExclusionSummary, columnFilterSummary, isValidAnalysisExclusions } from './analysisVisualsModel.ts';
|
||
import { analysisPeriodLabel, hasAnalysisPeriodFields } from './analysisPeriodModel.ts';
|
||
|
||
type Data = Record<string, unknown>;
|
||
const record = (value: unknown): Data => value && typeof value === 'object' && !Array.isArray(value) ? value as Data : {};
|
||
const meaningful = (value: unknown) => value !== undefined && value !== null && value !== '';
|
||
const SCOPE_KEYS = ['department', 'group', 'product', 'productSearch', 'projectGroup', 'stage', 'includeUnassigned', 'extraFilters', 'columnFilters', 'exclusions'];
|
||
const BINDING_KEYS = ['year', 'month', 'quarter', 'monthStart', 'monthEnd', 'period', ...SCOPE_KEYS];
|
||
const canonical = (value: unknown): string => Array.isArray(value) ? JSON.stringify(value)
|
||
: value && typeof value === 'object' ? JSON.stringify(Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)]))) : JSON.stringify(value);
|
||
|
||
export function analysisPeriodText(value: unknown): string {
|
||
const period = record(value);
|
||
if (hasAnalysisPeriodFields(period)) return analysisPeriodLabel(period, 2000, 2200);
|
||
if (typeof period.label === 'string' && period.label.trim()) return period.label.trim();
|
||
if (typeof period.start === 'string' && typeof period.end === 'string') return `${period.start}—${period.end}`;
|
||
return '';
|
||
}
|
||
|
||
function scopeValue(value: unknown): string {
|
||
if (Array.isArray(value)) return value.filter(item => typeof item === 'string' || typeof item === 'number').join('、');
|
||
if (typeof value !== 'string' && typeof value !== 'number') return '';
|
||
const text = String(value);
|
||
if (text.startsWith('[')) {
|
||
try { const values: unknown = JSON.parse(text); if (Array.isArray(values)) return scopeValue(values); } catch { /* retain the bound label */ }
|
||
}
|
||
return text;
|
||
}
|
||
|
||
/** A native turn may only save its release in the plan. Use an unambiguous
|
||
* broadest chart binding, never a local product investigation or a mixture. */
|
||
function visualBinding(turn: Data, result: Data): Data | undefined {
|
||
const turnId = String(turn.id || turn.turnId || result.turnId || '');
|
||
const visuals = parseAnalysisVisuals(turn.visuals || result.visuals).visuals
|
||
.filter(visual => !turnId || !visual.originTurnId || visual.originTurnId === turnId);
|
||
if (!visuals.length) return undefined;
|
||
const depth = (scope: Data) => ['department', 'group', 'product', 'productSearch', 'projectGroup', 'stage', 'category', 'defect', 'extraFilters', 'exclusions'].filter(key => meaningful(scope[key])).length;
|
||
const bindings = visuals.map(visual => ({ ...visual.scope, ...(visual.stage ? { stage: visual.stage } : {}), period: visual.period,
|
||
...(visual.comparisonPeriod ? { comparisonPeriod: visual.comparisonPeriod } : {}) }));
|
||
const shallowest = Math.min(...bindings.map(depth));
|
||
const roots = bindings.filter(binding => depth(binding) === shallowest);
|
||
const signature = (binding: Data) => canonical(binding);
|
||
if (new Set(roots.map(signature)).size === 1) return roots[0];
|
||
const stages = new Set(roots.map(binding => binding.stage));
|
||
const withoutStage = (binding: Data) => Object.fromEntries(Object.entries(binding).filter(([key]) => key !== 'stage'));
|
||
if (stages.size === 2 && stages.has('black') && stages.has('bright')
|
||
&& new Set(roots.map(binding => signature(withoutStage(binding)))).size === 1) {
|
||
return { ...withoutStage(roots[0]), stage: 'all' };
|
||
}
|
||
return undefined;
|
||
}
|
||
|
||
/** Display server-bound fields only. Never infer filters from question prose,
|
||
* or reuse the mutable current session context for an older turn. */
|
||
export function analysisScopeText(turn: Data): string {
|
||
const result = record(turn.result), plan = record(turn.plan || result.plan);
|
||
const durable = Object.keys(result).length ? result : turn;
|
||
const historyReport = durable.completionMethod === 'confirmed_history_report';
|
||
let historyContext: Data | undefined;
|
||
if (historyReport) {
|
||
const sources = new Set((Array.isArray(durable.historySources) ? durable.historySources : [])
|
||
.map(record).filter(source => source.available === true).map(source => source.turnId));
|
||
const frames = (Array.isArray(durable.historySections) ? durable.historySections : []).map(record)
|
||
.filter(section => sources.has(section.sourceTurnId) && analysisPeriodText(section.period))
|
||
.map(section => ({ ...record(section.filters), period: section.period,
|
||
...(section.comparisonPeriod ? { comparisonPeriod: section.comparisonPeriod } : {}),
|
||
...(section.stage ? { stage: section.stage } : {}), view: 'overall' }));
|
||
// A multi-scope report describes each source beside its own table. The
|
||
// chat's current query context must not label the whole report as one month
|
||
// or one organization.
|
||
if (!frames.length || new Set(frames.map(canonical)).size !== 1) return '';
|
||
historyContext = frames[0];
|
||
}
|
||
const contexts = historyReport ? [historyContext!] : [record(plan.context), record(plan.frozenContext), record(result.context), record(turn.context)];
|
||
const context = contexts.find(value => BINDING_KEYS.some(key => meaningful(value[key])));
|
||
const visual = historyReport ? undefined : visualBinding(turn, result);
|
||
const visualContext = visual ? { ...visual, ...record(visual.period) } : undefined;
|
||
const compatible = context && visualContext && BINDING_KEYS.filter(key => meaningful(context[key]))
|
||
.every(key => key === 'stage' && ['all', 'combined'].includes(String(context.stage)) && !meaningful(visualContext.stage)
|
||
|| canonical(context[key]) === canonical(visualContext[key]));
|
||
const binding = compatible ? { ...context, ...visual } : context || visual;
|
||
if (!binding) return '';
|
||
if (meaningful(binding.exclusions) && !isValidAnalysisExclusions(binding.exclusions)) return '';
|
||
const semantic = historyReport ? {} : record(plan.semantic);
|
||
const period = analysisPeriodText(binding.period || binding);
|
||
// Legacy semantic plans store a comparison query in priorContext only when
|
||
// compare is explicitly true; an unmarked previous context is not evidence.
|
||
const comparison = analysisPeriodText(binding.comparisonPeriod || (context && semantic.compare === true ? semantic.priorContext : undefined));
|
||
const parts = [period, comparison ? `对比 ${comparison}` : ''];
|
||
const labels: Record<string, string> = { department: '产业部', group: '业务分组', product: '产品', productSearch: '产品检索', projectGroup: '项目组' };
|
||
for (const [key, label] of Object.entries(labels)) {
|
||
const value = scopeValue(binding[key]);
|
||
if (value) parts.push(`${label}:${value}`);
|
||
}
|
||
if (!Object.keys(labels).some(key => meaningful(binding[key])) && (visual === binding || compatible || binding.view === 'overall')) parts.push('当前授权范围');
|
||
const stage = binding.stage;
|
||
if (stage === 'black') parts.push('黑片');
|
||
if (stage === 'bright') parts.push('亮片');
|
||
if (stage === 'all' || stage === 'combined') parts.push('黑片与亮片');
|
||
if (binding.includeUnassigned === true) parts.push('含未分类');
|
||
if (binding.includeUnassigned === false) parts.push('不含未分类');
|
||
const filters = record(binding.extraFilters);
|
||
for (const [key, value] of Object.entries(filters)) {
|
||
const text = scopeValue(value);
|
||
if (text) parts.push(`${key}:${text}`);
|
||
}
|
||
parts.push(...analysisExclusionSummary(binding.exclusions));
|
||
parts.push(...columnFilterSummary(binding.columnFilters, binding.columnLabels || record(plan.task).sourceFieldLabels));
|
||
return parts.filter(Boolean).join(' · ');
|
||
}
|
||
|
||
export function restoredAnalysisDraft(draft: string, queued: string): string {
|
||
if (!queued.trim() || queued.trim() === draft.trim()) return draft || queued;
|
||
return draft.trim() ? `${queued}\n\n${draft}` : queued;
|
||
}
|
||
|
||
export function analysisComposerState(busy: boolean, stopping: boolean, historyLoading: boolean, draft: string, queued: string) {
|
||
return {
|
||
showStop: busy,
|
||
stopDisabled: stopping || historyLoading,
|
||
sendDisabled: historyLoading || stopping || !draft.trim() || (busy && Boolean(queued)),
|
||
sendLabel: busy ? '排队发送' : '发送',
|
||
};
|
||
}
|
||
|
||
/** Re-arm following only after the submitted turn is committed to the DOM.
|
||
* An observer still looking at the preceding completed turn must not consume it. */
|
||
export function analysisFollowRequestReady(request: string | null, turn: Data | null): boolean {
|
||
return Boolean(request && turn?._uiFollowKey === request);
|
||
}
|