feat(shipping-notice): 新增临时库存管理功能,支持创建会话、获取分析结果及字段映射建议

This commit is contained in:
hugo committed 2026-07-18 11:41:02 +08:00
1 parent 46eb63f5bb
commit e9bdd81f1a
320 files changed
+28361 -10487

No files matched your search

@@ -0,0 +1,180 @@
/**
* features/shipping-notice/api/customer-master.api.ts
* 用途:货代客户主数据的管理 API,归属货代发货业务域。
* 依赖:requestJson、认证请求头、客户主数据类型。
* 逻辑:页面位于货代发货工作台,但所有写操作仍调用管理员受保护的后端契约。
*/
import { getAuthHeaders } from '@/shared/utils/auth';
import { BusinessError, requestJson, resolveLocalizedErrorMessage } from '@/shared/api/client';
import type {
ShippingCustomerIdentifier,
ShippingCustomerImportBatch,
ShippingCustomerLifecycleImpact,
ShippingCustomerLifecycleTimeline,
DeleteShippingCustomerRequest,
DeleteShippingCustomerResult,
MergeShippingCustomerRequest,
MergeShippingCustomerResult,
ShippingCustomerMergeImpact,
ShippingCustomerPage,
ShippingCustomerRow,
ShippingCustomerShadowItem,
ShippingCustomerShadowReport,
ShippingIdentifierFormState,
} from '../types/customer-master.types';
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
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 getShippingCustomerLifecycleImpact = (id: number) =>
requestJson<ShippingCustomerLifecycleImpact>(`/api/admin/shipping-customers/${id}/lifecycle-impact`, auth());
/** 查询客户创建、变更、证据及归并的不可变治理时间线。 */
export const getShippingCustomerLifecycleTimeline = (id: number) =>
requestJson<ShippingCustomerLifecycleTimeline>(`/api/admin/shipping-customers/${id}/lifecycle-timeline`, auth());
/** 受控删除误建客户;服务端在提交时重新检查全部生命周期阻断引用。 */
export const deleteShippingCustomer = (id: number, payload: DeleteShippingCustomerRequest) =>
requestJson<DeleteShippingCustomerResult>(`/api/admin/shipping-customers/${id}`, {
method: 'DELETE', ...jsonAuth(), body: JSON.stringify(payload),
});
/** 预览客户归并时保留的历史引用和可迁移的未来识别配置。 */
export const getShippingCustomerMergeImpact = (sourceId: number, targetId: number) =>
requestJson<ShippingCustomerMergeImpact>(
`/api/admin/shipping-customers/${sourceId}/merge-impact?target_customer_id=${targetId}`,
auth(),
);
/** 归并重复客户;后端锁定双方并保留历史业务与业务号快照。 */
export const mergeShippingCustomer = (sourceId: number, payload: MergeShippingCustomerRequest) =>
requestJson<MergeShippingCustomerResult>(`/api/admin/shipping-customers/${sourceId}/merge`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
});
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, reason: string) =>
requestJson<ShippingCustomerRow>(`/api/admin/shipping-customers/${id}/deactivate`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify({ reason }),
});
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 createShippingCustomerExternalRef = (
customerId: number,
payload: { source_system: string; customer_code: string },
) => requestJson(`/api/admin/shipping-customers/${customerId}/external-refs`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
});
export const createShippingCustomerSite = (
customerId: number,
payload: { site_name: string; site_code: string; address?: string; city?: string; country?: string; remark?: string },
) => requestJson(`/api/admin/shipping-customers/${customerId}/sites`, {
method: 'POST', ...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(),
});
/** 下载需要管理员权限的二进制文件,并保持统一 BusinessError 契约。 */
const downloadCustomerMasterFile = 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);
};
export const downloadShippingCustomerImportTemplate = () =>
downloadCustomerMasterFile('/api/admin/shipping-customers/import-template', 'shipping_customer_import_template.xlsx');
export const downloadShippingCustomerReconciliation = (batchId: number, batchNo: string) =>
downloadCustomerMasterFile(
`/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 }) },
);
@@ -0,0 +1,96 @@
<!--
features/shipping-notice/customers/ShippingCustomersPage.vue
用途:货代客户主数据管理入口,提供列表、识别证据和期初导入工作台。
依赖:useShippingCustomersAdmin、PaginationBar、三个域内组件。
逻辑:路由加载后查询客户;页面只组合展示与事件,业务状态由 composable 管理。
-->
<script setup lang="ts">
import { onMounted, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Edit, FileSpreadsheet, Fingerprint, GitMerge, History, Plus, Search, Trash2, UserX } from 'lucide-vue-next';
import CustomerDeleteDialog from './components/CustomerDeleteDialog.vue';
import CustomerMergeDialog from './components/CustomerMergeDialog.vue';
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 CustomerLifecyclePanel from './components/CustomerLifecyclePanel.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>
<option value="merged">{{ t('admin.shippingCustomers.status.merged') }}</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-slate-600 hover:bg-slate-100 rounded-lg" :title="t('admin.shippingCustomers.lifecycle.open')" @click="admin.openLifecycleTimeline(customer)"><History 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>
<button v-if="customer.status !== 'merged'" type="button" class="p-2 text-amber-700 hover:bg-amber-50 rounded-lg" :title="t('admin.shippingCustomers.mergeDialog.open')" @click="admin.openMergeCustomer(customer)"><GitMerge class="w-4 h-4" /></button>
<button type="button" class="p-2 text-red-700 hover:bg-red-50 rounded-lg" :title="t('admin.shippingCustomers.deleteDialog.open')" @click="admin.openDeleteCustomer(customer)"><Trash2 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" @add-external-ref="admin.addExternalRef" @add-site="admin.addSite" />
<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" />
<CustomerDeleteDialog :visible="admin.showDeleteDialog.value" :customer="admin.deleteCustomer.value" :impact="admin.deleteImpact.value" :is-saving="admin.isSaving.value" @close="admin.closeDeleteCustomer" @confirm="admin.confirmDeleteCustomer" />
<CustomerLifecyclePanel :visible="admin.showLifecyclePanel.value" :customer="admin.lifecycleCustomer.value" :timeline="admin.lifecycleTimeline.value" @close="admin.closeLifecycleTimeline" />
<CustomerMergeDialog :visible="admin.showMergeDialog.value" :source="admin.mergeCustomer.value" :impact="admin.mergeImpact.value" :customers="admin.importTargetCustomers.value" :is-saving="admin.isSaving.value" @close="admin.closeMergeCustomer" @preview="admin.previewMergeCustomer" @confirm="admin.confirmMergeCustomer" />
</section>
</template>
@@ -0,0 +1,81 @@
<!--
features/shipping-notice/customers/components/CustomerDeleteDialog.vue
用途:展示客户永久删除预检,并收集简码二次确认和删除原因。
依赖:customer-master.types、vue-i18n。
逻辑:有任何服务端生命周期阻断项时不暴露确认按钮;提交仍由父级调用后端原子校验。
-->
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingCustomerLifecycleImpact, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types';
const props = defineProps<{
visible: boolean;
customer: ShippingCustomerRow | null;
impact: ShippingCustomerLifecycleImpact | null;
isSaving: boolean;
}>();
const emit = defineEmits<{ close: []; confirm: [confirmationShortCode: string, reason: string] }>();
const { t } = useI18n();
const confirmationShortCode = ref('');
const reason = ref('');
const blockerEntries = computed(() => Object.entries(props.impact?.blockers || {}).filter(([, count]) => count > 0));
watch(() => props.visible, (visible) => {
if (visible) {
confirmationShortCode.value = '';
reason.value = '';
}
});
/** 仅在预检无阻断且二次确认信息完整时允许发起删除请求。 */
const canSubmit = computed(() => Boolean(
props.impact?.can_delete
&& confirmationShortCode.value.trim()
&& reason.value.trim()
&& !props.isSaving,
));
</script>
<template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
<div class="admin-modal-panel max-w-xl max-h-[92vh] scale-100">
<div class="px-6 py-5 border-b border-subtle">
<h3 class="section-title text-red-700">{{ t('admin.shippingCustomers.deleteDialog.title') }}</h3>
<p class="section-desc mt-1">{{ t('admin.shippingCustomers.deleteDialog.subtitle') }}</p>
</div>
<div class="px-6 py-5 space-y-4 overflow-y-auto">
<div v-if="!impact" class="text-sm text-muted">{{ t('admin.shippingCustomers.deleteDialog.loading') }}</div>
<template v-else>
<div class="rounded-lg border border-default bg-surface-secondary p-4 text-sm">
<div class="font-medium text-primary">{{ impact.customer.standard_name }} <span class="font-mono">({{ impact.customer.short_code }})</span></div>
<div class="mt-1 text-muted">{{ t('admin.shippingCustomers.deleteDialog.identifiers', { count: impact.cascade.identifiers }) }}</div>
</div>
<div v-if="!impact.can_delete" class="rounded-lg border border-red-200 bg-red-50 p-4">
<div class="font-medium text-red-700">{{ t('admin.shippingCustomers.deleteDialog.blocked') }}</div>
<ul class="mt-2 space-y-1 text-sm text-red-700">
<li v-for="[key, count] in blockerEntries" :key="key">{{ t(`admin.shippingCustomers.deleteDialog.blockers.${key}`) }}: {{ count }}</li>
</ul>
<p class="mt-3 text-sm text-red-700">{{ t('admin.shippingCustomers.deleteDialog.blockedHint') }}</p>
</div>
<template v-else>
<p class="text-sm text-red-700">{{ t('admin.shippingCustomers.deleteDialog.warning') }}</p>
<label class="block space-y-1.5">
<span class="label-field">{{ t('admin.shippingCustomers.deleteDialog.confirmationShortCode', { shortCode: impact.customer.short_code }) }}</span>
<input v-model="confirmationShortCode" class="input-field text-sm uppercase" maxlength="6" />
</label>
<label class="block space-y-1.5">
<span class="label-field">{{ t('admin.shippingCustomers.deleteDialog.reason') }}</span>
<textarea v-model="reason" rows="3" class="input-field text-sm resize-y" />
</label>
</template>
</template>
</div>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button v-if="impact?.can_delete" type="button" class="btn-danger" :disabled="!canSubmit" @click="emit('confirm', confirmationShortCode, reason)">{{ isSaving ? t('admin.shippingCustomers.saving') : t('admin.shippingCustomers.deleteDialog.confirm') }}</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,58 @@
<!--
features/shipping-notice/customers/components/CustomerFormModal.vue
用途:创建或编辑货代标准客户。
依赖:customer-master.types、admin 通用表单样式、vue-i18n。
逻辑:父页面传入可变表单;提交事件交由 useShippingCustomersAdmin 保存。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { ShippingCustomerFormState } from '@/features/shipping-notice/types/customer-master.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>
<label v-if="form.id" class="block space-y-1.5">
<span class="label-field">{{ t('admin.shippingCustomers.fields.changeReason') }}</span>
<textarea v-model="form.reason" rows="2" class="input-field text-sm resize-y" :placeholder="t('admin.shippingCustomers.fields.changeReasonHint')" />
</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>
@@ -0,0 +1,138 @@
<!--
features/shipping-notice/customers/components/CustomerIdentifiersPanel.vue
用途:展示、新增、审核和停用客户识别证据。
依赖:customer-master.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/shipping-notice/types/customer-master.types';
import { createEmptyShippingIdentifierForm } from '@/features/shipping-notice/types/customer-master.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>];
addExternalRef: [payload: { source_system: string; customer_code: string }];
addSite: [payload: { site_name: string; site_code: string; address?: string; city?: string; country?: string; remark?: string }];
}>();
const { t } = useI18n();
const form = ref(createEmptyShippingIdentifierForm());
const externalRefForm = ref({ source_system: '', customer_code: '' });
const siteForm = ref({ site_name: '', site_code: '', address: '', city: '', country: '', remark: '' });
/** 切换客户或关闭面板时清空未提交证据。 */
watch(() => [props.visible, props.customer?.id], () => {
form.value = createEmptyShippingIdentifierForm();
externalRefForm.value = { source_system: '', customer_code: '' };
siteForm.value = { site_name: '', site_code: '', address: '', city: '', country: '', remark: '' };
});
/** 提交证据后重置表单,实际保存由父级处理。 */
const submit = (): void => {
emit('add', { ...form.value });
form.value = createEmptyShippingIdentifierForm();
};
/** 提交来源系统客户编码;客户简称仍由客户基本信息统一维护。 */
const submitExternalRef = (): void => {
emit('addExternalRef', { ...externalRefForm.value });
externalRefForm.value = { source_system: '', customer_code: '' };
};
/** 提交送货站点;站点用于 Ship-to 匹配,不创建新的账款客户。 */
const submitSite = (): void => {
emit('addSite', { ...siteForm.value });
siteForm.value = { site_name: '', site_code: '', address: '', city: '', country: '', remark: '' };
};
</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">
<section class="rounded-xl border border-default p-4 space-y-4">
<div><h4 class="font-semibold text-primary">{{ t('admin.shippingCustomers.externalRefs.title') }}</h4><p class="text-xs text-muted mt-1">{{ t('admin.shippingCustomers.externalRefs.hint') }}</p></div>
<div v-if="customer.external_refs?.length" class="flex flex-wrap gap-2"><span v-for="item in customer.external_refs" :key="item.id" class="badge">{{ item.source_system }} · {{ item.customer_code }}</span></div>
<p v-else class="text-sm text-muted">{{ t('admin.shippingCustomers.externalRefs.empty') }}</p>
<div class="grid grid-cols-1 md:grid-cols-[1fr_1fr_auto] gap-3">
<input v-model="externalRefForm.source_system" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.externalRefs.sourceSystem')" />
<input v-model="externalRefForm.customer_code" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.externalRefs.customerCode')" />
<button type="button" class="btn-primary" :disabled="isSaving || !externalRefForm.source_system.trim() || !externalRefForm.customer_code.trim()" @click="submitExternalRef">{{ t('admin.add') }}</button>
</div>
</section>
<section class="rounded-xl border border-default p-4 space-y-4">
<div><h4 class="font-semibold text-primary">{{ t('admin.shippingCustomers.sites.title') }}</h4><p class="text-xs text-muted mt-1">{{ t('admin.shippingCustomers.sites.hint') }}</p></div>
<div v-if="customer.sites?.length" class="grid gap-2"><div v-for="site in customer.sites" :key="site.id" class="rounded-lg bg-surface-soft p-3"><div class="font-medium text-primary">{{ site.site_name }} · {{ site.site_code }}</div><div class="text-xs text-muted mt-1">{{ [site.address, site.city, site.country].filter(Boolean).join(' · ') || '-' }}</div></div></div>
<p v-else class="text-sm text-muted">{{ t('admin.shippingCustomers.sites.empty') }}</p>
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
<input v-model="siteForm.site_name" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.sites.siteName')" />
<input v-model="siteForm.site_code" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.sites.siteCode')" />
<input v-model="siteForm.address" class="input-field text-sm md:col-span-2" :placeholder="t('admin.shippingCustomers.sites.address')" />
<input v-model="siteForm.city" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.sites.city')" />
<input v-model="siteForm.country" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.sites.country')" />
</div>
<div class="flex justify-end"><button type="button" class="btn-primary" :disabled="isSaving || !siteForm.site_name.trim() || !siteForm.site_code.trim()" @click="submitSite">{{ t('admin.add') }}</button></div>
</section>
<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>
@@ -0,0 +1,121 @@
<!--
features/shipping-notice/customers/components/CustomerImportDialog.vue
用途:上传期初客户 Excel、查看预检结果、处理 warning、发布并下载对账。
依赖:customer-master.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/shipping-notice/types/customer-master.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>
@@ -0,0 +1,59 @@
<!--
features/shipping-notice/customers/components/CustomerLifecyclePanel.vue
用途:展示单个货代客户不可变的生命周期治理审计。
依赖:customer-master.types、vue-i18n。
逻辑:由客户主数据页拉取时间线后传入;仅渲染快照,不触发任何客户写操作。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { ShippingCustomerLifecycleTimeline, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types';
defineProps<{ visible: boolean; customer: ShippingCustomerRow | null; timeline: ShippingCustomerLifecycleTimeline | null }>();
const emit = defineEmits<{ close: [] }>();
const { t } = useI18n();
/** 将不同事件的变更明细压缩成易读文本,完整结构仍可由审计 API 获取。 */
const changeSummary = (detail: Record<string, unknown>): string => {
const changes = detail.changes;
if (!changes || typeof changes !== 'object') return '-';
return Object.entries(changes as Record<string, { before?: unknown; after?: unknown }>)
.map(([key, value]) => `${key}: ${String(value.before ?? '-')} → ${String(value.after ?? '-')}`)
.join(';');
};
</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.lifecycle.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">
<div v-if="!timeline" class="py-12 text-center text-sm text-muted">{{ t('admin.shippingCustomers.lifecycle.loading') }}</div>
<div v-else class="overflow-x-auto rounded-xl border border-default">
<table class="admin-table min-w-[760px]">
<thead><tr>
<th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.lifecycle.time') }}</th>
<th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.lifecycle.event') }}</th>
<th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.lifecycle.reason') }}</th>
<th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.lifecycle.change') }}</th>
</tr></thead>
<tbody>
<tr v-if="!timeline.items.length"><td colspan="4" class="admin-table-empty px-4">{{ t('admin.shippingCustomers.lifecycle.empty') }}</td></tr>
<tr v-for="event in timeline.items" :key="event.id">
<td class="px-4 py-3 text-sm text-muted">{{ event.created_at || '-' }}</td>
<td class="px-4 py-3 text-sm">{{ t(`admin.shippingCustomers.lifecycle.events.${event.event_type}`) }}</td>
<td class="px-4 py-3 text-sm">{{ event.reason || '-' }}</td>
<td class="px-4 py-3 text-sm break-all">{{ changeSummary(event.detail) }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,66 @@
<!--
features/shipping-notice/customers/components/CustomerMergeDialog.vue
用途:预览并确认将重复客户归并到启用目标客户。
依赖:customer-master.types、vue-i18n。
逻辑:展示历史保留与未来配置迁移边界;提交必须输入源客户简码和合并原因。
-->
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingCustomerMergeImpact, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types';
const props = defineProps<{
visible: boolean;
source: ShippingCustomerRow | null;
impact: ShippingCustomerMergeImpact | null;
customers: ShippingCustomerRow[];
isSaving: boolean;
}>();
const emit = defineEmits<{
close: [];
preview: [targetCustomerId: number];
confirm: [targetCustomerId: number, confirmationShortCode: string, reason: string];
}>();
const { t } = useI18n();
const targetCustomerId = ref<number | null>(null);
const confirmationShortCode = ref('');
const reason = ref('');
const targetOptions = computed(() => props.customers.filter((item) => item.id !== props.source?.id && item.status === 'active'));
watch(() => props.visible, (visible) => {
if (visible) {
targetCustomerId.value = null;
confirmationShortCode.value = '';
reason.value = '';
}
});
/** 选择目标后再调用服务端预检,阻止在未确认归并边界时提交。 */
const preview = (): void => {
if (targetCustomerId.value) emit('preview', targetCustomerId.value);
};
const canSubmit = computed(() => Boolean(
targetCustomerId.value && props.impact && confirmationShortCode.value.trim() && reason.value.trim() && !props.isSaving,
));
</script>
<template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
<div class="admin-modal-panel max-w-xl max-h-[92vh] scale-100">
<div class="px-6 py-5 border-b border-subtle"><h3 class="section-title">{{ t('admin.shippingCustomers.mergeDialog.title') }}</h3><p class="section-desc mt-1">{{ t('admin.shippingCustomers.mergeDialog.subtitle') }}</p></div>
<div class="px-6 py-5 space-y-4 overflow-y-auto">
<div v-if="source" class="rounded-lg border border-default bg-surface-secondary p-4 text-sm"><span class="text-muted">{{ t('admin.shippingCustomers.mergeDialog.source') }}</span><div class="font-medium text-primary mt-1">{{ source.standard_name }} <span class="font-mono">({{ source.short_code }})</span></div></div>
<label class="block space-y-1.5"><span class="label-field">{{ t('admin.shippingCustomers.mergeDialog.target') }}</span><select v-model="targetCustomerId" class="input-field text-sm" @change="preview"><option :value="null">{{ t('admin.shippingCustomers.mergeDialog.chooseTarget') }}</option><option v-for="customer in targetOptions" :key="customer.id" :value="customer.id">{{ customer.standard_name }} ({{ customer.short_code }})</option></select></label>
<template v-if="impact">
<div class="rounded-lg border border-default p-4 text-sm"><div class="font-medium text-primary">{{ t('admin.shippingCustomers.mergeDialog.historyTitle') }}</div><p class="mt-1 text-muted">{{ t('admin.shippingCustomers.mergeDialog.historyHint') }}</p><div class="mt-2 text-muted">{{ t('admin.shippingCustomers.mergeDialog.historyCount', { count: Object.values(impact.historical_references).reduce((sum, value) => sum + value, 0) }) }}</div></div>
<div class="rounded-lg border border-default p-4 text-sm"><div class="font-medium text-primary">{{ t('admin.shippingCustomers.mergeDialog.migrateTitle') }}</div><div class="mt-2 grid grid-cols-3 gap-2 text-center"><div><div class="text-lg font-semibold">{{ impact.migrate.identifiers }}</div><div class="text-xs text-muted">{{ t('admin.shippingCustomers.mergeDialog.identifiers') }}</div></div><div><div class="text-lg font-semibold">{{ impact.migrate.duplicate_identifiers }}</div><div class="text-xs text-muted">{{ t('admin.shippingCustomers.mergeDialog.duplicates') }}</div></div><div><div class="text-lg font-semibold">{{ impact.migrate.external_references }}</div><div class="text-xs text-muted">{{ t('admin.shippingCustomers.mergeDialog.references') }}</div></div></div></div>
<p class="text-sm text-amber-700">{{ t('admin.shippingCustomers.mergeDialog.warning') }}</p>
<label class="block space-y-1.5"><span class="label-field">{{ t('admin.shippingCustomers.mergeDialog.confirmationShortCode', { shortCode: impact.source.short_code }) }}</span><input v-model="confirmationShortCode" class="input-field text-sm uppercase" maxlength="6" /></label>
<label class="block space-y-1.5"><span class="label-field">{{ t('admin.shippingCustomers.mergeDialog.reason') }}</span><textarea v-model="reason" rows="3" class="input-field text-sm resize-y" /></label>
</template>
</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="!canSubmit" @click="targetCustomerId && emit('confirm', targetCustomerId, confirmationShortCode, reason)">{{ isSaving ? t('admin.shippingCustomers.saving') : t('admin.shippingCustomers.mergeDialog.confirm') }}</button></div>
</div>
</div>
</template>
@@ -0,0 +1,97 @@
<!--
features/shipping-notice/customers/components/CustomerShadowQualityPanel.vue
用途:展示客户影子识别分布、自动确认/纠错指标、人工标注准确率和最近样本。
依赖:customer-master.types、vue-i18n。
逻辑:展示质量卡片、客户事件审计与真值标签;不调用客户绑定、编号或任务接口。
-->
<script setup lang="ts">
import { ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingCustomerRow, ShippingCustomerShadowReport } from '@/features/shipping-notice/types/customer-master.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?.auto_resolution?.quality_gate" class="rounded-xl border p-4" :class="report.auto_resolution.quality_gate.is_eligible ? 'border-emerald-300 bg-emerald-50/50' : 'border-amber-300 bg-amber-50/50'">
<div class="font-semibold text-primary">{{ t('admin.shippingCustomers.shadow.gate.title') }}</div>
<div class="mt-1 text-sm text-secondary">{{ t(`admin.shippingCustomers.shadow.gate.statuses.${report.auto_resolution.quality_gate.status}`) }}</div>
<div class="mt-2 text-xs text-muted">
{{ t('admin.shippingCustomers.shadow.gate.metrics', {
samples: report.auto_resolution.quality_gate.labeled_sample_count,
minSamples: report.auto_resolution.quality_gate.min_labeled_samples,
accuracy: report.auto_resolution.quality_gate.accuracy == null ? '-' : `${(report.auto_resolution.quality_gate.accuracy * 100).toFixed(1)}%`,
minAccuracy: `${(report.auto_resolution.quality_gate.min_accuracy * 100).toFixed(1)}%`,
}) }}
</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>
@@ -0,0 +1,503 @@
/**
* features/shipping-notice/customers/composables/useShippingCustomersAdmin.ts
* 用途:编排货代客户列表、详情、识别证据、期初导入与发布状态。
* 依赖:customer-master.api、customer-master.types、BusinessError、useMessage。
* 逻辑:ShippingCustomersPage 与子组件共享本 composable 暴露的状态和动作。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
createShippingCustomer,
createShippingCustomerExternalRef,
createShippingCustomerIdentifier,
createShippingCustomerSite,
deleteShippingCustomer,
deactivateShippingCustomer,
decideShippingCustomerImportRow,
downloadShippingCustomerImportTemplate,
downloadShippingCustomerReconciliation,
getShippingCustomer,
getShippingCustomerLifecycleImpact,
getShippingCustomerLifecycleTimeline,
getShippingCustomerMergeImpact,
getShippingCustomerShadowReport,
listShippingCustomers,
labelShippingCustomerShadowResolution,
mergeShippingCustomer,
publishShippingCustomerImport,
updateShippingCustomer,
updateShippingCustomerIdentifier,
uploadShippingCustomerImport,
} from '@/features/shipping-notice/api/customer-master.api';
import type {
ShippingCustomerFormState,
ShippingCustomerLifecycleImpact,
ShippingCustomerLifecycleTimeline,
ShippingCustomerMergeImpact,
ShippingCustomerImportBatch,
ShippingCustomerImportRow,
ShippingCustomerRow,
ShippingCustomerShadowReport,
ShippingIdentifierFormState,
} from '@/features/shipping-notice/types/customer-master.types';
import {
createEmptyShippingCustomerForm,
shippingCustomerToForm,
} from '@/features/shipping-notice/types/customer-master.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 deleteCustomer = ref<ShippingCustomerRow | null>(null);
const deleteImpact = ref<ShippingCustomerLifecycleImpact | null>(null);
const lifecycleCustomer = ref<ShippingCustomerRow | null>(null);
const lifecycleTimeline = ref<ShippingCustomerLifecycleTimeline | null>(null);
const mergeCustomer = ref<ShippingCustomerRow | null>(null);
const mergeImpact = ref<ShippingCustomerMergeImpact | 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 showDeleteDialog = ref(false);
const showLifecyclePanel = ref(false);
const showMergeDialog = 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(),
reason: form.reason.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;
const reason = window.prompt(t('admin.shippingCustomers.prompts.deactivateReason'))?.trim();
if (!reason) return;
try {
await deactivateShippingCustomer(customer.id, reason);
await loadCustomers();
} catch (error) {
showError(error, 'admin.shippingCustomers.msg.saveFailed');
}
};
/** 打开客户治理时间线;读取失败时不显示过期的其他客户审计。 */
const openLifecycleTimeline = async (customer: ShippingCustomerRow): Promise<void> => {
lifecycleCustomer.value = customer;
lifecycleTimeline.value = null;
showLifecyclePanel.value = true;
try {
const timeline = await getShippingCustomerLifecycleTimeline(customer.id);
if (showLifecyclePanel.value && lifecycleCustomer.value?.id === customer.id) lifecycleTimeline.value = timeline;
} catch (error) {
showError(error, 'admin.shippingCustomers.msg.loadFailed');
}
};
/** 关闭时间线面板并清空快照,避免切换客户时展示错误审计。 */
const closeLifecycleTimeline = (): void => {
showLifecyclePanel.value = false;
lifecycleCustomer.value = null;
lifecycleTimeline.value = null;
};
/** 打开永久删除预检;资格必须以服务端生命周期统计为准。 */
const openDeleteCustomer = async (customer: ShippingCustomerRow): Promise<void> => {
deleteCustomer.value = customer;
deleteImpact.value = null;
showDeleteDialog.value = true;
try {
const impact = await getShippingCustomerLifecycleImpact(customer.id);
// 快速切换行时只接受仍属于当前弹窗客户的预检响应。
if (showDeleteDialog.value && deleteCustomer.value?.id === customer.id) {
deleteImpact.value = impact;
}
} catch (error) {
showError(error, 'admin.shippingCustomers.msg.loadFailed');
}
};
/** 关闭删除窗口并清空预检快照,避免错误复用其他客户的删除资格。 */
const closeDeleteCustomer = (): void => {
showDeleteDialog.value = false;
deleteCustomer.value = null;
deleteImpact.value = null;
};
/** 提交受控永久删除;后端会在同一事务内再次统计引用以处理并发变更。 */
const confirmDeleteCustomer = async (confirmationShortCode: string, reason: string): Promise<void> => {
if (!deleteCustomer.value) return;
isSaving.value = true;
try {
await deleteShippingCustomer(deleteCustomer.value.id, {
confirmation_short_code: confirmationShortCode.trim().toUpperCase(),
reason: reason.trim(),
});
closeDeleteCustomer();
await loadCustomers();
msg.success(t('admin.shippingCustomers.deleteDialog.deleted'));
} catch (error) {
showError(error, 'admin.shippingCustomers.deleteDialog.failed');
if (error instanceof BusinessError && error.code === 'SHIPPING.CUSTOMER_DELETE_BLOCKED') {
try {
deleteImpact.value = await getShippingCustomerLifecycleImpact(deleteCustomer.value.id);
} catch {
// 保留原预检内容;错误提示已由统一处理展示。
}
}
} finally {
isSaving.value = false;
}
};
/** 打开客户归并窗口;目标客户列表只加载可用于未来识别的启用客户。 */
const openMergeCustomer = async (customer: ShippingCustomerRow): Promise<void> => {
mergeCustomer.value = customer;
mergeImpact.value = null;
showMergeDialog.value = true;
try {
await loadAllCustomerOptions();
} catch (error) {
showError(error, 'admin.shippingCustomers.msg.loadFailed');
}
};
/** 选择目标客户后读取服务端预检,不以页面计数推断可归并内容。 */
const previewMergeCustomer = async (targetCustomerId: number): Promise<void> => {
if (!mergeCustomer.value) return;
mergeImpact.value = null;
try {
const impact = await getShippingCustomerMergeImpact(mergeCustomer.value.id, targetCustomerId);
if (showMergeDialog.value && mergeCustomer.value?.id === impact.source.id) {
mergeImpact.value = impact;
}
} catch (error) {
showError(error, 'admin.shippingCustomers.mergeDialog.previewFailed');
}
};
/** 关闭归并窗口并清空源客户和预检快照。 */
const closeMergeCustomer = (): void => {
showMergeDialog.value = false;
mergeCustomer.value = null;
mergeImpact.value = null;
};
/** 提交受控归并;历史业务号和审计引用由服务端保留在源客户。 */
const confirmMergeCustomer = async (targetCustomerId: number, confirmationShortCode: string, reason: string): Promise<void> => {
if (!mergeCustomer.value) return;
isSaving.value = true;
try {
await mergeShippingCustomer(mergeCustomer.value.id, {
target_customer_id: targetCustomerId,
confirmation_short_code: confirmationShortCode.trim().toUpperCase(),
reason: reason.trim(),
});
closeMergeCustomer();
await Promise.all([loadCustomers(), loadAllCustomerOptions()]);
msg.success(t('admin.shippingCustomers.mergeDialog.merged'));
} catch (error) {
showError(error, 'admin.shippingCustomers.mergeDialog.failed');
} finally {
isSaving.value = false;
}
};
/** 拉取客户详情并打开识别证据面板。 */
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 {
const reason = window.prompt(t('admin.shippingCustomers.prompts.identifierChangeReason'))?.trim();
if (!reason) return;
await updateShippingCustomerIdentifier(identifierId, { ...payload, reason });
selectedCustomer.value = await getShippingCustomer(selectedCustomer.value.id);
} catch (error) {
showError(error, 'admin.shippingCustomers.msg.saveFailed');
}
};
/** 新增外部系统客户编码,并重新读取客户详情。 */
const addExternalRef = async (payload: { source_system: string; customer_code: string }): Promise<void> => {
if (!selectedCustomer.value) return;
isSaving.value = true;
try {
await createShippingCustomerExternalRef(selectedCustomer.value.id, payload);
selectedCustomer.value = await getShippingCustomer(selectedCustomer.value.id);
msg.success(t('admin.shippingCustomers.msg.saved'));
} catch (error) {
showError(error, 'admin.shippingCustomers.msg.saveFailed');
} finally {
isSaving.value = false;
}
};
/** 新增送货站点,并重新读取客户详情。 */
const addSite = async (payload: { site_name: string; site_code: string; address?: string; city?: string; country?: string; remark?: string }): Promise<void> => {
if (!selectedCustomer.value) return;
isSaving.value = true;
try {
await createShippingCustomerSite(selectedCustomer.value.id, payload);
selectedCustomer.value = await getShippingCustomer(selectedCustomer.value.id);
msg.success(t('admin.shippingCustomers.msg.saved'));
} catch (error) {
showError(error, 'admin.shippingCustomers.msg.saveFailed');
} finally {
isSaving.value = false;
}
};
/** 打开期初导入对话框并清空上次批次。 */
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, deleteCustomer, deleteImpact, lifecycleCustomer, lifecycleTimeline, mergeCustomer, mergeImpact,
searchQuery, statusFilter, page, pageSize, total, pages,
isLoading, isSaving, isImporting, isShadowLoading,
showCustomerModal, showIdentifiersPanel, showImportDialog, showDeleteDialog, showLifecyclePanel, showMergeDialog,
loadCustomers, searchCustomers, openCreateCustomer, openEditCustomer, closeCustomerModal,
saveCustomer, deactivateCustomer, openLifecycleTimeline, closeLifecycleTimeline, openDeleteCustomer, closeDeleteCustomer, confirmDeleteCustomer, openMergeCustomer, previewMergeCustomer, closeMergeCustomer, confirmMergeCustomer, openIdentifiers, addIdentifier, updateIdentifier, addExternalRef, addSite,
openImport, uploadImport, decideImportRow, publishImport, downloadTemplate, downloadReconciliation,
loadShadowReport, labelShadowResolution,
};
}
@@ -0,0 +1,63 @@
/**
* 用途:验证货代发货通知业务域在四种语言中的文案键保持一致。
* 依赖:admin/chat/workspace 四语言 JSON;只检查货代业务子树,不受其他历史业务域影响。
* 逻辑:递归收集叶子键并比较集合,防止只在单一语言新增或删除货代文案。
*/
import { describe, expect, it } from 'vitest';
import adminEn from '@/locales/en/admin.json';
import adminTh from '@/locales/th/admin.json';
import adminZhCn from '@/locales/zh-CN/admin.json';
import adminZhTw from '@/locales/zh-TW/admin.json';
import chatEn from '@/locales/en/chat.json';
import chatTh from '@/locales/th/chat.json';
import chatZhCn from '@/locales/zh-CN/chat.json';
import chatZhTw from '@/locales/zh-TW/chat.json';
import workspaceEn from '@/locales/en/workspace.json';
import workspaceTh from '@/locales/th/workspace.json';
import workspaceZhCn from '@/locales/zh-CN/workspace.json';
import workspaceZhTw from '@/locales/zh-TW/workspace.json';
type LocaleTree = Record<string, unknown>;
const leafKeys = (value: unknown, prefix = ''): string[] => {
if (!value || typeof value !== 'object' || Array.isArray(value)) return [prefix];
return Object.entries(value as LocaleTree).flatMap(([key, child]) => (
leafKeys(child, prefix ? `${prefix}.${key}` : key)
));
};
const expectSameKeys = (trees: LocaleTree[]) => {
const expected = leafKeys(trees[0]).sort();
trees.slice(1).forEach((tree) => expect(leafKeys(tree).sort()).toEqual(expected));
};
describe('shipping notice i18n parity', () => {
it('keeps admin inventory configuration keys aligned', () => {
expectSameKeys([
adminZhCn.shippingInventory as LocaleTree,
adminZhTw.shippingInventory as LocaleTree,
adminEn.shippingInventory as LocaleTree,
adminTh.shippingInventory as LocaleTree,
]);
});
it('keeps chat shipping notice keys aligned', () => {
expectSameKeys([
chatZhCn.shippingNotice as LocaleTree,
chatZhTw.shippingNotice as LocaleTree,
chatEn.shippingNotice as LocaleTree,
chatTh.shippingNotice as LocaleTree,
]);
});
it('keeps workspace shipping notice keys aligned', () => {
expectSameKeys([
workspaceZhCn.shippingNotice as LocaleTree,
workspaceZhTw.shippingNotice as LocaleTree,
workspaceEn.shippingNotice as LocaleTree,
workspaceTh.shippingNotice as LocaleTree,
]);
});
});
@@ -0,0 +1,285 @@
/**
* features/shipping-notice/types/customer-master.types.ts
* 用途:货代客户主数据、识别证据和期初导入管理端类型契约。
* 依赖:无运行时依赖。
* 逻辑:customer-master.api 返回这些结构;客户主数据页面与组件据此渲染和提交。
*/
export type ShippingCustomerStatus = 'active' | 'inactive' | 'merged';
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;
merged_into_customer_id?: number | null;
remark?: string | null;
case_count: number;
identifier_count: number;
identifiers?: ShippingCustomerIdentifier[];
external_refs?: ShippingCustomerExternalRef[];
sites?: ShippingCustomerSite[];
created_at?: string | null;
updated_at?: string | null;
}
export interface ShippingCustomerPage {
items: ShippingCustomerRow[];
total: number;
page: number;
page_size: number;
pages: number;
}
export interface ShippingCustomerExternalRef {
id: number;
customer_id: number;
source_system: string;
customer_code: string;
}
export interface ShippingCustomerSite {
id: number;
customer_id: number;
site_name: string;
site_code: string;
address?: string | null;
city?: string | null;
country?: string | null;
status: string;
remark?: string | null;
identifiers: Array<Record<string, unknown>>;
}
export interface ShippingCustomerLifecycleImpact {
customer: Pick<ShippingCustomerRow, 'id' | 'standard_name' | 'short_code' | 'status'>;
can_delete: boolean;
blockers: {
business_cases: number;
business_sequences: number;
external_references: number;
order_customer_matches: number;
import_target_rows: number;
import_result_rows: number;
shadow_top_candidates: number;
shadow_manual_labels: number;
shadow_candidate_matches: number;
merged_source_customers: number;
merged_into_customer: number;
};
cascade: {
identifiers: number;
sites: number;
};
}
export interface DeleteShippingCustomerRequest {
confirmation_short_code: string;
reason: string;
}
export interface DeleteShippingCustomerResult {
deleted_customer: ShippingCustomerLifecycleImpact['customer'];
cascade: ShippingCustomerLifecycleImpact['cascade'];
lifecycle_event_id: number;
}
export interface ShippingCustomerMergeImpact {
source: Pick<ShippingCustomerRow, 'id' | 'standard_name' | 'short_code' | 'status'>;
target: Pick<ShippingCustomerRow, 'id' | 'standard_name' | 'short_code' | 'status'>;
historical_references: ShippingCustomerLifecycleImpact['blockers'];
migrate: {
identifiers: number;
duplicate_identifiers: number;
external_references: number;
sites: number;
};
}
export interface MergeShippingCustomerRequest {
target_customer_id: number;
confirmation_short_code: string;
reason: string;
}
export interface MergeShippingCustomerResult {
source: ShippingCustomerMergeImpact['source'];
target: ShippingCustomerMergeImpact['target'];
migrate: ShippingCustomerMergeImpact['migrate'];
merge_id: 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;
auto_confirmation_rate?: number | null;
quality_gate: {
status: 'eligible' | 'insufficient_labeled_samples' | 'insufficient_accuracy';
is_eligible: boolean;
labeled_sample_count: number;
correct_sample_count: number;
accuracy?: number | null;
min_labeled_samples: number;
min_accuracy: number;
};
recent_events: Array<{
id: number;
task_no: string;
event_type: string;
detail: Record<string, unknown>;
created_at?: string | null;
}>;
};
items: ShippingCustomerShadowItem[];
}
export interface ShippingCustomerLifecycleEvent {
id: number;
event_type: string;
actor_id?: number | null;
reason?: string | null;
detail: Record<string, unknown>;
created_at?: string | null;
}
export interface ShippingCustomerLifecycleTimeline {
customer: Omit<Pick<ShippingCustomerRow, 'id' | 'standard_name' | 'short_code' | 'status'>, 'status'> & {
status: ShippingCustomerStatus | 'deleted';
};
items: ShippingCustomerLifecycleEvent[];
}
export interface ShippingCustomerFormState {
id?: number;
standard_name: string;
short_code: string;
status: ShippingCustomerStatus;
remark: string;
reason: 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: '',
reason: '',
});
/** 将客户详情转换为可编辑表单快照。 */
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 || '',
reason: '',
});
/** 创建空识别证据表单,默认待审核且禁止自动匹配。 */
export const createEmptyShippingIdentifierForm = (): ShippingIdentifierFormState => ({
identifier_type: 'name_alias',
identifier_value: '',
status: 'pending',
auto_match_allowed: false,
remark: '',
});
@@ -0,0 +1,30 @@
/**
* features/shipping-notice/utils/exportSelection.spec.ts
* 用途:验证显式任务批量下载选择的去重、取消、可见范围和数量门禁。
* 依赖:Vitest、exportSelection。
* 逻辑:以纯函数覆盖工作台交互边界,不依赖浏览器 DOM。
*/
import { describe, expect, it } from 'vitest';
import {
retainVisibleShippingExportSelection,
selectVisibleShippingExports,
updateShippingExportSelection,
} from './exportSelection';
describe('shipping export selection', () => {
it('adds, deduplicates and removes task numbers', () => {
expect(updateShippingExportSelection([], ' SN-1 ', true)).toEqual(['SN-1']);
expect(updateShippingExportSelection(['SN-1'], 'SN-1', true)).toEqual(['SN-1']);
expect(updateShippingExportSelection(['SN-1', 'SN-2'], 'SN-1', false)).toEqual(['SN-2']);
});
it('rejects selections over the archive limit', () => {
expect(() => selectVisibleShippingExports(['SN-1', 'SN-2'], 1)).toThrowError(RangeError);
expect(() => updateShippingExportSelection(['SN-1'], 'SN-2', true, 1)).toThrowError(RangeError);
});
it('retains only tasks still visible after a refresh', () => {
expect(retainVisibleShippingExportSelection(['SN-1', 'SN-2'], ['SN-2', 'SN-3'])).toEqual(['SN-2']);
});
});
@@ -0,0 +1,43 @@
/**
* features/shipping-notice/utils/exportSelection.ts
* 用途:维护工作台显式勾选的发货任务编号,并与批量下载 100 票上限保持一致。
* 依赖:无。
* 逻辑:所有入口统一去重、过滤空编号,并在加入新任务时执行上限门禁。
*/
export const SHIPPING_EXPORT_SELECTION_LIMIT = 100;
/** 更新单个任务的选择状态;超过服务端上限时拒绝产生新状态。 */
export function updateShippingExportSelection(
current: readonly string[],
taskNo: string,
selected: boolean,
limit = SHIPPING_EXPORT_SELECTION_LIMIT,
): string[] {
const normalizedTaskNo = taskNo.trim();
const normalized = [...new Set(current.map((item) => item.trim()).filter(Boolean))];
if (!normalizedTaskNo) return normalized;
if (!selected) return normalized.filter((item) => item !== normalizedTaskNo);
if (normalized.includes(normalizedTaskNo)) return normalized;
if (normalized.length >= limit) throw new RangeError('SHIPPING_EXPORT_SELECTION_LIMIT');
return [...normalized, normalizedTaskNo];
}
/** 选择当前查询结果;调用方应将超限作为明确错误展示,而不是静默截断。 */
export function selectVisibleShippingExports(
taskNos: readonly string[],
limit = SHIPPING_EXPORT_SELECTION_LIMIT,
): string[] {
const normalized = [...new Set(taskNos.map((item) => item.trim()).filter(Boolean))];
if (normalized.length > limit) throw new RangeError('SHIPPING_EXPORT_SELECTION_LIMIT');
return normalized;
}
/** 刷新查询结果后仅保留仍可见的选择,避免下载陈旧或越界任务。 */
export function retainVisibleShippingExportSelection(
current: readonly string[],
visibleTaskNos: readonly string[],
): string[] {
const visible = new Set(visibleTaskNos.map((item) => item.trim()).filter(Boolean));
return [...new Set(current.map((item) => item.trim()).filter((item) => visible.has(item)))];
}