Files
syops/frontend/src/features/chat/components/messages/ContractReviewResultCard.vue
T
runny 1034435355 fix(auth): 企微提醒卡片深链登录后回跳原目标
- 新增 shared/utils/redirect.ts 安全回跳校验(防开放重定向)
- 路由守卫未登录跳转携带 redirect 完整深链,已登录访问登录页优先回跳
- 登录成功统一按 redirect 深链落地,支持企微卡片点击直达精益培训模块
2026-09-11 04:09:56 +08:00

754 lines
34 KiB
Vue
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.
/**
* features/chat/components/messages/ContractReviewResultCard.vue
* 用途:在聊天会话中渲染采购合同审查结果卡(改动项、独立风险项 + 下载报告)。
* 依赖:vue-i18n、procurement-contract.api、chat.types。
* 逻辑:queued/running 展示审核步骤;成功后按来源拆分合同改动与独立风险;比对模式不展示 OCR 待确认主列表。
*/
<script setup lang="ts">
import { computed, onUnmounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Check, Loader2 } from 'lucide-vue-next';
import {
downloadChatAnnotatedContract,
downloadChatContractReviewReport,
getChatContractReview,
type ContractClauseItem,
type ContractReviewRow,
} from '@/features/admin/api/procurement-contract.api';
import { useMessage } from '@/shared/composables/useMessage';
import type { ChatMessage } from '../../types/chat.types';
const props = defineProps<{ message: ChatMessage }>();
const { t } = useI18n();
const msg = useMessage();
const downloading = ref(false);
const downloadingAnnotated = ref(false);
const latestReview = ref<ContractReviewRow | null>(null);
// 浏览器端 window.setTimeout 返回 number;勿用 ReturnType<typeof window.setTimeout>,
// 其在 @types/node 与 DOM lib 混用时会解析为 NodeJS.Timeout 导致 TS2322。
let refreshTimer: number | undefined;
let refreshing = false;
let disposed = false;
const review = computed<ContractReviewRow | null>(() => {
if (latestReview.value) return latestReview.value;
const raw = props.message.payload;
return raw && typeof raw === 'object' ? raw as ContractReviewRow : null;
});
const clauses = computed<ContractClauseItem[]>(() =>
Array.isArray(review.value?.clauses_json) ? review.value.clauses_json : [],
);
const isCompareMode = computed(() => review.value?.review_mode === 'compare');
const confirmedChangeTypes = new Set(['insert', 'delete', 'modify']);
const independentRiskTypes = new Set(['missing', 'rule_scan', 'policy_scan', 'llm_scan']);
const changeClauses = computed(() => clauses.value.filter((clause) =>
confirmedChangeTypes.has(clause.change_type || ''),
));
const independentRiskClauses = computed(() => clauses.value.filter((clause) =>
independentRiskTypes.has(clause.change_type || '')
&& clause.risk_level !== 'ok'
&& clause.validation_status !== 'needs_review',
));
/** 比对模式不展示待确认主列表;单份模式仅保留策略 OCR 待确认。 */
const confirmationClauses = computed(() => {
if (isCompareMode.value) return [];
return clauses.value.filter((clause) =>
clause.change_type === 'ocr_uncertain' || clause.validation_status === 'needs_review',
);
});
const clauseSections = computed(() => {
const sections = [
{ key: 'changes', title: t('chat.procurementContract.sectionChanges'), clauses: changeClauses.value },
{ key: 'risks', title: t('chat.procurementContract.sectionIndependentRisks'), clauses: independentRiskClauses.value },
];
if (!isCompareMode.value) {
sections.push({
key: 'confirmations',
title: t('chat.procurementContract.sectionConfirmations'),
clauses: confirmationClauses.value,
});
}
return sections.filter((section) => section.clauses.length > 0);
});
const changeCount = computed(() => review.value?.total_change_count ?? changeClauses.value.length);
const comparisonQuality = computed<Record<string, unknown>>(() => {
const raw = review.value?.summary_json?.comparison_quality;
return raw && typeof raw === 'object' ? raw as Record<string, unknown> : {};
});
const comparisonScope = computed<Record<string, unknown>>(() => {
const raw = review.value?.summary_json?.comparison_scope;
return raw && typeof raw === 'object' ? raw as Record<string, unknown> : {};
});
const attachmentComparison = computed<Record<string, unknown>>(() => {
const raw = review.value?.summary_json?.attachment_comparison;
return raw && typeof raw === 'object' ? raw as Record<string, unknown> : {};
});
const attachmentNotice = computed(() => {
const status = String(attachmentComparison.value.status || '');
const added = Number(attachmentComparison.value.added_pages || 0);
const removed = Number(attachmentComparison.value.removed_pages || 0);
if (status === 'added' && added > 0) return t('chat.procurementContract.attachmentAdded', { count: added });
if (status === 'removed' && removed > 0) return t('chat.procurementContract.attachmentRemoved', { count: removed });
return '';
});
const confirmationTotal = computed(() => {
if (isCompareMode.value) return 0;
const raw = comparisonQuality.value.needs_confirmation;
return typeof raw === 'number' ? raw : confirmationClauses.value.length;
});
const confirmationHiddenCount = computed(() => Math.max(0, confirmationTotal.value - confirmationClauses.value.length));
const isProcessing = computed(() => ['queued', 'running'].includes(review.value?.status || ''));
interface ReviewProgressStep {
stage: string;
label: string;
milestone: number;
state: 'completed' | 'active' | 'pending';
}
const REVIEW_PROGRESS_STAGE_ORDER = [
'queued',
'extracting',
'structuring',
'deterministic_review',
'llm_reviewing',
'validating',
'success',
];
/**
* 构建完整审核步骤轨道,并根据后端 processing_stage 标记已完成、当前和未开始阶段。
* 核心逻辑:阶段顺序由前后端稳定协议确定;比对与单份审核仅替换确定性审核步骤文案。
* @returns 含阶段文案、里程碑进度和展示状态的七步轨道
*/
const reviewProgressSteps = computed<ReviewProgressStep[]>(() => {
const currentStage = review.value?.processing_stage || 'queued';
const currentIndex = Math.max(0, REVIEW_PROGRESS_STAGE_ORDER.indexOf(currentStage));
const labels = [
t('chat.procurementContract.stepQueued'),
t('chat.procurementContract.stepExtracting'),
t('chat.procurementContract.stepStructuring'),
t(review.value?.review_mode === 'solo'
? 'chat.procurementContract.stepRiskScanning'
: 'chat.procurementContract.stepComparing'),
t('chat.procurementContract.stepAiReviewing'),
t('chat.procurementContract.stepValidating'),
t('chat.procurementContract.stepCompleted'),
];
const milestones = [0, 10, 30, 45, 60, 88, 100];
return REVIEW_PROGRESS_STAGE_ORDER.map((stage, index) => ({
stage,
label: labels[index] || stage,
milestone: milestones[index] ?? 0,
state: index < currentIndex ? 'completed' : index === currentIndex ? 'active' : 'pending',
}));
});
const cardStatusTitle = computed(() => {
if (isProcessing.value) return t('chat.procurementContract.reviewRunning');
if (review.value?.status === 'failed') return t('chat.procurementContract.reviewFailed');
return t('chat.procurementContract.completed');
});
const reportDownloadLabel = computed(() => t(
isCompareMode.value
? 'chat.procurementContract.downloadDifferenceReport'
: 'chat.procurementContract.downloadReport',
));
/**
* Refresh a persisted in-progress card after the user reloads or reopens a chat.
* The initial send flow also polls, but this local polling prevents an old card from freezing
* when the page was closed before its worker job reached a terminal state.
*/
function scheduleReviewRefresh(): void {
if (disposed) return;
if (refreshTimer !== undefined) {
window.clearTimeout(refreshTimer);
refreshTimer = undefined;
}
const reviewNo = review.value?.review_no;
if (!reviewNo || !isProcessing.value) return;
refreshTimer = window.setTimeout(async () => {
if (refreshing) return;
refreshing = true;
try {
latestReview.value = await getChatContractReview(reviewNo);
} catch (error) {
// A temporary network error must not turn a still-running review into a failed result.
console.warn('Failed to refresh procurement contract review', error);
} finally {
refreshing = false;
if (!disposed) scheduleReviewRefresh();
}
}, 2000);
}
watch(
() => [review.value?.review_no, isProcessing.value] as const,
() => scheduleReviewRefresh(),
{ immediate: true },
);
onUnmounted(() => {
disposed = true;
if (refreshTimer !== undefined) window.clearTimeout(refreshTimer);
});
/**
* 页头右侧风险徽标文案:有高风险时强调数量,否则提示无高风险。
* @returns 已本地化徽标文案
*/
const headerRiskBadge = computed(() => {
const high = review.value?.high_risk_count ?? 0;
if (high > 0) {
return t('chat.procurementContract.containsHighRisk', { count: high });
}
return t('chat.procurementContract.noHighRisk');
});
/**
* 比对基准来源徽标;历史库内模板显示模板库,新流程显示本次上传。
* @returns 本地化来源文案,无则 null
*/
const templateSourceLabel = computed(() => {
const source = review.value?.template_source;
if (source === 'library') return t('chat.procurementContract.sourceLibrary');
if (source === 'user_upload') return t('chat.procurementContract.sourceUpload');
return null;
});
/**
* 返回表格风险列的短标签(高 / 中 / 低),对齐原型单字徽标。
* @param level - 风险等级
* @param isComparisonChange - 是否为合同对比中的已识别差异;无风险时避免误称“通过”
*/
function riskShortLabel(level?: string | null, isComparisonChange = false): string {
if (level === 'high') return t('chat.procurementContract.riskShortHigh');
if (level === 'medium') return t('chat.procurementContract.riskShortMedium');
if (level === 'low') return t('chat.procurementContract.riskShortLow');
if (level === 'ok' && isComparisonChange) return t('chat.procurementContract.riskNoFinding');
if (level === 'ok') return t('chat.procurementContract.riskOk');
return level || '-';
}
/**
* 风险徽标样式(高/中/低/通过)。
* @param level - 风险等级
*/
function riskBadgeClass(level?: string | null): string {
if (level === 'high') return 'border-[#fecdca] bg-[#fef3f2] text-[#b42318]';
if (level === 'medium') return 'border-[#fedf89] bg-[#fffaeb] text-[#b54708]';
if (level === 'low') return 'border-[#b2ddff] bg-[#eff8ff] text-[#175cd3]';
if (level === 'ok') return 'border-[#abe6c5] bg-[#ecfdf3] text-[#067647]';
return 'border-[#d8e0ec] bg-white text-[#667792]';
}
/**
* 变更类型本地化文案。
* @param type - 变更类型
*/
function changeTypeLabel(type?: string | null): string {
if (type === 'insert') return t('chat.procurementContract.changeInsert');
if (type === 'delete') return t('chat.procurementContract.changeDelete');
if (type === 'modify') return t('chat.procurementContract.changeModify');
if (type === 'pass') return t('chat.procurementContract.changePass');
if (type === 'missing') return t('chat.procurementContract.changeMissing');
if (type === 'rule_scan') return t('chat.procurementContract.changeRuleScan');
if (type === 'policy_scan') return t('chat.procurementContract.changePolicyScan');
if (type === 'llm_scan') return t('chat.procurementContract.changeLlmScan');
if (type === 'ocr_uncertain') return t('chat.procurementContract.changeOcrUncertain');
return type || '-';
}
/**
* 条款列展示:优先可读标题(规则名 /「变更段 #N」),不用 Diff 序号。
* @param clause - 条款项
*/
function clauseLabel(clause: ContractClauseItem): string {
const title = (clause.title || '').trim();
if (title) return title;
return clause.clause_no || '-';
}
/** 展示审核证据在原 PDF 中的页码;未定位时返回空串。 */
function anchorPageLabel(clause: ContractClauseItem): string {
const pageNo = clause.evidence_anchor?.page_no;
return pageNo ? t('chat.procurementContract.anchorPage', { page: pageNo }) : '';
}
/**
* 清洗 PDF 缺字占位与私用区字符,避免豆腐字进入对照列。
* @param value - 抽取文本
*/
function cleanExtractedText(value?: string | null): string {
return (value || '')
.replace(/[\u25a0-\u25ff\ufffd\ue000-\uf8ff]+/g, ' ')
.replace(/\s+/g, ' ')
.trim();
}
/**
* 判断抽取片段是否足够可读(与后端 _is_readable_extracted_text 同口径)。
* @param value - 待展示对照文本
*/
function isReadableComparisonText(value?: string | null): boolean {
const raw = value || '';
if (!raw.trim() || raw.startsWith('[binary:')) return false;
const compactRaw = raw.replace(/\s+/g, '');
if (!compactRaw) return false;
const tofu = (compactRaw.match(/[\u25a0-\u25ff\ufffd\ue000-\uf8ff]/g) || []).length;
if (tofu / compactRaw.length >= 0.1) return false;
const cleaned = cleanExtractedText(raw).replace(/\s+/g, '');
if (cleaned.length < 4) return false;
const useful = (cleaned.match(/[\u4e00-\u9fffA-Za-z0-9]/g) || []).length;
return useful / cleaned.length >= 0.5;
}
/**
* 截取条款摘要,优先匹配标题相关商务关键词句,控制单元格宽度。
* @param value - 原文
* @param title - 条款标题(用于关键词打分)
*/
function clauseExcerpt(value: string | null | undefined, title?: string): string {
if (!isReadableComparisonText(value)) return '';
const cleaned = cleanExtractedText(value);
if (!cleaned) return '';
const sentences = cleaned.split(/(?<=[。!?;;])\s*|\s+(?=第[一二三四五六七八九十百\d]+[条章节、..])/).filter(Boolean);
const businessKeywords = ['付款', '支付', '验收', '发票', '交付', '质保', '保修', '违约', '赔偿', '管辖', '仲裁', '保密', '知识产权'];
const keywords = businessKeywords.filter((keyword) => (title || '').includes(keyword));
const matched = sentences
.map((sentence) => ({ sentence, score: keywords.filter((keyword) => sentence.includes(keyword)).length }))
.sort((a, b) => b.score - a.score)
.find((item) => item.score > 0)?.sentence;
const excerpt = matched || sentences.find((sentence) => sentence.length >= 8) || cleaned;
return excerpt.length > 180 ? `${excerpt.slice(0, 180)}...` : excerpt;
}
/**
* 组装变更对照:可读时展示模板/合同抽取片段;否则提示编码不兼容。
* 说明:对照列是抽取后的删改摘录,不是 PDF 像素级原文。
* @param clause - 条款项
*/
function clauseComparison(clause: ContractClauseItem): {
before: string;
after: string;
unreadable: boolean;
note: string;
missingBefore: boolean;
missingAfter: boolean;
unavailableReturnedSchedule: boolean;
} {
const before = clauseExcerpt(clause.old_text, clause.title);
const after = clauseExcerpt(clause.new_text, clause.title);
if (before || after) {
return { before, after, unreadable: false, note: '', missingBefore: false, missingAfter: false, unavailableReturnedSchedule: false };
}
const hasBinaryPlaceholder = [clause.old_text, clause.new_text]
.some((value) => (value || '').trim().startsWith('[binary:'));
const unreadable = clause.comparison_readable === false && hasBinaryPlaceholder;
const evidence = cleanExtractedText(clause.evidence || clause.evidence_anchor?.matched_text || '');
const fallback = cleanExtractedText(clause.detail || clause.risk_hint || '');
if (unreadable) {
return { before: '', after: '', unreadable: true, note: fallback, missingBefore: false, missingAfter: false, unavailableReturnedSchedule: false };
}
const isSchedule = /清单|设备|型号|规格|数量|单价|总价|配置/.test(`${clause.title || ''}${fallback}`);
return {
before: '', after: evidence, unreadable: false, note: evidence ? '' : fallback,
// 单边清单的正文未提取时仍明确两侧事实,避免泛化说明被误读为具体对照内容。
missingBefore: !evidence && isSchedule && clause.change_type === 'insert',
missingAfter: !evidence && isSchedule && clause.change_type === 'delete',
unavailableReturnedSchedule: !evidence && isSchedule && clause.change_type === 'insert',
};
}
/** 风险项的建议独立展示,避免误标成“对方合同原文”。 */
function clauseSuggestion(clause: ContractClauseItem): string {
return cleanExtractedText(clause.llm_suggestion || clause.suggestion || clause.negotiation_text || '');
}
type DiffPiece = { text: string; changed: boolean };
/**
* Build a compact character-level diff for one template/contract excerpt.
*
* The backend stores only the two excerpts. Computing the visual marks here keeps old review
* records readable too: removed template text is red and added counterparty text is green.
*/
function buildInlineDiff(before: string, after: string): { before: DiffPiece[]; after: DiffPiece[] } {
if (!before || !after) {
return {
before: before ? [{ text: before, changed: true }] : [],
after: after ? [{ text: after, changed: true }] : [],
};
}
let prefixLength = 0;
const maxPrefix = Math.min(before.length, after.length);
while (prefixLength < maxPrefix && before[prefixLength] === after[prefixLength]) prefixLength += 1;
let suffixLength = 0;
const beforeRemaining = before.length - prefixLength;
const afterRemaining = after.length - prefixLength;
while (
suffixLength < beforeRemaining
&& suffixLength < afterRemaining
&& before[before.length - 1 - suffixLength] === after[after.length - 1 - suffixLength]
) suffixLength += 1;
const beforeChangedEnd = before.length - suffixLength;
const afterChangedEnd = after.length - suffixLength;
const prefix = before.slice(0, prefixLength);
const suffix = suffixLength ? before.slice(beforeChangedEnd) : '';
const beforePieces: DiffPiece[] = [];
const afterPieces: DiffPiece[] = [];
if (prefix) {
beforePieces.push({ text: prefix, changed: false });
afterPieces.push({ text: prefix, changed: false });
}
if (before.slice(prefixLength, beforeChangedEnd)) {
beforePieces.push({ text: before.slice(prefixLength, beforeChangedEnd), changed: true });
}
if (after.slice(prefixLength, afterChangedEnd)) {
afterPieces.push({ text: after.slice(prefixLength, afterChangedEnd), changed: true });
}
if (suffix) {
beforePieces.push({ text: suffix, changed: false });
afterPieces.push({ text: suffix, changed: false });
}
return { before: beforePieces, after: afterPieces };
}
/**
* 下载当前会话用户的审查报告(Word .docx)。
*/
async function onDownloadReport(): Promise<void> {
const reviewNo = review.value?.review_no;
if (!reviewNo || downloading.value) return;
downloading.value = true;
try {
await downloadChatContractReviewReport(reviewNo, 'docx');
msg.success(t('chat.procurementContract.downloadOk'));
} catch (error: unknown) {
msg.warning(error instanceof Error ? error.message : t('chat.procurementContract.downloadFailed'));
} finally {
downloading.value = false;
}
}
/** 下载当前合同的 PDF 风险高亮副本。 */
async function onDownloadAnnotated(): Promise<void> {
const reviewNo = review.value?.review_no;
if (!reviewNo || downloadingAnnotated.value) return;
downloadingAnnotated.value = true;
try {
await downloadChatAnnotatedContract(reviewNo);
msg.success(t('chat.procurementContract.downloadAnnotatedOk'));
} catch (error: unknown) {
msg.warning(error instanceof Error ? error.message : t('chat.procurementContract.downloadAnnotatedFailed'));
} finally {
downloadingAnnotated.value = false;
}
}
</script>
<template>
<article
v-if="review"
class="w-full max-w-[860px] overflow-hidden rounded-2xl border border-[#d8e0ec] bg-white shadow-[0_14px_36px_rgba(23,32,51,0.08)]"
>
<!-- 页头:审查编号 + 合同/模板元信息 + 高风险徽标 -->
<div class="flex flex-wrap items-start justify-between gap-3 border-b border-[#d8e0ec] bg-[#fbfcfe] px-4 py-3.5 md:px-4">
<div class="min-w-0">
<h3 class="m-0 text-[15px] font-bold leading-snug text-[#172033]">
{{ cardStatusTitle }} · {{ review.review_no }}
</h3>
<div class="mt-1 space-y-0.5 text-xs leading-5 text-[#667792]">
<p class="m-0">
{{ t('chat.procurementContract.counterpartyContract') }}:{{ review.contract_file_name }}
</p>
<p v-if="review.contract_no" class="m-0">
{{ t('chat.procurementContract.contractNo') }}:{{ review.contract_no }}
</p>
<p v-if="review.supplier_name" class="m-0">
{{ t('chat.procurementContract.supplier') }}:{{ review.supplier_name }}
</p>
<p v-if="review.template_name" class="m-0 flex flex-wrap items-center gap-1.5">
<span>{{ t(review.review_mode === 'compare'
? 'chat.procurementContract.comparisonBaseline'
: 'chat.procurementContract.template') }}:{{ review.template_name }}</span>
<span
v-if="templateSourceLabel"
class="inline-flex items-center rounded-full border border-[#9ec5ea] bg-[#eaf4ff] px-2.5 py-0.5 text-[11px] font-semibold text-[#2f80d1]"
>
{{ templateSourceLabel }}
</span>
</p>
</div>
</div>
<span
v-if="!isProcessing"
class="inline-flex shrink-0 items-center rounded-full border px-2.5 py-1 text-xs font-semibold"
:class="review.high_risk_count > 0
? 'border-[#fecdca] bg-[#fef3f2] text-[#b42318]'
: 'border-[#abe6c5] bg-[#ecfdf3] text-[#067647]'"
>
{{ headerRiskBadge }}
</span>
</div>
<div v-if="review.error_message" class="mx-4 mt-4 rounded-xl border border-[#fecdca] bg-[#fef3f2] px-3 py-2 text-sm text-[#b42318]">
{{ review.error_message }}
</div>
<div v-if="isProcessing" class="px-4 py-5">
<div class="overflow-x-auto pb-1">
<ol class="grid min-w-[700px] grid-cols-7">
<li
v-for="(step, index) in reviewProgressSteps"
:key="step.stage"
class="relative flex min-w-0 flex-col items-center px-1 text-center"
>
<div
v-if="index > 0"
class="absolute right-1/2 top-3 h-0.5 w-full"
:class="step.state === 'pending' ? 'bg-[#d8e0ec]' : 'bg-[#2f80d1]'"
/>
<div
class="relative z-10 flex h-6 w-6 items-center justify-center rounded-full border-2 bg-white text-[10px] font-bold transition-colors duration-300"
:class="step.state === 'completed'
? 'border-[#2f80d1] bg-[#2f80d1] text-white'
: step.state === 'active'
? 'border-[#2f80d1] text-[#2f80d1] shadow-[0_0_0_4px_rgba(47,128,209,0.13)]'
: 'border-[#cfd8e5] text-[#98a5b7]'"
>
<Check v-if="step.state === 'completed'" class="h-3.5 w-3.5" />
<Loader2 v-else-if="step.state === 'active'" class="h-3.5 w-3.5 animate-spin" />
<span v-else>{{ index + 1 }}</span>
</div>
<span
class="mt-2 block text-[11px] leading-4"
:class="step.state === 'active'
? 'font-bold text-[#1f5f99]'
: step.state === 'completed'
? 'font-medium text-[#31445f]'
: 'text-[#98a5b7]'"
>
{{ step.label }}
</span>
<span
class="mt-0.5 text-[10px] tabular-nums"
:class="step.state === 'pending' ? 'text-[#b0bac8]' : 'text-[#667792]'"
>
{{ step.milestone }}%
</span>
</li>
</ol>
</div>
</div>
<div v-else class="px-4 py-3.5">
<!-- 风险统计看板 -->
<div class="mb-3.5 grid grid-cols-2 gap-2.5 md:grid-cols-4">
<div class="rounded-xl border border-[#d8e0ec] bg-[#fafbfd] px-3 py-2.5">
<div class="text-xs text-[#667792]">{{ t('chat.procurementContract.changesCount') }}</div>
<div class="mt-0.5 text-xl font-bold text-[#2f80d1]">{{ changeCount }}</div>
</div>
<div class="rounded-xl border border-[#d8e0ec] bg-[#fafbfd] px-3 py-2.5">
<div class="text-xs text-[#667792]">{{ t('chat.procurementContract.riskHigh') }}</div>
<div class="mt-0.5 text-xl font-bold text-[#b42318]">{{ review.high_risk_count }}</div>
</div>
<div class="rounded-xl border border-[#d8e0ec] bg-[#fafbfd] px-3 py-2.5">
<div class="text-xs text-[#667792]">{{ t('chat.procurementContract.riskMedium') }}</div>
<div class="mt-0.5 text-xl font-bold text-[#b54708]">{{ review.medium_risk_count }}</div>
</div>
<div class="rounded-xl border border-[#d8e0ec] bg-[#fafbfd] px-3 py-2.5">
<div class="text-xs text-[#667792]">{{ t('chat.procurementContract.riskLow') }}</div>
<div class="mt-0.5 text-xl font-bold text-[#175cd3]">{{ review.low_risk_count }}</div>
</div>
</div>
<!-- 按业务语义互斥拆分:模板改动、独立风险;比对模式不展示 OCR 待确认主列表。 -->
<div
v-if="isCompareMode && comparisonScope.status === 'fallback'"
class="mb-3 rounded-xl border border-[#fedf89] bg-[#fffaeb] px-3 py-2 text-sm text-[#b54708]"
>
{{ t('chat.procurementContract.regionFallback') }}
</div>
<div
v-if="attachmentNotice"
class="mb-3 rounded-xl border border-[#9ec5ea] bg-[#eaf4ff] px-3 py-2 text-sm font-medium text-[#1f5f99]"
>
{{ attachmentNotice }} · {{ t('chat.procurementContract.attachmentContentIgnored') }}
</div>
<div v-if="clauses.length" class="space-y-4">
<section v-for="section in clauseSections" :key="section.key" class="overflow-x-auto">
<h4 class="mb-2 text-sm font-semibold text-[#31445f]">{{ section.title }}</h4>
<table class="w-full min-w-[720px] table-fixed border-collapse text-[13px]">
<colgroup>
<col class="w-[24%]" />
<col class="w-[12%]" />
<col class="w-[44%]" />
<col class="w-[20%]" />
</colgroup>
<thead>
<tr class="bg-[#f8fafc] text-left text-xs font-semibold text-[#667792]">
<th class="border-b border-[#d8e0ec] px-2 py-2.5">{{ t('chat.procurementContract.colClause') }}</th>
<th class="border-b border-[#d8e0ec] px-2 py-2.5">{{ t('chat.procurementContract.colChange') }}</th>
<th class="border-b border-[#d8e0ec] px-2 py-2.5">
{{ section.key === 'changes'
? t('chat.procurementContract.colComparison')
: t('chat.procurementContract.colEvidence') }}
</th>
<th class="border-b border-[#d8e0ec] px-2 py-2.5">
{{ section.key === 'changes'
? t('chat.procurementContract.colRisk')
: t('chat.procurementContract.colSuggestion') }}
</th>
</tr>
</thead>
<tbody>
<tr
v-for="(clause, index) in section.clauses"
:key="`${section.key}-${clause.clause_no || clause.title || index}-${index}`"
class="align-top"
>
<td class="break-words border-b border-[#d8e0ec] px-2 py-2.5 font-medium leading-5 text-[#172033]">
{{ clauseLabel(clause) }}
<span
v-if="section.key === 'risks'"
class="ml-1 inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-semibold"
:class="riskBadgeClass(clause.risk_level)"
>
{{ riskShortLabel(clause.risk_level) }}
</span>
<span
v-if="anchorPageLabel(clause)"
class="mt-1 block text-[11px] font-normal text-[#2f80d1]"
>
{{ anchorPageLabel(clause) }}
</span>
<span
v-if="clause.validation_status === 'needs_review'"
class="ml-1 inline-flex rounded border border-[#fedf89] bg-[#fffaeb] px-1.5 py-0.5 text-[10px] font-semibold text-[#b54708]"
>{{ t('chat.procurementContract.needsReview') }}</span>
</td>
<td class="border-b border-[#d8e0ec] px-2 py-2.5 text-[#667792]">
{{ changeTypeLabel(clause.change_type) }}
</td>
<td class="border-b border-[#d8e0ec] px-2 py-2.5">
<div
v-for="cmp in [clauseComparison(clause)]"
:key="`${clause.clause_no || clause.title || index}-cmp`"
class="grid gap-1 break-words"
>
<span
v-if="cmp.before || cmp.missingBefore"
class="grid gap-1 rounded border border-[#fecdca] bg-[#fef3f2] px-2 py-1.5 text-xs leading-5 text-[#667792]"
>
<span class="font-semibold text-[#b42318]">{{ t('chat.procurementContract.colTemplateText') }}</span>
<span>
<template v-if="cmp.missingBefore">{{ t('chat.procurementContract.missingOriginalSchedule') }}</template>
<template v-for="(piece, pieceIndex) in buildInlineDiff(cmp.before, cmp.after).before" v-else :key="`before-${pieceIndex}`">
<mark v-if="piece.changed" class="rounded bg-[#fecdca] px-0.5 text-[#b42318] line-through">{{ piece.text }}</mark>
<template v-else>{{ piece.text }}</template>
</template>
</span>
</span>
<span
v-if="cmp.after || cmp.missingAfter || cmp.unavailableReturnedSchedule"
class="grid gap-1 rounded border border-[#abe6c5] bg-[#ecfdf3] px-2 py-1.5 text-xs leading-5 text-[#172033]"
>
<span class="font-semibold text-[#067647]">
{{ section.key === 'changes'
? t('chat.procurementContract.colContractText')
: t('chat.procurementContract.colEvidence') }}
</span>
<span>
<template v-if="cmp.unavailableReturnedSchedule">{{ t('chat.procurementContract.unavailableReturnedSchedule') }}</template>
<template v-else-if="cmp.missingAfter">{{ t('chat.procurementContract.missingReturnedSchedule') }}</template>
<template v-for="(piece, pieceIndex) in buildInlineDiff(cmp.before, cmp.after).after" v-else :key="`after-${pieceIndex}`">
<mark v-if="piece.changed" class="rounded bg-[#abe6c5] px-0.5 text-[#067647]">{{ piece.text }}</mark>
<template v-else>{{ piece.text }}</template>
</template>
</span>
</span>
<span
v-if="!cmp.before && !cmp.after && cmp.unreadable"
class="text-xs leading-5 text-[#b54708]"
>{{ t('chat.procurementContract.unreadableComparison') }}</span>
<span
v-else-if="!cmp.before && !cmp.after && !cmp.note"
class="text-xs text-[#667792]"
>{{ t('chat.procurementContract.noComparisonText') }}</span>
<span
v-if="cmp.note"
class="text-xs leading-5 text-[#31445f]"
>{{ cmp.note }}</span>
</div>
</td>
<td class="border-b border-[#d8e0ec] px-2 py-2.5">
<span
v-if="section.key === 'changes'"
class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold"
:class="riskBadgeClass(clause.risk_level)"
>
{{ riskShortLabel(clause.risk_level, true) }}
</span>
<span v-else class="text-xs leading-5 text-[#31445f]">
{{ clauseSuggestion(clause) || clause.detail || '-' }}
</span>
</td>
</tr>
</tbody>
</table>
<p
v-if="section.key === 'confirmations' && confirmationHiddenCount > 0"
class="mt-2 text-xs text-[#667792]"
>
{{ t('chat.procurementContract.confirmationsHidden', { count: confirmationHiddenCount }) }}
</p>
</section>
<p
v-if="confirmationTotal > 0 && confirmationClauses.length === 0"
class="rounded-xl border border-[#fedf89] bg-[#fffaeb] px-3 py-2 text-sm text-[#b54708]"
>
{{ t('chat.procurementContract.confirmationsSummary', { count: confirmationTotal }) }}
</p>
</div>
<p
v-else-if="review.status === 'success' && confirmationTotal > 0"
class="rounded-xl border border-[#fedf89] bg-[#fffaeb] px-3 py-2 text-sm text-[#b54708]"
>
{{ t('chat.procurementContract.confirmationsSummary', { count: confirmationTotal }) }}
</p>
<p v-else-if="review.status === 'success'" class="text-sm text-[#667792]">
{{ t('chat.procurementContract.noClauses') }}
</p>
</div>
<!-- 底部操作:PDF 审核固定提供标注副本下载,扫描件由后端按 OCR 页码添加批注意见。 -->
<div v-if="!isProcessing" class="flex flex-wrap gap-2 px-4 pb-3.5">
<button
type="button"
class="inline-flex h-9 items-center rounded-[10px] bg-[#2f80d1] px-3.5 text-sm font-semibold text-white transition-colors hover:bg-[#276fb8] disabled:cursor-not-allowed disabled:opacity-50"
:disabled="downloading || review.status === 'failed'"
@click="onDownloadReport"
>
{{ downloading ? t('chat.procurementContract.downloading') : reportDownloadLabel }}
</button>
<button
v-if="review.status === 'success' && review.contract_file_name?.toLowerCase().endsWith('.pdf')"
type="button"
class="inline-flex h-9 items-center rounded-[10px] border border-[#9ec5ea] bg-[#eaf4ff] px-3.5 text-sm font-semibold text-[#2f80d1] transition-colors hover:bg-[#dceeff] disabled:cursor-not-allowed disabled:opacity-50"
:disabled="downloadingAnnotated"
@click="onDownloadAnnotated"
>
{{ downloadingAnnotated
? t('chat.procurementContract.downloading')
: t('chat.procurementContract.downloadAnnotated') }}
</button>
</div>
</article>
</template>