Merge branch 'dev' into hugo-shipping-notice

This commit is contained in:
hugo committed 2026-08-11 14:33:56 +08:00
commit 472b530be3
397 files changed
+46450 -34171

No files matched your search

@@ -21,6 +21,24 @@ import type {
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
export type LinkedServicePayload = {
name: string;
url: string;
description?: string;
icon?: string;
sort_order?: number;
enabled?: boolean;
is_enabled?: boolean;
};
export const listLinkedServices = () => requestJson<any[]>('/api/admin/linked-services', auth());
export const createLinkedService = (payload: LinkedServicePayload) =>
requestJson<any>('/api/admin/linked-services', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
export const updateLinkedService = (id: number, payload: LinkedServicePayload) =>
requestJson<any>(`/api/admin/linked-services/${id}`, { method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) });
export const deleteLinkedService = (id: number) =>
requestJson<void>(`/api/admin/linked-services/${id}`, { method: 'DELETE', ...auth() });
export type ShippingInventoryReadinessCheck = {
code: string;
status: 'passed' | 'pending' | 'failed' | 'stale' | 'empty';
@@ -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)}`);
}
@@ -1,9 +1,8 @@
/**
* features/admin/components/AdminNav.vue
* 管理后台左侧导航,在模块原始顺序中渲染货代手风琴、企微和报表二级菜单。
* 管理后台左侧导航,使用子路由跳转。
* 依赖:admin-nav.store、modules 常量、vue-router。
* 逻辑:报表/企微子菜单默认折叠;当前路由落在对应模块时自动展开;
* lg 起固定宽度侧栏,小屏横向滚动导航以免挤占主内容。
* 逻辑:报表/企微子菜单默认折叠;当前路由落在对应模块时自动展开以便看到激活项。
*/
<script setup lang="ts">
import { computed, watch } from 'vue';
@@ -11,14 +10,13 @@ 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, Warehouse,
ChevronDown, ChevronRight
Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2, AppWindow,
ScrollText, ExternalLink,
} from 'lucide-vue-next';
import type { Component } from 'vue';
import { config } from '@/config';
import { ADMIN_MODULE_METAS, ADMIN_REPORT_TABLES, SHIPPING_CONFIG_SUB_MODULE_METAS } from '../constants/modules';
import { ADMIN_MODULE_METAS, ADMIN_REPORT_TABLES } from '../constants/modules';
import { useAdminNavStore } from '../stores/admin-nav.store';
import type { ShippingManagementGroupKey } from '../stores/admin-nav.store';
import type { AdminModuleId } from '../types/admin.types';
const { t } = useI18n();
@@ -37,9 +35,10 @@ const iconMap: Record<AdminModuleId, Component> = {
announcements: Megaphone,
questions: MessageCircleQuestion,
wecom: Link2,
linked_services: ExternalLink,
permissions: Users,
platform_apps: AppWindow,
shipping_inventory: Warehouse,
procurement_contract: ScrollText,
requests: ShieldCheck,
reports: BarChart2,
};
@@ -48,13 +47,15 @@ const visibleModules = computed(() =>
ADMIN_MODULE_METAS.filter((item) => config.admin.modules[item.configKey] !== false),
);
const standardModules = computed(() =>
visibleModules.value.filter((item) => item.id !== 'wecom'),
);
const isModuleActive = (moduleId: AdminModuleId): boolean =>
route.meta.adminModule === moduleId;
const isReportsActive = computed(() => route.meta.adminModule === 'reports');
const isWecomActive = computed(() => route.meta.adminModule === 'wecom');
const isShippingManagementActive = computed(() => route.meta.adminModule === 'shipping_inventory');
const shippingNavGroups = [...new Set(SHIPPING_CONFIG_SUB_MODULE_METAS.map((item) => item.groupKey))];
const wecomSubRoutes = [
{ name: 'AdminWecomSettings', labelKey: 'admin.wecom.nav.settings' },
@@ -66,26 +67,6 @@ const navigateWecom = (routeName: string): void => {
router.push({ name: routeName });
};
/** 判断货代二级菜单当前项;综合工作台按 section 深链高亮,库存字段目录归入库存解析。 */
const isShippingNavActive = (item: typeof SHIPPING_CONFIG_SUB_MODULE_METAS[number]): boolean => {
if (route.name !== item.routeName) return false;
if (!item.query) return true;
const section = typeof route.query.section === 'string' ? route.query.section : 'parsing';
if (item.query.section === 'parsing') return section === 'parsing' || section === 'inventoryFields';
return section === item.query.section;
};
/** 打开货代独立页面或综合工作台区段,保留可收藏的 section 深链。 */
const navigateShipping = (item: typeof SHIPPING_CONFIG_SUB_MODULE_METAS[number]): void => {
router.push({ name: item.routeName, query: item.query });
};
/** 返回当前货代页面所在分组,用于路由进入时只展开对应手风琴。 */
const currentShippingGroup = (): ShippingManagementGroupKey | null => {
const currentItem = SHIPPING_CONFIG_SUB_MODULE_METAS.find(isShippingNavActive);
return currentItem?.groupKey ?? null;
};
const getReportTableLabel = (table: string): string => {
const i18nKey = `admin.report.tables.${table}`;
const translated = t(i18nKey);
@@ -102,7 +83,7 @@ const navigateReport = (table: string): void => {
};
/**
* 进入报表、企微或货代模块时自动展开子菜单,避免当前页在折叠状态下不可见。
* 进入报表/企微模块时自动展开子菜单,避免当前页在折叠状态下不可见。
*/
watch(
isReportsActive,
@@ -119,132 +100,69 @@ watch(
},
{ immediate: true },
);
watch(
isShippingManagementActive,
(active) => {
if (!active) return;
navStore.shippingManagementExpanded = true;
navStore.shippingManagementGroup = currentShippingGroup();
},
{ immediate: true },
);
watch(
() => [route.name, route.query.section],
() => {
if (isShippingManagementActive.value) navStore.shippingManagementGroup = currentShippingGroup();
},
);
</script>
<template>
<aside
class="surface-panel rounded-2xl shadow-sm h-fit w-full lg:sticky lg:top-24 overflow-hidden shrink-0 z-10 transition-all duration-300"
:class="navStore.sidebarCollapsed ? 'max-h-14 lg:max-h-none lg:w-20' : 'lg:w-64'"
class="surface-panel rounded-2xl shadow-sm h-fit md:sticky md:top-24 overflow-hidden shrink-0 z-10 transition-all duration-300"
:class="navStore.sidebarCollapsed ? 'w-0 md:w-20' : 'w-full md:w-64'"
>
<nav class="flex lg:flex-col p-3 gap-1 overflow-x-auto lg:overflow-visible no-scrollbar">
<template v-for="item in visibleModules" :key="item.id">
<div v-if="item.id === 'shipping_inventory'" class="flex flex-col flex-shrink-0">
<button
type="button"
class="admin-nav-btn group justify-between"
:class="{ 'admin-nav-btn--active': isShippingManagementActive }"
:title="navStore.sidebarCollapsed ? t(item.labelKey) : ''"
@click="navStore.shippingManagementExpanded = !navStore.shippingManagementExpanded"
>
<div class="flex items-center gap-3">
<Warehouse class="w-5 h-5 flex-shrink-0" :class="isShippingManagementActive ? 'text-brand-600' : 'text-muted'" />
<span :class="navStore.sidebarCollapsed ? 'lg:hidden' : ''">{{ t(item.labelKey) }}</span>
</div>
</button>
<div
v-if="navStore.shippingManagementExpanded && !navStore.sidebarCollapsed"
class="mt-1 ml-6 space-y-1 border-l-2 border-subtle pl-3 pb-1"
>
<section v-for="groupKey in shippingNavGroups" :key="groupKey" class="shipping-nav-group">
<button
type="button"
class="flex w-full items-center justify-between rounded-lg px-3 py-2 text-left text-xs font-semibold text-secondary transition-colors hover:bg-surface-soft"
:aria-expanded="navStore.shippingManagementGroup === groupKey"
@click="navStore.toggleShippingManagementGroup(groupKey)"
>
<span>{{ t(groupKey) }}</span>
<ChevronDown v-if="navStore.shippingManagementGroup === groupKey" class="h-3.5 w-3.5 text-muted" />
<ChevronRight v-else class="h-3.5 w-3.5 text-muted" />
</button>
<div v-if="navStore.shippingManagementGroup === groupKey" class="ml-2 border-l border-subtle pl-2 py-1 space-y-0.5">
<button
v-for="sub in SHIPPING_CONFIG_SUB_MODULE_METAS.filter((entry) => entry.groupKey === groupKey)"
:key="sub.id"
type="button"
class="admin-nav-subitem w-[8em] whitespace-nowrap py-1.5 pl-3"
:class="{ 'admin-nav-subitem--active': isShippingNavActive(sub) }"
@click="navigateShipping(sub)"
>
{{ t(sub.labelKey) }}
</button>
</div>
</section>
</div>
</div>
<div v-else-if="item.id === 'wecom'" class="flex flex-col flex-shrink-0">
<button
type="button"
class="admin-nav-btn group justify-between"
:class="{ 'admin-nav-btn--active': isWecomActive }"
@click="navStore.wecomExpanded = !navStore.wecomExpanded"
>
<div class="flex items-center gap-3">
<Link2 class="w-5 h-5 flex-shrink-0" :class="isWecomActive ? 'text-brand-600' : 'text-muted'" />
<span :class="navStore.sidebarCollapsed ? 'lg:hidden' : ''">{{ t(item.labelKey) }}</span>
</div>
</button>
<div
v-if="navStore.wecomExpanded && !navStore.sidebarCollapsed"
class="pl-4 space-y-1 mt-1 border-l-2 border-subtle ml-6"
>
<button
v-for="sub in wecomSubRoutes"
:key="sub.name"
type="button"
class="admin-nav-subitem"
:class="{ 'admin-nav-subitem--active': route.name === sub.name }"
@click="navigateWecom(sub.name)"
>
{{ t(sub.labelKey) }}
</button>
</div>
</div>
<button
v-else
type="button"
class="admin-nav-btn group"
:class="{ 'admin-nav-btn--active': isModuleActive(item.id) }"
:title="navStore.sidebarCollapsed ? t(item.labelKey) : ''"
@click="navigateModule(item.routeName)"
<nav class="flex md:flex-col p-3 gap-1 overflow-x-auto md:overflow-visible no-scrollbar">
<button
v-for="item in standardModules"
:key="item.id"
type="button"
class="admin-nav-btn group"
:class="{ 'admin-nav-btn--active': isModuleActive(item.id) }"
:title="navStore.sidebarCollapsed ? t(item.labelKey) : ''"
@click="navigateModule(item.routeName)"
>
<component
:is="iconMap[item.id]"
class="w-5 h-5 transition-transform group-hover:scale-110 flex-shrink-0"
:class="isModuleActive(item.id) ? 'text-brand-600' : 'text-muted group-hover:text-secondary'"
/>
<span :class="navStore.sidebarCollapsed ? 'md:hidden' : ''">{{ t(item.labelKey) }}</span>
<span
v-if="navStore.badgeForModule(item.id) && !navStore.sidebarCollapsed"
class="ml-auto bg-red-500 text-white text-[10px] font-bold px-2 py-0.5 rounded-full shadow-sm"
>
<component
:is="iconMap[item.id]"
class="w-5 h-5 transition-transform group-hover:scale-110 flex-shrink-0"
:class="isModuleActive(item.id) ? 'text-brand-600' : 'text-muted group-hover:text-secondary'"
/>
<span :class="navStore.sidebarCollapsed ? 'lg:hidden' : ''">{{ t(item.labelKey) }}</span>
<span
v-if="navStore.badgeForModule(item.id) && !navStore.sidebarCollapsed"
class="ml-auto bg-red-500 text-white text-[10px] font-bold px-2 py-0.5 rounded-full shadow-sm"
>
{{ navStore.badgeForModule(item.id) }}
</span>
<div
v-if="isModuleActive(item.id)"
class="absolute left-0 top-1/2 -translate-y-1/2 w-1 h-6 bg-brand-600 rounded-r-full"
/>
{{ navStore.badgeForModule(item.id) }}
</span>
<div
v-if="isModuleActive(item.id)"
class="absolute left-0 top-1/2 -translate-y-1/2 w-1 h-6 bg-brand-600 rounded-r-full"
/>
</button>
<div v-if="config.admin.modules.wecom !== false" class="flex flex-col flex-shrink-0">
<button
type="button"
class="admin-nav-btn group justify-between"
:class="{ 'admin-nav-btn--active': isWecomActive }"
@click="navStore.wecomExpanded = !navStore.wecomExpanded"
>
<div class="flex items-center gap-3">
<Link2 class="w-5 h-5 flex-shrink-0" :class="isWecomActive ? 'text-brand-600' : 'text-muted'" />
<span :class="navStore.sidebarCollapsed ? 'md:hidden' : ''">{{ t('admin.nav.wecom') }}</span>
</div>
</button>
</template>
<div
v-if="navStore.wecomExpanded && !navStore.sidebarCollapsed"
class="pl-4 space-y-1 mt-1 border-l-2 border-subtle ml-6"
>
<button
v-for="sub in wecomSubRoutes"
:key="sub.name"
type="button"
class="admin-nav-subitem"
:class="{ 'admin-nav-subitem--active': route.name === sub.name }"
@click="navigateWecom(sub.name)"
>
{{ t(sub.labelKey) }}
</button>
</div>
</div>
<div v-if="config.admin.modules.reports !== false" class="flex flex-col flex-shrink-0">
<button
@@ -255,7 +173,7 @@ watch(
>
<div class="flex items-center gap-3">
<BarChart2 class="w-5 h-5 flex-shrink-0" :class="isReportsActive ? 'text-brand-600' : 'text-muted'" />
<span :class="navStore.sidebarCollapsed ? 'lg:hidden' : ''">{{ t('admin.nav.reports') }}</span>
<span :class="navStore.sidebarCollapsed ? 'md:hidden' : ''">{{ t('admin.nav.reports') }}</span>
</div>
</button>
<div
@@ -3,7 +3,7 @@
* 管理后台模块元数据,AdminNav 与子路由共用。
*/
import type { AdminModuleId, AdminReportTableId, ShippingConfigSubModuleId } from '../types/admin.types';
import type { AdminModuleId, AdminReportTableId } from '../types/admin.types';
export interface AdminModuleMeta {
id: AdminModuleId;
@@ -13,36 +13,9 @@ export interface AdminModuleMeta {
configKey: keyof typeof import('@/config').config.admin.modules;
}
export interface ShippingConfigSubModuleMeta {
id: ShippingConfigSubModuleId;
routeName:
| 'AdminShippingInventory'
| 'AdminShippingFieldAssets'
| 'AdminShippingOrderSchema'
| 'AdminShippingIdentityRules'
| 'AdminShippingOrderExtractionRuns'
| 'AdminShippingAudit'
| 'AdminShippingProcessGates'
| 'AdminShippingLegacyStpJobs'
| 'AdminShippingOrderDocumentProfiles';
path:
| 'shipping-notice'
| 'shipping-field-assets'
| 'shipping-order-schema'
| 'shipping-identity-rules'
| 'shipping-order-extraction-runs'
| 'shipping-audit'
| 'shipping-process-gates'
| 'shipping-legacy-stp-jobs'
| 'shipping-order-document-profiles';
labelKey: string;
groupKey: 'admin.nav.shippingOrderRecognition' | 'admin.nav.shippingInventoryManagement' | 'admin.nav.shippingRunAudit';
query?: { section: 'parsing' | 'profiles' | 'sources' | 'mappings' | 'rules' | 'templates' | 'snapshots' | 'exports' };
}
/** 已独立拆分的模块(全部 admin 模块均已拆分) */
export const STANDALONE_ADMIN_MODULES = new Set<AdminModuleId>([
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'platform_apps', 'shipping_inventory', 'reports',
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'linked_services', 'platform_apps', 'procurement_contract', 'reports',
]);
export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
@@ -53,34 +26,16 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
{ id: 'agents', routeName: 'AdminAgents', path: 'agents', labelKey: 'admin.nav.agents', configKey: 'agents' },
{ id: 'knowledge_base', routeName: 'AdminKnowledgeBase', path: 'knowledge-base', labelKey: 'admin.nav.knowledgeBase', configKey: 'knowledge_base' },
{ id: 'schedules', routeName: 'AdminSchedules', path: 'schedules', labelKey: 'admin.nav.schedules', configKey: 'schedules' },
{ id: 'shipping_inventory', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.nav.shippingConfig', configKey: 'shipping_inventory' },
{ id: 'announcements', routeName: 'AdminAnnouncements', path: 'announcements', labelKey: 'admin.nav.announcements', configKey: 'announcements' },
{ id: 'questions', routeName: 'AdminQuestions', path: 'questions', labelKey: 'admin.nav.questions', configKey: 'questions' },
{ id: 'wecom', routeName: 'AdminWecom', path: 'wecom', labelKey: 'admin.nav.wecom', configKey: 'wecom' },
{ id: 'linked_services', routeName: 'AdminLinkedServices', path: 'linked-services', labelKey: 'admin.nav.linkedServices', configKey: 'linked_services' },
{ 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' },
];
/** 货代管理的业务导航唯一真相源;按基础定义、适配规则、运行任务的依赖顺序排列。 */
export const SHIPPING_CONFIG_SUB_MODULE_METAS: ShippingConfigSubModuleMeta[] = [
{ id: 'field_assets', routeName: 'AdminShippingFieldAssets', path: 'shipping-field-assets', labelKey: 'admin.nav.shippingFieldAssets', groupKey: 'admin.nav.shippingOrderRecognition' },
{ id: 'order_schema', routeName: 'AdminShippingOrderSchema', path: 'shipping-order-schema', labelKey: 'admin.nav.shippingOrderSchema', groupKey: 'admin.nav.shippingOrderRecognition' },
{ id: 'order_document_profiles', routeName: 'AdminShippingOrderDocumentProfiles', path: 'shipping-order-document-profiles', labelKey: 'admin.nav.shippingOrderDocumentProfiles', groupKey: 'admin.nav.shippingOrderRecognition' },
{ id: 'identity_rules', routeName: 'AdminShippingIdentityRules', path: 'shipping-identity-rules', labelKey: 'admin.nav.shippingIdentityRules', groupKey: 'admin.nav.shippingOrderRecognition' },
{ id: 'order_extraction_runs', routeName: 'AdminShippingOrderExtractionRuns', path: 'shipping-order-extraction-runs', labelKey: 'admin.nav.shippingOrderExtractionRuns', groupKey: 'admin.nav.shippingOrderRecognition' },
{ id: 'inventory_fields', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.parsingProfiles', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'parsing' } },
{ id: 'connections', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.connections', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'profiles' } },
{ id: 'inventory_sites', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.sources', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'sources' } },
{ id: 'warehouse_mappings', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.externalMappings', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'mappings' } },
{ id: 'routing_rules', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.rules', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'rules' } },
{ id: 'shipping_templates', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.excelTemplates', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'templates' } },
{ id: 'shipping_audit', routeName: 'AdminShippingAudit', path: 'shipping-audit', labelKey: 'admin.nav.shippingAudit', groupKey: 'admin.nav.shippingRunAudit' },
{ id: 'process_gates', routeName: 'AdminShippingProcessGates', path: 'shipping-process-gates', labelKey: 'admin.nav.shippingProcessGates', groupKey: 'admin.nav.shippingRunAudit' },
{ id: 'inventory_snapshots', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.snapshots', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'snapshots' } },
{ id: 'export_records', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.exports', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'exports' } },
];
export const ADMIN_REPORT_TABLES: AdminReportTableId[] = [
'usage_analysis',
'chat_logs',
@@ -1,9 +1,9 @@
/**
* features/admin/modules/agents/components/AgentFormModal.vue
*
* 用途:应用管理新增/编辑弹窗,集中承载 Agent 基础信息、Dify/Iframe 配置和常见问题表单。
* 用途:应用管理新增/编辑弹窗,集中承载 Agent 基础信息(含启用状态)、Dify/Iframe 配置和常见问题表单。
* 依赖:agent.types AgentFormState、schedule.types ScheduleTask、AgentToolRunProgressConfig、vue-i18n。
* 逻辑:父组件控制 visible/isEditing/isSaving 与保存;本组件直接编辑传入的 form,并通过事件通知关闭、保存、增删常见问题。
* 逻辑:父组件控制 visible/isEditing/isSaving 与保存;本组件直接编辑传入的 form(含 is_active),并通过事件通知关闭、保存、增删常见问题。
*/
<script setup lang="ts">
@@ -15,8 +15,7 @@ import type { ScheduleTask } from '@/shared/types/schedule.types';
import type { AgentTypeCatalogEntry, IntentRouteOption } from '../composables/useAgentsAdminRegistry';
import type { AdminContentProfileOption } from '@/features/admin/api/admin.api';
import {
DEFAULT_TRAINING_EMPLOYEE_CHAT_QUESTIONS,
DEFAULT_TRAINING_HR_CHAT_QUESTIONS,
getDefaultTrainingChatQuestions,
} from '@/features/chat/training/trainingChatQuestions';
import {
applyCatalogDefaultsToForm,
@@ -188,10 +187,10 @@ const handleTrainingWorkspaceToggle = () => {
if (props.form.training_workspace_enabled) {
props.form.content_profile = 'training';
if (!props.form.training_employee_chat_questions_text.trim()) {
props.form.training_employee_chat_questions_text = DEFAULT_TRAINING_EMPLOYEE_CHAT_QUESTIONS.join('\n');
props.form.training_employee_chat_questions_text = getDefaultTrainingChatQuestions('employee').join('\n');
}
if (!props.form.training_hr_chat_questions_text.trim()) {
props.form.training_hr_chat_questions_text = DEFAULT_TRAINING_HR_CHAT_QUESTIONS.join('\n');
props.form.training_hr_chat_questions_text = getDefaultTrainingChatQuestions('hr').join('\n');
}
} else if (props.form.content_profile === 'training') {
props.form.content_profile = '';
@@ -208,7 +207,6 @@ watch(
},
);
watch(
() => props.form.is_aggregate,
(enabled) => {
@@ -303,12 +301,13 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
</option>
</select>
</div>
<template v-if="showDifyFields">
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">Dify应用类型</label>
<select v-model="form.dify_app_type" class="w-full input-field text-sm">
<option value="chatflow">Chatflow</option>
<option value="workflow">Workflow</option>
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.difyAppType') }}</label>
<select v-model="form.dify_app_type" class="w-full input-field text-sm">
<option value="chatflow">{{ t('admin.agent.fields.difyAppTypes.chatflow') }}</option>
<option value="workflow">{{ t('admin.agent.fields.difyAppTypes.workflow') }}</option>
</select>
</div>
<div class="space-y-2">
@@ -341,6 +340,23 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
</div>
</template>
<div class="col-span-1 md:col-span-2 space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.isActive') }}</label>
<div class="flex flex-col gap-2 rounded-xl border border-default bg-surface-soft/40 px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
<p class="text-sm leading-6 text-secondary">
{{ form.is_active ? t('admin.agent.fields.isActiveHintOn') : t('admin.agent.fields.isActiveHintOff') }}
</p>
<label class="inline-flex shrink-0 items-center gap-2 rounded-xl border border-default bg-white px-3 py-2 text-sm text-secondary">
<input
v-model="form.is_active"
type="checkbox"
class="accent-brand-600"
/>
<span>{{ t('admin.agent.fields.isActiveEnable') }}</span>
</label>
</div>
</div>
<div class="col-span-1 md:col-span-2 space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.description') }}</label>
<input
@@ -565,30 +581,30 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
<div class="col-span-1 md:col-span-2 space-y-3">
<div class="flex flex-wrap items-center justify-between gap-3">
<label class="text-xs font-bold text-muted uppercase tracking-wider">常见问题</label>
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.suggestedQuestions.title') }}</label>
<button
type="button"
class="inline-flex items-center gap-1 rounded-lg border border-default px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
@click="emit('addSuggestedQuestion')"
>
<Plus class="h-4 w-4" />
添加问题
{{ t('admin.agent.suggestedQuestions.add') }}
</button>
</div>
<div class="flex flex-wrap items-center gap-3 text-sm">
<label class="inline-flex items-center gap-2 text-secondary">
<input v-model="form.suggested_questions_style" type="radio" value="plain" class="accent-brand-600" />
<span>无样式</span>
<span>{{ t('admin.agent.suggestedQuestions.stylePlain') }}</span>
</label>
<label class="inline-flex items-center gap-2 text-secondary">
<input v-model="form.suggested_questions_style" type="radio" value="styled" class="accent-brand-600" />
<span>有样式</span>
<span>{{ t('admin.agent.suggestedQuestions.styleStyled') }}</span>
</label>
</div>
<div v-if="form.suggested_questions.length === 0" class="rounded-xl border border-dashed border-default px-4 py-5 text-sm text-muted">
暂未配置常见问题,点击“添加问题”后会同步到对应 Agent 的 Chat 欢迎页。
{{ t('admin.agent.suggestedQuestions.empty') }}
</div>
<div v-else class="space-y-3">
@@ -602,14 +618,16 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
v-model="item.question"
type="text"
class="w-full input-field text-sm"
placeholder="请输入常见问题,例如:查询我有多少假期?"
:placeholder="t('admin.agent.suggestedQuestions.questionPlaceholder')"
/>
<input
v-model="item.group"
type="text"
class="w-full input-field text-sm"
:disabled="form.suggested_questions_style !== 'styled'"
:placeholder="form.suggested_questions_style === 'styled' ? '可选:分组标题,例如:考勤与休假' : '无样式下无需分组'"
:placeholder="form.suggested_questions_style === 'styled'
? t('admin.agent.suggestedQuestions.groupPlaceholderStyled')
: t('admin.agent.suggestedQuestions.groupPlaceholderPlain')"
/>
<button
type="button"
@@ -500,13 +500,13 @@ export function useAgentsAdmin() {
payload.dify_api_key = form.value.dify_api_key;
}
await updateAdminAgent(form.value.id, payload);
msg.success('应用更新成功');
msg.success(t('admin.agent.updateSuccess'));
} else {
await createAdminAgent({
...registryPayload,
dify_api_key: form.value.dify_api_key,
});
msg.success('应用创建成功');
msg.success(t('admin.agent.createSuccess'));
}
await loadAgents();
@@ -0,0 +1,135 @@
/**
* features/admin/modules/linked-services/LinkedServicesPage.vue
* 关联服务管理独立页面:表格列表 + 新增/编辑弹窗。
* 依赖:useLinkedServicesAdmin、LinkedServiceFormModal、DeleteConfirmDialog。
* 逻辑:路由 /admin/linked-services;启用项自动出现在 Chat/工作台侧栏底部。
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Edit, Plus, Trash2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import LinkedServiceFormModal from './components/LinkedServiceFormModal.vue';
import { useLinkedServicesAdmin } from './composables/useLinkedServicesAdmin';
const { t } = useI18n();
const {
services,
form,
isLoading,
isSaving,
showFormModal,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
openCreateModal,
openEditModal,
closeFormModal,
saveService,
toggleEnabled,
deleteServiceItem,
closeDeleteConfirm,
confirmDelete,
} = useLinkedServicesAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="admin-table-section animate-fade-in-up">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div class="admin-table-header admin-table-header--stacked">
<div>
<h2 class="section-title">{{ t('admin.linkedServices.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.linkedServices.subtitle') }}</p>
</div>
<button
type="button"
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
@click="openCreateModal"
>
<Plus class="w-4 h-4" />
<span>{{ t('admin.linkedServices.add') }}</span>
</button>
</div>
<div class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.linkedServices.headers.name') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.linkedServices.headers.url') }}</th>
<th class="px-6 py-4 text-left text-xs w-28">{{ t('admin.linkedServices.headers.status') }}</th>
<th class="px-6 py-4 text-left text-xs w-24">{{ t('admin.linkedServices.headers.sortOrder') }}</th>
<th class="px-6 py-4 text-right text-xs w-40">{{ t('admin.linkedServices.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="services.length === 0">
<td colspan="5" class="px-6 admin-table-empty">{{ t('admin.linkedServices.empty') }}</td>
</tr>
<tr v-for="row in services" :key="row.id">
<td class="px-6 py-4 text-sm font-medium text-primary">{{ row.name }}</td>
<td class="px-6 py-4 text-sm text-secondary font-mono break-all">{{ row.url }}</td>
<td class="px-6 py-4">
<button
type="button"
class="inline-flex items-center rounded-full px-2.5 py-1 text-xs font-medium transition-colors"
:class="row.is_enabled
? 'bg-emerald-50 text-emerald-700 hover:bg-emerald-100'
: 'bg-surface-soft text-muted hover:bg-surface'"
@click="toggleEnabled(row)"
>
{{ row.is_enabled ? t('admin.linkedServices.status.enabled') : t('admin.linkedServices.status.disabled') }}
</button>
</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.sort_order }}</td>
<td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1">
<button
type="button"
class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary"
:title="t('admin.edit')"
@click="openEditModal(row)"
>
<Edit class="w-4 h-4" />
</button>
<button
type="button"
class="p-2 rounded-lg text-muted hover:bg-red-50 hover:text-red-600"
:title="t('admin.delete')"
@click="deleteServiceItem(row.id)"
>
<Trash2 class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<LinkedServiceFormModal
:visible="showFormModal"
:form="form"
:is-saving="isSaving"
@close="closeFormModal"
@save="saveService"
/>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@cancel="closeDeleteConfirm"
@confirm="confirmDelete"
/>
</section>
</template>
@@ -0,0 +1,70 @@
/**
* features/admin/modules/linked-services/components/LinkedServiceFormModal.vue
* 关联服务创建/编辑居中弹窗。
* 依赖:LinkedServiceFormState、admin 通用 modal 样式。
* 逻辑:LinkedServicesPage 打开本组件;提交时 emit save。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { LinkedServiceFormState } from '@/features/admin/types/linked-service.types';
defineProps<{
visible: boolean;
form: LinkedServiceFormState;
isSaving: boolean;
}>();
const emit = defineEmits<{
close: [];
save: [];
}>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
<div class="admin-modal-panel max-w-lg max-h-[92vh] scale-100">
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
<h3 class="section-title">
{{ form.id ? t('admin.linkedServices.edit') : t('admin.linkedServices.add') }}
</h3>
<p class="section-desc mt-1">{{ t('admin.linkedServices.formHint') }}</p>
</div>
<div class="px-5 sm:px-8 py-5 space-y-5 overflow-y-auto">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.linkedServices.fields.name') }}</label>
<input
v-model="form.name"
type="text"
class="input-field text-sm"
:placeholder="t('admin.linkedServices.placeholders.name')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.linkedServices.fields.url') }}</label>
<input
v-model="form.url"
type="url"
class="input-field text-sm font-mono"
:placeholder="t('admin.linkedServices.placeholders.url')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.linkedServices.fields.sortOrder') }}</label>
<input v-model.number="form.sort_order" type="number" class="input-field text-sm" min="0" />
</div>
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
<input v-model="form.is_enabled" type="checkbox" class="w-4 h-4 rounded text-brand-600 border-default" />
{{ t('admin.linkedServices.fields.enabled') }}
</label>
</div>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-70" :disabled="isSaving" @click="emit('save')">
{{ isSaving ? t('admin.save') + '...' : form.id ? t('admin.update') : t('admin.add') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,198 @@
/**
* features/admin/modules/linked-services/composables/useLinkedServicesAdmin.ts
* 关联服务管理:列表、新增/编辑弹窗、启用开关、删除。
* 依赖:admin.api、linked-service.types、linked-nav.store、useMessage。
* 逻辑:LinkedServicesPage 调用本 composable;保存/删除后刷新侧栏入口缓存。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
createLinkedService,
deleteLinkedService,
listLinkedServices,
updateLinkedService,
} from '@/features/admin/api/admin.api';
import { useLinkedNavStore } from '@/features/sso/stores/linked-nav.store';
import { useMessage } from '@/shared/composables/useMessage';
import {
createEmptyLinkedServiceForm,
linkedServiceRowToForm,
type AdminLinkedServiceRow,
type LinkedServiceFormState,
} from '@/features/admin/types/linked-service.types';
export function useLinkedServicesAdmin() {
const { t } = useI18n();
const msg = useMessage();
const linkedNav = useLinkedNavStore();
const services = ref<AdminLinkedServiceRow[]>([]);
const form = ref<LinkedServiceFormState>(createEmptyLinkedServiceForm());
const isLoading = ref(true);
const isSaving = ref(false);
const showFormModal = ref(false);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
/**
* 拉取关联服务列表。
* @returns Promise<void>
*/
const loadServices = async (): Promise<void> => {
try {
services.value = await listLinkedServices();
} catch (e) {
console.error('Failed to load linked services', e);
services.value = [];
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
};
/**
* 页面初始化:加载列表并结束 loading。
* @returns Promise<void>
*/
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await loadServices();
isLoading.value = false;
};
/** 打开删除确认对话框。 */
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
/** 关闭删除确认对话框。 */
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
/** 执行删除确认动作。 */
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
/** 打开「新增关联服务」弹窗。 */
const openCreateModal = (): void => {
form.value = createEmptyLinkedServiceForm();
form.value.sort_order = services.value.length;
showFormModal.value = true;
};
/**
* 打开「编辑关联服务」弹窗。
* @param row - 待编辑行
*/
const openEditModal = (row: AdminLinkedServiceRow): void => {
form.value = linkedServiceRowToForm(row);
showFormModal.value = true;
};
/** 关闭表单弹窗。 */
const closeFormModal = (): void => {
showFormModal.value = false;
form.value = createEmptyLinkedServiceForm();
};
/**
* 保存关联服务:有 id 则更新,否则新建。
* 核心逻辑:校验名称与 URL → 调 API → 刷新列表。
*/
const saveService = async (): Promise<void> => {
if (!form.value.name.trim() || !form.value.url.trim()) {
msg.warning(t('admin.linkedServices.msg.fillAll'));
return;
}
isSaving.value = true;
try {
const payload = {
name: form.value.name.trim(),
url: form.value.url.trim(),
is_enabled: form.value.is_enabled,
sort_order: Number(form.value.sort_order || 0),
};
if (form.value.id) {
await updateLinkedService(form.value.id, payload);
} else {
await createLinkedService(payload);
}
closeFormModal();
await loadServices();
void linkedNav.refresh();
msg.success(t('admin.linkedServices.msg.saved'));
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
};
/**
* 切换启用状态并立即保存。
* @param row - 目标行
*/
const toggleEnabled = async (row: AdminLinkedServiceRow): Promise<void> => {
try {
await updateLinkedService(row.id, {
name: row.name,
url: row.url,
is_enabled: !row.is_enabled,
sort_order: row.sort_order,
});
await loadServices();
void linkedNav.refresh();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
};
/**
* 删除指定关联服务。
* @param id - 主键
*/
const deleteServiceItem = (id: number): void => {
openDeleteConfirm(t('admin.linkedServices.confirmDelete'), async () => {
try {
await deleteLinkedService(id);
await loadServices();
void linkedNav.refresh();
msg.success(t('admin.linkedServices.msg.deleted'));
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
};
return {
services,
form,
isLoading,
isSaving,
showFormModal,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
openCreateModal,
openEditModal,
closeFormModal,
saveService,
toggleEnabled,
deleteServiceItem,
closeDeleteConfirm,
confirmDelete,
};
}
@@ -1,9 +1,14 @@
/**
* features/admin/modules/platform-apps/PlatformAppsPage.vue
* 用途:平台应用说明(新手指南)管理——按 Agent 维护指南资料上传、启停与排序。
* 依赖:admin.api 指南 CRUD/上传、vue-i18n、lucide 图标。
* 逻辑:Admin 路由挂载;选择应用后拉取指南列表,弹窗内上传并保存元数据。
*/
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { Plus, Trash2, Edit2, Play, FileText, Image as ImageIcon } from 'lucide-vue-next';
import { listAdminAgents, listAdminAgentGuides, createAdminAgentGuide, updateAdminAgentGuide, deleteAdminAgentGuide, uploadAdminAgentGuideFile } from '@/features/admin/api/admin.api';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
const { t } = useI18n();
@@ -29,9 +34,10 @@ const form = ref({
const isUploading = ref(false);
const uploadError = ref('');
const deleteDialogOpen = ref(false);
const pendingDeleteGuideId = ref<number | null>(null);
/**
* 拉取 Agent 列表并默认选中第一项,再加载其指南。
*/
const fetchAgents = async () => {
try {
agents.value = await listAdminAgents();
@@ -44,6 +50,9 @@ const fetchAgents = async () => {
}
};
/**
* 按当前选中 Agent 拉取指南列表。
*/
const fetchGuides = async () => {
if (!selectedAgentId.value) return;
isLoading.value = true;
@@ -65,6 +74,9 @@ onMounted(() => {
fetchAgents();
});
/**
* 打开新建指南弹窗并重置表单。
*/
const openCreateModal = () => {
isEditing.value = false;
editingId.value = null;
@@ -82,6 +94,10 @@ const openCreateModal = () => {
isModalOpen.value = true;
};
/**
* 打开编辑指南弹窗并回填行数据。
* @param guide - 列表行指南对象
*/
const openEditModal = (guide: any) => {
isEditing.value = true;
editingId.value = guide.id;
@@ -99,6 +115,10 @@ const openEditModal = (guide: any) => {
isModalOpen.value = true;
};
/**
* 上传指南文件并回填 path/type/size;必要时校正 guide_usage 与文件类型一致性。
* @param event - input file change 事件
*/
const handleFileUpload = async (event: Event) => {
const file = (event.target as HTMLInputElement).files?.[0];
if (!file) return;
@@ -121,12 +141,15 @@ const handleFileUpload = async (event: Event) => {
form.value.file_name = res.file_name;
}
} catch (err: any) {
uploadError.value = err.message || '上传失败';
uploadError.value = err.message || t('admin.platformApps.uploadFailed');
} finally {
isUploading.value = false;
}
};
/**
* 提交新建或更新指南元数据。
*/
const submitForm = async () => {
if (!selectedAgentId.value || !form.value.file_path || !form.value.file_name) return;
@@ -146,23 +169,24 @@ const submitForm = async () => {
}
};
const deleteGuide = (id: number) => {
pendingDeleteGuideId.value = id;
deleteDialogOpen.value = true;
};
const confirmDeleteGuide = async () => {
const id = pendingDeleteGuideId.value;
if (!id) return;
/**
* 确认后删除指南。
* @param id - 指南主键
*/
const deleteGuide = async (id: number) => {
if (!confirm(t('admin.platformApps.confirmDelete'))) return;
try {
await deleteAdminAgentGuide(id);
await fetchGuides();
} catch (error) {
console.error('Failed to delete guide:', error);
} finally {
pendingDeleteGuideId.value = null;
}
};
/**
* 切换指南启停状态。
* @param guide - 列表行指南对象
*/
const toggleStatus = async (guide: any) => {
try {
await updateAdminAgentGuide(guide.id, { status: guide.status === 1 ? 0 : 1 });
@@ -172,6 +196,11 @@ const toggleStatus = async (guide: any) => {
}
};
/**
* 将字节数格式化为可读文件大小。
* @param bytes - 文件字节数
* @returns 如 `1.2 MB`
*/
const formatSize = (bytes: number) => {
if (!bytes) return '0 B';
const k = 1024;
@@ -180,6 +209,10 @@ const formatSize = (bytes: number) => {
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
/**
* 按文件类型返回列表图标组件。
* @param type - 文件类型(video/pdf/其它)
*/
const getIcon = (type: string) => {
if (type === 'video') return Play;
if (type === 'pdf') return FileText;
@@ -195,7 +228,7 @@ const getIcon = (type: string) => {
{{ t('admin.nav.platformApps') }}
</h2>
<p class="text-sm text-muted mt-1">
管理应用的新手指南资料(支持视频、PDF等)
{{ t('admin.platformApps.subtitle') }}
</p>
</div>
</div>
@@ -203,7 +236,7 @@ const getIcon = (type: string) => {
<div class="surface-panel rounded-2xl p-6 shadow-sm border border-subtle flex-1 flex flex-col gap-6">
<div class="flex items-center justify-between">
<div class="flex items-center gap-4">
<label class="font-medium text-sm text-default">选择应用:</label>
<label class="font-medium text-sm text-default">{{ t('admin.platformApps.selectAgent') }}</label>
<select v-model="selectedAgentId" class="input-field w-64" @change="fetchGuides">
<option v-for="agent in agents" :key="agent.id" :value="agent.id">
{{ agent.name }}
@@ -212,7 +245,7 @@ const getIcon = (type: string) => {
</div>
<button v-if="selectedAgentId" type="button" class="btn-primary" @click="openCreateModal">
<Plus class="w-5 h-5 mr-1" />
<span>添加指南</span>
<span>{{ t('admin.platformApps.addGuide') }}</span>
</button>
</div>
@@ -221,25 +254,25 @@ const getIcon = (type: string) => {
</div>
<div v-else-if="!selectedAgentId" class="flex flex-col items-center justify-center py-20 text-muted">
请先选择一个应用
{{ t('admin.platformApps.selectAgentFirst') }}
</div>
<div v-else-if="guides.length === 0" class="flex flex-col items-center justify-center py-20 text-muted">
该应用暂无新手指南资料
{{ t('admin.platformApps.emptyGuides') }}
</div>
<div v-else class="overflow-x-auto rounded-xl border border-subtle">
<table class="w-full text-left text-sm whitespace-nowrap">
<thead class="bg-muted text-muted uppercase text-xs font-semibold tracking-wider border-b border-subtle">
<tr>
<th class="px-6 py-4">类型</th>
<th class="px-6 py-4">资料名称</th>
<th class="px-6 py-4">{{ t('admin.platformApps.colType') }}</th>
<th class="px-6 py-4">{{ t('admin.platformApps.colFileName') }}</th>
<th class="px-6 py-4">{{ t('admin.platformApps.guideUsage') }}</th>
<th class="px-6 py-4">Agent应用</th>
<th class="px-6 py-4">文件大小</th>
<th class="px-6 py-4">排序</th>
<th class="px-6 py-4">状态</th>
<th class="px-6 py-4 text-right">操作</th>
<th class="px-6 py-4">{{ t('admin.platformApps.colAgent') }}</th>
<th class="px-6 py-4">{{ t('admin.platformApps.colFileSize') }}</th>
<th class="px-6 py-4">{{ t('admin.platformApps.colSort') }}</th>
<th class="px-6 py-4">{{ t('admin.platformApps.colStatus') }}</th>
<th class="px-6 py-4 text-right">{{ t('admin.platformApps.colActions') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-subtle">
@@ -269,14 +302,14 @@ const getIcon = (type: string) => {
:class="guide.status === 1 ? 'bg-green-100 text-green-700 hover:bg-green-200' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'"
@click="toggleStatus(guide)"
>
{{ guide.status === 1 ? '已启用' : '已禁用' }}
{{ guide.status === 1 ? t('admin.platformApps.statusEnabled') : t('admin.platformApps.statusDisabled') }}
</button>
</td>
<td class="px-6 py-4 text-right space-x-2">
<button type="button" class="btn-icon-ds" @click="openEditModal(guide)" title="编辑">
<button type="button" class="btn-icon-ds" @click="openEditModal(guide)" :title="t('common.edit')">
<Edit2 class="w-4 h-4" />
</button>
<button type="button" class="btn-icon-ds text-red-500 hover:bg-red-50" @click="deleteGuide(guide.id)" title="删除">
<button type="button" class="btn-icon-ds text-red-500 hover:bg-red-50" @click="deleteGuide(guide.id)" :title="t('common.delete')">
<Trash2 class="w-4 h-4" />
</button>
</td>
@@ -290,13 +323,13 @@ const getIcon = (type: string) => {
<div v-if="isModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl w-full max-w-lg overflow-hidden flex flex-col max-h-[90vh]">
<div class="px-6 py-4 border-b border-subtle flex justify-between items-center">
<h3 class="text-lg font-bold text-default">{{ isEditing ? '编辑指南' : '添加指南' }}</h3>
<h3 class="text-lg font-bold text-default">{{ isEditing ? t('admin.platformApps.editGuide') : t('admin.platformApps.addGuide') }}</h3>
<button @click="isModalOpen = false" class="text-muted hover:text-default text-xl leading-none">&times;</button>
</div>
<div class="p-6 overflow-y-auto space-y-4">
<div v-if="!isEditing" class="space-y-2">
<label class="text-sm font-medium text-default">上传文件</label>
<label class="text-sm font-medium text-default">{{ t('admin.platformApps.uploadFile') }}</label>
<input
type="file"
accept="video/mp4,video/webm,application/pdf,image/png,image/jpeg"
@@ -304,20 +337,20 @@ const getIcon = (type: string) => {
@change="handleFileUpload"
/>
<div v-if="isUploading" class="text-sm text-blue-600 mt-2 flex items-center gap-2">
<div class="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div> 上传中...
<div class="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div> {{ t('admin.platformApps.uploading') }}
</div>
<div v-if="uploadError" class="text-sm text-red-500 mt-2">{{ uploadError }}</div>
<div v-if="form.file_path && !isUploading" class="text-sm text-green-600 mt-2">已上传文件就绪</div>
<div v-if="form.file_path && !isUploading" class="text-sm text-green-600 mt-2">{{ t('admin.platformApps.uploadReady') }}</div>
</div>
<div class="space-y-2">
<label class="text-sm font-medium text-default">资料名称</label>
<input v-model="form.file_name" type="text" class="input-field w-full" placeholder="如:人事助手使用手册" />
<label class="text-sm font-medium text-default">{{ t('admin.platformApps.fileName') }}</label>
<input v-model="form.file_name" type="text" class="input-field w-full" :placeholder="t('admin.platformApps.fileNamePlaceholder')" />
</div>
<div class="space-y-2">
<label class="text-sm font-medium text-default">备注说明</label>
<textarea v-model="form.remark" class="input-field w-full h-20" placeholder="简要说明..."></textarea>
<label class="text-sm font-medium text-default">{{ t('admin.platformApps.remark') }}</label>
<textarea v-model="form.remark" class="input-field w-full h-20" :placeholder="t('admin.platformApps.remarkPlaceholder')"></textarea>
</div>
<div class="grid grid-cols-2 gap-4">
@@ -331,33 +364,32 @@ const getIcon = (type: string) => {
<p class="text-xs text-muted">{{ t('admin.platformApps.guideUsageHint') }}</p>
</div>
<div class="space-y-2">
<label class="text-sm font-medium text-default">排序权重</label>
<label class="text-sm font-medium text-default">{{ t('admin.platformApps.sortOrder') }}</label>
<input v-model.number="form.sort_order" type="number" class="input-field w-full" />
<p class="text-xs text-muted">数值越小越靠前</p>
<p class="text-xs text-muted">{{ t('admin.platformApps.sortOrderHint') }}</p>
</div>
<div class="space-y-2">
<label class="text-sm font-medium text-default">状态</label>
<label class="text-sm font-medium text-default">{{ t('admin.platformApps.status') }}</label>
<select v-model="form.status" class="input-field w-full">
<option :value="1">启用</option>
<option :value="0">禁用</option>
<option :value="1">{{ t('admin.platformApps.enable') }}</option>
<option :value="0">{{ t('admin.platformApps.disable') }}</option>
</select>
</div>
</div>
</div>
<div class="px-6 py-4 border-t border-subtle bg-muted flex justify-end gap-3">
<button type="button" class="btn-secondary" @click="isModalOpen = false">取消</button>
<button type="button" class="btn-secondary" @click="isModalOpen = false">{{ t('admin.cancel') }}</button>
<button
type="button"
class="btn-primary"
@click="submitForm"
:disabled="isUploading || !form.file_path || !form.file_name"
>
保存
{{ t('admin.platformApps.save') }}
</button>
</div>
</div>
</div>
<DeleteConfirmDialog v-model="deleteDialogOpen" title="删除指南" message="确定要删除该指南吗?删除后不可恢复。" confirm-tone="danger" @confirm="confirmDeleteGuide" />
</div>
</template>
@@ -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>
@@ -0,0 +1,20 @@
/**
* features/admin/modules/procurement-contract/contract-ocr-match-tokens.ts
* 用途:采购合同比对区域的 V4 默认 OCR/正文匹配锚点与签章关键词(检测用 token,非 UI 文案)。
* 依赖:procurement-contract.api 的 ContractComparisonRegionConfig 类型。
* 逻辑:ProcurementContractPage「恢复 V4 默认配置」与新建区域配置时引用;勿当作 i18n 展示文案。
*
* NOTE: Strings below are OCR match tokens for Chinese contract PDFs. Keep them in Chinese
* regardless of UI locale so region recognition against Chinese source documents still works.
*/
import type { ContractComparisonRegionConfig } from '@/features/admin/api/procurement-contract.api';
/** V4 默认比对区域配置(锚点/关键词为中文 OCR 匹配 token)。 */
export const V4_REGION_CONFIG: ContractComparisonRegionConfig = {
metadata_fields: ['contract_no', 'buyer', 'seller', 'version'],
body_start_anchors: ['兹因甲方向乙方购买设备'],
body_end_anchors: ['本合同一式两份', '以下无正文', '本页以下无正文'],
signature_terms: ['甲方', '乙方', '盖章', '签署日期', '合同专用章'],
attachment_start_anchors: ['附件', '性能需求表', '技术协议', '设备配置清单'],
attachment_policy: 'page_count_only',
};
@@ -74,7 +74,6 @@ const {
getApplicationSortMark,
handleApplicationSearchChange,
openApplicationChatLogs,
openApplicationPermissionRequests,
isLoading,
currentTable,
tableData,
@@ -139,7 +138,6 @@ const applicationSortableKeys: ApplicationSortKey[] = [
'unique_users',
'last_active_at',
'authorized_users',
'pending_requests',
'avg_score',
];
@@ -531,7 +529,7 @@ onBeforeUnmount(() => {
</div>
</div>
<div v-if="applicationSummary" class="grid grid-cols-2 gap-3 md:grid-cols-4">
<div v-if="applicationSummary" class="grid grid-cols-1 gap-3 sm:grid-cols-3">
<button type="button" class="rounded-xl border border-default bg-surface p-4 text-left" @click="setApplicationUsageFilter('all')">
<div class="text-sm text-muted">{{ t('admin.report.appOps.summaryActive') }}</div>
<div class="mt-2 text-2xl font-bold text-primary">{{ applicationSummary.active_agents }}</div>
@@ -545,25 +543,20 @@ onBeforeUnmount(() => {
<div class="text-sm text-muted">{{ t('admin.report.appOps.summaryUnused') }}</div>
<div class="mt-2 text-2xl font-bold text-primary">{{ applicationSummary.unused_agents }}</div>
</button>
<div class="rounded-xl border border-default bg-surface p-4">
<div class="text-sm text-muted">{{ t('admin.report.appOps.summaryPending') }}</div>
<div class="mt-2 text-2xl font-bold text-primary">{{ applicationSummary.pending_permission_total }}</div>
</div>
</div>
<div class="admin-report-table-wrap">
<table class="admin-report-table admin-report-table--app-ops w-full table-fixed border-collapse">
<colgroup>
<col class="w-[14%]" />
<col class="w-[7%]" />
<col class="w-[7%]" />
<col class="w-[16%]" />
<col class="w-[7%]" />
<col class="w-[7%]" />
<col class="w-[8%]" />
<col class="w-[8%]" />
<col class="w-[8%]" />
<col class="w-[18%]" />
<col class="w-[8%]" />
<col class="w-[10%]" />
<col class="w-[10%]" />
<col class="w-[10%]" />
<col class="w-[12%]" />
</colgroup>
<thead>
<tr>
@@ -588,7 +581,7 @@ onBeforeUnmount(() => {
</thead>
<tbody>
<tr v-if="applicationItems.length === 0">
<td colspan="10" class="text-center text-muted py-12">
<td colspan="9" class="text-center text-muted py-12">
{{ t('admin.report.appOps.empty') }}
</td>
</tr>
@@ -600,7 +593,6 @@ onBeforeUnmount(() => {
{{ row.last_active_at ? formatLocalDateTime(row.last_active_at) : '-' }}
</td>
<td class="px-3 py-3 text-left align-middle font-mono tabular-nums">{{ row.authorized_users }}</td>
<td class="px-3 py-3 text-left align-middle font-mono tabular-nums">{{ row.pending_requests }}</td>
<td class="px-3 py-3 text-left align-middle font-mono tabular-nums whitespace-nowrap">
{{ row.avg_score == null ? '-' : row.avg_score }}
<span v-if="row.feedback_count" class="text-xs text-muted">({{ row.feedback_count }})</span>
@@ -612,14 +604,9 @@ onBeforeUnmount(() => {
</span>
</td>
<td class="px-3 py-3 text-left align-middle">
<div class="flex flex-wrap gap-1">
<button type="button" class="btn-secondary text-xs px-2 py-1" @click="openApplicationChatLogs(row)">
{{ t('admin.report.appOps.actionLogs') }}
</button>
<button type="button" class="btn-secondary text-xs px-2 py-1" @click="openApplicationPermissionRequests(row)">
{{ t('admin.report.appOps.actionRequests') }}
</button>
</div>
<button type="button" class="btn-secondary text-xs px-2 py-1" @click="openApplicationChatLogs(row)">
{{ t('admin.report.appOps.actionLogs') }}
</button>
</td>
</tr>
</tbody>
@@ -207,18 +207,6 @@ export function useReportsAdmin() {
});
};
/**
* 下钻到权限申请列表,按 agent_id 精确过滤。
* @param row - 应用运营行
*/
const openApplicationPermissionRequests = (row: ApplicationReportItem): void => {
void router.push({
name: 'AdminReports',
params: { table: 'permission_requests' },
query: { agent_id: String(row.agent_id) },
});
};
/**
* 导出应用运营报表 Excel(仅运营字段)。
*/
@@ -237,7 +225,6 @@ export function useReportsAdmin() {
? formatLocalDateTime(row.last_active_at)
: '-',
[t('admin.report.appOps.columns.authorized_users')]: row.authorized_users,
[t('admin.report.appOps.columns.pending_requests')]: row.pending_requests,
[t('admin.report.appOps.columns.avg_score')]: row.avg_score ?? '-',
[t('admin.report.appOps.columns.feedback_count')]: row.feedback_count,
[t('admin.report.appOps.columns.tokens_used')]: row.tokens_used,
@@ -405,7 +392,7 @@ const dataSourceTable = computed<Exclude<AdminReportTableId, 'usage_analysis'>>(
});
/**
* 从路由 query 灌入列筛选(用于应用运营下钻到聊天日志 / 权限申请)。
* 从路由 query 灌入列筛选(用于应用运营下钻到聊天日志)。
*/
const applyRouteQueryFilters = (): void => {
const next: Record<string, string> = {};
@@ -1218,7 +1205,6 @@ watch([reportPageSize, sortedTableData], () => {
getApplicationSortMark,
handleApplicationSearchChange,
openApplicationChatLogs,
openApplicationPermissionRequests,
isLoading,
currentTable,
tableData,
@@ -1,6 +1,6 @@
/**
* features/admin/stores/admin-nav.store.ts
* 管理后台导航 UI 状态(侧栏折叠、货代/报表/企微子菜单展开、角标)。
* 管理后台导航 UI 状态(侧栏折叠、报表/企微子菜单展开、角标)。
*
* 角标数据来自 GET /api/admin/dashboard/badges,在 store 内做 TTL 缓存与 in-flight 去重,
* 避免切换 admin 子路由时重复请求(AdminLayout 挂载一次即可)。
@@ -11,11 +11,6 @@ import { ref } from 'vue';
import { getAdminDashboardBadges } from '@/features/admin/api/admin.api';
import type { AdminModuleId } from '../types/admin.types';
export type ShippingManagementGroupKey =
| 'admin.nav.shippingOrderRecognition'
| 'admin.nav.shippingInventoryManagement'
| 'admin.nav.shippingRunAudit';
/** 角标缓存有效期(毫秒):此时间内 ensureBadges 直接复用内存中的计数 */
const BADGE_CACHE_TTL_MS = 60_000;
@@ -25,10 +20,6 @@ export const useAdminNavStore = defineStore('adminNav', () => {
const reportsExpanded = ref(false);
/** 企业微信子菜单:默认折叠 */
const wecomExpanded = ref(false);
/** 货代管理二级菜单:默认折叠,进入货代页面时自动展开。 */
const shippingManagementExpanded = ref(false);
/** 货代手风琴当前展开分组;单值约束保证同一时间最多展开一组。 */
const shippingManagementGroup = ref<ShippingManagementGroupKey | null>(null);
/** 「用户审批」导航角标:pending 注册用户数 */
const pendingApprovalsCount = ref(0);
/** 「权限申请」导航角标:pending 权限申请数 */
@@ -43,11 +34,6 @@ export const useAdminNavStore = defineStore('adminNav', () => {
sidebarCollapsed.value = !sidebarCollapsed.value;
};
/** 展开指定货代分组;再次点击当前分组时收起全部功能项。 */
const toggleShippingManagementGroup = (groupKey: ShippingManagementGroupKey): void => {
shippingManagementGroup.value = shippingManagementGroup.value === groupKey ? null : groupKey;
};
const setBadgeCounts = (approvals: number, requests: number): void => {
pendingApprovalsCount.value = approvals;
pendingRequestsCount.value = requests;
@@ -102,12 +88,9 @@ export const useAdminNavStore = defineStore('adminNav', () => {
sidebarCollapsed,
reportsExpanded,
wecomExpanded,
shippingManagementExpanded,
shippingManagementGroup,
pendingApprovalsCount,
pendingRequestsCount,
toggleSidebar,
toggleShippingManagementGroup,
setBadgeCounts,
badgeForModule,
ensureBadges,
@@ -14,31 +14,13 @@ export type AdminModuleId =
| 'announcements'
| 'questions'
| 'wecom'
| 'linked_services'
| 'permissions'
| 'requests'
| 'platform_apps'
| 'shipping_inventory'
| 'procurement_contract'
| 'reports';
/** 货代管理领域下可由侧栏展示和高亮的稳定业务页面。 */
export type ShippingConfigSubModuleId =
| 'field_assets'
| 'order_schema'
| 'order_document_profiles'
| 'identity_rules'
| 'order_extraction_runs'
| 'shipping_audit'
| 'process_gates'
| 'legacy_stp_jobs'
| 'inventory_fields'
| 'connections'
| 'inventory_sites'
| 'warehouse_mappings'
| 'routing_rules'
| 'shipping_templates'
| 'inventory_snapshots'
| 'export_records';
export type AdminReportTableId =
| 'usage_analysis'
| 'users'
@@ -0,0 +1,44 @@
/**
* features/admin/types/linked-service.types.ts
* 关联服务管理表单与行数据类型。
*/
export interface AdminLinkedServiceRow {
id: number;
name: string;
url: string;
is_enabled: boolean;
sort_order: number;
created_at?: string | null;
updated_at?: string | null;
}
export interface LinkedServiceFormState {
id: number | null;
name: string;
url: string;
is_enabled: boolean;
sort_order: number;
}
/** 创建空的关联服务表单。 */
export function createEmptyLinkedServiceForm(): LinkedServiceFormState {
return {
id: null,
name: '',
url: '',
is_enabled: true,
sort_order: 0,
};
}
/** 将列表行回填为编辑表单。 */
export function linkedServiceRowToForm(row: AdminLinkedServiceRow): LinkedServiceFormState {
return {
id: row.id,
name: row.name,
url: row.url,
is_enabled: Boolean(row.is_enabled),
sort_order: Number(row.sort_order || 0),
};
}
@@ -45,7 +45,6 @@ export type ApplicationSortKey =
| 'unique_users'
| 'last_active_at'
| 'authorized_users'
| 'pending_requests'
| 'avg_score'
| 'tokens_used';
@@ -58,7 +57,8 @@ export interface ApplicationReportItem {
unique_users: number;
last_active_at: string | null;
authorized_users: number;
pending_requests: number;
/** 后端仍返回;应用运营页已不再展示待审列 */
pending_requests?: number;
avg_score: number | null;
feedback_count: number;
tokens_used: number;
@@ -70,7 +70,8 @@ export interface ApplicationReportSummary {
active_agents: number;
used_agents: number;
unused_agents: number;
pending_permission_total: number;
/** 后端仍返回;应用运营页已不再展示待审摘要卡 */
pending_permission_total?: number;
}
export interface ApplicationReport {
@@ -1,9 +1,7 @@
/**
* features/admin/views/AdminLayout.vue
* 管理后台壳层:顶栏 + 左侧导航 + 子路由出口。
* 依赖:AdminNav、vue-router、admin-nav.store。
* 逻辑:AdminNav 统一承担模块和二级目录导航;lg 起侧栏与内容并排,
* 小于 lg(含 768px)上下堆叠,避免运维诊断页主区被侧栏挤窄。
* 管理后台壳层:顶栏 + AdminNav + 子路由出口。
* 角标仅在 Layout 首次挂载时 ensureBadges(store 内 60s TTL 缓存)。
*/
<script setup lang="ts">
import { onMounted } from 'vue';
@@ -28,7 +26,7 @@ onMounted(() => {
<div class="page-shell min-h-screen font-sans flex flex-col">
<header class="app-header px-6">
<div class="flex items-center gap-4">
<button type="button" class="btn-icon-ds lg:block hidden" @click="navStore.toggleSidebar()">
<button type="button" class="btn-icon-ds md:block hidden" @click="navStore.toggleSidebar()">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M9 3v18"/></svg>
</button>
<button type="button" class="btn-icon-ds" @click="router.push('/workspace')">
@@ -44,10 +42,9 @@ onMounted(() => {
<AppHeaderTools />
</header>
<!-- lg 起才并排侧栏;768px 平板保持上下堆叠,避免诊断等运维页主内容被挤窄 -->
<main class="flex-1 w-full mx-auto px-4 md:px-8 py-6 md:py-8 flex flex-col lg:flex-row gap-6 lg:gap-8 items-start">
<main class="flex-1 w-full mx-auto px-4 md:px-8 py-6 md:py-8 flex flex-col md:flex-row gap-8 items-start">
<AdminNav />
<section class="flex-1 min-w-0 w-full space-y-8">
<section class="flex-1 min-w-0 space-y-8 w-full">
<router-view />
</section>
</main>
@@ -0,0 +1,76 @@
/**
* features/auth/api/auth.api.ts
* 用途:封装登录、Casdoor/企微回调、注册和密码重置等认证域 HTTP 请求。
* 依赖:shared/api/client。
* 逻辑:auth views 与 composables 只调用本模块;后端暂保留 /api/user 路径以兼容既有接口。
*/
import { requestJson } from '@/shared/api/client';
export interface PasswordLoginInput {
username: string;
password: string;
}
/** 使用当前认证模式的登录端点完成用户名密码认证。 */
export const loginWithPassword = (api: string, input: PasswordLoginInput) =>
requestJson<Record<string, unknown>>(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input),
});
/** 将 Casdoor 授权码兑换为 HXOPS 登录会话。 */
export const loginWithCasdoorCode = (api: string, code: string, state: string | null) =>
requestJson<Record<string, unknown>>(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, state }),
});
/** 读取 Casdoor 授权地址及后端签发的 state。 */
export const getCasdoorAuthorizeUrl = (api: string, query: URLSearchParams) =>
requestJson<{ url?: string; state?: string }>(`${api}?${query.toString()}`);
/** 将企微授权码兑换为 HXOPS 登录会话。 */
export const loginWithWecomCode = (api: string, code: string, state: string | null) =>
requestJson<Record<string, unknown>>(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, state }),
});
/** 读取企微授权地址及后端签发的 state。 */
export const getWecomAuthorizeUrl = (api: string, redirectUri: string) =>
requestJson<{ url?: string; state?: string }>(`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`);
/** 完成企微首次登录所需的本地用户匹配。 */
export const completeWecomBind = (api: string, input: { binding_token: string; field: string; value: string }) =>
requestJson<Record<string, unknown>>(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input),
});
/** 从登录页发起企业微信密码重置通知。 */
export const requestPasswordResetByWecom = (employeeId: string, username: string) =>
requestJson('/api/user/reset-password-by-wecom', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ employee_id: employeeId, username }),
});
/** 使用重置链接中的 token 设置新密码。 */
export const confirmPasswordReset = (token: string, newPassword: string) =>
requestJson('/api/user/reset-password-confirm', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, new_password: newPassword }),
});
/** 注册 HXOPS 用户;后端负责后续 Casdoor 用户同步。 */
export const registerUser = (form: Record<string, unknown>) =>
requestJson('/api/user/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(form),
});
@@ -1,6 +1,8 @@
/**
* features/auth/composables/useLogin.ts
* 登录页编排层:组合认证、公告展示与 OAuth 回调,provide 给 LoginView 子组件。
* 依赖:auth.store、linked-nav.store、useLoginAuth、useLoginLanding。
* 逻辑:登录成功后预取关联服务侧栏入口,减少进入 Chat/工作台后的入口闪现。
*/
import { onMounted, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
@@ -12,6 +14,8 @@ import { useAuthStore } from '@/features/auth/stores/auth.store';
import loginBg from '@/assets/login-bg.png';
import { DEFAULT_POST_LOGIN_AGENT_ID } from '@/features/workspace/types/workspace.types';
import { useWorkspaceLocale } from '@/features/workspace/composables/useWorkspaceLocale';
import { continuationLocation, readSsoContinuation } from '@/features/sso';
import { useLinkedNavStore } from '@/features/sso/stores/linked-nav.store';
import { useLoginAuth } from './useLoginAuth';
import { useLoginLanding } from './useLoginLanding';
@@ -21,6 +25,7 @@ export function useLogin() {
const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();
const linkedNav = useLinkedNavStore();
const { setThemePreference, appliedTheme } = useTheme();
const deps = { t, locale, msg, router, route, setThemePreference, appliedTheme };
@@ -28,11 +33,23 @@ export function useLogin() {
const completePasswordLogin = async () => {
authStore.syncFromStorage();
void linkedNav.ensureLoaded({ force: true });
const continuation = readSsoContinuation();
if (continuation) {
await router.replace(continuationLocation(continuation));
return;
}
await router.replace(`/chat/${DEFAULT_POST_LOGIN_AGENT_ID}`);
};
const completeOAuthLogin = async () => {
authStore.syncFromStorage();
void linkedNav.ensureLoaded({ force: true });
const continuation = readSsoContinuation();
if (continuation) {
await router.replace(continuationLocation(continuation));
return;
}
await router.replace('/workspace/applications');
};
@@ -58,7 +75,8 @@ export function useLogin() {
authStore.syncFromStorage();
if (authStore.isLoggedIn) {
await router.replace('/workspace/applications');
const continuation = readSsoContinuation();
await router.replace(continuation ? continuationLocation(continuation) : '/workspace/applications');
return;
}
@@ -2,7 +2,7 @@
* features/auth/composables/useLoginAuth.ts
*
* 用途:封装登录表单、记住我偏好、企微/Casdoor OAuth 回调、注册与找回密码逻辑。
* 依赖:shared/utils/auth、requestJson、WeCom/Casdoor 工具函数。
* 依赖:shared/utils/auth、auth.api、WeCom/Casdoor 工具函数。
* 逻辑:密码登录成功后根据“记住我”同步本地登录态与 remembered username/password;
* OAuth 登录仅负责认证,不自动写入 remember 偏好,避免用户未明确选择时持久化登录页账号。
*/
@@ -22,7 +22,17 @@ import {
saveRememberedLoginPreference,
saveRememberedLoginProfile,
} from '@/shared/utils/auth';
import { BusinessError, requestJson } from '@/shared/api/client';
import { BusinessError } from '@/shared/api/client';
import {
completeWecomBind,
getCasdoorAuthorizeUrl,
getWecomAuthorizeUrl,
loginWithCasdoorCode,
loginWithPassword,
loginWithWecomCode,
registerUser,
requestPasswordResetByWecom,
} from '../api/auth.api';
import { DEFAULT_POST_LOGIN_AGENT_ID } from '@/features/workspace/types/workspace.types';
import type { WecomBindPromptState, WecomLoginDialogContent } from '@/features/workspace/types/workspace.types';
import type { LoginDeps } from './login.deps';
@@ -127,11 +137,7 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
return;
}
try {
await requestJson('/api/user/reset-password-by-wecom', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ employee_id: employeeId, username }),
});
await requestPasswordResetByWecom(employeeId, username);
msg.success(t('login.passwordResetWecomSent'));
showForgotPasswordModal.value = false;
forgotPasswordForm.value = { employee_id: '', username: '' };
@@ -173,13 +179,9 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
const loginApi = isCasdoorMode
? (config.auth?.casdoor?.passwordLoginApi || '/api/user/casdoor/password-login')
: '/api/user/login';
const user = await requestJson<Record<string, unknown>>(loginApi, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: loginUsername.value.trim(),
password: loginPassword.value,
}),
const user = await loginWithPassword(loginApi, {
username: loginUsername.value.trim(),
password: loginPassword.value,
});
persistLoginUser(user);
@@ -221,11 +223,7 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
}
try {
const api = config.auth.casdoor.loginApi || '/api/user/casdoor/login';
const data = await requestJson<Record<string, unknown>>(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, state }),
});
const data = await loginWithCasdoorCode(api, code, state);
persistLoginUser(data);
sessionStorage.removeItem('hxops_casdoor_state');
await completeOAuthLogin();
@@ -267,7 +265,7 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
const qs = new URLSearchParams({ redirect_uri: redirectUri, default_provider: 'wecom' });
const hint = (config.auth.casdoor as { wecomProviderHint?: string }).wecomProviderHint?.trim();
if (hint) qs.set('provider_hint', hint);
const data = await requestJson<{ url?: string; state?: string }>(`${api}?${qs.toString()}`);
const data = await getCasdoorAuthorizeUrl(api, qs);
if (!data?.url) {
msg.error(t('login.wecomStartFailed'));
return;
@@ -280,9 +278,7 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
const callbackPath = wecomCfg.callbackPath || '/login';
const redirectUri = `${window.location.origin}${callbackPath}`;
const api = wecomCfg.authorizeApi || '/api/user/wecom/authorize-url';
const data = await requestJson<{ url?: string; state?: string }>(
`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`,
);
const data = await getWecomAuthorizeUrl(api, redirectUri);
if (!data?.url) {
msg.error(t('login.wecomStartFailed'));
return;
@@ -336,14 +332,10 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
wecomBindPrompt.value.error = '';
try {
const api = config.auth.wecom.completeBindApi || '/api/user/wecom/complete-bind';
const data = await requestJson<Record<string, unknown>>(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
binding_token: wecomBindPrompt.value.binding_token,
field: wecomBindPrompt.value.field,
value: wecomBindPrompt.value.value.trim(),
}),
const data = await completeWecomBind(api, {
binding_token: wecomBindPrompt.value.binding_token,
field: wecomBindPrompt.value.field,
value: wecomBindPrompt.value.value.trim(),
});
wecomLoginDialog.value = null;
persistLoginUser(data);
@@ -389,11 +381,7 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
isWecomLoggingIn.value = true;
try {
const api = config.auth.wecom.loginApi || '/api/user/wecom/login';
const data = await requestJson<Record<string, unknown>>(api, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, state }),
});
const data = await loginWithWecomCode(api, code, state);
wecomLoginDialog.value = null;
persistLoginUser(data);
sessionStorage.removeItem('hxops_wecom_state');
@@ -434,11 +422,7 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
return;
}
try {
await requestJson('/api/user/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(form),
});
await registerUser(form);
msg.success(t('register.success'));
showRegisterModal.value = false;
registerForm.value = {
+2 -13
View File
@@ -1,18 +1,7 @@
/**
* features/auth/index.ts
* 认证 feature 对外导出:store、登录 composable、用户 API。
* 认证 feature 对外导出:store、登录 composable 与认证 API。
*/
export { useAuthStore, bindAuthStoreSync } from './stores/auth.store';
export { useLogin } from './composables/useLogin';
export {
getUserProfile,
getLeaveBalance,
submitLeaveWorkflow,
resetPasswordByWecom,
resetPasswordConfirm,
getUserAgent,
listUserAgents,
listAgentGuides,
type LeaveBalanceResult,
type LeaveWorkflowSubmitResult,
} from './api/user.api';
export * from './api/auth.api';
@@ -2,7 +2,7 @@
/**
* features/auth/views/ResetPasswordView.vue
* 企微 textcard / 邮件链接重置密码页(/reset-password?token=...)。
* 依赖:user.api resetPasswordConfirm、vue-i18n、MinimalShell。
* 依赖:auth.api confirmPasswordReset、vue-i18n、MinimalShell。
* 逻辑:校验 token 与两次密码一致后调 confirm 接口,成功后跳转 /login。
*/
import { onMounted, ref } from 'vue';
@@ -10,7 +10,7 @@ import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { Lock, AlertCircle, CheckCircle } from 'lucide-vue-next';
import MinimalShell from '@/shared/layouts/MinimalShell.vue';
import { resetPasswordConfirm } from '@/features/auth/api/user.api';
import { confirmPasswordReset } from '@/features/auth/api/auth.api';
import { BusinessError } from '@/shared/api/client';
import { resolveCasdoorErrorMessage } from '@/shared/utils/casdoor';
@@ -65,7 +65,7 @@ onMounted(() => {
/**
* 提交新密码并重置 token。
* 核心逻辑:前端校验 → resetPasswordConfirm → 成功 3 秒后跳转登录页。
* 核心逻辑:前端校验 → confirmPasswordReset → 成功 3 秒后跳转登录页。
*/
const handleReset = async () => {
if (!token.value) {
@@ -91,7 +91,7 @@ const handleReset = async () => {
message.value = '';
try {
await resetPasswordConfirm(token.value, password.value);
await confirmPasswordReset(token.value, password.value);
status.value = 'success';
message.value = t('resetPassword.successRedirect');
setTimeout(() => {
@@ -0,0 +1,751 @@
/**
* features/chat/components/messages/ContractReviewResultCard.vue
* 用途:在聊天会话中渲染采购合同审查结果卡(改动项、独立风险项 + 下载报告)。
* 依赖:vue-i18n、procurement-contract.api、chat.types。
* 逻辑:queued/running 展示审核步骤;成功后按来源拆分合同改动与独立风险;比对模式不展示 OCR 待确认主列表。
*/
<script setup lang="ts">
import { computed, onUnmounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Check, Loader2 } from 'lucide-vue-next';
import {
downloadChatAnnotatedContract,
downloadChatContractReviewReport,
getChatContractReview,
type ContractClauseItem,
type ContractReviewRow,
} from '@/features/admin/api/procurement-contract.api';
import { useMessage } from '@/shared/composables/useMessage';
import type { ChatMessage } from '../../types/chat.types';
const props = defineProps<{ message: ChatMessage }>();
const { t } = useI18n();
const msg = useMessage();
const downloading = ref(false);
const downloadingAnnotated = ref(false);
const latestReview = ref<ContractReviewRow | null>(null);
let refreshTimer: ReturnType<typeof window.setTimeout> | undefined;
let refreshing = false;
let disposed = false;
const review = computed<ContractReviewRow | null>(() => {
if (latestReview.value) return latestReview.value;
const raw = props.message.payload;
return raw && typeof raw === 'object' ? raw as ContractReviewRow : null;
});
const clauses = computed<ContractClauseItem[]>(() =>
Array.isArray(review.value?.clauses_json) ? review.value.clauses_json : [],
);
const isCompareMode = computed(() => review.value?.review_mode === 'compare');
const confirmedChangeTypes = new Set(['insert', 'delete', 'modify']);
const independentRiskTypes = new Set(['missing', 'rule_scan', 'policy_scan', 'llm_scan']);
const changeClauses = computed(() => clauses.value.filter((clause) =>
confirmedChangeTypes.has(clause.change_type || ''),
));
const independentRiskClauses = computed(() => clauses.value.filter((clause) =>
independentRiskTypes.has(clause.change_type || '')
&& clause.risk_level !== 'ok'
&& clause.validation_status !== 'needs_review',
));
/** 比对模式不展示待确认主列表;单份模式仅保留策略 OCR 待确认。 */
const confirmationClauses = computed(() => {
if (isCompareMode.value) return [];
return clauses.value.filter((clause) =>
clause.change_type === 'ocr_uncertain' || clause.validation_status === 'needs_review',
);
});
const clauseSections = computed(() => {
const sections = [
{ key: 'changes', title: t('chat.procurementContract.sectionChanges'), clauses: changeClauses.value },
{ key: 'risks', title: t('chat.procurementContract.sectionIndependentRisks'), clauses: independentRiskClauses.value },
];
if (!isCompareMode.value) {
sections.push({
key: 'confirmations',
title: t('chat.procurementContract.sectionConfirmations'),
clauses: confirmationClauses.value,
});
}
return sections.filter((section) => section.clauses.length > 0);
});
const changeCount = computed(() => review.value?.total_change_count ?? changeClauses.value.length);
const comparisonQuality = computed<Record<string, unknown>>(() => {
const raw = review.value?.summary_json?.comparison_quality;
return raw && typeof raw === 'object' ? raw as Record<string, unknown> : {};
});
const comparisonScope = computed<Record<string, unknown>>(() => {
const raw = review.value?.summary_json?.comparison_scope;
return raw && typeof raw === 'object' ? raw as Record<string, unknown> : {};
});
const attachmentComparison = computed<Record<string, unknown>>(() => {
const raw = review.value?.summary_json?.attachment_comparison;
return raw && typeof raw === 'object' ? raw as Record<string, unknown> : {};
});
const attachmentNotice = computed(() => {
const status = String(attachmentComparison.value.status || '');
const added = Number(attachmentComparison.value.added_pages || 0);
const removed = Number(attachmentComparison.value.removed_pages || 0);
if (status === 'added' && added > 0) return t('chat.procurementContract.attachmentAdded', { count: added });
if (status === 'removed' && removed > 0) return t('chat.procurementContract.attachmentRemoved', { count: removed });
return '';
});
const confirmationTotal = computed(() => {
if (isCompareMode.value) return 0;
const raw = comparisonQuality.value.needs_confirmation;
return typeof raw === 'number' ? raw : confirmationClauses.value.length;
});
const confirmationHiddenCount = computed(() => Math.max(0, confirmationTotal.value - confirmationClauses.value.length));
const isProcessing = computed(() => ['queued', 'running'].includes(review.value?.status || ''));
interface ReviewProgressStep {
stage: string;
label: string;
milestone: number;
state: 'completed' | 'active' | 'pending';
}
const REVIEW_PROGRESS_STAGE_ORDER = [
'queued',
'extracting',
'structuring',
'deterministic_review',
'llm_reviewing',
'validating',
'success',
];
/**
* 构建完整审核步骤轨道,并根据后端 processing_stage 标记已完成、当前和未开始阶段。
* 核心逻辑:阶段顺序由前后端稳定协议确定;比对与单份审核仅替换确定性审核步骤文案。
* @returns 含阶段文案、里程碑进度和展示状态的七步轨道
*/
const reviewProgressSteps = computed<ReviewProgressStep[]>(() => {
const currentStage = review.value?.processing_stage || 'queued';
const currentIndex = Math.max(0, REVIEW_PROGRESS_STAGE_ORDER.indexOf(currentStage));
const labels = [
t('chat.procurementContract.stepQueued'),
t('chat.procurementContract.stepExtracting'),
t('chat.procurementContract.stepStructuring'),
t(review.value?.review_mode === 'solo'
? 'chat.procurementContract.stepRiskScanning'
: 'chat.procurementContract.stepComparing'),
t('chat.procurementContract.stepAiReviewing'),
t('chat.procurementContract.stepValidating'),
t('chat.procurementContract.stepCompleted'),
];
const milestones = [0, 10, 30, 45, 60, 88, 100];
return REVIEW_PROGRESS_STAGE_ORDER.map((stage, index) => ({
stage,
label: labels[index] || stage,
milestone: milestones[index] ?? 0,
state: index < currentIndex ? 'completed' : index === currentIndex ? 'active' : 'pending',
}));
});
const cardStatusTitle = computed(() => {
if (isProcessing.value) return t('chat.procurementContract.reviewRunning');
if (review.value?.status === 'failed') return t('chat.procurementContract.reviewFailed');
return t('chat.procurementContract.completed');
});
const reportDownloadLabel = computed(() => t(
isCompareMode.value
? 'chat.procurementContract.downloadDifferenceReport'
: 'chat.procurementContract.downloadReport',
));
/**
* Refresh a persisted in-progress card after the user reloads or reopens a chat.
* The initial send flow also polls, but this local polling prevents an old card from freezing
* when the page was closed before its worker job reached a terminal state.
*/
function scheduleReviewRefresh(): void {
if (disposed) return;
if (refreshTimer !== undefined) {
window.clearTimeout(refreshTimer);
refreshTimer = undefined;
}
const reviewNo = review.value?.review_no;
if (!reviewNo || !isProcessing.value) return;
refreshTimer = window.setTimeout(async () => {
if (refreshing) return;
refreshing = true;
try {
latestReview.value = await getChatContractReview(reviewNo);
} catch (error) {
// A temporary network error must not turn a still-running review into a failed result.
console.warn('Failed to refresh procurement contract review', error);
} finally {
refreshing = false;
if (!disposed) scheduleReviewRefresh();
}
}, 2000);
}
watch(
() => [review.value?.review_no, isProcessing.value] as const,
() => scheduleReviewRefresh(),
{ immediate: true },
);
onUnmounted(() => {
disposed = true;
if (refreshTimer !== undefined) window.clearTimeout(refreshTimer);
});
/**
* 页头右侧风险徽标文案:有高风险时强调数量,否则提示无高风险。
* @returns 已本地化徽标文案
*/
const headerRiskBadge = computed(() => {
const high = review.value?.high_risk_count ?? 0;
if (high > 0) {
return t('chat.procurementContract.containsHighRisk', { count: high });
}
return t('chat.procurementContract.noHighRisk');
});
/**
* 比对基准来源徽标;历史库内模板显示模板库,新流程显示本次上传。
* @returns 本地化来源文案,无则 null
*/
const templateSourceLabel = computed(() => {
const source = review.value?.template_source;
if (source === 'library') return t('chat.procurementContract.sourceLibrary');
if (source === 'user_upload') return t('chat.procurementContract.sourceUpload');
return null;
});
/**
* 返回表格风险列的短标签(高 / 中 / 低),对齐原型单字徽标。
* @param level - 风险等级
* @param isComparisonChange - 是否为合同对比中的已识别差异;无风险时避免误称“通过”
*/
function riskShortLabel(level?: string | null, isComparisonChange = false): string {
if (level === 'high') return t('chat.procurementContract.riskShortHigh');
if (level === 'medium') return t('chat.procurementContract.riskShortMedium');
if (level === 'low') return t('chat.procurementContract.riskShortLow');
if (level === 'ok' && isComparisonChange) return t('chat.procurementContract.riskNoFinding');
if (level === 'ok') return t('chat.procurementContract.riskOk');
return level || '-';
}
/**
* 风险徽标样式(高/中/低/通过)。
* @param level - 风险等级
*/
function riskBadgeClass(level?: string | null): string {
if (level === 'high') return 'border-[#fecdca] bg-[#fef3f2] text-[#b42318]';
if (level === 'medium') return 'border-[#fedf89] bg-[#fffaeb] text-[#b54708]';
if (level === 'low') return 'border-[#b2ddff] bg-[#eff8ff] text-[#175cd3]';
if (level === 'ok') return 'border-[#abe6c5] bg-[#ecfdf3] text-[#067647]';
return 'border-[#d8e0ec] bg-white text-[#667792]';
}
/**
* 变更类型本地化文案。
* @param type - 变更类型
*/
function changeTypeLabel(type?: string | null): string {
if (type === 'insert') return t('chat.procurementContract.changeInsert');
if (type === 'delete') return t('chat.procurementContract.changeDelete');
if (type === 'modify') return t('chat.procurementContract.changeModify');
if (type === 'pass') return t('chat.procurementContract.changePass');
if (type === 'missing') return t('chat.procurementContract.changeMissing');
if (type === 'rule_scan') return t('chat.procurementContract.changeRuleScan');
if (type === 'policy_scan') return t('chat.procurementContract.changePolicyScan');
if (type === 'llm_scan') return t('chat.procurementContract.changeLlmScan');
if (type === 'ocr_uncertain') return t('chat.procurementContract.changeOcrUncertain');
return type || '-';
}
/**
* 条款列展示:优先可读标题(规则名 /「变更段 #N」),不用 Diff 序号。
* @param clause - 条款项
*/
function clauseLabel(clause: ContractClauseItem): string {
const title = (clause.title || '').trim();
if (title) return title;
return clause.clause_no || '-';
}
/** 展示审核证据在原 PDF 中的页码;未定位时返回空串。 */
function anchorPageLabel(clause: ContractClauseItem): string {
const pageNo = clause.evidence_anchor?.page_no;
return pageNo ? t('chat.procurementContract.anchorPage', { page: pageNo }) : '';
}
/**
* 清洗 PDF 缺字占位与私用区字符,避免豆腐字进入对照列。
* @param value - 抽取文本
*/
function cleanExtractedText(value?: string | null): string {
return (value || '')
.replace(/[\u25a0-\u25ff\ufffd\ue000-\uf8ff]+/g, ' ')
.replace(/\s+/g, ' ')
.trim();
}
/**
* 判断抽取片段是否足够可读(与后端 _is_readable_extracted_text 同口径)。
* @param value - 待展示对照文本
*/
function isReadableComparisonText(value?: string | null): boolean {
const raw = value || '';
if (!raw.trim() || raw.startsWith('[binary:')) return false;
const compactRaw = raw.replace(/\s+/g, '');
if (!compactRaw) return false;
const tofu = (compactRaw.match(/[\u25a0-\u25ff\ufffd\ue000-\uf8ff]/g) || []).length;
if (tofu / compactRaw.length >= 0.1) return false;
const cleaned = cleanExtractedText(raw).replace(/\s+/g, '');
if (cleaned.length < 4) return false;
const useful = (cleaned.match(/[\u4e00-\u9fffA-Za-z0-9]/g) || []).length;
return useful / cleaned.length >= 0.5;
}
/**
* 截取条款摘要,优先匹配标题相关商务关键词句,控制单元格宽度。
* @param value - 原文
* @param title - 条款标题(用于关键词打分)
*/
function clauseExcerpt(value: string | null | undefined, title?: string): string {
if (!isReadableComparisonText(value)) return '';
const cleaned = cleanExtractedText(value);
if (!cleaned) return '';
const sentences = cleaned.split(/(?<=[。!?;;])\s*|\s+(?=第[一二三四五六七八九十百\d]+[条章节、..])/).filter(Boolean);
const businessKeywords = ['付款', '支付', '验收', '发票', '交付', '质保', '保修', '违约', '赔偿', '管辖', '仲裁', '保密', '知识产权'];
const keywords = businessKeywords.filter((keyword) => (title || '').includes(keyword));
const matched = sentences
.map((sentence) => ({ sentence, score: keywords.filter((keyword) => sentence.includes(keyword)).length }))
.sort((a, b) => b.score - a.score)
.find((item) => item.score > 0)?.sentence;
const excerpt = matched || sentences.find((sentence) => sentence.length >= 8) || cleaned;
return excerpt.length > 180 ? `${excerpt.slice(0, 180)}...` : excerpt;
}
/**
* 组装变更对照:可读时展示模板/合同抽取片段;否则提示编码不兼容。
* 说明:对照列是抽取后的删改摘录,不是 PDF 像素级原文。
* @param clause - 条款项
*/
function clauseComparison(clause: ContractClauseItem): {
before: string;
after: string;
unreadable: boolean;
note: string;
missingBefore: boolean;
missingAfter: boolean;
unavailableReturnedSchedule: boolean;
} {
const before = clauseExcerpt(clause.old_text, clause.title);
const after = clauseExcerpt(clause.new_text, clause.title);
if (before || after) {
return { before, after, unreadable: false, note: '', missingBefore: false, missingAfter: false, unavailableReturnedSchedule: false };
}
const hasBinaryPlaceholder = [clause.old_text, clause.new_text]
.some((value) => (value || '').trim().startsWith('[binary:'));
const unreadable = clause.comparison_readable === false && hasBinaryPlaceholder;
const evidence = cleanExtractedText(clause.evidence || clause.evidence_anchor?.matched_text || '');
const fallback = cleanExtractedText(clause.detail || clause.risk_hint || '');
if (unreadable) {
return { before: '', after: '', unreadable: true, note: fallback, missingBefore: false, missingAfter: false, unavailableReturnedSchedule: false };
}
const isSchedule = /清单|设备|型号|规格|数量|单价|总价|配置/.test(`${clause.title || ''}${fallback}`);
return {
before: '', after: evidence, unreadable: false, note: evidence ? '' : fallback,
// 单边清单的正文未提取时仍明确两侧事实,避免泛化说明被误读为具体对照内容。
missingBefore: !evidence && isSchedule && clause.change_type === 'insert',
missingAfter: !evidence && isSchedule && clause.change_type === 'delete',
unavailableReturnedSchedule: !evidence && isSchedule && clause.change_type === 'insert',
};
}
/** 风险项的建议独立展示,避免误标成“对方合同原文”。 */
function clauseSuggestion(clause: ContractClauseItem): string {
return cleanExtractedText(clause.llm_suggestion || clause.suggestion || clause.negotiation_text || '');
}
type DiffPiece = { text: string; changed: boolean };
/**
* Build a compact character-level diff for one template/contract excerpt.
*
* The backend stores only the two excerpts. Computing the visual marks here keeps old review
* records readable too: removed template text is red and added counterparty text is green.
*/
function buildInlineDiff(before: string, after: string): { before: DiffPiece[]; after: DiffPiece[] } {
if (!before || !after) {
return {
before: before ? [{ text: before, changed: true }] : [],
after: after ? [{ text: after, changed: true }] : [],
};
}
let prefixLength = 0;
const maxPrefix = Math.min(before.length, after.length);
while (prefixLength < maxPrefix && before[prefixLength] === after[prefixLength]) prefixLength += 1;
let suffixLength = 0;
const beforeRemaining = before.length - prefixLength;
const afterRemaining = after.length - prefixLength;
while (
suffixLength < beforeRemaining
&& suffixLength < afterRemaining
&& before[before.length - 1 - suffixLength] === after[after.length - 1 - suffixLength]
) suffixLength += 1;
const beforeChangedEnd = before.length - suffixLength;
const afterChangedEnd = after.length - suffixLength;
const prefix = before.slice(0, prefixLength);
const suffix = suffixLength ? before.slice(beforeChangedEnd) : '';
const beforePieces: DiffPiece[] = [];
const afterPieces: DiffPiece[] = [];
if (prefix) {
beforePieces.push({ text: prefix, changed: false });
afterPieces.push({ text: prefix, changed: false });
}
if (before.slice(prefixLength, beforeChangedEnd)) {
beforePieces.push({ text: before.slice(prefixLength, beforeChangedEnd), changed: true });
}
if (after.slice(prefixLength, afterChangedEnd)) {
afterPieces.push({ text: after.slice(prefixLength, afterChangedEnd), changed: true });
}
if (suffix) {
beforePieces.push({ text: suffix, changed: false });
afterPieces.push({ text: suffix, changed: false });
}
return { before: beforePieces, after: afterPieces };
}
/**
* 下载当前会话用户的审查报告(Word .docx)。
*/
async function onDownloadReport(): Promise<void> {
const reviewNo = review.value?.review_no;
if (!reviewNo || downloading.value) return;
downloading.value = true;
try {
await downloadChatContractReviewReport(reviewNo, 'docx');
msg.success(t('chat.procurementContract.downloadOk'));
} catch (error: unknown) {
msg.warning(error instanceof Error ? error.message : t('chat.procurementContract.downloadFailed'));
} finally {
downloading.value = false;
}
}
/** 下载当前合同的 PDF 风险高亮副本。 */
async function onDownloadAnnotated(): Promise<void> {
const reviewNo = review.value?.review_no;
if (!reviewNo || downloadingAnnotated.value) return;
downloadingAnnotated.value = true;
try {
await downloadChatAnnotatedContract(reviewNo);
msg.success(t('chat.procurementContract.downloadAnnotatedOk'));
} catch (error: unknown) {
msg.warning(error instanceof Error ? error.message : t('chat.procurementContract.downloadAnnotatedFailed'));
} finally {
downloadingAnnotated.value = false;
}
}
</script>
<template>
<article
v-if="review"
class="w-full max-w-[860px] overflow-hidden rounded-2xl border border-[#d8e0ec] bg-white shadow-[0_14px_36px_rgba(23,32,51,0.08)]"
>
<!-- 页头:审查编号 + 合同/模板元信息 + 高风险徽标 -->
<div class="flex flex-wrap items-start justify-between gap-3 border-b border-[#d8e0ec] bg-[#fbfcfe] px-4 py-3.5 md:px-4">
<div class="min-w-0">
<h3 class="m-0 text-[15px] font-bold leading-snug text-[#172033]">
{{ cardStatusTitle }} · {{ review.review_no }}
</h3>
<div class="mt-1 space-y-0.5 text-xs leading-5 text-[#667792]">
<p class="m-0">
{{ t('chat.procurementContract.counterpartyContract') }}:{{ review.contract_file_name }}
</p>
<p v-if="review.contract_no" class="m-0">
{{ t('chat.procurementContract.contractNo') }}:{{ review.contract_no }}
</p>
<p v-if="review.supplier_name" class="m-0">
{{ t('chat.procurementContract.supplier') }}:{{ review.supplier_name }}
</p>
<p v-if="review.template_name" class="m-0 flex flex-wrap items-center gap-1.5">
<span>{{ t(review.review_mode === 'compare'
? 'chat.procurementContract.comparisonBaseline'
: 'chat.procurementContract.template') }}:{{ review.template_name }}</span>
<span
v-if="templateSourceLabel"
class="inline-flex items-center rounded-full border border-[#9ec5ea] bg-[#eaf4ff] px-2.5 py-0.5 text-[11px] font-semibold text-[#2f80d1]"
>
{{ templateSourceLabel }}
</span>
</p>
</div>
</div>
<span
v-if="!isProcessing"
class="inline-flex shrink-0 items-center rounded-full border px-2.5 py-1 text-xs font-semibold"
:class="review.high_risk_count > 0
? 'border-[#fecdca] bg-[#fef3f2] text-[#b42318]'
: 'border-[#abe6c5] bg-[#ecfdf3] text-[#067647]'"
>
{{ headerRiskBadge }}
</span>
</div>
<div v-if="review.error_message" class="mx-4 mt-4 rounded-xl border border-[#fecdca] bg-[#fef3f2] px-3 py-2 text-sm text-[#b42318]">
{{ review.error_message }}
</div>
<div v-if="isProcessing" class="px-4 py-5">
<div class="overflow-x-auto pb-1">
<ol class="grid min-w-[700px] grid-cols-7">
<li
v-for="(step, index) in reviewProgressSteps"
:key="step.stage"
class="relative flex min-w-0 flex-col items-center px-1 text-center"
>
<div
v-if="index > 0"
class="absolute right-1/2 top-3 h-0.5 w-full"
:class="step.state === 'pending' ? 'bg-[#d8e0ec]' : 'bg-[#2f80d1]'"
/>
<div
class="relative z-10 flex h-6 w-6 items-center justify-center rounded-full border-2 bg-white text-[10px] font-bold transition-colors duration-300"
:class="step.state === 'completed'
? 'border-[#2f80d1] bg-[#2f80d1] text-white'
: step.state === 'active'
? 'border-[#2f80d1] text-[#2f80d1] shadow-[0_0_0_4px_rgba(47,128,209,0.13)]'
: 'border-[#cfd8e5] text-[#98a5b7]'"
>
<Check v-if="step.state === 'completed'" class="h-3.5 w-3.5" />
<Loader2 v-else-if="step.state === 'active'" class="h-3.5 w-3.5 animate-spin" />
<span v-else>{{ index + 1 }}</span>
</div>
<span
class="mt-2 block text-[11px] leading-4"
:class="step.state === 'active'
? 'font-bold text-[#1f5f99]'
: step.state === 'completed'
? 'font-medium text-[#31445f]'
: 'text-[#98a5b7]'"
>
{{ step.label }}
</span>
<span
class="mt-0.5 text-[10px] tabular-nums"
:class="step.state === 'pending' ? 'text-[#b0bac8]' : 'text-[#667792]'"
>
{{ step.milestone }}%
</span>
</li>
</ol>
</div>
</div>
<div v-else class="px-4 py-3.5">
<!-- 风险统计看板 -->
<div class="mb-3.5 grid grid-cols-2 gap-2.5 md:grid-cols-4">
<div class="rounded-xl border border-[#d8e0ec] bg-[#fafbfd] px-3 py-2.5">
<div class="text-xs text-[#667792]">{{ t('chat.procurementContract.changesCount') }}</div>
<div class="mt-0.5 text-xl font-bold text-[#2f80d1]">{{ changeCount }}</div>
</div>
<div class="rounded-xl border border-[#d8e0ec] bg-[#fafbfd] px-3 py-2.5">
<div class="text-xs text-[#667792]">{{ t('chat.procurementContract.riskHigh') }}</div>
<div class="mt-0.5 text-xl font-bold text-[#b42318]">{{ review.high_risk_count }}</div>
</div>
<div class="rounded-xl border border-[#d8e0ec] bg-[#fafbfd] px-3 py-2.5">
<div class="text-xs text-[#667792]">{{ t('chat.procurementContract.riskMedium') }}</div>
<div class="mt-0.5 text-xl font-bold text-[#b54708]">{{ review.medium_risk_count }}</div>
</div>
<div class="rounded-xl border border-[#d8e0ec] bg-[#fafbfd] px-3 py-2.5">
<div class="text-xs text-[#667792]">{{ t('chat.procurementContract.riskLow') }}</div>
<div class="mt-0.5 text-xl font-bold text-[#175cd3]">{{ review.low_risk_count }}</div>
</div>
</div>
<!-- 按业务语义互斥拆分:模板改动、独立风险;比对模式不展示 OCR 待确认主列表。 -->
<div
v-if="isCompareMode && comparisonScope.status === 'fallback'"
class="mb-3 rounded-xl border border-[#fedf89] bg-[#fffaeb] px-3 py-2 text-sm text-[#b54708]"
>
{{ t('chat.procurementContract.regionFallback') }}
</div>
<div
v-if="attachmentNotice"
class="mb-3 rounded-xl border border-[#9ec5ea] bg-[#eaf4ff] px-3 py-2 text-sm font-medium text-[#1f5f99]"
>
{{ attachmentNotice }} · {{ t('chat.procurementContract.attachmentContentIgnored') }}
</div>
<div v-if="clauses.length" class="space-y-4">
<section v-for="section in clauseSections" :key="section.key" class="overflow-x-auto">
<h4 class="mb-2 text-sm font-semibold text-[#31445f]">{{ section.title }}</h4>
<table class="w-full min-w-[720px] table-fixed border-collapse text-[13px]">
<colgroup>
<col class="w-[24%]" />
<col class="w-[12%]" />
<col class="w-[44%]" />
<col class="w-[20%]" />
</colgroup>
<thead>
<tr class="bg-[#f8fafc] text-left text-xs font-semibold text-[#667792]">
<th class="border-b border-[#d8e0ec] px-2 py-2.5">{{ t('chat.procurementContract.colClause') }}</th>
<th class="border-b border-[#d8e0ec] px-2 py-2.5">{{ t('chat.procurementContract.colChange') }}</th>
<th class="border-b border-[#d8e0ec] px-2 py-2.5">
{{ section.key === 'changes'
? t('chat.procurementContract.colComparison')
: t('chat.procurementContract.colEvidence') }}
</th>
<th class="border-b border-[#d8e0ec] px-2 py-2.5">
{{ section.key === 'changes'
? t('chat.procurementContract.colRisk')
: t('chat.procurementContract.colSuggestion') }}
</th>
</tr>
</thead>
<tbody>
<tr
v-for="(clause, index) in section.clauses"
:key="`${section.key}-${clause.clause_no || clause.title || index}-${index}`"
class="align-top"
>
<td class="break-words border-b border-[#d8e0ec] px-2 py-2.5 font-medium leading-5 text-[#172033]">
{{ clauseLabel(clause) }}
<span
v-if="section.key === 'risks'"
class="ml-1 inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-semibold"
:class="riskBadgeClass(clause.risk_level)"
>
{{ riskShortLabel(clause.risk_level) }}
</span>
<span
v-if="anchorPageLabel(clause)"
class="mt-1 block text-[11px] font-normal text-[#2f80d1]"
>
{{ anchorPageLabel(clause) }}
</span>
<span
v-if="clause.validation_status === 'needs_review'"
class="ml-1 inline-flex rounded border border-[#fedf89] bg-[#fffaeb] px-1.5 py-0.5 text-[10px] font-semibold text-[#b54708]"
>{{ t('chat.procurementContract.needsReview') }}</span>
</td>
<td class="border-b border-[#d8e0ec] px-2 py-2.5 text-[#667792]">
{{ changeTypeLabel(clause.change_type) }}
</td>
<td class="border-b border-[#d8e0ec] px-2 py-2.5">
<div
v-for="cmp in [clauseComparison(clause)]"
:key="`${clause.clause_no || clause.title || index}-cmp`"
class="grid gap-1 break-words"
>
<span
v-if="cmp.before || cmp.missingBefore"
class="grid gap-1 rounded border border-[#fecdca] bg-[#fef3f2] px-2 py-1.5 text-xs leading-5 text-[#667792]"
>
<span class="font-semibold text-[#b42318]">{{ t('chat.procurementContract.colTemplateText') }}</span>
<span>
<template v-if="cmp.missingBefore">{{ t('chat.procurementContract.missingOriginalSchedule') }}</template>
<template v-for="(piece, pieceIndex) in buildInlineDiff(cmp.before, cmp.after).before" v-else :key="`before-${pieceIndex}`">
<mark v-if="piece.changed" class="rounded bg-[#fecdca] px-0.5 text-[#b42318] line-through">{{ piece.text }}</mark>
<template v-else>{{ piece.text }}</template>
</template>
</span>
</span>
<span
v-if="cmp.after || cmp.missingAfter || cmp.unavailableReturnedSchedule"
class="grid gap-1 rounded border border-[#abe6c5] bg-[#ecfdf3] px-2 py-1.5 text-xs leading-5 text-[#172033]"
>
<span class="font-semibold text-[#067647]">
{{ section.key === 'changes'
? t('chat.procurementContract.colContractText')
: t('chat.procurementContract.colEvidence') }}
</span>
<span>
<template v-if="cmp.unavailableReturnedSchedule">{{ t('chat.procurementContract.unavailableReturnedSchedule') }}</template>
<template v-else-if="cmp.missingAfter">{{ t('chat.procurementContract.missingReturnedSchedule') }}</template>
<template v-for="(piece, pieceIndex) in buildInlineDiff(cmp.before, cmp.after).after" v-else :key="`after-${pieceIndex}`">
<mark v-if="piece.changed" class="rounded bg-[#abe6c5] px-0.5 text-[#067647]">{{ piece.text }}</mark>
<template v-else>{{ piece.text }}</template>
</template>
</span>
</span>
<span
v-if="!cmp.before && !cmp.after && cmp.unreadable"
class="text-xs leading-5 text-[#b54708]"
>{{ t('chat.procurementContract.unreadableComparison') }}</span>
<span
v-else-if="!cmp.before && !cmp.after && !cmp.note"
class="text-xs text-[#667792]"
>{{ t('chat.procurementContract.noComparisonText') }}</span>
<span
v-if="cmp.note"
class="text-xs leading-5 text-[#31445f]"
>{{ cmp.note }}</span>
</div>
</td>
<td class="border-b border-[#d8e0ec] px-2 py-2.5">
<span
v-if="section.key === 'changes'"
class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold"
:class="riskBadgeClass(clause.risk_level)"
>
{{ riskShortLabel(clause.risk_level, true) }}
</span>
<span v-else class="text-xs leading-5 text-[#31445f]">
{{ clauseSuggestion(clause) || clause.detail || '-' }}
</span>
</td>
</tr>
</tbody>
</table>
<p
v-if="section.key === 'confirmations' && confirmationHiddenCount > 0"
class="mt-2 text-xs text-[#667792]"
>
{{ t('chat.procurementContract.confirmationsHidden', { count: confirmationHiddenCount }) }}
</p>
</section>
<p
v-if="confirmationTotal > 0 && confirmationClauses.length === 0"
class="rounded-xl border border-[#fedf89] bg-[#fffaeb] px-3 py-2 text-sm text-[#b54708]"
>
{{ t('chat.procurementContract.confirmationsSummary', { count: confirmationTotal }) }}
</p>
</div>
<p
v-else-if="review.status === 'success' && confirmationTotal > 0"
class="rounded-xl border border-[#fedf89] bg-[#fffaeb] px-3 py-2 text-sm text-[#b54708]"
>
{{ t('chat.procurementContract.confirmationsSummary', { count: confirmationTotal }) }}
</p>
<p v-else-if="review.status === 'success'" class="text-sm text-[#667792]">
{{ t('chat.procurementContract.noClauses') }}
</p>
</div>
<!-- 底部操作:PDF 审核固定提供标注副本下载,扫描件由后端按 OCR 页码添加批注意见。 -->
<div v-if="!isProcessing" class="flex flex-wrap gap-2 px-4 pb-3.5">
<button
type="button"
class="inline-flex h-9 items-center rounded-[10px] bg-[#2f80d1] px-3.5 text-sm font-semibold text-white transition-colors hover:bg-[#276fb8] disabled:cursor-not-allowed disabled:opacity-50"
:disabled="downloading || review.status === 'failed'"
@click="onDownloadReport"
>
{{ downloading ? t('chat.procurementContract.downloading') : reportDownloadLabel }}
</button>
<button
v-if="review.status === 'success' && review.contract_file_name?.toLowerCase().endsWith('.pdf')"
type="button"
class="inline-flex h-9 items-center rounded-[10px] border border-[#9ec5ea] bg-[#eaf4ff] px-3.5 text-sm font-semibold text-[#2f80d1] transition-colors hover:bg-[#dceeff] disabled:cursor-not-allowed disabled:opacity-50"
:disabled="downloadingAnnotated"
@click="onDownloadAnnotated"
>
{{ downloadingAnnotated
? t('chat.procurementContract.downloading')
: t('chat.procurementContract.downloadAnnotated') }}
</button>
</div>
</article>
</template>
@@ -0,0 +1,264 @@
/**
* features/chat/composables/useProcurementContractChat.ts
* 用途:采购合同审查 Agent 的会话态(模式、双文件输入、异步发起与进度轮询)。
* 依赖:procurement-contract.api、file-assets.api、agent-registry.utils。
* 逻辑:模板比对要求我方原合同与卖方回传合同;单份审核仅要求待审合同,结果卡可在刷新后回放。
*/
import { computed, ref, watch, type ComputedRef, type Ref } from 'vue';
import {
getChatContractReview,
startChatContractReview,
type ContractReviewRow,
} from '@/features/admin/api/procurement-contract.api';
import { uploadFileAsset } from '@/shared/api/file-assets.api';
import {
isProcurementContractAgent as resolveProcurementContractAgent,
type AgentRegistryFields,
} from '@/shared/utils/agent-registry.utils';
import type { ChatMessage } from '../types/chat.types';
import type { PendingAttachment } from '../types/shipping.types';
export type ContractReviewMode = 'compare' | 'solo';
const REVIEW_POLL_INTERVAL_MS = 2000;
const REVIEW_POLL_TIMEOUT_MS = 10 * 60 * 1000;
export interface ProcurementContractChatOptions {
currentAgent: Ref<AgentRegistryFields | null>;
currentAgentId: ComputedRef<number>;
attachments: Ref<PendingAttachment[]>;
messages: Ref<ChatMessage[]>;
isThinking: Ref<boolean>;
isUploadingAttachments: Ref<boolean>;
input: Ref<string>;
clearAttachments: () => void;
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
loadHistory: () => Promise<void>;
msg: { warning: (text: string) => void; success: (text: string) => void; info: (text: string) => void };
t: (key: string, params?: Record<string, unknown>) => string;
}
/**
* 从审查 API 结果构建结果卡 payload(去掉过大的冗余后仍保留 Diff/红线数据)。
*/
function buildReviewResultPayload(review: ContractReviewRow): ContractReviewRow {
return {
id: review.id,
review_no: review.review_no,
review_mode: review.review_mode,
status: review.status,
contract_file_name: review.contract_file_name,
supplier_name: review.supplier_name,
contract_no: review.contract_no,
contract_type: review.contract_type,
template_id: review.template_id,
template_source: review.template_source,
template_name: review.template_name,
total_change_count: review.total_change_count,
high_risk_count: review.high_risk_count,
medium_risk_count: review.medium_risk_count,
low_risk_count: review.low_risk_count,
user_id: review.user_id,
user_name: review.user_name,
error_message: review.error_message,
started_at: review.started_at,
finished_at: review.finished_at,
created_at: review.created_at,
progress: review.progress,
processing_stage: review.processing_stage,
processing_message: review.processing_message,
summary_json: review.summary_json,
clauses_json: review.clauses_json,
report_text: review.report_text,
};
}
/**
* 轮询单次合同审核直到成功、失败或达到前端等待上限。
* 核心逻辑:后端任务继续独立运行;前端超时只停止本页等待,不取消后台审核。
* @param reviewNo - 后端返回的合同审查编号
* @param onProgress - 每轮查询后更新当前消息卡
*/
async function pollContractReview(
reviewNo: string,
onProgress: (review: ContractReviewRow) => void,
): Promise<ContractReviewRow> {
const startedAt = Date.now();
while (Date.now() - startedAt < REVIEW_POLL_TIMEOUT_MS) {
const review = await getChatContractReview(reviewNo);
onProgress(review);
if (review.status === 'success' || review.status === 'failed') return review;
await new Promise((resolve) => window.setTimeout(resolve, REVIEW_POLL_INTERVAL_MS));
}
throw new Error('contract review polling timed out');
}
/**
* 采购合同审查 Chat 编排。
*/
export function useProcurementContractChat(options: ProcurementContractChatOptions) {
const isProcurementContractAgent = computed(() =>
resolveProcurementContractAgent(options.currentAgent.value),
);
const reviewMode = ref<ContractReviewMode>('compare');
const originalContractAssetNo = ref<string | null>(null);
const originalContractName = ref<string | null>(null);
const allowsSendWithAttachmentsOnly = computed(
() => isProcurementContractAgent.value && (
options.attachments.value.some((a) => a.kind === 'local')
|| (reviewMode.value === 'compare' && Boolean(originalContractAssetNo.value))
),
);
watch(
isProcurementContractAgent,
(active) => {
if (!active) {
reviewMode.value = 'compare';
originalContractAssetNo.value = null;
originalContractName.value = null;
}
},
{ immediate: true },
);
/**
* 上传合同比对所需的我方原合同,仅作为本次审核基准,不进入模板库。
*/
async function handleOriginalContractSelected(event: Event): Promise<void> {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = '';
if (!file) return;
options.isUploadingAttachments.value = true;
try {
const asset = await uploadFileAsset(file);
originalContractAssetNo.value = asset.asset_no;
originalContractName.value = asset.original_filename || file.name;
} catch (e: unknown) {
options.msg.warning(e instanceof Error ? e.message : options.t('chat.procurementContract.uploadFailed'));
} finally {
options.isUploadingAttachments.value = false;
}
}
/**
* 清除已上传的我方原合同基准。
*/
function clearOriginalContract(): void {
originalContractAssetNo.value = null;
originalContractName.value = null;
}
/**
* 拦截带本地附件的发送:上传 FileAsset → 创建异步审查 → 轮询进度 → 写入最终结果卡。
* @returns true 表示已消费本次发送
*/
async function tryHandleProcurementContractSend(
textOrEvent: string | Event | undefined,
_content: string,
trimmed: string,
): Promise<boolean> {
if (!isProcurementContractAgent.value) return false;
const locals = options.attachments.value.filter(
(a): a is Extract<PendingAttachment, { kind: 'local' }> => a.kind === 'local',
);
if (!locals.length) {
if (reviewMode.value === 'compare' && originalContractAssetNo.value) {
options.msg.warning(options.t('chat.procurementContract.compareFilesRequired'));
return true;
}
return false;
}
if (options.isThinking.value || options.isUploadingAttachments.value) return true;
if (locals.length > 1) {
options.msg.warning(options.t('chat.procurementContract.oneContractOnly'));
return true;
}
if (reviewMode.value === 'compare' && !originalContractAssetNo.value) {
options.msg.warning(options.t('chat.procurementContract.compareFilesRequired'));
return true;
}
const contractFile = locals[0]!.file;
options.isUploadingAttachments.value = true;
options.isThinking.value = true;
try {
// [STEP 1] 上传待审合同
const contractAsset = await uploadFileAsset(contractFile);
// [STEP 2] 比对模式固定以用户上传的我方原合同作为基准,不再读取默认模板。
const queuedReview = await startChatContractReview({
review_mode: reviewMode.value,
contract_asset_no: contractAsset.asset_no,
original_contract_asset_no:
reviewMode.value === 'compare' ? originalContractAssetNo.value : null,
contract_type: 'general_procurement',
agent_id: options.currentAgentId.value || null,
});
// [STEP 3] 立即显示用户消息和排队进度卡
const userText =
trimmed
|| options.t('chat.procurementContract.defaultUserQuery', {
file: contractFile.name,
mode:
reviewMode.value === 'solo'
? options.t('chat.procurementContract.modeSolo')
: options.t('chat.procurementContract.modeCompare'),
});
const userMsg: ChatMessage = { role: 'user', content: userText, type: 'text' };
options.messages.value.push(userMsg);
const assistantMsg: ChatMessage = {
role: 'assistant',
type: 'procurement-contract-review',
content: options.t('chat.procurementContract.reviewQueued'),
payload: buildReviewResultPayload(queuedReview),
};
options.messages.value.push(assistantMsg);
if (typeof textOrEvent !== 'string') options.input.value = '';
options.clearAttachments();
clearOriginalContract();
options.isUploadingAttachments.value = false;
options.isThinking.value = false;
// [STEP 4] 后台完成后原地替换进度卡,再持久化正式结果。
const review = await pollContractReview(queuedReview.review_no, (latest) => {
assistantMsg.payload = buildReviewResultPayload(latest);
assistantMsg.content = latest.processing_message || options.t('chat.procurementContract.reviewRunning');
});
if (review.status === 'failed') {
throw new Error(review.error_message || options.t('chat.procurementContract.reviewFailed'));
}
assistantMsg.payload = buildReviewResultPayload(review);
assistantMsg.content =
review.summary_json && typeof review.summary_json.headline === 'string'
? String(review.summary_json.headline)
: options.t('chat.procurementContract.resultTitle');
await options.saveLocalMessageToBackend(assistantMsg, userText);
await options.loadHistory();
} catch (e: unknown) {
options.msg.warning(
e instanceof Error ? e.message : options.t('chat.procurementContract.reviewFailed'),
);
} finally {
options.isUploadingAttachments.value = false;
options.isThinking.value = false;
}
return true;
}
return {
isProcurementContractAgent,
reviewMode,
originalContractAssetNo,
originalContractName,
allowsSendWithAttachmentsOnly,
handleOriginalContractSelected,
clearOriginalContract,
tryHandleProcurementContractSend,
};
}
@@ -0,0 +1,39 @@
/**
* features/chat/leave/leave.api.ts
* 用途:封装聊天请假流程的余额查询与 OA 工作流提交请求。
* 依赖:shared/utils/auth、shared/api/client。
* 逻辑:聊天请假表单调用本模块;后端暂保留 /api/user/leave-* 路径以兼容既有接口。
*/
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
import type { LeaveRequestFormData } from '../types/leave.types';
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
export interface LeaveBalanceResult {
has_balance: boolean;
leave_type_label: string;
year: number;
total_hours: number | null;
used_hours: number | null;
remaining_hours: number | null;
}
/** 查询当前用户指定假别的可用余额。 */
export const getLeaveBalance = (leaveType: string) =>
requestJson<LeaveBalanceResult>(`/api/user/leave-balance?leave_type=${encodeURIComponent(leaveType)}`, auth());
export interface LeaveWorkflowSubmitResult {
request_id?: string;
submitted_at?: string;
request_name?: string;
}
/** 将聊天内确认后的请假表单提交至 OA 工作流。 */
export const submitLeaveWorkflow = (form: LeaveRequestFormData) =>
requestJson<LeaveWorkflowSubmitResult>('/api/user/leave-workflow/submit', {
method: 'POST',
...jsonAuth(),
body: JSON.stringify(form),
});
@@ -26,6 +26,13 @@ export const DEFAULT_TRAINING_HR_CHAT_QUESTIONS = [
'我想查看本月培训成绩统计',
];
/** 返回指定培训角色的默认问题,供管理表单初始化使用。 */
export const getDefaultTrainingChatQuestions = (role: TrainingChatQuestionRole): string[] => (
role === 'hr'
? cloneQuestions(DEFAULT_TRAINING_HR_CHAT_QUESTIONS)
: cloneQuestions(DEFAULT_TRAINING_EMPLOYEE_CHAT_QUESTIONS)
);
const asRecord = (value: unknown): Record<string, unknown> => (
value && typeof value === 'object' && !Array.isArray(value)
? value as Record<string, unknown>
@@ -49,11 +56,7 @@ const normalizeTrainingChatQuestionList = (value: unknown): string[] => {
.filter(Boolean);
};
const getDefaultQuestions = (role: TrainingChatQuestionRole) => (
role === 'hr'
? cloneQuestions(DEFAULT_TRAINING_HR_CHAT_QUESTIONS)
: cloneQuestions(DEFAULT_TRAINING_EMPLOYEE_CHAT_QUESTIONS)
);
const getDefaultQuestions = getDefaultTrainingChatQuestions;
/**
* 读取培训配置中的角色化聊天常见问题。
@@ -216,7 +216,7 @@ export interface ChatMessage {
content: string;
/** 用户提交时固化的附件展示快照;助手消息不使用此字段。 */
attachments?: ChatMessageAttachment[];
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result' | 'maintenance-device-result';
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result' | 'maintenance-device-result' | 'procurement-contract-review';
retriever_resources?: RetrieverResource[];
attribution_parts?: string[];
chat_log_id?: number;
@@ -0,0 +1,28 @@
/**
* 用途:验证 Mermaid 兼容规范化,防止中文分组标题再次导致流程图解析失败。
* 依赖:vitest、mermaidChart。
* 逻辑:覆盖无 ID 中文 subgraph 的标准化以及原本标准语法的不变性。
*/
import { describe, expect, it } from 'vitest';
import { buildMermaidFlowFallbackHtml, normalizeMermaidChart } from './mermaidChart';
describe('normalizeMermaidChart', () => {
it('为中文 subgraph 标题补齐可解析的 ASCII ID', () => {
// 断言:Dify 常见的中文分组写法被转为 Mermaid 标准分组声明。
expect(normalizeMermaidChart('graph TD\nsubgraph 项目启动阶段\nA[接单]\nend'))
.toContain('subgraph group_1["项目启动阶段"]');
});
it('保留已有 ID 的标准 subgraph', () => {
// 断言:已规范的 Mermaid 不被重复改写。
expect(normalizeMermaidChart('subgraph phase_start["项目启动阶段"]'))
.toBe('subgraph phase_start["项目启动阶段"]');
});
it('将无法解析的主流程降级为可视化卡片', () => {
// 断言:即使 Mermaid 语法异常,用户仍能看到节点和顺序,而不是红色源码。
const html = buildMermaidFlowFallbackHtml('A[接单] --> B[项目立项]\nB --> C[项目启动阶段]');
expect(html).toContain('接单');
expect(html).toContain('项目启动阶段');
});
});
@@ -0,0 +1,71 @@
/**
* 用途:规范化智能体输出的 Mermaid 图表文本,兼容中文分组标题等常见非标准写法。
* 依赖:由 ChatMessageBubble 在调用 mermaid.render 前使用。
* 逻辑:保留合法语句不变;仅为没有 ID 的 subgraph 补充稳定 ASCII ID 与带引号标题,
* 避免 Mermaid 把中文标题解析为图语法 token 而导致整张流程图无法显示。
*/
/**
* 用途:将常见的中文 Mermaid 分组语法转换为 Mermaid 可稳定解析的标准形式。
* AI 触发时机:智能体返回 `subgraph 项目启动阶段` 等没有 ASCII 节点 ID 的分组标题时调用。
* 核心逻辑:逐行识别 subgraph;已经包含 ID、方括号或引号的标准写法不变;其余标题生成唯一 ID。
* 参数与输出约束:输入必须为 Mermaid 文本;输出只调整 subgraph 声明,不修改节点、连线及 end 语句。
*/
export function normalizeMermaidChart(source: string): string {
let subgraphIndex = 0;
return String(source || '')
.replace(/^\s*graph\s+/im, (matched) => matched.replace(/graph/i, 'flowchart'))
.split('\n')
.map((line) => {
const match = line.match(/^(\s*)subgraph\s+(.+?)\s*$/i);
if (!match) return line;
const indent = match[1] || '';
const rawTitle = (match[2] || '').trim();
if (!rawTitle || /[\[\]"']/.test(rawTitle) || /^[A-Za-z_][A-Za-z0-9_-]*\s/.test(rawTitle)) return line;
subgraphIndex += 1;
return `${indent}subgraph group_${subgraphIndex}["${rawTitle.replace(/"/g, '\\"')}"]`;
})
.join('\n')
// Mermaid 对含括号、标点或中文的节点标签需要显式引号;Dify 常会遗漏它。
.replace(/([A-Za-z][A-Za-z0-9_-]*)\[([^\]"\n]+)\]/g, (_matched, nodeId: string, label: string) => (
`${nodeId}["${label.trim().replace(/"/g, '\\"')}"]`
));
}
/**
* 用途:在 Mermaid 仍无法解析时,将简单流程图转换为可读的流程卡片。
* AI 触发时机:图表库抛出语法异常且原文中存在 `A[节点] --> B[节点]` 这类链路时调用。
* 核心逻辑:提取节点顺序和标签,输出已转义的 HTML 卡片;忽略不影响主流程的 subgraph 细节。
* 参数与输出约束:只用于展示兜底,不执行任何模型输出中的 HTML 或脚本。
*/
export function buildMermaidFlowFallbackHtml(source: string): string | null {
const labels = new Map<string, string>();
const order: string[] = [];
const text = String(source || '');
const nodePattern = /([A-Za-z][A-Za-z0-9_-]*)\s*\[\s*"?([^\]\n"]+)"?\s*\]/g;
const edgePattern = /([A-Za-z][A-Za-z0-9_-]*)(?:\s*\[[^\]\n]*\])?\s*--+>\s*([A-Za-z][A-Za-z0-9_-]*)(?:\s*\[[^\]\n]*\])?/g;
const escapeHtml = (value: string) => String(value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
for (const match of text.matchAll(nodePattern)) {
const nodeId = match[1];
const label = match[2];
if (nodeId && label) labels.set(nodeId, label.trim());
}
for (const match of text.matchAll(edgePattern)) {
const fromId = match[1];
const toId = match[2];
if (!fromId || !toId) continue;
if (!order.includes(fromId)) order.push(fromId);
if (!order.includes(toId)) order.push(toId);
}
if (order.length < 2) return null;
const cards = order.map((id, index) => {
const card = `<div class="chat-flow-fallback-card">${escapeHtml(labels.get(id) || id)}</div>`;
return index < order.length - 1 ? `${card}<div class="chat-flow-fallback-arrow" aria-hidden="true">↓</div>` : card;
});
return `<div class="chat-flow-fallback" role="img" aria-label="流程图">${cards.join('')}</div>`;
}
+32 -27
View File
@@ -1,10 +1,17 @@
/**
* features/kb/api/kb.api.ts
* 知识库 HTTP API。
* 用途:知识库 HTTP API 封装。
* 依赖:auth、requestJson/BusinessError、vue-i18n(错误 fallback 文案)。
* 逻辑:KbWorkspace / composables 调用;失败时优先保留 BusinessError.message,否则回退本地化 fallback。
*/
import i18n from '@/i18n';
import { getAuthHeaders } from '@/shared/utils/auth';
import { BusinessError, requestJson } from '@/shared/api/client';
const kbT = (key: string) => String(i18n.global.t(key));
const kbErrorMessage = (e: unknown, fallbackKey: string) =>
(e as Error).message || kbT(fallbackKey);
export interface KbGroup {
id: number;
name: string;
@@ -137,8 +144,6 @@ export interface KbListResponse<T> {
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
const kbErrorMessage = (e: unknown, fallback: string) => (e as Error).message || fallback;
const getJson = async <T>(path: string, fallback: T): Promise<T> => {
try {
return await requestJson<T>(path, auth());
@@ -156,7 +161,7 @@ const getJsonWithStatus = async <T>(path: string, fallback: T): Promise<KbListRe
return {
ok: false,
data: fallback,
error: kbErrorMessage(e, '知识库接口请求失败'),
error: kbErrorMessage(e, 'kbWorkspace.errors.apiRequestFailed'),
status: err.status,
};
}
@@ -190,7 +195,7 @@ export const createKbGroup = async (payload: {
});
return { ok: true, group };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '创建知识库分组失败') };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.createGroupFailed') };
}
};
@@ -217,7 +222,7 @@ export const updateKbDifySettings = async (
});
return { ok: true, settings };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '保存 Dify 设置失败') };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.saveDifySettingsFailed') };
}
};
@@ -235,7 +240,7 @@ export const runKbJob = async (
});
return { ok: true, job, run_result: job.run_result };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '执行任务失败') };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.executeJobFailed') };
}
};
@@ -251,7 +256,7 @@ export const createKbDocument = async (
});
return { ok: true, document };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '创建文档失败') };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.createDocumentFailed') };
}
};
@@ -267,7 +272,7 @@ export const updateKbDocument = async (
});
return { ok: true, document };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '更新文档失败') };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.updateDocumentFailed') };
}
};
@@ -278,7 +283,7 @@ export const deleteKbDocument = async (
await requestJson(`/api/kb/documents/${documentId}`, { method: 'DELETE', ...auth() });
return { ok: true };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '删除文档失败') };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.deleteDocumentFailed') };
}
};
@@ -296,7 +301,7 @@ export const getKbDocumentVersionSourceFile = async (
headers: getAuthHeaders(),
});
if (!res.ok) {
let message = '读取原始文件失败';
let message = kbT('kbWorkspace.msg.readSourceFailed');
try {
const data = await res.json();
if (typeof data?.error === 'string' && data.error.trim()) message = data.error;
@@ -316,7 +321,7 @@ export const getKbDocumentVersionSourceFile = async (
contentType: res.headers.get('content-type') || undefined,
};
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
return { ok: false, error: kbT('kbWorkspace.msg.apiNotReady') };
}
};
@@ -333,7 +338,7 @@ export const getKbDocumentMarkdown = async (
const data = await requestJson<KbDocumentMarkdown>(`/api/kb/documents/${documentId}/markdown`, auth());
return { ok: true, data };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '读取清洗后的 Markdown 失败') };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.readMarkdownFailed') };
}
};
@@ -349,7 +354,7 @@ export const updateKbDocumentMarkdown = async (
});
return { ok: true, data };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '保存 Markdown 失败') };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.saveMarkdownFailed') };
}
};
@@ -371,11 +376,11 @@ export const uploadKbDocumentVersion = async (
if (err.status === 413) {
return {
ok: false,
error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试',
error: kbT('kbWorkspace.msg.fileTooLarge'),
status: 413,
};
}
return { ok: false, error: kbErrorMessage(e, '上传文档版本失败'), status: err.status };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.uploadVersionFailed'), status: err.status };
}
};
@@ -390,7 +395,7 @@ export const submitKbDocumentClean = async (
return { ok: true, job, message: job.message || undefined };
} catch (e) {
const err = e as BusinessError;
return { ok: false, error: kbErrorMessage(e, '提交清洗任务失败'), status: err.status };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.submitCleanFailed'), status: err.status };
}
};
@@ -411,7 +416,7 @@ export const createKbPathUploadJob = async (
return { ok: true, job };
} catch (e) {
const err = e as BusinessError;
return { ok: false, error: kbErrorMessage(e, '创建路径上传任务失败'), status: err.status };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.createPathJobFailed'), status: err.status };
}
};
@@ -435,11 +440,11 @@ export const uploadKbPathJobFile = async (
if (err.status === 413) {
return {
ok: false,
error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试',
error: kbT('kbWorkspace.msg.fileTooLarge'),
status: 413,
};
}
return { ok: false, error: kbErrorMessage(e, '上传路径文件失败'), status: err.status };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.uploadPathFileFailed'), status: err.status };
}
};
@@ -455,7 +460,7 @@ export const markKbPathJobFileFailed = async (
});
return { ok: true, job };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '记录路径文件失败状态失败') };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.markPathFileFailedStatusFailed') };
}
};
@@ -469,7 +474,7 @@ export const finalizeKbPathUploadJob = async (
});
return { ok: true, job };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '提交路径上传任务失败') };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.submitPathUploadFailed') };
}
};
@@ -486,7 +491,7 @@ export const retryFailedKbPathUploadJob = async (
return { ok: true, job };
} catch (e) {
const err = e as BusinessError;
return { ok: false, error: kbErrorMessage(e, '重试失败文件失败'), status: err.status };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.retryPathFailed'), status: err.status };
}
};
@@ -502,7 +507,7 @@ export const deleteKbPathJobFile = async (
);
return { ok: true, job: result.job, document_deleted: result.document_deleted };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '删除路径上传文件失败') };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.deletePathFileFailed') };
}
};
@@ -516,7 +521,7 @@ export const syncKbDocumentToDify = async (
});
return { ok: true, job };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '同步到 Dify 失败') };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.syncDifyFailedGeneric') };
}
};
@@ -532,7 +537,7 @@ export const updateKbGroup = async (
});
return { ok: true, group };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '更新知识库分组失败') };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.updateGroupFailed') };
}
};
@@ -543,6 +548,6 @@ export const deleteKbGroup = async (
await requestJson(`/api/kb/groups/${groupId}`, { method: 'DELETE', ...auth() });
return { ok: true };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '删除知识库分组失败') };
return { ok: false, error: kbErrorMessage(e, 'kbWorkspace.msg.deleteGroupFailed') };
}
};
@@ -58,7 +58,9 @@ export const getDocumentDisplayDescription = (doc: KbDocumentItem, t: KbTranslat
return text || getDocumentDisplayTitle(doc, t);
};
/** 将后端重复文档错误归一为前端可展示的简短文案 */
/** 将后端重复文档错误归一为前端可展示的简短文案。
* [NLU] includes() 匹配后端中文错误原文,刻意保留;返回值走 i18n。
*/
export const normalizeDuplicateDocumentError = (message: string | null | undefined, t: KbTranslateFn) => {
const text = String(message || '').trim();
if (!text) return t('kbWorkspace.errors.apiRequestFailed');
@@ -122,12 +122,16 @@ export const getDocumentWorkflowState = (
let syncStage: WorkflowStageState;
if (!doc.latest_version || cleanStage.code === 'failed') {
syncStage = { code: 'idle', label: t('kbWorkspace.status.idle'), className: IDLE_BADGE_CLASS };
} else if (syncJob?.status === 'failed') {
} else if (syncJob?.status === 'failed' || (latestStatus === 'ready' && Boolean(doc.latest_version?.error_message))) {
syncStage = {
code: 'failed',
label: t('kbWorkspace.status.failed'),
className: getStatusBadgeClass('failed'),
errorMessage: normalizeWorkflowErrorMessage(syncJob.error_message || syncJob.message, 'sync', t),
errorMessage: normalizeWorkflowErrorMessage(
syncJob?.error_message || syncJob?.message || doc.latest_version?.error_message,
'sync',
t,
),
};
} else if (latestStatus === 'synced' || syncJob?.status === 'success') {
syncStage = { code: 'success', label: t('kbWorkspace.status.done'), className: getStatusBadgeClass('success') };
@@ -2,10 +2,11 @@
/**
* features/maintenance/components/MaintenanceRecordPanel.vue
* 用途:设备维保助手右侧固定面板中的“新增维修记录”页面。
* 依赖:maintenanceRecord.api、maintenanceLedger.api、MaintenanceDeviceSnapshotCard、useMessage。
* 依赖:maintenanceRecord.api、maintenanceLedger.api、MaintenanceDeviceSnapshotCard、useMessage、vue-i18n。
* 逻辑:管理员通过按钮进入固定面板后填写维修记录;设备编号失焦时查询台账快照,保存后刷新最近记录用于确认。
*/
import { computed, onMounted, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '@/shared/composables/useMessage';
import MaintenanceDeviceSnapshotCard from '@/features/maintenance/components/MaintenanceDeviceSnapshotCard.vue';
import { listMaintenanceDevices } from '@/features/maintenance/api/maintenanceLedger.api';
@@ -19,8 +20,10 @@ import type {
MaintenanceRecordPayload,
MaintenanceRepairStatus,
} from '@/features/maintenance/types/record.types';
import { repairStatusLabelKey } from '@/features/maintenance/utils/repair-status-display.utils';
const msg = useMessage();
const { t } = useI18n();
const saving = ref(false);
const deviceLoading = ref(false);
const recentLoading = ref(false);
@@ -49,24 +52,28 @@ const form = reactive<MaintenanceRecordPayload>({
});
const statusOptions: Array<{ value: MaintenanceRepairStatus | ''; label: string }> = [
{ value: '', label: '全部状态' },
{ value: 'pending', label: '待维修' },
{ value: 'processing', label: '维修中' },
{ value: 'done', label: '已完成' },
{ value: 'cancelled', label: '已取消' },
{ value: '', label: 'maintenance.record.status.all' },
{ value: 'pending', label: 'maintenance.record.status.pending' },
{ value: 'processing', label: 'maintenance.record.status.processing' },
{ value: 'done', label: 'maintenance.record.status.done' },
{ value: 'cancelled', label: 'maintenance.record.status.cancelled' },
];
const selectedStatusLabel = computed(() => {
return statusOptions.find((item) => item.value === form.repairStatus)?.label || form.repairStatus;
const key = repairStatusLabelKey(form.repairStatus);
return key ? t(key) : form.repairStatus;
});
/**
* 将状态值转换为中文展示。
* 将状态值转换为当前语言展示文案。
* @param value - 后端状态枚举。
* @returns 页面展示文案。
*/
const formatStatus = (value: string): string => {
return statusOptions.find((item) => item.value === value)?.label || value || '-';
const key = repairStatusLabelKey(value);
if (key) return t(key);
const option = statusOptions.find((item) => item.value === value);
return option ? t(option.label) : value || '-';
};
/**
@@ -103,7 +110,7 @@ const loadDeviceSnapshot = async (): Promise<void> => {
const result = await listMaintenanceDevices({ keyword: code, page: 1, pageSize: 5 });
matchedDevice.value = result.items.find((item) => item.deviceCode === code) || null;
} catch (error: any) {
msg.error(error?.message || '查询设备台账失败');
msg.error(error?.message || t('maintenance.record.messages.deviceLoadFailed'));
} finally {
deviceLoading.value = false;
}
@@ -121,12 +128,12 @@ const ensureDeviceExists = async (): Promise<boolean> => {
const result = await listMaintenanceDevices({ keyword: code, page: 1, pageSize: 5 });
matchedDevice.value = result.items.find((item) => item.deviceCode === code) || null;
if (!matchedDevice.value) {
msg.warning('设备不存在,不能新增维修记录');
msg.warning(t('maintenance.record.messages.deviceNotFound'));
return false;
}
return true;
} catch (error: any) {
msg.error(error?.message || '鏌ヨ璁惧鍙拌处澶辫触');
msg.error(error?.message || t('maintenance.record.messages.deviceLoadFailed'));
return false;
} finally {
deviceLoading.value = false;
@@ -147,7 +154,7 @@ const loadRecentRecords = async (): Promise<void> => {
});
recentRecords.value = result.items;
} catch (error: any) {
msg.error(error?.message || '查询维修记录失败');
msg.error(error?.message || t('maintenance.record.messages.loadFailed'));
} finally {
recentLoading.value = false;
}
@@ -182,7 +189,7 @@ const resetForm = (): void => {
const saveRecord = async (): Promise<void> => {
const payload = buildPayload();
if (!payload.deviceCode || !payload.reportDate || !payload.faultDescription) {
msg.warning('设备编号、报修日期和故障描述不能为空');
msg.warning(t('maintenance.record.messages.required'));
return;
}
if (!await ensureDeviceExists()) {
@@ -191,12 +198,12 @@ const saveRecord = async (): Promise<void> => {
saving.value = true;
try {
await createMaintenanceRecord(payload);
msg.success('维修记录已保存');
msg.success(t('maintenance.record.messages.saved'));
recordKeyword.value = payload.deviceCode;
resetForm();
await loadRecentRecords();
} catch (error: any) {
msg.error(error?.message || '保存维修记录失败');
msg.error(error?.message || t('maintenance.record.messages.saveFailed'));
} finally {
saving.value = false;
}
@@ -209,22 +216,22 @@ onMounted(loadRecentRecords);
<section class="flex h-full min-h-0 flex-col gap-4">
<form class="min-h-0 flex-1 overflow-auto" @submit.prevent="saveRecord">
<div class="mb-4 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900">
维修记录为管理员配置入口,查询类问题仍建议通过会话直接提问。
{{ t('maintenance.record.notice') }}
</div>
<div class="grid gap-4 md:grid-cols-2">
<label class="grid gap-1 text-sm text-secondary">
设备编号 *
{{ t('maintenance.record.fields.deviceCode') }} *
<input
v-model="form.deviceCode"
class="admin-table-filter-input"
placeholder="如 EQ-2026-001"
:placeholder="t('maintenance.record.placeholder.deviceCode')"
@blur="loadDeviceSnapshot"
@keyup.enter.prevent="loadDeviceSnapshot"
/>
</label>
<label class="grid gap-1 text-sm text-secondary">
报修日期 *
{{ t('maintenance.record.fields.reportDate') }} *
<input v-model="form.reportDate" type="date" class="admin-table-filter-input" />
</label>
</div>
@@ -239,94 +246,122 @@ onMounted(loadRecentRecords);
<div class="mt-4 grid gap-4 md:grid-cols-2">
<label class="grid gap-1 text-sm text-secondary">
维修类别
<input v-model="form.repairCategory" class="admin-table-filter-input" placeholder="日常维修 / 保养 / 点检" />
{{ t('maintenance.record.fields.repairCategory') }}
<input
v-model="form.repairCategory"
class="admin-table-filter-input"
:placeholder="t('maintenance.record.placeholder.repairCategory')"
/>
</label>
<label class="grid gap-1 text-sm text-secondary">
维修状态
{{ t('maintenance.record.fields.repairStatus') }}
<select v-model="form.repairStatus" class="admin-table-filter-input">
<option value="pending">待维修</option>
<option value="processing">维修中</option>
<option value="done">已完成</option>
<option value="cancelled">已取消</option>
<option value="pending">{{ t('maintenance.record.status.pending') }}</option>
<option value="processing">{{ t('maintenance.record.status.processing') }}</option>
<option value="done">{{ t('maintenance.record.status.done') }}</option>
<option value="cancelled">{{ t('maintenance.record.status.cancelled') }}</option>
</select>
</label>
</div>
<div class="mt-4 grid gap-4 md:grid-cols-2">
<label class="grid gap-1 text-sm text-secondary md:col-span-2">
故障描述 *
{{ t('maintenance.record.fields.faultDescription') }} *
<textarea v-model="form.faultDescription" class="admin-table-filter-input min-h-24" />
</label>
<label class="grid gap-1 text-sm text-secondary">
报修人
{{ t('maintenance.record.fields.reporter') }}
<input v-model="form.reporter" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
审批人
{{ t('maintenance.record.fields.approver') }}
<input v-model="form.approver" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
维修日期
{{ t('maintenance.record.fields.repairDate') }}
<input v-model="form.repairDate" type="date" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
维修单位
{{ t('maintenance.record.fields.repairUnit') }}
<input v-model="form.repairUnit" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
维修人
{{ t('maintenance.record.fields.repairer') }}
<input v-model="form.repairer" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
来源工单号
{{ t('maintenance.record.fields.sourceOrderNo') }}
<input v-model="form.sourceOrderNo" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
维修费用
<input v-model="form.repairCost" class="admin-table-filter-input" placeholder="如 1200.00" />
{{ t('maintenance.record.fields.repairCost') }}
<input
v-model="form.repairCost"
class="admin-table-filter-input"
:placeholder="t('maintenance.record.placeholder.repairCost')"
/>
</label>
<label class="grid gap-1 text-sm text-secondary">
维修工时
<input v-model="form.repairHours" class="admin-table-filter-input" placeholder="如 3.5h" />
{{ t('maintenance.record.fields.repairHours') }}
<input
v-model="form.repairHours"
class="admin-table-filter-input"
:placeholder="t('maintenance.record.placeholder.repairHours')"
/>
</label>
<label class="grid gap-1 text-sm text-secondary md:col-span-2">
维修说明
{{ t('maintenance.record.fields.repairDescription') }}
<textarea v-model="form.repairDescription" class="admin-table-filter-input min-h-24" />
</label>
</div>
<div class="sticky bottom-0 mt-5 flex justify-end gap-2 border-t border-default bg-surface py-3">
<button type="button" class="admin-report-page-btn" @click="resetForm">清空</button>
<button type="button" class="admin-report-page-btn" @click="resetForm">
{{ t('maintenance.record.actions.clear') }}
</button>
<button
type="submit"
class="admin-report-page-btn admin-report-page-btn--active"
:disabled="saving"
>
{{ saving ? '保存中...' : `保存为${selectedStatusLabel}` }}
{{
saving
? t('maintenance.record.actions.saving')
: t('maintenance.record.actions.saveAs', { status: selectedStatusLabel })
}}
</button>
</div>
</form>
<div class="border-t border-default pt-4">
<div class="mb-3 flex items-center justify-between gap-2">
<h3 class="text-sm font-semibold text-primary">最近维修记录</h3>
<button type="button" class="admin-report-page-btn" @click="loadRecentRecords">刷新</button>
<h3 class="text-sm font-semibold text-primary">{{ t('maintenance.record.recentTitle') }}</h3>
<button type="button" class="admin-report-page-btn" @click="loadRecentRecords">
{{ t('common.refresh') }}
</button>
</div>
<div class="mb-3 grid gap-2 md:grid-cols-[1fr_120px_72px]">
<input v-model="recordKeyword" class="admin-table-filter-input" placeholder="筛选设备编号、故障、维修人" />
<input
v-model="recordKeyword"
class="admin-table-filter-input"
:placeholder="t('maintenance.record.filters.recentKeywordPlaceholder')"
/>
<select v-model="recordStatus" class="admin-table-filter-input">
<option v-for="item in statusOptions" :key="item.value || 'all'" :value="item.value">
{{ item.label }}
{{ t(item.label) }}
</option>
</select>
<button type="button" class="admin-report-page-btn admin-report-page-btn--active" @click="loadRecentRecords">
查询
{{ t('maintenance.record.actions.search') }}
</button>
</div>
<div class="max-h-56 overflow-auto rounded-xl border border-default bg-surface">
<div v-if="recentLoading" class="px-3 py-6 text-center text-sm text-secondary">加载中...</div>
<div v-else-if="!recentRecords.length" class="px-3 py-6 text-center text-sm text-secondary">暂无维修记录</div>
<div v-if="recentLoading" class="px-3 py-6 text-center text-sm text-secondary">
{{ t('maintenance.record.table.loading') }}
</div>
<div v-else-if="!recentRecords.length" class="px-3 py-6 text-center text-sm text-secondary">
{{ t('maintenance.record.table.empty') }}
</div>
<div
v-for="record in recentRecords"
v-else
@@ -1,8 +1,8 @@
/**
* features/maintenance/utils/repair-status-display.utils.ts
* 用途:维修记录状态在列表、卡片中的标签配色映射。
* 用途:维修记录状态在列表、卡片中的标签配色与 i18n key 映射。
* 依赖:MaintenanceRepairStatus 类型。
* 逻辑:MaintenanceRecordManagerPanel、MaintenanceDeviceResultCard 等组件统一引用,保证状态色一致。
* 逻辑:MaintenanceRecordManagerPanel、MaintenanceRecordPanel、MaintenanceDeviceResultCard 等组件统一引用,保证状态色与文案一致。
*/
import type { MaintenanceRepairStatus } from '@/features/maintenance/types/record.types';
@@ -18,3 +18,16 @@ export function repairStatusBadgeClass(value: MaintenanceRepairStatus | string):
if (value === 'cancelled') return 'border-slate-200 bg-slate-100 text-slate-600';
return 'border-slate-200 bg-slate-50 text-slate-600';
}
/**
* 返回维修状态对应的 i18n 文案 key,供组件内 t() 翻译。
* @param value - 维修状态枚举值。
* @returns maintenance.record.status.* 的 key 路径;未知状态返回空字符串。
*/
export function repairStatusLabelKey(value: MaintenanceRepairStatus | string): string {
if (value === 'pending') return 'maintenance.record.status.pending';
if (value === 'processing') return 'maintenance.record.status.processing';
if (value === 'done') return 'maintenance.record.status.done';
if (value === 'cancelled') return 'maintenance.record.status.cancelled';
return '';
}
@@ -0,0 +1,20 @@
/**
* features/sso/api/linked-services.api.ts
* 用途:读取管理台配置的关联服务(已启用),供侧栏入口展示。
* 依赖:shared/api/client。
* 逻辑:ExternalSystemLinks 合并本目录与 SSO 应用目录后渲染。
*/
import { requestJson } from '@/shared/api/client';
export interface LinkedServiceItem {
id: number;
name: string;
url: string;
}
/** 获取当前用户可见的已启用关联服务。 */
export async function listLinkedServices(): Promise<LinkedServiceItem[]> {
const data = await requestJson<{ items?: LinkedServiceItem[] } | LinkedServiceItem[]>('/api/linked-services');
if (Array.isArray(data)) return data;
return Array.isArray(data?.items) ? data.items : [];
}
+39
View File
@@ -0,0 +1,39 @@
/**
* features/sso/api/sso.api.ts
* 用途:访问 HXOPS 平级服务目录与短时登录 assertion 签发接口。
* 依赖:shared/api/client。
* 逻辑:导航组件读取安全服务元数据;授权页按 app key 请求受众绑定 JWT 和服务端登记的回调地址。
*/
import { requestJson } from '@/shared/api/client';
export interface SsoApplication {
key: string;
display_name: string;
login_url: string;
}
export interface SsoAssertionResponse {
post_url: string;
assertion: string;
state: string;
expires_in: number;
}
/** 获取当前用户可见的已启用产品内平级服务。 */
export async function listSsoApplications(): Promise<SsoApplication[]> {
const data = await requestJson<{ items?: SsoApplication[] }>('/api/sso/apps');
return Array.isArray(data?.items) ? data.items : [];
}
/**
* 为目标平级服务签发受众绑定的短时登录 assertion。
* @param appKey - 服务端配置的应用 key,不能传 callback URL。
* @param state - 平级服务签名的短时 state,HXOPS 仅原样返回。
*/
export function createSsoAssertion(appKey: string, state: string): Promise<SsoAssertionResponse> {
return requestJson<SsoAssertionResponse>(`/api/sso/apps/${encodeURIComponent(appKey)}/assertions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ state }),
});
}
@@ -0,0 +1,63 @@
<!--
features/sso/components/ExternalSystemLinks.vue
用途:在 HXOPS 已登录页面展示关联服务与产品内 SSO 平级服务入口。
依赖:linked-nav.store、lucide-vue-next。
逻辑:读 Pinia 缓存即时渲染;未缓存时触发一次预取。工作台可通过 buttonClass/iconClass 对齐 ws-nav-btn。
-->
<script setup lang="ts">
import { computed, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import { ExternalLink } from 'lucide-vue-next';
import { useLinkedNavStore } from '../stores/linked-nav.store';
const props = withDefaults(defineProps<{
compact?: boolean;
showLabel?: boolean;
/** 覆盖按钮样式(如工作台 ws-nav-btn),未传时用紧凑/默认样式 */
buttonClass?: string;
/** 覆盖图标尺寸类,未传时随 compact 变化 */
iconClass?: string;
}>(), {
compact: false,
showLabel: true,
buttonClass: '',
iconClass: '',
});
const linkedNav = useLinkedNavStore();
const { items } = storeToRefs(linkedNav);
/**
* 解析按钮 class。
* 核心逻辑:外部传入优先;compact 默认与 Chat 底栏图标按钮一致(无额外 36px 盒子,避免错位)。
*/
const resolvedButtonClass = computed(() => {
if (props.buttonClass) return props.buttonClass;
if (props.compact) {
return 'inline-flex items-center justify-center transition-colors hover:text-secondary';
}
return 'inline-flex items-center justify-center gap-2 rounded-xl px-3 py-2 text-sm text-muted transition-colors hover:bg-surface-soft hover:text-secondary min-h-9';
});
/** 解析图标 class:默认 16px,与 Chat 底栏 Moon/Briefcase 一致。 */
const resolvedIconClass = computed(() => props.iconClass || 'h-4 w-4 shrink-0');
onMounted(() => {
// 已缓存则立即展示;未缓存时补一次预取(登录后 App 通常已预取)。
void linkedNav.ensureLoaded();
});
</script>
<template>
<template v-for="entry in items" :key="entry.key">
<button
type="button"
:class="resolvedButtonClass"
:title="entry.display_name"
@click="linkedNav.openItem(entry)"
>
<ExternalLink :class="resolvedIconClass" />
<span v-if="showLabel && !compact" class="truncate">{{ entry.display_name }}</span>
</button>
</template>
</template>
+12
View File
@@ -0,0 +1,12 @@
/**
* features/sso/index.ts
* 用途:统一导出 SSO 复用组件与续跳能力。
* 依赖:features/sso 子模块。
* 逻辑:页面通过本入口复用平级服务导航,登录模块复用 continuation。
*/
export { default as ExternalSystemLinks } from './components/ExternalSystemLinks.vue';
export { useLinkedNavStore } from './stores/linked-nav.store';
export {
continuationLocation,
readSsoContinuation,
} from './utils/continuation';
@@ -0,0 +1,154 @@
/**
* features/sso/stores/linked-nav.store.ts
* 用途:缓存关联服务 / SSO 侧栏入口,避免页面切换时重复请求导致入口闪现。
* 依赖:linked-services.api、sso.api、pinia。
* 逻辑:登录后预取一次;ExternalSystemLinks 直接读 store;登出或管理台变更时刷新/清空。
*/
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import { listLinkedServices, type LinkedServiceItem } from '../api/linked-services.api';
import { listSsoApplications, type SsoApplication } from '../api/sso.api';
/** 侧栏可渲染的入口元数据(可序列化,不含函数)。 */
export interface LinkedNavItem {
key: string;
display_name: string;
/** sso:走 /sso/launch;url:直接打开 target */
mode: 'sso' | 'url';
target: string;
}
/** 规范化 URL 便于与 SSO login_url 比对。 */
function normalizeUrl(value: string): string {
return String(value || '').trim().replace(/\/+$/, '').toLowerCase();
}
/**
* 合并关联服务与 SSO 目录为侧栏入口列表。
* 核心逻辑:关联服务优先;命中 SSO 注册表则 mode=sso。
*/
function buildNavItems(linked: LinkedServiceItem[], ssoApps: SsoApplication[]): LinkedNavItem[] {
const usedSsoKeys = new Set<string>();
const next: LinkedNavItem[] = [];
for (const item of linked) {
const matched = ssoApps.find(
(app) =>
normalizeUrl(app.login_url) === normalizeUrl(item.url)
|| String(app.display_name || '').trim() === String(item.name || '').trim(),
);
if (matched) {
usedSsoKeys.add(matched.key);
next.push({
key: `linked-${item.id}`,
display_name: item.name,
mode: 'sso',
target: matched.key,
});
} else {
next.push({
key: `linked-${item.id}`,
display_name: item.name,
mode: 'url',
target: item.url,
});
}
}
for (const app of ssoApps) {
if (usedSsoKeys.has(app.key)) continue;
next.push({
key: `sso-${app.key}`,
display_name: app.display_name,
mode: 'sso',
target: app.key,
});
}
return next;
}
export const useLinkedNavStore = defineStore('linkedNav', () => {
const items = ref<LinkedNavItem[]>([]);
const loaded = ref(false);
const loading = ref(false);
let inflight: Promise<void> | null = null;
const hasItems = computed(() => items.value.length > 0);
/**
* 预取侧栏入口;已加载且非 force 时直接复用缓存。
* @param options.force - 为 true 时忽略缓存强制刷新(管理台保存后)
*/
async function ensureLoaded(options?: { force?: boolean }): Promise<void> {
if (options?.force) {
loaded.value = false;
}
if (loaded.value) return;
if (inflight) {
await inflight;
return;
}
loading.value = true;
inflight = (async () => {
let linked: LinkedServiceItem[] = [];
let ssoApps: SsoApplication[] = [];
try {
linked = await listLinkedServices();
} catch (error) {
console.warn('[linked-nav] failed to load linked services', error);
}
try {
ssoApps = await listSsoApplications();
} catch (error) {
console.warn('[linked-nav] failed to load sso apps', error);
}
items.value = buildNavItems(linked, ssoApps);
loaded.value = true;
})();
try {
await inflight;
} finally {
loading.value = false;
inflight = null;
}
}
/** 强制刷新入口缓存(管理台增删改后调用)。 */
async function refresh(): Promise<void> {
await ensureLoaded({ force: true });
}
/** 登出时清空,避免下一账号看到旧入口。 */
function reset(): void {
items.value = [];
loaded.value = false;
loading.value = false;
inflight = null;
}
/**
* 打开入口:SSO 走同源 launch,其它直接新开 URL。
* @param item - 侧栏入口元数据
*/
function openItem(item: LinkedNavItem): void {
if (item.mode === 'sso') {
window.open(`/sso/launch?app=${encodeURIComponent(item.target)}`, '_blank');
return;
}
window.open(item.target, '_blank');
}
return {
items,
loaded,
loading,
hasItems,
ensureLoaded,
refresh,
reset,
openItem,
};
});
@@ -0,0 +1,72 @@
/**
* features/sso/utils/continuation.ts
* 用途:在平级服务跳转到 HXOPS 登录页期间保存并恢复 SSO 请求。
* 依赖:浏览器 sessionStorage、Vue Router 查询参数类型。
* 逻辑:只保存 app key 和签名 state,不接收或持久化 callback URL、JWT 或用户资料。
*/
import type { LocationQuery } from 'vue-router';
export interface SsoContinuation {
app: string;
state: string;
createdAt: number;
}
const STORAGE_KEY = 'hxops_sso_continuation';
const MAX_AGE_MS = 10 * 60 * 1000;
const APP_KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{1,63}$/;
/** 从授权路由查询参数构造安全的续跳请求。 */
export function parseSsoContinuation(query: LocationQuery): SsoContinuation | null {
const app = typeof query.app === 'string' ? query.app.trim().toLowerCase() : '';
const state = typeof query.state === 'string' ? query.state.trim() : '';
if (!APP_KEY_PATTERN.test(app) || !state || state.length > 4096) return null;
return { app, state, createdAt: Date.now() };
}
/** 保存未登录用户的 SSO 请求,登录成功后在同一标签页恢复。 */
export function saveSsoContinuation(continuation: SsoContinuation): void {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(continuation));
}
/** 读取仍在有效期内的 SSO 请求;坏数据或超时数据会立即清理。 */
export function readSsoContinuation(): SsoContinuation | null {
try {
const raw = sessionStorage.getItem(STORAGE_KEY);
if (!raw) return null;
const data = JSON.parse(raw) as Partial<SsoContinuation>;
if (
!APP_KEY_PATTERN.test(String(data.app || ''))
|| !String(data.state || '')
|| String(data.state || '').length > 4096
|| Date.now() - Number(data.createdAt || 0) > MAX_AGE_MS
) {
clearSsoContinuation();
return null;
}
return {
app: String(data.app),
state: String(data.state),
createdAt: Number(data.createdAt),
};
} catch {
clearSsoContinuation();
return null;
}
}
/** 清理已完成或无效的登录续跳请求。 */
export function clearSsoContinuation(): void {
sessionStorage.removeItem(STORAGE_KEY);
}
/** 生成只包含服务端应用 key 的 HXOPS 授权路由。 */
export function continuationLocation(continuation: SsoContinuation) {
return {
path: '/sso/authorize',
query: {
app: continuation.app,
state: continuation.state,
},
};
}
@@ -0,0 +1,27 @@
/**
* features/sso/utils/postForm.ts
* 用途:用浏览器表单 POST 将短时 SSO assertion 交给已登记的平级服务回调。
* 依赖:DOM API。
* 逻辑:assertion 只进入请求体,不拼接 URL;提交后浏览器离开 HXOPS 授权页。
*/
/**
* POST assertion 和 state 到后端返回的已登记回调地址。
* @param action - HXOPS 服务端从应用注册表返回的绝对 HTTPS callback URL。
* @param fields - 仅包含 assertion 与平级服务原始 state。
*/
export function submitSsoForm(action: string, fields: Record<string, string>): void {
const form = document.createElement('form');
form.method = 'POST';
form.action = action;
form.style.display = 'none';
for (const [name, value] of Object.entries(fields)) {
const input = document.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = value;
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
}
@@ -0,0 +1,73 @@
<!--
features/sso/views/SsoAuthorizeView.vue
用途:承接平级服务登录请求;未登录时转 HXOPS 登录页,已登录时签发 assertion 并 POST 回平级服务。
依赖:auth store、SSO API、continuation 与 postForm 工具。
逻辑:平级服务只提供 app/state;callback 与 JWT audience 始终由 HXOPS 服务端注册表决定。
-->
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { ArrowLeft, Loader2 } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import { createSsoAssertion } from '../api/sso.api';
import {
clearSsoContinuation,
parseSsoContinuation,
saveSsoContinuation,
} from '../utils/continuation';
import { submitSsoForm } from '../utils/postForm';
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const authStore = useAuthStore();
const errorMessage = ref('');
/** 校验授权请求,并按当前登录状态执行保存续跳或签发短时 assertion。 */
async function authorize(): Promise<void> {
const continuation = parseSsoContinuation(route.query);
if (!continuation) {
errorMessage.value = t('common.sso.invalidRequest');
return;
}
authStore.syncFromStorage();
if (!authStore.isLoggedIn) {
saveSsoContinuation(continuation);
await router.replace('/login');
return;
}
try {
const result = await createSsoAssertion(continuation.app, continuation.state);
clearSsoContinuation();
submitSsoForm(result.post_url, { assertion: result.assertion, state: result.state });
} catch (error) {
errorMessage.value = (error as Error)?.message || t('common.sso.failed');
}
}
onMounted(() => {
void authorize();
});
</script>
<template>
<main class="page-shell flex min-h-screen items-center justify-center px-6">
<section class="w-full max-w-md rounded-2xl border border-default bg-surface p-8 text-center shadow-xl">
<template v-if="!errorMessage">
<Loader2 class="mx-auto h-10 w-10 animate-spin text-brand-600" />
<h1 class="mt-5 text-xl font-semibold text-primary">{{ t('common.sso.authorizing') }}</h1>
<p class="mt-2 text-sm text-muted">{{ t('common.sso.authorizingHint') }}</p>
</template>
<template v-else>
<h1 class="text-xl font-semibold text-primary">{{ t('common.sso.failed') }}</h1>
<p class="mt-3 text-sm text-red-600">{{ errorMessage }}</p>
<button type="button" class="btn-secondary mt-6 inline-flex items-center gap-2" @click="router.replace('/workspace/applications')">
<ArrowLeft class="h-4 w-4" /> {{ t('common.sso.backToHxops') }}
</button>
</template>
</section>
</main>
</template>
@@ -0,0 +1,63 @@
<!--
features/sso/views/SsoLaunchView.vue
用途:在新标签先继承 HXOPS sessionStorage,再安全跳转到平级服务登录起点。
依赖:SSO 应用目录 API、Vue Router。
逻辑:页面只接收 app key,加载后立即切断 opener,目标 URL 由 HXOPS 服务端注册表提供。
-->
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { ArrowLeft, Loader2 } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { listSsoApplications } from '../api/sso.api';
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const errorMessage = ref('');
// 新标签已完成同源 sessionStorage 克隆,跳跨域前切断 opener 防止反向标签劫持。
window.opener = null;
/** 按服务端应用目录解析 app key,并跳转到平级服务登录起点。 */
async function launch(): Promise<void> {
const appKey = typeof route.query.app === 'string' ? route.query.app.trim().toLowerCase() : '';
if (!appKey) {
errorMessage.value = t('common.sso.invalidRequest');
return;
}
try {
const applications = await listSsoApplications();
const application = applications.find((item) => item.key === appKey);
if (!application) {
errorMessage.value = t('errors.codes.AUTH_SSO_APP_NOT_FOUND');
return;
}
window.location.replace(application.login_url);
} catch (error) {
errorMessage.value = (error as Error)?.message || t('common.sso.failed');
}
}
onMounted(() => {
void launch();
});
</script>
<template>
<main class="page-shell flex min-h-screen items-center justify-center px-6">
<section class="w-full max-w-md rounded-2xl border border-default bg-surface p-8 text-center shadow-xl">
<template v-if="!errorMessage">
<Loader2 class="mx-auto h-10 w-10 animate-spin text-brand-600" />
<h1 class="mt-5 text-xl font-semibold text-primary">{{ t('common.sso.authorizing') }}</h1>
</template>
<template v-else>
<h1 class="text-xl font-semibold text-primary">{{ t('common.sso.failed') }}</h1>
<p class="mt-3 text-sm text-red-600">{{ errorMessage }}</p>
<button type="button" class="btn-secondary mt-6 inline-flex items-center gap-2" @click="router.replace('/workspace/applications')">
<ArrowLeft class="h-4 w-4" /> {{ t('common.sso.backToHxops') }}
</button>
</template>
</section>
</main>
</template>
@@ -0,0 +1,45 @@
/**
* features/user/api/user.api.ts
* 用途:封装当前登录用户的资料与其可访问 Agent 查询请求。
* 依赖:shared/utils/auth、shared/api/client。
* 逻辑:Chat 和用户页面通过本模块读取当前用户资源,不与认证登录流程耦合。
*/
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
import type { UserProfileForm } from '../types/user-profile.types';
const auth = () => ({ headers: getAuthHeaders() });
/** 获取当前登录用户的资料及个人设置。 */
export const getUserProfile = () => requestJson<Record<string, unknown>>('/api/user/profile', auth());
/** 读取个人中心编辑表单所需的完整资料。 */
export const getEditableUserProfile = () =>
requestJson<Partial<UserProfileForm>>('/api/user/profile', auth());
/** 保存当前用户允许自助编辑的资料与偏好。 */
export const updateUserProfile = (profile: Partial<UserProfileForm>) =>
requestJson('/api/user/profile', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(profile),
});
/** 校验当前密码后修改 Casdoor 与 HXOPS 的统一密码。 */
export const changeUserPassword = (currentPassword: string, newPassword: string) =>
requestJson('/api/user/change-password', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
});
/** 获取当前用户有权访问的单个 Agent。 */
export const getUserAgent = <T = Record<string, unknown>>(agentId: number) =>
requestJson<T>(`/api/user/agents/${agentId}`, auth());
/** 获取当前用户有权访问的 Agent 列表。 */
export const listUserAgents = <T = unknown>() => requestJson<T[]>('/api/agents', auth());
/** 获取当前用户有权查看的 Agent 使用指南。 */
export const listAgentGuides = (agentId: number) =>
requestJson<unknown[]>(`/api/agents/${agentId}/guides`, auth());
@@ -0,0 +1,59 @@
<script setup lang="ts">
/**
* features/user/components/UserPasswordDialog.vue
* 用途:呈现并提交当前用户的密码修改表单。
* 依赖:user-profile.context 提供的资料状态和操作方法。
* 逻辑:由工作台布局常驻渲染,用户资料页打开弹窗后在此完成密码修改。
*/
import { inject } from 'vue';
import { X } from 'lucide-vue-next';
import { USER_PROFILE_KEY } from '../composables/user-profile.context';
const userProfile = inject(USER_PROFILE_KEY)!;
</script>
<template>
<div
v-if="userProfile.CHANGE_PASSWORD_ENABLED && userProfile.showPasswordModal"
class="dialog-overlay z-50 items-center"
>
<div class="dialog-panel max-w-md">
<div class="dialog-header">
<h3 class="section-title">{{ $t('profile.changePassword') || 'Change Password' }}</h3>
<button
type="button"
class="btn-icon-ds"
:aria-label="$t('admin.close')"
:disabled="userProfile.isChangingPassword"
@click="userProfile.showPasswordModal = false"
>
<X class="w-5 h-5" />
</button>
</div>
<form @submit.prevent="userProfile.handleChangePassword">
<div class="dialog-body">
<div>
<label class="label-field">{{ $t('profile.currentPassword') || 'Current Password' }}</label>
<input v-model="userProfile.passwordForm.current" type="password" class="input-field mt-1" :disabled="userProfile.isChangingPassword" required />
</div>
<div>
<label class="label-field">{{ $t('profile.newPassword') || 'New Password' }}</label>
<input v-model="userProfile.passwordForm.new" type="password" class="input-field mt-1" :disabled="userProfile.isChangingPassword" required />
</div>
<div>
<label class="label-field">{{ $t('profile.confirmPassword') || 'Confirm Password' }}</label>
<input v-model="userProfile.passwordForm.confirm" type="password" class="input-field mt-1" :disabled="userProfile.isChangingPassword" required />
</div>
</div>
<div class="dialog-footer">
<button type="button" :disabled="userProfile.isChangingPassword" @click="userProfile.showPasswordModal = false" class="btn-secondary flex-1 disabled:opacity-50 disabled:cursor-not-allowed">
{{ $t('profile.cancel') || 'Cancel' }}
</button>
<button type="submit" :disabled="userProfile.isChangingPassword" class="btn-primary flex-1 disabled:opacity-50 disabled:cursor-not-allowed">
{{ userProfile.isChangingPassword ? $t('profile.changingPassword') : ($t('profile.changePassword') || 'Update') }}
</button>
</div>
</form>
</div>
</div>
</template>
@@ -0,0 +1,193 @@
/**
* features/user/composables/useUserProfile.ts
* 用途:编排个人资料读取/编辑、主题偏好与统一密码修改。
* 依赖:user.api、主题/消息/i18n composable、Casdoor 错误映射。
* 逻辑:UserProfilePage 和 UserPasswordDialog 消费本 composable;Workspace 仅提供它以维持布局上下文。
*/
import { computed, ref } from 'vue';
import type { ThemePreference } from '@/shared/composables/useTheme';
import { resolveCasdoorErrorMessage } from '@/shared/utils/casdoor';
import { BusinessError } from '@/shared/api/client';
import { changeUserPassword, getEditableUserProfile, updateUserProfile } from '../api/user.api';
import { CHANGE_PASSWORD_ENABLED, type UserProfileForm } from '../types/user-profile.types';
import type { ComputedRef, WritableComputedRef } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
import type { useMessage } from '@/shared/composables/useMessage';
interface UserProfileDeps {
t: ComposerTranslation;
locale: WritableComputedRef<string>;
msg: ReturnType<typeof useMessage>;
setThemePreference: (preference: ThemePreference) => void;
appliedTheme: ComputedRef<ThemePreference>;
}
/**
* 管理当前用户资料、偏好设置和密码修改状态。
* 由工作台在初始化时创建,使资料页面与改密弹窗共享同一份状态和请求动作。
*/
export function useUserProfile(deps: UserProfileDeps) {
const { t, locale, msg, setThemePreference, appliedTheme } = deps;
const isProfileLoading = ref(false);
const isProfileSaving = ref(false);
const isChangingPassword = ref(false);
const isProfileEditing = ref(false);
const showPasswordModal = ref(false);
const profileUser = ref<UserProfileForm>({
id: 0,
username: '',
real_name: '',
email: '',
phone_number: '',
department: '',
role: '',
employee_id: '',
language: 'zh-CN',
theme_preference: 'system' as ThemePreference,
});
const originalProfile = ref<UserProfileForm | null>(null);
const passwordForm = ref({ current: '', new: '', confirm: '' });
const themeOptions: Array<{ value: ThemePreference; label: () => string }> = [
{ value: 'light', label: () => t('theme.light') || 'Light' },
{ value: 'dark', label: () => t('theme.dark') || 'Dark' },
{ value: 'system', label: () => t('theme.system') || 'Follow System' },
];
const hasProfileUnsavedChanges = computed(() => {
if (!originalProfile.value) return false;
return (
profileUser.value.real_name !== originalProfile.value.real_name ||
profileUser.value.phone_number !== originalProfile.value.phone_number ||
profileUser.value.language !== originalProfile.value.language ||
profileUser.value.theme_preference !== originalProfile.value.theme_preference ||
profileUser.value.email !== originalProfile.value.email ||
profileUser.value.employee_id !== originalProfile.value.employee_id ||
profileUser.value.department !== originalProfile.value.department
);
});
const captureOriginalProfile = () => {
originalProfile.value = { ...profileUser.value };
};
const handleChangePasswordClick = () => {
if (!CHANGE_PASSWORD_ENABLED) {
msg.warning(t('profile.changePasswordContactAdmin'));
return;
}
showPasswordModal.value = true;
};
const fetchProfile = async () => {
isProfileLoading.value = true;
try {
const data = await getEditableUserProfile();
if (!data) {
msg.error(t('workspace.profile.msg.loadFailed'));
return;
}
profileUser.value = { ...profileUser.value, ...data };
if (data.language) locale.value = data.language;
if (data.theme_preference) {
setThemePreference(data.theme_preference);
} else {
profileUser.value.theme_preference = appliedTheme.value;
}
captureOriginalProfile();
isProfileEditing.value = false;
} catch (e) {
console.error(e);
msg.error(t('workspace.profile.msg.loadFailed'));
} finally {
isProfileLoading.value = false;
}
};
const startProfileEditing = () => {
isProfileEditing.value = true;
};
const cancelProfileEditing = () => {
if (originalProfile.value) {
profileUser.value = { ...originalProfile.value };
locale.value = profileUser.value.language;
setThemePreference(profileUser.value.theme_preference);
}
isProfileEditing.value = false;
};
const saveProfile = async () => {
if (!hasProfileUnsavedChanges.value) {
isProfileEditing.value = false;
return;
}
const payload = {
real_name: profileUser.value.real_name,
phone_number: profileUser.value.phone_number,
language: profileUser.value.language,
theme_preference: profileUser.value.theme_preference,
email: profileUser.value.email,
employee_id: profileUser.value.employee_id,
department: profileUser.value.department,
};
locale.value = profileUser.value.language;
setThemePreference(profileUser.value.theme_preference);
try {
isProfileSaving.value = true;
await updateUserProfile(payload);
msg.success(t('workspace.profile.msg.saved'));
captureOriginalProfile();
isProfileEditing.value = false;
} catch (e) {
console.error(e);
msg.error((e as Error)?.message || t('workspace.profile.msg.saveFailed'));
} finally {
isProfileSaving.value = false;
}
};
const handleChangePassword = async () => {
if (isChangingPassword.value) return;
if (passwordForm.value.new !== passwordForm.value.confirm) {
msg.warning(t('profile.passwordMismatch') || 'Passwords do not match');
return;
}
try {
isChangingPassword.value = true;
await changeUserPassword(passwordForm.value.current, passwordForm.value.new);
msg.success(t('profile.passwordChanged') || 'Password changed successfully');
passwordForm.value = { current: '', new: '', confirm: '' };
showPasswordModal.value = false;
} catch (e) {
console.error(e);
msg.error(
resolveCasdoorErrorMessage(e as BusinessError, t) || t('workspace.profile.msg.changePasswordFailed'),
);
} finally {
isChangingPassword.value = false;
}
};
return {
isProfileLoading,
isProfileSaving,
isChangingPassword,
isProfileEditing,
showPasswordModal,
CHANGE_PASSWORD_ENABLED,
handleChangePasswordClick,
profileUser,
originalProfile,
passwordForm,
themeOptions,
hasProfileUnsavedChanges,
captureOriginalProfile,
fetchProfile,
startProfileEditing,
cancelProfileEditing,
saveProfile,
handleChangePassword,
};
}
@@ -0,0 +1,31 @@
/**
* features/user/composables/user-profile.context.ts
* 用途:定义个人资料页面和改密弹窗共享的注入上下文。
* 依赖:useUserProfile 的返回契约与工作台提供的移动端/登出能力。
* 逻辑:WorkspaceLayout 提供上下文;user 域组件只依赖此契约,不读取工作台注入 key。
*/
import type { InjectionKey } from 'vue';
import type { UserProfileForm } from '../types/user-profile.types';
import type { ThemePreference } from '@/shared/composables/useTheme';
export interface UserProfileContext {
isMobile: boolean;
handleLogout: () => void;
isProfileLoading: boolean;
isProfileSaving: boolean;
isChangingPassword: boolean;
isProfileEditing: boolean;
showPasswordModal: boolean;
CHANGE_PASSWORD_ENABLED: boolean;
profileUser: UserProfileForm;
passwordForm: { current: string; new: string; confirm: string };
hasProfileUnsavedChanges: boolean;
themeOptions: Array<{ value: ThemePreference; label: () => string }>;
handleChangePasswordClick: () => void;
startProfileEditing: () => void;
cancelProfileEditing: () => void;
saveProfile: () => Promise<void>;
handleChangePassword: () => Promise<void>;
}
export const USER_PROFILE_KEY: InjectionKey<UserProfileContext> = Symbol('user-profile');
+9
View File
@@ -0,0 +1,9 @@
/**
* features/user/index.ts
* 用途:暴露用户域 HTTP 能力,避免其他 feature 直接依赖实现路径。
* 依赖:user.api。
* 逻辑:Chat 等使用方从此处或 user.api 导入当前用户资料和授权资源查询。
*/
export * from './api/user.api';
export { useUserProfile } from './composables/useUserProfile';
export type { UserProfileForm } from './types/user-profile.types';
@@ -0,0 +1,22 @@
/**
* features/user/types/user-profile.types.ts
* 用途:定义个人资料编辑与密码修改的用户域类型和功能开关。
* 依赖:shared/composables/useTheme。
* 逻辑:useUserProfile、UserProfilePage 和 UserPasswordDialog 使用同一份资料契约。
*/
import type { ThemePreference } from '@/shared/composables/useTheme';
export interface UserProfileForm {
id: number;
username: string;
real_name: string;
email: string;
phone_number: string;
department: string;
role: string;
employee_id: string;
language: string;
theme_preference: ThemePreference;
}
export const CHANGE_PASSWORD_ENABLED = true;
@@ -0,0 +1,198 @@
<script setup lang="ts">
/**
* features/user/views/UserProfilePage.vue
* 閻劑鈧棑绱扮仦鏇犮仛閸滃瞼绱潏鎴濈秼閸撳秶鏁ら幋鐤カ閺傛瑣鈧浇顕㈢懛鈧?娑撳顣介崑蹇撱偨閿涘苯鑻熼幓鎰返娣囶喗鏁肩€靛棛鐖滈崗銉ュ經閵? * 娓氭繆绂嗛敍姝秙er-profile.context閵嗕勾ucide 閸ョ偓鐖i妴涔倁e i18n閵? * 闁槒绶敍姘矝閻?/workspace/profile 鐠侯垳鏁遍幍鑳祰閿涘奔绲炬い鐢告桨閸滃奔绗熼崝鈥崇秺鐏?user feature閵? */
import { inject } from 'vue';
import {
User, Mail, Building, CreditCard, Globe, Save, Palette,
} from 'lucide-vue-next';
import { USER_PROFILE_KEY } from '../composables/user-profile.context';
const userProfile = inject(USER_PROFILE_KEY)!;
</script>
<template>
<div v-if="userProfile.isProfileLoading" class="flex justify-center py-20">
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
</div>
<div v-else class="space-y-6">
<div class="rounded-3xl border border-default bg-surface px-6 py-6 shadow-sm md:px-8">
<div class="flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between">
<div class="flex flex-1 flex-col gap-6 sm:flex-row sm:items-center sm:justify-start">
<div class="flex h-24 w-24 shrink-0 items-center justify-center rounded-full bg-brand-100 text-4xl font-bold text-brand-600" :class="userProfile.isMobile ? 'h-14 w-14 text-2xl' : ''">
{{ (userProfile.profileUser.real_name || userProfile.profileUser.username || 'U').charAt(0).toUpperCase() }}
</div>
<div class="grid flex-1 text-left" :class="userProfile.isMobile ? 'grid-cols-2 gap-x-4 gap-y-1' : 'grid-cols-1 gap-x-12 gap-y-3 sm:grid-cols-2'">
<div :class="userProfile.isMobile ? '' : ''">
<div :class="userProfile.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ userProfile.isMobile ? $t('profile.realName') : (userProfile.profileUser.username || '-') }}</div>
<div v-if="userProfile.isMobile" class="text-sm font-medium text-primary truncate">{{ userProfile.profileUser.real_name || userProfile.profileUser.username || '-' }}</div>
</div>
<div>
<div :class="userProfile.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ userProfile.isMobile ? $t('profile.employeeId') : (userProfile.profileUser.employee_id || '-') }}</div>
<div v-if="userProfile.isMobile" class="text-sm font-medium text-primary truncate">{{ userProfile.profileUser.employee_id || '-' }}</div>
</div>
<div>
<div :class="userProfile.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ userProfile.isMobile ? $t('profile.department') : (userProfile.profileUser.department || '-') }}</div>
<div v-if="userProfile.isMobile" class="text-sm font-medium text-primary truncate">{{ userProfile.profileUser.department || '-' }}</div>
</div>
<div>
<div :class="userProfile.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ userProfile.isMobile ? $t('profile.role') : (userProfile.profileUser.role === 'admin' ? ($t('profile.roleAdmin') || 'Administrator') : ($t('profile.roleUser') || 'User')) }}</div>
<div v-if="userProfile.isMobile" class="text-sm font-medium text-primary truncate">{{ userProfile.profileUser.role === 'admin' ? ($t('profile.roleAdmin') || 'Administrator') : ($t('profile.roleUser') || 'User') }}</div>
</div>
<div :class="userProfile.isMobile ? 'col-span-2' : 'sm:col-span-2'">
<div :class="userProfile.isMobile ? 'text-xs text-muted' : 'break-all text-lg font-semibold text-primary'">{{ userProfile.isMobile ? $t('profile.email') : (userProfile.profileUser.email || '-') }}</div>
<div v-if="userProfile.isMobile" class="text-sm font-medium text-primary truncate">{{ userProfile.profileUser.email || '-' }}</div>
</div>
</div>
</div>
<div v-if="!userProfile.isMobile" class="flex shrink-0 items-center gap-2 self-start lg:ml-6">
<button @click="userProfile.handleChangePasswordClick" class="btn-primary px-6 py-3 text-base">
{{ $t('profile.changePassword') }}
</button>
</div>
</div>
<div v-if="userProfile.isMobile" class="mt-4 flex items-center justify-center gap-4">
<button @click="userProfile.handleChangePasswordClick" class="btn-primary flex-1 py-2.5 text-sm text-center">
{{ $t('profile.changePassword') }}
</button>
<button @click="userProfile.handleLogout" class="btn-secondary flex-1 py-2.5 text-sm text-center text-red-600 hover:bg-red-50">
{{ $t('workspace.nav.logout') }}
</button>
</div>
</div>
<div class="space-y-6">
<div class="rounded-3xl border border-default bg-surface p-8 shadow-sm" :class="userProfile.isMobile ? 'p-4' : ''">
<div class="mb-8 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between" :class="userProfile.isMobile ? 'mb-4 gap-2' : ''">
<div class="flex items-center" :class="userProfile.isMobile ? 'w-full justify-center gap-2' : ''">
<h3 class="flex items-center gap-3 text-3xl font-bold text-primary" :class="userProfile.isMobile ? 'text-lg gap-2' : ''">
<User class="h-6 w-6 text-brand-500" :class="userProfile.isMobile ? 'h-4 w-4' : ''" />
{{ $t('profile.basicInfo') }}
</h3>
<button v-if="userProfile.isMobile && !userProfile.isProfileEditing" @click="userProfile.startProfileEditing" class="btn-secondary px-3 py-1 text-xs">
{{ $t('profile.edit') }}
</button>
</div>
<p v-if="!userProfile.isMobile" class="mt-2 text-sm text-muted">
{{ userProfile.isProfileEditing ? $t('profile.directEditHint') : $t('profile.switchEditHint') }}
</p>
<div v-if="!userProfile.isMobile" class="flex items-center gap-2">
<button v-if="!userProfile.isProfileEditing" @click="userProfile.startProfileEditing" class="btn-secondary px-5 py-2.5 text-sm">
{{ $t('profile.edit') }}
</button>
<template v-else>
<button @click="userProfile.cancelProfileEditing" class="btn-secondary px-5 py-2.5 text-sm">
{{ $t('profile.cancel') || 'Cancel' }}
</button>
<button
@click="userProfile.saveProfile"
:disabled="userProfile.isProfileSaving || !userProfile.hasProfileUnsavedChanges"
class="btn-primary px-5 py-2.5 text-sm disabled:opacity-50 disabled:cursor-not-allowed"
>
<Save class="w-4 h-4" />
<span>{{ userProfile.isProfileSaving ? $t('profile.saving') : $t('workspace.save') }}</span>
</button>
</template>
</div>
</div>
<div class="grid grid-cols-1 gap-5 md:grid-cols-2" :class="userProfile.isMobile ? 'gap-3' : ''">
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="userProfile.isMobile ? 'text-xs mb-1' : ''">
<User class="h-4 w-4" /> {{ $t('profile.username') }}
</label>
<div class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="userProfile.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
{{ userProfile.profileUser.username || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="userProfile.isMobile ? 'text-xs mb-1' : ''">
<CreditCard class="h-4 w-4" /> {{ $t('profile.employeeId') }}
</label>
<input v-if="userProfile.isProfileEditing" v-model="userProfile.profileUser.employee_id" type="text" class="input-field" :class="userProfile.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="userProfile.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
{{ userProfile.profileUser.employee_id || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="userProfile.isMobile ? 'text-xs mb-1' : ''">
<User class="h-4 w-4" /> {{ $t('profile.realName') }}
</label>
<input v-if="userProfile.isProfileEditing" v-model="userProfile.profileUser.real_name" type="text" class="input-field" :class="userProfile.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="userProfile.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
{{ userProfile.profileUser.real_name || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="userProfile.isMobile ? 'text-xs mb-1' : ''">
<Building class="h-4 w-4" /> {{ $t('profile.department') }}
</label>
<input v-if="userProfile.isProfileEditing" v-model="userProfile.profileUser.department" type="text" class="input-field" :class="userProfile.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="userProfile.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
{{ userProfile.profileUser.department || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="userProfile.isMobile ? 'text-xs mb-1' : ''">
<Mail class="h-4 w-4" /> {{ $t('profile.email') }}
</label>
<input v-if="userProfile.isProfileEditing" v-model="userProfile.profileUser.email" type="email" class="input-field" :class="userProfile.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="userProfile.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
{{ userProfile.profileUser.email || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="userProfile.isMobile ? 'text-xs mb-1' : ''">
<Globe class="h-4 w-4" /> {{ $t('profile.phoneNumber') }}
</label>
<input v-if="userProfile.isProfileEditing" v-model="userProfile.profileUser.phone_number" type="text" class="input-field" :class="userProfile.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="userProfile.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
{{ userProfile.profileUser.phone_number || '-' }}
</div>
</div>
</div>
</div>
<div class="rounded-3xl border border-default bg-surface p-8 shadow-sm">
<h3 class="mb-6 flex items-center gap-3 text-2xl font-bold text-primary">
<Palette class="h-5 w-5 text-brand-500" />
{{ $t('profile.preferences') }}
</h3>
<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
<div>
<label class="mb-2 block text-sm font-medium text-muted">{{ $t('workspace.languageLabel') }}</label>
<select v-model="userProfile.profileUser.language" :disabled="!userProfile.isProfileEditing" class="input-field h-[58px]">
<option value="en">English</option>
<option value="zh-CN">{{ $t('workspace.lang.zhCN') }}</option>
<option value="zh-TW">{{ $t('workspace.lang.zhTW') }}</option>
<option value="th">Thai</option>
</select>
</div>
<div>
<label class="mb-2 block text-sm font-medium text-muted">{{ $t('profile.theme') }}</label>
<div
class="segment-control segment-control--cols-3 segment-control--md"
role="radiogroup"
:aria-label="$t('profile.theme')"
>
<button
v-for="item in userProfile.themeOptions"
:key="item.value"
type="button"
role="radio"
:aria-checked="userProfile.profileUser.theme_preference === item.value"
:disabled="!userProfile.isProfileEditing"
class="segment-item"
:class="userProfile.profileUser.theme_preference === item.value ? 'segment-item--active' : ''"
@click="userProfile.profileUser.theme_preference = item.value"
>
{{ item.label() }}
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,91 @@
/**
* features/workspace/api/voucherCheck.api.ts
* 用途:工作台立账凭证检核记录查询 API 客户端。
* 依赖:@/shared/api/client、getAuthHeaders。
* 逻辑:AccountingVoucherCheckView 调用;对应 /api/workspace/accounting-voucher-check/*。
*/
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
export interface VoucherCheckStateItem {
id: number;
scope_code: string;
period_month: string | null;
invoice_no: string;
invoice_date?: string | null;
status: string;
folder_path?: string | null;
folder_exists?: boolean;
matched_files?: Record<string, string>;
missing_materials?: Array<{ code?: string; name?: string }>;
last_checked_at?: string | null;
last_missing_notified_on?: string | null;
}
export interface VoucherCheckStatesResponse {
scope_code: string;
period: string;
page: number;
page_size: number;
total: number;
items: VoucherCheckStateItem[];
}
export interface VoucherCheckRunItemsResponse {
run_id: number;
run_no: string;
page: number;
page_size: number;
total: number;
items: Array<{
id: number;
invoice_no: string;
invoice_date?: string | null;
result: string;
folder_path?: string | null;
folder_exists?: boolean;
matched_files?: Record<string, string>;
missing_materials?: Array<{ code?: string; name?: string }>;
error_code?: string | null;
error_message?: string | null;
checked_at?: string | null;
}>;
}
/**
* 按月份/状态/发票号筛选最新检核状态。
*/
export function listVoucherCheckStates(params: {
period?: string;
status?: string;
invoice_no?: string;
page?: number;
page_size?: number;
}) {
const q = new URLSearchParams();
if (params.period) q.set('period', params.period);
if (params.status) q.set('status', params.status);
if (params.invoice_no) q.set('invoice_no', params.invoice_no);
if (params.page) q.set('page', String(params.page));
if (params.page_size) q.set('page_size', String(params.page_size));
const qs = q.toString();
return requestJson<VoucherCheckStatesResponse>(
`/api/workspace/accounting-voucher-check/states${qs ? `?${qs}` : ''}`,
{ headers: getAuthHeaders() },
);
}
/**
* 分页查询指定批次明细。
*/
export function listVoucherCheckRunItems(runId: number, params?: { result?: string; page?: number; page_size?: number }) {
const q = new URLSearchParams();
if (params?.result) q.set('result', params.result);
if (params?.page) q.set('page', String(params.page));
if (params?.page_size) q.set('page_size', String(params.page_size));
const qs = q.toString();
return requestJson<VoucherCheckRunItemsResponse>(
`/api/workspace/accounting-voucher-check/runs/${runId}/items${qs ? `?${qs}` : ''}`,
{ headers: getAuthHeaders() },
);
}
@@ -0,0 +1,13 @@
<script setup lang="ts">
/**
* features/workspace/pages/AccountingVoucherCheckPage.vue
* 用途:立账凭证检核工作台页面壳。
* 依赖:AccountingVoucherCheckView。
* 逻辑:路由懒加载入口。
*/
import AccountingVoucherCheckView from '../views/AccountingVoucherCheckView.vue';
</script>
<template>
<AccountingVoucherCheckView />
</template>
@@ -0,0 +1,255 @@
<script setup lang="ts">
/**
* features/workspace/views/AccountingVoucherCheckView.vue
* 用途:立账凭证检核记录页——按月筛选最新状态与缺资料票。
* 依赖:voucherCheck.api、vue-i18n、useMessage。
* 逻辑:路由 /workspace/accounting-voucher-check;企微 textcard 也可跳转至此。
*/
import { computed, onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { Loader2, RefreshCw, Search } from 'lucide-vue-next';
import { useMessage } from '@/shared/composables/useMessage';
import {
listVoucherCheckRunItems,
listVoucherCheckStates,
type VoucherCheckStateItem,
} from '../api/voucherCheck.api';
const { t } = useI18n();
const msg = useMessage();
const route = useRoute();
const loading = ref(false);
const items = ref<VoucherCheckStateItem[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = 50;
const period = ref('');
const status = ref('');
const invoiceNo = ref('');
const runIdFilter = ref<number | null>(null);
const runItems = ref<Awaited<ReturnType<typeof listVoucherCheckRunItems>>['items']>([]);
/**
* 默认检核月份(当前自然月 YYYY-MM)。
*/
function currentPeriod(): string {
const d = new Date();
const m = String(d.getMonth() + 1).padStart(2, '0');
return `${d.getFullYear()}-${m}`;
}
const statusOptions = computed(() => [
{ value: '', label: t('workspace.voucherCheck.statusAll') },
{ value: 'complete', label: t('workspace.voucherCheck.statusComplete') },
{ value: 'missing', label: t('workspace.voucherCheck.statusMissing') },
]);
/**
* 加载最新状态列表。
*/
async function loadStates() {
loading.value = true;
try {
const data = await listVoucherCheckStates({
period: period.value || undefined,
status: status.value || undefined,
invoice_no: invoiceNo.value || undefined,
page: page.value,
page_size: pageSize,
});
items.value = data.items || [];
total.value = data.total || 0;
if (data.period && !period.value) period.value = data.period;
} catch (e: any) {
msg.error(e?.message || t('workspace.voucherCheck.loadFailed'));
} finally {
loading.value = false;
}
}
/**
* 若 URL 带 run_id,额外加载该批次明细。
*/
async function loadRunItemsIfNeeded() {
const raw = route.query.run_id;
const id = Number(Array.isArray(raw) ? raw[0] : raw);
if (!Number.isFinite(id) || id <= 0) {
runIdFilter.value = null;
runItems.value = [];
return;
}
runIdFilter.value = id;
try {
const data = await listVoucherCheckRunItems(id, { page: 1, page_size: 100 });
runItems.value = data.items || [];
} catch (e: any) {
msg.error(e?.message || t('workspace.voucherCheck.loadFailed'));
}
}
function statusLabel(value: string) {
if (value === 'complete') return t('workspace.voucherCheck.statusComplete');
if (value === 'missing') return t('workspace.voucherCheck.statusMissing');
if (value === 'skipped') return t('workspace.voucherCheck.statusSkipped');
if (value === 'technical_error') return t('workspace.voucherCheck.statusTechError');
return value || '-';
}
function formatMissing(list?: Array<{ code?: string; name?: string }>) {
if (!list?.length) return '-';
return list.map((x) => x.name || x.code || '').filter(Boolean).join('、');
}
onMounted(async () => {
period.value = currentPeriod();
const qStatus = route.query.status;
if (typeof qStatus === 'string' && qStatus) status.value = qStatus;
await Promise.all([loadStates(), loadRunItemsIfNeeded()]);
});
watch(
() => route.query.run_id,
() => {
void loadRunItemsIfNeeded();
},
);
</script>
<template>
<div class="mx-auto flex h-full w-full max-w-6xl flex-col gap-4 p-4 md:p-6">
<header class="space-y-1">
<h1 class="text-xl font-semibold text-slate-800">{{ $t('workspace.voucherCheck.title') }}</h1>
<p class="text-sm text-slate-500">{{ $t('workspace.voucherCheck.subtitle') }}</p>
</header>
<section class="flex flex-wrap items-end gap-3 rounded-xl border border-slate-200 bg-white p-3">
<label class="flex flex-col gap-1 text-xs text-slate-500">
{{ $t('workspace.voucherCheck.period') }}
<input v-model="period" type="month" class="rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-800" />
</label>
<label class="flex flex-col gap-1 text-xs text-slate-500">
{{ $t('workspace.voucherCheck.status') }}
<select v-model="status" class="rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-800">
<option v-for="opt in statusOptions" :key="opt.value || 'all'" :value="opt.value">{{ opt.label }}</option>
</select>
</label>
<label class="flex min-w-[12rem] flex-1 flex-col gap-1 text-xs text-slate-500">
{{ $t('workspace.voucherCheck.invoiceNo') }}
<input
v-model="invoiceNo"
type="text"
class="rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-800"
:placeholder="$t('workspace.voucherCheck.invoicePlaceholder')"
@keyup.enter="page = 1; loadStates()"
/>
</label>
<button
type="button"
class="inline-flex items-center gap-1 rounded-lg bg-sky-600 px-3 py-2 text-sm font-medium text-white hover:bg-sky-700"
@click="page = 1; loadStates()"
>
<Search class="h-4 w-4" />
{{ $t('workspace.voucherCheck.search') }}
</button>
<button
type="button"
class="inline-flex items-center gap-1 rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-700 hover:bg-slate-50"
@click="loadStates()"
>
<RefreshCw class="h-4 w-4" />
{{ $t('workspace.voucherCheck.refresh') }}
</button>
</section>
<section v-if="runIdFilter" class="rounded-xl border border-amber-200 bg-amber-50/60 p-3">
<h2 class="mb-2 text-sm font-semibold text-amber-900">
{{ $t('workspace.voucherCheck.runItemsTitle', { runId: runIdFilter }) }}
</h2>
<div class="overflow-x-auto">
<table class="min-w-full text-left text-sm">
<thead class="text-xs text-slate-500">
<tr>
<th class="px-2 py-1">{{ $t('workspace.voucherCheck.invoiceNo') }}</th>
<th class="px-2 py-1">{{ $t('workspace.voucherCheck.result') }}</th>
<th class="px-2 py-1">{{ $t('workspace.voucherCheck.missing') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in runItems" :key="row.id" class="border-t border-amber-100">
<td class="px-2 py-1.5 font-medium text-slate-800">{{ row.invoice_no }}</td>
<td class="px-2 py-1.5">{{ statusLabel(row.result) }}</td>
<td class="px-2 py-1.5 text-slate-600">{{ formatMissing(row.missing_materials) }}</td>
</tr>
</tbody>
</table>
</div>
</section>
<section class="min-h-0 flex-1 overflow-hidden rounded-xl border border-slate-200 bg-white">
<div v-if="loading" class="flex items-center justify-center gap-2 py-16 text-sm text-slate-500">
<Loader2 class="h-4 w-4 animate-spin" />
{{ $t('workspace.voucherCheck.loading') }}
</div>
<div v-else-if="!items.length" class="py-16 text-center text-sm text-slate-500">
{{ $t('workspace.voucherCheck.empty') }}
</div>
<div v-else class="max-h-full overflow-auto">
<table class="min-w-full text-left text-sm">
<thead class="sticky top-0 bg-slate-50 text-xs text-slate-500">
<tr>
<th class="px-3 py-2">{{ $t('workspace.voucherCheck.invoiceNo') }}</th>
<th class="px-3 py-2">{{ $t('workspace.voucherCheck.invoiceDate') }}</th>
<th class="px-3 py-2">{{ $t('workspace.voucherCheck.status') }}</th>
<th class="px-3 py-2">{{ $t('workspace.voucherCheck.folder') }}</th>
<th class="px-3 py-2">{{ $t('workspace.voucherCheck.missing') }}</th>
<th class="px-3 py-2">{{ $t('workspace.voucherCheck.checkedAt') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in items" :key="row.id" class="border-t border-slate-100 hover:bg-slate-50/80">
<td class="px-3 py-2 font-medium text-slate-800">{{ row.invoice_no }}</td>
<td class="px-3 py-2 text-slate-600">{{ row.invoice_date || '-' }}</td>
<td class="px-3 py-2">
<span
class="inline-flex rounded-full px-2 py-0.5 text-xs font-medium"
:class="row.status === 'complete' ? 'bg-emerald-50 text-emerald-700' : 'bg-rose-50 text-rose-700'"
>
{{ statusLabel(row.status) }}
</span>
</td>
<td class="max-w-[16rem] truncate px-3 py-2 text-slate-600" :title="row.folder_path || ''">
{{ row.folder_path || '-' }}
</td>
<td class="px-3 py-2 text-slate-600">{{ formatMissing(row.missing_materials) }}</td>
<td class="px-3 py-2 text-slate-600">{{ row.last_checked_at || '-' }}</td>
</tr>
</tbody>
</table>
</div>
<div class="flex items-center justify-between border-t border-slate-100 px-3 py-2 text-xs text-slate-500">
<span>{{ $t('workspace.voucherCheck.totalCount', { total }) }}</span>
<div class="flex items-center gap-2">
<button
type="button"
class="rounded border border-slate-200 px-2 py-1 disabled:opacity-40"
:disabled="page <= 1 || loading"
@click="page -= 1; loadStates()"
>
{{ $t('workspace.voucherCheck.prevPage') }}
</button>
<span>{{ page }}</span>
<button
type="button"
class="rounded border border-slate-200 px-2 py-1 disabled:opacity-40"
:disabled="page * pageSize >= total || loading"
@click="page += 1; loadStates()"
>
{{ $t('workspace.voucherCheck.nextPage') }}
</button>
</div>
</div>
</section>
</div>
</template>