Merge branch 'env' into dev
This commit is contained in:
commit
d79def5519
90 files changed
+16729
-1344
No files matched your search
@@ -0,0 +1,406 @@
|
||||
/**
|
||||
* features/admin/api/procurement-contract.api.ts
|
||||
* 用途:采购合同审查 Admin / 会话 API 封装(含鉴权下载)。
|
||||
* 依赖:shared/api/client requestJson、auth headers。
|
||||
* 逻辑:Templates / Reviews 页面与 Chat 控件调用;下载走 fetch+blob。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
|
||||
export type ContractMetadataField = 'title' | 'version' | 'contract_no' | 'buyer' | 'seller';
|
||||
|
||||
export interface ContractComparisonRegionConfig {
|
||||
metadata_fields: ContractMetadataField[];
|
||||
body_start_anchors: string[];
|
||||
body_end_anchors: string[];
|
||||
signature_terms: string[];
|
||||
attachment_start_anchors: string[];
|
||||
attachment_policy: 'page_count_only';
|
||||
}
|
||||
|
||||
export interface ContractComparisonRegionPreview {
|
||||
status: 'recognized' | 'incomplete' | string;
|
||||
body_start_anchor?: string | null;
|
||||
body_end_anchor?: string | null;
|
||||
signature_terms_found?: string[];
|
||||
attachment_anchor?: string | null;
|
||||
warning?: string | null;
|
||||
}
|
||||
|
||||
export interface ContractTemplateRow {
|
||||
id: number;
|
||||
name: string;
|
||||
version: string;
|
||||
file_name: string;
|
||||
file_asset_id?: number | null;
|
||||
contract_type?: string;
|
||||
applicable_scope?: string | null;
|
||||
change_note?: string | null;
|
||||
comparison_region_config?: ContractComparisonRegionConfig | null;
|
||||
status: 'enabled' | 'disabled' | string;
|
||||
is_default: boolean;
|
||||
remark?: string | null;
|
||||
updated_by_name?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ContractClauseItem {
|
||||
clause_no?: string;
|
||||
title?: string;
|
||||
change_type?: string;
|
||||
/** 后端语义分类:仅 obligation 会参与法律与履约风险统计。 */
|
||||
change_class?: 'format' | 'metadata' | 'commercial' | 'obligation' | string;
|
||||
risk_level?: string;
|
||||
clause_category?: string;
|
||||
detail?: string;
|
||||
risk_hint?: string;
|
||||
suggestion?: string;
|
||||
negotiation_text?: string;
|
||||
old_text?: string;
|
||||
new_text?: string;
|
||||
/** 后端标记:old/new 是否为可读抽取片段;false 时前端展示编码不兼容提示 */
|
||||
comparison_readable?: boolean;
|
||||
llm_enabled?: boolean;
|
||||
llm_confidence?: number | null;
|
||||
llm_reason?: string;
|
||||
llm_suggestion?: string;
|
||||
llm_negotiation_text?: string;
|
||||
llm_model_risk_level?: string;
|
||||
llm_decision?: 'confirm' | 'reject' | 'uncertain' | string;
|
||||
llm_evidence?: string;
|
||||
evidence?: string;
|
||||
source?: string;
|
||||
validation_status?: 'confirmed' | 'needs_review' | string;
|
||||
/** 同一业务主题下聚合的底层 OCR 不确定片段数。 */
|
||||
affected_fragments?: number;
|
||||
business_impact?: string;
|
||||
anchor_status?: 'anchored' | 'unanchored' | string;
|
||||
evidence_anchor?: {
|
||||
page_no?: number;
|
||||
rects?: number[][];
|
||||
matched_text?: string;
|
||||
source_text?: string;
|
||||
confidence?: number;
|
||||
method?: 'exact' | 'fuzzy' | 'ocr_page' | string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface ContractRiskRuleRow {
|
||||
id: number;
|
||||
code: string;
|
||||
/** 内置规则携带组合业务判断;自定义规则仅执行关键词命中判断。 */
|
||||
rule_kind?: 'builtin' | 'custom' | string;
|
||||
contract_type: string;
|
||||
clause_category: string;
|
||||
title: string;
|
||||
keywords: string[];
|
||||
trigger_type: 'keyword_missing' | 'keyword_present' | string;
|
||||
risk_level: 'high' | 'medium' | 'low' | string;
|
||||
risk_hint: string;
|
||||
suggestion: string;
|
||||
negotiation_text?: string | null;
|
||||
status: 'enabled' | 'disabled' | string;
|
||||
sort_order: number;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ContractReviewRow {
|
||||
id: number;
|
||||
review_no: string;
|
||||
review_mode: 'compare' | 'solo' | string;
|
||||
status: string;
|
||||
contract_file_name: string;
|
||||
supplier_name?: string | null;
|
||||
/** 从合同正文抽取的业务合同编号(非审查编号) */
|
||||
contract_no?: string | null;
|
||||
contract_type?: string;
|
||||
template_id?: number | null;
|
||||
template_source: string;
|
||||
template_name?: string | null;
|
||||
total_change_count?: number;
|
||||
high_risk_count: number;
|
||||
medium_risk_count: number;
|
||||
low_risk_count: number;
|
||||
user_id: number;
|
||||
user_name?: string | null;
|
||||
error_message?: string | null;
|
||||
started_at?: string | null;
|
||||
finished_at?: string | null;
|
||||
created_at?: string | null;
|
||||
progress?: number;
|
||||
processing_stage?: string | null;
|
||||
processing_message?: string | null;
|
||||
summary_json?: Record<string, unknown> | null;
|
||||
clauses_json?: ContractClauseItem[] | null;
|
||||
report_text?: string | null;
|
||||
template_asset_id?: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 鉴权下载:fetch blob → 触发浏览器保存。
|
||||
* @param url - 需携带 JWT 的下载 URL
|
||||
* @param fallbackName - Content-Disposition 缺失时的文件名
|
||||
*/
|
||||
async function downloadAuthenticatedFile(url: string, fallbackName: string): Promise<void> {
|
||||
const res = await fetch(url, { headers: getAuthHeaders() });
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
const err = body as { error?: { message?: string }; message?: string };
|
||||
throw new Error(err?.error?.message || err?.message || res.statusText);
|
||||
}
|
||||
const disposition = res.headers.get('content-disposition');
|
||||
const blob = await res.blob();
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = objectUrl;
|
||||
const rawName = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || fallbackName;
|
||||
try {
|
||||
a.download = decodeURIComponent(rawName);
|
||||
} catch {
|
||||
a.download = rawName;
|
||||
}
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
|
||||
/** Admin:下载模板文件 */
|
||||
export function downloadAdminContractTemplate(templateId: number): Promise<void> {
|
||||
return downloadAuthenticatedFile(
|
||||
`/api/admin/procurement-contract/templates/${templateId}/file`,
|
||||
`template-${templateId}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin:下载审查报告。
|
||||
* @param reviewId - 审查主键
|
||||
* @param reviewNo - 审查编号(文件名用)
|
||||
* @param format - 默认 docx;传 txt 可下载纯文本
|
||||
*/
|
||||
export function downloadAdminContractReviewReport(
|
||||
reviewId: number,
|
||||
reviewNo?: string,
|
||||
format: 'txt' | 'docx' = 'docx',
|
||||
): Promise<void> {
|
||||
const q = format === 'docx' ? '?format=docx' : '';
|
||||
return downloadAuthenticatedFile(
|
||||
`/api/admin/procurement-contract/reviews/${reviewId}/report${q}`,
|
||||
`${reviewNo || reviewId}_report.${format === 'docx' ? 'docx' : 'txt'}`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Admin:下载待审合同 */
|
||||
export function downloadAdminContractReviewContract(reviewId: number, fileName?: string): Promise<void> {
|
||||
return downloadAuthenticatedFile(
|
||||
`/api/admin/procurement-contract/reviews/${reviewId}/contract`,
|
||||
fileName || `contract-${reviewId}`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Admin:下载带风险高亮批注的合同 PDF 副本 */
|
||||
export function downloadAdminAnnotatedContract(reviewId: number, reviewNo?: string): Promise<void> {
|
||||
return downloadAuthenticatedFile(
|
||||
`/api/admin/procurement-contract/reviews/${reviewId}/annotated-contract`,
|
||||
`${reviewNo || reviewId}_annotated.pdf`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Admin:下载本次审查所用模板文件 */
|
||||
export function downloadAdminContractReviewTemplateFile(reviewId: number): Promise<void> {
|
||||
return downloadAuthenticatedFile(
|
||||
`/api/admin/procurement-contract/reviews/${reviewId}/template-file`,
|
||||
`template-for-review-${reviewId}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Chat:下载本人审查报告。
|
||||
* @param reviewNo - 审查编号
|
||||
* @param format - 默认 docx;传 txt 可下载纯文本
|
||||
*/
|
||||
export function downloadChatContractReviewReport(
|
||||
reviewNo: string,
|
||||
format: 'txt' | 'docx' = 'docx',
|
||||
): Promise<void> {
|
||||
const q = format === 'docx' ? '?format=docx' : '';
|
||||
return downloadAuthenticatedFile(
|
||||
`/api/procurement-contract/reviews/${encodeURIComponent(reviewNo)}/report${q}`,
|
||||
`${reviewNo}_report.${format === 'docx' ? 'docx' : 'txt'}`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Chat:下载本人带风险高亮批注的合同 PDF */
|
||||
export function downloadChatAnnotatedContract(reviewNo: string): Promise<void> {
|
||||
return downloadAuthenticatedFile(
|
||||
`/api/procurement-contract/reviews/${encodeURIComponent(reviewNo)}/annotated-contract`,
|
||||
`${reviewNo}_annotated.pdf`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理端模板列表。
|
||||
*/
|
||||
export async function listAdminContractTemplates(status?: string): Promise<ContractTemplateRow[]> {
|
||||
const q = status ? `?status=${encodeURIComponent(status)}` : '';
|
||||
return requestJson<ContractTemplateRow[]>(`/api/admin/procurement-contract/templates${q}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传并创建模板(multipart)。
|
||||
*/
|
||||
export async function createAdminContractTemplate(form: FormData): Promise<ContractTemplateRow> {
|
||||
const res = await fetch('/api/admin/procurement-contract/templates', {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
body: form,
|
||||
});
|
||||
const body = await res.json();
|
||||
if (!res.ok || body?.success === false) {
|
||||
throw new Error(body?.error?.message || body?.message || 'upload failed');
|
||||
}
|
||||
return (body?.data ?? body) as ContractTemplateRow;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新模板。
|
||||
*/
|
||||
export async function updateAdminContractTemplate(
|
||||
id: number,
|
||||
data: Partial<Pick<ContractTemplateRow, 'name' | 'version' | 'status' | 'is_default' | 'remark' | 'contract_type' | 'applicable_scope' | 'change_note' | 'comparison_region_config'>>,
|
||||
): Promise<ContractTemplateRow> {
|
||||
return requestJson<ContractTemplateRow>(`/api/admin/procurement-contract/templates/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
/** Admin: preview unsaved region anchors against the stored template file. */
|
||||
export async function previewAdminContractTemplateRegions(
|
||||
id: number,
|
||||
comparisonRegionConfig: ContractComparisonRegionConfig,
|
||||
): Promise<ContractComparisonRegionPreview> {
|
||||
return requestJson<ContractComparisonRegionPreview>(
|
||||
`/api/admin/procurement-contract/templates/${id}/comparison-region-preview`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ comparison_region_config: comparisonRegionConfig }),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除模板。
|
||||
*/
|
||||
export async function deleteAdminContractTemplate(id: number): Promise<void> {
|
||||
await requestJson(`/api/admin/procurement-contract/templates/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
/**
|
||||
* 审查历史列表。
|
||||
*/
|
||||
export async function listAdminContractReviews(params?: {
|
||||
review_mode?: string;
|
||||
template_source?: string;
|
||||
status?: string;
|
||||
keyword?: string;
|
||||
contract_type?: string;
|
||||
supplier_name?: string;
|
||||
risk_level?: string;
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
}): Promise<{ total: number; items: ContractReviewRow[] }> {
|
||||
const sp = new URLSearchParams();
|
||||
if (params?.review_mode) sp.set('review_mode', params.review_mode);
|
||||
if (params?.template_source) sp.set('template_source', params.template_source);
|
||||
if (params?.status) sp.set('status', params.status);
|
||||
if (params?.keyword) sp.set('keyword', params.keyword);
|
||||
if (params?.contract_type) sp.set('contract_type', params.contract_type);
|
||||
if (params?.supplier_name) sp.set('supplier_name', params.supplier_name);
|
||||
if (params?.risk_level) sp.set('risk_level', params.risk_level);
|
||||
if (params?.date_from) sp.set('date_from', params.date_from);
|
||||
if (params?.date_to) sp.set('date_to', params.date_to);
|
||||
const q = sp.toString() ? `?${sp.toString()}` : '';
|
||||
return requestJson(`/api/admin/procurement-contract/reviews${q}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 审查详情。
|
||||
*/
|
||||
export async function getAdminContractReview(id: number): Promise<ContractReviewRow> {
|
||||
return requestJson(`/api/admin/procurement-contract/reviews/${id}`);
|
||||
}
|
||||
|
||||
/** Admin:风险规则列表 */
|
||||
export async function listAdminContractRiskRules(params?: {
|
||||
contract_type?: string;
|
||||
status?: string;
|
||||
clause_category?: string;
|
||||
}): Promise<ContractRiskRuleRow[]> {
|
||||
const sp = new URLSearchParams();
|
||||
if (params?.contract_type) sp.set('contract_type', params.contract_type);
|
||||
if (params?.status) sp.set('status', params.status);
|
||||
if (params?.clause_category) sp.set('clause_category', params.clause_category);
|
||||
const q = sp.toString() ? `?${sp.toString()}` : '';
|
||||
return requestJson(`/api/admin/procurement-contract/rules${q}`);
|
||||
}
|
||||
|
||||
/** Admin:创建风险规则 */
|
||||
export async function createAdminContractRiskRule(
|
||||
data: Omit<Partial<ContractRiskRuleRow>, 'id'>,
|
||||
): Promise<ContractRiskRuleRow> {
|
||||
return requestJson('/api/admin/procurement-contract/rules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
/** Admin:更新风险规则 */
|
||||
export async function updateAdminContractRiskRule(
|
||||
id: number,
|
||||
data: Partial<ContractRiskRuleRow>,
|
||||
): Promise<ContractRiskRuleRow> {
|
||||
return requestJson(`/api/admin/procurement-contract/rules/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
/** Admin:删除风险规则 */
|
||||
export async function deleteAdminContractRiskRule(id: number): Promise<void> {
|
||||
await requestJson(`/api/admin/procurement-contract/rules/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
/** 会话:启用模板列表 */
|
||||
export async function listChatContractTemplates(): Promise<ContractTemplateRow[]> {
|
||||
return requestJson('/api/procurement-contract/templates');
|
||||
}
|
||||
|
||||
/** 会话:发起审查 */
|
||||
export async function startChatContractReview(payload: {
|
||||
review_mode: 'compare' | 'solo';
|
||||
contract_asset_no: string;
|
||||
/** 模板比对时必填:用户上传的我方原合同资产编号。 */
|
||||
original_contract_asset_no?: string | null;
|
||||
contract_type?: string | null;
|
||||
supplier_name?: string | null;
|
||||
agent_id?: number | null;
|
||||
}): Promise<ContractReviewRow> {
|
||||
return requestJson('/api/procurement-contract/reviews', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
/** 会话:轮询本人合同审查详情 */
|
||||
export async function getChatContractReview(reviewNo: string): Promise<ContractReviewRow> {
|
||||
return requestJson(`/api/procurement-contract/reviews/${encodeURIComponent(reviewNo)}`);
|
||||
}
|
||||
@@ -10,7 +10,8 @@ import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import {
|
||||
LayoutDashboard, UserPlus, UserCog, Building, Bot, FileText,
|
||||
Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2, AppWindow
|
||||
Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2, AppWindow,
|
||||
ScrollText,
|
||||
} from 'lucide-vue-next';
|
||||
import type { Component } from 'vue';
|
||||
import { config } from '@/config';
|
||||
@@ -36,6 +37,7 @@ const iconMap: Record<AdminModuleId, Component> = {
|
||||
wecom: Link2,
|
||||
permissions: Users,
|
||||
platform_apps: AppWindow,
|
||||
procurement_contract: ScrollText,
|
||||
requests: ShieldCheck,
|
||||
reports: BarChart2,
|
||||
};
|
||||
|
||||
@@ -15,7 +15,7 @@ export interface AdminModuleMeta {
|
||||
|
||||
/** 已独立拆分的模块(全部 admin 模块均已拆分) */
|
||||
export const STANDALONE_ADMIN_MODULES = new Set<AdminModuleId>([
|
||||
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'platform_apps', 'reports',
|
||||
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'platform_apps', 'procurement_contract', 'reports',
|
||||
]);
|
||||
|
||||
export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
|
||||
@@ -31,6 +31,7 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
|
||||
{ id: 'wecom', routeName: 'AdminWecom', path: 'wecom', labelKey: 'admin.nav.wecom', configKey: 'wecom' },
|
||||
{ id: 'permissions', routeName: 'AdminPermissions', path: 'permissions', labelKey: 'admin.nav.permissions', configKey: 'permissions' },
|
||||
{ id: 'platform_apps', routeName: 'AdminPlatformApps', path: 'platform-apps', labelKey: 'admin.nav.platformApps', configKey: 'platform_apps' },
|
||||
{ id: 'procurement_contract', routeName: 'AdminProcurementContract', path: 'procurement-contract', labelKey: 'admin.nav.procurementContract', configKey: 'procurement_contract' },
|
||||
{ id: 'requests', routeName: 'AdminRequests', path: 'requests', labelKey: 'admin.nav.requests', configKey: 'requests' },
|
||||
];
|
||||
|
||||
|
||||
+1073
File diff suppressed because it is too large.
Load diff
+590
@@ -0,0 +1,590 @@
|
||||
/**
|
||||
* features/admin/modules/procurement-contract/components/ContractRiskRulesPanel.vue
|
||||
* 用途:采购合同风险红线规则列表与新增/编辑(含迁移种子默认规则)。
|
||||
* 依赖:procurement-contract.api、DeleteConfirmDialog、useMessage、vue-i18n。
|
||||
* 逻辑:由 ProcurementContractPage「风险规则」Tab 挂载;CRUD 走 Admin rules API。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { CircleHelp, Plus, ShieldAlert, ShieldCheck, SlidersHorizontal } from 'lucide-vue-next';
|
||||
import {
|
||||
createAdminContractRiskRule,
|
||||
deleteAdminContractRiskRule,
|
||||
listAdminContractRiskRules,
|
||||
updateAdminContractRiskRule,
|
||||
type ContractRiskRuleRow,
|
||||
} from '@/features/admin/api/procurement-contract.api';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
const rules = ref<ContractRiskRuleRow[]>([]);
|
||||
const filterStatus = ref('');
|
||||
|
||||
const showForm = ref(false);
|
||||
const editing = ref<ContractRiskRuleRow | null>(null);
|
||||
const formTitle = ref('');
|
||||
const formCategory = ref('');
|
||||
const formKeywords = ref('');
|
||||
const formTriggerType = ref<'keyword_missing' | 'keyword_present'>('keyword_missing');
|
||||
const formRiskLevel = ref<'high' | 'medium' | 'low'>('medium');
|
||||
const formRiskHint = ref('');
|
||||
const formSuggestion = ref('');
|
||||
const formNegotiation = ref('');
|
||||
const formStatus = ref<'enabled' | 'disabled'>('enabled');
|
||||
const formSortOrder = ref(100);
|
||||
|
||||
const clauseCategories = [
|
||||
'payment',
|
||||
'delivery',
|
||||
'acceptance',
|
||||
'warranty',
|
||||
'liability',
|
||||
'jurisdiction',
|
||||
'dispute',
|
||||
'ip',
|
||||
'other',
|
||||
] as const;
|
||||
|
||||
const showDeleteConfirm = ref(false);
|
||||
const pendingDelete = ref<ContractRiskRuleRow | null>(null);
|
||||
const deleting = ref(false);
|
||||
|
||||
const isEditMode = computed(() => Boolean(editing.value));
|
||||
const formTitleText = computed(() =>
|
||||
isEditMode.value
|
||||
? t('admin.procurementContract.ruleEditTitle')
|
||||
: t('admin.procurementContract.ruleCreateTitle'),
|
||||
);
|
||||
|
||||
const isBuiltinRule = computed(() => editing.value?.rule_kind === 'builtin');
|
||||
|
||||
const keywordLogicHint = computed(() =>
|
||||
formTriggerType.value === 'keyword_present'
|
||||
? t('admin.procurementContract.keywordPresentLogicHint')
|
||||
: t('admin.procurementContract.keywordMissingLogicHint'),
|
||||
);
|
||||
const ruleStats = computed(() => ({
|
||||
total: rules.value.length,
|
||||
enabled: rules.value.filter((rule) => rule.status === 'enabled').length,
|
||||
highRisk: rules.value.filter((rule) => rule.risk_level === 'high').length,
|
||||
}));
|
||||
|
||||
/**
|
||||
* 生成风险规则统计卡片,帮助管理员先扫状态再进入列表维护。
|
||||
*/
|
||||
const ruleSummaryCards = computed(() => [
|
||||
{
|
||||
key: 'total',
|
||||
label: t('admin.procurementContract.ruleStatTotal'),
|
||||
value: ruleStats.value.total,
|
||||
icon: SlidersHorizontal,
|
||||
className: 'border-slate-200 bg-white text-slate-600',
|
||||
},
|
||||
{
|
||||
key: 'enabled',
|
||||
label: t('admin.procurementContract.ruleStatEnabled'),
|
||||
value: ruleStats.value.enabled,
|
||||
icon: ShieldCheck,
|
||||
className: 'border-emerald-100 bg-emerald-50/80 text-emerald-700',
|
||||
},
|
||||
{
|
||||
key: 'highRisk',
|
||||
label: t('admin.procurementContract.ruleStatHighRisk'),
|
||||
value: ruleStats.value.highRisk,
|
||||
icon: ShieldAlert,
|
||||
className: 'border-rose-100 bg-rose-50/80 text-rose-700',
|
||||
},
|
||||
]);
|
||||
|
||||
/**
|
||||
* 加载风险规则列表。
|
||||
* @param options.silent - 为 true 时不切换 loading,避免启停时整表闪烁
|
||||
*/
|
||||
async function loadRules(options?: { silent?: boolean }): Promise<void> {
|
||||
const silent = Boolean(options?.silent);
|
||||
if (!silent) loading.value = true;
|
||||
try {
|
||||
rules.value = await listAdminContractRiskRules({
|
||||
status: filterStatus.value || undefined,
|
||||
});
|
||||
} catch (e: unknown) {
|
||||
console.error(e);
|
||||
msg.error(e instanceof Error ? e.message : t('admin.procurementContract.loadFailed'));
|
||||
} finally {
|
||||
if (!silent) loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 响应筛选条件变更并刷新规则列表。
|
||||
*/
|
||||
async function onFilterStatusChange(): Promise<void> {
|
||||
await loadRules();
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadRules();
|
||||
});
|
||||
|
||||
/**
|
||||
* 重置规则表单为新建默认值。
|
||||
*/
|
||||
function resetForm(): void {
|
||||
editing.value = null;
|
||||
formTitle.value = '';
|
||||
formCategory.value = 'payment';
|
||||
formKeywords.value = '';
|
||||
formTriggerType.value = 'keyword_missing';
|
||||
formRiskLevel.value = 'medium';
|
||||
formRiskHint.value = '';
|
||||
formSuggestion.value = '';
|
||||
formNegotiation.value = '';
|
||||
formStatus.value = 'enabled';
|
||||
formSortOrder.value = 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开新建规则弹窗。
|
||||
*/
|
||||
function openCreate(): void {
|
||||
resetForm();
|
||||
showForm.value = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开编辑规则弹窗(种子规则也可改,code 只读)。
|
||||
*/
|
||||
function openEdit(row: ContractRiskRuleRow): void {
|
||||
editing.value = row;
|
||||
formTitle.value = row.title;
|
||||
formCategory.value = row.clause_category;
|
||||
formKeywords.value = (row.keywords || []).join(',');
|
||||
formTriggerType.value = row.trigger_type === 'keyword_present' ? 'keyword_present' : 'keyword_missing';
|
||||
formRiskLevel.value =
|
||||
row.risk_level === 'high' || row.risk_level === 'low' ? row.risk_level : 'medium';
|
||||
formRiskHint.value = row.risk_hint || '';
|
||||
formSuggestion.value = row.suggestion || '';
|
||||
formNegotiation.value = row.negotiation_text || '';
|
||||
formStatus.value = row.status === 'disabled' ? 'disabled' : 'enabled';
|
||||
formSortOrder.value = Number(row.sort_order) || 100;
|
||||
showForm.value = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭规则表单。
|
||||
*/
|
||||
function closeForm(): void {
|
||||
showForm.value = false;
|
||||
editing.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交新建或更新规则。
|
||||
*/
|
||||
async function submitForm(): Promise<void> {
|
||||
if (!formTitle.value.trim() || !formCategory.value.trim()) {
|
||||
msg.error(t('admin.procurementContract.ruleRequiredFields'));
|
||||
return;
|
||||
}
|
||||
if (!formKeywords.value.trim()) {
|
||||
msg.error(t('admin.procurementContract.ruleKeywordsRequired'));
|
||||
return;
|
||||
}
|
||||
if (!formRiskHint.value.trim() || !formSuggestion.value.trim()) {
|
||||
msg.error(t('admin.procurementContract.ruleRequiredFields'));
|
||||
return;
|
||||
}
|
||||
|
||||
saving.value = true;
|
||||
try {
|
||||
// 与后端 _normalize_keywords 一致:逗号/中文逗号分隔
|
||||
const keywords = formKeywords.value
|
||||
.replace(/,/g, ',')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
const payload = {
|
||||
title: formTitle.value.trim(),
|
||||
clause_category: formCategory.value.trim(),
|
||||
// 当前采购合同审核只支持通用采购类型,保留固定值以兼容后端规则加载。
|
||||
contract_type: 'general_procurement',
|
||||
keywords,
|
||||
trigger_type: formTriggerType.value,
|
||||
risk_level: formRiskLevel.value,
|
||||
risk_hint: formRiskHint.value.trim(),
|
||||
suggestion: formSuggestion.value.trim(),
|
||||
negotiation_text: formNegotiation.value.trim() || null,
|
||||
status: formStatus.value,
|
||||
sort_order: Number(formSortOrder.value) || 100,
|
||||
};
|
||||
if (isEditMode.value && editing.value) {
|
||||
await updateAdminContractRiskRule(editing.value.id, payload);
|
||||
msg.success(t('admin.procurementContract.ruleEditOk'));
|
||||
} else {
|
||||
await createAdminContractRiskRule(payload);
|
||||
msg.success(t('admin.procurementContract.ruleCreateOk'));
|
||||
}
|
||||
closeForm();
|
||||
await loadRules({ silent: true });
|
||||
} catch (e: unknown) {
|
||||
msg.error(e instanceof Error ? e.message : t('admin.procurementContract.actionFailed'));
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换规则启停(种子与自定义规则均可)。
|
||||
* 核心逻辑:先乐观更新本地行,成功后再静默对齐服务端;失败则回滚。
|
||||
*/
|
||||
async function toggleStatus(row: ContractRiskRuleRow): Promise<void> {
|
||||
const prev = row.status;
|
||||
const next = prev === 'enabled' ? 'disabled' : 'enabled';
|
||||
row.status = next;
|
||||
try {
|
||||
const updated = await updateAdminContractRiskRule(row.id, { status: next });
|
||||
Object.assign(row, updated);
|
||||
// 当前筛选为「启用/停用」时,状态变更后该项应离开列表
|
||||
if (filterStatus.value && filterStatus.value !== next) {
|
||||
rules.value = rules.value.filter((r) => r.id !== row.id);
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
row.status = prev;
|
||||
msg.error(e instanceof Error ? e.message : t('admin.procurementContract.actionFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开删除确认。
|
||||
*/
|
||||
function openDelete(row: ContractRiskRuleRow): void {
|
||||
pendingDelete.value = row;
|
||||
showDeleteConfirm.value = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭删除确认。
|
||||
*/
|
||||
function closeDelete(): void {
|
||||
showDeleteConfirm.value = false;
|
||||
pendingDelete.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认删除规则。
|
||||
*/
|
||||
async function confirmDelete(): Promise<void> {
|
||||
const row = pendingDelete.value;
|
||||
if (!row) return;
|
||||
deleting.value = true;
|
||||
try {
|
||||
await deleteAdminContractRiskRule(row.id);
|
||||
closeDelete();
|
||||
rules.value = rules.value.filter((r) => r.id !== row.id);
|
||||
} catch (e: unknown) {
|
||||
msg.error(e instanceof Error ? e.message : t('admin.procurementContract.actionFailed'));
|
||||
} finally {
|
||||
deleting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 风险等级文案。
|
||||
*/
|
||||
function riskLabel(level: string): string {
|
||||
if (level === 'high') return t('admin.procurementContract.riskHigh');
|
||||
if (level === 'medium') return t('admin.procurementContract.riskMedium');
|
||||
if (level === 'low') return t('admin.procurementContract.riskLow');
|
||||
return level;
|
||||
}
|
||||
|
||||
/**
|
||||
* 触发类型文案。
|
||||
*/
|
||||
function triggerLabel(type: string): string {
|
||||
if (type === 'keyword_present') return t('admin.procurementContract.triggerPresent');
|
||||
return t('admin.procurementContract.triggerMissing');
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态文案。
|
||||
*/
|
||||
function statusLabel(status: string): string {
|
||||
if (status === 'enabled') return t('admin.procurementContract.enable');
|
||||
if (status === 'disabled') return t('admin.procurementContract.disable');
|
||||
return status;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规则关键词展示文本。
|
||||
* @param row - 风险规则行;关键词为空时返回短横线占位,避免表格空洞。
|
||||
*/
|
||||
function keywordText(row: ContractRiskRuleRow): string {
|
||||
const keywords = row.keywords || [];
|
||||
return keywords.length ? keywords.join(',') : '-';
|
||||
}
|
||||
|
||||
/**
|
||||
* 将内部条款分类编码转换为与规则弹窗一致的可读名称。
|
||||
* 核心逻辑:规则仍保存稳定编码,列表仅负责展示本地化文案。
|
||||
* @param category - 后端返回的条款分类编码。
|
||||
* @returns 用户可读的分类名称;历史未知编码保持原样,避免丢失信息。
|
||||
*/
|
||||
function categoryLabel(category: string): string {
|
||||
const key = `admin.procurementContract.category_${category}`;
|
||||
const translated = t(key);
|
||||
return translated === key ? category : translated;
|
||||
}
|
||||
|
||||
defineExpose({ loadRules, openCreate });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-5">
|
||||
<div class="grid gap-3 md:grid-cols-3">
|
||||
<div
|
||||
v-for="card in ruleSummaryCards"
|
||||
:key="card.key"
|
||||
class="rounded-xl border px-4 py-3 shadow-sm"
|
||||
:class="card.className"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<div class="text-xs font-medium text-muted">{{ card.label }}</div>
|
||||
<div class="mt-1 text-2xl font-semibold text-primary">{{ card.value }}</div>
|
||||
</div>
|
||||
<span class="inline-flex h-9 w-9 items-center justify-center rounded-lg bg-white/80 shadow-sm">
|
||||
<component :is="card.icon" class="h-4 w-4" />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-3 rounded-xl border border-subtle bg-white px-4 py-3 shadow-sm sm:flex-row sm:items-center sm:justify-between">
|
||||
<div class="flex items-center gap-3">
|
||||
<label class="flex shrink-0 items-center gap-2 text-sm font-medium text-secondary">
|
||||
<span>{{ t('admin.procurementContract.colStatus') }}</span>
|
||||
<select
|
||||
v-model="filterStatus"
|
||||
class="input-field h-10 w-48 min-w-48 py-0 text-sm"
|
||||
@change="onFilterStatusChange"
|
||||
>
|
||||
<option value="">{{ t('admin.procurementContract.all') }}</option>
|
||||
<option value="enabled">{{ t('admin.procurementContract.enable') }}</option>
|
||||
<option value="disabled">{{ t('admin.procurementContract.disable') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<button type="button" class="btn-primary inline-flex h-10 items-center gap-2 px-4 shadow-sm" @click="openCreate">
|
||||
<Plus class="h-4 w-4" />
|
||||
{{ t('admin.procurementContract.addRule') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="overflow-hidden rounded-xl border border-subtle bg-white shadow-sm">
|
||||
<div class="overflow-auto">
|
||||
<table class="w-full min-w-[1030px] whitespace-nowrap text-sm">
|
||||
<thead class="bg-slate-50/80 text-xs font-semibold text-muted">
|
||||
<tr>
|
||||
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colRuleTitle') }}</th>
|
||||
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colCategory') }}</th>
|
||||
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colKeywords') }}</th>
|
||||
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colTrigger') }}</th>
|
||||
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colRisk') }}</th>
|
||||
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colStatus') }}</th>
|
||||
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colSort') }}</th>
|
||||
<th class="px-5 py-3 text-left">{{ t('admin.procurementContract.colActions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="loading">
|
||||
<td colspan="8" class="px-4 py-8 text-center text-muted">
|
||||
{{ t('admin.procurementContract.loading') }}
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-else-if="!rules.length">
|
||||
<td colspan="8" class="px-4 py-8 text-center text-muted">
|
||||
{{ t('admin.procurementContract.emptyRules') }}
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-for="row in rules" :key="row.id" class="border-t border-subtle transition-colors hover:bg-slate-50/70">
|
||||
<td class="px-5 py-4 align-top">
|
||||
<div class="font-semibold text-primary">{{ row.title }}</div>
|
||||
</td>
|
||||
<td class="px-5 py-4 align-top">
|
||||
<span class="inline-flex rounded-md border border-slate-200 bg-slate-50 px-2 py-1 text-xs font-medium text-slate-700">
|
||||
{{ categoryLabel(row.clause_category) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="max-w-[260px] px-5 py-4 align-top text-xs text-muted" :title="keywordText(row)">
|
||||
<div class="line-clamp-2 whitespace-normal leading-5">{{ keywordText(row) }}</div>
|
||||
</td>
|
||||
<td class="px-5 py-4 align-top text-secondary">{{ triggerLabel(row.trigger_type) }}</td>
|
||||
<td class="px-5 py-4 align-top">
|
||||
<span
|
||||
class="inline-flex rounded-full px-2.5 py-1 text-xs font-semibold"
|
||||
:class="{
|
||||
'bg-rose-50 text-rose-700': row.risk_level === 'high',
|
||||
'bg-amber-50 text-amber-800': row.risk_level === 'medium',
|
||||
'bg-sky-50 text-sky-700': row.risk_level === 'low',
|
||||
}"
|
||||
>
|
||||
{{ riskLabel(row.risk_level) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-5 py-4 align-top">
|
||||
<span
|
||||
class="inline-flex rounded-full px-2.5 py-1 text-xs font-semibold"
|
||||
:class="row.status === 'enabled' ? 'bg-emerald-50 text-emerald-700' : 'bg-slate-100 text-slate-600'"
|
||||
>
|
||||
{{ statusLabel(row.status) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-5 py-4 align-top font-mono text-xs text-muted">{{ row.sort_order }}</td>
|
||||
<td class="px-5 py-4 align-top">
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-8 items-center rounded-lg border border-[#d8e0ec] bg-white px-3 text-xs font-semibold text-[#2f80d1] transition-colors hover:border-[#2f80d1] hover:bg-[#eaf4ff]"
|
||||
@click="openEdit(row)"
|
||||
>
|
||||
{{ t('admin.edit') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-8 items-center rounded-lg border border-[#d8e0ec] bg-white px-3 text-xs font-semibold text-[#172033] transition-colors hover:border-[#667792] hover:bg-slate-50"
|
||||
@click="toggleStatus(row)"
|
||||
>
|
||||
{{ row.status === 'enabled' ? t('admin.procurementContract.disable') : t('admin.procurementContract.enable') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-8 items-center rounded-lg border border-rose-200 bg-white px-3 text-xs font-semibold text-rose-600 transition-colors hover:border-rose-300 hover:bg-rose-50"
|
||||
@click="openDelete(row)"
|
||||
>
|
||||
{{ t('admin.delete') }}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="showForm"
|
||||
class="admin-modal-overlay animate-fade-in"
|
||||
@click.self="closeForm"
|
||||
>
|
||||
<div class="admin-modal-panel max-w-2xl max-h-[92vh] my-auto scale-100" role="dialog" aria-modal="true">
|
||||
<div class="admin-modal-header flex items-center justify-between gap-3">
|
||||
<h3 class="section-title">{{ formTitleText }}</h3>
|
||||
<button type="button" class="btn-ghost h-9 px-3 text-sm" @click="closeForm">
|
||||
{{ t('admin.close') }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="admin-modal-body min-h-0 !space-y-0 grid grid-cols-1 gap-4 sm:grid-cols-2 items-start">
|
||||
<label class="flex flex-col gap-1.5 text-sm">
|
||||
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colRuleTitle') }}</span>
|
||||
<input v-model="formTitle" type="text" class="input-field w-full" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5 text-sm">
|
||||
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colCategory') }}</span>
|
||||
<select v-model="formCategory" class="input-field w-full" :disabled="isBuiltinRule">
|
||||
<option v-for="category in clauseCategories" :key="category" :value="category">
|
||||
{{ t(`admin.procurementContract.category_${category}`) }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5 text-sm sm:col-span-2">
|
||||
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colKeywords') }}</span>
|
||||
<input
|
||||
v-model="formKeywords"
|
||||
type="text"
|
||||
class="input-field w-full"
|
||||
:disabled="isBuiltinRule"
|
||||
:placeholder="t('admin.procurementContract.ruleKeywordsPlaceholder')"
|
||||
/>
|
||||
<span class="text-xs leading-5 text-muted">{{ keywordLogicHint }}</span>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5 text-sm">
|
||||
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colTrigger') }}</span>
|
||||
<select v-model="formTriggerType" class="input-field w-full" :disabled="isBuiltinRule">
|
||||
<option value="keyword_missing">{{ t('admin.procurementContract.triggerMissing') }}</option>
|
||||
<option value="keyword_present">{{ t('admin.procurementContract.triggerPresent') }}</option>
|
||||
</select>
|
||||
<span v-if="isBuiltinRule" class="text-xs leading-5 text-amber-700">{{ t('admin.procurementContract.builtinRuleLogicHint') }}</span>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5 text-sm">
|
||||
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colRisk') }}</span>
|
||||
<select v-model="formRiskLevel" class="input-field w-full">
|
||||
<option value="high">{{ t('admin.procurementContract.riskHigh') }}</option>
|
||||
<option value="medium">{{ t('admin.procurementContract.riskMedium') }}</option>
|
||||
<option value="low">{{ t('admin.procurementContract.riskLow') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5 text-sm">
|
||||
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colStatus') }}</span>
|
||||
<select v-model="formStatus" class="input-field w-full">
|
||||
<option value="enabled">{{ t('admin.procurementContract.enable') }}</option>
|
||||
<option value="disabled">{{ t('admin.procurementContract.disable') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<div class="flex flex-col gap-1.5 text-sm">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<label for="risk-rule-sort-order" class="font-medium text-secondary">{{ t('admin.procurementContract.colSort') }}</label>
|
||||
<span class="group relative inline-flex">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex text-muted transition-colors hover:text-brand-600 focus:outline-none focus-visible:text-brand-600"
|
||||
:aria-label="t('admin.procurementContract.ruleSortHint')"
|
||||
>
|
||||
<CircleHelp class="h-4 w-4" />
|
||||
</button>
|
||||
<span class="pointer-events-none absolute bottom-full left-1/2 z-10 mb-2 hidden w-60 -translate-x-1/2 rounded-lg border border-subtle bg-white px-3 py-2 text-xs font-normal leading-5 text-secondary shadow-lg group-hover:block group-focus-within:block">
|
||||
{{ t('admin.procurementContract.ruleSortHint') }}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<input id="risk-rule-sort-order" v-model.number="formSortOrder" type="number" class="input-field w-full" min="0" />
|
||||
</div>
|
||||
<label class="flex flex-col gap-1.5 text-sm sm:col-span-2">
|
||||
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colRiskHint') }}</span>
|
||||
<textarea v-model="formRiskHint" rows="2" class="input-field w-full resize-y" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5 text-sm sm:col-span-2">
|
||||
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colSuggestion') }}</span>
|
||||
<textarea v-model="formSuggestion" rows="2" class="input-field w-full resize-y" />
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5 text-sm sm:col-span-2">
|
||||
<span class="font-medium text-secondary">{{ t('admin.procurementContract.colNegotiation') }}</span>
|
||||
<textarea v-model="formNegotiation" rows="2" class="input-field w-full resize-y" />
|
||||
</label>
|
||||
</div>
|
||||
<div class="admin-modal-footer flex justify-end gap-2">
|
||||
<button type="button" class="btn-ghost h-10 px-4" @click="closeForm">
|
||||
{{ t('admin.cancel') }}
|
||||
</button>
|
||||
<button type="button" class="btn-primary h-10 px-4 disabled:opacity-70" :disabled="saving" @click="submitForm">
|
||||
{{ saving ? t('admin.procurementContract.saving') : t('admin.procurementContract.saveChanges') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DeleteConfirmDialog
|
||||
v-model="showDeleteConfirm"
|
||||
:message="t('admin.procurementContract.confirmDeleteRule', { title: pendingDelete?.title || '' })"
|
||||
:confirm-loading="deleting"
|
||||
@confirm="confirmDelete"
|
||||
@cancel="closeDelete"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -17,6 +17,7 @@ export type AdminModuleId =
|
||||
| 'permissions'
|
||||
| 'requests'
|
||||
| 'platform_apps'
|
||||
| 'procurement_contract'
|
||||
| 'reports';
|
||||
|
||||
export type AdminReportTableId =
|
||||
|
||||
@@ -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>
|
||||
@@ -6,6 +6,7 @@ import { computed, ref, type ComputedRef, type Ref } from 'vue';
|
||||
import { uploadChatFile } from '../api/chat.api';
|
||||
import type { PendingAttachment } from '../types/shipping.types';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
import { isProcurementContractAgent as resolveProcurementContractAgent } from '@/shared/utils/agent-registry.utils';
|
||||
|
||||
type ChatUploadFileType = 'image' | 'document' | 'audio' | 'video' | 'custom';
|
||||
|
||||
@@ -23,6 +24,8 @@ const DIFY_SUPPORTED_EXTS: Record<Exclude<ChatUploadFileType, 'custom'>, Set<str
|
||||
video: new Set(['mp4', 'mov', 'mpeg', 'webm']),
|
||||
};
|
||||
|
||||
const PROCUREMENT_CONTRACT_EXTS = new Set(['pdf', 'doc', 'docx', 'txt', 'md', 'markdown']);
|
||||
|
||||
const extractExt = (value: string) => {
|
||||
const text = (value || '').trim().toLowerCase();
|
||||
const withoutQuery = (text.split('?')[0] || '').split('#')[0] || '';
|
||||
@@ -76,9 +79,11 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
return (currentAgent.value?.dify_parameters?.system_parameters as any) || {};
|
||||
});
|
||||
|
||||
const isProcurementContractAgent = computed(() => resolveProcurementContractAgent(currentAgent.value));
|
||||
|
||||
const attachmentPolicy = computed(() => {
|
||||
const fileUploadAllowed = currentAgent.value?.capabilities?.file_upload;
|
||||
if (fileUploadAllowed === false) {
|
||||
if (fileUploadAllowed === false && !isProcurementContractAgent.value) {
|
||||
return {
|
||||
anyEnabled: false,
|
||||
enabled: {
|
||||
@@ -172,6 +177,10 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
}
|
||||
}
|
||||
|
||||
if (isProcurementContractAgent.value) {
|
||||
enabled.document = { local: true, remote: false, limit: 1 };
|
||||
}
|
||||
|
||||
const mergedLimits = {
|
||||
...(difySystemParameters.value || {}),
|
||||
...(raw?.fileUploadConfig || {}),
|
||||
@@ -189,6 +198,7 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
const canLocal = Object.values(enabled).some((v) => v.local);
|
||||
const canRemote = Object.values(enabled).some((v) => v.remote);
|
||||
const totalLimit = (() => {
|
||||
if (isProcurementContractAgent.value) return 1;
|
||||
const v1 = raw?.fileUploadConfig?.file_upload_limit;
|
||||
if (Number.isFinite(Number(v1))) return Number(v1);
|
||||
const v2 = raw?.number_limits;
|
||||
@@ -197,6 +207,7 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
})();
|
||||
|
||||
const effectiveAllowedExts: Set<string> | null = (() => {
|
||||
if (isProcurementContractAgent.value) return new Set(PROCUREMENT_CONTRACT_EXTS);
|
||||
if (!allowedExts) return null;
|
||||
const filtered = new Set<string>();
|
||||
for (const ext of allowedExts) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/composables/useChatPage.ts
|
||||
* 对话页主编排:组合 SSE、Agent、附件、请假/出货、路由同步与 page/* 子模块。
|
||||
* 对话页主编排:组合 SSE、Agent、附件、请假/出货/采购合同、路由同步与 page/* 子模块。
|
||||
*/
|
||||
import { computed, markRaw, nextTick, ref, watch } from 'vue';
|
||||
import { storeToRefs } from 'pinia';
|
||||
@@ -24,6 +24,7 @@ import { useChatRouteSync } from './useChatRouteSync';
|
||||
import { useChatScroll } from './useChatScroll';
|
||||
import { useChatSessions } from './useChatSessions';
|
||||
import { useChatShipping } from './useChatShipping';
|
||||
import { useProcurementContractChat } from './useProcurementContractChat';
|
||||
import { useChatSourceFiles } from './useChatSourceFiles';
|
||||
import { useChatAssetHistory } from './useChatAssetHistory';
|
||||
import { useChatAssetImage } from './useChatAssetImage';
|
||||
@@ -239,6 +240,8 @@ export function useChatPage() {
|
||||
const { newLocalMessageId, saveLocalMessageToBackend } = createChatPageLocalMessageApi({
|
||||
conversationId,
|
||||
currentAgentId,
|
||||
route,
|
||||
router,
|
||||
});
|
||||
|
||||
const pushLocalAssistantMessage = async (content: string) => {
|
||||
@@ -304,6 +307,27 @@ export function useChatPage() {
|
||||
});
|
||||
resetShippingConversationState = shipping.resetShippingConversationState;
|
||||
|
||||
const procurement = useProcurementContractChat({
|
||||
currentAgent: agent.currentAgent,
|
||||
currentAgentId,
|
||||
attachments: attachmentApi.attachments,
|
||||
messages,
|
||||
isThinking,
|
||||
isUploadingAttachments: attachmentApi.isUploadingAttachments,
|
||||
input,
|
||||
clearAttachments: attachmentApi.clearAttachments,
|
||||
saveLocalMessageToBackend,
|
||||
loadHistory,
|
||||
msg,
|
||||
t,
|
||||
});
|
||||
|
||||
const allowsSendWithAttachmentsOnly = computed(
|
||||
() =>
|
||||
shipping.allowsSendWithAttachmentsOnly.value
|
||||
|| procurement.allowsSendWithAttachmentsOnly.value,
|
||||
);
|
||||
|
||||
/**
|
||||
* Drawer「重试所有失败」点击:仅打开确认弹窗,不立刻发请求。
|
||||
*/
|
||||
@@ -413,7 +437,7 @@ export function useChatPage() {
|
||||
isUploadingAttachments: attachmentApi.isUploadingAttachments,
|
||||
attachmentPolicy: attachmentApi.attachmentPolicy,
|
||||
attachments: attachmentApi.attachments,
|
||||
allowsSendWithAttachmentsOnly: shipping.allowsSendWithAttachmentsOnly,
|
||||
allowsSendWithAttachmentsOnly,
|
||||
buildFileSpecsForSend: attachmentApi.buildFileSpecsForSend,
|
||||
clearAttachments: attachmentApi.clearAttachments,
|
||||
sendMessage,
|
||||
@@ -445,6 +469,7 @@ export function useChatPage() {
|
||||
tryHandleShippingAttachmentAutoFlow: shipping.tryHandleShippingAttachmentAutoFlow,
|
||||
tryHandleLeaveSend: leave.tryHandleLeaveSend,
|
||||
tryHandleShippingSend: shipping.tryHandleShippingSend,
|
||||
tryHandleProcurementContractSend: procurement.tryHandleProcurementContractSend,
|
||||
refreshToolRunProgressAfterSend: toolRun.refreshToolRunProgressAfterSend,
|
||||
prepareToolRunProgressBeforeSend: toolRun.prepareToolRunProgressBeforeSend,
|
||||
msg,
|
||||
@@ -607,6 +632,11 @@ export function useChatPage() {
|
||||
clearShippingToast: dialogs.clearShippingToast,
|
||||
showChatRating,
|
||||
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
|
||||
isProcurementContractAgent: procurement.isProcurementContractAgent,
|
||||
procurementReviewMode: procurement.reviewMode,
|
||||
procurementOriginalContractName: procurement.originalContractName,
|
||||
handleProcurementOriginalContractSelected: procurement.handleOriginalContractSelected,
|
||||
clearProcurementOriginalContract: procurement.clearOriginalContract,
|
||||
showShippingProgressWorkspace: shipping.showShippingProgressWorkspace,
|
||||
shippingBatchSummary: shipping.shippingBatchSummary,
|
||||
shippingConversationWorkspace: shipping.shippingConversationWorkspace,
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
/**
|
||||
* 对话页:本地消息落库(请假/出货等不经过 SSE 的消息)。
|
||||
* features/chat/page/useChatPageLocalMessage.ts
|
||||
* 用途:对话页本地消息落库(请假/出货/合同审查等不经 SSE 的消息)。
|
||||
* 依赖:chat.api.saveLocalChatMessage、vue Router。
|
||||
* 逻辑:落库后回写 conversationId / chat_log_id,并同步 URL 的 conversation_id 以便刷新可恢复。
|
||||
*/
|
||||
import type { RouteLocationNormalizedLoaded, Router } from 'vue-router';
|
||||
import { saveLocalChatMessage } from '../api/chat.api';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
@@ -8,16 +12,31 @@ import type { ComputedRef, Ref } from 'vue';
|
||||
export interface ChatPageLocalMessageContext {
|
||||
conversationId: Ref<string | null>;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
route?: RouteLocationNormalizedLoaded;
|
||||
router?: Router;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建本地消息落库 API。
|
||||
* @param ctx - 会话 ID、当前 Agent,以及可选的 route/router 用于同步 URL
|
||||
*/
|
||||
export function createChatPageLocalMessageApi(ctx: ChatPageLocalMessageContext) {
|
||||
let localMessageCounter = 0;
|
||||
|
||||
/**
|
||||
* 生成前端本地消息 ID 前缀。
|
||||
* @param prefix - ID 前缀
|
||||
*/
|
||||
const newLocalMessageId = (prefix: string) => {
|
||||
localMessageCounter += 1;
|
||||
return `${prefix}-${Date.now()}-${localMessageCounter}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* 将本地消息写入后端,并在首次落库时把 conversation_id 写入路由 query。
|
||||
* @param localMsg - 待保存消息
|
||||
* @param userQuery - 用户提问(结构化助手消息回放用)
|
||||
*/
|
||||
const saveLocalMessageToBackend = async (localMsg: ChatMessage, userQuery: string = '') => {
|
||||
try {
|
||||
const data = await saveLocalChatMessage({
|
||||
@@ -29,12 +48,25 @@ export function createChatPageLocalMessageApi(ctx: ChatPageLocalMessageContext)
|
||||
query: userQuery,
|
||||
agent_id: ctx.currentAgentId.value,
|
||||
});
|
||||
if (!ctx.conversationId.value && data.conversation_id) {
|
||||
ctx.conversationId.value = data.conversation_id;
|
||||
const cid = data.conversation_id ? String(data.conversation_id) : '';
|
||||
if (cid && !ctx.conversationId.value) {
|
||||
ctx.conversationId.value = cid;
|
||||
}
|
||||
if (data.chat_log_id) {
|
||||
localMsg.chat_log_id = data.chat_log_id;
|
||||
}
|
||||
// [STEP] 同步 URL,刷新后可按 conversation_id 拉回用户提问 + 结果卡
|
||||
if (cid && ctx.route && ctx.router) {
|
||||
const current = typeof ctx.route.query.conversation_id === 'string'
|
||||
? ctx.route.query.conversation_id
|
||||
: '';
|
||||
if (current !== cid) {
|
||||
await ctx.router.replace({
|
||||
path: ctx.route.path,
|
||||
query: { ...ctx.route.query, conversation_id: cid },
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to save local message', e);
|
||||
}
|
||||
|
||||
@@ -342,6 +342,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
if (msgItem?.role === 'user') return true;
|
||||
if (msgItem?.type === 'shipping-parse-review') return false;
|
||||
if (msgItem?.type === 'leave-form' || msgItem?.type === 'leave-confirmation' || msgItem?.type === 'leave-result') return true;
|
||||
if (msgItem?.type === 'procurement-contract-review') return true;
|
||||
const content = (msgItem?.content || '').trim();
|
||||
if (content) return true;
|
||||
if (ctx.getMessageLinks(msgItem as unknown as Record<string, unknown>).length > 0) return true;
|
||||
@@ -361,7 +362,9 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
|| msgItem?.type === 'leave-result'
|
||||
|| msgItem?.type === 'shipping-inventory-mapping'
|
||||
|| msgItem?.type === 'shipping-parse-review'
|
||||
|| msgItem?.type === 'shipping-match-result') {
|
||||
|| msgItem?.type === 'shipping-match-result'
|
||||
|| msgItem?.type === 'maintenance-device-result'
|
||||
|| msgItem?.type === 'procurement-contract-review') {
|
||||
return true;
|
||||
}
|
||||
return Boolean(String(msgItem?.content || '').trim());
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* 对话页:发送消息编排(出货/请假前置拦截 → Dify SSE)、复制与重新生成。
|
||||
* 对话页:发送消息编排(出货/请假/采购合同前置拦截 → Dify SSE)、复制与重新生成。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
@@ -64,6 +64,11 @@ export interface ChatPageSendContext {
|
||||
content: string,
|
||||
trimmed: string,
|
||||
) => Promise<boolean>;
|
||||
tryHandleProcurementContractSend: (
|
||||
textOrEvent: string | Event | undefined,
|
||||
content: string,
|
||||
trimmed: string,
|
||||
) => Promise<boolean>;
|
||||
refreshToolRunProgressAfterSend: () => Promise<void>;
|
||||
prepareToolRunProgressBeforeSend: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void; info: (text: string) => void };
|
||||
@@ -89,6 +94,9 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
|
||||
if (await ctx.tryHandleShippingAttachmentAutoFlow(textOrEvent, content, trimmed)) {
|
||||
return;
|
||||
}
|
||||
if (await ctx.tryHandleProcurementContractSend(textOrEvent, content, trimmed)) {
|
||||
return;
|
||||
}
|
||||
if (!trimmed || ctx.isUploadingAttachments.value || (ctx.isThinking.value && !allowSendWhileThinking)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ export interface RetrieverResource {
|
||||
export interface ChatMessage {
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
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;
|
||||
|
||||
Reference in new issue
Block a user