Merge branch 'dev' into hugo-shipping-notice
This commit is contained in:
commit
472b530be3
397 files changed
+46450
-34171
No files matched your search
@@ -0,0 +1,751 @@
|
||||
/**
|
||||
* 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;
|
||||
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>
|
||||
@@ -0,0 +1,264 @@
|
||||
/**
|
||||
* features/chat/composables/useProcurementContractChat.ts
|
||||
* 用途:采购合同审查 Agent 的会话态(模式、双文件输入、异步发起与进度轮询)。
|
||||
* 依赖:procurement-contract.api、file-assets.api、agent-registry.utils。
|
||||
* 逻辑:模板比对要求我方原合同与卖方回传合同;单份审核仅要求待审合同,结果卡可在刷新后回放。
|
||||
*/
|
||||
import { computed, ref, watch, type ComputedRef, type Ref } from 'vue';
|
||||
import {
|
||||
getChatContractReview,
|
||||
startChatContractReview,
|
||||
type ContractReviewRow,
|
||||
} from '@/features/admin/api/procurement-contract.api';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
import {
|
||||
isProcurementContractAgent as resolveProcurementContractAgent,
|
||||
type AgentRegistryFields,
|
||||
} from '@/shared/utils/agent-registry.utils';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { PendingAttachment } from '../types/shipping.types';
|
||||
|
||||
export type ContractReviewMode = 'compare' | 'solo';
|
||||
const REVIEW_POLL_INTERVAL_MS = 2000;
|
||||
const REVIEW_POLL_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
|
||||
export interface ProcurementContractChatOptions {
|
||||
currentAgent: Ref<AgentRegistryFields | null>;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
attachments: Ref<PendingAttachment[]>;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
isThinking: Ref<boolean>;
|
||||
isUploadingAttachments: Ref<boolean>;
|
||||
input: Ref<string>;
|
||||
clearAttachments: () => void;
|
||||
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
|
||||
loadHistory: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void; success: (text: string) => void; info: (text: string) => void };
|
||||
t: (key: string, params?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从审查 API 结果构建结果卡 payload(去掉过大的冗余后仍保留 Diff/红线数据)。
|
||||
*/
|
||||
function buildReviewResultPayload(review: ContractReviewRow): ContractReviewRow {
|
||||
return {
|
||||
id: review.id,
|
||||
review_no: review.review_no,
|
||||
review_mode: review.review_mode,
|
||||
status: review.status,
|
||||
contract_file_name: review.contract_file_name,
|
||||
supplier_name: review.supplier_name,
|
||||
contract_no: review.contract_no,
|
||||
contract_type: review.contract_type,
|
||||
template_id: review.template_id,
|
||||
template_source: review.template_source,
|
||||
template_name: review.template_name,
|
||||
total_change_count: review.total_change_count,
|
||||
high_risk_count: review.high_risk_count,
|
||||
medium_risk_count: review.medium_risk_count,
|
||||
low_risk_count: review.low_risk_count,
|
||||
user_id: review.user_id,
|
||||
user_name: review.user_name,
|
||||
error_message: review.error_message,
|
||||
started_at: review.started_at,
|
||||
finished_at: review.finished_at,
|
||||
created_at: review.created_at,
|
||||
progress: review.progress,
|
||||
processing_stage: review.processing_stage,
|
||||
processing_message: review.processing_message,
|
||||
summary_json: review.summary_json,
|
||||
clauses_json: review.clauses_json,
|
||||
report_text: review.report_text,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 轮询单次合同审核直到成功、失败或达到前端等待上限。
|
||||
* 核心逻辑:后端任务继续独立运行;前端超时只停止本页等待,不取消后台审核。
|
||||
* @param reviewNo - 后端返回的合同审查编号
|
||||
* @param onProgress - 每轮查询后更新当前消息卡
|
||||
*/
|
||||
async function pollContractReview(
|
||||
reviewNo: string,
|
||||
onProgress: (review: ContractReviewRow) => void,
|
||||
): Promise<ContractReviewRow> {
|
||||
const startedAt = Date.now();
|
||||
while (Date.now() - startedAt < REVIEW_POLL_TIMEOUT_MS) {
|
||||
const review = await getChatContractReview(reviewNo);
|
||||
onProgress(review);
|
||||
if (review.status === 'success' || review.status === 'failed') return review;
|
||||
await new Promise((resolve) => window.setTimeout(resolve, REVIEW_POLL_INTERVAL_MS));
|
||||
}
|
||||
throw new Error('contract review polling timed out');
|
||||
}
|
||||
|
||||
/**
|
||||
* 采购合同审查 Chat 编排。
|
||||
*/
|
||||
export function useProcurementContractChat(options: ProcurementContractChatOptions) {
|
||||
const isProcurementContractAgent = computed(() =>
|
||||
resolveProcurementContractAgent(options.currentAgent.value),
|
||||
);
|
||||
|
||||
const reviewMode = ref<ContractReviewMode>('compare');
|
||||
const originalContractAssetNo = ref<string | null>(null);
|
||||
const originalContractName = ref<string | null>(null);
|
||||
|
||||
const allowsSendWithAttachmentsOnly = computed(
|
||||
() => isProcurementContractAgent.value && (
|
||||
options.attachments.value.some((a) => a.kind === 'local')
|
||||
|| (reviewMode.value === 'compare' && Boolean(originalContractAssetNo.value))
|
||||
),
|
||||
);
|
||||
|
||||
watch(
|
||||
isProcurementContractAgent,
|
||||
(active) => {
|
||||
if (!active) {
|
||||
reviewMode.value = 'compare';
|
||||
originalContractAssetNo.value = null;
|
||||
originalContractName.value = null;
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/**
|
||||
* 上传合同比对所需的我方原合同,仅作为本次审核基准,不进入模板库。
|
||||
*/
|
||||
async function handleOriginalContractSelected(event: Event): Promise<void> {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
input.value = '';
|
||||
if (!file) return;
|
||||
options.isUploadingAttachments.value = true;
|
||||
try {
|
||||
const asset = await uploadFileAsset(file);
|
||||
originalContractAssetNo.value = asset.asset_no;
|
||||
originalContractName.value = asset.original_filename || file.name;
|
||||
} catch (e: unknown) {
|
||||
options.msg.warning(e instanceof Error ? e.message : options.t('chat.procurementContract.uploadFailed'));
|
||||
} finally {
|
||||
options.isUploadingAttachments.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除已上传的我方原合同基准。
|
||||
*/
|
||||
function clearOriginalContract(): void {
|
||||
originalContractAssetNo.value = null;
|
||||
originalContractName.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拦截带本地附件的发送:上传 FileAsset → 创建异步审查 → 轮询进度 → 写入最终结果卡。
|
||||
* @returns true 表示已消费本次发送
|
||||
*/
|
||||
async function tryHandleProcurementContractSend(
|
||||
textOrEvent: string | Event | undefined,
|
||||
_content: string,
|
||||
trimmed: string,
|
||||
): Promise<boolean> {
|
||||
if (!isProcurementContractAgent.value) return false;
|
||||
const locals = options.attachments.value.filter(
|
||||
(a): a is Extract<PendingAttachment, { kind: 'local' }> => a.kind === 'local',
|
||||
);
|
||||
if (!locals.length) {
|
||||
if (reviewMode.value === 'compare' && originalContractAssetNo.value) {
|
||||
options.msg.warning(options.t('chat.procurementContract.compareFilesRequired'));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (options.isThinking.value || options.isUploadingAttachments.value) return true;
|
||||
|
||||
if (locals.length > 1) {
|
||||
options.msg.warning(options.t('chat.procurementContract.oneContractOnly'));
|
||||
return true;
|
||||
}
|
||||
if (reviewMode.value === 'compare' && !originalContractAssetNo.value) {
|
||||
options.msg.warning(options.t('chat.procurementContract.compareFilesRequired'));
|
||||
return true;
|
||||
}
|
||||
|
||||
const contractFile = locals[0]!.file;
|
||||
options.isUploadingAttachments.value = true;
|
||||
options.isThinking.value = true;
|
||||
try {
|
||||
// [STEP 1] 上传待审合同
|
||||
const contractAsset = await uploadFileAsset(contractFile);
|
||||
|
||||
// [STEP 2] 比对模式固定以用户上传的我方原合同作为基准,不再读取默认模板。
|
||||
const queuedReview = await startChatContractReview({
|
||||
review_mode: reviewMode.value,
|
||||
contract_asset_no: contractAsset.asset_no,
|
||||
original_contract_asset_no:
|
||||
reviewMode.value === 'compare' ? originalContractAssetNo.value : null,
|
||||
contract_type: 'general_procurement',
|
||||
agent_id: options.currentAgentId.value || null,
|
||||
});
|
||||
|
||||
// [STEP 3] 立即显示用户消息和排队进度卡
|
||||
const userText =
|
||||
trimmed
|
||||
|| options.t('chat.procurementContract.defaultUserQuery', {
|
||||
file: contractFile.name,
|
||||
mode:
|
||||
reviewMode.value === 'solo'
|
||||
? options.t('chat.procurementContract.modeSolo')
|
||||
: options.t('chat.procurementContract.modeCompare'),
|
||||
});
|
||||
const userMsg: ChatMessage = { role: 'user', content: userText, type: 'text' };
|
||||
options.messages.value.push(userMsg);
|
||||
|
||||
const assistantMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'procurement-contract-review',
|
||||
content: options.t('chat.procurementContract.reviewQueued'),
|
||||
payload: buildReviewResultPayload(queuedReview),
|
||||
};
|
||||
options.messages.value.push(assistantMsg);
|
||||
if (typeof textOrEvent !== 'string') options.input.value = '';
|
||||
options.clearAttachments();
|
||||
clearOriginalContract();
|
||||
options.isUploadingAttachments.value = false;
|
||||
options.isThinking.value = false;
|
||||
|
||||
// [STEP 4] 后台完成后原地替换进度卡,再持久化正式结果。
|
||||
const review = await pollContractReview(queuedReview.review_no, (latest) => {
|
||||
assistantMsg.payload = buildReviewResultPayload(latest);
|
||||
assistantMsg.content = latest.processing_message || options.t('chat.procurementContract.reviewRunning');
|
||||
});
|
||||
if (review.status === 'failed') {
|
||||
throw new Error(review.error_message || options.t('chat.procurementContract.reviewFailed'));
|
||||
}
|
||||
assistantMsg.payload = buildReviewResultPayload(review);
|
||||
assistantMsg.content =
|
||||
review.summary_json && typeof review.summary_json.headline === 'string'
|
||||
? String(review.summary_json.headline)
|
||||
: options.t('chat.procurementContract.resultTitle');
|
||||
await options.saveLocalMessageToBackend(assistantMsg, userText);
|
||||
await options.loadHistory();
|
||||
} catch (e: unknown) {
|
||||
options.msg.warning(
|
||||
e instanceof Error ? e.message : options.t('chat.procurementContract.reviewFailed'),
|
||||
);
|
||||
} finally {
|
||||
options.isUploadingAttachments.value = false;
|
||||
options.isThinking.value = false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return {
|
||||
isProcurementContractAgent,
|
||||
reviewMode,
|
||||
originalContractAssetNo,
|
||||
originalContractName,
|
||||
allowsSendWithAttachmentsOnly,
|
||||
handleOriginalContractSelected,
|
||||
clearOriginalContract,
|
||||
tryHandleProcurementContractSend,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* features/chat/leave/leave.api.ts
|
||||
* 用途:封装聊天请假流程的余额查询与 OA 工作流提交请求。
|
||||
* 依赖:shared/utils/auth、shared/api/client。
|
||||
* 逻辑:聊天请假表单调用本模块;后端暂保留 /api/user/leave-* 路径以兼容既有接口。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { LeaveRequestFormData } from '../types/leave.types';
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||
|
||||
export interface LeaveBalanceResult {
|
||||
has_balance: boolean;
|
||||
leave_type_label: string;
|
||||
year: number;
|
||||
total_hours: number | null;
|
||||
used_hours: number | null;
|
||||
remaining_hours: number | null;
|
||||
}
|
||||
|
||||
/** 查询当前用户指定假别的可用余额。 */
|
||||
export const getLeaveBalance = (leaveType: string) =>
|
||||
requestJson<LeaveBalanceResult>(`/api/user/leave-balance?leave_type=${encodeURIComponent(leaveType)}`, auth());
|
||||
|
||||
export interface LeaveWorkflowSubmitResult {
|
||||
request_id?: string;
|
||||
submitted_at?: string;
|
||||
request_name?: string;
|
||||
}
|
||||
|
||||
/** 将聊天内确认后的请假表单提交至 OA 工作流。 */
|
||||
export const submitLeaveWorkflow = (form: LeaveRequestFormData) =>
|
||||
requestJson<LeaveWorkflowSubmitResult>('/api/user/leave-workflow/submit', {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
@@ -26,6 +26,13 @@ export const DEFAULT_TRAINING_HR_CHAT_QUESTIONS = [
|
||||
'我想查看本月培训成绩统计',
|
||||
];
|
||||
|
||||
/** 返回指定培训角色的默认问题,供管理表单初始化使用。 */
|
||||
export const getDefaultTrainingChatQuestions = (role: TrainingChatQuestionRole): string[] => (
|
||||
role === 'hr'
|
||||
? cloneQuestions(DEFAULT_TRAINING_HR_CHAT_QUESTIONS)
|
||||
: cloneQuestions(DEFAULT_TRAINING_EMPLOYEE_CHAT_QUESTIONS)
|
||||
);
|
||||
|
||||
const asRecord = (value: unknown): Record<string, unknown> => (
|
||||
value && typeof value === 'object' && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
@@ -49,11 +56,7 @@ const normalizeTrainingChatQuestionList = (value: unknown): string[] => {
|
||||
.filter(Boolean);
|
||||
};
|
||||
|
||||
const getDefaultQuestions = (role: TrainingChatQuestionRole) => (
|
||||
role === 'hr'
|
||||
? cloneQuestions(DEFAULT_TRAINING_HR_CHAT_QUESTIONS)
|
||||
: cloneQuestions(DEFAULT_TRAINING_EMPLOYEE_CHAT_QUESTIONS)
|
||||
);
|
||||
const getDefaultQuestions = getDefaultTrainingChatQuestions;
|
||||
|
||||
/**
|
||||
* 读取培训配置中的角色化聊天常见问题。
|
||||
|
||||
@@ -216,7 +216,7 @@ export interface ChatMessage {
|
||||
content: string;
|
||||
/** 用户提交时固化的附件展示快照;助手消息不使用此字段。 */
|
||||
attachments?: ChatMessageAttachment[];
|
||||
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result' | 'maintenance-device-result';
|
||||
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result' | 'maintenance-device-result' | 'procurement-contract-review';
|
||||
retriever_resources?: RetrieverResource[];
|
||||
attribution_parts?: string[];
|
||||
chat_log_id?: number;
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* 用途:验证 Mermaid 兼容规范化,防止中文分组标题再次导致流程图解析失败。
|
||||
* 依赖:vitest、mermaidChart。
|
||||
* 逻辑:覆盖无 ID 中文 subgraph 的标准化以及原本标准语法的不变性。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildMermaidFlowFallbackHtml, normalizeMermaidChart } from './mermaidChart';
|
||||
|
||||
describe('normalizeMermaidChart', () => {
|
||||
it('为中文 subgraph 标题补齐可解析的 ASCII ID', () => {
|
||||
// 断言:Dify 常见的中文分组写法被转为 Mermaid 标准分组声明。
|
||||
expect(normalizeMermaidChart('graph TD\nsubgraph 项目启动阶段\nA[接单]\nend'))
|
||||
.toContain('subgraph group_1["项目启动阶段"]');
|
||||
});
|
||||
|
||||
it('保留已有 ID 的标准 subgraph', () => {
|
||||
// 断言:已规范的 Mermaid 不被重复改写。
|
||||
expect(normalizeMermaidChart('subgraph phase_start["项目启动阶段"]'))
|
||||
.toBe('subgraph phase_start["项目启动阶段"]');
|
||||
});
|
||||
|
||||
it('将无法解析的主流程降级为可视化卡片', () => {
|
||||
// 断言:即使 Mermaid 语法异常,用户仍能看到节点和顺序,而不是红色源码。
|
||||
const html = buildMermaidFlowFallbackHtml('A[接单] --> B[项目立项]\nB --> C[项目启动阶段]');
|
||||
expect(html).toContain('接单');
|
||||
expect(html).toContain('项目启动阶段');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* 用途:规范化智能体输出的 Mermaid 图表文本,兼容中文分组标题等常见非标准写法。
|
||||
* 依赖:由 ChatMessageBubble 在调用 mermaid.render 前使用。
|
||||
* 逻辑:保留合法语句不变;仅为没有 ID 的 subgraph 补充稳定 ASCII ID 与带引号标题,
|
||||
* 避免 Mermaid 把中文标题解析为图语法 token 而导致整张流程图无法显示。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 用途:将常见的中文 Mermaid 分组语法转换为 Mermaid 可稳定解析的标准形式。
|
||||
* AI 触发时机:智能体返回 `subgraph 项目启动阶段` 等没有 ASCII 节点 ID 的分组标题时调用。
|
||||
* 核心逻辑:逐行识别 subgraph;已经包含 ID、方括号或引号的标准写法不变;其余标题生成唯一 ID。
|
||||
* 参数与输出约束:输入必须为 Mermaid 文本;输出只调整 subgraph 声明,不修改节点、连线及 end 语句。
|
||||
*/
|
||||
export function normalizeMermaidChart(source: string): string {
|
||||
let subgraphIndex = 0;
|
||||
return String(source || '')
|
||||
.replace(/^\s*graph\s+/im, (matched) => matched.replace(/graph/i, 'flowchart'))
|
||||
.split('\n')
|
||||
.map((line) => {
|
||||
const match = line.match(/^(\s*)subgraph\s+(.+?)\s*$/i);
|
||||
if (!match) return line;
|
||||
const indent = match[1] || '';
|
||||
const rawTitle = (match[2] || '').trim();
|
||||
if (!rawTitle || /[\[\]"']/.test(rawTitle) || /^[A-Za-z_][A-Za-z0-9_-]*\s/.test(rawTitle)) return line;
|
||||
subgraphIndex += 1;
|
||||
return `${indent}subgraph group_${subgraphIndex}["${rawTitle.replace(/"/g, '\\"')}"]`;
|
||||
})
|
||||
.join('\n')
|
||||
// Mermaid 对含括号、标点或中文的节点标签需要显式引号;Dify 常会遗漏它。
|
||||
.replace(/([A-Za-z][A-Za-z0-9_-]*)\[([^\]"\n]+)\]/g, (_matched, nodeId: string, label: string) => (
|
||||
`${nodeId}["${label.trim().replace(/"/g, '\\"')}"]`
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 用途:在 Mermaid 仍无法解析时,将简单流程图转换为可读的流程卡片。
|
||||
* AI 触发时机:图表库抛出语法异常且原文中存在 `A[节点] --> B[节点]` 这类链路时调用。
|
||||
* 核心逻辑:提取节点顺序和标签,输出已转义的 HTML 卡片;忽略不影响主流程的 subgraph 细节。
|
||||
* 参数与输出约束:只用于展示兜底,不执行任何模型输出中的 HTML 或脚本。
|
||||
*/
|
||||
export function buildMermaidFlowFallbackHtml(source: string): string | null {
|
||||
const labels = new Map<string, string>();
|
||||
const order: string[] = [];
|
||||
const text = String(source || '');
|
||||
const nodePattern = /([A-Za-z][A-Za-z0-9_-]*)\s*\[\s*"?([^\]\n"]+)"?\s*\]/g;
|
||||
const edgePattern = /([A-Za-z][A-Za-z0-9_-]*)(?:\s*\[[^\]\n]*\])?\s*--+>\s*([A-Za-z][A-Za-z0-9_-]*)(?:\s*\[[^\]\n]*\])?/g;
|
||||
const escapeHtml = (value: string) => String(value)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
for (const match of text.matchAll(nodePattern)) {
|
||||
const nodeId = match[1];
|
||||
const label = match[2];
|
||||
if (nodeId && label) labels.set(nodeId, label.trim());
|
||||
}
|
||||
for (const match of text.matchAll(edgePattern)) {
|
||||
const fromId = match[1];
|
||||
const toId = match[2];
|
||||
if (!fromId || !toId) continue;
|
||||
if (!order.includes(fromId)) order.push(fromId);
|
||||
if (!order.includes(toId)) order.push(toId);
|
||||
}
|
||||
if (order.length < 2) return null;
|
||||
const cards = order.map((id, index) => {
|
||||
const card = `<div class="chat-flow-fallback-card">${escapeHtml(labels.get(id) || id)}</div>`;
|
||||
return index < order.length - 1 ? `${card}<div class="chat-flow-fallback-arrow" aria-hidden="true">↓</div>` : card;
|
||||
});
|
||||
return `<div class="chat-flow-fallback" role="img" aria-label="流程图">${cards.join('')}</div>`;
|
||||
}
|
||||
Reference in new issue
Block a user