feat(admin): 新增在途调拨类型管理页
调拨类型四块配置的维护入口:基本信息(编码/多语言名称/排序/启停)、范围规则 (受控字段下拉+匹配方式+多值标签,规则间且/值间或)、仓库定义(拨出/拨入角色 映射档或固定仓)、字段转换(批号前缀替换)。列表含规则数与启用状态检索, 类型被调拨链路引用时编码与用途不可改(两段式校验),重复编码返回 422。 管理控制台注册导航与路由;新增 8 个 TRANSFER.* 错误码四语言文案。
This commit is contained in:
1 parent
52c71ee46a
commit
3a19f9c27d
14 files changed
+2103
-2
No files matched your search
@@ -82,6 +82,9 @@ const TrainingConfigPage = () =>
|
||||
const IntegrationConnectorPage = () =>
|
||||
import("@/features/admin/modules/integration-connector/IntegrationConnectorPage.vue");
|
||||
|
||||
const TransferTypesPage = () =>
|
||||
import("@/features/admin/modules/transfer-types/TransferTypesPage.vue");
|
||||
|
||||
export const adminRoutes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: "/admin",
|
||||
@@ -341,6 +344,16 @@ export const adminRoutes: RouteRecordRaw[] = [
|
||||
title: "admin.nav.integrationConnector",
|
||||
},
|
||||
},
|
||||
{
|
||||
path: "transfer-types",
|
||||
name: "AdminTransferTypes",
|
||||
component: TransferTypesPage,
|
||||
meta: {
|
||||
requiresAdmin: true,
|
||||
adminModule: "transfer_types",
|
||||
title: "admin.nav.transferTypes",
|
||||
},
|
||||
},
|
||||
{
|
||||
path: "reports/:table?",
|
||||
name: "AdminReports",
|
||||
|
||||
@@ -74,6 +74,7 @@ export const config = {
|
||||
procurement_contract: true, // 采购合同审查(模板库 + 历史)
|
||||
training_config: true,
|
||||
integration_connector: true, // 集成连接器配置
|
||||
transfer_types: true, // 在途调拨类型配置(ADR 0002)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -11,7 +11,7 @@ import { useRoute, useRouter } from 'vue-router';
|
||||
import {
|
||||
LayoutDashboard, UserCog, Building, Bot, FileText,
|
||||
Settings2, Megaphone, MessageCircleQuestion, Link2, Users, BarChart2, AppWindow,
|
||||
ScrollText, ExternalLink, PackageSearch, GraduationCap, Cable,
|
||||
ScrollText, ExternalLink, PackageSearch, GraduationCap, Cable, ArrowLeftRight,
|
||||
} from 'lucide-vue-next';
|
||||
import type { Component } from 'vue';
|
||||
import { config } from '@/config';
|
||||
@@ -44,6 +44,7 @@ const iconMap: Record<AdminModuleId, Component> = {
|
||||
procurement_contract: ScrollText,
|
||||
training_config: GraduationCap,
|
||||
integration_connector: Cable,
|
||||
transfer_types: ArrowLeftRight,
|
||||
reports: BarChart2,
|
||||
shipping_inventory: PackageSearch,
|
||||
};
|
||||
|
||||
@@ -40,7 +40,7 @@ export interface ShippingConfigSubModuleMeta {
|
||||
|
||||
/** 已独立拆分的模块(全部 admin 模块均已拆分) */
|
||||
export const STANDALONE_ADMIN_MODULES = new Set<AdminModuleId>([
|
||||
'dashboard', 'agents', 'users', 'departments', 'announcements', 'questions', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'linked_services', 'platform_apps', 'shipping_inventory', 'procurement_contract', 'reports', 'training_config', 'integration_connector'
|
||||
'dashboard', 'agents', 'users', 'departments', 'announcements', 'questions', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'linked_services', 'platform_apps', 'shipping_inventory', 'procurement_contract', 'reports', 'training_config', 'integration_connector', 'transfer_types'
|
||||
]);
|
||||
|
||||
export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
|
||||
@@ -60,6 +60,7 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
|
||||
{ id: 'procurement_contract', routeName: 'AdminProcurementContract', path: 'procurement-contract', labelKey: 'admin.nav.procurementContract', configKey: 'procurement_contract' },
|
||||
{ id: 'training_config', routeName: 'AdminTrainingConfig', path: 'training-config', labelKey: 'admin.nav.trainingConfig', configKey: 'training_config' },
|
||||
{ id: 'integration_connector', routeName: 'AdminIntegrationConnector', path: 'integration-connector', labelKey: 'admin.nav.integrationConnector', configKey: 'integration_connector' },
|
||||
{ id: 'transfer_types', routeName: 'AdminTransferTypes', path: 'transfer-types', labelKey: 'admin.nav.transferTypes', configKey: 'transfer_types' },
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -10,3 +10,4 @@ export { adminModulePath, ADMIN_MODULE_METAS } from './constants/modules';
|
||||
export type { AdminModuleId } from './types/admin.types';
|
||||
export * from './api/admin.api';
|
||||
export * from './api/schedule.api';
|
||||
export * from './modules/transfer-types/transferTypes.api';
|
||||
@@ -0,0 +1,958 @@
|
||||
<!--
|
||||
features/admin/modules/transfer-types/TransferTypesPage.vue
|
||||
用途:在途调拨「调拨类型配置化」管理页——列表(搜索/状态筛选/空态)+ 编辑抽屉四块
|
||||
(基本信息 / 范围规则行编辑器 / 仓库定义 / 转换规则行编辑器),ADR 0002。
|
||||
依赖:transferTypes.api(受控词表与请求)、useTransferTypesAdmin(状态与动作编排)、vue-i18n。
|
||||
逻辑:页面只负责模板与样式;校验/保存/重叠比对/映射档校验全部在 composable。
|
||||
可用性契约:onBlur 行内校验 + aria-describedby;提交失败顶部错误摘要(role=alert,
|
||||
锚点跳字段);保存按钮 loading→成功/失败反馈;显式 label;tag 删除点击区 ≥24px;
|
||||
范围重叠与映射档未命中仅黄色提示、不拦截保存(D10/D6)。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
TRANSFER_SCOPE_FIELDS,
|
||||
TRANSFER_SCOPE_MATCHES,
|
||||
TRANSFORM_FIELDS,
|
||||
TRANSFORM_OPS,
|
||||
} from './transferTypes.api';
|
||||
import { useTransferTypesAdmin } from './useTransferTypesAdmin';
|
||||
|
||||
const { t } = useI18n();
|
||||
const {
|
||||
isLoading,
|
||||
search,
|
||||
statusFilter,
|
||||
filteredTypes,
|
||||
loadTypes,
|
||||
drawerOpen,
|
||||
editingCode,
|
||||
form,
|
||||
scopeDrafts,
|
||||
openCreate,
|
||||
openEdit,
|
||||
closeDrawer,
|
||||
fieldErrors,
|
||||
errorSummary,
|
||||
overlapCodes,
|
||||
warehouseChecks,
|
||||
validateField,
|
||||
clearFieldError,
|
||||
focusField,
|
||||
addScopeRule,
|
||||
removeScopeRule,
|
||||
commitScopeDraft,
|
||||
removeScopeValue,
|
||||
onScopeDraftBlur,
|
||||
addTransformRule,
|
||||
removeTransformRule,
|
||||
saving,
|
||||
saveButtonLabel,
|
||||
save,
|
||||
} = useTransferTypesAdmin();
|
||||
|
||||
const drawerTitle = computed(() => (
|
||||
editingCode.value
|
||||
? t('admin.transferTypes.drawerEditTitle')
|
||||
: t('admin.transferTypes.drawerCreateTitle')
|
||||
));
|
||||
|
||||
onMounted(() => {
|
||||
void loadTypes();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="transfer-types-page">
|
||||
<header class="page-heading">
|
||||
<div>
|
||||
<h2 data-testid="page-title">{{ t('admin.transferTypes.title') }}</h2>
|
||||
<p class="page-subtitle">{{ t('admin.transferTypes.subtitle') }}</p>
|
||||
</div>
|
||||
<button type="button" class="btn-primary" data-testid="create-type" @click="openCreate">
|
||||
+ {{ t('admin.transferTypes.createType') }}
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div class="list-toolbar">
|
||||
<label class="toolbar-field toolbar-search">
|
||||
<span>{{ t('admin.transferTypes.searchLabel') }}</span>
|
||||
<input
|
||||
v-model="search"
|
||||
class="input-field"
|
||||
data-testid="search-input"
|
||||
:placeholder="t('admin.transferTypes.searchPlaceholder')"
|
||||
>
|
||||
</label>
|
||||
<label class="toolbar-field">
|
||||
<span>{{ t('admin.transferTypes.statusLabel') }}</span>
|
||||
<select v-model="statusFilter" class="select-field" data-testid="status-filter">
|
||||
<option value="all">{{ t('admin.transferTypes.statusAll') }}</option>
|
||||
<option value="enabled">{{ t('admin.transferTypes.statusEnabled') }}</option>
|
||||
<option value="disabled">{{ t('admin.transferTypes.statusDisabled') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<p v-if="isLoading" class="loading-tip">{{ t('admin.transferTypes.loading') }}</p>
|
||||
|
||||
<div v-else-if="!filteredTypes.length" class="empty-state" data-testid="empty-state">
|
||||
<p class="empty-message">{{ t('admin.transferTypes.empty') }}</p>
|
||||
<p class="empty-hint">{{ t('admin.transferTypes.emptyHint') }}</p>
|
||||
<button type="button" class="btn-secondary" data-testid="empty-create" @click="openCreate">
|
||||
{{ t('admin.transferTypes.createType') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<table v-else class="type-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{{ t('admin.transferTypes.colCode') }}</th>
|
||||
<th>{{ t('admin.transferTypes.colName') }}</th>
|
||||
<th>{{ t('admin.transferTypes.colRules') }}</th>
|
||||
<th>{{ t('admin.transferTypes.colStatus') }}</th>
|
||||
<th>{{ t('admin.transferTypes.colActions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="(row, index) in filteredTypes" :key="row.code" data-testid="type-row">
|
||||
<td><strong>{{ row.code }}</strong></td>
|
||||
<td>{{ row.names?.['zh-CN'] || '-' }}</td>
|
||||
<td :data-testid="`rule-count-${index}`">{{ row.scope_rules?.length || 0 }}</td>
|
||||
<td>
|
||||
<span class="status-dot" :class="row.enabled ? 'on' : 'off'" aria-hidden="true"></span>
|
||||
<span>{{ row.enabled ? t('admin.transferTypes.enabled') : t('admin.transferTypes.disabled') }}</span>
|
||||
</td>
|
||||
<td>
|
||||
<button type="button" class="btn-secondary btn-sm" data-testid="edit-type" @click="openEdit(row)">
|
||||
{{ t('admin.transferTypes.edit') }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div v-if="drawerOpen" class="drawer-mask" @click.self="closeDrawer">
|
||||
<aside
|
||||
class="editor-drawer"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="drawerTitle"
|
||||
data-testid="type-drawer"
|
||||
>
|
||||
<header class="drawer-header">
|
||||
<h3>{{ drawerTitle }}</h3>
|
||||
<button type="button" class="drawer-close" :aria-label="t('admin.close')" data-testid="drawer-close" @click="closeDrawer">×</button>
|
||||
</header>
|
||||
|
||||
<form class="editor-form" autocomplete="off" @submit.prevent="save">
|
||||
<!-- 提交失败顶部错误摘要:role=alert、可聚焦,条目锚点跳到对应字段(行内错误保留) -->
|
||||
<div
|
||||
v-if="errorSummary.length"
|
||||
id="tt-error-summary"
|
||||
class="error-summary"
|
||||
role="alert"
|
||||
tabindex="-1"
|
||||
data-testid="error-summary"
|
||||
>
|
||||
<strong>{{ t('admin.transferTypes.errorSummaryTitle') }}</strong>
|
||||
<ul>
|
||||
<li v-for="item in errorSummary" :key="item.key">
|
||||
<button v-if="item.targetId" type="button" class="error-anchor" @click="focusField(item.key)">
|
||||
{{ item.message }}
|
||||
</button>
|
||||
<span v-else>{{ item.message }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<!-- ① 基本信息 -->
|
||||
<h4 class="section-title">{{ t('admin.transferTypes.sectionBasic') }}</h4>
|
||||
<div class="basic-grid">
|
||||
<div class="field-block">
|
||||
<label class="field" for="tt-code">
|
||||
<span>{{ t('admin.transferTypes.codeLabel') }} *</span>
|
||||
<input
|
||||
id="tt-code"
|
||||
v-model="form.code"
|
||||
class="input-field"
|
||||
data-testid="type-code"
|
||||
:disabled="Boolean(editingCode)"
|
||||
:aria-invalid="fieldErrors.code ? 'true' : undefined"
|
||||
:aria-describedby="fieldErrors.code ? 'tt-error-code' : undefined"
|
||||
@blur="validateField('code')"
|
||||
@input="clearFieldError('code')"
|
||||
>
|
||||
<small v-if="!editingCode">{{ t('admin.transferTypes.codeImmutableHint') }}</small>
|
||||
</label>
|
||||
<p v-if="fieldErrors.code" id="tt-error-code" class="field-error" data-testid="code-error">
|
||||
{{ fieldErrors.code }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="field-block">
|
||||
<label class="field" for="tt-name">
|
||||
<span>{{ t('admin.transferTypes.nameZhCnLabel') }}</span>
|
||||
<input
|
||||
id="tt-name"
|
||||
v-model="form.nameZhCn"
|
||||
class="input-field"
|
||||
data-testid="name-zh-CN"
|
||||
:aria-invalid="fieldErrors.name ? 'true' : undefined"
|
||||
:aria-describedby="fieldErrors.name ? 'tt-error-name' : undefined"
|
||||
@blur="validateField('name')"
|
||||
@input="clearFieldError('name')"
|
||||
>
|
||||
</label>
|
||||
<p v-if="fieldErrors.name" id="tt-error-name" class="field-error" data-testid="name-error">
|
||||
{{ fieldErrors.name }}
|
||||
</p>
|
||||
</div>
|
||||
<label class="field">
|
||||
<span>{{ t('admin.transferTypes.nameZhTwLabel') }}</span>
|
||||
<input v-model="form.nameZhTw" class="input-field" data-testid="name-zh-TW">
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>{{ t('admin.transferTypes.nameEnLabel') }}</span>
|
||||
<input v-model="form.nameEn" class="input-field" data-testid="name-en">
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>{{ t('admin.transferTypes.nameThLabel') }}</span>
|
||||
<input v-model="form.nameTh" class="input-field" data-testid="name-th">
|
||||
</label>
|
||||
<label class="field field-narrow">
|
||||
<span>{{ t('admin.transferTypes.sortLabel') }}</span>
|
||||
<input v-model.number="form.sortOrder" class="input-field" type="number" min="0" data-testid="sort-order">
|
||||
</label>
|
||||
<div class="field-block">
|
||||
<span class="field-label">{{ t('admin.transferTypes.enabledLabel') }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="status-switch"
|
||||
:class="{ on: form.enabled }"
|
||||
role="switch"
|
||||
:aria-checked="form.enabled"
|
||||
data-testid="enabled-switch"
|
||||
@click="form.enabled = !form.enabled"
|
||||
>
|
||||
<i></i><b>{{ form.enabled ? t('admin.transferTypes.enabled') : t('admin.transferTypes.disabled') }}</b>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ② 范围规则(规则间=且,规则内多值=或);重叠仅黄条提示不拦截(D10) -->
|
||||
<h4 class="section-title">
|
||||
{{ t('admin.transferTypes.sectionScope') }}
|
||||
<small class="section-hint">{{ t('admin.transferTypes.scopeHint') }}</small>
|
||||
</h4>
|
||||
<p
|
||||
v-if="overlapCodes.length"
|
||||
class="warning-banner"
|
||||
data-testid="scope-overlap-warning"
|
||||
>
|
||||
⚠ {{ t('admin.transferTypes.overlapWarning', { codes: overlapCodes.join('、') }) }}
|
||||
</p>
|
||||
<div
|
||||
v-for="(rule, index) in form.scopeRules"
|
||||
:key="`scope-rule-${index}`"
|
||||
class="scope-rule-row"
|
||||
:data-testid="`scope-rule-row-${index}`"
|
||||
>
|
||||
<div class="rule-cell">
|
||||
<label :for="`tt-scope-field-${index}`">
|
||||
<span>{{ t('admin.transferTypes.fieldLabel') }}</span>
|
||||
<select
|
||||
:id="`tt-scope-field-${index}`"
|
||||
v-model="rule.field"
|
||||
class="select-field"
|
||||
:data-testid="`scope-field-${index}`"
|
||||
:aria-invalid="fieldErrors[`scope-field-${index}`] ? 'true' : undefined"
|
||||
:aria-describedby="fieldErrors[`scope-field-${index}`] ? `tt-error-scope-field-${index}` : undefined"
|
||||
@change="clearFieldError(`scope-field-${index}`)"
|
||||
>
|
||||
<option value="">{{ t('admin.transferTypes.chooseField') }}</option>
|
||||
<option
|
||||
v-for="field in TRANSFER_SCOPE_FIELDS"
|
||||
:key="field"
|
||||
:value="field"
|
||||
>
|
||||
{{ t(`admin.transferTypes.scopeFieldLabels.${field}`) }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<p
|
||||
v-if="fieldErrors[`scope-field-${index}`]"
|
||||
:id="`tt-error-scope-field-${index}`"
|
||||
class="field-error"
|
||||
:data-testid="`scope-field-error-${index}`"
|
||||
>
|
||||
{{ fieldErrors[`scope-field-${index}`] }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="rule-cell">
|
||||
<label :for="`tt-scope-match-${index}`">
|
||||
<span>{{ t('admin.transferTypes.matchLabel') }}</span>
|
||||
<select
|
||||
:id="`tt-scope-match-${index}`"
|
||||
v-model="rule.match"
|
||||
class="select-field"
|
||||
:data-testid="`scope-match-${index}`"
|
||||
>
|
||||
<option
|
||||
v-for="match in TRANSFER_SCOPE_MATCHES"
|
||||
:key="match"
|
||||
:value="match"
|
||||
>
|
||||
{{ t(`admin.transferTypes.matchLabels.${match}`) }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="rule-cell rule-values">
|
||||
<label :for="`tt-scope-values-${index}`">
|
||||
<span>{{ t('admin.transferTypes.valuesLabel') }}</span>
|
||||
</label>
|
||||
<div class="tag-list">
|
||||
<span
|
||||
v-for="(value, valueIndex) in rule.values"
|
||||
:key="`${index}-${value}`"
|
||||
class="value-tag"
|
||||
:data-testid="`scope-tag-${index}-${valueIndex}`"
|
||||
>
|
||||
{{ value }}
|
||||
<button
|
||||
type="button"
|
||||
class="tag-remove"
|
||||
style="min-width: 24px; min-height: 24px;"
|
||||
:aria-label="t('admin.transferTypes.removeValue', { value })"
|
||||
:data-testid="`scope-tag-remove-${index}-${valueIndex}`"
|
||||
@click="removeScopeValue(index, valueIndex)"
|
||||
>✕</button>
|
||||
</span>
|
||||
<input
|
||||
:id="`tt-scope-values-${index}`"
|
||||
v-model="scopeDrafts[index]"
|
||||
class="input-field tag-input"
|
||||
:data-testid="`scope-value-input-${index}`"
|
||||
:placeholder="t('admin.transferTypes.valuesPlaceholder')"
|
||||
:aria-invalid="fieldErrors[`scope-values-${index}`] ? 'true' : undefined"
|
||||
:aria-describedby="fieldErrors[`scope-values-${index}`] ? `tt-error-scope-values-${index}` : undefined"
|
||||
@keydown.enter.prevent="commitScopeDraft(index)"
|
||||
@blur="onScopeDraftBlur(index)"
|
||||
>
|
||||
</div>
|
||||
<p
|
||||
v-if="fieldErrors[`scope-values-${index}`]"
|
||||
:id="`tt-error-scope-values-${index}`"
|
||||
class="field-error"
|
||||
:data-testid="`scope-values-error-${index}`"
|
||||
>
|
||||
{{ fieldErrors[`scope-values-${index}`] }}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-danger btn-sm rule-remove"
|
||||
:aria-label="t('admin.transferTypes.removeRule')"
|
||||
:data-testid="`remove-scope-rule-${index}`"
|
||||
@click="removeScopeRule(index)"
|
||||
>🗑</button>
|
||||
</div>
|
||||
<button type="button" class="btn-secondary btn-sm" data-testid="add-scope-rule" @click="addScopeRule">
|
||||
+ {{ t('admin.transferTypes.addScopeRule') }}
|
||||
</button>
|
||||
|
||||
<!-- ③ 仓库定义(拨出/拨入各一角色;映射档未命中仅黄色提示不拦截,D6) -->
|
||||
<h4 class="section-title">{{ t('admin.transferTypes.sectionWarehouse') }}</h4>
|
||||
<div
|
||||
v-for="role in (['from', 'to'] as const)"
|
||||
:key="role"
|
||||
class="warehouse-role"
|
||||
>
|
||||
<label class="field field-narrow">
|
||||
<span>{{ role === 'from' ? t('admin.transferTypes.warehouseFrom') : t('admin.transferTypes.warehouseTo') }}</span>
|
||||
<select
|
||||
v-model="form.warehouse[role].mode"
|
||||
class="select-field"
|
||||
:data-testid="`warehouse-${role}-mode`"
|
||||
@change="clearFieldError(`warehouse-${role}-code`)"
|
||||
>
|
||||
<option value="mapped">{{ t('admin.transferTypes.modeMapped') }}</option>
|
||||
<option value="fixed">{{ t('admin.transferTypes.modeFixed') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<template v-if="form.warehouse[role].mode === 'fixed'">
|
||||
<div class="field-block">
|
||||
<label class="field" :for="`tt-warehouse-${role}-code`">
|
||||
<span>{{ t('admin.transferTypes.fixedCodeLabel') }}</span>
|
||||
<input
|
||||
:id="`tt-warehouse-${role}-code`"
|
||||
v-model="form.warehouse[role].warehouseCode"
|
||||
class="input-field"
|
||||
:data-testid="`warehouse-${role}-code`"
|
||||
:aria-invalid="fieldErrors[`warehouse-${role}-code`] ? 'true' : undefined"
|
||||
:aria-describedby="fieldErrors[`warehouse-${role}-code`] ? `tt-error-warehouse-${role}-code` : undefined"
|
||||
@blur="validateField(`warehouse-${role}-code`)"
|
||||
@input="clearFieldError(`warehouse-${role}-code`)"
|
||||
>
|
||||
</label>
|
||||
<p
|
||||
v-if="fieldErrors[`warehouse-${role}-code`]"
|
||||
:id="`tt-error-warehouse-${role}-code`"
|
||||
class="field-error"
|
||||
:data-testid="`warehouse-${role}-code-error`"
|
||||
>
|
||||
{{ fieldErrors[`warehouse-${role}-code`] }}
|
||||
</p>
|
||||
</div>
|
||||
<label class="field">
|
||||
<span>{{ t('admin.transferTypes.orgLabel') }}</span>
|
||||
<input
|
||||
v-model="form.warehouse[role].externalOrg"
|
||||
class="input-field"
|
||||
:data-testid="`warehouse-${role}-org`"
|
||||
>
|
||||
<small>{{ t('admin.transferTypes.orgHint') }}</small>
|
||||
</label>
|
||||
<p
|
||||
v-if="warehouseChecks[role] === 'ok'"
|
||||
class="mapping-check ok"
|
||||
:data-testid="`warehouse-${role}-check`"
|
||||
>
|
||||
✓ {{ t('admin.transferTypes.mappingCheckOk') }}
|
||||
</p>
|
||||
<p
|
||||
v-else-if="warehouseChecks[role] === 'missing'"
|
||||
class="mapping-check missing"
|
||||
:data-testid="`warehouse-${role}-check`"
|
||||
>
|
||||
✕ {{ t('admin.transferTypes.mappingCheckMissing') }}
|
||||
</p>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- ④ 转换规则(受控词表:当前仅批号前缀替换) -->
|
||||
<h4 class="section-title">{{ t('admin.transferTypes.sectionTransform') }}</h4>
|
||||
<div
|
||||
v-for="(rule, index) in form.transformRules"
|
||||
:key="`transform-${index}`"
|
||||
class="transform-row"
|
||||
:data-testid="`transform-row-${index}`"
|
||||
>
|
||||
<label>
|
||||
<span>{{ t('admin.transferTypes.transformField') }}</span>
|
||||
<select v-model="rule.field" class="select-field" :data-testid="`transform-field-${index}`">
|
||||
<option
|
||||
v-for="field in TRANSFORM_FIELDS"
|
||||
:key="field"
|
||||
:value="field"
|
||||
>
|
||||
{{ t(`admin.transferTypes.transformFieldLabels.${field}`) }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>{{ t('admin.transferTypes.transformOp') }}</span>
|
||||
<select v-model="rule.op" class="select-field" :data-testid="`transform-op-${index}`">
|
||||
<option
|
||||
v-for="op in TRANSFORM_OPS"
|
||||
:key="op"
|
||||
:value="op"
|
||||
>
|
||||
{{ t(`admin.transferTypes.transformOpLabels.${op}`) }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<div class="field-block">
|
||||
<label :for="`tt-transform-source-${index}`">
|
||||
<span>{{ t('admin.transferTypes.transformSource') }}</span>
|
||||
<input
|
||||
:id="`tt-transform-source-${index}`"
|
||||
v-model="rule.source"
|
||||
class="input-field transform-input"
|
||||
:data-testid="`transform-source-${index}`"
|
||||
:aria-invalid="fieldErrors[`transform-source-${index}`] ? 'true' : undefined"
|
||||
:aria-describedby="fieldErrors[`transform-source-${index}`] ? `tt-error-transform-source-${index}` : undefined"
|
||||
@blur="validateField(`transform-source-${index}`)"
|
||||
@input="clearFieldError(`transform-source-${index}`)"
|
||||
>
|
||||
</label>
|
||||
<p
|
||||
v-if="fieldErrors[`transform-source-${index}`]"
|
||||
:id="`tt-error-transform-source-${index}`"
|
||||
class="field-error"
|
||||
:data-testid="`transform-source-error-${index}`"
|
||||
>
|
||||
{{ fieldErrors[`transform-source-${index}`] }}
|
||||
</p>
|
||||
</div>
|
||||
<span class="transform-arrow" aria-hidden="true">→</span>
|
||||
<div class="field-block">
|
||||
<label :for="`tt-transform-target-${index}`">
|
||||
<span>{{ t('admin.transferTypes.transformTarget') }}</span>
|
||||
<input
|
||||
:id="`tt-transform-target-${index}`"
|
||||
v-model="rule.target"
|
||||
class="input-field transform-input"
|
||||
:data-testid="`transform-target-${index}`"
|
||||
:aria-invalid="fieldErrors[`transform-target-${index}`] ? 'true' : undefined"
|
||||
:aria-describedby="fieldErrors[`transform-target-${index}`] ? `tt-error-transform-target-${index}` : undefined"
|
||||
@blur="validateField(`transform-target-${index}`)"
|
||||
@input="clearFieldError(`transform-target-${index}`)"
|
||||
>
|
||||
</label>
|
||||
<p
|
||||
v-if="fieldErrors[`transform-target-${index}`]"
|
||||
:id="`tt-error-transform-target-${index}`"
|
||||
class="field-error"
|
||||
:data-testid="`transform-target-error-${index}`"
|
||||
>
|
||||
{{ fieldErrors[`transform-target-${index}`] }}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-danger btn-sm rule-remove"
|
||||
:aria-label="t('admin.transferTypes.removeTransform')"
|
||||
:data-testid="`remove-transform-rule-${index}`"
|
||||
@click="removeTransformRule(index)"
|
||||
>🗑</button>
|
||||
</div>
|
||||
<button type="button" class="btn-secondary btn-sm" data-testid="add-transform-rule" @click="addTransformRule">
|
||||
+ {{ t('admin.transferTypes.addTransformRule') }}
|
||||
</button>
|
||||
|
||||
<div class="form-actions">
|
||||
<button type="button" class="btn-ghost btn-sm" data-testid="cancel-save" @click="closeDrawer">
|
||||
{{ t('admin.transferTypes.cancel') }}
|
||||
</button>
|
||||
<button type="button" class="btn-primary" :disabled="saving" data-testid="save-type" @click="save">
|
||||
{{ saveButtonLabel }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</aside>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.transfer-types-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
padding: 16px 20px;
|
||||
}
|
||||
|
||||
.page-heading {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.page-heading h2 {
|
||||
margin: 0;
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.page-subtitle {
|
||||
margin: 4px 0 0;
|
||||
color: #6b7280;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.list-toolbar {
|
||||
display: flex;
|
||||
gap: 16px;
|
||||
align-items: flex-end;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.toolbar-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: 12px;
|
||||
color: #6b7280;
|
||||
}
|
||||
|
||||
.toolbar-search .input-field {
|
||||
min-width: 260px;
|
||||
}
|
||||
|
||||
.loading-tip {
|
||||
color: #6b7280;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 48px 16px;
|
||||
border: 1px dashed #d1d5db;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.empty-message {
|
||||
margin: 0;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.empty-hint {
|
||||
margin: 0;
|
||||
color: #6b7280;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.type-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.type-table th,
|
||||
.type-table td {
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
padding: 10px 12px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.type-table th {
|
||||
color: #6b7280;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.status-dot {
|
||||
display: inline-block;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
margin-right: 6px;
|
||||
}
|
||||
|
||||
.status-dot.on {
|
||||
background: #16a34a;
|
||||
}
|
||||
|
||||
.status-dot.off {
|
||||
background: #9ca3af;
|
||||
}
|
||||
|
||||
/* 抽屉:右侧滑出,≥480px(框线图约束) */
|
||||
.drawer-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(15, 23, 42, 0.45);
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
z-index: 60;
|
||||
}
|
||||
|
||||
.editor-drawer {
|
||||
width: 560px;
|
||||
min-width: 480px;
|
||||
max-width: 92vw;
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
background: #fff;
|
||||
padding: 20px 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.drawer-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.drawer-header h3 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.drawer-close {
|
||||
border: none;
|
||||
background: transparent;
|
||||
font-size: 20px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
padding: 4px 8px;
|
||||
}
|
||||
|
||||
.editor-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.error-summary {
|
||||
border: 1px solid #fca5a5;
|
||||
background: #fef2f2;
|
||||
color: #b91c1c;
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.error-summary ul {
|
||||
margin: 6px 0 0;
|
||||
padding-left: 18px;
|
||||
}
|
||||
|
||||
.error-anchor {
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: #b91c1c;
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
margin: 8px 0 0;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
border-top: 1px solid #e5e7eb;
|
||||
padding-top: 12px;
|
||||
}
|
||||
|
||||
.section-hint {
|
||||
margin-left: 8px;
|
||||
color: #6b7280;
|
||||
font-weight: 400;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.basic-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px 16px;
|
||||
}
|
||||
|
||||
.field-block {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.field > span,
|
||||
.field-label {
|
||||
font-size: 12px;
|
||||
color: #6b7280;
|
||||
}
|
||||
|
||||
.field small {
|
||||
color: #9ca3af;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.field-narrow {
|
||||
max-width: 200px;
|
||||
}
|
||||
|
||||
.field-error {
|
||||
margin: 0;
|
||||
color: #dc2626;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.status-switch {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
border: 1px solid #d1d5db;
|
||||
border-radius: 999px;
|
||||
padding: 4px 12px 4px 6px;
|
||||
background: #f3f4f6;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.status-switch i {
|
||||
display: inline-block;
|
||||
position: relative;
|
||||
width: 28px;
|
||||
height: 16px;
|
||||
border-radius: 999px;
|
||||
background: #9ca3af;
|
||||
}
|
||||
|
||||
.status-switch i::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
left: 2px;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
transition: left 0.15s ease;
|
||||
}
|
||||
|
||||
.status-switch.on i {
|
||||
background: #16a34a;
|
||||
}
|
||||
|
||||
.status-switch.on i::after {
|
||||
left: 14px;
|
||||
}
|
||||
|
||||
.warning-banner {
|
||||
margin: 0;
|
||||
border: 1px solid #fcd34d;
|
||||
background: #fffbeb;
|
||||
color: #92400e;
|
||||
border-radius: 8px;
|
||||
padding: 8px 12px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.scope-rule-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(140px, 1.2fr) minmax(96px, 0.8fr) minmax(200px, 2fr) auto;
|
||||
gap: 10px;
|
||||
align-items: start;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
.rule-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.rule-cell > label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.rule-cell > label > span {
|
||||
font-size: 12px;
|
||||
color: #6b7280;
|
||||
}
|
||||
|
||||
.rule-remove {
|
||||
align-self: center;
|
||||
}
|
||||
|
||||
.tag-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.value-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
border: 1px solid #d1d5db;
|
||||
background: #f9fafb;
|
||||
border-radius: 999px;
|
||||
padding: 2px 4px 2px 10px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.tag-remove {
|
||||
border: none;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
border-radius: 50%;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.tag-input {
|
||||
min-width: 140px;
|
||||
flex: 1;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.warehouse-role {
|
||||
display: flex;
|
||||
gap: 16px;
|
||||
align-items: flex-start;
|
||||
flex-wrap: wrap;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
.mapping-check {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
align-self: center;
|
||||
}
|
||||
|
||||
.mapping-check.ok {
|
||||
color: #16a34a;
|
||||
}
|
||||
|
||||
.mapping-check.missing {
|
||||
color: #b45309;
|
||||
background: #fffbeb;
|
||||
border: 1px solid #fcd34d;
|
||||
border-radius: 6px;
|
||||
padding: 4px 8px;
|
||||
}
|
||||
|
||||
.transform-row {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: flex-end;
|
||||
flex-wrap: wrap;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
.transform-row > label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.transform-row > label > span {
|
||||
font-size: 12px;
|
||||
color: #6b7280;
|
||||
}
|
||||
|
||||
.transform-input {
|
||||
width: 90px;
|
||||
}
|
||||
|
||||
.transform-arrow {
|
||||
padding-bottom: 8px;
|
||||
color: #6b7280;
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
border-top: 1px solid #e5e7eb;
|
||||
padding-top: 12px;
|
||||
}
|
||||
</style>
|
||||
+500
@@ -0,0 +1,500 @@
|
||||
/**
|
||||
* features/admin/modules/transfer-types/__tests__/TransferTypesPage.spec.ts
|
||||
* 用途:锁定在途调拨「调拨类型」管理页的列表渲染、编辑抽屉四块(基本信息/范围规则/仓库定义/
|
||||
* 转换规则)、保存 payload 结构(规则间 AND)、onBlur 校验 + aria-describedby、顶部错误
|
||||
* 摘要锚点跳字段、保存 loading/成功/失败反馈、范围重叠与映射档未命中的黄色不拦截提示、
|
||||
* 空范围显式确认、tag 删除点击区 ≥24px、四语言 admin.json 键集一致与模块四处注册契约。
|
||||
* 依赖:@vue/test-utils、vitest、@/i18n、transferTypes.api(mock)、constants/modules、admin.routes。
|
||||
* 逻辑:mock transferTypes.api 控制列表/写入返回;交互按框线图与可用性规则逐条断言。
|
||||
*/
|
||||
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import i18n from '@/i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { config } from '@/config';
|
||||
import { ADMIN_MODULE_METAS } from '@/features/admin/constants/modules';
|
||||
import { adminRoutes } from '@/app/router/routes/admin.routes';
|
||||
import zhCnAdmin from '@/locales/zh-CN/admin.json';
|
||||
import zhTwAdmin from '@/locales/zh-TW/admin.json';
|
||||
import enAdmin from '@/locales/en/admin.json';
|
||||
import thAdmin from '@/locales/th/admin.json';
|
||||
import { TRANSFER_SCOPE_FIELDS } from '../transferTypes.api';
|
||||
import TransferTypesPage from '../TransferTypesPage.vue';
|
||||
|
||||
const apiMocks = vi.hoisted(() => ({
|
||||
listTransferTypes: vi.fn(),
|
||||
createTransferType: vi.fn(),
|
||||
updateTransferType: vi.fn(),
|
||||
listExternalWarehouseMappings: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../transferTypes.api', async () => {
|
||||
const actual = await vi.importActual<Record<string, unknown>>('../transferTypes.api');
|
||||
return {
|
||||
...actual,
|
||||
listTransferTypes: apiMocks.listTransferTypes,
|
||||
createTransferType: apiMocks.createTransferType,
|
||||
updateTransferType: apiMocks.updateTransferType,
|
||||
listExternalWarehouseMappings: apiMocks.listExternalWarehouseMappings,
|
||||
};
|
||||
});
|
||||
|
||||
enableAutoUnmount(afterEach);
|
||||
|
||||
// ---- 测试夹具:两条类型(一条启用带 1 条范围规则,一条停用空规则) ----
|
||||
const mappedRole = { mode: 'mapped', warehouse_code: null, external_org: null };
|
||||
const rowEnabled = {
|
||||
code: 'in_transit_to_hub',
|
||||
names: { 'zh-CN': '在途仓至HUB仓' },
|
||||
enabled: true,
|
||||
sort_order: 10,
|
||||
scope_rules: [{ field: 'doc_no', match: 'prefix', values: ['HOM', 'HOX'] }],
|
||||
warehouse_config: { from: mappedRole, to: mappedRole },
|
||||
transform_rules: [],
|
||||
description: null,
|
||||
updated_at: '2026-10-13T00:00:00',
|
||||
};
|
||||
const rowDisabled = {
|
||||
code: 'hub_repair_out',
|
||||
names: { 'zh-CN': 'HUB仓维修出' },
|
||||
enabled: false,
|
||||
sort_order: 20,
|
||||
scope_rules: [],
|
||||
warehouse_config: { from: mappedRole, to: mappedRole },
|
||||
transform_rules: [],
|
||||
description: null,
|
||||
updated_at: null,
|
||||
};
|
||||
const mappingRows = [
|
||||
{ external_system_code: 'ERP', in_transit_warehouse_code: 'WH-TRANSIT-01', external_warehouse_code: 'WH-HUB', external_organization_code: 'ORG-1' },
|
||||
];
|
||||
|
||||
const mountPage = async () => {
|
||||
// attachTo:错误摘要锚点跳字段依赖 document.getElementById + focus,必须真实挂载
|
||||
const wrapper = mount(TransferTypesPage, { attachTo: document.body, global: { plugins: [i18n] } });
|
||||
await flushPromises();
|
||||
return wrapper;
|
||||
};
|
||||
|
||||
const openCreateDrawer = async (wrapper: Awaited<ReturnType<typeof mountPage>>) => {
|
||||
await wrapper.find('[data-testid="create-type"]').trigger('click');
|
||||
// 打开抽屉会异步懒加载仓库映射档(存在性校验数据源),统一冲刷后再断言
|
||||
await flushPromises();
|
||||
};
|
||||
|
||||
/**
|
||||
* 在新建抽屉里填齐必填项并配置一条范围规则(field/match/value),供保存类测试复用。
|
||||
* 关键断言意图:value 通过「输入 + Enter」提交为 tag,模拟真实多值编辑路径。
|
||||
*/
|
||||
const fillCreateFormWithRule = async (wrapper: Awaited<ReturnType<typeof mountPage>>, code = 'wtp_to_how') => {
|
||||
await openCreateDrawer(wrapper);
|
||||
await wrapper.find('[data-testid="type-code"]').setValue(code);
|
||||
await wrapper.find('[data-testid="name-zh-CN"]').setValue('WTP转HOW');
|
||||
await wrapper.find('[data-testid="add-scope-rule"]').trigger('click');
|
||||
await wrapper.find('[data-testid="scope-field-0"]').setValue('doc_no');
|
||||
await wrapper.find('[data-testid="scope-match-0"]').setValue('prefix');
|
||||
await wrapper.find('[data-testid="scope-value-input-0"]').setValue('HOM');
|
||||
await wrapper.find('[data-testid="scope-value-input-0"]').trigger('keydown.enter');
|
||||
};
|
||||
|
||||
describe('TransferTypesPage 列表渲染', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
apiMocks.listTransferTypes.mockResolvedValue([rowEnabled, rowDisabled]);
|
||||
apiMocks.listExternalWarehouseMappings.mockResolvedValue(mappingRows);
|
||||
});
|
||||
|
||||
it('渲染列表行:编码/名称/规则数/状态/编辑', async () => {
|
||||
const wrapper = await mountPage();
|
||||
const rows = wrapper.findAll('[data-testid="type-row"]');
|
||||
// 关键断言:两行数据齐全,启用行规则数=1、状态=启用;停用行规则数=0、状态=停用
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows[0].text()).toContain('in_transit_to_hub');
|
||||
expect(rows[0].text()).toContain('在途仓至HUB仓');
|
||||
expect(rows[0].find('[data-testid="rule-count-0"]').text()).toBe('1');
|
||||
expect(rows[0].text()).toContain('启用');
|
||||
expect(rows[1].find('[data-testid="rule-count-1"]').text()).toBe('0');
|
||||
expect(rows[1].text()).toContain('停用');
|
||||
expect(wrapper.findAll('[data-testid="edit-type"]')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('空列表渲染空态:消息 + 新建类型行动按钮', async () => {
|
||||
// 关键断言:空态必须「消息+行动」成对出现(可用性规则⑤)
|
||||
apiMocks.listTransferTypes.mockResolvedValue([]);
|
||||
const wrapper = await mountPage();
|
||||
const empty = wrapper.find('[data-testid="empty-state"]');
|
||||
expect(empty.exists()).toBe(true);
|
||||
expect(empty.text()).toContain('暂无调拨类型');
|
||||
expect(empty.find('[data-testid="empty-create"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('搜索编码/名称与状态筛选联动过滤列表', async () => {
|
||||
const wrapper = await mountPage();
|
||||
// 按中文名称搜索「维修」只命中停用行
|
||||
await wrapper.find('[data-testid="search-input"]').setValue('维修');
|
||||
expect(wrapper.findAll('[data-testid="type-row"]')).toHaveLength(1);
|
||||
expect(wrapper.find('[data-testid="type-row"]').text()).toContain('hub_repair_out');
|
||||
// 状态筛选=启用 时清空搜索,只命中启用行
|
||||
await wrapper.find('[data-testid="search-input"]').setValue('');
|
||||
await wrapper.find('[data-testid="status-filter"]').setValue('enabled');
|
||||
expect(wrapper.findAll('[data-testid="type-row"]')).toHaveLength(1);
|
||||
expect(wrapper.find('[data-testid="type-row"]').text()).toContain('in_transit_to_hub');
|
||||
});
|
||||
});
|
||||
|
||||
describe('TransferTypesPage 编辑抽屉基础块', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
apiMocks.listTransferTypes.mockResolvedValue([rowEnabled, rowDisabled]);
|
||||
apiMocks.listExternalWarehouseMappings.mockResolvedValue(mappingRows);
|
||||
});
|
||||
|
||||
it('编辑态打开抽屉:dialog 语义、编码只读且回显、名称四语言输入框齐全', async () => {
|
||||
const wrapper = await mountPage();
|
||||
await wrapper.findAll('[data-testid="edit-type"]')[0].trigger('click');
|
||||
const drawer = wrapper.find('[data-testid="type-drawer"]');
|
||||
// 关键断言:抽屉是 dialog 且编码创建后不可变(disabled + 回显)
|
||||
expect(drawer.exists()).toBe(true);
|
||||
expect(drawer.attributes('role')).toBe('dialog');
|
||||
const code = wrapper.find('[data-testid="type-code"]');
|
||||
expect((code.element as HTMLInputElement).disabled).toBe(true);
|
||||
expect((code.element as HTMLInputElement).value).toBe('in_transit_to_hub');
|
||||
// 名称四语言(zh-CN 必填)+ 排序 + 启用开关
|
||||
for (const key of ['name-zh-CN', 'name-zh-TW', 'name-en', 'name-th']) {
|
||||
expect(wrapper.find(`[data-testid="${key}"]`).exists()).toBe(true);
|
||||
}
|
||||
expect((wrapper.find('[data-testid="name-zh-CN"]').element as HTMLInputElement).value).toBe('在途仓至HUB仓');
|
||||
expect((wrapper.find('[data-testid="sort-order"]').element as HTMLInputElement).value).toBe('10');
|
||||
expect(wrapper.find('[data-testid="enabled-switch"]').attributes('aria-checked')).toBe('true');
|
||||
});
|
||||
|
||||
it('仓库定义 mode 切换:fixed 才显示仓库编码与法人覆盖输入', async () => {
|
||||
const wrapper = await mountPage();
|
||||
await openCreateDrawer(wrapper);
|
||||
// 关键断言:默认映射档不渲染固定仓库输入;切 fixed 出现,切回 mapped 消失
|
||||
expect(wrapper.find('[data-testid="warehouse-from-code"]').exists()).toBe(false);
|
||||
await wrapper.find('[data-testid="warehouse-from-mode"]').setValue('fixed');
|
||||
expect(wrapper.find('[data-testid="warehouse-from-code"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="warehouse-from-org"]').exists()).toBe(true);
|
||||
await wrapper.find('[data-testid="warehouse-from-mode"]').setValue('mapped');
|
||||
expect(wrapper.find('[data-testid="warehouse-from-code"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('映射档存在性校验:命中=✓ 提示、未命中=黄色✕ 提示,且均不拦截保存', async () => {
|
||||
// 本测试聚焦仓库校验,不放范围规则;空范围确认放行(默认拒绝语义不在此验证)
|
||||
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||
const wrapper = await mountPage();
|
||||
await openCreateDrawer(wrapper);
|
||||
await wrapper.find('[data-testid="type-code"]').setValue('wtp_to_how');
|
||||
await wrapper.find('[data-testid="name-zh-CN"]').setValue('WTP转HOW');
|
||||
await wrapper.find('[data-testid="warehouse-from-mode"]').setValue('fixed');
|
||||
// 未命中:黄色提示但不拦截
|
||||
await wrapper.find('[data-testid="warehouse-from-code"]').setValue('WH-REPAIR');
|
||||
const missing = wrapper.find('[data-testid="warehouse-from-check"]');
|
||||
expect(missing.exists()).toBe(true);
|
||||
expect(missing.text()).toContain('映射档未找到');
|
||||
// 拨入仓命中:✓ 提示
|
||||
await wrapper.find('[data-testid="warehouse-to-mode"]').setValue('fixed');
|
||||
await wrapper.find('[data-testid="warehouse-to-code"]').setValue('WH-HUB');
|
||||
expect(wrapper.find('[data-testid="warehouse-to-check"]').text()).toContain('映射档已包含');
|
||||
// 关键断言:映射档未命中不拦截保存(D6/D10),payload 固定仓 + 法人覆盖正确
|
||||
await wrapper.find('[data-testid="save-type"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(apiMocks.createTransferType).toHaveBeenCalledTimes(1);
|
||||
const payload = apiMocks.createTransferType.mock.calls[0][0];
|
||||
expect(payload.warehouse_config.from).toEqual({ mode: 'fixed', warehouse_code: 'WH-REPAIR', external_org: null });
|
||||
expect(payload.warehouse_config.to).toEqual({ mode: 'fixed', warehouse_code: 'WH-HUB', external_org: null });
|
||||
// 法人覆盖非空时透传
|
||||
await openCreateDrawer(wrapper);
|
||||
await wrapper.find('[data-testid="type-code"]').setValue('wtp_to_how2');
|
||||
await wrapper.find('[data-testid="name-zh-CN"]').setValue('WTP转HOW2');
|
||||
await wrapper.find('[data-testid="warehouse-from-mode"]').setValue('fixed');
|
||||
await wrapper.find('[data-testid="warehouse-from-code"]').setValue('WH-REPAIR');
|
||||
await wrapper.find('[data-testid="warehouse-from-org"]').setValue('ORG-X');
|
||||
await wrapper.find('[data-testid="save-type"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(apiMocks.createTransferType.mock.calls[1][0].warehouse_config.from).toEqual({ mode: 'fixed', warehouse_code: 'WH-REPAIR', external_org: 'ORG-X' });
|
||||
confirmSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('TransferTypesPage 范围规则与转换规则编辑器', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
apiMocks.listTransferTypes.mockResolvedValue([rowEnabled, rowDisabled]);
|
||||
apiMocks.listExternalWarehouseMappings.mockResolvedValue(mappingRows);
|
||||
});
|
||||
|
||||
it('添加规则:字段下拉=受控词表 18 项、匹配四选一、值输入 Enter 生成 tag', async () => {
|
||||
const wrapper = await mountPage();
|
||||
await openCreateDrawer(wrapper);
|
||||
await wrapper.find('[data-testid="add-scope-rule"]').trigger('click');
|
||||
const fieldOptions = wrapper.find('[data-testid="scope-field-0"]').findAll('option');
|
||||
// 关键断言:占位项 + 后端受控词表 18 字段,label 走 i18n(收料单号等)
|
||||
expect(fieldOptions).toHaveLength(1 + TRANSFER_SCOPE_FIELDS.length);
|
||||
const optionTexts = fieldOptions.map((o) => o.text());
|
||||
expect(optionTexts).toContain('收料单号');
|
||||
expect(optionTexts).toContain('供应商·客户编号');
|
||||
const matchTexts = wrapper.find('[data-testid="scope-match-0"]').findAll('option').map((o) => o.text());
|
||||
expect(matchTexts).toEqual(['前缀', '等于', '包含', '属于']);
|
||||
// Enter 提交 tag;重复值去重
|
||||
await wrapper.find('[data-testid="scope-field-0"]').setValue('doc_no');
|
||||
await wrapper.find('[data-testid="scope-value-input-0"]').setValue('HOM');
|
||||
await wrapper.find('[data-testid="scope-value-input-0"]').trigger('keydown.enter');
|
||||
expect(wrapper.find('[data-testid="scope-tag-0-0"]').exists()).toBe(true);
|
||||
await wrapper.find('[data-testid="scope-value-input-0"]').setValue('HOM, HOX');
|
||||
await wrapper.find('[data-testid="scope-value-input-0"]').trigger('keydown.enter');
|
||||
expect(wrapper.findAll('[data-testid="scope-tag-0-0"], [data-testid="scope-tag-0-1"]')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('tag 删除按钮点击区 ≥24px 且可删除值', async () => {
|
||||
const wrapper = await mountPage();
|
||||
await openCreateDrawer(wrapper);
|
||||
await wrapper.find('[data-testid="add-scope-rule"]').trigger('click');
|
||||
await wrapper.find('[data-testid="scope-field-0"]').setValue('doc_no');
|
||||
await wrapper.find('[data-testid="scope-value-input-0"]').setValue('HOM');
|
||||
await wrapper.find('[data-testid="scope-value-input-0"]').trigger('keydown.enter');
|
||||
const remove = wrapper.find('[data-testid="scope-tag-remove-0-0"]');
|
||||
// 关键断言:点击区最小 24px(可用性规则④),删除后 tag 消失
|
||||
expect(remove.attributes('style')).toContain('24px');
|
||||
await remove.trigger('click');
|
||||
expect(wrapper.find('[data-testid="scope-tag-0-0"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('失焦提交值草稿为 tag,且空值规则失焦后行内报错并 aria-describedby 关联', async () => {
|
||||
const wrapper = await mountPage();
|
||||
await openCreateDrawer(wrapper);
|
||||
await wrapper.find('[data-testid="add-scope-rule"]').trigger('click');
|
||||
await wrapper.find('[data-testid="scope-field-0"]').setValue('doc_no');
|
||||
// 未输入值直接失焦 → 字段正下方行内错误(可用性规则①)
|
||||
await wrapper.find('[data-testid="scope-value-input-0"]').setValue('HOM');
|
||||
await wrapper.find('[data-testid="scope-value-input-0"]').trigger('blur');
|
||||
// 失焦先提交草稿 → 有值不报错
|
||||
expect(wrapper.find('[data-testid="scope-tag-0-0"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="scope-values-error-0"]').exists()).toBe(false);
|
||||
// 删掉 tag 后失焦 → 行内错误 + aria-describedby
|
||||
await wrapper.find('[data-testid="scope-tag-remove-0-0"]').trigger('click');
|
||||
await wrapper.find('[data-testid="scope-value-input-0"]').trigger('blur');
|
||||
const error = wrapper.find('[data-testid="scope-values-error-0"]');
|
||||
expect(error.exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="scope-value-input-0"]').attributes('aria-describedby')).toBe(error.attributes('id'));
|
||||
});
|
||||
|
||||
it('保存 payload:scope_rules 为规则对象数组(规则间 AND),多值为 OR 数组', async () => {
|
||||
const wrapper = await mountPage();
|
||||
await fillCreateFormWithRule(wrapper);
|
||||
// 第二条规则(规则间 AND)
|
||||
await wrapper.find('[data-testid="add-scope-rule"]').trigger('click');
|
||||
await wrapper.find('[data-testid="scope-field-1"]').setValue('source_code');
|
||||
await wrapper.find('[data-testid="scope-match-1"]').setValue('in');
|
||||
await wrapper.find('[data-testid="scope-value-input-1"]').setValue('SRC-A, SRC-B');
|
||||
await wrapper.find('[data-testid="scope-value-input-1"]').trigger('keydown.enter');
|
||||
await wrapper.find('[data-testid="save-type"]').trigger('click');
|
||||
await flushPromises();
|
||||
// 关键断言:payload.scope_rules 保序两条规则,多值成数组(或关系),即 AND-of-OR 结构
|
||||
expect(apiMocks.createTransferType).toHaveBeenCalledTimes(1);
|
||||
const payload = apiMocks.createTransferType.mock.calls[0][0];
|
||||
expect(payload.scope_rules).toEqual([
|
||||
{ field: 'doc_no', match: 'prefix', values: ['HOM'] },
|
||||
{ field: 'source_code', match: 'in', values: ['SRC-A', 'SRC-B'] },
|
||||
]);
|
||||
expect(payload.code).toBe('wtp_to_how');
|
||||
expect(payload.names['zh-CN']).toBe('WTP转HOW');
|
||||
expect(payload.enabled).toBe(true);
|
||||
expect(payload.sort_order).toBe(10);
|
||||
expect(payload.warehouse_config.from).toEqual({ mode: 'mapped', warehouse_code: null, external_org: null });
|
||||
});
|
||||
|
||||
it('编辑保存走 PUT,转换规则行可添加并写入 payload', async () => {
|
||||
const wrapper = await mountPage();
|
||||
await wrapper.findAll('[data-testid="edit-type"]')[0].trigger('click');
|
||||
await wrapper.find('[data-testid="add-transform-rule"]').trigger('click');
|
||||
expect(wrapper.find('[data-testid="transform-row-0"]').exists()).toBe(true);
|
||||
await wrapper.find('[data-testid="transform-source-0"]').setValue('WTP');
|
||||
await wrapper.find('[data-testid="transform-target-0"]').setValue('HOW');
|
||||
await wrapper.find('[data-testid="save-type"]').trigger('click');
|
||||
await flushPromises();
|
||||
// 关键断言:编辑态走 updateTransferType(code 不可变),转换规则含字段/方式/前后缀
|
||||
expect(apiMocks.updateTransferType).toHaveBeenCalledTimes(1);
|
||||
expect(apiMocks.updateTransferType.mock.calls[0][0]).toBe('in_transit_to_hub');
|
||||
expect(apiMocks.updateTransferType.mock.calls[0][1].transform_rules).toEqual([
|
||||
{ field: 'lot_no', op: 'prefix_replace', source: 'WTP', target: 'HOW' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('范围重叠:与其它启用类型字段+值有交集时黄条列出冲突编码,但不拦截保存', async () => {
|
||||
const wrapper = await mountPage();
|
||||
// doc_no 值 HOM 与启用行 rowEnabled 的 [HOM, HOX] 有交集(匹配方式不同也提示)
|
||||
await fillCreateFormWithRule(wrapper);
|
||||
const warning = wrapper.find('[data-testid="scope-overlap-warning"]');
|
||||
expect(warning.exists()).toBe(true);
|
||||
expect(warning.text()).toContain('in_transit_to_hub');
|
||||
// 关键断言:重叠仅黄条提示,保存照常提交(D10)
|
||||
await wrapper.find('[data-testid="save-type"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(apiMocks.createTransferType).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('编辑自身不与自身重叠;与停用类型不提示', async () => {
|
||||
const wrapper = await mountPage();
|
||||
await wrapper.findAll('[data-testid="edit-type"]')[0].trigger('click');
|
||||
// 自身规则就是 [HOM, HOX],编辑自身不应把自身算入冲突
|
||||
expect(wrapper.find('[data-testid="scope-overlap-warning"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TransferTypesPage 校验、错误摘要与保存反馈', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
apiMocks.listTransferTypes.mockResolvedValue([rowEnabled, rowDisabled]);
|
||||
apiMocks.listExternalWarehouseMappings.mockResolvedValue(mappingRows);
|
||||
});
|
||||
|
||||
it('onBlur 校验:编码必填/格式错误在字段正下方展示并 aria-describedby 关联', async () => {
|
||||
const wrapper = await mountPage();
|
||||
await openCreateDrawer(wrapper);
|
||||
await wrapper.find('[data-testid="type-code"]').setValue('');
|
||||
await wrapper.find('[data-testid="type-code"]').trigger('blur');
|
||||
const error = wrapper.find('[data-testid="code-error"]');
|
||||
// 关键断言:行内错误(非只弹 toast)且 aria-describedby 指向错误元素 id
|
||||
expect(error.exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="type-code"]').attributes('aria-describedby')).toBe(error.attributes('id'));
|
||||
await wrapper.find('[data-testid="type-code"]').setValue('ABC');
|
||||
await wrapper.find('[data-testid="type-code"]').trigger('blur');
|
||||
expect(wrapper.find('[data-testid="code-error"]').text()).toContain('小写字母');
|
||||
});
|
||||
|
||||
it('zh-CN 名称 onBlur 必填校验', async () => {
|
||||
const wrapper = await mountPage();
|
||||
await openCreateDrawer(wrapper);
|
||||
await wrapper.find('[data-testid="name-zh-CN"]').setValue('');
|
||||
await wrapper.find('[data-testid="name-zh-CN"]').trigger('blur');
|
||||
expect(wrapper.find('[data-testid="name-error"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('提交失败渲染顶部错误摘要(role=alert),锚点跳到对应字段且行内错误保留', async () => {
|
||||
const wrapper = await mountPage();
|
||||
await openCreateDrawer(wrapper);
|
||||
await wrapper.find('[data-testid="save-type"]').trigger('click');
|
||||
const summary = wrapper.find('[data-testid="error-summary"]');
|
||||
// 关键断言:错误摘要 role=alert 顶部呈现(可用性规则②)
|
||||
expect(summary.exists()).toBe(true);
|
||||
expect(summary.attributes('role')).toBe('alert');
|
||||
expect(summary.text()).toContain('请输入调拨类型编码');
|
||||
// 点击摘要条目 → 焦点跳到编码输入框;行内错误保留
|
||||
await summary.find('button').trigger('click');
|
||||
expect(document.activeElement).toBe(wrapper.find('[data-testid="type-code"]').element);
|
||||
expect(wrapper.find('[data-testid="code-error"]').exists()).toBe(true);
|
||||
expect(apiMocks.createTransferType).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('保存按钮 loading 反馈:请求挂起时显示保存中并禁用', async () => {
|
||||
const wrapper = await mountPage();
|
||||
await fillCreateFormWithRule(wrapper);
|
||||
apiMocks.createTransferType.mockImplementation(() => new Promise(() => {}));
|
||||
await wrapper.find('[data-testid="save-type"]').trigger('click');
|
||||
const save = wrapper.find('[data-testid="save-type"]');
|
||||
// 关键断言:loading 态文案切换 + 禁用防重复提交(可用性规则③)
|
||||
expect(save.text()).toContain('保存中');
|
||||
expect(save.attributes('disabled')).toBeDefined();
|
||||
});
|
||||
|
||||
it('保存成功:提示反馈、抽屉关闭并刷新列表', async () => {
|
||||
const wrapper = await mountPage();
|
||||
await fillCreateFormWithRule(wrapper);
|
||||
apiMocks.createTransferType.mockResolvedValue({ ...rowEnabled, code: 'wtp_to_how' });
|
||||
expect(apiMocks.listTransferTypes).toHaveBeenCalledTimes(1);
|
||||
await wrapper.find('[data-testid="save-type"]').trigger('click');
|
||||
await flushPromises();
|
||||
// 关键断言:成功后抽屉关闭 + 列表重新拉取(成功反馈)
|
||||
expect(wrapper.find('[data-testid="type-drawer"]').exists()).toBe(false);
|
||||
expect(apiMocks.listTransferTypes).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('保存失败:BusinessError 文案进入顶部摘要,抽屉保留可改', async () => {
|
||||
const wrapper = await mountPage();
|
||||
await fillCreateFormWithRule(wrapper);
|
||||
apiMocks.createTransferType.mockRejectedValue(
|
||||
new BusinessError({ message: '调拨类型编码已存在。', code: 'TRANSFER.TRANSFER_TYPE_CODE_EXISTS' }),
|
||||
);
|
||||
await wrapper.find('[data-testid="save-type"]').trigger('click');
|
||||
await flushPromises();
|
||||
// 关键断言:失败后抽屉不关闭、错误码本地化文案进摘要(四语言 errors.json 契约)
|
||||
expect(wrapper.find('[data-testid="type-drawer"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="error-summary"]').text()).toContain('编码已存在');
|
||||
expect((wrapper.find('[data-testid="save-type"]').element as HTMLButtonElement).disabled).toBe(false);
|
||||
});
|
||||
|
||||
it('空范围规则保存需显式确认:拒绝不发请求,确认则携带 allow_empty_scope_rules', async () => {
|
||||
const confirmSpy = vi.spyOn(window, 'confirm');
|
||||
const wrapper = await mountPage();
|
||||
await openCreateDrawer(wrapper);
|
||||
await wrapper.find('[data-testid="type-code"]').setValue('no_scope');
|
||||
await wrapper.find('[data-testid="name-zh-CN"]').setValue('无范围类型');
|
||||
confirmSpy.mockReturnValue(false);
|
||||
await wrapper.find('[data-testid="save-type"]').trigger('click');
|
||||
// 关键断言:拒绝确认 → 不发请求(对齐后端 fail-closed 门禁)
|
||||
expect(confirmSpy).toHaveBeenCalledTimes(1);
|
||||
expect(apiMocks.createTransferType).not.toHaveBeenCalled();
|
||||
confirmSpy.mockReturnValue(true);
|
||||
await wrapper.find('[data-testid="save-type"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(apiMocks.createTransferType).toHaveBeenCalledTimes(1);
|
||||
expect(apiMocks.createTransferType.mock.calls[0][0].allow_empty_scope_rules).toBe(true);
|
||||
confirmSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('TransferTypesPage i18n 与模块注册契约', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
apiMocks.listTransferTypes.mockResolvedValue([]);
|
||||
apiMocks.listExternalWarehouseMappings.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it('四个 locale 的 admin.json transferTypes 键集一致且含模块/导航键', () => {
|
||||
// 关键断言:四语言键集完全一致(i18n 红线),导航键与页面标题键齐备
|
||||
const flatKeys = (obj: unknown, prefix = ''): string[] => {
|
||||
if (obj === null || typeof obj !== 'object') return prefix ? [prefix] : [];
|
||||
return Object.entries(obj as Record<string, unknown>)
|
||||
.flatMap(([key, value]) => flatKeys(value, prefix ? `${prefix}.${key}` : key))
|
||||
.sort();
|
||||
};
|
||||
const base = flatKeys(zhCnAdmin.transferTypes);
|
||||
expect(base.length).toBeGreaterThan(30);
|
||||
expect(flatKeys(zhTwAdmin.transferTypes)).toEqual(base);
|
||||
expect(flatKeys(enAdmin.transferTypes)).toEqual(base);
|
||||
expect(flatKeys(thAdmin.transferTypes)).toEqual(base);
|
||||
for (const messages of [zhCnAdmin, zhTwAdmin, enAdmin, thAdmin] as const) {
|
||||
expect(String((messages.nav as Record<string, unknown>).transferTypes)).toBeTruthy();
|
||||
expect(String((messages.transferTypes as Record<string, unknown>).title)).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
it('范围规则字段标签覆盖后端受控词表 18 字段(zh-CN)', () => {
|
||||
// 关键断言:受控词表逐字段有标签且不多不少(后端引擎校验,前端下拉固定 18 项)
|
||||
const labels = zhCnAdmin.transferTypes.scopeFieldLabels as Record<string, string>;
|
||||
expect(Object.keys(labels)).toHaveLength(TRANSFER_SCOPE_FIELDS.length);
|
||||
TRANSFER_SCOPE_FIELDS.forEach((field) => {
|
||||
expect(labels[field]).toBeTruthy();
|
||||
});
|
||||
expect(labels.doc_no).toBe('收料单号');
|
||||
expect(labels.source_code).toBe('收料来源实例');
|
||||
expect(labels.partner_code).toBe('供应商·客户编号');
|
||||
});
|
||||
|
||||
it('模块注册四处齐全:meta / 路由 / config 开关 / 导航标签', () => {
|
||||
// 关键断言:AdminModuleId 注册表、深链路由、config 开关、导航 labelKey 四处一致
|
||||
const meta = ADMIN_MODULE_METAS.find((item) => item.id === 'transfer_types');
|
||||
expect(meta).toEqual(expect.objectContaining({
|
||||
routeName: 'AdminTransferTypes',
|
||||
path: 'transfer-types',
|
||||
labelKey: 'admin.nav.transferTypes',
|
||||
configKey: 'transfer_types',
|
||||
}));
|
||||
const route = adminRoutes[0].children?.find((item) => item.name === 'AdminTransferTypes');
|
||||
expect(route?.path).toBe('transfer-types');
|
||||
expect(route?.meta).toEqual(expect.objectContaining({ requiresAdmin: true, adminModule: 'transfer_types' }));
|
||||
expect(config.admin.modules.transfer_types).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* features/admin/modules/transfer-types/transferTypes.api.ts
|
||||
* 用途:在途调拨「调拨类型」管理 API 客户端(列表/创建/更新),附仓库映射档查询
|
||||
* (固定仓库存在性黄色提示用)与范围/转换规则受控词表常量(ADR 0002 类型配置化)。
|
||||
* 依赖:@/shared/api/client(requestJson / BusinessError)。
|
||||
* 逻辑:薄封装 /api/admin/in-transit-transfer/transfer-types*;错误码(TRANSFER.*)
|
||||
* 由 requestJson 解析为四语言 errors.json 文案后以 BusinessError 抛出。
|
||||
* 词表常量与后端 scope_rules.SCOPE_FIELDS / field_transforms 保持一致,后端仍会兜底校验。
|
||||
*/
|
||||
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
|
||||
const BASE = '/api/admin/in-transit-transfer';
|
||||
|
||||
/** 范围规则字段受控词表(与后端 SCOPE_FIELDS 一致;下拉固定 18 项,新增须同步后端)。 */
|
||||
export const TRANSFER_SCOPE_FIELDS = [
|
||||
'source_code', 'doc_no', 'warehouse_code', 'storage_code', 'lot_no',
|
||||
'movement_date', 'record_kind', 'in_out_flag', 'order_type', 'odm_id',
|
||||
'odm_name', 'carton_id', 'pallet_id', 'material_code', 'doc_nature',
|
||||
'movement_type', 'reason_code', 'partner_code',
|
||||
] as const;
|
||||
|
||||
/** 匹配方式受控词表(与后端 _MATCHES 一致)。 */
|
||||
export const TRANSFER_SCOPE_MATCHES = ['prefix', 'equals', 'contains', 'in'] as const;
|
||||
|
||||
/** 转换规则字段/方式受控词表(与后端 TRANSFORM_FIELDS / TRANSFORM_OPS 一致)。 */
|
||||
export const TRANSFORM_FIELDS = ['lot_no'] as const;
|
||||
export const TRANSFORM_OPS = ['prefix_replace'] as const;
|
||||
|
||||
export type TransferScopeField = (typeof TRANSFER_SCOPE_FIELDS)[number];
|
||||
export type TransferScopeMatch = (typeof TRANSFER_SCOPE_MATCHES)[number];
|
||||
|
||||
/** 单条范围规则:规则间 AND,规则内 values 为 OR。 */
|
||||
export interface TransferScopeRule {
|
||||
field: string;
|
||||
match: string;
|
||||
values: string[];
|
||||
}
|
||||
|
||||
/** 仓库角色:mapped 沿用映射档;fixed 覆盖仓库编码,external_org 非空才覆盖法人。 */
|
||||
export interface TransferWarehouseRole {
|
||||
mode: 'mapped' | 'fixed';
|
||||
warehouse_code: string | null;
|
||||
external_org: string | null;
|
||||
}
|
||||
|
||||
/** 单条字段转换规则(当前仅批号前缀替换)。 */
|
||||
export interface TransferTransformRule {
|
||||
field: string;
|
||||
op: string;
|
||||
source: string;
|
||||
target: string;
|
||||
}
|
||||
|
||||
/** 创建/更新 payload(code 创建后不可变;空范围规则需显式 allow_empty_scope_rules)。 */
|
||||
export interface TransferTypePayload {
|
||||
code: string;
|
||||
names: Record<string, string>;
|
||||
enabled: boolean;
|
||||
sort_order: number;
|
||||
scope_rules: TransferScopeRule[];
|
||||
warehouse_config: { from: TransferWarehouseRole; to: TransferWarehouseRole };
|
||||
transform_rules: TransferTransformRule[];
|
||||
allow_empty_scope_rules?: boolean;
|
||||
}
|
||||
|
||||
/** 管理端类型配置全量视图(列表与写响应同形)。 */
|
||||
export interface TransferTypeRow {
|
||||
code: string;
|
||||
names: Record<string, string>;
|
||||
enabled: boolean;
|
||||
sort_order: number;
|
||||
scope_rules: TransferScopeRule[];
|
||||
warehouse_config: { from: TransferWarehouseRole; to: TransferWarehouseRole };
|
||||
transform_rules: TransferTransformRule[];
|
||||
description: string | null;
|
||||
updated_at: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 全量类型配置(含停用),sort_order 升序——管理页列表数据源。
|
||||
* @returns 类型配置数组
|
||||
*/
|
||||
export const listTransferTypes = () =>
|
||||
requestJson<TransferTypeRow[]>(`${BASE}/transfer-types`);
|
||||
|
||||
/**
|
||||
* 创建类型配置。
|
||||
* @param payload - 表单规范化后的完整 payload
|
||||
* @returns 新建的类型配置(后端 201)
|
||||
* @throws BusinessError 重复编码 → 422 TRANSFER.TRANSFER_TYPE_CODE_EXISTS 等本地化错误
|
||||
*/
|
||||
export const createTransferType = (payload: TransferTypePayload) =>
|
||||
requestJson<TransferTypeRow>(`${BASE}/transfer-types`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
/**
|
||||
* 更新类型配置(code 不可变,由路径携带)。
|
||||
* @param code - 类型编码(业务主键)
|
||||
* @param payload - 表单规范化后的完整 payload
|
||||
* @returns 更新后的类型配置
|
||||
* @throws BusinessError 目标不存在 → 404 TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED 等
|
||||
*/
|
||||
export const updateTransferType = (code: string, payload: TransferTypePayload) =>
|
||||
requestJson<TransferTypeRow>(`${BASE}/transfer-types/${encodeURIComponent(code)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
/**
|
||||
* 拉取货代库存外部仓库映射档,仅用于固定仓库编码的存在性黄色提示校验。
|
||||
* @returns 映射行数组;请求失败返回空数组(校验静默降级为「未命中」语义之外的不提示)
|
||||
*/
|
||||
export const listExternalWarehouseMappings = async (): Promise<Array<Record<string, unknown>>> => {
|
||||
try {
|
||||
return await requestJson<Array<Record<string, unknown>>>('/api/admin/shipping-notice/external-mappings');
|
||||
} catch {
|
||||
// 校验属辅助提示,加载失败不影响配置主流程
|
||||
return [];
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,468 @@
|
||||
/**
|
||||
* features/admin/modules/transfer-types/useTransferTypesAdmin.ts
|
||||
* 用途:调拨类型管理页的状态与动作编排——列表筛选、编辑抽屉表单、onBlur 校验、
|
||||
* 顶部错误摘要、范围重叠提示、映射档存在性校验与保存流程(ADR 0002 类型配置化)。
|
||||
* 依赖:transferTypes.api、useMessage、vue-i18n。
|
||||
* 逻辑:TransferTypesPage 调用本 composable 驱动列表与抽屉。校验失败时行内错误
|
||||
* (aria-describedby)+ 顶部错误摘要(role=alert,锚点跳字段);范围重叠与固定仓库
|
||||
* 未命中映射档仅黄色提示、不拦截保存(D10/D6);空范围规则保存前经 window.confirm
|
||||
* 显式确认后携带 allow_empty_scope_rules(对齐后端 fail-closed 门禁)。
|
||||
*/
|
||||
|
||||
import { computed, nextTick, reactive, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
createTransferType,
|
||||
listExternalWarehouseMappings,
|
||||
listTransferTypes,
|
||||
updateTransferType,
|
||||
type TransferScopeRule,
|
||||
type TransferTransformRule,
|
||||
type TransferTypeRow,
|
||||
type TransferWarehouseRole,
|
||||
} from './transferTypes.api';
|
||||
|
||||
/** code 契约:小写字母开头,仅小写字母/数字/下划线,总长 2..64(与后端 CODE_PATTERN 一致)。 */
|
||||
const CODE_PATTERN = /^[a-z][a-z0-9_]{1,63}$/;
|
||||
|
||||
/** 仓库角色表单态(mapped 时固定仓/法人字段不参与提交)。 */
|
||||
export interface TransferWarehouseRoleForm {
|
||||
mode: 'mapped' | 'fixed';
|
||||
warehouseCode: string;
|
||||
externalOrg: string;
|
||||
}
|
||||
|
||||
/** 编辑抽屉表单态(names 拆四语言字段便于逐输入框绑定)。 */
|
||||
export interface TransferTypeFormState {
|
||||
code: string;
|
||||
nameZhCn: string;
|
||||
nameZhTw: string;
|
||||
nameEn: string;
|
||||
nameTh: string;
|
||||
enabled: boolean;
|
||||
sortOrder: number;
|
||||
scopeRules: TransferScopeRule[];
|
||||
warehouse: { from: TransferWarehouseRoleForm; to: TransferWarehouseRoleForm };
|
||||
transformRules: TransferTransformRule[];
|
||||
}
|
||||
|
||||
/** 新建空表单:默认启用、排序 10、双角色映射档。 */
|
||||
export const createEmptyTransferTypeForm = (): TransferTypeFormState => ({
|
||||
code: '',
|
||||
nameZhCn: '',
|
||||
nameZhTw: '',
|
||||
nameEn: '',
|
||||
nameTh: '',
|
||||
enabled: true,
|
||||
sortOrder: 10,
|
||||
scopeRules: [],
|
||||
warehouse: {
|
||||
from: { mode: 'mapped', warehouseCode: '', externalOrg: '' },
|
||||
to: { mode: 'mapped', warehouseCode: '', externalOrg: '' },
|
||||
},
|
||||
transformRules: [],
|
||||
});
|
||||
|
||||
/** 后端仓库角色 JSON → 表单态。 */
|
||||
const roleToForm = (role?: TransferWarehouseRole): TransferWarehouseRoleForm => ({
|
||||
mode: role?.mode === 'fixed' ? 'fixed' : 'mapped',
|
||||
warehouseCode: role?.warehouse_code || '',
|
||||
externalOrg: role?.external_org || '',
|
||||
});
|
||||
|
||||
/** 列表行 → 抽屉表单态(深拷贝规则数组,避免编辑直接改列表数据)。 */
|
||||
export const rowToForm = (row: TransferTypeRow): TransferTypeFormState => ({
|
||||
code: row.code,
|
||||
nameZhCn: row.names?.['zh-CN'] || '',
|
||||
nameZhTw: row.names?.['zh-TW'] || '',
|
||||
nameEn: row.names?.en || '',
|
||||
nameTh: row.names?.th || '',
|
||||
enabled: row.enabled,
|
||||
sortOrder: row.sort_order,
|
||||
scopeRules: (row.scope_rules || []).map((rule) => ({
|
||||
field: rule.field,
|
||||
match: rule.match,
|
||||
values: [...(rule.values || [])],
|
||||
})),
|
||||
warehouse: {
|
||||
from: roleToForm(row.warehouse_config?.from),
|
||||
to: roleToForm(row.warehouse_config?.to),
|
||||
},
|
||||
transformRules: (row.transform_rules || []).map((rule) => ({ ...rule })),
|
||||
});
|
||||
|
||||
/** 错误摘要条目:key 同时是字段 DOM 元素 id(tt-<key>)与行内错误键。 */
|
||||
export interface TransferTypeErrorItem {
|
||||
key: string;
|
||||
targetId: string | null;
|
||||
message: string;
|
||||
}
|
||||
|
||||
/** 映射档存在性校验结果:idle=不适用 / ok=命中 / missing=未命中(仅黄色提示)。 */
|
||||
export type MappingCheckState = 'idle' | 'ok' | 'missing';
|
||||
|
||||
/**
|
||||
* 调拨类型管理页 composable。
|
||||
* @returns 列表/筛选/抽屉/校验/保存全部状态与动作,供 TransferTypesPage 模板绑定
|
||||
*/
|
||||
export function useTransferTypesAdmin() {
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
const types = ref<TransferTypeRow[]>([]);
|
||||
const isLoading = ref(false);
|
||||
const saving = ref(false);
|
||||
const search = ref('');
|
||||
const statusFilter = ref<'all' | 'enabled' | 'disabled'>('all');
|
||||
|
||||
const drawerOpen = ref(false);
|
||||
const editingCode = ref<string | null>(null);
|
||||
const form = reactive<TransferTypeFormState>(createEmptyTransferTypeForm());
|
||||
const fieldErrors = reactive<Record<string, string>>({});
|
||||
const errorSummary = ref<TransferTypeErrorItem[]>([]);
|
||||
/** 各范围规则行的值输入草稿(Enter/失焦提交为 tag)。 */
|
||||
const scopeDrafts = ref<string[]>([]);
|
||||
|
||||
/** 仓库映射档缓存(打开抽屉时懒加载一次),用于固定仓存在性提示。 */
|
||||
const mappings = ref<Array<Record<string, unknown>>>([]);
|
||||
let mappingsRequested = false;
|
||||
|
||||
/** 列表过滤:编码/任意语言名称命中关键字 + 启停状态筛选。 */
|
||||
const filteredTypes = computed(() => {
|
||||
const keyword = search.value.trim().toLowerCase();
|
||||
return types.value.filter((row) => {
|
||||
if (statusFilter.value === 'enabled' && !row.enabled) return false;
|
||||
if (statusFilter.value === 'disabled' && row.enabled) return false;
|
||||
if (!keyword) return true;
|
||||
const names = Object.values(row.names || {}).join(' ').toLowerCase();
|
||||
return row.code.toLowerCase().includes(keyword) || names.includes(keyword);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 范围重叠客户端比对(保存前后常驻):当前规则与「其它启用类型」同字段且值有交集
|
||||
* 即列出对方编码;仅黄色提示,不拦截保存(D10)。编辑自身不计入。
|
||||
*/
|
||||
const overlapCodes = computed(() => {
|
||||
const mine = form.scopeRules.filter((rule) => rule.field && rule.values.length);
|
||||
if (!mine.length) return [];
|
||||
const upperValues = (values: string[]) => values.map((value) => value.trim().toUpperCase());
|
||||
return types.value
|
||||
.filter((row) => row.enabled && row.code !== editingCode.value)
|
||||
.filter((row) => (row.scope_rules || []).some((other) =>
|
||||
mine.some((rule) => rule.field === other.field
|
||||
&& upperValues(rule.values).some((value) => upperValues(other.values || []).includes(value)))))
|
||||
.map((row) => row.code);
|
||||
});
|
||||
|
||||
/** 打开抽屉时懒加载映射档(失败静默为空表,存在性提示退化为不展示)。 */
|
||||
const ensureMappings = async (): Promise<void> => {
|
||||
if (mappingsRequested) return;
|
||||
mappingsRequested = true;
|
||||
mappings.value = await listExternalWarehouseMappings();
|
||||
};
|
||||
|
||||
/**
|
||||
* 固定仓库编码存在性校验:拨出仓比对映射档在途仓、拨入仓比对映射仓;
|
||||
* mapped 模式或未填编码返回 idle(不提示)。
|
||||
*/
|
||||
const warehouseCheckFor = (role: 'from' | 'to'): MappingCheckState => {
|
||||
const cfg = form.warehouse[role];
|
||||
if (cfg.mode !== 'fixed' || !cfg.warehouseCode.trim()) return 'idle';
|
||||
const code = cfg.warehouseCode.trim().toUpperCase();
|
||||
const hit = mappings.value.some((row) => {
|
||||
const candidate = role === 'from' ? row.in_transit_warehouse_code : row.external_warehouse_code;
|
||||
return String(candidate ?? '').trim().toUpperCase() === code;
|
||||
});
|
||||
return hit ? 'ok' : 'missing';
|
||||
};
|
||||
|
||||
const warehouseChecks = computed<{ from: MappingCheckState; to: MappingCheckState }>(
|
||||
() => ({ from: warehouseCheckFor('from'), to: warehouseCheckFor('to') }),
|
||||
);
|
||||
|
||||
const loadTypes = async (): Promise<void> => {
|
||||
isLoading.value = true;
|
||||
try {
|
||||
types.value = await listTransferTypes();
|
||||
} catch (error) {
|
||||
console.error('Failed to load transfer types', error);
|
||||
msg.error(
|
||||
error instanceof BusinessError ? error.message : t('admin.transferTypes.loadFailed'),
|
||||
t('admin.transferTypes.loadFailedTitle'),
|
||||
);
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 单字段校验(onBlur 触发):按 key 前缀分发到编码/名称/范围规则/固定仓/转换规则。
|
||||
* @param key - 错误键,同时是字段元素 id(tt-<key>)
|
||||
*/
|
||||
const validateField = (key: string): void => {
|
||||
let message = '';
|
||||
if (key === 'code' && !editingCode.value) {
|
||||
const code = form.code.trim();
|
||||
if (!code) message = t('admin.transferTypes.errors.codeRequired');
|
||||
else if (!CODE_PATTERN.test(code)) message = t('admin.transferTypes.errors.codeFormat');
|
||||
} else if (key === 'name') {
|
||||
if (!form.nameZhCn.trim()) message = t('admin.transferTypes.errors.nameRequired');
|
||||
} else if (key.startsWith('scope-field-')) {
|
||||
const index = Number(key.slice('scope-field-'.length));
|
||||
if (!form.scopeRules[index]?.field) message = t('admin.transferTypes.errors.ruleFieldRequired');
|
||||
} else if (key.startsWith('scope-values-')) {
|
||||
const index = Number(key.slice('scope-values-'.length));
|
||||
if (form.scopeRules[index] && !form.scopeRules[index].values.length) {
|
||||
message = t('admin.transferTypes.errors.ruleValuesRequired');
|
||||
}
|
||||
} else if (key === 'warehouse-from-code' || key === 'warehouse-to-code') {
|
||||
const role = key === 'warehouse-from-code' ? 'from' : 'to';
|
||||
if (form.warehouse[role].mode === 'fixed' && !form.warehouse[role].warehouseCode.trim()) {
|
||||
message = t('admin.transferTypes.errors.fixedCodeRequired');
|
||||
}
|
||||
} else if (key.startsWith('transform-source-') || key.startsWith('transform-target-')) {
|
||||
const index = Number(key.split('-').pop());
|
||||
const rule = form.transformRules[index];
|
||||
if (rule) {
|
||||
if (key.startsWith('transform-source-') && !rule.source.trim()) {
|
||||
message = t('admin.transferTypes.errors.transformSourceRequired');
|
||||
}
|
||||
if (key.startsWith('transform-target-') && !rule.target.trim()) {
|
||||
message = t('admin.transferTypes.errors.transformTargetRequired');
|
||||
}
|
||||
}
|
||||
}
|
||||
if (message) fieldErrors[key] = message;
|
||||
else delete fieldErrors[key];
|
||||
};
|
||||
|
||||
/** 输入时清除该字段行内错误,避免打字过程残留旧错误。 */
|
||||
const clearFieldError = (key: string): void => {
|
||||
delete fieldErrors[key];
|
||||
};
|
||||
|
||||
/** 关抽屉/重开表单时清空全部行内错误与顶部摘要。 */
|
||||
const resetErrors = (): void => {
|
||||
Object.keys(fieldErrors).forEach((key) => delete fieldErrors[key]);
|
||||
errorSummary.value = [];
|
||||
};
|
||||
|
||||
/**
|
||||
* 保存前全量校验:收集全部错误写回 fieldErrors(行内保留)并生成摘要条目。
|
||||
* @returns 错误摘要数组(空 = 可提交)
|
||||
*/
|
||||
const collectErrors = (): TransferTypeErrorItem[] => {
|
||||
const errors: TransferTypeErrorItem[] = [];
|
||||
const push = (key: string, message: string) => {
|
||||
fieldErrors[key] = message;
|
||||
errors.push({ key, targetId: `tt-${key}`, message });
|
||||
};
|
||||
if (!editingCode.value) {
|
||||
const code = form.code.trim();
|
||||
if (!code) push('code', t('admin.transferTypes.errors.codeRequired'));
|
||||
else if (!CODE_PATTERN.test(code)) push('code', t('admin.transferTypes.errors.codeFormat'));
|
||||
}
|
||||
if (!form.nameZhCn.trim()) push('name', t('admin.transferTypes.errors.nameRequired'));
|
||||
form.scopeRules.forEach((rule, index) => {
|
||||
if (!rule.field) push(`scope-field-${index}`, t('admin.transferTypes.errors.ruleFieldRequired'));
|
||||
if (!rule.values.length) push(`scope-values-${index}`, t('admin.transferTypes.errors.ruleValuesRequired'));
|
||||
});
|
||||
(['from', 'to'] as const).forEach((role) => {
|
||||
if (form.warehouse[role].mode === 'fixed' && !form.warehouse[role].warehouseCode.trim()) {
|
||||
push(`warehouse-${role}-code`, t('admin.transferTypes.errors.fixedCodeRequired'));
|
||||
}
|
||||
});
|
||||
form.transformRules.forEach((rule, index) => {
|
||||
if (!rule.source.trim()) push(`transform-source-${index}`, t('admin.transferTypes.errors.transformSourceRequired'));
|
||||
if (!rule.target.trim()) push(`transform-target-${index}`, t('admin.transferTypes.errors.transformTargetRequired'));
|
||||
});
|
||||
return errors;
|
||||
};
|
||||
|
||||
/** 表单态 → 后端 payload;mapped 角色规范化为空值(与后端读写对称)。 */
|
||||
const buildPayload = (allowEmptyScopeRules: boolean) => {
|
||||
const rolePayload = (role: TransferWarehouseRoleForm): TransferWarehouseRole => (
|
||||
role.mode === 'fixed'
|
||||
? { mode: 'fixed', warehouse_code: role.warehouseCode.trim(), external_org: role.externalOrg.trim() || null }
|
||||
: { mode: 'mapped', warehouse_code: null, external_org: null }
|
||||
);
|
||||
const names: Record<string, string> = {};
|
||||
if (form.nameZhCn.trim()) names['zh-CN'] = form.nameZhCn.trim();
|
||||
if (form.nameZhTw.trim()) names['zh-TW'] = form.nameZhTw.trim();
|
||||
if (form.nameEn.trim()) names.en = form.nameEn.trim();
|
||||
if (form.nameTh.trim()) names.th = form.nameTh.trim();
|
||||
return {
|
||||
code: form.code.trim(),
|
||||
names,
|
||||
enabled: form.enabled,
|
||||
sort_order: Number(form.sortOrder) || 0,
|
||||
scope_rules: form.scopeRules
|
||||
.filter((rule) => rule.field)
|
||||
.map((rule) => ({ field: rule.field, match: rule.match, values: [...rule.values] })),
|
||||
warehouse_config: { from: rolePayload(form.warehouse.from), to: rolePayload(form.warehouse.to) },
|
||||
transform_rules: form.transformRules
|
||||
.filter((rule) => rule.source.trim() && rule.target.trim())
|
||||
.map((rule) => ({ field: rule.field, op: rule.op, source: rule.source.trim(), target: rule.target.trim() })),
|
||||
...(allowEmptyScopeRules ? { allow_empty_scope_rules: true } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
/** 摘要条目点击 → 焦点跳到对应字段(targetId 即元素 id)。 */
|
||||
const focusField = (key: string): void => {
|
||||
document.getElementById(`tt-${key}`)?.focus();
|
||||
};
|
||||
|
||||
const save = async (): Promise<void> => {
|
||||
// [STEP 1] 全量校验:失败时渲染顶部错误摘要(role=alert)并聚焦,行内错误保留,不发请求
|
||||
const errors = collectErrors();
|
||||
Object.keys(fieldErrors).forEach((key) => {
|
||||
if (!errors.some((item) => item.key === key)) delete fieldErrors[key];
|
||||
});
|
||||
errorSummary.value = errors;
|
||||
if (errors.length) {
|
||||
void nextTick(() => document.getElementById('tt-error-summary')?.focus());
|
||||
return;
|
||||
}
|
||||
// [STEP 2] 空范围规则需显式确认:后端 fail-closed 默认拒绝,确认后才携带 allow_empty_scope_rules
|
||||
let allowEmptyScopeRules = false;
|
||||
if (!form.scopeRules.length) {
|
||||
allowEmptyScopeRules = window.confirm(t('admin.transferTypes.emptyScopeConfirm'));
|
||||
if (!allowEmptyScopeRules) return;
|
||||
}
|
||||
// [STEP 3] 提交:范围重叠/映射档未命中仅黄条提示,不在此拦截(D10/D6);失败落顶部摘要
|
||||
saving.value = true;
|
||||
try {
|
||||
const payload = buildPayload(allowEmptyScopeRules);
|
||||
if (editingCode.value) await updateTransferType(editingCode.value, payload);
|
||||
else await createTransferType(payload);
|
||||
msg.success(t('admin.transferTypes.saveSuccess'));
|
||||
drawerOpen.value = false;
|
||||
resetErrors();
|
||||
await loadTypes();
|
||||
} catch (error) {
|
||||
const message = error instanceof BusinessError ? error.message : t('admin.transferTypes.saveFailed');
|
||||
errorSummary.value = [{ key: 'request', targetId: null, message }];
|
||||
msg.error(message, t('admin.transferTypes.saveFailed'));
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const openCreate = (): void => {
|
||||
Object.assign(form, createEmptyTransferTypeForm());
|
||||
scopeDrafts.value = [];
|
||||
editingCode.value = null;
|
||||
resetErrors();
|
||||
drawerOpen.value = true;
|
||||
void ensureMappings();
|
||||
};
|
||||
|
||||
const openEdit = (row: TransferTypeRow): void => {
|
||||
Object.assign(form, rowToForm(row));
|
||||
scopeDrafts.value = form.scopeRules.map(() => '');
|
||||
editingCode.value = row.code;
|
||||
resetErrors();
|
||||
drawerOpen.value = true;
|
||||
void ensureMappings();
|
||||
};
|
||||
|
||||
const closeDrawer = (): void => {
|
||||
drawerOpen.value = false;
|
||||
resetErrors();
|
||||
};
|
||||
|
||||
/** 新增空范围规则(默认前缀匹配),草稿数组同步对齐。 */
|
||||
const addScopeRule = (): void => {
|
||||
form.scopeRules.push({ field: '', match: 'prefix', values: [] });
|
||||
scopeDrafts.value.push('');
|
||||
};
|
||||
|
||||
const removeScopeRule = (index: number): void => {
|
||||
form.scopeRules.splice(index, 1);
|
||||
scopeDrafts.value.splice(index, 1);
|
||||
resetErrors();
|
||||
};
|
||||
|
||||
/**
|
||||
* 值草稿提交为 tag:按逗号(中英文)/空白拆分、去重追加,然后清空草稿。
|
||||
* @param index - 范围规则行下标
|
||||
*/
|
||||
const commitScopeDraft = (index: number): void => {
|
||||
const rule = form.scopeRules[index];
|
||||
if (!rule) return;
|
||||
const draft = scopeDrafts.value[index] || '';
|
||||
draft
|
||||
.split(/[,,\s]+/)
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean)
|
||||
.forEach((value) => {
|
||||
if (!rule.values.includes(value)) rule.values.push(value);
|
||||
});
|
||||
scopeDrafts.value[index] = '';
|
||||
};
|
||||
|
||||
const removeScopeValue = (index: number, valueIndex: number): void => {
|
||||
form.scopeRules[index]?.values.splice(valueIndex, 1);
|
||||
};
|
||||
|
||||
/** 值输入失焦:先提交草稿再校验(保证「失焦即落 tag」与错误判定基于已提交值)。 */
|
||||
const onScopeDraftBlur = (index: number): void => {
|
||||
commitScopeDraft(index);
|
||||
validateField(`scope-values-${index}`);
|
||||
};
|
||||
|
||||
/** 新增转换规则行(受控词表当前仅批号前缀替换)。 */
|
||||
const addTransformRule = (): void => {
|
||||
form.transformRules.push({ field: 'lot_no', op: 'prefix_replace', source: '', target: '' });
|
||||
};
|
||||
|
||||
const removeTransformRule = (index: number): void => {
|
||||
form.transformRules.splice(index, 1);
|
||||
};
|
||||
|
||||
const saveButtonLabel = computed(() => (
|
||||
saving.value ? t('admin.transferTypes.saving') : t('admin.transferTypes.save')
|
||||
));
|
||||
|
||||
return {
|
||||
// 列表
|
||||
types,
|
||||
isLoading,
|
||||
search,
|
||||
statusFilter,
|
||||
filteredTypes,
|
||||
loadTypes,
|
||||
// 抽屉与表单
|
||||
drawerOpen,
|
||||
editingCode,
|
||||
form,
|
||||
scopeDrafts,
|
||||
openCreate,
|
||||
openEdit,
|
||||
closeDrawer,
|
||||
// 校验与提示
|
||||
fieldErrors,
|
||||
errorSummary,
|
||||
overlapCodes,
|
||||
warehouseChecks,
|
||||
validateField,
|
||||
clearFieldError,
|
||||
focusField,
|
||||
// 范围规则编辑
|
||||
addScopeRule,
|
||||
removeScopeRule,
|
||||
commitScopeDraft,
|
||||
removeScopeValue,
|
||||
onScopeDraftBlur,
|
||||
// 转换规则编辑
|
||||
addTransformRule,
|
||||
removeTransformRule,
|
||||
// 保存
|
||||
saving,
|
||||
saveButtonLabel,
|
||||
save,
|
||||
};
|
||||
}
|
||||
@@ -21,6 +21,7 @@ export type AdminModuleId =
|
||||
| 'procurement_contract'
|
||||
| 'training_config'
|
||||
| 'integration_connector'
|
||||
| 'transfer_types'
|
||||
| 'reports';
|
||||
|
||||
/** 货代管理领域下可由侧栏展示和高亮的稳定业务页面。 */
|
||||
|
||||
@@ -603,6 +603,14 @@
|
||||
"TRANSFER.RETRY_NOT_ALLOWED": "This row was removed along with the file and cannot be requeried; mark it as no further action or wait for the file to re-sync.",
|
||||
"TRANSFER.DOCUMENT_CLOSE_NOT_ALLOWED": "Only failed tickets (business/technical) can be closed; use \"Retrigger\" for result_unknown tickets, in-flight tickets cannot be closed.",
|
||||
"TRANSFER.DOCUMENT_NOT_FOUND": "Transfer ticket not found.",
|
||||
"TRANSFER.TRANSFER_TYPE_REQUIRED": "A transfer type is required to create a matching.",
|
||||
"TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED": "No transfer types available; configure them in the admin console first.",
|
||||
"TRANSFER.TRANSFER_TYPE_DISABLED": "This transfer type is disabled.",
|
||||
"TRANSFER.TRANSFER_TYPE_CODE_EXISTS": "The transfer type code already exists.",
|
||||
"TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE": "The transfer type code cannot be changed after creation.",
|
||||
"TRANSFER.SCOPE_RULE_INVALID": "Scope rules are invalid.",
|
||||
"TRANSFER.WAREHOUSE_CONFIG_INVALID": "Warehouse configuration is invalid.",
|
||||
"TRANSFER.TRANSFORM_RULE_INVALID": "Field transform rules are invalid.",
|
||||
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "Legacy single-step fields would truncate this binding's multi-step recipe; submit ordered steps via steps_json instead.",
|
||||
"INTEGRATION.CALL_NOT_FOUND": "Integration call not found.",
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "Binding steps invalid: steps_json is required, must be a non-empty array of objects.",
|
||||
|
||||
@@ -603,6 +603,14 @@
|
||||
"TRANSFER.RETRY_NOT_ALLOWED": "แถวนี้ถูกลบออกไปพร้อมกับไฟล์และตรวจซ้ำไม่ได้ โปรดทำเครื่องหมายว่าไม่จำเป็นต้องดำเนินการต่อ หรือรอให้ไฟล์ซิงก์ใหม่",
|
||||
"TRANSFER.DOCUMENT_CLOSE_NOT_ALLOWED": "ปิดได้เฉพาะตั๋วที่ล้มเหลว (ถูกปฏิเสธทางธุรกิจ/ล้มเหลวทางเทคนิค) สำหรับตั๋วที่ผลลัพธ์ไม่ทราบแน่ชัดโปรดใช้ \"ทริกเกอร์ใหม่\" และตั๋วที่กำลังดำเนินการปิดไม่ได้",
|
||||
"TRANSFER.DOCUMENT_NOT_FOUND": "ไม่พบตั๋วโอนย้าย",
|
||||
"TRANSFER.TRANSFER_TYPE_REQUIRED": "ต้องระบุประเภทการโอนย้ายเพื่อสร้างการจับคู่",
|
||||
"TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED": "ยังไม่มีประเภทการโอนย้าย กรุณาตั้งค่าในหน้าผู้ดูแลก่อน",
|
||||
"TRANSFER.TRANSFER_TYPE_DISABLED": "ประเภทการโอนย้ายนี้ถูกปิดใช้งาน",
|
||||
"TRANSFER.TRANSFER_TYPE_CODE_EXISTS": "รหัสประเภทการโอนย้ายมีอยู่แล้ว",
|
||||
"TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE": "รหัสประเภทการโอนย้ายแก้ไขไม่ได้หลังสร้าง",
|
||||
"TRANSFER.SCOPE_RULE_INVALID": "กฎขอบเขตไม่ถูกต้อง",
|
||||
"TRANSFER.WAREHOUSE_CONFIG_INVALID": "การตั้งค่าคลังสินค้าไม่ถูกต้อง",
|
||||
"TRANSFER.TRANSFORM_RULE_INVALID": "กฎการแปลงฟิลด์ไม่ถูกต้อง",
|
||||
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "ฟิลด์ขั้นตอนเดียวแบบเดิมจะตัดทอนสูตรหลายขั้นตอนของการผูกนี้ โปรดส่งขั้นตอนตามลำดับด้วย steps_json แทน",
|
||||
"INTEGRATION.CALL_NOT_FOUND": "ไม่พบระเบียนการเรียกใช้งานการผสานรวม",
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "การกำหนดค่าขั้นตอนการเชื่อมโยงไม่ถูกต้อง: steps_json จำเป็นต้องมีและเป็นอาร์เรย์ที่ไม่ว่าง โดยแต่ละรายการต้องเป็นออบเจกต์",
|
||||
|
||||
@@ -603,6 +603,14 @@
|
||||
"TRANSFER.RETRY_NOT_ALLOWED": "该行已随文件移除,无法重查;请标记无需继续处理或等待文件重新同步。",
|
||||
"TRANSFER.DOCUMENT_CLOSE_NOT_ALLOWED": "仅失败票(业务拒绝/技术失败)允许关闭;结果未知票请使用「重新触发」,执行中的票不可关闭。",
|
||||
"TRANSFER.DOCUMENT_NOT_FOUND": "调拨票不存在。",
|
||||
"TRANSFER.TRANSFER_TYPE_REQUIRED": "匹配创建缺少调拨类型。",
|
||||
"TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED": "暂无可用调拨类型,请先在管理端配置。",
|
||||
"TRANSFER.TRANSFER_TYPE_DISABLED": "该调拨类型已停用。",
|
||||
"TRANSFER.TRANSFER_TYPE_CODE_EXISTS": "调拨类型编码已存在。",
|
||||
"TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE": "调拨类型编码创建后不可修改。",
|
||||
"TRANSFER.SCOPE_RULE_INVALID": "范围规则不合法。",
|
||||
"TRANSFER.WAREHOUSE_CONFIG_INVALID": "仓库定义不合法。",
|
||||
"TRANSFER.TRANSFORM_RULE_INVALID": "字段转换规则不合法。",
|
||||
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "旧单步字段会截断该绑定的多步配方,请改用 steps_json 提交有序步骤。",
|
||||
"INTEGRATION.CALL_NOT_FOUND": "集成调用记录不存在。",
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "绑定步骤配置不合法:steps_json 必填且为非空数组,每项须为对象。",
|
||||
|
||||
@@ -603,6 +603,14 @@
|
||||
"TRANSFER.RETRY_NOT_ALLOWED": "該行已隨檔案移除,無法重查;請標記無需繼續處理或等待檔案重新同步。",
|
||||
"TRANSFER.DOCUMENT_CLOSE_NOT_ALLOWED": "僅失敗票(業務拒絕/技術失敗)允許關閉;結果未知票請使用「重新觸發」,執行中的票不可關閉。",
|
||||
"TRANSFER.DOCUMENT_NOT_FOUND": "調撥票不存在。",
|
||||
"TRANSFER.TRANSFER_TYPE_REQUIRED": "匹配建立缺少調撥類型。",
|
||||
"TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED": "暫無可用調撥類型,請先在管理端配置。",
|
||||
"TRANSFER.TRANSFER_TYPE_DISABLED": "該調撥類型已停用。",
|
||||
"TRANSFER.TRANSFER_TYPE_CODE_EXISTS": "調撥類型編碼已存在。",
|
||||
"TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE": "調撥類型編碼建立後不可修改。",
|
||||
"TRANSFER.SCOPE_RULE_INVALID": "範圍規則不合法。",
|
||||
"TRANSFER.WAREHOUSE_CONFIG_INVALID": "倉庫定義不合法。",
|
||||
"TRANSFER.TRANSFORM_RULE_INVALID": "欄位轉換規則不合法。",
|
||||
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "舊單步欄位會截斷該繫結的多步配方,請改用 steps_json 提交有序步驟。",
|
||||
"INTEGRATION.CALL_NOT_FOUND": "整合調用記錄不存在。",
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "綁定步驟配置不合法:steps_json 必填且為非空陣列,每項須為物件。",
|
||||
|
||||
Reference in new issue
Block a user