feat(contract): 采购合同对比agent

Signed-off-by: sophie <sophie>

Signed-off-by: sophie <sophie>
This commit is contained in:
sophie committed 2026-07-27 14:47:09 +08:00
1 parent ffccf19ba2
commit 0503ff76a6
90 files changed
+16729 -1344

No files matched your search

@@ -1,16 +1,17 @@
/**
* features/chat/components/ChatInputBar.vue
* 聊天输入栏:文本框、附件、语音、知识库选择与发送按钮。
* 逻辑:设备维保助手的管理入口(设备台账、登记维修)与语音按钮同侧排列,发送按钮独占右侧。
* 聊天输入栏:文本框、附件、语音、知识库与采购合同双文件输入控件。
* 逻辑:采购合同审查隐藏企业知识库;模板比对明确上传我方原合同和卖方回传合同,单份审核仅上传待审合同。
*/
<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import type { Ref } from 'vue';
import {
Check,
ChevronDown,
Database,
FileText,
Link2,
Loader2,
Mic,
@@ -18,8 +19,10 @@ import {
RefreshCw,
Send,
Square,
Upload,
X,
} from 'lucide-vue-next';
import type { ContractReviewMode } from '../composables/useProcurementContractChat';
import type { PendingAttachment, ShippingNoticePendingAttachment } from '../types/shipping.types';
import {
isBlockingWarning,
@@ -35,6 +38,7 @@ export interface ChatInputAttachmentPolicy {
const inputValue = defineModel<string>({ required: true });
const selectedKb = defineModel<string>('selectedKb', { required: true });
const procurementReviewMode = defineModel<ContractReviewMode>('procurementReviewMode', { default: 'compare' });
const props = defineProps<{
attachments: PendingAttachment[];
@@ -47,6 +51,8 @@ const props = defineProps<{
isUploadingAttachments: boolean;
canSendMessage: boolean;
isShippingNoticeAgent: boolean;
isProcurementContractAgent?: boolean;
procurementOriginalContractName?: string | null;
isMaintenanceAgent?: boolean;
canManageMaintenance?: boolean;
shippingSuggestedPrompt: string;
@@ -72,9 +78,12 @@ const emit = defineEmits<{
'maintenance-ledger-config': [];
'maintenance-create-record': [];
'clear-shipping-focus': [];
'procurement-original-contract-selected': [event: Event];
'clear-procurement-original-contract': [];
}>();
const filePickerRef = ref<HTMLInputElement | null>(null);
const originalContractPickerRef = ref<HTMLInputElement | null>(null);
const { t } = useI18n();
const textareaRef = ref<HTMLTextAreaElement | null>(null);
const attachmentMenuRef = ref<HTMLElement | null>(null);
@@ -85,6 +94,35 @@ const showAttachmentUrlPanel = ref(false);
const showKbDropdown = ref(false);
const attachmentUrlInput = ref('');
const hasProcurementContractAttachment = computed(() =>
Boolean(props.isProcurementContractAgent)
&& props.attachments.some((item) => item.kind === 'local'),
);
const procurementQuickActions = computed(() => {
const actions = [
{
label: 'chat.procurementContract.quickReview',
prompt: 'chat.procurementContract.promptReview',
},
{
label: 'chat.procurementContract.quickRisk',
prompt: 'chat.procurementContract.promptRisk',
},
];
if (procurementReviewMode.value === 'compare') {
actions.push({
label: 'chat.procurementContract.quickDiff',
prompt: 'chat.procurementContract.promptDiff',
});
}
actions.push({
label: 'chat.procurementContract.quickSuggestion',
prompt: 'chat.procurementContract.promptSuggestion',
});
return actions;
});
/**
* 汇总 EML 附件解析进度,供输入栏徽标展示。
* 核心逻辑:failed/empty/skipped/超限/文本预算耗尽计为问题;duplicate 单独提示,不记为失败。
@@ -172,6 +210,15 @@ const selectAttachmentLocal = () => {
filePickerRef.value?.click();
};
/**
* 采购合同 Agent 的主上传入口:比对模式选择卖方回传合同,单份模式选择待审合同。
*/
const selectProcurementContractLocal = () => {
if (!props.attachmentPolicy.canLocal || props.isThinking || props.isUploadingAttachments) return;
closeAttachmentMenu();
filePickerRef.value?.click();
};
const selectAttachmentUrl = async () => {
if (!props.attachmentPolicy.canRemote) return;
showAttachmentMenu.value = true;
@@ -201,6 +248,16 @@ const submitRemoteUrl = () => {
closeAttachmentMenu();
};
/**
* 上传合同后的快捷审查动作:写入审查方案并立即发送。
*/
const runProcurementQuickAction = async (promptKey: string) => {
if (!hasProcurementContractAttachment.value || props.isThinking || props.isUploadingAttachments) return;
inputValue.value = t(promptKey);
await nextTick();
emit('send');
};
const bindShippingPickerRef = (el: unknown) => {
props.shippingPickerRefHolder.pickerRef.value = (el as HTMLInputElement | null) ?? null;
};
@@ -259,6 +316,47 @@ watch(
<template>
<footer class="safe-bottom z-20 shrink-0 bg-transparent p-2 md:p-3">
<div class="relative mx-auto max-w-4xl">
<div
v-if="isProcurementContractAgent"
class="mb-2 flex flex-wrap items-center gap-2"
>
<div
class="inline-flex items-center gap-1 rounded-full border border-[#d8e0ec] bg-[#eef2f7] p-[3px]"
role="tablist"
:aria-label="$t('chat.procurementContract.mode')"
>
<button
type="button"
role="tab"
class="rounded-full px-3 py-1.5 text-xs font-bold transition-all"
:class="procurementReviewMode === 'compare'
? 'bg-white text-[#2f80d1] shadow-[0_1px_4px_rgba(23,32,51,0.08)]'
: 'bg-transparent text-[#667792] hover:text-[#172033]'"
:aria-selected="procurementReviewMode === 'compare'"
@click="procurementReviewMode = 'compare'"
>
{{ $t('chat.procurementContract.modeCompare') }}
</button>
<button
type="button"
role="tab"
class="rounded-full px-3 py-1.5 text-xs font-bold transition-all"
:class="procurementReviewMode === 'solo'
? 'bg-white text-[#2f80d1] shadow-[0_1px_4px_rgba(23,32,51,0.08)]'
: 'bg-transparent text-[#667792] hover:text-[#172033]'"
:aria-selected="procurementReviewMode === 'solo'"
@click="procurementReviewMode = 'solo'"
>
{{ $t('chat.procurementContract.modeSolo') }}
</button>
</div>
<span class="text-xs text-[#667792]">
{{ $t(procurementReviewMode === 'compare'
? 'chat.procurementContract.compareHint'
: 'chat.procurementContract.soloHint') }}
</span>
</div>
<div class="flex flex-col rounded-2xl bg-surface p-1.5 shadow-[0_0_15px_rgba(0,0,0,0.05)] transition-all">
<div
v-if="isShippingNoticeAgent && shippingFocusTaskNo"
@@ -307,12 +405,40 @@ watch(
@change="emit('local-files-selected', $event)"
/>
<input
ref="originalContractPickerRef"
type="file"
class="hidden"
accept=".pdf,.doc,.docx,.txt,.md"
@change="emit('procurement-original-contract-selected', $event)"
/>
<div
v-if="isProcurementContractAgent && procurementReviewMode === 'compare' && procurementOriginalContractName"
class="flex flex-wrap gap-2 px-3 pb-1"
>
<div class="flex items-center gap-2 rounded-lg border border-dashed border-[#8db8e6] bg-[#eef6ff] px-2 py-1 text-xs font-semibold text-[#1f5f99]">
<FileText class="h-3.5 w-3.5" />
<span class="max-w-[260px] truncate">{{ $t('chat.procurementContract.originalContractChip', { name: procurementOriginalContractName }) }}</span>
<button type="button" class="text-[#1f5f99] hover:opacity-80" @click="emit('clear-procurement-original-contract')">
<X class="h-3.5 w-3.5" />
</button>
</div>
</div>
<div v-if="attachments.length > 0" class="flex flex-wrap gap-2 px-3 pb-1">
<div
v-for="a in attachments"
:key="a.id"
class="flex items-center gap-2 rounded-lg border border-default bg-surface-soft px-2 py-1 text-xs text-secondary"
class="flex items-center gap-2 rounded-lg border px-2 py-1 text-xs"
:class="isProcurementContractAgent && a.kind === 'local'
? 'border-[#9cc7f2] bg-[#eef6ff] font-semibold text-[#1f5f99]'
: 'border-default bg-surface-soft text-secondary'"
>
<FileText
v-if="isProcurementContractAgent && a.kind === 'local'"
class="h-3.5 w-3.5 shrink-0 text-[#2f80d1]"
/>
<span class="max-w-[220px] truncate">
<template v-if="a.kind === 'shipping_notice'">
{{ a.originalFilename }}
@@ -351,6 +477,11 @@ watch(
<span v-else-if="a.parseStatus === 'failed'" class="text-muted"> · {{ t('chat.shippingNoticeParseFailed') }}</span>
</template>
<template v-else>
<span v-if="isProcurementContractAgent" class="mr-1 text-[#2f80d1]">
{{ $t(procurementReviewMode === 'compare'
? 'chat.procurementContract.sellerReturnedContractLabel'
: 'chat.procurementContract.contractToReviewLabel') }}:
</span>
{{ a.kind === 'local' ? a.file.name : a.url }}
</template>
</span>
@@ -378,6 +509,22 @@ watch(
</div>
</div>
<div
v-if="hasProcurementContractAttachment"
class="flex flex-wrap items-center gap-2 px-3 pb-1"
>
<button
v-for="action in procurementQuickActions"
:key="action.label"
type="button"
class="rounded-full border border-[#d8e0ec] bg-white px-3 py-1.5 text-xs font-semibold text-[#31445f] transition-colors hover:border-[#2f80d1] hover:bg-[#eef6ff] hover:text-[#1f5f99] disabled:cursor-not-allowed disabled:opacity-50"
:disabled="isThinking || isUploadingAttachments"
@click="runProcurementQuickAction(action.prompt)"
>
{{ $t(action.label) }}
</button>
</div>
<div
v-if="isShippingNoticeAgent && attachments.length > 0"
class="flex flex-wrap items-center gap-2 px-3 pb-1 text-xs text-muted"
@@ -471,7 +618,47 @@ watch(
</div>
</div>
<div v-if="!isMaintenanceAgent" ref="kbMenuRef" class="relative">
<div v-if="isProcurementContractAgent && procurementReviewMode === 'compare'" class="flex flex-wrap items-center gap-1.5">
<button
type="button"
class="flex items-center gap-1 rounded-full border border-[#8db8e6] bg-[#f8fbff] px-3 py-1.5 text-xs font-semibold text-[#1f5f99] transition-colors hover:border-[#2f80d1] hover:bg-[#eef6ff] disabled:cursor-not-allowed disabled:opacity-50"
:disabled="isThinking || isUploadingAttachments"
@click="originalContractPickerRef?.click()"
>
<Upload class="h-3.5 w-3.5" />
{{ $t('chat.procurementContract.uploadOriginalContract') }}
</button>
<button
type="button"
class="flex items-center gap-1 rounded-full bg-[#2f80d1] px-3 py-1.5 text-xs font-semibold text-white shadow-sm transition-colors hover:bg-[#2369ad] disabled:cursor-not-allowed disabled:opacity-50"
:disabled="isThinking || isUploadingAttachments || !attachmentPolicy.canLocal"
:title="$t('chat.procurementContract.uploadSellerReturnedContract')"
@click="selectProcurementContractLocal"
>
<Upload class="h-3.5 w-3.5" />
{{ $t('chat.procurementContract.uploadSellerReturnedContract') }}
</button>
</div>
<div
v-else-if="isProcurementContractAgent"
class="flex flex-wrap items-center gap-1.5"
>
<button
type="button"
class="flex items-center gap-1 rounded-full bg-[#2f80d1] px-3 py-1.5 text-xs font-semibold text-white shadow-sm transition-colors hover:bg-[#2369ad] disabled:cursor-not-allowed disabled:opacity-50"
:disabled="isThinking || isUploadingAttachments || !attachmentPolicy.canLocal"
:title="$t('chat.procurementContract.uploadContractToReview')"
@click="selectProcurementContractLocal"
>
<Upload class="h-3.5 w-3.5" />
{{ $t('chat.procurementContract.uploadContractToReview') }}
</button>
<span class="rounded-full border border-dashed border-[#d8e0ec] px-3 py-1.5 text-xs font-semibold text-[#667792]">
{{ $t('chat.procurementContract.soloHint') }}
</span>
</div>
<div v-else-if="!isMaintenanceAgent" ref="kbMenuRef" class="relative">
<button
type="button"
:disabled="kbDropdownDisabled"
@@ -264,6 +264,7 @@ watch(() => page.currentAgentId, () => {
:key="`${page.currentAgentId}-${page.conversationId || 'draft'}-${page.messages.length}`"
v-model="page.input"
v-model:selected-kb="page.selectedKb"
v-model:procurement-review-mode="page.procurementReviewMode"
:attachments="page.attachments"
:attachment-policy="page.attachmentPolicy"
:available-kb-options="page.availableKbOptions"
@@ -274,6 +275,8 @@ watch(() => page.currentAgentId, () => {
:is-uploading-attachments="page.isUploadingAttachments"
:can-send-message="page.canSendMessage"
:is-shipping-notice-agent="page.isShippingNoticeAgent"
:is-procurement-contract-agent="page.isProcurementContractAgent"
:procurement-original-contract-name="page.procurementOriginalContractName"
:is-maintenance-agent="isMaintenanceAgentPage"
:can-manage-maintenance="canManageMaintenance"
:shipping-suggested-prompt="page.shippingSuggestedPrompt"
@@ -295,6 +298,8 @@ watch(() => page.currentAgentId, () => {
@maintenance-ledger-config="maintenancePanel = 'ledger'"
@maintenance-create-record="openBlankMaintenanceRecordCreate"
@clear-shipping-focus="page.clearShippingFocus"
@procurement-original-contract-selected="page.handleProcurementOriginalContractSelected"
@clear-procurement-original-contract="page.clearProcurementOriginalContract"
/>
</div>
@@ -1,8 +1,8 @@
/**
* features/chat/components/messages/ChatMessageBubble.vue
* 用途:渲染单条聊天消息,统一承接用户气泡、助手 Markdown、内嵌文件下载、请假/出货子组件与操作栏。
* 依赖:Vue computed、lucide 图标、Leave/Shipping 子消息组件、chat.types 与页面级 handlers。
* 逻辑:由 ChatMessageList 按消息逐条挂载;正文渲染与特殊交互委托 useChatPageMarkdown 等页面编排层提供的 handlers。
* 用途:渲染单条聊天消息,统一承接用户气泡、助手 Markdown、内嵌文件下载、请假/出货/合同审查子组件与操作栏。
* 依赖:Vue computed、lucide 图标、Leave/Shipping/ContractReview 子消息组件、chat.types 与页面级 handlers。
* 逻辑:由 ChatMessageList 按消息逐条挂载;合同审查结果卡自带边框,外层不再套 chat-msg-assistant 气泡以免双层框。
*/
<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';
@@ -10,6 +10,7 @@ import { Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, Rotat
import { useAuthStore } from '@/features/auth/stores/auth.store';
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
import MaintenanceDeviceResultCard from './MaintenanceDeviceResultCard.vue';
import ContractReviewResultCard from './ContractReviewResultCard.vue';
import ShippingInventoryMappingMessage, { type ShippingMappingHandlers } from './ShippingInventoryMappingMessage.vue';
import ShippingMatchResultCard from './ShippingMatchResultCard.vue';
import ShippingParseReviewMessage, { type ShippingParseReviewHandlers } from './ShippingParseReviewMessage.vue';
@@ -87,6 +88,9 @@ const authStore = useAuthStore();
const INLINE_DOWNLOAD_ALLOWED_EMPLOYEE_ID = '17070141';
const RESTRICTED_INLINE_DOWNLOAD_FILE_NAME = '资产明细全量导出表.csv';
/** 合同审查结果卡:自身已是完整卡片,外层只需透明容器。 */
const isContractReviewMessage = computed(() => message.type === 'procurement-contract-review');
const isLeaveMessage = computed(() =>
message.type === 'leave-form'
|| message.type === 'leave-confirmation'
@@ -626,7 +630,9 @@ function handleInlineDownload(file: InlineDownloadFile): void {
class="text-[15px] leading-relaxed"
:class="message.role === 'user'
? 'rounded-2xl rounded-tr-sm bg-brand-600 px-5 py-2.5 text-white shadow-sm shadow-brand-500/15'
: 'chat-msg-assistant'"
: isContractReviewMessage
? 'w-full'
: 'chat-msg-assistant'"
>
<div v-if="message.role === 'user'" class="whitespace-pre-wrap">{{ message.content }}</div>
<div v-else>
@@ -664,6 +670,10 @@ function handleInlineDownload(file: InlineDownloadFile): void {
@view-record-history="emit('maintenance-view-record-history', $event)"
@create-record="emit('maintenance-create-record-for-device', $event)"
/>
<ContractReviewResultCard
v-else-if="message.type === 'procurement-contract-review'"
:message="message"
/>
<TrainingExamQuestionMessage
v-else-if="isTrainingExamMessage && trainingHandlers.getQuestion()"
:question="trainingHandlers.getQuestion()!"
@@ -0,0 +1,738 @@
/**
* 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);
let refreshTimer: ReturnType<typeof window.setTimeout> | 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;
} {
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: '' };
}
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 };
}
return { before: '', after: evidence, unreadable: false, note: evidence ? '' : fallback };
}
/** 风险项的建议独立展示,避免误标成“对方合同原文”。 */
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"
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-for="(piece, pieceIndex) in buildInlineDiff(cmp.before, cmp.after).before" :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"
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-for="(piece, pieceIndex) in buildInlineDiff(cmp.before, cmp.after).after" :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>