feat(shipping-notice): 新增货代客户管理功能,支持客户导入、识别证据管理与客户确认
This commit is contained in:
1 parent
b595e157e9
commit
4fbaed2b4c
176 files changed
+14011
-994
No files matched your search
@@ -1,9 +1,11 @@
|
||||
/**
|
||||
* features/admin/api/admin.api.ts
|
||||
* 管理后台 HTTP API:用户、部门、Agent、权限、报表、企业微信、公告等。
|
||||
* 用途:管理后台用户、部门、Agent、货代客户、权限、报表等 HTTP API。
|
||||
* 依赖:requestJson、getAuthHeaders、各管理域类型。
|
||||
* 逻辑:JSON 接口统一走 requestJson;模板与对账二进制下载沿用认证 fetch 并抛 BusinessError。
|
||||
*/
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { BusinessError, requestJson, resolveLocalizedErrorMessage } from '@/shared/api/client';
|
||||
import type { AdminUserRow } from '../types/admin.types';
|
||||
import type { AdminDashboardBadges, AdminDashboardSummary } from '../types/dashboard.types';
|
||||
import type { PaginatedResult } from '@/shared/types/pagination.types';
|
||||
@@ -15,10 +17,131 @@ import type {
|
||||
UsageReport,
|
||||
UsageRangeKey,
|
||||
} from '../types/report.types';
|
||||
import type {
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingCustomerImportBatch,
|
||||
ShippingCustomerPage,
|
||||
ShippingCustomerRow,
|
||||
ShippingCustomerShadowItem,
|
||||
ShippingCustomerShadowReport,
|
||||
ShippingIdentifierFormState,
|
||||
} from '../types/shipping-customer.types';
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||
|
||||
/** 下载管理端二进制文件,并将标准错误 envelope 保留为 BusinessError。 */
|
||||
const downloadAdminFile = async (url: string, fallbackName: string): Promise<void> => {
|
||||
const response = await fetch(url, { headers: getAuthHeaders() });
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => null);
|
||||
const code = payload?.error?.code || 'SYSTEM.HTTP_ERROR';
|
||||
throw new BusinessError({
|
||||
message: resolveLocalizedErrorMessage(code, payload?.error?.message || `HTTP ${response.status}`),
|
||||
code,
|
||||
details: payload?.error?.details || {},
|
||||
requestId: payload?.request_id,
|
||||
status: response.status,
|
||||
});
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const disposition = response.headers.get('Content-Disposition') || '';
|
||||
const encodedName = disposition.match(/filename\*=UTF-8''([^;]+)/i)?.[1];
|
||||
const plainName = disposition.match(/filename="?([^";]+)"?/i)?.[1];
|
||||
const filename = encodedName ? decodeURIComponent(encodedName) : plainName || fallbackName;
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = objectUrl;
|
||||
anchor.download = filename;
|
||||
anchor.click();
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
};
|
||||
|
||||
// Shipping customers
|
||||
export interface ListShippingCustomersParams {
|
||||
q?: string;
|
||||
status?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
/** 分页查询货代标准客户。 */
|
||||
export const listShippingCustomers = (params: ListShippingCustomersParams = {}) => {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.q?.trim()) qs.set('q', params.q.trim());
|
||||
if (params.status) qs.set('status', params.status);
|
||||
qs.set('page', String(params.page || 1));
|
||||
qs.set('page_size', String(params.pageSize || 20));
|
||||
return requestJson<ShippingCustomerPage>(`/api/admin/shipping-customers?${qs.toString()}`, auth());
|
||||
};
|
||||
|
||||
export const getShippingCustomer = (id: number) =>
|
||||
requestJson<ShippingCustomerRow>(`/api/admin/shipping-customers/${id}`, auth());
|
||||
|
||||
export const createShippingCustomer = (payload: Record<string, unknown>) =>
|
||||
requestJson<ShippingCustomerRow>('/api/admin/shipping-customers', {
|
||||
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
export const updateShippingCustomer = (id: number, payload: Record<string, unknown>) =>
|
||||
requestJson<ShippingCustomerRow>(`/api/admin/shipping-customers/${id}`, {
|
||||
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
export const deactivateShippingCustomer = (id: number) =>
|
||||
requestJson<ShippingCustomerRow>(`/api/admin/shipping-customers/${id}/deactivate`, {
|
||||
method: 'POST', ...auth(),
|
||||
});
|
||||
|
||||
export const createShippingCustomerIdentifier = (customerId: number, payload: ShippingIdentifierFormState) =>
|
||||
requestJson<ShippingCustomerIdentifier>(`/api/admin/shipping-customers/${customerId}/identifiers`, {
|
||||
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
export const updateShippingCustomerIdentifier = (identifierId: number, payload: Record<string, unknown>) =>
|
||||
requestJson<ShippingCustomerIdentifier>(`/api/admin/shipping-customer-identifiers/${identifierId}`, {
|
||||
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
export const uploadShippingCustomerImport = (file: File, sourceSystem: string) => {
|
||||
const body = new FormData();
|
||||
body.append('file', file);
|
||||
body.append('source_system', sourceSystem);
|
||||
return requestJson<ShippingCustomerImportBatch>('/api/admin/shipping-customer-imports', {
|
||||
method: 'POST', headers: getAuthHeaders(), body,
|
||||
});
|
||||
};
|
||||
|
||||
export const decideShippingCustomerImportRow = (
|
||||
rowId: number,
|
||||
payload: { action: string; target_customer_id?: number; note?: string },
|
||||
) => requestJson(`/api/admin/shipping-customer-import-rows/${rowId}/decision`, {
|
||||
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
export const publishShippingCustomerImport = (batchId: number) =>
|
||||
requestJson<ShippingCustomerImportBatch>(`/api/admin/shipping-customer-imports/${batchId}/publish`, {
|
||||
method: 'POST', ...auth(),
|
||||
});
|
||||
|
||||
export const downloadShippingCustomerImportTemplate = () =>
|
||||
downloadAdminFile('/api/admin/shipping-customers/import-template', 'shipping_customer_import_template.xlsx');
|
||||
|
||||
export const downloadShippingCustomerReconciliation = (batchId: number, batchNo: string) =>
|
||||
downloadAdminFile(
|
||||
`/api/admin/shipping-customer-imports/${batchId}/reconciliation`,
|
||||
`${batchNo}_reconciliation.csv`,
|
||||
);
|
||||
|
||||
export const getShippingCustomerShadowReport = (limit = 100) =>
|
||||
requestJson<ShippingCustomerShadowReport>(`/api/admin/shipping-customer-shadow-report?limit=${limit}`, auth());
|
||||
|
||||
export const labelShippingCustomerShadowResolution = (resolutionId: number, customerId: number) =>
|
||||
requestJson<ShippingCustomerShadowItem>(
|
||||
`/api/admin/shipping-customer-shadow-resolutions/${resolutionId}/label`,
|
||||
{ method: 'PUT', ...jsonAuth(), body: JSON.stringify({ customer_id: customerId }) },
|
||||
);
|
||||
|
||||
// Users
|
||||
export const listAdminUsers = () => requestJson<AdminUserRow[]>('/api/admin/users', auth());
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@ export const ADMIN_REPORT_TABLES: AdminReportTableId[] = [
|
||||
export const LEGACY_MODULE_QUERY_TO_PATH: Record<string, string> = {};
|
||||
|
||||
export const adminModulePath = (moduleId: AdminModuleId | string): string => {
|
||||
if (moduleId === 'shipping_customers') return '/workspace/shipping-notice/customers';
|
||||
if (moduleId === 'reports') return '/admin/reports';
|
||||
const meta = ADMIN_MODULE_METAS.find((m) => m.id === moduleId);
|
||||
if (meta) return `/admin/${meta.path}`;
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-customers/ShippingCustomersPage.vue
|
||||
用途:货代客户主数据管理入口,提供列表、识别证据和期初导入工作台。
|
||||
依赖:useShippingCustomersAdmin、PaginationBar、三个域内组件。
|
||||
逻辑:路由加载后查询客户;页面只组合展示与事件,业务状态由 composable 管理。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { onMounted, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Edit, FileSpreadsheet, Fingerprint, Plus, Search, UserX } from 'lucide-vue-next';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import CustomerFormModal from './components/CustomerFormModal.vue';
|
||||
import CustomerIdentifiersPanel from './components/CustomerIdentifiersPanel.vue';
|
||||
import CustomerImportDialog from './components/CustomerImportDialog.vue';
|
||||
import CustomerShadowQualityPanel from './components/CustomerShadowQualityPanel.vue';
|
||||
import { useShippingCustomersAdmin } from './composables/useShippingCustomersAdmin';
|
||||
|
||||
const { t } = useI18n();
|
||||
const admin = useShippingCustomersAdmin();
|
||||
|
||||
/** 页码或每页条数改变时重新读取服务端分页。 */
|
||||
watch([admin.page, admin.pageSize], () => { void admin.loadCustomers(); });
|
||||
onMounted(() => { void Promise.all([admin.loadCustomers(), admin.loadShadowReport()]); });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="admin-table-section animate-fade-in-up">
|
||||
<div class="admin-table-header admin-table-header--stacked">
|
||||
<div><h2 class="section-title">{{ t('admin.shippingCustomers.title') }}</h2><p class="section-desc mt-1">{{ t('admin.shippingCustomers.subtitle') }}</p></div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button type="button" class="btn-ghost flex items-center gap-2" @click="admin.openImport"><FileSpreadsheet class="w-4 h-4" />{{ t('admin.shippingCustomers.importButton') }}</button>
|
||||
<button type="button" class="btn-primary flex items-center gap-2" @click="admin.openCreateCustomer"><Plus class="w-4 h-4" />{{ t('admin.shippingCustomers.add') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="admin-table-filters--inline gap-3">
|
||||
<div class="relative flex-1 min-w-[220px] max-w-md">
|
||||
<Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted" />
|
||||
<input v-model="admin.searchQuery.value" type="search" class="admin-table-filter-input w-full pl-9" :placeholder="t('admin.shippingCustomers.searchPlaceholder')" @keyup.enter="admin.searchCustomers" />
|
||||
</div>
|
||||
<select v-model="admin.statusFilter.value" class="admin-table-filter-input" @change="admin.searchCustomers">
|
||||
<option value="">{{ t('admin.shippingCustomers.status.all') }}</option>
|
||||
<option value="active">{{ t('admin.shippingCustomers.status.active') }}</option>
|
||||
<option value="inactive">{{ t('admin.shippingCustomers.status.inactive') }}</option>
|
||||
</select>
|
||||
<button type="button" class="btn-ghost" @click="admin.searchCustomers">{{ t('admin.shippingCustomers.search') }}</button>
|
||||
</div>
|
||||
|
||||
<div v-if="admin.isLoading.value" class="flex justify-center py-20"><div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" /></div>
|
||||
<div v-else class="admin-table-wrap">
|
||||
<table class="admin-table min-w-[860px]">
|
||||
<thead><tr>
|
||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.name') }}</th>
|
||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.shortCode') }}</th>
|
||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.status') }}</th>
|
||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.identifiers') }}</th>
|
||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.cases') }}</th>
|
||||
<th class="px-5 py-4 text-right">{{ t('admin.shippingCustomers.headers.actions') }}</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
<tr v-if="admin.customers.value.length === 0"><td colspan="6" class="admin-table-empty px-5">{{ t('admin.shippingCustomers.empty') }}</td></tr>
|
||||
<tr v-for="customer in admin.customers.value" :key="customer.id">
|
||||
<td class="px-5 py-4"><div class="font-medium text-primary">{{ customer.standard_name }}</div><div v-if="customer.remark" class="text-xs text-muted truncate max-w-sm">{{ customer.remark }}</div></td>
|
||||
<td class="px-5 py-4 font-mono text-sm">{{ customer.short_code }}</td>
|
||||
<td class="px-5 py-4"><span class="text-sm" :class="customer.status === 'active' ? 'text-emerald-600' : 'text-muted'">{{ t(`admin.shippingCustomers.status.${customer.status}`) }}</span></td>
|
||||
<td class="px-5 py-4 text-sm">{{ customer.identifier_count }}</td>
|
||||
<td class="px-5 py-4 text-sm">{{ customer.case_count }}</td>
|
||||
<td class="px-5 py-4"><div class="flex justify-end gap-1">
|
||||
<button type="button" class="p-2 text-indigo-600 hover:bg-indigo-50 rounded-lg" :title="t('admin.shippingCustomers.identifiers.title')" @click="admin.openIdentifiers(customer)"><Fingerprint class="w-4 h-4" /></button>
|
||||
<button type="button" class="p-2 text-indigo-600 hover:bg-indigo-50 rounded-lg" :title="t('admin.edit')" @click="admin.openEditCustomer(customer)"><Edit class="w-4 h-4" /></button>
|
||||
<button v-if="customer.status === 'active'" type="button" class="p-2 text-red-600 hover:bg-red-50 rounded-lg" :title="t('admin.shippingCustomers.deactivate')" @click="admin.deactivateCustomer(customer)"><UserX class="w-4 h-4" /></button>
|
||||
</div></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<PaginationBar v-model:page="admin.page.value" v-model:page-size="admin.pageSize.value" :total="admin.total.value" :pages="admin.pages.value" />
|
||||
|
||||
<CustomerShadowQualityPanel :report="admin.shadowReport.value" :customers="admin.importTargetCustomers.value.length ? admin.importTargetCustomers.value : admin.customers.value" :loading="admin.isShadowLoading.value" @refresh="admin.loadShadowReport" @label="admin.labelShadowResolution" />
|
||||
|
||||
<CustomerFormModal :visible="admin.showCustomerModal.value" :form="admin.customerForm.value" :is-saving="admin.isSaving.value" @close="admin.closeCustomerModal" @save="admin.saveCustomer" />
|
||||
<CustomerIdentifiersPanel :visible="admin.showIdentifiersPanel.value" :customer="admin.selectedCustomer.value" :is-saving="admin.isSaving.value" @close="admin.showIdentifiersPanel.value = false" @add="admin.addIdentifier" @update="admin.updateIdentifier" />
|
||||
<CustomerImportDialog :visible="admin.showImportDialog.value" :batch="admin.importBatch.value" :customers="admin.importTargetCustomers.value" :is-importing="admin.isImporting.value" @close="admin.showImportDialog.value = false" @upload="admin.uploadImport" @decide="admin.decideImportRow" @publish="admin.publishImport" @template="admin.downloadTemplate" @reconciliation="admin.downloadReconciliation" />
|
||||
</section>
|
||||
</template>
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-customers/components/CustomerFormModal.vue
|
||||
用途:创建或编辑货代标准客户。
|
||||
依赖:shipping-customer.types、admin 通用表单样式、vue-i18n。
|
||||
逻辑:父页面传入可变表单;提交事件交由 useShippingCustomersAdmin 保存。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingCustomerFormState } from '@/features/admin/types/shipping-customer.types';
|
||||
|
||||
defineProps<{ visible: boolean; form: ShippingCustomerFormState; 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-6 py-5 border-b border-subtle">
|
||||
<h3 class="section-title">{{ form.id ? t('admin.shippingCustomers.edit') : t('admin.shippingCustomers.add') }}</h3>
|
||||
</div>
|
||||
<div class="px-6 py-5 space-y-4 overflow-y-auto">
|
||||
<label class="block space-y-1.5">
|
||||
<span class="label-field">{{ t('admin.shippingCustomers.fields.standardName') }}</span>
|
||||
<input v-model="form.standard_name" class="input-field text-sm" />
|
||||
</label>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<label class="block space-y-1.5">
|
||||
<span class="label-field">{{ t('admin.shippingCustomers.fields.shortCode') }}</span>
|
||||
<input v-model="form.short_code" maxlength="6" class="input-field text-sm uppercase" />
|
||||
<span class="text-xs text-muted">{{ t('admin.shippingCustomers.fields.shortCodeHint') }}</span>
|
||||
</label>
|
||||
<label class="block space-y-1.5">
|
||||
<span class="label-field">{{ t('admin.shippingCustomers.fields.status') }}</span>
|
||||
<select v-model="form.status" class="input-field text-sm">
|
||||
<option value="active">{{ t('admin.shippingCustomers.status.active') }}</option>
|
||||
<option value="inactive">{{ t('admin.shippingCustomers.status.inactive') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<label class="block space-y-1.5">
|
||||
<span class="label-field">{{ t('admin.shippingCustomers.fields.remark') }}</span>
|
||||
<textarea v-model="form.remark" rows="3" class="input-field text-sm resize-y" />
|
||||
</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="isSaving" @click="emit('save')">
|
||||
{{ isSaving ? t('admin.shippingCustomers.saving') : t('admin.save') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-customers/components/CustomerIdentifiersPanel.vue
|
||||
用途:展示、新增、审核和停用客户识别证据。
|
||||
依赖:shipping-customer.types、vue-i18n。
|
||||
逻辑:所有修改通过事件上送 composable;本组件不直接访问 API。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type {
|
||||
ShippingCustomerRow,
|
||||
ShippingIdentifierFormState,
|
||||
} from '@/features/admin/types/shipping-customer.types';
|
||||
import { createEmptyShippingIdentifierForm } from '@/features/admin/types/shipping-customer.types';
|
||||
|
||||
const props = defineProps<{ visible: boolean; customer: ShippingCustomerRow | null; isSaving: boolean }>();
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
add: [form: ShippingIdentifierFormState];
|
||||
update: [id: number, payload: Record<string, unknown>];
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
const form = ref(createEmptyShippingIdentifierForm());
|
||||
|
||||
/** 切换客户或关闭面板时清空未提交证据。 */
|
||||
watch(() => [props.visible, props.customer?.id], () => {
|
||||
form.value = createEmptyShippingIdentifierForm();
|
||||
});
|
||||
|
||||
/** 提交证据后重置表单,实际保存由父级处理。 */
|
||||
const submit = (): void => {
|
||||
emit('add', { ...form.value });
|
||||
form.value = createEmptyShippingIdentifierForm();
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible && customer" class="admin-modal-overlay animate-fade-in items-center">
|
||||
<div class="admin-modal-panel max-w-5xl max-h-[92vh] scale-100">
|
||||
<div class="px-6 py-5 border-b border-subtle flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h3 class="section-title">{{ t('admin.shippingCustomers.identifiers.title') }}</h3>
|
||||
<p class="section-desc mt-1">{{ customer.standard_name }} · {{ customer.short_code }}</p>
|
||||
</div>
|
||||
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.close') }}</button>
|
||||
</div>
|
||||
<div class="px-6 py-5 overflow-y-auto space-y-6">
|
||||
<div class="rounded-xl border border-default overflow-x-auto">
|
||||
<table class="admin-table min-w-[780px]">
|
||||
<thead><tr>
|
||||
<th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.identifiers.type') }}</th>
|
||||
<th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.identifiers.value') }}</th>
|
||||
<th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.identifiers.status') }}</th>
|
||||
<th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.identifiers.autoMatch') }}</th>
|
||||
<th class="px-4 py-3 text-right">{{ t('admin.shippingCustomers.headers.actions') }}</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
<tr v-if="!customer.identifiers?.length">
|
||||
<td colspan="5" class="admin-table-empty px-4">{{ t('admin.shippingCustomers.identifiers.empty') }}</td>
|
||||
</tr>
|
||||
<tr v-for="item in customer.identifiers" :key="item.id">
|
||||
<td class="px-4 py-3 text-sm">{{ t(`admin.shippingCustomers.identifierTypes.${item.identifier_type}`) }}</td>
|
||||
<td class="px-4 py-3 text-sm"><div>{{ item.raw_value }}</div><div class="text-xs text-muted">{{ item.normalized_value }}</div></td>
|
||||
<td class="px-4 py-3 text-sm">{{ t(`admin.shippingCustomers.identifierStatus.${item.status}`) }}</td>
|
||||
<td class="px-4 py-3 text-sm">{{ item.auto_match_allowed ? t('admin.shippingCustomers.yes') : t('admin.shippingCustomers.no') }}</td>
|
||||
<td class="px-4 py-3"><div class="flex justify-end gap-2">
|
||||
<button v-if="item.status !== 'approved'" type="button" class="btn-ghost text-xs" @click="emit('update', item.id, { status: 'approved' })">{{ t('admin.shippingCustomers.identifiers.approve') }}</button>
|
||||
<button v-if="item.status === 'approved' && !item.auto_match_allowed" type="button" class="btn-ghost text-xs" @click="emit('update', item.id, { auto_match_allowed: true })">{{ t('admin.shippingCustomers.identifiers.enableAuto') }}</button>
|
||||
<button v-if="item.status !== 'disabled'" type="button" class="btn-ghost text-xs text-red-600" @click="emit('update', item.id, { status: 'disabled' })">{{ t('admin.shippingCustomers.identifiers.disable') }}</button>
|
||||
</div></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="rounded-xl border border-default p-4 space-y-4">
|
||||
<h4 class="font-semibold text-primary">{{ t('admin.shippingCustomers.identifiers.add') }}</h4>
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-3">
|
||||
<select v-model="form.identifier_type" class="input-field text-sm">
|
||||
<option v-for="kind in ['name_alias','email','domain','template_fingerprint','address','contact']" :key="kind" :value="kind">{{ t(`admin.shippingCustomers.identifierTypes.${kind}`) }}</option>
|
||||
</select>
|
||||
<input v-model="form.identifier_value" class="input-field text-sm md:col-span-2" :placeholder="t('admin.shippingCustomers.identifiers.valuePlaceholder')" />
|
||||
<select v-model="form.status" class="input-field text-sm">
|
||||
<option value="pending">{{ t('admin.shippingCustomers.identifierStatus.pending') }}</option>
|
||||
<option value="approved">{{ t('admin.shippingCustomers.identifierStatus.approved') }}</option>
|
||||
</select>
|
||||
<label class="flex items-center gap-2 text-sm text-secondary"><input v-model="form.auto_match_allowed" type="checkbox" :disabled="form.status !== 'approved'" />{{ t('admin.shippingCustomers.identifiers.allowAuto') }}</label>
|
||||
<input v-model="form.remark" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.fields.remark')" />
|
||||
</div>
|
||||
<div class="flex justify-end"><button type="button" class="btn-primary" :disabled="isSaving" @click="submit">{{ t('admin.add') }}</button></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-customers/components/CustomerImportDialog.vue
|
||||
用途:上传期初客户 Excel、查看预检结果、处理 warning、发布并下载对账。
|
||||
依赖:shipping-customer.types、vue-i18n。
|
||||
逻辑:组件只收集文件和行级决定;上传、发布与下载均委托父级 composable。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingCustomerImportBatch, ShippingCustomerImportRow, ShippingCustomerRow } from '@/features/admin/types/shipping-customer.types';
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean;
|
||||
batch: ShippingCustomerImportBatch | null;
|
||||
customers: ShippingCustomerRow[];
|
||||
isImporting: boolean;
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
upload: [file: File, sourceSystem: string];
|
||||
decide: [row: ShippingCustomerImportRow, action: string, targetCustomerId?: number];
|
||||
publish: [];
|
||||
template: [];
|
||||
reconciliation: [];
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
const selectedFile = ref<File | null>(null);
|
||||
const sourceSystem = ref('INITIAL_EXCEL');
|
||||
const rowActions = ref<Record<number, string>>({});
|
||||
const rowTargets = ref<Record<number, number | undefined>>({});
|
||||
|
||||
const unresolvedWarnings = computed(() => props.batch?.rows.filter((row) => row.validation_status === 'warning' && !row.decision_action).length || 0);
|
||||
const canPublish = computed(() => !!props.batch && props.batch.status !== 'published' && props.batch.error_rows === 0 && unresolvedWarnings.value === 0);
|
||||
|
||||
/** 读取文件选择控件中的首个文件。 */
|
||||
const onFileChange = (event: Event): void => {
|
||||
selectedFile.value = (event.target as HTMLInputElement).files?.[0] || null;
|
||||
};
|
||||
|
||||
/** 提交选中的 Excel 文件和来源系统。 */
|
||||
const upload = (): void => {
|
||||
if (selectedFile.value) emit('upload', selectedFile.value, sourceSystem.value.trim() || 'INITIAL_EXCEL');
|
||||
};
|
||||
|
||||
/** 保存 warning 行动作;update/merge 同时携带目标客户。 */
|
||||
const saveDecision = (row: ShippingCustomerImportRow): void => {
|
||||
const action = rowActions.value[row.id] || row.decision_action || '';
|
||||
if (!action) return;
|
||||
emit('decide', row, action, rowTargets.value[row.id]);
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
|
||||
<div class="admin-modal-panel max-w-6xl max-h-[94vh] scale-100">
|
||||
<div class="px-6 py-5 border-b border-subtle flex items-start justify-between gap-4">
|
||||
<div><h3 class="section-title">{{ t('admin.shippingCustomers.import.title') }}</h3><p class="section-desc mt-1">{{ t('admin.shippingCustomers.import.subtitle') }}</p></div>
|
||||
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.close') }}</button>
|
||||
</div>
|
||||
<div class="px-6 py-5 overflow-y-auto space-y-5">
|
||||
<div class="rounded-xl border border-default p-4 grid grid-cols-1 md:grid-cols-[1fr_220px_auto_auto] gap-3 items-end">
|
||||
<label class="space-y-1.5"><span class="label-field">{{ t('admin.shippingCustomers.import.file') }}</span><input type="file" accept=".xlsx" class="block w-full text-sm" @change="onFileChange" /></label>
|
||||
<label class="space-y-1.5"><span class="label-field">{{ t('admin.shippingCustomers.import.sourceSystem') }}</span><input v-model="sourceSystem" class="input-field text-sm uppercase" /></label>
|
||||
<button type="button" class="btn-ghost" @click="emit('template')">{{ t('admin.shippingCustomers.import.downloadTemplate') }}</button>
|
||||
<button type="button" class="btn-primary" :disabled="!selectedFile || isImporting" @click="upload">{{ t('admin.shippingCustomers.import.upload') }}</button>
|
||||
</div>
|
||||
|
||||
<template v-if="batch">
|
||||
<div class="grid grid-cols-2 md:grid-cols-5 gap-3">
|
||||
<div v-for="item in [
|
||||
['total', batch.total_rows], ['valid', batch.valid_rows], ['warning', batch.warning_rows], ['error', batch.error_rows], ['published', batch.published_rows]
|
||||
]" :key="String(item[0])" class="rounded-xl border border-default p-3">
|
||||
<div class="text-xs text-muted">{{ t(`admin.shippingCustomers.import.stats.${item[0]}`) }}</div><div class="text-xl font-semibold text-primary">{{ item[1] }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-sm text-secondary">{{ batch.batch_no }} · {{ batch.source_system }} · {{ batch.file_name }}</div>
|
||||
<div class="rounded-xl border border-default overflow-x-auto">
|
||||
<table class="admin-table min-w-[1050px]">
|
||||
<thead><tr>
|
||||
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.import.row') }}</th>
|
||||
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.import.type') }}</th>
|
||||
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.import.key') }}</th>
|
||||
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.import.preview') }}</th>
|
||||
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.import.validation') }}</th>
|
||||
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.import.decision') }}</th>
|
||||
</tr></thead>
|
||||
<tbody><tr v-for="row in batch.rows" :key="row.id">
|
||||
<td class="px-3 py-3 text-sm">{{ row.sheet_name }}!{{ row.row_no }}</td>
|
||||
<td class="px-3 py-3 text-sm">{{ t(`admin.shippingCustomers.import.rowTypes.${row.row_type}`) }}</td>
|
||||
<td class="px-3 py-3 text-sm font-mono">{{ row.legacy_customer_key || '-' }}</td>
|
||||
<td class="px-3 py-3 text-sm max-w-[320px]"><div class="truncate">{{ row.normalized.standard_name || row.normalized.identifier_value || '-' }}</div><div class="text-xs text-muted">{{ row.normalized.short_code || row.normalized.identifier_type || '' }}</div></td>
|
||||
<td class="px-3 py-3 text-sm"><span :class="row.validation_status === 'error' ? 'text-red-600' : row.validation_status === 'warning' ? 'text-amber-600' : 'text-emerald-600'">{{ t(`admin.shippingCustomers.import.validationStatus.${row.validation_status}`) }}</span><div v-for="issue in [...row.errors, ...row.warnings]" :key="issue.code" class="text-xs text-muted">{{ t(`errors.codes.${issue.code.replace(/\./g, '_')}`) }}</div></td>
|
||||
<td class="px-3 py-3 text-sm">
|
||||
<div v-if="row.validation_status === 'warning' && batch.status !== 'published'" class="flex flex-wrap gap-2">
|
||||
<select v-model="rowActions[row.id]" class="admin-table-filter-input text-xs">
|
||||
<option value="">{{ t('admin.shippingCustomers.import.choose') }}</option>
|
||||
<option value="create">{{ t('admin.shippingCustomers.import.actions.create') }}</option>
|
||||
<option v-if="row.row_type === 'customer'" value="update">{{ t('admin.shippingCustomers.import.actions.update') }}</option>
|
||||
<option v-if="row.row_type === 'customer'" value="merge">{{ t('admin.shippingCustomers.import.actions.merge') }}</option>
|
||||
<option value="skip">{{ t('admin.shippingCustomers.import.actions.skip') }}</option>
|
||||
</select>
|
||||
<select v-if="row.row_type === 'customer' && ['update','merge'].includes(rowActions[row.id] || '')" v-model="rowTargets[row.id]" class="admin-table-filter-input text-xs">
|
||||
<option :value="undefined">{{ t('admin.shippingCustomers.import.target') }}</option>
|
||||
<option v-for="customer in customers" :key="customer.id" :value="customer.id">{{ customer.standard_name }} ({{ customer.short_code }})</option>
|
||||
</select>
|
||||
<button type="button" class="btn-ghost text-xs" @click="saveDecision(row)">{{ t('admin.save') }}</button>
|
||||
</div>
|
||||
<span v-else>{{ row.decision_action || row.result_message || row.suggested_action || '-' }}</span>
|
||||
</td>
|
||||
</tr></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="flex flex-wrap justify-between gap-3">
|
||||
<button type="button" class="btn-ghost" @click="emit('reconciliation')">{{ t('admin.shippingCustomers.import.downloadReconciliation') }}</button>
|
||||
<button type="button" class="btn-primary" :disabled="!canPublish || isImporting" @click="emit('publish')">{{ batch.status === 'published' ? t('admin.shippingCustomers.import.alreadyPublished') : t('admin.shippingCustomers.import.publish') }}</button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-customers/components/CustomerShadowQualityPanel.vue
|
||||
用途:展示客户影子识别分布、自动确认/纠错指标、人工标注准确率和最近样本。
|
||||
依赖:shipping-customer.types、vue-i18n。
|
||||
逻辑:展示质量卡片、客户事件审计与真值标签;不调用客户绑定、编号或任务接口。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingCustomerRow, ShippingCustomerShadowReport } from '@/features/admin/types/shipping-customer.types';
|
||||
|
||||
const props = defineProps<{ report: ShippingCustomerShadowReport | null; customers: ShippingCustomerRow[]; loading: boolean }>();
|
||||
const emit = defineEmits<{ refresh: []; label: [resolutionId: number, customerId: number] }>();
|
||||
const { t } = useI18n();
|
||||
const labels = ref<Record<number, number | undefined>>({});
|
||||
|
||||
/** 报告刷新后回填既有人工真值,避免下拉框丢失已标注状态。 */
|
||||
watch(
|
||||
() => props.report,
|
||||
(report) => {
|
||||
labels.value = Object.fromEntries(
|
||||
(report?.items || []).map((item) => [item.id, item.manual_customer_id || undefined]),
|
||||
);
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/** 提交单条样本人工真值,空选择不触发。 */
|
||||
const submitLabel = (resolutionId: number): void => {
|
||||
const customerId = labels.value[resolutionId];
|
||||
if (customerId) emit('label', resolutionId, customerId);
|
||||
};
|
||||
|
||||
/** 从客户事件详情中提取新旧业务号,保持表格简洁且兼容不同事件类型。 */
|
||||
const eventBusinessChange = (detail: Record<string, unknown>): string => {
|
||||
const oldNo = String(detail.old_business_no || '').trim();
|
||||
const newNo = String(detail.new_business_no || detail.business_no || '').trim();
|
||||
if (oldNo && newNo) return `${oldNo} → ${newNo}`;
|
||||
return newNo || oldNo || '-';
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="rounded-2xl border border-default bg-surface p-5 space-y-4">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div><h3 class="font-semibold text-primary">{{ t('admin.shippingCustomers.shadow.title') }}</h3><p class="text-sm text-muted mt-1">{{ t('admin.shippingCustomers.shadow.subtitle') }}</p></div>
|
||||
<button type="button" class="btn-ghost" :disabled="loading" @click="emit('refresh')">{{ t('admin.shippingCustomers.shadow.refresh') }}</button>
|
||||
</div>
|
||||
<div v-if="report" class="grid grid-cols-2 md:grid-cols-4 xl:grid-cols-8 gap-3">
|
||||
<div v-for="card in [
|
||||
['total', report.total], ['unique', report.status_counts.unique_candidate || 0], ['ambiguous', report.status_counts.ambiguous || 0],
|
||||
['unmatched', report.status_counts.unmatched || 0], ['accuracy', report.accuracy == null ? '-' : `${(report.accuracy * 100).toFixed(1)}%`],
|
||||
['autoBound', report.auto_bound_count], ['autoRate', report.auto_resolution?.auto_confirmation_rate == null ? '-' : `${(report.auto_resolution.auto_confirmation_rate * 100).toFixed(1)}%`],
|
||||
['corrected', report.auto_resolution?.corrected_task_count || 0]
|
||||
]" :key="String(card[0])" class="rounded-xl border border-default p-3"><div class="text-xs text-muted">{{ t(`admin.shippingCustomers.shadow.cards.${card[0]}`) }}</div><div class="text-xl font-semibold">{{ card[1] }}</div></div>
|
||||
</div>
|
||||
<div v-if="report" class="overflow-x-auto rounded-xl border border-default">
|
||||
<table class="admin-table min-w-[900px]"><thead><tr>
|
||||
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.sample') }}</th><th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.status') }}</th><th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.topCandidate') }}</th><th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.manualLabel') }}</th>
|
||||
</tr></thead><tbody>
|
||||
<tr v-if="!report.items.length"><td colspan="4" class="admin-table-empty px-3">{{ t('admin.shippingCustomers.shadow.empty') }}</td></tr>
|
||||
<tr v-for="item in report.items" :key="item.id">
|
||||
<td class="px-3 py-3 text-sm"><div>{{ item.candidate_no || item.candidate_id }}</div><div class="text-xs text-muted">{{ item.intake_no }}</div></td>
|
||||
<td class="px-3 py-3 text-sm">{{ t(`admin.shippingCustomers.shadow.statuses.${item.status}`) }}</td>
|
||||
<td class="px-3 py-3 text-sm"><span v-if="item.matches[0]">{{ item.matches[0].standard_name }} ({{ item.matches[0].short_code }}) · {{ item.matches[0].score }}</span><span v-else>-</span></td>
|
||||
<td class="px-3 py-3"><div class="flex gap-2"><select v-model="labels[item.id]" class="admin-table-filter-input text-xs"><option :value="undefined">{{ t('admin.shippingCustomers.shadow.chooseCustomer') }}</option><option v-for="customer in customers" :key="customer.id" :value="customer.id">{{ customer.standard_name }} ({{ customer.short_code }})</option></select><button type="button" class="btn-ghost text-xs" @click="submitLabel(item.id)">{{ item.manual_customer_id ? t('admin.update') : t('admin.save') }}</button></div></td>
|
||||
</tr>
|
||||
</tbody></table>
|
||||
</div>
|
||||
<div v-if="report?.auto_resolution" class="overflow-x-auto rounded-xl border border-default">
|
||||
<div class="border-b border-default px-3 py-3 text-sm font-semibold text-primary">{{ t('admin.shippingCustomers.shadow.auditTitle') }}</div>
|
||||
<table class="admin-table min-w-[760px]"><thead><tr>
|
||||
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.auditTask') }}</th><th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.auditEvent') }}</th><th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.auditBusinessNo') }}</th><th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.auditTime') }}</th>
|
||||
</tr></thead><tbody>
|
||||
<tr v-if="!report.auto_resolution.recent_events.length"><td colspan="4" class="admin-table-empty px-3">{{ t('admin.shippingCustomers.shadow.auditEmpty') }}</td></tr>
|
||||
<tr v-for="event in report.auto_resolution.recent_events" :key="event.id">
|
||||
<td class="px-3 py-3 text-sm">{{ event.task_no }}</td>
|
||||
<td class="px-3 py-3 text-sm">{{ t(`admin.shippingCustomers.shadow.events.${event.event_type}`) }}</td>
|
||||
<td class="px-3 py-3 text-sm">{{ eventBusinessChange(event.detail) }}</td>
|
||||
<td class="px-3 py-3 text-sm text-muted">{{ event.created_at || '-' }}</td>
|
||||
</tr>
|
||||
</tbody></table>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
+327
@@ -0,0 +1,327 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-customers/composables/useShippingCustomersAdmin.ts
|
||||
* 用途:编排货代客户列表、详情、识别证据、期初导入与发布状态。
|
||||
* 依赖:admin.api、shipping-customer.types、BusinessError、useMessage。
|
||||
* 逻辑:ShippingCustomersPage 与子组件共享本 composable 暴露的状态和动作。
|
||||
*/
|
||||
|
||||
import { ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
createShippingCustomer,
|
||||
createShippingCustomerIdentifier,
|
||||
deactivateShippingCustomer,
|
||||
decideShippingCustomerImportRow,
|
||||
downloadShippingCustomerImportTemplate,
|
||||
downloadShippingCustomerReconciliation,
|
||||
getShippingCustomer,
|
||||
getShippingCustomerShadowReport,
|
||||
listShippingCustomers,
|
||||
labelShippingCustomerShadowResolution,
|
||||
publishShippingCustomerImport,
|
||||
updateShippingCustomer,
|
||||
updateShippingCustomerIdentifier,
|
||||
uploadShippingCustomerImport,
|
||||
} from '@/features/admin/api/admin.api';
|
||||
import type {
|
||||
ShippingCustomerFormState,
|
||||
ShippingCustomerImportBatch,
|
||||
ShippingCustomerImportRow,
|
||||
ShippingCustomerRow,
|
||||
ShippingCustomerShadowReport,
|
||||
ShippingIdentifierFormState,
|
||||
} from '@/features/admin/types/shipping-customer.types';
|
||||
import {
|
||||
createEmptyShippingCustomerForm,
|
||||
shippingCustomerToForm,
|
||||
} from '@/features/admin/types/shipping-customer.types';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
export function useShippingCustomersAdmin() {
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const customers = ref<ShippingCustomerRow[]>([]);
|
||||
const importTargetCustomers = ref<ShippingCustomerRow[]>([]);
|
||||
const selectedCustomer = ref<ShippingCustomerRow | null>(null);
|
||||
const customerForm = ref<ShippingCustomerFormState>(createEmptyShippingCustomerForm());
|
||||
const importBatch = ref<ShippingCustomerImportBatch | null>(null);
|
||||
const shadowReport = ref<ShippingCustomerShadowReport | null>(null);
|
||||
const searchQuery = ref('');
|
||||
const statusFilter = ref('');
|
||||
const page = ref(1);
|
||||
const pageSize = ref(20);
|
||||
const total = ref(0);
|
||||
const pages = ref(1);
|
||||
const isLoading = ref(false);
|
||||
const isSaving = ref(false);
|
||||
const isImporting = ref(false);
|
||||
const isShadowLoading = ref(false);
|
||||
const showCustomerModal = ref(false);
|
||||
const showIdentifiersPanel = ref(false);
|
||||
const showImportDialog = ref(false);
|
||||
|
||||
/** 分页加载全部客户选项,供导入冲突和影子真值标签共用。 */
|
||||
const loadAllCustomerOptions = async (): Promise<void> => {
|
||||
const first = await listShippingCustomers({ page: 1, pageSize: 100 });
|
||||
const targets = [...first.items];
|
||||
for (let targetPage = 2; targetPage <= first.pages; targetPage += 1) {
|
||||
const next = await listShippingCustomers({ page: targetPage, pageSize: 100 });
|
||||
targets.push(...next.items);
|
||||
}
|
||||
importTargetCustomers.value = targets;
|
||||
};
|
||||
|
||||
/** 将未知异常转换为已本地化的用户提示。 */
|
||||
const showError = (error: unknown, fallbackKey: string): void => {
|
||||
msg.error(error instanceof BusinessError ? error.message : t(fallbackKey));
|
||||
};
|
||||
|
||||
/** 按当前筛选和分页加载客户列表。 */
|
||||
const loadCustomers = async (): Promise<void> => {
|
||||
isLoading.value = true;
|
||||
try {
|
||||
const result = await listShippingCustomers({
|
||||
q: searchQuery.value,
|
||||
status: statusFilter.value,
|
||||
page: page.value,
|
||||
pageSize: pageSize.value,
|
||||
});
|
||||
customers.value = result.items;
|
||||
total.value = result.total;
|
||||
pages.value = result.pages;
|
||||
} catch (error) {
|
||||
customers.value = [];
|
||||
showError(error, 'admin.shippingCustomers.msg.loadFailed');
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 重置到第一页并按筛选条件查询。 */
|
||||
const searchCustomers = async (): Promise<void> => {
|
||||
page.value = 1;
|
||||
await loadCustomers();
|
||||
};
|
||||
|
||||
/** 打开新建客户弹窗。 */
|
||||
const openCreateCustomer = (): void => {
|
||||
customerForm.value = createEmptyShippingCustomerForm();
|
||||
showCustomerModal.value = true;
|
||||
};
|
||||
|
||||
/** 打开编辑客户弹窗并回填当前行。 */
|
||||
const openEditCustomer = (customer: ShippingCustomerRow): void => {
|
||||
customerForm.value = shippingCustomerToForm(customer);
|
||||
showCustomerModal.value = true;
|
||||
};
|
||||
|
||||
/** 关闭客户弹窗并清空编辑快照。 */
|
||||
const closeCustomerModal = (): void => {
|
||||
showCustomerModal.value = false;
|
||||
customerForm.value = createEmptyShippingCustomerForm();
|
||||
};
|
||||
|
||||
/** 校验并保存标准客户,成功后刷新列表。 */
|
||||
const saveCustomer = async (): Promise<void> => {
|
||||
const form = customerForm.value;
|
||||
if (!form.standard_name.trim()) {
|
||||
msg.warning(t('admin.shippingCustomers.msg.nameRequired'));
|
||||
return;
|
||||
}
|
||||
if (!/^[A-Za-z]{2,6}$/.test(form.short_code.trim())) {
|
||||
msg.warning(t('admin.shippingCustomers.msg.shortCodeInvalid'));
|
||||
return;
|
||||
}
|
||||
isSaving.value = true;
|
||||
try {
|
||||
const payload = {
|
||||
standard_name: form.standard_name.trim(),
|
||||
short_code: form.short_code.trim().toUpperCase(),
|
||||
status: form.status,
|
||||
remark: form.remark.trim(),
|
||||
};
|
||||
if (form.id) await updateShippingCustomer(form.id, payload);
|
||||
else await createShippingCustomer(payload);
|
||||
closeCustomerModal();
|
||||
await loadCustomers();
|
||||
msg.success(t('admin.shippingCustomers.msg.saved'));
|
||||
} catch (error) {
|
||||
showError(error, 'admin.shippingCustomers.msg.saveFailed');
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 停用客户并保留历史业务引用。 */
|
||||
const deactivateCustomer = async (customer: ShippingCustomerRow): Promise<void> => {
|
||||
if (!window.confirm(t('admin.shippingCustomers.confirmDeactivate', { name: customer.standard_name }))) return;
|
||||
try {
|
||||
await deactivateShippingCustomer(customer.id);
|
||||
await loadCustomers();
|
||||
} catch (error) {
|
||||
showError(error, 'admin.shippingCustomers.msg.saveFailed');
|
||||
}
|
||||
};
|
||||
|
||||
/** 拉取客户详情并打开识别证据面板。 */
|
||||
const openIdentifiers = async (customer: ShippingCustomerRow): Promise<void> => {
|
||||
try {
|
||||
selectedCustomer.value = await getShippingCustomer(customer.id);
|
||||
showIdentifiersPanel.value = true;
|
||||
} catch (error) {
|
||||
showError(error, 'admin.shippingCustomers.msg.loadFailed');
|
||||
}
|
||||
};
|
||||
|
||||
/** 新增识别证据后刷新当前客户详情和列表计数。 */
|
||||
const addIdentifier = async (form: ShippingIdentifierFormState): Promise<void> => {
|
||||
if (!selectedCustomer.value) return;
|
||||
if (!form.identifier_value.trim()) {
|
||||
msg.warning(t('admin.shippingCustomers.msg.identifierRequired'));
|
||||
return;
|
||||
}
|
||||
isSaving.value = true;
|
||||
try {
|
||||
await createShippingCustomerIdentifier(selectedCustomer.value.id, {
|
||||
...form,
|
||||
identifier_value: form.identifier_value.trim(),
|
||||
remark: form.remark.trim(),
|
||||
});
|
||||
selectedCustomer.value = await getShippingCustomer(selectedCustomer.value.id);
|
||||
await loadCustomers();
|
||||
msg.success(t('admin.shippingCustomers.msg.identifierSaved'));
|
||||
} catch (error) {
|
||||
showError(error, 'admin.shippingCustomers.msg.saveFailed');
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 更新证据审核状态或自动匹配授权,并刷新详情。 */
|
||||
const updateIdentifier = async (identifierId: number, payload: Record<string, unknown>): Promise<void> => {
|
||||
if (!selectedCustomer.value) return;
|
||||
try {
|
||||
await updateShippingCustomerIdentifier(identifierId, payload);
|
||||
selectedCustomer.value = await getShippingCustomer(selectedCustomer.value.id);
|
||||
} catch (error) {
|
||||
showError(error, 'admin.shippingCustomers.msg.saveFailed');
|
||||
}
|
||||
};
|
||||
|
||||
/** 打开期初导入对话框并清空上次批次。 */
|
||||
const openImport = async (): Promise<void> => {
|
||||
importBatch.value = null;
|
||||
showImportDialog.value = true;
|
||||
try {
|
||||
await loadAllCustomerOptions();
|
||||
} catch (error) {
|
||||
importTargetCustomers.value = [...customers.value];
|
||||
showError(error, 'admin.shippingCustomers.msg.loadFailed');
|
||||
}
|
||||
};
|
||||
|
||||
/** 上传 Excel 并保存预检批次。 */
|
||||
const uploadImport = async (file: File, sourceSystem: string): Promise<void> => {
|
||||
isImporting.value = true;
|
||||
try {
|
||||
importBatch.value = await uploadShippingCustomerImport(file, sourceSystem);
|
||||
msg.success(t('admin.shippingCustomers.import.uploaded'));
|
||||
} catch (error) {
|
||||
showError(error, 'admin.shippingCustomers.import.uploadFailed');
|
||||
} finally {
|
||||
isImporting.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 保存 warning 行决定并同步本地批次行。 */
|
||||
const decideImportRow = async (
|
||||
row: ShippingCustomerImportRow,
|
||||
action: string,
|
||||
targetCustomerId?: number,
|
||||
): Promise<void> => {
|
||||
try {
|
||||
const updated = await decideShippingCustomerImportRow(row.id, {
|
||||
action,
|
||||
target_customer_id: targetCustomerId,
|
||||
}) as ShippingCustomerImportRow;
|
||||
if (importBatch.value) {
|
||||
importBatch.value.rows = importBatch.value.rows.map((item) => item.id === row.id ? updated : item);
|
||||
}
|
||||
} catch (error) {
|
||||
showError(error, 'admin.shippingCustomers.import.decisionFailed');
|
||||
}
|
||||
};
|
||||
|
||||
/** 发布当前导入批次,成功后刷新客户列表。 */
|
||||
const publishImport = async (): Promise<void> => {
|
||||
if (!importBatch.value) return;
|
||||
isImporting.value = true;
|
||||
try {
|
||||
importBatch.value = await publishShippingCustomerImport(importBatch.value.id);
|
||||
await loadCustomers();
|
||||
msg.success(t('admin.shippingCustomers.import.published'));
|
||||
} catch (error) {
|
||||
showError(error, 'admin.shippingCustomers.import.publishFailed');
|
||||
} finally {
|
||||
isImporting.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 下载标准 Excel 模板。 */
|
||||
const downloadTemplate = async (): Promise<void> => {
|
||||
try {
|
||||
await downloadShippingCustomerImportTemplate();
|
||||
} catch (error) {
|
||||
showError(error, 'admin.shippingCustomers.import.downloadFailed');
|
||||
}
|
||||
};
|
||||
|
||||
/** 下载当前批次逐行对账 CSV。 */
|
||||
const downloadReconciliation = async (): Promise<void> => {
|
||||
if (!importBatch.value) return;
|
||||
try {
|
||||
await downloadShippingCustomerReconciliation(importBatch.value.id, importBatch.value.batch_no);
|
||||
} catch (error) {
|
||||
showError(error, 'admin.shippingCustomers.import.downloadFailed');
|
||||
}
|
||||
};
|
||||
|
||||
/** 加载影子识别质量报告;未标注样本不计算准确率。 */
|
||||
const loadShadowReport = async (): Promise<void> => {
|
||||
isShadowLoading.value = true;
|
||||
try {
|
||||
const [report] = await Promise.all([
|
||||
getShippingCustomerShadowReport(100),
|
||||
importTargetCustomers.value.length ? Promise.resolve() : loadAllCustomerOptions(),
|
||||
]);
|
||||
shadowReport.value = report;
|
||||
} catch (error) {
|
||||
showError(error, 'admin.shippingCustomers.shadow.loadFailed');
|
||||
} finally {
|
||||
isShadowLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 写入影子样本人工真值并刷新报告;不执行客户绑定。 */
|
||||
const labelShadowResolution = async (resolutionId: number, customerId: number): Promise<void> => {
|
||||
try {
|
||||
await labelShippingCustomerShadowResolution(resolutionId, customerId);
|
||||
await loadShadowReport();
|
||||
msg.success(t('admin.shippingCustomers.shadow.labeled'));
|
||||
} catch (error) {
|
||||
showError(error, 'admin.shippingCustomers.shadow.labelFailed');
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
customers, importTargetCustomers, selectedCustomer, customerForm, importBatch, shadowReport,
|
||||
searchQuery, statusFilter, page, pageSize, total, pages,
|
||||
isLoading, isSaving, isImporting, isShadowLoading,
|
||||
showCustomerModal, showIdentifiersPanel, showImportDialog,
|
||||
loadCustomers, searchCustomers, openCreateCustomer, openEditCustomer, closeCustomerModal,
|
||||
saveCustomer, deactivateCustomer, openIdentifiers, addIdentifier, updateIdentifier,
|
||||
openImport, uploadImport, decideImportRow, publishImport, downloadTemplate, downloadReconciliation,
|
||||
loadShadowReport, labelShadowResolution,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
/**
|
||||
* features/admin/types/shipping-customer.types.ts
|
||||
* 用途:货代客户主数据、识别证据和期初导入管理端类型契约。
|
||||
* 依赖:无运行时依赖。
|
||||
* 逻辑:admin.api 返回这些结构;shipping-customers 页面与组件据此渲染和提交。
|
||||
*/
|
||||
|
||||
export type ShippingCustomerStatus = 'active' | 'inactive';
|
||||
export type ShippingIdentifierStatus = 'pending' | 'approved' | 'disabled';
|
||||
export type ShippingImportDecision = 'create' | 'update' | 'merge' | 'skip';
|
||||
|
||||
export interface ShippingCustomerIdentifier {
|
||||
id: number;
|
||||
customer_id: number;
|
||||
identifier_type: string;
|
||||
raw_value: string;
|
||||
normalized_value: string;
|
||||
auto_match_allowed: boolean;
|
||||
status: ShippingIdentifierStatus;
|
||||
source: string;
|
||||
remark?: string | null;
|
||||
confirmed_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingCustomerRow {
|
||||
id: number;
|
||||
standard_name: string;
|
||||
short_code: string;
|
||||
status: ShippingCustomerStatus;
|
||||
remark?: string | null;
|
||||
case_count: number;
|
||||
identifier_count: number;
|
||||
identifiers?: ShippingCustomerIdentifier[];
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingCustomerPage {
|
||||
items: ShippingCustomerRow[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
pages: number;
|
||||
}
|
||||
|
||||
export interface ShippingImportIssue {
|
||||
code: string;
|
||||
field?: string;
|
||||
customer_id?: number;
|
||||
candidate_customer_ids?: number[];
|
||||
}
|
||||
|
||||
export interface ShippingCustomerImportRow {
|
||||
id: number;
|
||||
sheet_name: string;
|
||||
row_no: number;
|
||||
row_type: 'customer' | 'identifier';
|
||||
legacy_customer_key?: string | null;
|
||||
raw: Record<string, unknown>;
|
||||
normalized: Record<string, unknown>;
|
||||
validation_status: 'valid' | 'warning' | 'error';
|
||||
errors: ShippingImportIssue[];
|
||||
warnings: ShippingImportIssue[];
|
||||
suggested_action?: ShippingImportDecision | null;
|
||||
decision_action?: ShippingImportDecision | null;
|
||||
target_customer_id?: number | null;
|
||||
decision_note?: string | null;
|
||||
result_customer_id?: number | null;
|
||||
result_status?: string | null;
|
||||
result_message?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingCustomerImportBatch {
|
||||
id: number;
|
||||
batch_no: string;
|
||||
file_name: string;
|
||||
file_hash: string;
|
||||
file_size: number;
|
||||
source_system: string;
|
||||
status: string;
|
||||
total_rows: number;
|
||||
valid_rows: number;
|
||||
warning_rows: number;
|
||||
error_rows: number;
|
||||
published_rows: number;
|
||||
published_at?: string | null;
|
||||
created_at?: string | null;
|
||||
rows: ShippingCustomerImportRow[];
|
||||
idempotent_replay?: boolean;
|
||||
}
|
||||
|
||||
export interface ShippingCustomerShadowItem {
|
||||
id: number;
|
||||
candidate_id: number;
|
||||
intake_id: number;
|
||||
candidate_no?: string | null;
|
||||
intake_no?: string | null;
|
||||
resolution_version: string;
|
||||
status: 'unique_candidate' | 'ambiguous' | 'unmatched' | 'failed';
|
||||
evidence: Array<Record<string, unknown>>;
|
||||
matches: Array<{ customer_id: number; standard_name: string; short_code: string; score: number }>;
|
||||
top_customer_id?: number | null;
|
||||
top_score?: number | null;
|
||||
manual_customer_id?: number | null;
|
||||
manual_customer_name?: string | null;
|
||||
manual_customer_short_code?: string | null;
|
||||
is_correct?: boolean | null;
|
||||
labeled_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingCustomerShadowReport {
|
||||
total: number;
|
||||
status_counts: Record<string, number>;
|
||||
labeled_count: number;
|
||||
correct_count: number;
|
||||
accuracy?: number | null;
|
||||
auto_bound_count: number;
|
||||
auto_resolution?: {
|
||||
enabled: boolean;
|
||||
rule_version: string;
|
||||
evaluated_count: number;
|
||||
auto_confirmed_count: number;
|
||||
corrected_task_count: number;
|
||||
historical_backfilled_count: number;
|
||||
auto_confirmation_rate?: number | null;
|
||||
recent_events: Array<{
|
||||
id: number;
|
||||
task_no: string;
|
||||
event_type: string;
|
||||
detail: Record<string, unknown>;
|
||||
created_at?: string | null;
|
||||
}>;
|
||||
};
|
||||
items: ShippingCustomerShadowItem[];
|
||||
}
|
||||
|
||||
export interface ShippingCustomerFormState {
|
||||
id?: number;
|
||||
standard_name: string;
|
||||
short_code: string;
|
||||
status: ShippingCustomerStatus;
|
||||
remark: string;
|
||||
}
|
||||
|
||||
export interface ShippingIdentifierFormState {
|
||||
identifier_type: string;
|
||||
identifier_value: string;
|
||||
status: ShippingIdentifierStatus;
|
||||
auto_match_allowed: boolean;
|
||||
remark: string;
|
||||
}
|
||||
|
||||
/** 创建空客户表单,避免页面和弹窗各自维护默认值。 */
|
||||
export const createEmptyShippingCustomerForm = (): ShippingCustomerFormState => ({
|
||||
standard_name: '',
|
||||
short_code: '',
|
||||
status: 'active',
|
||||
remark: '',
|
||||
});
|
||||
|
||||
/** 将客户详情转换为可编辑表单快照。 */
|
||||
export const shippingCustomerToForm = (customer: ShippingCustomerRow): ShippingCustomerFormState => ({
|
||||
id: customer.id,
|
||||
standard_name: customer.standard_name,
|
||||
short_code: customer.short_code,
|
||||
status: customer.status,
|
||||
remark: customer.remark || '',
|
||||
});
|
||||
|
||||
/** 创建空识别证据表单,默认待审核且禁止自动匹配。 */
|
||||
export const createEmptyShippingIdentifierForm = (): ShippingIdentifierFormState => ({
|
||||
identifier_type: 'name_alias',
|
||||
identifier_value: '',
|
||||
status: 'pending',
|
||||
auto_match_allowed: false,
|
||||
remark: '',
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* features/chat/api/chat.api.spec.ts
|
||||
* 用途:验证聊天历史接口适配层不会在 hydrate 过程中丢失用户附件快照。
|
||||
* 依赖:Vitest、mock 后的 shared/api/client 与 auth、chat.api。
|
||||
* 逻辑:覆盖历史消息过滤 shipping-parse-review、恢复订单识别状态时仍保留 attachments。
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { listChatMessages } from './chat.api';
|
||||
|
||||
vi.mock('@/shared/utils/auth', () => ({
|
||||
getAuthHeaders: vi.fn(() => ({ Authorization: 'Bearer test-token' })),
|
||||
}));
|
||||
|
||||
vi.mock('@/shared/api/client', () => ({
|
||||
requestJson: vi.fn(),
|
||||
}));
|
||||
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
|
||||
const requestJsonMock = vi.mocked(requestJson);
|
||||
|
||||
describe('chat.api history hydration', () => {
|
||||
beforeEach(() => {
|
||||
requestJsonMock.mockReset();
|
||||
});
|
||||
|
||||
it('keeps user attachment snapshots while hydrating persisted assistant payload', async () => {
|
||||
requestJsonMock.mockResolvedValue([
|
||||
{
|
||||
role: 'user',
|
||||
content: '',
|
||||
attachments: [{
|
||||
id: 'attachment-only-1',
|
||||
name: 'notice.eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}],
|
||||
},
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '中间态消息',
|
||||
type: 'shipping-parse-review',
|
||||
},
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '订单识别完成',
|
||||
payload: {
|
||||
shipping_order_extraction_state: {
|
||||
status: 'completed',
|
||||
phase: 'result_persisted',
|
||||
message: '已创建 1 个任务',
|
||||
created_count: 1,
|
||||
opened_existing_count: 0,
|
||||
pending_count: 0,
|
||||
non_shipping_count: 0,
|
||||
created_with_missing_fields_count: 0,
|
||||
batch_no: 'SB-HISTORY-001',
|
||||
terminal: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const messages = await listChatMessages('conv-history-1', 24);
|
||||
|
||||
expect(requestJsonMock).toHaveBeenCalledWith(
|
||||
'/api/chat/messages?conversation_id=conv-history-1&agent_id=24',
|
||||
{ headers: { Authorization: 'Bearer test-token' } },
|
||||
);
|
||||
expect(messages).toHaveLength(2);
|
||||
expect(messages[0]).toEqual({
|
||||
role: 'user',
|
||||
content: '',
|
||||
attachments: [{
|
||||
id: 'attachment-only-1',
|
||||
name: 'notice.eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}],
|
||||
});
|
||||
expect(messages[1]?.shipping_order_extraction_state).toMatchObject({
|
||||
status: 'completed',
|
||||
batch_no: 'SB-HISTORY-001',
|
||||
terminal: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
/**
|
||||
* features/chat/api/chat.api.ts
|
||||
* 聊天域 HTTP API:会话、消息、源文件、附件上传。
|
||||
* 用途:封装聊天会话、消息、源文件与附件上传 HTTP API,并恢复结构化历史消息状态。
|
||||
* 依赖:shared/api/client、鉴权工具、chat.types。
|
||||
* 逻辑:页面 composable 调用本模块;历史消息响应在返回前将 ChatLog.payload 中的领域状态投影到 ChatMessage。
|
||||
*/
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
@@ -14,6 +16,7 @@ import type {
|
||||
ChatSourceFileResult,
|
||||
ChatUploadResult,
|
||||
OaEmployeesResponse,
|
||||
ShippingOrderExtractionState,
|
||||
} from '../types/chat.types';
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
@@ -28,10 +31,30 @@ export const deleteAllChatSessions = (agentId: number) =>
|
||||
export const deleteChatSession = (conversationId: string, agentId: number) =>
|
||||
requestJson(`/api/chat/sessions/${conversationId}?agent_id=${agentId}`, { method: 'DELETE', ...auth() });
|
||||
|
||||
/**
|
||||
* 从 ChatLog.payload 恢复订单识别终态,保证刷新会话后与实时 SSE 消息形状一致。
|
||||
* 核心逻辑:仅接受带合法 status 的对象;服务端仍是终态事实源,本函数不推导或改写计数。
|
||||
* @param message - 历史接口返回的单条消息。
|
||||
* @returns 原消息或已补充 shipping_order_extraction_state 的消息。
|
||||
*/
|
||||
export const hydrateShippingOrderExtractionState = (message: ChatMessage): ChatMessage => {
|
||||
const payload = message.payload && typeof message.payload === 'object'
|
||||
? message.payload as Record<string, unknown>
|
||||
: {};
|
||||
const state = payload.shipping_order_extraction_state;
|
||||
if (!state || typeof state !== 'object') return message;
|
||||
const status = String((state as Record<string, unknown>).status || '');
|
||||
if (!['extracting', 'completed', 'partially_completed', 'failed'].includes(status)) return message;
|
||||
message.shipping_order_extraction_state = state as ShippingOrderExtractionState;
|
||||
return message;
|
||||
};
|
||||
|
||||
export const listChatMessages = async (conversationId: string, agentId: number) => {
|
||||
const messages = await requestJson<ChatMessage[]>(`/api/chat/messages?conversation_id=${conversationId}&agent_id=${agentId}`, auth());
|
||||
return Array.isArray(messages)
|
||||
? messages.filter((message) => message?.type !== 'shipping-parse-review')
|
||||
? messages
|
||||
.filter((message) => message?.type !== 'shipping-parse-review')
|
||||
.map(hydrateShippingOrderExtractionState)
|
||||
: messages;
|
||||
};
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ import type {
|
||||
ShippingTaskCreateResponse,
|
||||
ShippingTaskDetail,
|
||||
ShippingTaskSummary,
|
||||
ShippingCustomerOption,
|
||||
ShippingTaskUiState,
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
@@ -154,6 +155,20 @@ export async function confirmWorkspaceShippingInventorySource(taskNo: string, so
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/** 搜索可供业务用户确认的启用标准客户。 */
|
||||
export const listWorkspaceShippingCustomerOptions = (query = '') => {
|
||||
const params = new URLSearchParams({ limit: '200' });
|
||||
if (query.trim()) params.set('q', query.trim());
|
||||
return requestJson<ShippingCustomerOption[]>(`/api/workspace/shipping-customers?${params.toString()}`);
|
||||
};
|
||||
|
||||
/** 为任务确认标准客户;确认成功后响应包含正式业务编号。 */
|
||||
export const confirmWorkspaceShippingCustomer = (taskNo: string, customerId: number) =>
|
||||
requestJson<ShippingTaskDetail>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/confirm-customer`,
|
||||
jsonPost({ customer_id: customerId }),
|
||||
);
|
||||
|
||||
/**
|
||||
* 提交库存字段映射。
|
||||
* @param taskNo - 发货任务编号
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* features/chat/components/ChatInputBar.vue
|
||||
* 聊天输入栏:文本框、附件、语音、知识库选择与发送按钮。
|
||||
* 逻辑:设备维保助手的管理入口(设备台账、登记维修)与语音按钮同侧排列,发送按钮独占右侧。
|
||||
* 用途:承载聊天文本输入、附件预览、语音、知识库选择与发送操作。
|
||||
* 依赖:lucide 图标、ShippingNoticeCandidateReview、附件完整性判断工具。
|
||||
* 逻辑:附件卡片位于文本框上方;发货通知保留解析/重复处理能力,普通附件展示逐文件上传状态。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
@@ -10,7 +11,13 @@ import type { Ref } from 'vue';
|
||||
import {
|
||||
Check,
|
||||
ChevronDown,
|
||||
CircleAlert,
|
||||
CircleCheck,
|
||||
Database,
|
||||
FileAudio,
|
||||
FileImage,
|
||||
FileText,
|
||||
FileVideo,
|
||||
Link2,
|
||||
Loader2,
|
||||
Mic,
|
||||
@@ -26,6 +33,13 @@ import {
|
||||
isBlockingWarning,
|
||||
isShippingNoticeAttachmentParseIncomplete,
|
||||
} from '../shipping/shippingNoticeAttachmentIntegrity';
|
||||
import {
|
||||
getAttachmentCardStatus,
|
||||
getAttachmentExtension,
|
||||
getAttachmentName,
|
||||
getAttachmentSize,
|
||||
isAttachmentRemoveDisabled,
|
||||
} from '../utils/attachmentCard.utils';
|
||||
|
||||
export interface ChatInputAttachmentPolicy {
|
||||
anyEnabled: boolean;
|
||||
@@ -156,6 +170,15 @@ function shippingNoticeAttachmentTitle(attachment: ShippingNoticePendingAttachme
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/** 根据附件业务类型选择文件图标,帮助用户快速区分媒体与文档。 */
|
||||
function attachmentIcon(attachment: PendingAttachment) {
|
||||
if (attachment.kind === 'remote') return Link2;
|
||||
if (attachment.type === 'image') return FileImage;
|
||||
if (attachment.type === 'audio') return FileAudio;
|
||||
if (attachment.type === 'video') return FileVideo;
|
||||
return FileText;
|
||||
}
|
||||
|
||||
const closeAttachmentMenu = () => {
|
||||
showAttachmentMenu.value = false;
|
||||
showAttachmentUrlPanel.value = false;
|
||||
@@ -293,6 +316,92 @@ watch(
|
||||
@resolve-duplicate="(candidateNo, action, targetTaskNo, reason, done) => emit('resolve-shipping-candidate-duplicate', candidateNo, action, targetTaskNo, reason, done)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="attachments.length > 0"
|
||||
data-testid="chat-attachment-list"
|
||||
class="flex flex-wrap gap-2 px-2.5 pb-2 pt-1"
|
||||
>
|
||||
<article
|
||||
v-for="a in attachments"
|
||||
:key="a.id"
|
||||
class="group relative flex min-w-0 basis-full items-center gap-3 rounded-xl border border-default bg-surface-soft px-3 py-2.5 transition-colors sm:basis-[calc(50%-0.25rem)] lg:max-w-[310px]"
|
||||
:title="a.kind === 'shipping_notice' ? shippingNoticeAttachmentTitle(a) : getAttachmentName(a)"
|
||||
>
|
||||
<div
|
||||
class="flex h-11 w-10 shrink-0 flex-col items-center justify-center rounded-lg bg-brand-50 text-brand-700 dark:bg-brand-900/30 dark:text-brand-300"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<component :is="attachmentIcon(a)" class="h-4.5 w-4.5" />
|
||||
<span class="mt-0.5 max-w-9 truncate text-[9px] font-bold leading-none">{{ getAttachmentExtension(a) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="min-w-0 flex-1 pr-5">
|
||||
<p class="truncate text-sm font-medium text-primary">{{ getAttachmentName(a) }}</p>
|
||||
<div class="mt-1 flex min-w-0 items-center gap-1.5 text-[11px] leading-none">
|
||||
<span v-if="getAttachmentSize(a)" class="shrink-0 text-muted">{{ getAttachmentSize(a) }}</span>
|
||||
<span v-if="getAttachmentSize(a)" class="text-slate-300">·</span>
|
||||
<span
|
||||
class="flex min-w-0 items-center gap-1 truncate"
|
||||
:class="{
|
||||
'text-muted': getAttachmentCardStatus(a).state === 'pending',
|
||||
'text-brand-600': ['uploading', 'processing'].includes(getAttachmentCardStatus(a).state),
|
||||
'text-amber-700': getAttachmentCardStatus(a).state === 'attention',
|
||||
'text-emerald-600': getAttachmentCardStatus(a).state === 'ready',
|
||||
'text-red-500': getAttachmentCardStatus(a).state === 'failed',
|
||||
}"
|
||||
>
|
||||
<Loader2
|
||||
v-if="['uploading', 'processing'].includes(getAttachmentCardStatus(a).state)"
|
||||
class="h-3 w-3 shrink-0 animate-spin"
|
||||
/>
|
||||
<CircleCheck v-else-if="getAttachmentCardStatus(a).state === 'ready'" class="h-3 w-3 shrink-0" />
|
||||
<CircleAlert v-else-if="['attention', 'failed'].includes(getAttachmentCardStatus(a).state)" class="h-3 w-3 shrink-0" />
|
||||
<span class="truncate">{{ t(getAttachmentCardStatus(a).labelKey) }}</span>
|
||||
<template v-if="a.kind === 'shipping_notice' && shippingNoticeAttachmentHint(a)">
|
||||
<span class="truncate">· {{ shippingNoticeAttachmentHint(a) }}</span>
|
||||
</template>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="a.kind === 'shipping_notice' && (canRetryShippingNoticeParse(a) || (!a.candidates?.length && a.duplicate?.blocking && !a.duplicateResolution?.action))"
|
||||
class="absolute bottom-1.5 right-2 flex items-center gap-1"
|
||||
>
|
||||
<button
|
||||
v-if="!a.candidates?.length && a.duplicate?.blocking && !a.duplicateResolution?.action"
|
||||
type="button"
|
||||
class="rounded px-1.5 py-1 text-[10px] font-medium text-amber-700 hover:bg-amber-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-400"
|
||||
:title="t('chat.shippingNoticeDuplicateHandle')"
|
||||
@click="emit('resolve-shipping-notice-duplicate', a.id)"
|
||||
>
|
||||
{{ t('chat.shippingNoticeDuplicateHandle') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canRetryShippingNoticeParse(a)"
|
||||
type="button"
|
||||
class="rounded p-1 text-muted hover:bg-surface hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-400"
|
||||
:title="t('chat.shippingNoticeRetryParse')"
|
||||
@click="emit('retry-shipping-notice-attachment', a.id)"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="absolute right-1.5 top-1.5 flex h-6 w-6 items-center justify-center rounded-full text-muted opacity-80 transition hover:bg-surface hover:text-red-500 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-400 disabled:cursor-not-allowed disabled:opacity-30"
|
||||
:disabled="isAttachmentRemoveDisabled(a)"
|
||||
:title="t('chat.attachment.remove')"
|
||||
:aria-label="t('chat.attachment.removeNamed', { name: getAttachmentName(a) })"
|
||||
@click="emit('remove-attachment', a.id)"
|
||||
>
|
||||
<X class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<textarea
|
||||
ref="textareaRef"
|
||||
v-model="inputValue"
|
||||
@@ -324,77 +433,6 @@ watch(
|
||||
@change="emit('local-files-selected', $event)"
|
||||
/>
|
||||
|
||||
<div v-if="attachments.length > 0" class="flex flex-wrap gap-2 px-3 pb-1">
|
||||
<div
|
||||
v-for="a in attachments"
|
||||
:key="a.id"
|
||||
class="flex items-center gap-2 rounded-lg border border-default bg-surface-soft px-2 py-1 text-xs text-secondary"
|
||||
>
|
||||
<span class="max-w-[220px] truncate">
|
||||
<template v-if="a.kind === 'shipping_notice'">
|
||||
{{ a.originalFilename }}
|
||||
<span v-if="a.uploadStatus === 'uploading'" class="text-muted"> · {{ t('chat.shippingNoticeUploading') }}</span>
|
||||
<span v-else-if="a.parseStatus === 'queued' || a.parseStatus === 'parsing'" class="text-muted"> · {{ t('chat.shippingNoticeParsing') }}</span>
|
||||
<span
|
||||
v-else-if="a.parseStatus === 'parsed' && !a.candidates?.length && a.duplicate?.status === 'possible_duplicate' && !a.duplicateResolution?.action"
|
||||
class="font-medium text-amber-700"
|
||||
> · {{ t('chat.shippingNoticeDuplicatePossibleBadge') }}</span>
|
||||
<span
|
||||
v-else-if="a.parseStatus === 'parsed' && !a.candidates?.length && a.duplicate?.blocking && !a.duplicateResolution?.action"
|
||||
class="font-medium text-amber-700"
|
||||
> · {{ t('chat.shippingNoticeDuplicateBlockingBadge') }}</span>
|
||||
<span
|
||||
v-else-if="a.parseStatus === 'parsed' && a.duplicateResolution?.action === 'create_revision'"
|
||||
class="text-brand-700"
|
||||
> · {{ t('chat.shippingNoticeDuplicateRevisionChosen') }}</span>
|
||||
<span
|
||||
v-else-if="a.parseStatus === 'parsed' && a.duplicateResolution?.action === 'force_create'"
|
||||
class="text-amber-700"
|
||||
> · {{ t('chat.shippingNoticeDuplicateForceChosen') }}</span>
|
||||
<span
|
||||
v-else-if="a.parseStatus === 'parsed' && a.duplicateResolution?.action === 'open_existing'"
|
||||
class="text-muted"
|
||||
> · {{ t('chat.shippingNoticeDuplicateOpenChosen') }}</span>
|
||||
<span
|
||||
v-else-if="a.parseStatus === 'parsed'"
|
||||
class="text-muted"
|
||||
:title="shippingNoticeAttachmentTitle(a)"
|
||||
>
|
||||
· {{ t('chat.shippingNoticeParsed') }}
|
||||
<template v-if="shippingNoticeAttachmentHint(a)">
|
||||
· {{ shippingNoticeAttachmentHint(a) }}
|
||||
</template>
|
||||
</span>
|
||||
<span v-else-if="a.parseStatus === 'failed'" class="text-muted"> · {{ t('chat.shippingNoticeParseFailed') }}</span>
|
||||
</template>
|
||||
<template v-else>
|
||||
{{ a.kind === 'local' ? a.file.name : a.url }}
|
||||
</template>
|
||||
</span>
|
||||
<button
|
||||
v-if="a.kind === 'shipping_notice' && !a.candidates?.length && a.duplicate?.blocking && !a.duplicateResolution?.action"
|
||||
type="button"
|
||||
class="text-amber-700 hover:text-amber-800"
|
||||
:title="t('chat.shippingNoticeDuplicateHandle')"
|
||||
@click="emit('resolve-shipping-notice-duplicate', a.id)"
|
||||
>
|
||||
{{ t('chat.shippingNoticeDuplicateHandle') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="a.kind === 'shipping_notice' && canRetryShippingNoticeParse(a)"
|
||||
type="button"
|
||||
class="text-muted hover:text-primary"
|
||||
:title="t('chat.shippingNoticeRetryParse')"
|
||||
@click="emit('retry-shipping-notice-attachment', a.id)"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button type="button" class="text-muted hover:text-red-500" @click="emit('remove-attachment', a.id)">
|
||||
<X class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="isShippingNoticeAgent && attachments.length > 0"
|
||||
class="flex flex-wrap items-center gap-2 px-3 pb-1 text-xs text-muted"
|
||||
|
||||
@@ -11,6 +11,7 @@ import ChatLeaveAgentDialog from '@/features/chat/components/ChatLeaveAgentDialo
|
||||
import ChatOALoginDialog from '@/features/chat/components/ChatOALoginDialog.vue';
|
||||
import ChatGuideModal from '@/features/chat/components/ChatGuideModal.vue';
|
||||
import ShippingNoticeDuplicateDialog from '@/features/chat/components/ShippingNoticeDuplicateDialog.vue';
|
||||
import ShippingCustomerConfirmDialog from '@/features/chat/components/ShippingCustomerConfirmDialog.vue';
|
||||
import { Check, Loader2, X } from 'lucide-vue-next';
|
||||
import { nextTick } from 'vue';
|
||||
import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
@@ -155,4 +156,12 @@ async function handleQueryPreviewAssetImage(assetId: string, assetName: string)
|
||||
@remove="() => void page.removeShippingDuplicateDialogAttachment?.()"
|
||||
@cancel="page.closeShippingDuplicateDialog?.()"
|
||||
/>
|
||||
<ShippingCustomerConfirmDialog
|
||||
:open="!!page.showShippingCustomerDialog"
|
||||
:options="page.shippingCustomerOptions || []"
|
||||
:loading="!!page.shippingCustomerLoading"
|
||||
@close="page.closeShippingCustomerDialog?.()"
|
||||
@search="(query) => void page.searchShippingCustomers?.(query)"
|
||||
@confirm="(customerId) => void page.confirmShippingCustomer?.(customerId)"
|
||||
/>
|
||||
</template>
|
||||
@@ -563,7 +563,12 @@ const handleSwitchBatch = (batchNo: string) => {
|
||||
></div>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="truncate font-mono text-sm font-bold text-primary">{{ task.task_no }}</div>
|
||||
<div class="truncate font-mono text-sm font-bold text-primary">
|
||||
{{ task.business_no || task.task_no }}
|
||||
</div>
|
||||
<div v-if="task.business_no" class="mt-0.5 truncate font-mono text-[10px] text-muted">
|
||||
{{ t('chat.shippingNoticeUi.technicalTaskNo', { taskNo: task.task_no }) }}
|
||||
</div>
|
||||
<div class="mt-0.5 truncate text-xs text-muted">
|
||||
{{ task.source_file_name || task.customer_name || t('chat.shippingNoticeUi.currentNotice') }}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<!--
|
||||
features/chat/components/ShippingCustomerConfirmDialog.vue
|
||||
用途:在 customer_review 检查点搜索并确认启用标准客户。
|
||||
依赖:ShippingCustomerOption、vue-i18n。
|
||||
逻辑:父 composable 提供选项与提交动作;本组件不解析邮件客户名,也不创建客户资料。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingCustomerOption } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{ open: boolean; options: ShippingCustomerOption[]; loading: boolean }>();
|
||||
const emit = defineEmits<{ close: []; search: [query: string]; confirm: [customerId: number] }>();
|
||||
const { t } = useI18n();
|
||||
const query = ref('');
|
||||
const selectedId = ref<number | null>(null);
|
||||
|
||||
/** 每次打开对话框时清空上次选择。 */
|
||||
watch(() => props.open, (open) => {
|
||||
if (open) {
|
||||
query.value = '';
|
||||
selectedId.value = null;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="open" class="admin-modal-overlay animate-fade-in items-center z-[170]">
|
||||
<div class="admin-modal-panel max-w-xl max-h-[90vh] scale-100">
|
||||
<div class="px-6 py-5 border-b border-subtle"><h3 class="section-title">{{ t('chat.shippingCustomer.title') }}</h3><p class="section-desc mt-1">{{ t('chat.shippingCustomer.subtitle') }}</p></div>
|
||||
<div class="px-6 py-5 space-y-4 overflow-y-auto">
|
||||
<div class="flex gap-2"><input v-model="query" class="input-field text-sm" :placeholder="t('chat.shippingCustomer.searchPlaceholder')" @keyup.enter="emit('search', query)" /><button type="button" class="btn-ghost" @click="emit('search', query)">{{ t('chat.shippingCustomer.search') }}</button></div>
|
||||
<div class="space-y-2 max-h-80 overflow-y-auto">
|
||||
<label v-for="customer in options" :key="customer.id" class="flex items-center gap-3 rounded-xl border border-default p-3 cursor-pointer hover:border-brand-300"><input v-model="selectedId" type="radio" :value="customer.id" /><span class="flex-1"><span class="font-medium text-primary">{{ customer.standard_name }}</span><span class="ml-2 font-mono text-xs text-muted">{{ customer.short_code }}</span></span></label>
|
||||
<div v-if="!loading && !options.length" class="text-sm text-muted py-8 text-center">{{ t('chat.shippingCustomer.empty') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-modal-footer"><button type="button" class="btn-ghost" @click="emit('close')">{{ t('common.cancel') }}</button><button type="button" class="btn-primary" :disabled="!selectedId || loading" @click="selectedId && emit('confirm', selectedId)">{{ t('chat.shippingCustomer.confirm') }}</button></div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -14,7 +14,7 @@ interface EditableCandidateLine {
|
||||
sku: string;
|
||||
qty: string;
|
||||
reservation_id: string;
|
||||
hub_code: string;
|
||||
source_type: string;
|
||||
uom: string;
|
||||
}
|
||||
|
||||
@@ -44,7 +44,12 @@ watch(() => props.attachment.candidates, () => {
|
||||
}
|
||||
});
|
||||
|
||||
/** 将 Candidate 摘要投影为业务用户可编辑的 PO、SKU、Qty、Reservation 与 Hub 字段。 */
|
||||
/**
|
||||
* 将 Candidate 摘要投影为可编辑的 PO 与订单行。
|
||||
* 核心逻辑:保留原始扩展字段,并显式映射 SKU、数量、Reservation ID、Source Type 与单位。
|
||||
* @param candidateNo - 待编辑的 Candidate 编号
|
||||
* @returns 无返回值;Candidate 不存在时保持当前编辑状态
|
||||
*/
|
||||
function startEdit(candidateNo: string): void {
|
||||
const candidate = candidates.value.find((item) => item.candidateNo === candidateNo);
|
||||
if (!candidate) return;
|
||||
@@ -58,30 +63,41 @@ function startEdit(candidateNo: string): void {
|
||||
sku: String(line.sku || ''),
|
||||
qty: String(line.qty ?? ''),
|
||||
reservation_id: String(line.reservation_id || ''),
|
||||
hub_code: String(line.hub_code || ''),
|
||||
source_type: String(line.source_type || ''),
|
||||
uom: String(line.uom || 'EA'),
|
||||
})));
|
||||
if (!editLines.length) addLine();
|
||||
editError.value = '';
|
||||
}
|
||||
|
||||
/** 新增一条待修订订单行。 */
|
||||
/**
|
||||
* 新增一条待修订订单行。
|
||||
* 核心逻辑:创建带可选 Source Type 路由线索的空白草稿。
|
||||
* @returns 无返回值
|
||||
*/
|
||||
function addLine(): void {
|
||||
editLines.push({ source: {}, sku: '', qty: '', reservation_id: '', hub_code: '', uom: 'EA' });
|
||||
editLines.push({ source: {}, sku: '', qty: '', reservation_id: '', source_type: '', uom: 'EA' });
|
||||
}
|
||||
|
||||
/** 校验所有订单行后提交,不允许空 SKU、非正数数量或空行静默通过。 */
|
||||
/**
|
||||
* 校验并提交 Candidate 修订。
|
||||
* 核心逻辑:保留原始扩展字段,并将 Source Type 作为唯一可选库存路由线索提交。
|
||||
* @returns 无返回值;校验失败时写入本地错误提示
|
||||
*/
|
||||
function saveEdit(): void {
|
||||
const candidate = candidates.value.find((item) => item.candidateNo === editingCandidateNo.value);
|
||||
if (!candidate || !editLines.length) return;
|
||||
const normalizedLines = editLines.map((line) => ({
|
||||
...line.source,
|
||||
sku: line.sku.trim(),
|
||||
qty: Number(line.qty),
|
||||
reservation_id: line.reservation_id.trim() || undefined,
|
||||
hub_code: line.hub_code.trim() || undefined,
|
||||
uom: line.uom.trim() || 'EA',
|
||||
}));
|
||||
const normalizedLines = editLines.map((line) => {
|
||||
const source = { ...line.source };
|
||||
return {
|
||||
...source,
|
||||
sku: line.sku.trim(),
|
||||
qty: Number(line.qty),
|
||||
reservation_id: line.reservation_id.trim() || undefined,
|
||||
source_type: line.source_type.trim() || undefined,
|
||||
uom: line.uom.trim() || 'EA',
|
||||
};
|
||||
});
|
||||
if (normalizedLines.some((line) => !line.sku || !Number.isFinite(line.qty) || line.qty <= 0)) {
|
||||
editError.value = t('chat.shippingCandidateInvalidLine');
|
||||
return;
|
||||
@@ -200,7 +216,7 @@ function submitForceCreate(candidateNo: string): void {
|
||||
<input v-model="line.sku" :placeholder="t('chat.shippingCandidateSku')" class="rounded border border-default px-2 py-1" />
|
||||
<input v-model="line.qty" type="number" min="0.0001" step="any" :placeholder="t('chat.shippingCandidateQty')" class="rounded border border-default px-2 py-1" />
|
||||
<input v-model="line.reservation_id" :placeholder="t('chat.shippingCandidateReservation')" class="rounded border border-default px-2 py-1" />
|
||||
<input v-model="line.hub_code" :placeholder="t('chat.shippingCandidateHubCode')" class="rounded border border-default px-2 py-1" />
|
||||
<input v-model="line.source_type" :placeholder="t('chat.shippingCandidateSourceType')" class="rounded border border-default px-2 py-1" />
|
||||
<div class="flex gap-1">
|
||||
<input v-model="line.uom" :placeholder="t('chat.shippingCandidateUom')" class="min-w-0 flex-1 rounded border border-default px-2 py-1" />
|
||||
<button v-if="editLines.length > 1" type="button" class="text-red-600" @click="editLines.splice(index, 1)">×</button>
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* features/chat/components/messages/ChatMessageAttachmentList.vue
|
||||
* 用途:在用户消息中展示已发送附件快照。
|
||||
* 依赖:lucide 文件图标、attachmentCard.utils 的大小格式化、chat.types 的消息附件契约。
|
||||
* 逻辑:ChatMessageBubble 将当前用户消息附件传入;本组件只读展示,不提供删除、重试或上传状态操作。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { FileAudio, FileImage, FileText, FileVideo, Link2 } from 'lucide-vue-next';
|
||||
import { formatAttachmentSize } from '../../utils/attachmentCard.utils';
|
||||
import type { ChatMessageAttachment } from '../../types/chat.types';
|
||||
|
||||
const { attachments } = defineProps<{
|
||||
attachments: ChatMessageAttachment[];
|
||||
}>();
|
||||
|
||||
/** 根据附件来源与业务类型选择只读消息卡片图标。 */
|
||||
function attachmentIcon(attachment: ChatMessageAttachment) {
|
||||
if (attachment.source === 'remote') return Link2;
|
||||
if (attachment.type === 'image') return FileImage;
|
||||
if (attachment.type === 'audio') return FileAudio;
|
||||
if (attachment.type === 'video') return FileVideo;
|
||||
return FileText;
|
||||
}
|
||||
|
||||
/** 生成附件类型徽标,优先使用快照扩展名。 */
|
||||
function attachmentBadge(attachment: ChatMessageAttachment): string {
|
||||
const extension = String(attachment.extension || '').trim().toUpperCase();
|
||||
if (extension) return extension.slice(0, 5);
|
||||
if (attachment.source === 'remote') return 'URL';
|
||||
return attachment.type.toUpperCase().slice(0, 5);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="attachments.length > 0"
|
||||
data-testid="chat-message-attachment-list"
|
||||
class="mb-2 flex w-full flex-wrap justify-end gap-2"
|
||||
>
|
||||
<article
|
||||
v-for="(attachment, attachmentIndex) in attachments"
|
||||
:key="attachment.id || `${attachment.name}-${attachment.size ?? 'unknown'}-${attachmentIndex}`"
|
||||
class="flex min-w-0 basis-full items-center gap-2.5 rounded-xl border border-default bg-surface px-3 py-2.5 shadow-sm dark:bg-slate-900 sm:basis-[calc(50%-0.25rem)] sm:min-w-[220px] sm:max-w-[290px]"
|
||||
:title="attachment.name"
|
||||
>
|
||||
<div
|
||||
class="flex h-10 w-9 shrink-0 flex-col items-center justify-center rounded-lg bg-brand-50 text-brand-700 dark:bg-brand-900/30 dark:text-brand-300"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<component :is="attachmentIcon(attachment)" class="h-4 w-4" />
|
||||
<span class="mt-0.5 max-w-8 truncate text-[8px] font-bold leading-none">
|
||||
{{ attachmentBadge(attachment) }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="truncate text-sm font-semibold text-primary">{{ attachment.name }}</div>
|
||||
<div v-if="attachment.size !== undefined" class="mt-1 text-[11px] leading-none text-muted">
|
||||
{{ formatAttachmentSize(attachment.size) }}
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,14 +1,29 @@
|
||||
/**
|
||||
* features/chat/components/messages/ChatMessageBubble.vue
|
||||
* 用途:渲染单条聊天消息,统一承接用户气泡、助手 Markdown、内嵌文件下载、请假/出货子组件与操作栏。
|
||||
* 依赖:Vue computed、lucide 图标、Leave/Shipping 子消息组件、chat.types 与页面级 handlers。
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;正文渲染与特殊交互委托 useChatPageMarkdown 等页面编排层提供的 handlers。
|
||||
* 依赖:Vue computed、lucide 图标、消息附件/Leave/Shipping 子组件、chat.types 与页面级 handlers。
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;用户附件显示在文字气泡上方,助手正文与特殊交互委托页面 handlers。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
import { Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next';
|
||||
import {
|
||||
Check,
|
||||
CircleCheck,
|
||||
CircleX,
|
||||
Copy,
|
||||
Download,
|
||||
Edit2,
|
||||
Eye,
|
||||
LayoutGrid,
|
||||
LoaderCircle,
|
||||
MessageSquareText,
|
||||
RotateCw,
|
||||
TriangleAlert,
|
||||
X,
|
||||
} from 'lucide-vue-next';
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
|
||||
import ChatMessageAttachmentList from './ChatMessageAttachmentList.vue';
|
||||
import MaintenanceDeviceResultCard from './MaintenanceDeviceResultCard.vue';
|
||||
import ShippingInventoryMappingMessage, { type ShippingMappingHandlers } from './ShippingInventoryMappingMessage.vue';
|
||||
import ShippingMatchResultCard from './ShippingMatchResultCard.vue';
|
||||
@@ -109,12 +124,30 @@ const showSourceSection = computed(() => {
|
||||
|| sourceLinks.value.length > 0;
|
||||
});
|
||||
|
||||
const showActions = computed(() => message.type !== 'leave-form');
|
||||
const hasUserContent = computed(() => message.role === 'user' && String(message.content || '').trim().length > 0);
|
||||
const showActions = computed(() => (
|
||||
message.type !== 'leave-form'
|
||||
&& (message.role !== 'user' || hasUserContent.value)
|
||||
));
|
||||
const showShippingActionsPanel = computed(() =>
|
||||
isShippingNoticeAgent
|
||||
&& !!message.shipping_actions?.length
|
||||
&& message.type !== 'shipping-match-result',
|
||||
);
|
||||
const shippingOrderExtractionState = computed(() => message.shipping_order_extraction_state);
|
||||
const shippingOrderExtractionTitleKey = computed(() => {
|
||||
switch (shippingOrderExtractionState.value?.status) {
|
||||
case 'completed': return 'chat.shippingOrderExtractionCompleted';
|
||||
case 'partially_completed': return 'chat.shippingOrderExtractionPartiallyCompleted';
|
||||
case 'failed': return 'chat.shippingOrderExtractionFailed';
|
||||
default: return 'chat.shippingOrderExtractionProcessing';
|
||||
}
|
||||
});
|
||||
const showShippingOrderExtractionMessage = computed(() => {
|
||||
const stateMessage = String(shippingOrderExtractionState.value?.message || '').trim();
|
||||
const assistantContent = String(message.content || '').trim();
|
||||
return !!stateMessage && stateMessage !== assistantContent && !assistantContent.includes(stateMessage);
|
||||
});
|
||||
const isLastMessage = computed(() => index === messageCount - 1 || (message.role === 'assistant' && isLatestAssistantMessage));
|
||||
const isCopied = computed(() => copiedIndex === index);
|
||||
const renderedMarkdown = computed(() => (
|
||||
@@ -622,7 +655,12 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
class="flex flex-col"
|
||||
:class="message.role === 'user' ? 'max-w-[88%] md:max-w-[74%] items-end' : 'w-full'"
|
||||
>
|
||||
<ChatMessageAttachmentList
|
||||
v-if="message.role === 'user' && message.attachments?.length"
|
||||
:attachments="message.attachments"
|
||||
/>
|
||||
<div
|
||||
v-if="message.role === 'assistant' || hasUserContent"
|
||||
class="text-[15px] leading-relaxed"
|
||||
:class="message.role === 'user'
|
||||
? 'rounded-2xl rounded-tr-sm bg-brand-600 px-5 py-2.5 text-white shadow-sm shadow-brand-500/15'
|
||||
@@ -630,6 +668,80 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
>
|
||||
<div v-if="message.role === 'user'" class="whitespace-pre-wrap">{{ message.content }}</div>
|
||||
<div v-else>
|
||||
<div
|
||||
v-if="shippingOrderExtractionState"
|
||||
class="mb-3 flex min-h-[60px] items-start gap-3 rounded-lg border px-3.5 py-3"
|
||||
:class="{
|
||||
'border-sky-200 bg-sky-50/80 text-sky-900 dark:border-sky-800 dark:bg-sky-950/35 dark:text-sky-100': shippingOrderExtractionState.status === 'extracting',
|
||||
'border-emerald-200 bg-emerald-50/80 text-emerald-900 dark:border-emerald-800 dark:bg-emerald-950/35 dark:text-emerald-100': shippingOrderExtractionState.status === 'completed',
|
||||
'border-amber-200 bg-amber-50/80 text-amber-950 dark:border-amber-800 dark:bg-amber-950/35 dark:text-amber-100': shippingOrderExtractionState.status === 'partially_completed',
|
||||
'border-rose-200 bg-rose-50/80 text-rose-900 dark:border-rose-800 dark:bg-rose-950/35 dark:text-rose-100': shippingOrderExtractionState.status === 'failed',
|
||||
}"
|
||||
>
|
||||
<LoaderCircle
|
||||
v-if="shippingOrderExtractionState.status === 'extracting'"
|
||||
class="mt-0.5 h-5 w-5 shrink-0 animate-spin"
|
||||
/>
|
||||
<CircleCheck
|
||||
v-else-if="shippingOrderExtractionState.status === 'completed'"
|
||||
class="mt-0.5 h-5 w-5 shrink-0"
|
||||
/>
|
||||
<TriangleAlert
|
||||
v-else-if="shippingOrderExtractionState.status === 'partially_completed'"
|
||||
class="mt-0.5 h-5 w-5 shrink-0"
|
||||
/>
|
||||
<CircleX v-else class="mt-0.5 h-5 w-5 shrink-0" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="text-sm font-semibold">{{ $t(shippingOrderExtractionTitleKey) }}</div>
|
||||
<div
|
||||
data-testid="shipping-order-extraction-progress"
|
||||
class="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-black/10 dark:bg-white/15"
|
||||
role="progressbar"
|
||||
:aria-label="$t(shippingOrderExtractionTitleKey)"
|
||||
aria-valuemin="0"
|
||||
aria-valuemax="100"
|
||||
:aria-valuenow="shippingOrderExtractionState.terminal ? 100 : undefined"
|
||||
:aria-busy="shippingOrderExtractionState.status === 'extracting'"
|
||||
>
|
||||
<div
|
||||
v-if="shippingOrderExtractionState.status === 'extracting'"
|
||||
class="shipping-order-extraction-indeterminate h-full w-2/5 rounded-full bg-sky-500"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="h-full w-full rounded-full"
|
||||
:class="{
|
||||
'bg-emerald-500': shippingOrderExtractionState.status === 'completed',
|
||||
'bg-amber-500': shippingOrderExtractionState.status === 'partially_completed',
|
||||
'bg-rose-500': shippingOrderExtractionState.status === 'failed',
|
||||
}"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-if="shippingOrderExtractionState.terminal"
|
||||
class="mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs"
|
||||
>
|
||||
<span v-if="shippingOrderExtractionState.created_count > 0">
|
||||
{{ $t('chat.shippingOrderExtractionCreatedCount', { count: shippingOrderExtractionState.created_count }) }}
|
||||
</span>
|
||||
<span v-if="shippingOrderExtractionState.opened_existing_count > 0">
|
||||
{{ $t('chat.shippingOrderExtractionOpenedExistingCount', { count: shippingOrderExtractionState.opened_existing_count }) }}
|
||||
</span>
|
||||
<span v-if="shippingOrderExtractionState.pending_count > 0">
|
||||
{{ $t('chat.shippingOrderExtractionPendingCount', { count: shippingOrderExtractionState.pending_count }) }}
|
||||
</span>
|
||||
<span v-if="shippingOrderExtractionState.non_shipping_count > 0">
|
||||
{{ $t('chat.shippingOrderExtractionIgnoredCount', { count: shippingOrderExtractionState.non_shipping_count }) }}
|
||||
</span>
|
||||
<span v-if="shippingOrderExtractionState.created_with_missing_fields_count > 0">
|
||||
{{ $t('chat.shippingOrderExtractionMissingFieldsCount', { count: shippingOrderExtractionState.created_with_missing_fields_count }) }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="showShippingOrderExtractionMessage" class="mt-1 break-words text-xs opacity-80">
|
||||
{{ shippingOrderExtractionState.message }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<LeaveMessageBlock
|
||||
v-if="isLeaveMessage"
|
||||
:message="message"
|
||||
@@ -1034,6 +1146,28 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.shipping-order-extraction-indeterminate {
|
||||
animation: shipping-order-extraction-progress 1.25s ease-in-out infinite;
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
@keyframes shipping-order-extraction-progress {
|
||||
from {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
|
||||
to {
|
||||
transform: translateX(250%);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.shipping-order-extraction-indeterminate {
|
||||
animation: none;
|
||||
transform: translateX(75%);
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.chat-markdown) {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
@@ -1,13 +1,43 @@
|
||||
/**
|
||||
* features/chat/composables/useChat.spec.ts
|
||||
* 用途:验证聊天流对发货通知 UI State SSE 事件的消息级回写行为。
|
||||
* 依赖:vitest、useChat 导出的纯函数、chat.types。
|
||||
* 逻辑:覆盖 batch_ui_state 到 focus_task_ui_state 的投影、focus 切换时按钮跟随更新,以及已消费按钮消息的防回挂保护。
|
||||
* 用途:验证聊天流对发货通知 UI State 与订单识别生命周期 SSE 的消息级回写行为。
|
||||
* 依赖:vitest、useChat/chat.api 导出的纯函数、chat.types。
|
||||
* 逻辑:覆盖任务状态投影、订单识别终态保护、terminal 后事件放行及历史 payload 恢复。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { applyShippingUiStateToMessage } from './useChat';
|
||||
import {
|
||||
applyShippingOrderExtractionStateToMessage,
|
||||
applyShippingUiStateToMessage,
|
||||
createUserChatMessage,
|
||||
isAllowedAfterStreamTerminal,
|
||||
} from './useChat';
|
||||
import { hydrateShippingOrderExtractionState } from '../api/chat.api';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
|
||||
describe('useChat user attachment snapshots', () => {
|
||||
it('copies sent attachments onto the user message without inheriting them for text-only messages', () => {
|
||||
const attachments = [{
|
||||
id: 'attachment-1',
|
||||
name: 'purchase-order.pdf',
|
||||
size: 144_456,
|
||||
extension: 'pdf',
|
||||
type: 'document' as const,
|
||||
source: 'local' as const,
|
||||
}];
|
||||
|
||||
const message = createUserChatMessage('总结附件', attachments);
|
||||
attachments[0]!.name = 'changed.pdf';
|
||||
|
||||
expect(message).toMatchObject({
|
||||
role: 'user',
|
||||
content: '总结附件',
|
||||
attachments: [{ name: 'purchase-order.pdf', size: 144_456 }],
|
||||
});
|
||||
expect(message.attachments).not.toBe(attachments);
|
||||
expect(createUserChatMessage('仅重发文字')).toEqual({ role: 'user', content: '仅重发文字' });
|
||||
});
|
||||
});
|
||||
|
||||
const buildBatchUiStateEvent = (
|
||||
taskNo: string,
|
||||
batchNo: string,
|
||||
@@ -97,3 +127,93 @@ describe('useChat shipping_ui_state SSE', () => {
|
||||
.toBe('SN-FOCUS-B');
|
||||
});
|
||||
});
|
||||
|
||||
describe('useChat shipping_order_extraction_state SSE', () => {
|
||||
it('replaces extracting with persisted facts without overwriting Dify content', () => {
|
||||
const message: ChatMessage = {
|
||||
role: 'assistant',
|
||||
content: 'Dify 最终正文保持不变',
|
||||
payload: { existing_key: 'kept' },
|
||||
};
|
||||
|
||||
applyShippingOrderExtractionStateToMessage(message, {
|
||||
event: 'shipping_order_extraction_state',
|
||||
status: 'extracting',
|
||||
phase: 'llm_extraction',
|
||||
message: '正在识别邮件及附件中的订单',
|
||||
created_count: -1,
|
||||
terminal: false,
|
||||
});
|
||||
expect(message.shipping_order_extraction_state?.status).toBe('extracting');
|
||||
expect(message.shipping_order_extraction_state?.created_count).toBe(0);
|
||||
|
||||
applyShippingOrderExtractionStateToMessage(message, {
|
||||
event: 'shipping_order_extraction_state',
|
||||
status: 'completed',
|
||||
phase: 'result_persisted',
|
||||
message: '已创建 1 个发货任务',
|
||||
created_count: 1,
|
||||
opened_existing_count: 2,
|
||||
pending_count: 0,
|
||||
non_shipping_count: 3,
|
||||
created_with_missing_fields_count: 1,
|
||||
batch_no: 'SB-STATE-001',
|
||||
terminal: true,
|
||||
});
|
||||
|
||||
expect(message.content).toBe('Dify 最终正文保持不变');
|
||||
expect(message.shipping_order_extraction_state).toMatchObject({
|
||||
status: 'completed',
|
||||
created_count: 1,
|
||||
opened_existing_count: 2,
|
||||
non_shipping_count: 3,
|
||||
batch_no: 'SB-STATE-001',
|
||||
terminal: true,
|
||||
});
|
||||
expect((message.payload as Record<string, unknown>).existing_key).toBe('kept');
|
||||
expect((message.payload as { shipping_order_extraction_state?: { created_count?: number } })
|
||||
.shipping_order_extraction_state?.created_count).toBe(1);
|
||||
|
||||
// 关键断言:网络重排导致的迟到进行态不能覆盖已经展示的终态。
|
||||
applyShippingOrderExtractionStateToMessage(message, {
|
||||
status: 'extracting',
|
||||
phase: 'llm_extraction',
|
||||
message: '迟到事件',
|
||||
terminal: false,
|
||||
});
|
||||
expect(message.shipping_order_extraction_state?.status).toBe('completed');
|
||||
});
|
||||
|
||||
it('allows HXOPS domain states after the upstream terminal event', () => {
|
||||
expect(isAllowedAfterStreamTerminal('shipping_order_extraction_state')).toBe(true);
|
||||
expect(isAllowedAfterStreamTerminal('shipping_ui_state')).toBe(true);
|
||||
expect(isAllowedAfterStreamTerminal('agent_message')).toBe(false);
|
||||
});
|
||||
|
||||
it('hydrates persisted terminal state from ChatLog payload', () => {
|
||||
const message: ChatMessage = {
|
||||
role: 'assistant',
|
||||
content: '订单识别完成',
|
||||
payload: {
|
||||
shipping_order_extraction_state: {
|
||||
status: 'partially_completed',
|
||||
phase: 'result_persisted',
|
||||
message: '仍有 1 个订单需要补充信息',
|
||||
created_count: 1,
|
||||
opened_existing_count: 0,
|
||||
pending_count: 1,
|
||||
non_shipping_count: 0,
|
||||
created_with_missing_fields_count: 0,
|
||||
batch_no: 'SB-HISTORY-001',
|
||||
terminal: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
hydrateShippingOrderExtractionState(message);
|
||||
|
||||
expect(message.shipping_order_extraction_state?.status).toBe('partially_completed');
|
||||
expect(message.shipping_order_extraction_state?.pending_count).toBe(1);
|
||||
expect(message.shipping_order_extraction_state?.batch_no).toBe('SB-HISTORY-001');
|
||||
});
|
||||
});
|
||||
@@ -1,19 +1,49 @@
|
||||
/**
|
||||
* features/chat/composables/useChat.ts
|
||||
* SSE 流式对话核心:消息列表、runs、发送与接收。
|
||||
* 用途:维护聊天消息、并行 run 与 legacy SSE 流式收发,并投影货代领域状态。
|
||||
* 依赖:Vue、vue-i18n、useChatTurn、streamErrorMessage、chat/shipping 类型。
|
||||
* 逻辑:页面调用 useChat 发起消息;Dify/HXOPS SSE 被归并到当前助手消息,领域终态可继续在上游终止事件后写入。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
|
||||
import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types';
|
||||
import type {
|
||||
ChatMessage,
|
||||
ChatMessageAttachment,
|
||||
ChatRun,
|
||||
RetrieverResource,
|
||||
ShippingOrderExtractionState,
|
||||
ShippingOrderExtractionStatus,
|
||||
} from '../types/chat.types';
|
||||
import type { ShippingBatchUiState, ShippingTaskUiState } from '../types/shipping.api.types';
|
||||
import { createStartChatTurn } from './useChatTurn';
|
||||
|
||||
export interface SendMessageLifecycleHooks {
|
||||
/** 当前轮用户消息的已发送附件快照;仅用于界面展示与后续持久化。 */
|
||||
userAttachments?: ChatMessageAttachment[];
|
||||
onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建当前轮乐观用户消息,并复制附件快照避免调用方后续修改污染消息历史。
|
||||
* @param content - 用户可见问题文本
|
||||
* @param attachments - 已上传并固化的附件快照
|
||||
* @returns 可直接推入消息列表的用户消息
|
||||
*/
|
||||
export function createUserChatMessage(
|
||||
content: string,
|
||||
attachments?: ChatMessageAttachment[],
|
||||
): ChatMessage {
|
||||
return {
|
||||
role: 'user',
|
||||
content,
|
||||
...(attachments?.length
|
||||
? { attachments: attachments.map((attachment) => ({ ...attachment })) }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
const normalizeResources = (resources: unknown) => {
|
||||
if (!resources) return [];
|
||||
if (Array.isArray(resources)) return resources;
|
||||
@@ -136,6 +166,74 @@ export const applyShippingUiStateToMessage = (msg: ChatMessage, data: Record<str
|
||||
};
|
||||
};
|
||||
|
||||
const SHIPPING_ORDER_EXTRACTION_STATUSES = new Set<ShippingOrderExtractionStatus>([
|
||||
'extracting',
|
||||
'completed',
|
||||
'partially_completed',
|
||||
'failed',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 将未知 SSE payload 规范为订单识别状态。
|
||||
* 核心逻辑:只接受固定状态枚举;计数字段统一约束为非负整数,避免异常上游值破坏卡片布局。
|
||||
* @param data - shipping_order_extraction_state 事件对象。
|
||||
* @returns 合法状态;协议不匹配时返回 undefined。
|
||||
*/
|
||||
const resolveShippingOrderExtractionState = (
|
||||
data: Record<string, unknown>,
|
||||
): ShippingOrderExtractionState | undefined => {
|
||||
const status = String(data.status || '') as ShippingOrderExtractionStatus;
|
||||
if (!SHIPPING_ORDER_EXTRACTION_STATUSES.has(status)) return undefined;
|
||||
const phase = String(data.phase || '');
|
||||
if (!['llm_extraction', 'result_persisted', 'failed'].includes(phase)) return undefined;
|
||||
const count = (value: unknown) => {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? Math.max(Math.trunc(parsed), 0) : 0;
|
||||
};
|
||||
return {
|
||||
status,
|
||||
phase: phase as ShippingOrderExtractionState['phase'],
|
||||
message: String(data.message || '').trim(),
|
||||
created_count: count(data.created_count),
|
||||
opened_existing_count: count(data.opened_existing_count),
|
||||
pending_count: count(data.pending_count),
|
||||
non_shipping_count: count(data.non_shipping_count),
|
||||
created_with_missing_fields_count: count(data.created_with_missing_fields_count),
|
||||
batch_no: typeof data.batch_no === 'string' && data.batch_no.trim() ? data.batch_no.trim() : null,
|
||||
terminal: data.terminal === true || status !== 'extracting',
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 将订单识别领域事件同步到当前助手消息及可持久化 payload。
|
||||
* 核心逻辑:终态不得被迟到的 extracting 覆盖;正文由 Dify 独立维护,本函数只更新结构化状态。
|
||||
* @param msg - 当前助手消息。
|
||||
* @param data - shipping_order_extraction_state SSE 事件。
|
||||
*/
|
||||
export const applyShippingOrderExtractionStateToMessage = (
|
||||
msg: ChatMessage,
|
||||
data: Record<string, unknown>,
|
||||
): void => {
|
||||
const state = resolveShippingOrderExtractionState(data);
|
||||
if (!state) return;
|
||||
if (msg.shipping_order_extraction_state?.terminal && !state.terminal) return;
|
||||
msg.shipping_order_extraction_state = state;
|
||||
msg.payload = {
|
||||
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
|
||||
shipping_order_extraction_state: state,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断上游终态之后仍允许写入当前消息的领域事件。
|
||||
* 核心逻辑:普通 Dify 文本在 terminal 后丢弃,但 HXOPS 的抽取终态和任务 UI State 由 Handler 在 terminal 后生成。
|
||||
* @param eventName - SSE event 字段。
|
||||
* @returns 是否允许继续消费。
|
||||
*/
|
||||
export const isAllowedAfterStreamTerminal = (eventName: string): boolean => (
|
||||
eventName === 'shipping_ui_state' || eventName === 'shipping_order_extraction_state'
|
||||
);
|
||||
|
||||
/**
|
||||
* 把 SSE 事件附带的元数据同步到当前消息对象。
|
||||
*
|
||||
@@ -436,7 +534,11 @@ export function useChat() {
|
||||
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => {
|
||||
const displayQuery = String(context?.display_query || query || '').trim();
|
||||
const displayQuery = String(
|
||||
context && Object.prototype.hasOwnProperty.call(context, 'display_query')
|
||||
? context.display_query ?? ''
|
||||
: query || '',
|
||||
).trim();
|
||||
clearLikelyCompletedStreamTimer();
|
||||
const shouldDetachPreviousStream = Boolean(activeStreamController.value) && hasVisibleCompletedAssistantReply(messages.value);
|
||||
if (shouldDetachPreviousStream) {
|
||||
@@ -463,7 +565,7 @@ export function useChat() {
|
||||
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
|
||||
activeRunId.value = run.runId;
|
||||
|
||||
runMessages.push({ role: 'user', content: displayQuery });
|
||||
runMessages.push(createUserChatMessage(displayQuery, hooks?.userAttachments));
|
||||
let botMsgIndex: number | null = null;
|
||||
let hasAssistantContent = false;
|
||||
let hasTerminalEvent = false;
|
||||
@@ -496,7 +598,10 @@ export function useChat() {
|
||||
task_id: context?.task_id || undefined,
|
||||
batch_no: context?.batch_no || undefined,
|
||||
shipping_intake_nos: context?.shipping_intake_nos?.length ? context.shipping_intake_nos : undefined,
|
||||
display_query: context?.display_query || undefined,
|
||||
display_query: context && Object.prototype.hasOwnProperty.call(context, 'display_query')
|
||||
? context.display_query
|
||||
: undefined,
|
||||
user_attachments: hooks?.userAttachments?.length ? hooks.userAttachments : undefined,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -550,13 +655,17 @@ export function useChat() {
|
||||
}
|
||||
|
||||
const eventName = String(data.event || '');
|
||||
if (ignoreFurtherStreamEvents && eventName !== 'shipping_ui_state') {
|
||||
if (ignoreFurtherStreamEvents && !isAllowedAfterStreamTerminal(eventName)) {
|
||||
continue;
|
||||
}
|
||||
if (eventName === 'shipping_ui_state') {
|
||||
const botMsg = ensureBotMessage();
|
||||
if (!botMsg) continue;
|
||||
applyShippingUiStateToMessage(botMsg, data);
|
||||
} else if (eventName === 'shipping_order_extraction_state') {
|
||||
const botMsg = ensureBotMessage();
|
||||
if (!botMsg) continue;
|
||||
applyShippingOrderExtractionStateToMessage(botMsg, data);
|
||||
} else if (eventName === 'message' || eventName === 'agent_message') {
|
||||
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||||
const botMsg = ensureBotMessage();
|
||||
@@ -686,6 +795,7 @@ export function useChat() {
|
||||
}
|
||||
}
|
||||
}
|
||||
return run.status === 'done';
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* features/chat/composables/useChatAttachments.spec.ts
|
||||
* 用途:验证普通聊天附件的逐文件上传状态、成功缓存、失败重试与删除保护。
|
||||
* 依赖:Vitest、Vue 响应式 API、mock 后的 chat.api。
|
||||
* 逻辑:直接调用 useChatAttachments,断言附件状态与生成的 Dify 文件参数保持一致。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { uploadChatFile } from '../api/chat.api';
|
||||
import { useChatAttachments } from './useChatAttachments';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
|
||||
vi.mock('../api/chat.api', () => ({
|
||||
uploadChatFile: vi.fn(),
|
||||
}));
|
||||
|
||||
const uploadChatFileMock = vi.mocked(uploadChatFile);
|
||||
|
||||
/** 创建满足 composable 依赖的最小测试上下文。 */
|
||||
function createAttachments() {
|
||||
return useChatAttachments({
|
||||
deps: {
|
||||
msg: { warning: vi.fn() },
|
||||
} as unknown as ChatDeps,
|
||||
currentAgentId: computed(() => 7),
|
||||
currentAgent: ref({
|
||||
capabilities: { file_upload: true },
|
||||
dify_parameters: {
|
||||
file_upload: {
|
||||
document: { enabled: true, transfer_methods: ['local_file'] },
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
/** 向附件状态中加入一个普通本地文件。 */
|
||||
function selectLocalFile(api: ReturnType<typeof createAttachments>, name = 'order.pdf') {
|
||||
const file = new File(['content'], name, { type: 'application/pdf' });
|
||||
api.handleLocalFilesSelected({ target: { files: [file], value: 'selected' } } as unknown as Event);
|
||||
return api.attachments.value[0];
|
||||
}
|
||||
|
||||
describe('useChatAttachments upload states', () => {
|
||||
beforeEach(() => {
|
||||
uploadChatFileMock.mockReset();
|
||||
});
|
||||
|
||||
it('marks a successful local upload ready and reuses its upload id', async () => {
|
||||
const api = createAttachments();
|
||||
const attachment = selectLocalFile(api);
|
||||
uploadChatFileMock.mockResolvedValue({ id: 'upload-1' });
|
||||
|
||||
const firstSpecs = await api.buildFileSpecsForSend();
|
||||
const secondSpecs = await api.buildFileSpecsForSend();
|
||||
|
||||
expect(attachment).toMatchObject({
|
||||
kind: 'local',
|
||||
uploadStatus: 'uploaded',
|
||||
uploadProgress: 100,
|
||||
uploadFileId: 'upload-1',
|
||||
});
|
||||
expect(firstSpecs).toEqual([{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-1' }]);
|
||||
expect(secondSpecs).toEqual(firstSpecs);
|
||||
expect(uploadChatFileMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keeps a failed attachment and retries it on the next send', async () => {
|
||||
const api = createAttachments();
|
||||
const attachment = selectLocalFile(api);
|
||||
uploadChatFileMock
|
||||
.mockRejectedValueOnce(new Error('network unavailable'))
|
||||
.mockResolvedValueOnce({ id: 'upload-retry' });
|
||||
|
||||
await expect(api.buildFileSpecsForSend()).rejects.toThrow('network unavailable');
|
||||
expect(attachment).toMatchObject({
|
||||
uploadStatus: 'failed',
|
||||
uploadProgress: 0,
|
||||
errorMessage: 'network unavailable',
|
||||
});
|
||||
|
||||
await expect(api.buildFileSpecsForSend()).resolves.toEqual([
|
||||
{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-retry' },
|
||||
]);
|
||||
expect(attachment).toMatchObject({ uploadStatus: 'uploaded', uploadFileId: 'upload-retry' });
|
||||
expect(attachment && 'errorMessage' in attachment ? attachment.errorMessage : undefined).toBeUndefined();
|
||||
});
|
||||
|
||||
it('reuses earlier successful files when a later file failed', async () => {
|
||||
const api = createAttachments();
|
||||
selectLocalFile(api, 'first.pdf');
|
||||
selectLocalFile(api, 'second.pdf');
|
||||
uploadChatFileMock
|
||||
.mockResolvedValueOnce({ id: 'upload-first' })
|
||||
.mockRejectedValueOnce(new Error('second failed'))
|
||||
.mockResolvedValueOnce({ id: 'upload-second' });
|
||||
|
||||
await expect(api.buildFileSpecsForSend()).rejects.toThrow('second failed');
|
||||
expect(api.attachments.value[0]).toMatchObject({
|
||||
uploadStatus: 'uploaded',
|
||||
uploadFileId: 'upload-first',
|
||||
});
|
||||
expect(api.attachments.value[1]).toMatchObject({ uploadStatus: 'failed' });
|
||||
|
||||
await expect(api.buildFileSpecsForSend()).resolves.toEqual([
|
||||
{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-first' },
|
||||
{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-second' },
|
||||
]);
|
||||
expect(uploadChatFileMock).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('does not remove a local attachment while its request is uploading', async () => {
|
||||
const api = createAttachments();
|
||||
const attachment = selectLocalFile(api);
|
||||
let resolveUpload: ((value: { id: string }) => void) | undefined;
|
||||
uploadChatFileMock.mockImplementation(() => new Promise((resolve) => {
|
||||
resolveUpload = resolve;
|
||||
}));
|
||||
|
||||
const buildPromise = api.buildFileSpecsForSend();
|
||||
await Promise.resolve();
|
||||
expect(attachment && 'uploadStatus' in attachment ? attachment.uploadStatus : undefined).toBe('uploading');
|
||||
|
||||
api.removeAttachment(attachment?.id || '');
|
||||
expect(api.attachments.value).toHaveLength(1);
|
||||
|
||||
resolveUpload?.({ id: 'upload-finished' });
|
||||
await buildPromise;
|
||||
api.removeAttachment(attachment?.id || '');
|
||||
expect(api.attachments.value).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,12 @@
|
||||
/**
|
||||
* features/chat/composables/useChatAttachments.ts
|
||||
* Dify 附件策略解析、本地/URL 附件管理与发送前上传。
|
||||
* 用途:解析 Dify 附件策略,管理本地/URL 附件,并在发送前逐文件上传。
|
||||
* 依赖:chat.api 的附件上传接口、chat.deps 的消息提示能力。
|
||||
* 逻辑:Chat 页面通过本 composable 维护附件状态;发送流程调用 buildFileSpecsForSend 生成 Dify 文件参数。
|
||||
*/
|
||||
import { computed, ref, type ComputedRef, type Ref } from 'vue';
|
||||
import { uploadChatFile } from '../api/chat.api';
|
||||
import { createChatMessageAttachmentSnapshots } from '../utils/attachmentCard.utils';
|
||||
import type { PendingAttachment } from '../types/shipping.types';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
|
||||
@@ -245,7 +248,13 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
return resolveDifyType(ext, file.type || '');
|
||||
};
|
||||
|
||||
/**
|
||||
* 删除未在上传中的附件,避免界面移除后网络请求仍继续造成状态失配。
|
||||
* @param id - 待删除附件的本地唯一标识
|
||||
*/
|
||||
const removeAttachment = (id: string) => {
|
||||
const target = attachments.value.find((attachment) => attachment.id === id);
|
||||
if (target?.kind === 'local' && target.uploadStatus === 'uploading') return;
|
||||
attachments.value = attachments.value.filter((a) => a.id !== id);
|
||||
};
|
||||
|
||||
@@ -288,7 +297,14 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
msg.warning(`该类型附件数量已达上限(${caps.limit})`);
|
||||
continue;
|
||||
}
|
||||
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'local', file: f, type });
|
||||
attachments.value.push({
|
||||
id: `${Date.now()}_${Math.random()}`,
|
||||
kind: 'local',
|
||||
file: f,
|
||||
type,
|
||||
uploadStatus: 'waiting',
|
||||
uploadProgress: 0,
|
||||
});
|
||||
}
|
||||
if (inputEl) inputEl.value = '';
|
||||
};
|
||||
@@ -336,6 +352,12 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'remote', url, type });
|
||||
};
|
||||
|
||||
/**
|
||||
* 将待发送附件转换为 Dify 文件参数,并逐个更新本地文件的真实上传状态。
|
||||
* 核心逻辑:复用已成功上传的 uploadFileId;失败附件保留并在下次发送时重试。
|
||||
* @returns 可直接传给聊天接口的文件参数列表
|
||||
* @throws 任一本地附件上传失败时抛出原始错误,中止本次消息发送
|
||||
*/
|
||||
const buildFileSpecsForSend = async (): Promise<ChatUploadFileSpec[]> => {
|
||||
if (!attachmentPolicy.value.anyEnabled) return [];
|
||||
if (attachments.value.length === 0) return [];
|
||||
@@ -348,11 +370,30 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
isUploadingAttachments.value = true;
|
||||
try {
|
||||
for (const item of locals) {
|
||||
const uploaded = await uploadChatFile(currentAgentId.value, item.file);
|
||||
if (!uploaded?.id) {
|
||||
throw new Error('Missing upload id');
|
||||
if (item.uploadStatus === 'uploaded' && item.uploadFileId) {
|
||||
specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: item.uploadFileId });
|
||||
continue;
|
||||
}
|
||||
|
||||
item.uploadStatus = 'uploading';
|
||||
item.uploadProgress = 0;
|
||||
item.errorMessage = undefined;
|
||||
try {
|
||||
const uploaded = await uploadChatFile(currentAgentId.value, item.file);
|
||||
if (!uploaded?.id) {
|
||||
throw new Error('Missing upload id');
|
||||
}
|
||||
item.uploadStatus = 'uploaded';
|
||||
item.uploadProgress = 100;
|
||||
item.uploadFileId = uploaded.id;
|
||||
specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: uploaded.id });
|
||||
} catch (error: unknown) {
|
||||
item.uploadStatus = 'failed';
|
||||
item.uploadProgress = 0;
|
||||
item.uploadFileId = undefined;
|
||||
item.errorMessage = error instanceof Error ? error.message : 'File upload failed';
|
||||
throw error;
|
||||
}
|
||||
specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: uploaded.id });
|
||||
}
|
||||
} finally {
|
||||
isUploadingAttachments.value = false;
|
||||
@@ -370,6 +411,14 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
attachments.value = [];
|
||||
};
|
||||
|
||||
/**
|
||||
* 固化当前待发送附件,供发送成功后的用户消息展示。
|
||||
* @returns 与当前附件顺序一致、可 JSON 序列化的安全快照
|
||||
*/
|
||||
const createMessageAttachmentSnapshots = () => (
|
||||
createChatMessageAttachmentSnapshots(attachments.value)
|
||||
);
|
||||
|
||||
return {
|
||||
attachments,
|
||||
isUploadingAttachments,
|
||||
@@ -378,6 +427,7 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
handleLocalFilesSelected,
|
||||
addRemoteUrlAttachment,
|
||||
buildFileSpecsForSend,
|
||||
createMessageAttachmentSnapshots,
|
||||
clearAttachments,
|
||||
};
|
||||
}
|
||||
@@ -415,6 +415,7 @@ export function useChatPage() {
|
||||
attachments: attachmentApi.attachments,
|
||||
allowsSendWithAttachmentsOnly: shipping.allowsSendWithAttachmentsOnly,
|
||||
buildFileSpecsForSend: attachmentApi.buildFileSpecsForSend,
|
||||
createMessageAttachmentSnapshots: attachmentApi.createMessageAttachmentSnapshots,
|
||||
clearAttachments: attachmentApi.clearAttachments,
|
||||
sendMessage,
|
||||
getChatContext: shipping.isShippingNoticeAgent ? shipping.getCurrentShippingChatContext : undefined,
|
||||
@@ -561,6 +562,12 @@ export function useChatPage() {
|
||||
resolveShippingDuplicateDialog: shipping.resolveShippingDuplicateDialog,
|
||||
removeShippingDuplicateDialogAttachment: shipping.removeShippingDuplicateDialogAttachment,
|
||||
closeShippingDuplicateDialog: shipping.closeShippingDuplicateDialog,
|
||||
showShippingCustomerDialog: shipping.showShippingCustomerDialog,
|
||||
shippingCustomerOptions: shipping.shippingCustomerOptions,
|
||||
shippingCustomerLoading: shipping.shippingCustomerLoading,
|
||||
searchShippingCustomers: shipping.searchShippingCustomers,
|
||||
confirmShippingCustomer: shipping.confirmShippingCustomer,
|
||||
closeShippingCustomerDialog: shipping.closeShippingCustomerDialog,
|
||||
filePreviewVisible,
|
||||
previewFile,
|
||||
previewFiles,
|
||||
|
||||
@@ -5,7 +5,12 @@
|
||||
* 逻辑:覆盖 current focus、process summary 回退、首票回退与无任务时清空焦点原因四种路径。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { resolveShippingBatchFocusState } from './useChatShipping';
|
||||
import {
|
||||
resolveLatestShippingMessageRecoveryPayload,
|
||||
resolveLatestShippingBatchSnapshot,
|
||||
resolveShippingBatchFocusState,
|
||||
selectShippingConversationBatch,
|
||||
} from './useChatShipping';
|
||||
|
||||
describe('useChatShipping batch focus sync', () => {
|
||||
it('prefers batch current focus task and keeps default reason', () => {
|
||||
@@ -62,3 +67,84 @@ describe('useChatShipping batch focus sync', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('useChatShipping conversation workspace selection', () => {
|
||||
const batches = [
|
||||
{ batch_no: 'SB-OLD', focus_task: { task_no: 'SN-OLD' } },
|
||||
{ batch_no: 'SB-NEW', focus_task: { task_no: 'SN-NEW' } },
|
||||
];
|
||||
|
||||
it('keeps the active batch during a normal refresh', () => {
|
||||
expect(selectShippingConversationBatch(batches, 'SB-OLD', '', false)?.batch_no).toBe('SB-OLD');
|
||||
});
|
||||
|
||||
it('selects the latest batch after an order extraction turn', () => {
|
||||
expect(selectShippingConversationBatch(batches, 'SB-OLD', '', true)?.batch_no).toBe('SB-NEW');
|
||||
});
|
||||
});
|
||||
|
||||
describe('useChatShipping persisted batch snapshot', () => {
|
||||
it('restores the latest valid batch snapshot from assistant message payloads', () => {
|
||||
const snapshot = resolveLatestShippingBatchSnapshot([
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '旧结果',
|
||||
payload: { shipping_batch_ui_state: { batch_no: 'SB-OLD', tasks: [] } },
|
||||
},
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '无效结果',
|
||||
payload: { shipping_batch_ui_state: { batch_no: 'SB-INVALID' } },
|
||||
},
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '已打开已有任务',
|
||||
payload: {
|
||||
shipping_batch_ui_state: {
|
||||
batch_no: 'SB-EXISTING',
|
||||
current_focus_task_no: 'SN-EXISTING',
|
||||
tasks: [{ task_no: 'SN-EXISTING', source_type: 'email', process_status: 'pending_review' }],
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
expect(snapshot?.batch_no).toBe('SB-EXISTING');
|
||||
expect(snapshot?.current_focus_task_no).toBe('SN-EXISTING');
|
||||
});
|
||||
|
||||
it('ignores malformed snapshots', () => {
|
||||
expect(resolveLatestShippingBatchSnapshot([
|
||||
{ role: 'assistant', content: '', payload: { shipping_batch_ui_state: { batch_no: 'SB-NO-TASKS' } } },
|
||||
{ role: 'user', content: '继续' },
|
||||
])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('useChatShipping message recovery payload', () => {
|
||||
it('falls back to task anchor when batch snapshot is absent', () => {
|
||||
const payload = resolveLatestShippingMessageRecoveryPayload([
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '已打开已有任务',
|
||||
payload: {
|
||||
task_no: 'SN-OPEN-EXISTING',
|
||||
batch_no: 'SB-OPEN-EXISTING',
|
||||
shipping_ui_state: {
|
||||
task_no: 'SN-OPEN-EXISTING',
|
||||
batch_no: 'SB-OPEN-EXISTING',
|
||||
process_status: 'waiting_inventory',
|
||||
steps: [],
|
||||
summary: {},
|
||||
action_buttons: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
expect(payload?.task_no).toBe('SN-OPEN-EXISTING');
|
||||
expect(payload?.batch_no).toBe('SB-OPEN-EXISTING');
|
||||
expect(payload?.shipping_ui_state?.task_no).toBe('SN-OPEN-EXISTING');
|
||||
expect(payload?.shipping_batch_ui_state).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -30,7 +30,6 @@ import {
|
||||
createShippingSendHandlers,
|
||||
createShippingUploadHandlers,
|
||||
onNoticeBatchConversationChanging,
|
||||
findHistorySessionForShippingTask,
|
||||
findLatestShippingTaskId,
|
||||
getShippingInventoryMappingPayload,
|
||||
getShippingMatchResultPayload,
|
||||
@@ -48,6 +47,8 @@ import {
|
||||
getWorkspaceShippingConversationBatches,
|
||||
getWorkspaceShippingBatch,
|
||||
getWorkspaceShippingTask,
|
||||
listWorkspaceShippingCustomerOptions,
|
||||
confirmWorkspaceShippingCustomer,
|
||||
switchWorkspaceShippingBatchFocusTask,
|
||||
type ShippingBatchUiState,
|
||||
type ShippingBatchSummary,
|
||||
@@ -55,13 +56,15 @@ import {
|
||||
type ShippingTaskDetail,
|
||||
type ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import type { ShippingCustomerOption } from '../types/shipping.api.types';
|
||||
import { buildShippingQueryShortageTurn } from '../shipping/shippingTurnActions';
|
||||
import {
|
||||
hasShortageLines,
|
||||
isShippingShortageQueryIntent,
|
||||
} from '../shipping/shippingShortageDetails';
|
||||
|
||||
import type { ChatMessage, ChatRun, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ChatMessage, ChatRun, ChatSessionItem, ShippingMessageRecoveryPayload } from '../types/chat.types';
|
||||
import type { SendMessageLifecycleHooks } from './useChat';
|
||||
import type { ChatUploadFileSpec, PendingAttachment, ShippingActionButton } from '../types/shipping.types';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
import { listChatMessages } from '../api/chat.api';
|
||||
@@ -94,8 +97,8 @@ export interface UseChatShippingOptions {
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
|
||||
hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void> },
|
||||
) => Promise<void>;
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => Promise<boolean | void>;
|
||||
startChatTurn: (options: import('../types/chat-turn.types').StartChatTurnOptions) => Promise<boolean>;
|
||||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||||
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
|
||||
@@ -130,6 +133,104 @@ export const resolveShippingBatchFocusState = (
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 从会话工作台选择本轮应展示的批次。
|
||||
* 核心逻辑:订单抽取完成后选服务端按创建时间升序返回的最后一个批次;普通续办优先保留当前批次。
|
||||
*/
|
||||
export const selectShippingConversationBatch = <T extends { batch_no: string; focus_task?: unknown }>(
|
||||
batches: T[],
|
||||
currentBatchNo: string,
|
||||
queryBatchNo: string,
|
||||
preferLatest = false,
|
||||
): T | undefined => (
|
||||
(preferLatest ? batches[batches.length - 1] : undefined)
|
||||
|| batches.find((item) => item.batch_no === currentBatchNo)
|
||||
|| (queryBatchNo ? batches.find((item) => item.batch_no === queryBatchNo) : undefined)
|
||||
|| batches.find((item) => Boolean(item.focus_task))
|
||||
|| batches[0]
|
||||
);
|
||||
|
||||
/**
|
||||
* 从消息列表解析最近一次权威批次快照。
|
||||
* 核心逻辑:只接受包含批次号和任务数组的 `shipping_batch_ui_state`,供实时终态与历史会话共用。
|
||||
* @param sourceMessages - 当前会话消息
|
||||
* @returns 最近的合法批次快照;不存在时返回 null
|
||||
*/
|
||||
export const resolveLatestShippingBatchSnapshot = (
|
||||
sourceMessages: ChatMessage[],
|
||||
): ShippingBatchUiState | null => {
|
||||
for (let index = sourceMessages.length - 1; index >= 0; index -= 1) {
|
||||
const message = sourceMessages[index];
|
||||
const payload = message?.payload && typeof message.payload === 'object'
|
||||
? message.payload as Record<string, unknown>
|
||||
: null;
|
||||
const rawSnapshot = payload?.shipping_batch_ui_state;
|
||||
if (!rawSnapshot || typeof rawSnapshot !== 'object') continue;
|
||||
const snapshot = rawSnapshot as ShippingBatchUiState;
|
||||
if (String(snapshot.batch_no || '').trim() && Array.isArray(snapshot.tasks)) {
|
||||
return snapshot;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 从单条助手消息中提取工作台恢复锚点。
|
||||
* 核心逻辑:优先识别合法 `shipping_batch_ui_state`,其次回退到 `task_no / batch_no / shipping_ui_state`;
|
||||
* 供实时终态、历史回放与刷新恢复共用。
|
||||
*/
|
||||
export const resolveShippingMessageRecoveryPayload = (
|
||||
message: ChatMessage | null | undefined,
|
||||
): ShippingMessageRecoveryPayload | null => {
|
||||
const payload = message?.payload && typeof message.payload === 'object'
|
||||
? message.payload as ShippingMessageRecoveryPayload
|
||||
: null;
|
||||
if (!payload) return null;
|
||||
const batchSnapshot = payload.shipping_batch_ui_state;
|
||||
const hasBatchSnapshot = Boolean(
|
||||
batchSnapshot
|
||||
&& String(batchSnapshot.batch_no || '').trim()
|
||||
&& Array.isArray(batchSnapshot.tasks),
|
||||
);
|
||||
const taskNo = String(
|
||||
payload.task_no
|
||||
|| payload.shipping_ui_state?.task_no
|
||||
|| batchSnapshot?.current_focus_task_no
|
||||
|| batchSnapshot?.focus_task?.task_no
|
||||
|| batchSnapshot?.tasks?.[0]?.task_no
|
||||
|| '',
|
||||
).trim();
|
||||
const batchNo = String(
|
||||
payload.batch_no
|
||||
|| payload.shipping_ui_state?.batch_no
|
||||
|| batchSnapshot?.batch_no
|
||||
|| '',
|
||||
).trim();
|
||||
const hasTaskUiState = Boolean(payload.shipping_ui_state && typeof payload.shipping_ui_state === 'object');
|
||||
if (!hasBatchSnapshot && !taskNo && !batchNo && !hasTaskUiState) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
...payload,
|
||||
...(taskNo ? { task_no: taskNo } : {}),
|
||||
...(batchNo ? { batch_no: batchNo } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 从消息列表中选择最近一条可恢复工作台的消息载荷。
|
||||
* 核心逻辑:从后往前找最近的权威恢复锚点,允许 `open_existing` 只靠 `task_no/ui_state` 恢复。
|
||||
*/
|
||||
export const resolveLatestShippingMessageRecoveryPayload = (
|
||||
sourceMessages: ChatMessage[],
|
||||
): ShippingMessageRecoveryPayload | null => {
|
||||
for (let index = sourceMessages.length - 1; index >= 0; index -= 1) {
|
||||
const payload = resolveShippingMessageRecoveryPayload(sourceMessages[index]);
|
||||
if (payload) return payload;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 组装发货通知聊天所需的状态、动作处理器与发送拦截逻辑。
|
||||
*
|
||||
@@ -163,7 +264,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
sendMessage,
|
||||
startChatTurn,
|
||||
buildFileSpecsForSend,
|
||||
loadConversation,
|
||||
createNewChatView,
|
||||
} = options;
|
||||
|
||||
@@ -280,34 +380,152 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
}
|
||||
};
|
||||
|
||||
const applyConversationWorkspaceFocus = (workspace: ShippingConversationWorkspace) => {
|
||||
const applyConversationWorkspaceFocus = (
|
||||
workspace: ShippingConversationWorkspace,
|
||||
options?: { preferLatest?: boolean },
|
||||
) => {
|
||||
const batches = Array.isArray(workspace.batches) ? workspace.batches : [];
|
||||
if (!batches.length) return;
|
||||
const queryBatchNo = String(shippingBatchNoFromQuery.value || '').trim();
|
||||
const currentBatchNo = String(activeShippingBatchNo.value || resolvedShippingBatchNo.value || queryBatchNo || '').trim();
|
||||
const selectedBatch = batches.find((item) => item.batch_no === currentBatchNo)
|
||||
|| (queryBatchNo ? batches.find((item) => item.batch_no === queryBatchNo) : null)
|
||||
|| batches.find((item) => item.focus_task?.task_no)
|
||||
|| batches[0];
|
||||
const selectedBatch = selectShippingConversationBatch(
|
||||
batches,
|
||||
currentBatchNo,
|
||||
queryBatchNo,
|
||||
Boolean(options?.preferLatest),
|
||||
);
|
||||
if (!selectedBatch) return;
|
||||
if (options?.preferLatest) {
|
||||
activeShippingBatchNo.value = selectedBatch.batch_no;
|
||||
}
|
||||
applyShippingBatchDetail(selectedBatch, selectedBatch.batch_no);
|
||||
};
|
||||
|
||||
const syncShippingConversationWorkspace = async () => {
|
||||
const syncShippingConversationWorkspace = async (
|
||||
options?: { preferLatest?: boolean },
|
||||
): Promise<boolean> => {
|
||||
const localConversationId = String(conversationId.value || '').trim();
|
||||
if (!localConversationId || !isShippingNoticeAgent.value) {
|
||||
shippingConversationWorkspace.value = null;
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const workspace = await getWorkspaceShippingConversationBatches(localConversationId);
|
||||
shippingConversationWorkspace.value = workspace;
|
||||
applyConversationWorkspaceFocus(workspace);
|
||||
applyConversationWorkspaceFocus(workspace, options);
|
||||
return true;
|
||||
} catch {
|
||||
shippingConversationWorkspace.value = null;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 从本轮 SSE 助手消息恢复权威批次快照。
|
||||
*
|
||||
* 核心逻辑:订单识别可能打开属于旧会话的已有任务,此时按当前会话补拉工作台会返回空批次;
|
||||
* 优先应用 `shipping_ui_state` 事件随消息持久化的 `shipping_batch_ui_state`,再由接口刷新后续状态。
|
||||
* @param message - 当前流式回答完成后的助手消息
|
||||
* @returns 是否找到并应用了合法批次快照
|
||||
*/
|
||||
const applyResolvedShippingBatchSnapshot = (snapshot: ShippingBatchUiState | null): boolean => {
|
||||
if (!snapshot) return false;
|
||||
const batchNo = String(snapshot.batch_no || '').trim();
|
||||
applyShippingBatchDetail(snapshot, batchNo);
|
||||
return true;
|
||||
};
|
||||
|
||||
const applyShippingBatchSnapshot = (message: ChatMessage): boolean => (
|
||||
applyResolvedShippingBatchSnapshot(resolveLatestShippingBatchSnapshot([message]))
|
||||
);
|
||||
|
||||
/**
|
||||
* 按“批次快照 -> 任务/批次锚点 -> 会话工作台”顺序恢复聊天工作台。
|
||||
*
|
||||
* 核心逻辑:`open_existing` 可能只携带 `task_no / shipping_ui_state`;此时先恢复任务锚点并补拉任务详情,
|
||||
* 再尝试按任务所属批次加载批次详情,最后才回退到当前会话工作台。
|
||||
* @param payload - 从消息中解析出的恢复载荷
|
||||
* @returns 是否至少恢复出一层任务或批次上下文
|
||||
*/
|
||||
const applyResolvedShippingMessageRecovery = async (
|
||||
payload: ShippingMessageRecoveryPayload | null,
|
||||
): Promise<boolean> => {
|
||||
if (!payload) return false;
|
||||
let recovered = false;
|
||||
const snapshot = payload.shipping_batch_ui_state ?? null;
|
||||
if (applyResolvedShippingBatchSnapshot(snapshot)) {
|
||||
recovered = true;
|
||||
}
|
||||
|
||||
const taskNo = String(
|
||||
payload.task_no
|
||||
|| payload.shipping_ui_state?.task_no
|
||||
|| '',
|
||||
).trim().toUpperCase();
|
||||
let batchNo = String(
|
||||
payload.batch_no
|
||||
|| payload.shipping_ui_state?.batch_no
|
||||
|| snapshot?.batch_no
|
||||
|| '',
|
||||
).trim();
|
||||
|
||||
if (batchNo) {
|
||||
resolvedShippingBatchNo.value = batchNo;
|
||||
activeShippingBatchNo.value = batchNo;
|
||||
}
|
||||
if (taskNo) {
|
||||
resolvedShippingTaskId.value = taskNo;
|
||||
focusedShippingTaskNo.value = taskNo;
|
||||
if (!shippingFocusReason.value) {
|
||||
shippingFocusReason.value = t('chat.shippingNoticeUi.currentFocusDefaultReason');
|
||||
}
|
||||
}
|
||||
if (payload.shipping_ui_state && taskNo) {
|
||||
activeShippingTaskDetail.value = {
|
||||
...(activeShippingTaskDetail.value || {}),
|
||||
task_no: taskNo,
|
||||
batch_no: batchNo || payload.shipping_ui_state.batch_no || null,
|
||||
lines: activeShippingTaskDetail.value?.lines || [],
|
||||
events: activeShippingTaskDetail.value?.events || [],
|
||||
ui_state: payload.shipping_ui_state,
|
||||
} as ShippingTaskDetail;
|
||||
recovered = true;
|
||||
}
|
||||
if (!snapshot && batchNo) {
|
||||
try {
|
||||
const detail = await getWorkspaceShippingBatch(batchNo);
|
||||
applyShippingBatchDetail(detail, batchNo);
|
||||
recovered = true;
|
||||
} catch {
|
||||
// ignore and continue with task-first recovery
|
||||
}
|
||||
}
|
||||
if (taskNo) {
|
||||
await syncActiveShippingTaskDetail(taskNo);
|
||||
const detailBatchNo = String(activeShippingTaskDetail.value?.batch_no || '').trim();
|
||||
if (detailBatchNo) {
|
||||
batchNo = detailBatchNo;
|
||||
resolvedShippingBatchNo.value = detailBatchNo;
|
||||
activeShippingBatchNo.value = detailBatchNo;
|
||||
}
|
||||
if (!snapshot && batchNo && String(shippingBatchSummary.value?.batch_no || '').trim() !== batchNo) {
|
||||
try {
|
||||
const detail = await getWorkspaceShippingBatch(batchNo);
|
||||
applyShippingBatchDetail(detail, batchNo);
|
||||
recovered = true;
|
||||
} catch {
|
||||
// ignore and keep task-only recovery
|
||||
}
|
||||
}
|
||||
recovered = recovered || Boolean(activeShippingTaskDetail.value);
|
||||
}
|
||||
return recovered || Boolean(batchNo);
|
||||
};
|
||||
|
||||
const applyShippingMessageRecovery = async (message: ChatMessage): Promise<boolean> => (
|
||||
applyResolvedShippingMessageRecovery(resolveShippingMessageRecoveryPayload(message))
|
||||
);
|
||||
|
||||
const switchShippingFocusTask = async (taskNo: string) => {
|
||||
const batchNo = getActiveShippingBatchNo();
|
||||
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
|
||||
@@ -529,7 +747,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
messages,
|
||||
conversationId,
|
||||
isThinking,
|
||||
history,
|
||||
resolvedShippingTaskId,
|
||||
shippingTaskIdFromQuery,
|
||||
getActiveBatchTaskId,
|
||||
@@ -563,6 +780,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const finalizeShippingAssistantMessage = async () => {
|
||||
if (!isShippingNoticeAgent.value) return;
|
||||
await shippingIntakes.refreshStatuses();
|
||||
if (!(await syncShippingConversationWorkspace())) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
await syncShippingConversationWorkspace();
|
||||
}
|
||||
shippingIntakes.clearConsumedAttachments();
|
||||
await refreshShippingActions();
|
||||
};
|
||||
@@ -672,6 +893,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
});
|
||||
|
||||
const showShippingDuplicateDialog = ref(false);
|
||||
const showShippingCustomerDialog = ref(false);
|
||||
const shippingCustomerDialogTaskId = ref('');
|
||||
const shippingCustomerOptions = ref<ShippingCustomerOption[]>([]);
|
||||
const shippingCustomerLoading = ref(false);
|
||||
const shippingDuplicateAttachmentId = ref<string | null>(null);
|
||||
const shippingDuplicateAttachment = computed(() => {
|
||||
const id = shippingDuplicateAttachmentId.value;
|
||||
@@ -733,6 +958,50 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
shippingDuplicateAttachmentId.value = null;
|
||||
};
|
||||
|
||||
/** 打开客户确认对话框并加载启用标准客户。 */
|
||||
const openShippingCustomerDialog = async (taskId: string): Promise<void> => {
|
||||
shippingCustomerDialogTaskId.value = String(taskId || '').trim().toUpperCase();
|
||||
showShippingCustomerDialog.value = true;
|
||||
shippingCustomerLoading.value = true;
|
||||
try {
|
||||
shippingCustomerOptions.value = await listWorkspaceShippingCustomerOptions();
|
||||
} catch (error: unknown) {
|
||||
shippingCustomerOptions.value = [];
|
||||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.loadFailed'));
|
||||
} finally {
|
||||
shippingCustomerLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 按关键词刷新客户选项。 */
|
||||
const searchShippingCustomers = async (query: string): Promise<void> => {
|
||||
shippingCustomerLoading.value = true;
|
||||
try {
|
||||
shippingCustomerOptions.value = await listWorkspaceShippingCustomerOptions(query);
|
||||
} catch (error: unknown) {
|
||||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.loadFailed'));
|
||||
} finally {
|
||||
shippingCustomerLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 确认客户后刷新任务详情与动作菜单;业务号仍由后续阶段生成。 */
|
||||
const confirmShippingCustomer = async (customerId: number): Promise<void> => {
|
||||
const taskId = shippingCustomerDialogTaskId.value;
|
||||
if (!taskId) return;
|
||||
shippingCustomerLoading.value = true;
|
||||
try {
|
||||
await confirmWorkspaceShippingCustomer(taskId, customerId);
|
||||
showShippingCustomerDialog.value = false;
|
||||
await Promise.all([syncActiveShippingTaskDetail(taskId), refreshShippingActions()]);
|
||||
msg.success(t('chat.shippingCustomer.confirmed'));
|
||||
} catch (error: unknown) {
|
||||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.confirmFailed'));
|
||||
} finally {
|
||||
shippingCustomerLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 更新 Candidate 选择状态,并将 API 失败统一反馈给用户。 */
|
||||
const setShippingCandidateSelected = async (candidateNo: string, selected: boolean) => {
|
||||
try {
|
||||
@@ -825,6 +1094,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
openShippingInventoryMappingFormForTask,
|
||||
openShippingInventoryPicker,
|
||||
openShippingNoticePicker,
|
||||
openShippingCustomerDialog,
|
||||
executeShippingDecision,
|
||||
executeShippingManualUpload,
|
||||
refreshShippingActions,
|
||||
@@ -870,8 +1140,13 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
hasSelectedNoticeCandidates: () => shippingIntakes.getSelectedCandidateNos().length > 0,
|
||||
openShippingDuplicateDialog,
|
||||
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
|
||||
markOrderExtractionStarted: shippingIntakes.markOrderExtractionStarted,
|
||||
rollbackOrderExtractionStarted: shippingIntakes.rollbackOrderExtractionStarted,
|
||||
refreshNoticeIntakeStatuses: shippingIntakes.refreshStatuses,
|
||||
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
|
||||
applyShippingMessageRecovery,
|
||||
applyShippingBatchSnapshot,
|
||||
syncShippingConversationWorkspace,
|
||||
refreshShippingActions,
|
||||
shippingSuggestedPrompt,
|
||||
isShippingShortageQueryIntent,
|
||||
@@ -881,6 +1156,12 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
});
|
||||
|
||||
// ── 路由 / 会话生命周期 ───────────────────────────────────
|
||||
/**
|
||||
* 根据路由中的 `task_id/batch_no` 恢复发货任务上下文。
|
||||
* 核心逻辑:优先同步显式传入的批次摘要;若仍缺少会话,则直接基于 `task_id` 发起一次继续任务请求,
|
||||
* 禁止再按历史标题模糊猜测旧会话,避免多批次/多票场景跳进错误会话。
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
const resumeShippingTaskFromQuery = async () => {
|
||||
const batchNo = shippingBatchNoFromQuery.value;
|
||||
if (batchNo && isShippingNoticeAgent.value) {
|
||||
@@ -894,11 +1175,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
if (route.query.conversation_id) return;
|
||||
if (presetQuestion.value) return;
|
||||
if (autoResumedShippingTasks.value[taskId]) return;
|
||||
const existing = findHistorySessionForShippingTask(history.value, taskId);
|
||||
if (existing) {
|
||||
await loadConversation(existing.conversation_id, { force: true });
|
||||
return;
|
||||
}
|
||||
autoResumedShippingTasks.value[taskId] = true;
|
||||
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId });
|
||||
await sendMessage(
|
||||
@@ -1010,6 +1286,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
kind: 'local',
|
||||
file,
|
||||
type: kind === 'inventory' ? 'document' : 'document',
|
||||
uploadStatus: 'waiting',
|
||||
uploadProgress: 0,
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -1089,6 +1367,23 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
String(last?.content || '').slice(-120),
|
||||
].join('|');
|
||||
});
|
||||
const shippingRecoveryWatchKey = computed(() => {
|
||||
const recovery = resolveLatestShippingMessageRecoveryPayload(messages.value);
|
||||
const snapshot = recovery?.shipping_batch_ui_state;
|
||||
const uiState = recovery?.shipping_ui_state;
|
||||
return [
|
||||
String(conversationId.value || ''),
|
||||
String(recovery?.batch_no || snapshot?.batch_no || uiState?.batch_no || ''),
|
||||
String(recovery?.task_no || snapshot?.current_focus_task_no || uiState?.task_no || ''),
|
||||
String(snapshot?.updated_at || ''),
|
||||
String(uiState?.updated_at || ''),
|
||||
String(snapshot?.tasks.length || 0),
|
||||
].join('|');
|
||||
});
|
||||
watch([shippingRecoveryWatchKey, isShippingNoticeAgent], () => {
|
||||
if (!isShippingNoticeAgent.value) return;
|
||||
void applyResolvedShippingMessageRecovery(resolveLatestShippingMessageRecoveryPayload(messages.value));
|
||||
}, { immediate: true });
|
||||
watch([shippingActionsWatchKey, isThinking, isShippingNoticeAgent, () => currentAgent.value?.name], () => {
|
||||
void refreshShippingActions().then(async () => {
|
||||
const taskId = getActiveBatchTaskId() || getActiveShippingTaskId();
|
||||
@@ -1188,6 +1483,14 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
updateShippingCandidateSummary,
|
||||
resolveShippingCandidateDuplicate,
|
||||
showShippingDuplicateDialog,
|
||||
showShippingCustomerDialog,
|
||||
shippingCustomerOptions,
|
||||
shippingCustomerLoading,
|
||||
searchShippingCustomers,
|
||||
confirmShippingCustomer,
|
||||
closeShippingCustomerDialog: () => {
|
||||
showShippingCustomerDialog.value = false;
|
||||
},
|
||||
shippingDuplicateAttachment,
|
||||
canForceCreateShippingDuplicate,
|
||||
openShippingDuplicateDialog,
|
||||
|
||||
@@ -9,7 +9,10 @@ import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
|
||||
import type { StartChatTurnOptions } from '../types/chat-turn.types';
|
||||
import type { ChatMessage, ChatRun } from '../types/chat.types';
|
||||
import { applyShippingUiStateToMessage } from './useChat';
|
||||
import {
|
||||
applyShippingOrderExtractionStateToMessage,
|
||||
applyShippingUiStateToMessage,
|
||||
} from './useChat';
|
||||
|
||||
export interface CreateStartChatTurnOptions {
|
||||
messages: Ref<ChatMessage[]>;
|
||||
@@ -169,6 +172,9 @@ export function createStartChatTurn(options: CreateStartChatTurnOptions) {
|
||||
if (eventName === 'shipping_ui_state' || eventName === 'ui_state.updated') {
|
||||
const botMsg = ensureBotMessage();
|
||||
if (botMsg) applyShippingUiStateToMessage(botMsg, data);
|
||||
} else if (eventName === 'shipping_order_extraction_state') {
|
||||
const botMsg = ensureBotMessage();
|
||||
if (botMsg) applyShippingOrderExtractionStateToMessage(botMsg, data);
|
||||
} else if (
|
||||
eventName === 'message'
|
||||
|| eventName === 'agent_message'
|
||||
|
||||
@@ -36,6 +36,7 @@ vi.mock('../shipping/shippingNoticeBatchIdempotency', () => ({
|
||||
const createConversationContext = () => {
|
||||
const conversationId = ref<string | null>('conv-a');
|
||||
const messages = ref([]);
|
||||
const loadConversationState = vi.fn();
|
||||
const createNewChatView = vi.fn(() => {
|
||||
conversationId.value = null;
|
||||
messages.value = [];
|
||||
@@ -44,6 +45,7 @@ const createConversationContext = () => {
|
||||
return {
|
||||
conversationId,
|
||||
messages,
|
||||
loadConversationState,
|
||||
createNewChatView,
|
||||
api: createChatPageConversationApi({
|
||||
deps: { t: (key: string) => key, msg: { warning: vi.fn() } },
|
||||
@@ -54,7 +56,7 @@ const createConversationContext = () => {
|
||||
activeRunId: ref(null),
|
||||
messages,
|
||||
isThinking: ref(false),
|
||||
loadConversationState: vi.fn(),
|
||||
loadConversationState,
|
||||
createNewChatView,
|
||||
clearPendingNoticeBatchRetry,
|
||||
onConversationIdChanging: vi.fn(),
|
||||
@@ -163,4 +165,32 @@ describe('useChatPageConversation', () => {
|
||||
expect(secondKey).toBeTruthy();
|
||||
expect(secondKey).not.toBe(firstKey);
|
||||
});
|
||||
|
||||
it('loadConversation keeps attachment-only history snapshots intact', async () => {
|
||||
const { api, loadConversationState } = createConversationContext();
|
||||
listChatMessages.mockResolvedValue([{
|
||||
role: 'user',
|
||||
content: '',
|
||||
attachments: [{
|
||||
id: 'attachment-only-1',
|
||||
name: 'notice.eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}],
|
||||
}]);
|
||||
|
||||
await api.loadConversation('conv-attachment-only', { force: true });
|
||||
|
||||
expect(listChatMessages).toHaveBeenCalledWith('conv-attachment-only', 42);
|
||||
expect(loadConversationState).toHaveBeenCalledWith('conv-attachment-only', [{
|
||||
role: 'user',
|
||||
content: '',
|
||||
attachments: [{
|
||||
id: 'attachment-only-1',
|
||||
name: 'notice.eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}],
|
||||
}]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* features/chat/page/useChatPageMarkdown.spec.ts
|
||||
* 用途:验证聊天消息可见性与思考提示在订单识别生命周期中的切换行为。
|
||||
* 依赖:Vitest、Vue 响应式 API、useChatPageMarkdown。
|
||||
* 逻辑:构造最小 Markdown 上下文,确保空正文的订单识别状态可见且替代通用思考提示。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import {
|
||||
createChatPageMarkdownApi,
|
||||
type ChatPageMarkdownContext,
|
||||
} from './useChatPageMarkdown';
|
||||
|
||||
/**
|
||||
* 创建消息可见性测试所需的最小 Markdown 上下文。
|
||||
* 核心逻辑:所有外部解析器返回空结果,让断言只受消息正文和订单识别状态影响。
|
||||
* @param messages - 当前聊天消息列表。
|
||||
* @param isThinking - 是否仍在等待助手回复。
|
||||
* @returns 可直接传给 createChatPageMarkdownApi 的上下文。
|
||||
*/
|
||||
function createContext(
|
||||
messages: ChatMessage[],
|
||||
isThinking = true,
|
||||
): ChatPageMarkdownContext {
|
||||
return {
|
||||
messages: ref(messages),
|
||||
isThinking: ref(isThinking),
|
||||
prepareMarkdownDisplayText: (text) => text,
|
||||
handleLeaveMarkdownClick: () => undefined,
|
||||
parsePlmPreviewLink: () => null,
|
||||
openPreview: async () => undefined,
|
||||
openAssetHistory: () => undefined,
|
||||
openAssetImage: () => undefined,
|
||||
getMessageLinks: () => [],
|
||||
getDisplayRetrieverResources: () => [],
|
||||
getSourceLinks: () => [],
|
||||
shouldExpandSourceDetails: () => false,
|
||||
getSourceTitle: () => '',
|
||||
getSourceMeta: () => '',
|
||||
getSourceBrief: () => '',
|
||||
getShippingInventoryMappingPayload: () => null,
|
||||
getShippingMatchResultPayload: () => null,
|
||||
canOpenQueryPreview: () => false,
|
||||
getQueryPreviewSummary: () => '',
|
||||
openQueryPreviewDialog: () => undefined,
|
||||
shippingActionButtonClass: () => '',
|
||||
onShippingActionClick: () => undefined,
|
||||
};
|
||||
}
|
||||
|
||||
const extractionMessage: ChatMessage = {
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
shipping_order_extraction_state: {
|
||||
status: 'extracting',
|
||||
phase: 'llm_extraction',
|
||||
message: '正在识别邮件及附件中的订单',
|
||||
created_count: 0,
|
||||
opened_existing_count: 0,
|
||||
pending_count: 0,
|
||||
non_shipping_count: 0,
|
||||
created_with_missing_fields_count: 0,
|
||||
batch_no: null,
|
||||
terminal: false,
|
||||
},
|
||||
};
|
||||
|
||||
describe('useChatPageMarkdown order extraction visibility', () => {
|
||||
it('renders an extraction-state message before Dify content arrives', () => {
|
||||
const api = createChatPageMarkdownApi(createContext([]));
|
||||
|
||||
// 关键断言:结构化进度不能因为 assistant 正文为空而被消息过滤器隐藏。
|
||||
expect(api.shouldRenderMessage(extractionMessage)).toBe(true);
|
||||
expect(api.shouldRenderMessage({ role: 'assistant', content: '' })).toBe(false);
|
||||
});
|
||||
|
||||
it('hides the generic thinking bubble when extraction progress is visible', () => {
|
||||
const api = createChatPageMarkdownApi(createContext([
|
||||
{ role: 'user', content: '请解析当前邮件中的发货订单' },
|
||||
extractionMessage,
|
||||
]));
|
||||
|
||||
// 关键断言:领域进度已出现时不再叠加通用“思考中”,避免重复反馈。
|
||||
expect(api.shouldShowThinkingBubble.value).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -338,10 +338,18 @@ function enhanceAssetHistoryTableLinks(html: string): string {
|
||||
export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
const message = useMessage();
|
||||
|
||||
/**
|
||||
* 判断消息是否具备可展示内容。
|
||||
* 核心逻辑:订单识别状态本身就是用户可见反馈,即使 Dify 正文尚未到达也必须渲染;
|
||||
* 其余消息继续沿用正文、链接、引用源和结构化消息的既有判断。
|
||||
* @param msgItem - 当前聊天消息。
|
||||
* @returns 消息是否应进入聊天列表渲染。
|
||||
*/
|
||||
const shouldRenderMessage = (msgItem: ChatMessage): boolean => {
|
||||
if (msgItem?.role === 'user') return true;
|
||||
if (msgItem?.type === 'shipping-parse-review') return false;
|
||||
if (msgItem?.type === 'leave-form' || msgItem?.type === 'leave-confirmation' || msgItem?.type === 'leave-result') return true;
|
||||
if (msgItem?.shipping_order_extraction_state) return true;
|
||||
const content = (msgItem?.content || '').trim();
|
||||
if (content) return true;
|
||||
if (ctx.getMessageLinks(msgItem as unknown as Record<string, unknown>).length > 0) return true;
|
||||
@@ -356,6 +364,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
*/
|
||||
const hasMeaningfulAssistantReply = (msgItem: ChatMessage): boolean => {
|
||||
if (msgItem?.role !== 'assistant') return false;
|
||||
if (msgItem?.shipping_order_extraction_state) return true;
|
||||
if (msgItem?.type === 'leave-form'
|
||||
|| msgItem?.type === 'leave-confirmation'
|
||||
|| msgItem?.type === 'leave-result'
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* features/chat/page/useChatPageSend.spec.ts
|
||||
* 用途:验证普通聊天发送时附件失败保留、消息成功后清空的恢复语义。
|
||||
* 依赖:Vitest、Vue 响应式 API、useChatPageSend。
|
||||
* 逻辑:构造最小发送上下文,分别模拟上传失败、SSE 发送失败与发送成功。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { createChatPageSendApi, type ChatPageSendContext } from './useChatPageSend';
|
||||
import type { ChatMessageAttachment } from '../types/chat.types';
|
||||
|
||||
const attachmentSnapshots: ChatMessageAttachment[] = [{
|
||||
id: 'attachment-1',
|
||||
name: 'purchase-order.pdf',
|
||||
size: 3,
|
||||
extension: 'pdf',
|
||||
type: 'document',
|
||||
source: 'local',
|
||||
}];
|
||||
|
||||
/** 创建普通聊天发送测试上下文。 */
|
||||
function createContext(overrides: Partial<ChatPageSendContext> = {}): ChatPageSendContext {
|
||||
return {
|
||||
input: ref('请分析附件'),
|
||||
messages: ref([]),
|
||||
isThinking: ref(false),
|
||||
currentAgentId: computed(() => 1),
|
||||
selectedKb: ref(''),
|
||||
isUploadingAttachments: ref(false),
|
||||
attachmentPolicy: computed(() => ({ anyEnabled: true })),
|
||||
attachments: ref([{ id: 'attachment-1' }]),
|
||||
allowsSendWithAttachmentsOnly: computed(() => true),
|
||||
buildFileSpecsForSend: vi.fn(async () => [
|
||||
{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-1' },
|
||||
]),
|
||||
createMessageAttachmentSnapshots: vi.fn(() => attachmentSnapshots.map((item) => ({ ...item }))),
|
||||
clearAttachments: vi.fn(),
|
||||
sendMessage: vi.fn(async () => true),
|
||||
refreshHistoryAfterSend: vi.fn(async () => undefined),
|
||||
refreshConversationAfterSend: vi.fn(async () => undefined),
|
||||
tryHandleShippingAttachmentAutoFlow: vi.fn(async () => false),
|
||||
tryHandleLeaveSend: vi.fn(() => false),
|
||||
tryHandleShippingSend: vi.fn(async () => false),
|
||||
refreshToolRunProgressAfterSend: vi.fn(async () => undefined),
|
||||
prepareToolRunProgressBeforeSend: vi.fn(async () => undefined),
|
||||
msg: { warning: vi.fn(), info: vi.fn() },
|
||||
t: (key: string) => key,
|
||||
copiedIndex: ref(null),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('createChatPageSendApi attachment lifecycle', () => {
|
||||
it('keeps attachments when file upload fails', async () => {
|
||||
const ctx = createContext({
|
||||
buildFileSpecsForSend: vi.fn(async () => { throw new Error('upload failed'); }),
|
||||
});
|
||||
|
||||
await createChatPageSendApi(ctx).handleSend();
|
||||
|
||||
expect(ctx.clearAttachments).not.toHaveBeenCalled();
|
||||
expect(ctx.sendMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps uploaded attachments when message sending fails', async () => {
|
||||
const ctx = createContext({
|
||||
sendMessage: vi.fn(async () => { throw new Error('stream failed'); }),
|
||||
});
|
||||
|
||||
await expect(createChatPageSendApi(ctx).handleSend()).rejects.toThrow('stream failed');
|
||||
|
||||
expect(ctx.clearAttachments).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps uploaded attachments when the real send result reports failure', async () => {
|
||||
const ctx = createContext({
|
||||
sendMessage: vi.fn(async () => false),
|
||||
});
|
||||
|
||||
await createChatPageSendApi(ctx).handleSend();
|
||||
|
||||
expect(ctx.clearAttachments).not.toHaveBeenCalled();
|
||||
expect(ctx.refreshHistoryAfterSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('clears attachments only after message sending succeeds', async () => {
|
||||
const ctx = createContext();
|
||||
|
||||
await createChatPageSendApi(ctx).handleSend();
|
||||
|
||||
expect(ctx.sendMessage).toHaveBeenCalledOnce();
|
||||
expect(ctx.sendMessage).toHaveBeenCalledWith(
|
||||
'请分析附件',
|
||||
1,
|
||||
'',
|
||||
[{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-1' }],
|
||||
undefined,
|
||||
expect.objectContaining({ userAttachments: attachmentSnapshots }),
|
||||
);
|
||||
expect(ctx.clearAttachments).toHaveBeenCalledOnce();
|
||||
expect(vi.mocked(ctx.sendMessage).mock.invocationCallOrder[0]).toBeLessThan(
|
||||
vi.mocked(ctx.clearAttachments).mock.invocationCallOrder[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('sends attachment-only messages with an internal prompt and an empty display query', async () => {
|
||||
const ctx = createContext({ input: ref('') });
|
||||
|
||||
await createChatPageSendApi(ctx).handleSend();
|
||||
|
||||
expect(ctx.sendMessage).toHaveBeenCalledWith(
|
||||
'chat.attachment.defaultPrompt',
|
||||
1,
|
||||
'',
|
||||
[{ type: 'document', transfer_method: 'local_file', upload_file_id: 'upload-1' }],
|
||||
{ display_query: '' },
|
||||
expect.objectContaining({ userAttachments: attachmentSnapshots }),
|
||||
);
|
||||
expect(ctx.clearAttachments).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,14 @@
|
||||
/**
|
||||
* 对话页:发送消息编排(出货/请假前置拦截 → Dify SSE)、复制与重新生成。
|
||||
* features/chat/page/useChatPageSend.ts
|
||||
* 用途:编排聊天消息发送、业务前置拦截、复制与重新生成。
|
||||
* 依赖:统一 BusinessError、剪贴板工具、Chat 消息与附件参数类型。
|
||||
* 逻辑:附件上传成功后调用 Dify SSE;仅在消息发送成功后清空附件,失败时保留供重试。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { copyTextToClipboard } from '@/shared/utils/clipboard';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ChatMessage, ChatMessageAttachment } from '../types/chat.types';
|
||||
import type { SendMessageLifecycleHooks } from '../composables/useChat';
|
||||
import type { ChatUploadFileSpec } from '../types/shipping.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
@@ -42,6 +46,7 @@ export interface ChatPageSendContext {
|
||||
attachments: Ref<unknown[]>;
|
||||
allowsSendWithAttachmentsOnly: ComputedRef<boolean>;
|
||||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||||
createMessageAttachmentSnapshots: () => ChatMessageAttachment[];
|
||||
clearAttachments: () => void;
|
||||
sendMessage: (
|
||||
content: string,
|
||||
@@ -49,8 +54,8 @@ export interface ChatPageSendContext {
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
|
||||
hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void> },
|
||||
) => Promise<void>;
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => Promise<boolean | void>;
|
||||
refreshHistoryAfterSend: () => Promise<void>;
|
||||
refreshConversationAfterSend?: () => Promise<void>;
|
||||
tryHandleShippingAttachmentAutoFlow: (
|
||||
@@ -78,6 +83,11 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
|
||||
const allowSendWhileThinking = canContinueSendWhileThinking(ctx.messages.value);
|
||||
if (ctx.isUploadingAttachments.value) return false;
|
||||
if (ctx.input.value.trim()) return !ctx.isThinking.value || allowSendWhileThinking;
|
||||
if (
|
||||
ctx.attachments.value.length > 0
|
||||
&& ctx.attachmentPolicy.value.anyEnabled
|
||||
&& (!ctx.isThinking.value || allowSendWhileThinking)
|
||||
) return true;
|
||||
if (ctx.allowsSendWithAttachmentsOnly.value) return true;
|
||||
return false;
|
||||
});
|
||||
@@ -85,11 +95,12 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
|
||||
const handleSend = async (textOrEvent?: string | Event) => {
|
||||
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || ctx.input.value;
|
||||
const trimmed = content.trim();
|
||||
const hasAttachments = ctx.attachmentPolicy.value.anyEnabled && ctx.attachments.value.length > 0;
|
||||
const allowSendWhileThinking = canContinueSendWhileThinking(ctx.messages.value);
|
||||
if (await ctx.tryHandleShippingAttachmentAutoFlow(textOrEvent, content, trimmed)) {
|
||||
return;
|
||||
}
|
||||
if (!trimmed || ctx.isUploadingAttachments.value || (ctx.isThinking.value && !allowSendWhileThinking)) {
|
||||
if ((!trimmed && !hasAttachments) || ctx.isUploadingAttachments.value || (ctx.isThinking.value && !allowSendWhileThinking)) {
|
||||
return;
|
||||
}
|
||||
if (ctx.tryHandleLeaveSend(content)) {
|
||||
@@ -100,9 +111,11 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
|
||||
}
|
||||
|
||||
let files: ChatUploadFileSpec[] = [];
|
||||
let messageAttachments: ChatMessageAttachment[] = [];
|
||||
if (ctx.attachmentPolicy.value.anyEnabled && ctx.attachments.value.length > 0) {
|
||||
try {
|
||||
files = await ctx.buildFileSpecsForSend();
|
||||
messageAttachments = ctx.createMessageAttachmentSnapshots();
|
||||
} catch (e: unknown) {
|
||||
let suffix = '';
|
||||
if (e instanceof BusinessError) {
|
||||
@@ -121,17 +134,26 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
|
||||
}
|
||||
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.clearAttachments();
|
||||
|
||||
const requestContent = trimmed || ctx.t('chat.attachment.defaultPrompt');
|
||||
const sendContext = {
|
||||
...(ctx.getChatContext?.() || {}),
|
||||
...(!trimmed && messageAttachments.length > 0 ? { display_query: '' } : {}),
|
||||
};
|
||||
await ctx.prepareToolRunProgressBeforeSend();
|
||||
await ctx.sendMessage(
|
||||
content,
|
||||
const sent = await ctx.sendMessage(
|
||||
requestContent,
|
||||
ctx.currentAgentId.value,
|
||||
ctx.selectedKb.value,
|
||||
files,
|
||||
ctx.getChatContext?.(),
|
||||
{ onAssistantMessageFinished: ctx.onAssistantMessageFinished },
|
||||
Object.keys(sendContext).length > 0 ? sendContext : undefined,
|
||||
{
|
||||
userAttachments: messageAttachments,
|
||||
onAssistantMessageFinished: ctx.onAssistantMessageFinished,
|
||||
},
|
||||
);
|
||||
if (sent === false) return;
|
||||
ctx.clearAttachments();
|
||||
await ctx.refreshHistoryAfterSend();
|
||||
await ctx.refreshConversationAfterSend?.();
|
||||
await ctx.refreshToolRunProgressAfterSend();
|
||||
|
||||
@@ -21,7 +21,7 @@ export interface ShippingConversationContext {
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; display_query?: string },
|
||||
) => Promise<void>;
|
||||
) => Promise<boolean | void>;
|
||||
}
|
||||
|
||||
/** 发送菜单类消息后,若当前会话尚未出现在侧栏历史中则刷新列表 */
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingTaskId.ts
|
||||
* 用途:从消息或会话历史中识别发货任务编号(SN- 格式)。
|
||||
* 用途:从聊天消息中识别发货任务编号(SN- 格式)。
|
||||
* 依赖:constants/shipping.SHIPPING_TASK_ID_RE、chat.types。
|
||||
* 逻辑:useChatShipping 切换任务/恢复会话时调用。
|
||||
* 逻辑:useChatShipping 与 shipping refresh 只把这里作为消息级兜底,不再承担历史标题猜测。
|
||||
*/
|
||||
import { SHIPPING_TASK_ID_RE } from '../constants/shipping';
|
||||
import type { ChatSessionItem } from '../types/chat.types';
|
||||
|
||||
/** 从消息列表倒序查找最近出现的 SN- 任务编号。 */
|
||||
export function findLatestShippingTaskId(msgs: Array<{ content?: string }>): string {
|
||||
@@ -15,13 +14,3 @@ export function findLatestShippingTaskId(msgs: Array<{ content?: string }>): str
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/** 在侧栏历史中按标题模糊匹配含 taskId 的会话。 */
|
||||
export function findHistorySessionForShippingTask(
|
||||
history: ChatSessionItem[],
|
||||
taskId: string,
|
||||
): ChatSessionItem | null {
|
||||
const needle = taskId.trim().toUpperCase();
|
||||
if (!needle) return null;
|
||||
return history.find((item) => String(item.title || '').toUpperCase().includes(needle)) || null;
|
||||
}
|
||||
@@ -23,6 +23,7 @@ export interface ShippingMenuHandlerContext {
|
||||
openShippingInventoryMappingFormForTask: (taskId: string) => Promise<boolean>;
|
||||
openShippingInventoryPicker: (taskId?: string) => boolean;
|
||||
openShippingNoticePicker: (taskId?: string) => boolean;
|
||||
openShippingCustomerDialog: (taskId: string) => Promise<void>;
|
||||
executeShippingDecision: (
|
||||
decision: string,
|
||||
displayText?: string,
|
||||
@@ -142,6 +143,15 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action.id === 'confirm_customer') {
|
||||
const taskId = resolveTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
}
|
||||
await ctx.openShippingCustomerDialog(taskId);
|
||||
return;
|
||||
}
|
||||
|
||||
const chatTurnActionIds = new Set([
|
||||
'generate_excel',
|
||||
|
||||
@@ -21,13 +21,12 @@ describe('useChatShippingRefresh', () => {
|
||||
getWorkspaceShippingTaskUiState.mockReset();
|
||||
});
|
||||
|
||||
it('prefers current batch focus task over message and history fallbacks', () => {
|
||||
it('prefers current batch focus task over other explicit anchors', () => {
|
||||
expect(resolvePreferredShippingTaskId({
|
||||
batchTaskId: 'sn-batch-001',
|
||||
messageTaskId: 'sn-message-001',
|
||||
resolvedTaskId: 'sn-resolved-001',
|
||||
queryTaskId: 'sn-query-001',
|
||||
historyTaskId: 'sn-history-001',
|
||||
})).toBe('SN-BATCH-001');
|
||||
});
|
||||
|
||||
@@ -37,7 +36,6 @@ describe('useChatShippingRefresh', () => {
|
||||
messageTaskId: '',
|
||||
resolvedTaskId: '',
|
||||
queryTaskId: '',
|
||||
historyTaskId: '',
|
||||
})).toBe('');
|
||||
});
|
||||
|
||||
@@ -88,7 +86,6 @@ describe('useChatShippingRefresh', () => {
|
||||
messages,
|
||||
conversationId: ref('conv-focus-switch'),
|
||||
isThinking: ref(false),
|
||||
history: ref([]),
|
||||
resolvedShippingTaskId,
|
||||
shippingTaskIdFromQuery: computed(() => ''),
|
||||
getActiveBatchTaskId: () => 'SN-FOCUS-B',
|
||||
@@ -159,7 +156,6 @@ describe('useChatShippingRefresh', () => {
|
||||
messages,
|
||||
conversationId: ref('conv-source'),
|
||||
isThinking: ref(false),
|
||||
history: ref([]),
|
||||
resolvedShippingTaskId: ref('SN-SOURCE-001'),
|
||||
shippingTaskIdFromQuery: computed(() => ''),
|
||||
getActiveBatchTaskId: () => 'SN-SOURCE-001',
|
||||
@@ -170,4 +166,27 @@ describe('useChatShippingRefresh', () => {
|
||||
expect(messages.value[0].shipping_actions?.map((item) => item.id)).toEqual(['download_excel']);
|
||||
expect(messages.value[0].shipping_ui_state?.action_buttons?.map((item) => item.id)).toEqual(['download_excel']);
|
||||
});
|
||||
|
||||
it('does not guess a task id from history metadata when no explicit anchor exists', async () => {
|
||||
const messages = ref([
|
||||
{
|
||||
role: 'assistant' as const,
|
||||
content: '请继续处理当前任务',
|
||||
},
|
||||
]);
|
||||
const { refreshShippingActions } = createShippingActionsRefresher({
|
||||
isShippingNoticeAgent: computed(() => true),
|
||||
messages,
|
||||
conversationId: ref('conv-no-anchor'),
|
||||
isThinking: ref(false),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
shippingTaskIdFromQuery: computed(() => ''),
|
||||
getActiveBatchTaskId: () => '',
|
||||
});
|
||||
|
||||
await refreshShippingActions();
|
||||
|
||||
expect(getWorkspaceShippingTaskUiState).not.toHaveBeenCalled();
|
||||
expect(messages.value[0].shipping_actions).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -2,14 +2,13 @@
|
||||
* features/chat/shipping/useChatShippingRefresh.ts
|
||||
* 用途:刷新聊天区发货通知 UI State,把后端状态机 action_buttons 同步到消息气泡。
|
||||
* 依赖:shipping.api、shippingTaskId、shippingNoticeActions 常量、chat.types。
|
||||
* 逻辑:由 useChatShipping 调用本文件;本文件只读取后端 /ui-state,不再从 Dify 正文解析按钮。
|
||||
* 逻辑:由 useChatShipping 调用本文件;本文件只读取后端 /ui-state,不再从会话标题猜任务号或从 Dify 正文解析按钮。
|
||||
*/
|
||||
import { getWorkspaceShippingTaskUiState } from '@/features/chat/api/shipping.api';
|
||||
import { SHIPPING_TERMINAL_CHECKPOINTS } from '@/constants/shippingNoticeActions';
|
||||
import { SHIPPING_TASK_ID_RE } from '../constants/shipping';
|
||||
import { findLatestShippingTaskId } from './shippingTaskId';
|
||||
import { stripShippingActionListByButtons, stripShippingPlainActionMenu } from './shippingText';
|
||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ShippingActionButton } from '../types/shipping.types';
|
||||
import type { ShippingTaskUiState } from '../types/shipping.api.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
@@ -19,7 +18,6 @@ export interface ShippingRefreshContext {
|
||||
messages: Ref<ChatMessage[]>;
|
||||
conversationId: Ref<string | null>;
|
||||
isThinking: Ref<boolean>;
|
||||
history: Ref<ChatSessionItem[]>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
shippingTaskIdFromQuery: ComputedRef<string>;
|
||||
getActiveBatchTaskId: () => string;
|
||||
@@ -29,7 +27,7 @@ export interface ShippingRefreshContext {
|
||||
* 解析当前聊天页最可靠的发货任务编号。
|
||||
*
|
||||
* 核心逻辑:优先使用批次当前焦点任务,其次才回退到消息内嵌任务号、已解析状态和路由参数;
|
||||
* 禁止再按 conversation 扫任务列表“猜”一票,避免多票会话把动作按钮挂错任务。
|
||||
* 禁止再按 conversation 标题“猜”一票,避免多票会话把动作按钮挂错任务。
|
||||
* @param params - 当前聊天页中可用的任务定位线索
|
||||
* @returns 可信的任务编号;无法明确定位时返回空字符串
|
||||
*/
|
||||
@@ -38,14 +36,12 @@ export function resolvePreferredShippingTaskId(params: {
|
||||
messageTaskId?: string | null;
|
||||
resolvedTaskId?: string | null;
|
||||
queryTaskId?: string | null;
|
||||
historyTaskId?: string | null;
|
||||
}) {
|
||||
return String(
|
||||
params.batchTaskId
|
||||
|| params.messageTaskId
|
||||
|| params.resolvedTaskId
|
||||
|| params.queryTaskId
|
||||
|| params.historyTaskId
|
||||
|| '',
|
||||
).trim().toUpperCase();
|
||||
}
|
||||
@@ -74,20 +70,11 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
if (!ctx.isShippingNoticeAgent.value) return;
|
||||
const msgs = ctx.messages.value;
|
||||
if (!msgs.length) return;
|
||||
const cid = String(ctx.conversationId.value || '').trim();
|
||||
const historyTaskId = (() => {
|
||||
if (!cid) return '';
|
||||
const session = ctx.history.value.find((item) => String(item.conversation_id || '') === cid);
|
||||
const title = String(session?.title || '');
|
||||
const match = title.match(SHIPPING_TASK_ID_RE);
|
||||
return match?.[0] ? match[0].toUpperCase() : '';
|
||||
})();
|
||||
const taskId = resolvePreferredShippingTaskId({
|
||||
batchTaskId: ctx.getActiveBatchTaskId(),
|
||||
messageTaskId: findLatestShippingTaskId(msgs),
|
||||
resolvedTaskId: ctx.resolvedShippingTaskId.value,
|
||||
queryTaskId: ctx.shippingTaskIdFromQuery.value,
|
||||
historyTaskId,
|
||||
});
|
||||
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
|
||||
let lastOpenAssistantIndex = -1;
|
||||
|
||||
@@ -22,7 +22,14 @@ const createContext = (
|
||||
conversationId: ref('conv-send'),
|
||||
history: ref([]),
|
||||
input: ref(''),
|
||||
attachments: ref([{ kind: 'local', file: new File(['notice'], 'notice.txt', { type: 'text/plain' }) }]),
|
||||
attachments: ref([{
|
||||
id: 'local-notice',
|
||||
kind: 'local',
|
||||
file: new File(['notice'], 'notice.txt', { type: 'text/plain' }),
|
||||
type: 'document',
|
||||
uploadStatus: 'waiting',
|
||||
uploadProgress: 0,
|
||||
}]),
|
||||
shippingAutoFlowRequested: ref(true),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
getActiveShippingBatchNo: () => '',
|
||||
@@ -32,7 +39,7 @@ const createContext = (
|
||||
getActiveShippingTaskId: () => '',
|
||||
lastAssistantMessageContent: () => '',
|
||||
lastAssistantShippingActions: () => [],
|
||||
sendMessage: vi.fn(async () => undefined),
|
||||
sendMessage: vi.fn(async () => true),
|
||||
buildFileSpecsForSend: vi.fn(async () => []),
|
||||
loadHistory: vi.fn(async () => undefined),
|
||||
sendShippingMenuMessage: vi.fn(async () => undefined),
|
||||
@@ -44,6 +51,9 @@ const createContext = (
|
||||
handleShippingAutoUploadFile: vi.fn(async () => undefined),
|
||||
handleShippingAutoUploadNoticeBatch: vi.fn(async () => undefined),
|
||||
isShippingNoticeBatchSubmitting: () => isShippingNoticeBatchSubmitting(),
|
||||
markOrderExtractionStarted: vi.fn(),
|
||||
rollbackOrderExtractionStarted: vi.fn(),
|
||||
syncShippingConversationWorkspace: vi.fn(async () => true),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
shippingSuggestedPrompt: computed(() => ''),
|
||||
isShippingShortageQueryIntent: () => false,
|
||||
@@ -73,6 +83,7 @@ describe('useChatShippingSendHandler', () => {
|
||||
});
|
||||
|
||||
it('sends parsed intakes to the existing Chatflow without requiring upload-time candidates', async () => {
|
||||
const completionOrder: string[] = [];
|
||||
const attachment = {
|
||||
id: 'notice-1',
|
||||
kind: 'shipping_notice' as const,
|
||||
@@ -89,8 +100,11 @@ describe('useChatShippingSendHandler', () => {
|
||||
hasCandidateReviewIssues: () => true,
|
||||
hasSelectedNoticeCandidates: () => true,
|
||||
getParsedIntakeNos: () => ['SNI-1'],
|
||||
refreshNoticeIntakeStatuses: vi.fn(async () => undefined),
|
||||
clearConsumedNoticeAttachments: vi.fn(),
|
||||
applyShippingMessageRecovery: vi.fn(async () => { completionOrder.push('recovery'); return true; }),
|
||||
refreshNoticeIntakeStatuses: vi.fn(async () => { completionOrder.push('intakes'); }),
|
||||
syncShippingConversationWorkspace: vi.fn(async () => { completionOrder.push('workspace'); return true; }),
|
||||
clearConsumedNoticeAttachments: vi.fn(() => { completionOrder.push('clear'); }),
|
||||
refreshShippingActions: vi.fn(async () => { completionOrder.push('actions'); }),
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
@@ -107,8 +121,26 @@ describe('useChatShippingSendHandler', () => {
|
||||
shipping_intake_nos: ['SNI-1'],
|
||||
display_query: 'chat.shippingOrderExtractionDefaultPrompt',
|
||||
},
|
||||
expect.objectContaining({ onAssistantMessageFinished: expect.any(Function) }),
|
||||
expect.objectContaining({
|
||||
userAttachments: [{
|
||||
id: 'notice-1',
|
||||
name: 'orders.eml',
|
||||
size: 100,
|
||||
extension: 'eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}],
|
||||
onAssistantMessageFinished: expect.any(Function),
|
||||
}),
|
||||
);
|
||||
expect(ctx.markOrderExtractionStarted).toHaveBeenCalledWith(['SNI-1']);
|
||||
|
||||
const hooks = vi.mocked(ctx.sendMessage).mock.calls[0]?.[5];
|
||||
const assistantMessage = { role: 'assistant', content: '已打开已有任务' } as const;
|
||||
await hooks?.onAssistantMessageFinished?.(assistantMessage, []);
|
||||
expect(ctx.applyShippingMessageRecovery).toHaveBeenCalledWith(assistantMessage);
|
||||
expect(completionOrder).toEqual(['recovery', 'intakes', 'workspace', 'clear', 'actions']);
|
||||
expect(ctx.syncShippingConversationWorkspace).toHaveBeenCalledWith({ preferLatest: true });
|
||||
});
|
||||
|
||||
it('uses the user query for full extraction even when no candidate exists before send', async () => {
|
||||
@@ -144,7 +176,102 @@ describe('useChatShippingSendHandler', () => {
|
||||
shipping_intake_nos: ['SNI-1'],
|
||||
display_query: '请解析这些附件',
|
||||
},
|
||||
expect.objectContaining({ onAssistantMessageFinished: expect.any(Function) }),
|
||||
expect.objectContaining({
|
||||
userAttachments: [{
|
||||
id: 'notice-1',
|
||||
name: 'orders.eml',
|
||||
size: 100,
|
||||
extension: 'eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}],
|
||||
onAssistantMessageFinished: expect.any(Function),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('retries the conversation workspace once when the first refresh fails', async () => {
|
||||
const syncWorkspace = vi.fn()
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(true);
|
||||
const ctx = createContext({
|
||||
attachments: ref([{
|
||||
id: 'notice-retry',
|
||||
kind: 'shipping_notice' as const,
|
||||
type: 'document' as const,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: 'parsed' as const,
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-RETRY',
|
||||
}]),
|
||||
getParsedIntakeNos: () => ['SNI-RETRY'],
|
||||
syncShippingConversationWorkspace: syncWorkspace,
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
const hooks = vi.mocked(ctx.sendMessage).mock.calls[0]?.[5];
|
||||
await hooks?.onAssistantMessageFinished?.({} as never, []);
|
||||
|
||||
expect(syncWorkspace).toHaveBeenCalledTimes(2);
|
||||
expect(syncWorkspace).toHaveBeenNthCalledWith(1, { preferLatest: true });
|
||||
expect(syncWorkspace).toHaveBeenNthCalledWith(2, { preferLatest: true });
|
||||
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('rolls back the local extracting state when the chat request fails', async () => {
|
||||
const rollback = vi.fn();
|
||||
const ctx = createContext({
|
||||
attachments: ref([{
|
||||
id: 'notice-failed-send',
|
||||
kind: 'shipping_notice' as const,
|
||||
type: 'document' as const,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: 'parsed' as const,
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-FAILED-SEND',
|
||||
}]),
|
||||
getParsedIntakeNos: () => ['SNI-FAILED-SEND'],
|
||||
sendMessage: vi.fn(async () => { throw new Error('network failed'); }),
|
||||
rollbackOrderExtractionStarted: rollback,
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(rollback).toHaveBeenCalledWith(['SNI-FAILED-SEND']);
|
||||
expect(ctx.msg.warning).toHaveBeenCalledWith('network failed');
|
||||
});
|
||||
|
||||
it('rolls back extraction state when sendMessage reports a handled stream failure', async () => {
|
||||
const rollback = vi.fn();
|
||||
const ctx = createContext({
|
||||
attachments: ref([{
|
||||
id: 'notice-handled-failure',
|
||||
kind: 'shipping_notice' as const,
|
||||
type: 'document' as const,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
parseStatus: 'parsed' as const,
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'orders.eml',
|
||||
fileSize: 100,
|
||||
intakeNo: 'SNI-HANDLED-FAILURE',
|
||||
}]),
|
||||
getParsedIntakeNos: () => ['SNI-HANDLED-FAILURE'],
|
||||
sendMessage: vi.fn(async () => false),
|
||||
rollbackOrderExtractionStarted: rollback,
|
||||
});
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(rollback).toHaveBeenCalledWith(['SNI-HANDLED-FAILURE']);
|
||||
expect(ctx.loadHistory).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -22,6 +22,8 @@ import {
|
||||
import { resolveShippingDecisionFromText, resolveShippingNumericChoice } from './shippingMenu';
|
||||
import { classifyShippingUploadFile } from './shippingUploadPrompt';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
import { createChatMessageAttachmentSnapshots } from '../utils/attachmentCard.utils';
|
||||
import type { SendMessageLifecycleHooks } from '../composables/useChat';
|
||||
import type { StartChatTurnOptions } from '../types/chat-turn.types';
|
||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ChatUploadFileSpec, PendingAttachment, ShippingActionButton } from '../types/shipping.types';
|
||||
@@ -51,8 +53,8 @@ export interface ShippingSendHandlerContext {
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
|
||||
hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void> },
|
||||
) => Promise<void>;
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => Promise<boolean | void>;
|
||||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||||
loadHistory: () => Promise<void>;
|
||||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||||
@@ -71,8 +73,13 @@ export interface ShippingSendHandlerContext {
|
||||
hasSelectedNoticeCandidates?: () => boolean;
|
||||
openShippingDuplicateDialog?: (attachmentId?: string) => void;
|
||||
getParsedIntakeNos?: () => string[];
|
||||
markOrderExtractionStarted?: (intakeNos: string[]) => void;
|
||||
rollbackOrderExtractionStarted?: (intakeNos: string[]) => void;
|
||||
refreshNoticeIntakeStatuses?: () => Promise<void>;
|
||||
clearConsumedNoticeAttachments?: () => void;
|
||||
applyShippingMessageRecovery?: (message: ChatMessage) => Promise<boolean>;
|
||||
applyShippingBatchSnapshot?: (message: ChatMessage) => boolean;
|
||||
syncShippingConversationWorkspace: (options?: { preferLatest?: boolean }) => Promise<boolean>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
shippingSuggestedPrompt: ComputedRef<string>;
|
||||
isShippingShortageQueryIntent: (text: string) => boolean;
|
||||
@@ -211,11 +218,13 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
}
|
||||
const intakeNos = ctx.getParsedIntakeNos?.() || [];
|
||||
if (intakeNos.length) {
|
||||
const userAttachments = createChatMessageAttachmentSnapshots(noticeItems);
|
||||
const query = trimmed || ctx.t('chat.shippingOrderExtractionDefaultPrompt');
|
||||
ctx.shippingAutoFlowRequested.value = false;
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.markOrderExtractionStarted?.(intakeNos);
|
||||
try {
|
||||
await ctx.sendMessage(
|
||||
const sent = await ctx.sendMessage(
|
||||
query,
|
||||
ctx.currentAgentId.value,
|
||||
ctx.selectedKb.value,
|
||||
@@ -225,15 +234,30 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
display_query: query,
|
||||
},
|
||||
{
|
||||
onAssistantMessageFinished: async () => {
|
||||
userAttachments,
|
||||
onAssistantMessageFinished: async (assistantMessage) => {
|
||||
if (ctx.applyShippingMessageRecovery) {
|
||||
await ctx.applyShippingMessageRecovery(assistantMessage);
|
||||
} else {
|
||||
ctx.applyShippingBatchSnapshot?.(assistantMessage);
|
||||
}
|
||||
await ctx.refreshNoticeIntakeStatuses?.();
|
||||
if (!(await ctx.syncShippingConversationWorkspace({ preferLatest: true }))) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
await ctx.syncShippingConversationWorkspace({ preferLatest: true });
|
||||
}
|
||||
ctx.clearConsumedNoticeAttachments?.();
|
||||
await ctx.refreshShippingActions();
|
||||
},
|
||||
},
|
||||
);
|
||||
if (sent === false) {
|
||||
ctx.rollbackOrderExtractionStarted?.(intakeNos);
|
||||
return true;
|
||||
}
|
||||
await ctx.loadHistory();
|
||||
} catch (e: unknown) {
|
||||
ctx.rollbackOrderExtractionStarted?.(intakeNos);
|
||||
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* features/chat/shipping/useShippingNoticeIntakes.spec.ts
|
||||
* 用途:验证订单抽取阶段的轮询与本地即时状态合并规则。
|
||||
* 依赖:Vitest、useShippingNoticeIntakes 纯函数导出。
|
||||
* 逻辑:确保 parsed 不会提前停止 extracting 轮询,且服务端 not_started 不覆盖刚点击发送的本地状态。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
resolveShippingOrderExtractionStatus,
|
||||
shouldPollShippingNoticeIntake,
|
||||
} from './useShippingNoticeIntakes';
|
||||
|
||||
describe('shipping notice order extraction state', () => {
|
||||
it('keeps polling after preprocessing is parsed while order extraction is active', () => {
|
||||
expect(shouldPollShippingNoticeIntake({
|
||||
parseStatus: 'parsed',
|
||||
orderExtractionStatus: 'extracting',
|
||||
})).toBe(true);
|
||||
expect(shouldPollShippingNoticeIntake({
|
||||
parseStatus: 'parsed',
|
||||
orderExtractionStatus: 'completed',
|
||||
})).toBe(false);
|
||||
expect(shouldPollShippingNoticeIntake({
|
||||
parseStatus: 'parsed',
|
||||
orderExtractionStatus: 'failed',
|
||||
})).toBe(false);
|
||||
});
|
||||
|
||||
it('preserves the immediate extracting state until the backend leaves not_started', () => {
|
||||
expect(resolveShippingOrderExtractionStatus('extracting', 'not_started')).toBe('extracting');
|
||||
expect(resolveShippingOrderExtractionStatus('extracting', 'extracting')).toBe('extracting');
|
||||
expect(resolveShippingOrderExtractionStatus('extracting', 'completed')).toBe('completed');
|
||||
expect(resolveShippingOrderExtractionStatus(undefined, 'not_started')).toBe('not_started');
|
||||
});
|
||||
});
|
||||
@@ -32,6 +32,23 @@ export { isShippingNoticeAttachmentParseIncomplete } from './shippingNoticeAttac
|
||||
|
||||
const TERMINAL_PARSE = new Set(['parsed', 'failed', 'parse_failed', 'consumed', 'cancelled', 'expired']);
|
||||
const ACTIVE_PARSE = new Set(['waiting', 'queued', 'parsing', 'created']);
|
||||
const ACTIVE_ORDER_EXTRACTION = new Set(['extracting']);
|
||||
|
||||
/** 判断 Intake 是否仍需轮询上传预处理或订单抽取状态。 */
|
||||
export function shouldPollShippingNoticeIntake(
|
||||
item: Pick<ShippingNoticePendingAttachment, 'parseStatus' | 'orderExtractionStatus'>,
|
||||
): boolean {
|
||||
return !TERMINAL_PARSE.has(item.parseStatus)
|
||||
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase());
|
||||
}
|
||||
|
||||
/** 保留刚点击发送的本地 extracting,直到服务端进入真实抽取状态或返回终态。 */
|
||||
export function resolveShippingOrderExtractionStatus(localStatus?: string, remoteStatus?: string | null): string | undefined {
|
||||
const local = String(localStatus || '').trim().toLowerCase();
|
||||
const remote = String(remoteStatus || '').trim().toLowerCase();
|
||||
if (local === 'extracting' && (!remote || remote === 'not_started')) return 'extracting';
|
||||
return remote || undefined;
|
||||
}
|
||||
|
||||
function mapServerParseStatus(status: string): ShippingNoticePendingAttachment['parseStatus'] {
|
||||
const normalized = String(status || '').trim().toLowerCase();
|
||||
@@ -160,7 +177,8 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
|| item.uploadStatus === 'waiting'
|
||||
|| ACTIVE_PARSE.has(item.parseStatus)
|
||||
|| item.parseStatus === 'queued'
|
||||
|| item.parseStatus === 'parsing',
|
||||
|| item.parseStatus === 'parsing'
|
||||
|| ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase()),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -223,7 +241,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
if (!intakeNos.length) return;
|
||||
if (intakeNos.every((no) => {
|
||||
const item = noticeAttachments.value.find((entry) => entry.intakeNo === no);
|
||||
return item != null && TERMINAL_PARSE.has(item.parseStatus);
|
||||
return item != null && !shouldPollShippingNoticeIntake(item);
|
||||
})) {
|
||||
return;
|
||||
}
|
||||
@@ -255,7 +273,10 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
if (!local) continue;
|
||||
patchAttachment(local.id, {
|
||||
parseStatus: mapServerParseStatus(remote.parse_status),
|
||||
orderExtractionStatus: remote.order_extraction_status || undefined,
|
||||
orderExtractionStatus: resolveShippingOrderExtractionStatus(
|
||||
local.orderExtractionStatus,
|
||||
remote.order_extraction_status,
|
||||
),
|
||||
orderExtractionVersion: remote.order_extraction_version || undefined,
|
||||
parseSummary: (remote.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
|
||||
errorCode: remote.order_extraction_error_code || remote.error_code || undefined,
|
||||
@@ -357,6 +378,32 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
)
|
||||
.map((item) => String(item.intakeNo));
|
||||
|
||||
/** 点击发送后立即展示订单识别阶段,并启动 Intake 状态轮询。 */
|
||||
const markOrderExtractionStarted = (intakeNos: string[]) => {
|
||||
const selected = new Set(intakeNos.map((item) => String(item || '').trim().toUpperCase()).filter(Boolean));
|
||||
for (const attachment of noticeAttachments.value) {
|
||||
if (!attachment.intakeNo || !selected.has(attachment.intakeNo.toUpperCase())) continue;
|
||||
patchAttachment(attachment.id, {
|
||||
orderExtractionStatus: 'extracting',
|
||||
errorCode: undefined,
|
||||
errorMessage: undefined,
|
||||
});
|
||||
}
|
||||
schedulePoll();
|
||||
};
|
||||
|
||||
/** 聊天请求未成功发起时撤销本地即时状态;服务端真实状态由下一次刷新覆盖。 */
|
||||
const rollbackOrderExtractionStarted = (intakeNos: string[]) => {
|
||||
const selected = new Set(intakeNos.map((item) => String(item || '').trim().toUpperCase()).filter(Boolean));
|
||||
for (const attachment of noticeAttachments.value) {
|
||||
if (!attachment.intakeNo || !selected.has(attachment.intakeNo.toUpperCase())) continue;
|
||||
if (attachment.orderExtractionStatus === 'extracting') {
|
||||
patchAttachment(attachment.id, { orderExtractionStatus: 'not_started' });
|
||||
}
|
||||
}
|
||||
schedulePoll();
|
||||
};
|
||||
|
||||
const clearConsumedAttachments = () => {
|
||||
options.attachments.value = options.attachments.value.filter(
|
||||
(item) => item.kind !== 'shipping_notice' || item.parseStatus !== 'consumed',
|
||||
@@ -391,7 +438,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
}));
|
||||
const nonNotice = options.attachments.value.filter((item) => item.kind !== 'shipping_notice');
|
||||
options.attachments.value = [...nonNotice, ...restored];
|
||||
if (restored.some((item) => item.parseStatus === 'queued' || item.parseStatus === 'parsing')) {
|
||||
if (restored.some((item) => shouldPollShippingNoticeIntake(item))) {
|
||||
schedulePoll();
|
||||
}
|
||||
};
|
||||
@@ -486,6 +533,8 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
|
||||
setCandidateSelected,
|
||||
updateCandidateSummary,
|
||||
getParsedIntakeNos,
|
||||
markOrderExtractionStarted,
|
||||
rollbackOrderExtractionStarted,
|
||||
getSelectedCandidateNos,
|
||||
refreshStatuses,
|
||||
clearConsumedAttachments,
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* 逻辑:作为 features/chat 域的类型中枢,向上提供页面编排约束,向下约束消息渲染与交互结构。
|
||||
*/
|
||||
import type { LeaveAgentOption } from './leave.types';
|
||||
import type { ShippingTaskUiState } from './shipping.api.types';
|
||||
import type { ShippingBatchUiState, ShippingTaskUiState } from './shipping.api.types';
|
||||
|
||||
export type { LeaveAgentOption };
|
||||
|
||||
@@ -18,15 +18,66 @@ export interface RetrieverResource {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export type ShippingOrderExtractionStatus = 'extracting' | 'completed' | 'partially_completed' | 'failed';
|
||||
|
||||
export interface ShippingOrderExtractionState {
|
||||
status: ShippingOrderExtractionStatus;
|
||||
phase: 'llm_extraction' | 'result_persisted' | 'failed';
|
||||
message: string;
|
||||
created_count: number;
|
||||
opened_existing_count: number;
|
||||
pending_count: number;
|
||||
non_shipping_count: number;
|
||||
created_with_missing_fields_count: number;
|
||||
batch_no?: string | null;
|
||||
terminal: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 货代消息在实时 SSE 与历史回放之间共享的最小恢复载荷。
|
||||
* 核心逻辑:`open_existing` 终态至少要保留 `task_no`;若已知所属批次或已拿到工作台快照,
|
||||
* 则继续补齐 `batch_no`、`shipping_ui_state`、`shipping_batch_ui_state`,供聊天页恢复右侧工作台。
|
||||
*/
|
||||
export interface ShippingMessageRecoveryPayload extends Record<string, unknown> {
|
||||
task_no?: string;
|
||||
batch_no?: string | null;
|
||||
shipping_ui_state?: ShippingTaskUiState;
|
||||
shipping_batch_ui_state?: ShippingBatchUiState;
|
||||
shipping_order_extraction_state?: ShippingOrderExtractionState;
|
||||
}
|
||||
|
||||
export type ChatMessageAttachmentType = 'image' | 'document' | 'audio' | 'video' | 'custom';
|
||||
export type ChatMessageAttachmentSource = 'local' | 'remote' | 'shipping_notice';
|
||||
|
||||
/**
|
||||
* 已发送消息中的附件快照。
|
||||
* 约束:只保留可展示、可 JSON 序列化的信息,不得包含 File、完整 URL、上传凭据或内部资产编号。
|
||||
readonly id: string;
|
||||
*/
|
||||
export interface ChatMessageAttachment {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly size?: number;
|
||||
readonly extension?: string;
|
||||
readonly type: ChatMessageAttachmentType;
|
||||
readonly source: ChatMessageAttachmentSource;
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
/** 用户提交时固化的附件展示快照;助手消息不使用此字段。 */
|
||||
attachments?: ChatMessageAttachment[];
|
||||
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result' | 'maintenance-device-result';
|
||||
retriever_resources?: RetrieverResource[];
|
||||
attribution_parts?: string[];
|
||||
chat_log_id?: number;
|
||||
/** 文件检核等异步任务批次 ID(按轮问答绑定) */
|
||||
run_id?: number;
|
||||
/**
|
||||
* 结构化回放载荷。
|
||||
* 约束:货代消息需兼容 `ShippingMessageRecoveryPayload`,保证历史刷新后仍可恢复任务锚点与批次工作台。
|
||||
*/
|
||||
payload?: unknown;
|
||||
local_id?: string;
|
||||
local_only?: boolean;
|
||||
@@ -39,6 +90,8 @@ export interface ChatMessage {
|
||||
source_code?: string;
|
||||
}>;
|
||||
shipping_ui_state?: ShippingTaskUiState;
|
||||
/** 点击发送后的 Intake 级订单识别生命周期;终态同时持久化在 payload 供历史回放。 */
|
||||
shipping_order_extraction_state?: ShippingOrderExtractionState;
|
||||
shipping_actions_used?: boolean;
|
||||
/** 流式对话是否因网络/上游中断而附带错误提示 */
|
||||
stream_error?: boolean;
|
||||
|
||||
@@ -23,7 +23,7 @@ export interface ShippingInventorySourceCandidate {
|
||||
display_name?: string | null;
|
||||
site_id?: string | null;
|
||||
warehouse_id?: string | null;
|
||||
source_type?: string | null;
|
||||
connector_type?: string | null;
|
||||
match_score?: number | null;
|
||||
matched_by?: string | null;
|
||||
}
|
||||
@@ -58,6 +58,9 @@ export interface ShippingInventorySnapshot {
|
||||
export interface ShippingTaskSummary {
|
||||
id: number;
|
||||
task_no: string;
|
||||
shipping_case_id?: number | null;
|
||||
case_no?: string | null;
|
||||
business_no?: string | null;
|
||||
batch_no?: string | null;
|
||||
source_type: string;
|
||||
source_file_name?: string | null;
|
||||
@@ -65,6 +68,11 @@ export interface ShippingTaskSummary {
|
||||
batch_index?: number | null;
|
||||
batch_total?: number | null;
|
||||
customer_name?: string | null;
|
||||
customer_id?: number | null;
|
||||
customer_resolution_status?: string | null;
|
||||
customer_resolution_method?: string | null;
|
||||
customer_name_snapshot?: string | null;
|
||||
customer_short_code_snapshot?: string | null;
|
||||
current_step?: string | null;
|
||||
process_status: string;
|
||||
review_status?: string | null;
|
||||
@@ -91,7 +99,7 @@ export interface ShippingTaskSummary {
|
||||
destination_country?: string | null;
|
||||
warehouse_hint?: string | null;
|
||||
inventory_source_code?: string | null;
|
||||
inventory_source_type?: string | null;
|
||||
inventory_connector_type?: string | null;
|
||||
inventory_site_id?: string | null;
|
||||
inventory_warehouse_id?: string | null;
|
||||
inventory_source_status?: InventorySourceStatus | null;
|
||||
@@ -169,6 +177,8 @@ export interface ShippingNoticeHeader {
|
||||
export interface ShippingNoticeLine {
|
||||
sku: string;
|
||||
reservation_id?: string | null;
|
||||
/** 可选库存路由线索,不代表任务通知来源或已确认的库存连接器类型。 */
|
||||
source_type?: string | null;
|
||||
qty: number;
|
||||
required_date?: string | null;
|
||||
uom?: string | null;
|
||||
@@ -189,6 +199,11 @@ export interface ShippingShortageSummary {
|
||||
}
|
||||
|
||||
export interface ShippingTaskDetail extends ShippingTaskSummary {
|
||||
customer_id?: number | null;
|
||||
customer_resolution_status?: string | null;
|
||||
customer_resolution_method?: string | null;
|
||||
customer_name_snapshot?: string | null;
|
||||
customer_short_code_snapshot?: string | null;
|
||||
customer_code?: string | null;
|
||||
ship_to?: string | null;
|
||||
po_number?: string | null;
|
||||
@@ -205,6 +220,12 @@ export interface ShippingTaskDetail extends ShippingTaskSummary {
|
||||
ui_state?: ShippingTaskUiState;
|
||||
}
|
||||
|
||||
export interface ShippingCustomerOption {
|
||||
id: number;
|
||||
standard_name: string;
|
||||
short_code: string;
|
||||
}
|
||||
|
||||
export interface ShippingChatAction {
|
||||
id: string;
|
||||
label: string;
|
||||
@@ -241,6 +262,21 @@ export interface ShippingTaskUiState {
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `shipping_ui_state` SSE 与历史回放共用的恢复契约。
|
||||
* 核心逻辑:任务锚点 `task_no` 是 open_existing 场景恢复聊天工作台的最小必需字段;
|
||||
* 若后端能解析到所属批次或完整批次快照,应继续补齐 `batch_no`、`batch_ui_state` 与 `ui_state`。
|
||||
*/
|
||||
export interface ShippingUiStateEventPayload {
|
||||
event?: 'shipping_ui_state';
|
||||
conversation_id?: string;
|
||||
task_no?: string | null;
|
||||
batch_no?: string | null;
|
||||
ui_state?: ShippingTaskUiState;
|
||||
batch_ui_state?: ShippingBatchUiState;
|
||||
source?: string;
|
||||
}
|
||||
|
||||
export interface ShippingBatchSummary {
|
||||
id: number;
|
||||
batch_no: string;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/chat/types/shipping.types.ts
|
||||
* 用途:发货通知聊天流程相关 TypeScript 类型定义。
|
||||
* 用途:聊天附件与发货通知流程相关 TypeScript 类型定义。
|
||||
* 依赖:无(纯类型模块)。
|
||||
* 逻辑:shipping/* composable 与 Chat 消息组件统一引用本文件类型。
|
||||
* 逻辑:附件 composable、shipping/* composable 与 Chat 消息组件统一引用本文件类型。
|
||||
*/
|
||||
|
||||
export type ShippingActionVariant = 'primary' | 'secondary' | 'danger';
|
||||
@@ -11,7 +11,13 @@ export type ShippingMenuAction = 'upload' | 'paste' | 'retry_rpa' | 'confirm' |
|
||||
|
||||
export type ChatUploadFileType = 'image' | 'document' | 'audio' | 'video' | 'custom';
|
||||
|
||||
export type ShippingNoticeUploadStatus = 'waiting' | 'uploading' | 'uploaded' | 'failed';
|
||||
/** 附件卡片统一展示状态,由各附件类型的真实业务字段映射得到。 */
|
||||
export type AttachmentUiStatus = 'pending' | 'uploading' | 'processing' | 'attention' | 'ready' | 'failed';
|
||||
|
||||
/** 普通本地附件的上传状态;语义与发货通知上传状态保持一致。 */
|
||||
export type ChatAttachmentUploadStatus = 'waiting' | 'uploading' | 'uploaded' | 'failed';
|
||||
|
||||
export type ShippingNoticeUploadStatus = ChatAttachmentUploadStatus;
|
||||
export type ShippingNoticeParseStatus =
|
||||
| 'waiting'
|
||||
| 'queued'
|
||||
@@ -139,10 +145,30 @@ export type ShippingNoticePendingAttachment = {
|
||||
candidates?: ShippingNoticeCandidate[];
|
||||
};
|
||||
|
||||
/** 普通本地附件:选择后等待发送,实际上传由发送流程触发。 */
|
||||
export interface ChatLocalPendingAttachment {
|
||||
id: string;
|
||||
kind: 'local';
|
||||
file: File;
|
||||
type: ChatUploadFileType;
|
||||
uploadStatus: ChatAttachmentUploadStatus;
|
||||
uploadProgress: number;
|
||||
uploadFileId?: string;
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
/** 远程 URL 附件:发送时直接传 URL,不伪造本地文件大小或上传进度。 */
|
||||
export interface ChatRemotePendingAttachment {
|
||||
id: string;
|
||||
kind: 'remote';
|
||||
url: string;
|
||||
type: ChatUploadFileType;
|
||||
}
|
||||
|
||||
/** 待发送附件(本地文件、远程 URL 或货代通知预解析) */
|
||||
export type PendingAttachment =
|
||||
| { id: string; kind: 'local'; file: File; type: ChatUploadFileType }
|
||||
| { id: string; kind: 'remote'; url: string; type: ChatUploadFileType }
|
||||
| ChatLocalPendingAttachment
|
||||
| ChatRemotePendingAttachment
|
||||
| ShippingNoticePendingAttachment;
|
||||
|
||||
export type ChatUploadFileSpec =
|
||||
@@ -179,6 +205,8 @@ export interface ShippingParseReviewPayload {
|
||||
lines: Array<{
|
||||
sku: string;
|
||||
reservation_id?: string | null;
|
||||
/** 可选库存路由线索;与 ShippingTask.source_type 通知来源无关。 */
|
||||
source_type?: string | null;
|
||||
qty: number;
|
||||
required_date?: string | null;
|
||||
uom?: string | null;
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* features/chat/utils/attachmentCard.utils.spec.ts
|
||||
* 用途:验证附件卡片名称、大小、状态与删除约束的纯函数映射。
|
||||
* 依赖:Vitest、attachmentCard.utils。
|
||||
* 逻辑:用普通附件、远程 URL 和发货通知覆盖用户可见的关键状态分支。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { PendingAttachment, ShippingNoticePendingAttachment } from '../types/shipping.types';
|
||||
import {
|
||||
createChatMessageAttachmentSnapshots,
|
||||
formatAttachmentSize,
|
||||
getAttachmentCardStatus,
|
||||
getAttachmentExtension,
|
||||
getAttachmentName,
|
||||
getAttachmentSize,
|
||||
isAttachmentRemoveDisabled,
|
||||
} from './attachmentCard.utils';
|
||||
|
||||
/** 创建普通本地附件夹具。 */
|
||||
function localAttachment(status: 'waiting' | 'uploading' | 'uploaded' | 'failed' = 'waiting'): PendingAttachment {
|
||||
return {
|
||||
id: 'local-1',
|
||||
kind: 'local',
|
||||
file: new File(['pdf'], 'purchase-order.pdf', { type: 'application/pdf' }),
|
||||
type: 'document',
|
||||
uploadStatus: status,
|
||||
uploadProgress: status === 'uploaded' ? 100 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** 创建发货通知附件夹具。 */
|
||||
function shippingAttachment(
|
||||
patch: Partial<ShippingNoticePendingAttachment> = {},
|
||||
): ShippingNoticePendingAttachment {
|
||||
return {
|
||||
id: 'shipping-1',
|
||||
kind: 'shipping_notice',
|
||||
type: 'document',
|
||||
uploadStatus: 'uploaded',
|
||||
parseStatus: 'parsed',
|
||||
uploadProgress: 100,
|
||||
originalFilename: 'notice.eml',
|
||||
fileSize: 2048,
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
describe('attachment card utils', () => {
|
||||
it('formats real file sizes without inventing remote URL sizes', () => {
|
||||
expect(formatAttachmentSize(0)).toBe('0 B');
|
||||
expect(formatAttachmentSize(144.46 * 1024)).toBe('144.46 KB');
|
||||
expect(formatAttachmentSize(2.31 * 1024 * 1024)).toBe('2.31 MB');
|
||||
expect(formatAttachmentSize(undefined)).toBe('');
|
||||
|
||||
const remote: PendingAttachment = {
|
||||
id: 'remote-1', kind: 'remote', url: 'https://example.com/files/report.xlsx', type: 'document',
|
||||
};
|
||||
expect(getAttachmentName(remote)).toBe('report.xlsx');
|
||||
expect(getAttachmentExtension(remote)).toBe('XLSX');
|
||||
expect(getAttachmentSize(remote)).toBe('');
|
||||
});
|
||||
|
||||
it('maps local upload lifecycle and disables removal only while uploading', () => {
|
||||
expect(getAttachmentCardStatus(localAttachment('waiting')).state).toBe('pending');
|
||||
expect(getAttachmentCardStatus(localAttachment('uploading')).state).toBe('uploading');
|
||||
expect(getAttachmentCardStatus(localAttachment('uploaded')).state).toBe('ready');
|
||||
expect(getAttachmentCardStatus(localAttachment('failed')).state).toBe('failed');
|
||||
expect(isAttachmentRemoveDisabled(localAttachment('uploading'))).toBe(true);
|
||||
expect(isAttachmentRemoveDisabled(localAttachment('failed'))).toBe(false);
|
||||
});
|
||||
|
||||
it('preserves shipping parsing, failure and duplicate attention states', () => {
|
||||
expect(getAttachmentCardStatus(shippingAttachment({ parseStatus: 'parsing' })).state).toBe('processing');
|
||||
expect(getAttachmentCardStatus(shippingAttachment({ parseStatus: 'failed' }))).toEqual({
|
||||
state: 'failed', labelKey: 'chat.attachment.parseFailed',
|
||||
});
|
||||
expect(getAttachmentCardStatus(shippingAttachment({
|
||||
duplicate: {
|
||||
status: 'possible_duplicate',
|
||||
blocking: true,
|
||||
fingerprintStrength: 'strong',
|
||||
matches: [],
|
||||
allowedActions: [],
|
||||
},
|
||||
})).state).toBe('attention');
|
||||
expect(getAttachmentCardStatus(shippingAttachment()).state).toBe('ready');
|
||||
});
|
||||
|
||||
it('shows the order extraction lifecycle separately from attachment parsing', () => {
|
||||
expect(getAttachmentCardStatus(shippingAttachment({ orderExtractionStatus: 'extracting' }))).toEqual({
|
||||
state: 'processing', labelKey: 'chat.shippingOrderExtractionProcessing',
|
||||
});
|
||||
expect(getAttachmentCardStatus(shippingAttachment({ orderExtractionStatus: 'partially_completed' }))).toEqual({
|
||||
state: 'attention', labelKey: 'chat.shippingOrderExtractionPartiallyCompleted',
|
||||
});
|
||||
expect(getAttachmentCardStatus(shippingAttachment({ orderExtractionStatus: 'completed' }))).toEqual({
|
||||
state: 'ready', labelKey: 'chat.shippingOrderExtractionCompleted',
|
||||
});
|
||||
expect(getAttachmentCardStatus(shippingAttachment({ orderExtractionStatus: 'failed' }))).toEqual({
|
||||
state: 'failed', labelKey: 'chat.shippingOrderExtractionFailed',
|
||||
});
|
||||
});
|
||||
|
||||
it('creates ordered JSON-safe snapshots for local, remote and shipping attachments', () => {
|
||||
const local = localAttachment('uploaded');
|
||||
if (local.kind === 'local') {
|
||||
local.uploadFileId = 'internal-upload-id';
|
||||
local.errorMessage = 'internal error';
|
||||
}
|
||||
const remote: PendingAttachment = {
|
||||
id: 'remote-secret',
|
||||
kind: 'remote',
|
||||
url: 'https://example.com/files/report.xlsx?signature=secret-token',
|
||||
type: 'document',
|
||||
};
|
||||
const shipping = shippingAttachment({
|
||||
assetNo: 'ASSET-INTERNAL',
|
||||
intakeNo: 'INTAKE-INTERNAL',
|
||||
originalFilename: 'notice.EML',
|
||||
fileSize: 229_877,
|
||||
});
|
||||
|
||||
const snapshots = createChatMessageAttachmentSnapshots([local, remote, shipping]);
|
||||
|
||||
expect(snapshots).toEqual([
|
||||
{
|
||||
id: 'local-1',
|
||||
name: 'purchase-order.pdf',
|
||||
size: 3,
|
||||
extension: 'pdf',
|
||||
type: 'document',
|
||||
source: 'local',
|
||||
},
|
||||
{
|
||||
id: 'remote-secret',
|
||||
name: 'report.xlsx',
|
||||
extension: 'xlsx',
|
||||
type: 'document',
|
||||
source: 'remote',
|
||||
},
|
||||
{
|
||||
id: 'shipping-1',
|
||||
name: 'notice.EML',
|
||||
size: 229_877,
|
||||
extension: 'eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
},
|
||||
]);
|
||||
const serialized = JSON.stringify(snapshots);
|
||||
expect(serialized).not.toContain('secret-token');
|
||||
expect(serialized).not.toContain('internal-upload-id');
|
||||
expect(serialized).not.toContain('ASSET-INTERNAL');
|
||||
expect(serialized).not.toContain('INTAKE-INTERNAL');
|
||||
|
||||
if (local.kind === 'local') local.file = new File(['changed'], 'changed.pdf');
|
||||
shipping.originalFilename = 'changed.eml';
|
||||
expect(snapshots[0]?.name).toBe('purchase-order.pdf');
|
||||
expect(snapshots[2]?.name).toBe('notice.EML');
|
||||
});
|
||||
|
||||
it('uses a safe fallback for remote URLs without a filename and never invents size', () => {
|
||||
const snapshots = createChatMessageAttachmentSnapshots([{
|
||||
id: 'remote-root',
|
||||
kind: 'remote',
|
||||
url: 'https://example.com/?signature=hidden',
|
||||
type: 'custom',
|
||||
}]);
|
||||
|
||||
expect(snapshots).toEqual([{
|
||||
id: 'remote-root',
|
||||
name: 'remote-file',
|
||||
type: 'custom',
|
||||
source: 'remote',
|
||||
}]);
|
||||
});
|
||||
|
||||
it('strips path fragments and control characters from snapshot names', () => {
|
||||
const snapshots = createChatMessageAttachmentSnapshots([
|
||||
shippingAttachment({ originalFilename: 'C:\\mail\\notice\u0000.eml' }),
|
||||
]);
|
||||
|
||||
expect(snapshots[0]).toMatchObject({
|
||||
id: 'shipping-1',
|
||||
name: 'notice.eml',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* features/chat/utils/attachmentCard.utils.ts
|
||||
* 用途:统一计算聊天附件卡片的名称、大小、扩展名、状态、删除约束与已发送快照。
|
||||
* 依赖:chat.types 的消息附件契约、shipping.types 的待发送附件联合类型。
|
||||
* 逻辑:ChatInputBar 只负责渲染;发送层通过快照函数把可变待发送附件固化为安全展示数据。
|
||||
*/
|
||||
import type { ChatMessageAttachment } from '../types/chat.types';
|
||||
import type { AttachmentUiStatus, PendingAttachment } from '../types/shipping.types';
|
||||
|
||||
export interface AttachmentCardStatus {
|
||||
state: AttachmentUiStatus;
|
||||
labelKey: string;
|
||||
}
|
||||
|
||||
/** 获取附件卡片文件名;URL 优先展示路径末段。 */
|
||||
export function getAttachmentName(attachment: PendingAttachment): string {
|
||||
if (attachment.kind === 'local') return attachment.file.name;
|
||||
if (attachment.kind === 'shipping_notice') return attachment.originalFilename;
|
||||
try {
|
||||
const pathname = new URL(attachment.url).pathname;
|
||||
return decodeURIComponent(pathname.split('/').filter(Boolean).pop() || attachment.url);
|
||||
} catch {
|
||||
return attachment.url;
|
||||
}
|
||||
}
|
||||
|
||||
/** 将字节数格式化为紧凑的 B/KB/MB/GB 文本;未知大小返回空字符串。 */
|
||||
export function formatAttachmentSize(bytes?: number): string {
|
||||
if (!Number.isFinite(bytes) || bytes === undefined || bytes < 0) return '';
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
const units = ['KB', 'MB', 'GB'];
|
||||
let value = bytes / 1024;
|
||||
let unitIndex = 0;
|
||||
while (value >= 1024 && unitIndex < units.length - 1) {
|
||||
value /= 1024;
|
||||
unitIndex += 1;
|
||||
}
|
||||
const formatted = value.toFixed(2).replace(/\.00$/, '').replace(/(\.\d)0$/, '$1');
|
||||
return `${formatted} ${units[unitIndex]}`;
|
||||
}
|
||||
|
||||
/** 根据附件来源返回真实文件大小;远程 URL 不伪造大小。 */
|
||||
export function getAttachmentSize(attachment: PendingAttachment): string {
|
||||
if (attachment.kind === 'local') return formatAttachmentSize(attachment.file.size);
|
||||
if (attachment.kind === 'shipping_notice') return formatAttachmentSize(attachment.fileSize);
|
||||
return '';
|
||||
}
|
||||
|
||||
/** 根据文件名扩展名生成卡片类型徽标。 */
|
||||
export function getAttachmentExtension(attachment: PendingAttachment): string {
|
||||
const name = getAttachmentName(attachment);
|
||||
const extension = name.includes('.') ? name.split('.').pop()?.toUpperCase() : '';
|
||||
if (extension && extension.length <= 5) return extension;
|
||||
if (attachment.kind === 'remote') return 'URL';
|
||||
return attachment.type.toUpperCase().slice(0, 5);
|
||||
}
|
||||
|
||||
/** 将普通上传状态与发货通知上传/解析状态映射为统一卡片状态。 */
|
||||
export function getAttachmentCardStatus(attachment: PendingAttachment): AttachmentCardStatus {
|
||||
if (attachment.kind === 'remote') return { state: 'ready', labelKey: 'chat.attachment.ready' };
|
||||
if (attachment.kind === 'local') {
|
||||
if (attachment.uploadStatus === 'uploading') return { state: 'uploading', labelKey: 'chat.attachment.uploading' };
|
||||
if (attachment.uploadStatus === 'uploaded') return { state: 'ready', labelKey: 'chat.attachment.ready' };
|
||||
if (attachment.uploadStatus === 'failed') return { state: 'failed', labelKey: 'chat.attachment.uploadFailed' };
|
||||
return { state: 'pending', labelKey: 'chat.attachment.pending' };
|
||||
}
|
||||
if (attachment.uploadStatus === 'uploading') return { state: 'uploading', labelKey: 'chat.attachment.uploading' };
|
||||
if (attachment.uploadStatus === 'failed') return { state: 'failed', labelKey: 'chat.attachment.uploadFailed' };
|
||||
if (attachment.parseStatus === 'queued' || attachment.parseStatus === 'parsing') {
|
||||
return { state: 'processing', labelKey: 'chat.attachment.processing' };
|
||||
}
|
||||
if (attachment.parseStatus === 'failed') return { state: 'failed', labelKey: 'chat.attachment.parseFailed' };
|
||||
const extractionStatus = String(attachment.orderExtractionStatus || '').trim().toLowerCase();
|
||||
if (extractionStatus === 'extracting') {
|
||||
return { state: 'processing', labelKey: 'chat.shippingOrderExtractionProcessing' };
|
||||
}
|
||||
if (extractionStatus === 'partially_completed') {
|
||||
return { state: 'attention', labelKey: 'chat.shippingOrderExtractionPartiallyCompleted' };
|
||||
}
|
||||
if (extractionStatus === 'failed') {
|
||||
return { state: 'failed', labelKey: 'chat.shippingOrderExtractionFailed' };
|
||||
}
|
||||
if (extractionStatus === 'completed') {
|
||||
return { state: 'ready', labelKey: 'chat.shippingOrderExtractionCompleted' };
|
||||
}
|
||||
if (attachment.parseStatus === 'parsed' && !attachment.duplicateResolution?.action) {
|
||||
if (attachment.duplicate?.blocking) {
|
||||
return { state: 'attention', labelKey: 'chat.shippingNoticeDuplicateBlockingBadge' };
|
||||
}
|
||||
if (attachment.duplicate?.status === 'possible_duplicate') {
|
||||
return { state: 'attention', labelKey: 'chat.shippingNoticeDuplicatePossibleBadge' };
|
||||
}
|
||||
}
|
||||
if (attachment.parseStatus === 'parsed' || attachment.parseStatus === 'consumed') {
|
||||
return { state: 'ready', labelKey: 'chat.attachment.ready' };
|
||||
}
|
||||
return { state: 'pending', labelKey: 'chat.attachment.pending' };
|
||||
}
|
||||
|
||||
/** 上传中的普通附件没有取消接口,因此禁止删除直至请求结束。 */
|
||||
export function isAttachmentRemoveDisabled(attachment: PendingAttachment): boolean {
|
||||
return attachment.kind === 'local' && attachment.uploadStatus === 'uploading';
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取可持久化的安全文件名,避免远程 URL 查询参数或临时签名进入聊天记录。
|
||||
* @param attachment - 当前待发送附件
|
||||
* @returns 最长 255 字符的文件名;远程 URL 无有效末段时返回 remote-file
|
||||
*/
|
||||
function getSnapshotAttachmentName(attachment: PendingAttachment): string {
|
||||
let name = '';
|
||||
if (attachment.kind === 'local') {
|
||||
name = attachment.file.name;
|
||||
} else if (attachment.kind === 'shipping_notice') {
|
||||
name = attachment.originalFilename;
|
||||
} else {
|
||||
try {
|
||||
const pathname = new URL(attachment.url).pathname;
|
||||
name = decodeURIComponent(pathname.split('/').filter(Boolean).pop() || '');
|
||||
} catch {
|
||||
name = '';
|
||||
}
|
||||
if (!name) name = 'remote-file';
|
||||
}
|
||||
const basename = String(name || 'attachment')
|
||||
.split(/[\\/]/)
|
||||
.filter(Boolean)
|
||||
.pop() || 'attachment';
|
||||
return basename.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 255) || 'attachment';
|
||||
}
|
||||
|
||||
/**
|
||||
* 鐢熸垚鍙寔涔呭寲鐨勯檮浠跺揩鐓?ID锛屼紭鍏堝鐢ㄥ緟鍙戦€侀檮浠剁殑鏈湴鏍囪瘑锛岄伩鍏嶅紩鍏?File 鎴栧唴閮ㄨ祫浜ф寚閽堛€?
|
||||
*/
|
||||
function getSnapshotAttachmentId(attachment: PendingAttachment, index: number): string {
|
||||
const candidate = String(attachment.id || '')
|
||||
.replace(/[\u0000-\u001f\u007f]/g, '')
|
||||
.trim()
|
||||
.slice(0, 128);
|
||||
return candidate || `attachment-${index + 1}`;
|
||||
}
|
||||
|
||||
/** 从安全文件名提取小写扩展名;无明确扩展名时不制造类型后缀。 */
|
||||
function getSnapshotAttachmentExtension(name: string): string | undefined {
|
||||
const dotIndex = name.lastIndexOf('.');
|
||||
if (dotIndex <= 0 || dotIndex === name.length - 1) return undefined;
|
||||
const extension = name.slice(dotIndex + 1).trim().toLowerCase();
|
||||
return extension && extension.length <= 16 ? extension : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把待发送附件固化为已发送消息快照。
|
||||
* 核心逻辑:创建全新纯对象并仅复制展示白名单;远程附件不保存 URL 或伪造大小。
|
||||
* @param attachments - 按用户选择顺序排列的待发送附件
|
||||
* @returns 可直接 JSON 序列化、顺序不变的消息附件快照
|
||||
*/
|
||||
export function createChatMessageAttachmentSnapshots(
|
||||
attachments: readonly PendingAttachment[],
|
||||
): ChatMessageAttachment[] {
|
||||
return attachments.map((attachment, index) => {
|
||||
const name = getSnapshotAttachmentName(attachment);
|
||||
const size = attachment.kind === 'local'
|
||||
? attachment.file.size
|
||||
: attachment.kind === 'shipping_notice'
|
||||
? attachment.fileSize
|
||||
: undefined;
|
||||
const extension = getSnapshotAttachmentExtension(name);
|
||||
return {
|
||||
id: getSnapshotAttachmentId(attachment, index),
|
||||
name,
|
||||
type: attachment.type,
|
||||
source: attachment.kind,
|
||||
...(extension ? { extension } : {}),
|
||||
...(Number.isFinite(size) && size !== undefined && size >= 0
|
||||
? { size: Math.round(size) }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -1,28 +1,34 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/workspace/components/WorkspaceSidebar.vue
|
||||
* 工作台左侧导航:子路由链接、返回聊天与退出登录。
|
||||
* 工作台左侧导航:业务一级/二级目录、返回聊天与退出登录。
|
||||
*/
|
||||
import { inject } from 'vue';
|
||||
import { computed, inject, ref, watch } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
import {
|
||||
LayoutGrid, Bot, FileText, User, LogOut, Edit, Megaphone, Clock, Package, PanelLeftClose, PanelLeftOpen,
|
||||
ChevronDown, ChevronRight, ContactRound, ListChecks,
|
||||
} from 'lucide-vue-next';
|
||||
import { WORKSPACE_PATHS } from '../constants/routes';
|
||||
import { WORKSPACE_KEY } from '../composables/workspace.context';
|
||||
|
||||
defineProps<{
|
||||
const props = defineProps<{
|
||||
collapsed?: boolean;
|
||||
}>();
|
||||
|
||||
const ws = inject(WORKSPACE_KEY)! as any;
|
||||
const route = useRoute();
|
||||
const shippingRouteNames = ['workspace-shipping-customers', 'workspace-shipping-tasks'] as const;
|
||||
const shippingExpanded = ref(false);
|
||||
const isAdmin = computed(() => String(ws.currentUser?.role || '').trim().toLowerCase() === 'admin');
|
||||
|
||||
const linkItems = [
|
||||
const primaryLinkItems = [
|
||||
{ path: WORKSPACE_PATHS.profile, labelKey: 'workspace.nav.profile', icon: User, match: ['workspace-profile'] },
|
||||
{ path: WORKSPACE_PATHS.applications, labelKey: 'workspace.nav.applications', icon: LayoutGrid, match: ['workspace-applications'] },
|
||||
{ path: WORKSPACE_PATHS.scheduleRuns, labelKey: 'workspace.nav.scheduleRuns', icon: Clock, match: ['workspace-schedule-runs'] },
|
||||
{ path: WORKSPACE_PATHS.shippingNotice, labelKey: 'workspace.nav.shippingNotice', icon: Package, match: ['workspace-shipping-notice'] },
|
||||
] as const;
|
||||
|
||||
const secondaryLinkItems = [
|
||||
{ path: WORKSPACE_PATHS.feedback, labelKey: 'workspace.nav.feedback', icon: Edit, match: ['workspace-feedback'] },
|
||||
{ path: WORKSPACE_PATHS.updates, labelKey: 'workspace.nav.updates', icon: Megaphone, match: ['workspace-updates'] },
|
||||
] as const;
|
||||
@@ -30,6 +36,26 @@ const linkItems = [
|
||||
function isActive(match: readonly string[]) {
|
||||
return match.includes(String(route.name || ''));
|
||||
}
|
||||
|
||||
/** 当前路由进入货代子页面时自动展开一级菜单,保证激活项可见。 */
|
||||
watch(
|
||||
() => route.name,
|
||||
(routeName) => {
|
||||
if (shippingRouteNames.includes(String(routeName || '') as typeof shippingRouteNames[number])) {
|
||||
shippingExpanded.value = true;
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/** 展开或收起货代发货目录;侧栏折叠时图标直接进入发货任务。 */
|
||||
const toggleShippingMenu = (): void => {
|
||||
if (props.collapsed) {
|
||||
void ws.router.push(WORKSPACE_PATHS.shippingNoticeTasks);
|
||||
return;
|
||||
}
|
||||
shippingExpanded.value = !shippingExpanded.value;
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -75,7 +101,56 @@ function isActive(match: readonly string[]) {
|
||||
<div class="flex-1 py-4">
|
||||
<nav class="space-y-2">
|
||||
<RouterLink
|
||||
v-for="item in linkItems"
|
||||
v-for="item in primaryLinkItems"
|
||||
:key="item.path"
|
||||
:to="item.path"
|
||||
class="ws-nav-btn"
|
||||
:class="[
|
||||
{ 'ws-nav-btn--active': isActive(item.match) },
|
||||
collapsed ? 'justify-center px-0' : '',
|
||||
]"
|
||||
:title="$t(item.labelKey)"
|
||||
>
|
||||
<component :is="item.icon" class="h-[18px] w-[18px]" />
|
||||
<span v-if="!collapsed">{{ $t(item.labelKey) }}</span>
|
||||
</RouterLink>
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
class="ws-nav-btn w-full"
|
||||
:class="[
|
||||
{ 'ws-nav-btn--active': isActive(shippingRouteNames) },
|
||||
collapsed ? 'justify-center px-0' : '',
|
||||
]"
|
||||
:title="$t('workspace.nav.shippingNotice')"
|
||||
@click="toggleShippingMenu"
|
||||
>
|
||||
<Package class="h-[18px] w-[18px]" />
|
||||
<span v-if="!collapsed" class="flex-1">{{ $t('workspace.nav.shippingNotice') }}</span>
|
||||
<component v-if="!collapsed" :is="shippingExpanded ? ChevronDown : ChevronRight" class="h-4 w-4" />
|
||||
</button>
|
||||
<div v-if="!collapsed && shippingExpanded" class="mt-1 space-y-1 pl-5">
|
||||
<RouterLink
|
||||
v-if="isAdmin"
|
||||
:to="WORKSPACE_PATHS.shippingNoticeCustomers"
|
||||
class="ws-nav-btn py-2.5 text-[13px]"
|
||||
:class="{ 'ws-nav-btn--active': isActive(['workspace-shipping-customers']) }"
|
||||
>
|
||||
<ContactRound class="h-4 w-4" />
|
||||
<span>{{ $t('workspace.nav.shippingCustomers') }}</span>
|
||||
</RouterLink>
|
||||
<RouterLink
|
||||
:to="WORKSPACE_PATHS.shippingNoticeTasks"
|
||||
class="ws-nav-btn py-2.5 text-[13px]"
|
||||
:class="{ 'ws-nav-btn--active': isActive(['workspace-shipping-tasks']) }"
|
||||
>
|
||||
<ListChecks class="h-4 w-4" />
|
||||
<span>{{ $t('workspace.nav.shippingTasks') }}</span>
|
||||
</RouterLink>
|
||||
</div>
|
||||
</div>
|
||||
<RouterLink
|
||||
v-for="item in secondaryLinkItems"
|
||||
:key="item.path"
|
||||
:to="item.path"
|
||||
class="ws-nav-btn"
|
||||
|
||||
@@ -19,7 +19,8 @@ const ROUTE_NAME_TO_SIDEBAR: Record<string, WorkspaceSidebarItem> = {
|
||||
'workspace-knowledge-base': 'knowledge_base',
|
||||
'workspace-knowledge-base-group': 'knowledge_base',
|
||||
'workspace-schedule-runs': 'schedule_runs',
|
||||
'workspace-shipping-notice': 'shipping_notice',
|
||||
'workspace-shipping-customers': 'shipping_notice',
|
||||
'workspace-shipping-tasks': 'shipping_notice',
|
||||
'workspace-feedback': 'feedback',
|
||||
'workspace-history': 'history',
|
||||
};
|
||||
|
||||
@@ -9,7 +9,9 @@ export const WORKSPACE_PATHS = {
|
||||
updates: '/workspace/updates',
|
||||
knowledgeBase: '/workspace/knowledge-base',
|
||||
scheduleRuns: '/workspace/schedule-runs',
|
||||
shippingNotice: '/workspace/shipping-notice',
|
||||
shippingNotice: '/workspace/shipping-notice/tasks',
|
||||
shippingNoticeCustomers: '/workspace/shipping-notice/customers',
|
||||
shippingNoticeTasks: '/workspace/shipping-notice/tasks',
|
||||
feedback: '/workspace/feedback',
|
||||
history: '/workspace/history',
|
||||
} as const;
|
||||
|
||||
Reference in new issue
Block a user