!13 feat(shipping-freight-auto-upload): 新增货代发货Excel连接级自动上传全链路功能

Merge pull request !13 from 曹惠鹏/hugo-shipping-notice
This commit is contained in:
sophie authored and Gitee committed 2026-08-27 07:51:42 +00:00
commit 2921c8d90f
93 files changed
+4867 -601

No files matched your search

@@ -0,0 +1,83 @@
/**
* features/admin/modules/schedules/components/DynamicTaskParamsForm.spec.ts
* 用途:复现「货代库存 RPA」平台任务参数表单的渲染。
* 背景:排程编辑弹窗选择 shipping-inventory-rpa 后,库存源多选字段不呈现,且弹窗按钮疑似失效。
* 断言:给定带 source_codes(multi_select/options_source=shipping_inventory_sources) 的定义,
* 挂载后应渲染「库存源」标签及动态选项,而不是抛错或渲染为空。
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { flushPromises, mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import DynamicTaskParamsForm from './DynamicTaskParamsForm.vue';
vi.mock('@/features/admin/api/schedule.api', () => ({
listAdminPlatformTaskOptions: vi.fn(() =>
Promise.resolve([
{ label: 'DSV 360 / Rooms BK HK', value: 'DSV360', description: 'dbs · fixed · W01' },
{ label: 'Crane Footprint', value: 'CRANE', description: 'crane · inventory_match · -' },
]),
),
}));
const shippingInventoryRpaDefinition = {
task_type: 'shipping-inventory-rpa',
label: '货代库存 RPA',
label_key: 'admin.schedule.form.platformJobShippingInventory',
description: '按计划从配置的库存源抓取库存数据,由 freight_rpa_worker 异步导出。',
description_key: 'admin.schedule.form.shippingInventoryJobHint',
category: 'shipping',
params_schema: [
{
key: 'source_codes',
type: 'multi_select',
label: '库存源',
label_key: 'admin.schedule.form.shippingInventorySources',
required: false,
default: [],
options_source: 'shipping_inventory_sources',
placeholder: '留空则导出全部启用库存源',
placeholder_key: 'admin.schedule.form.shippingInventorySourcesPlaceholder',
help: '选择需要执行的库存源;选项来自库存源配置,留空则全部执行。',
help_key: 'admin.schedule.form.shippingInventorySourcesHelp',
},
],
defaults: { source_codes: [] },
};
function mountForm() {
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
'admin.schedule.form.dynamicParamsAdvancedPlaceholder': '可选:粘贴高级 JSON 对象参数,例如添加 timeout_seconds 等键值对',
'admin.schedule.form.dynamicParamsAdvanced': '高级配置(JSON,可选)',
},
},
});
return mount(DynamicTaskParamsForm, {
props: {
definition: shippingInventoryRpaDefinition as any,
modelValue: { source_codes: [] },
valid: true,
},
global: { plugins: [i18n] },
});
}
describe('DynamicTaskParamsForm (shipping-inventory-rpa)', () => {
beforeEach(() => vi.clearAllMocks());
it('renders the 库存源 label and the two dynamic options', async () => {
const wrapper = mountForm();
await flushPromises();
expect(wrapper.text()).toContain('库存源');
expect(wrapper.text()).toContain('DSV 360 / Rooms BK HK');
expect(wrapper.text()).toContain('Crane Footprint');
expect(wrapper.find('input[type="checkbox"]').exists()).toBe(true);
});
it('does not throw during mount/render given the definition', async () => {
expect(() => mountForm()).not.toThrow();
});
});
@@ -30,6 +30,7 @@ const emit = defineEmits<{
const { t, te } = useI18n();
/** options_source → 选项列表缓存(组件生命周期内共享,避免重复请求) */
const optionsCache = reactive<Record<string, PlatformTaskOption[]>>({});
const optionsLoading = reactive<Record<string, boolean>>({});
@@ -18,8 +18,8 @@ const showCreateModal = useScheduleCreateModalOpen();
<template>
<Teleport to="body">
<div v-if="showCreateModal" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-w-3xl">
<div class="flex items-center justify-between border-b border-subtle px-8 py-6">
<div class="admin-modal-panel max-h-[92vh] max-w-3xl min-h-0">
<div class="flex shrink-0 items-center justify-between border-b border-subtle px-8 py-6">
<h3 class="text-2xl font-bold tracking-tight text-primary">{{ admin.scheduleEditingId ? $t('admin.schedule.form.editTitle') : $t('admin.schedule.form.createTitle') }}</h3>
<button
class="rounded-full p-2 text-muted transition hover-surface-soft hover:text-secondary"
@@ -28,7 +28,7 @@ const showCreateModal = useScheduleCreateModalOpen();
✕
</button>
</div>
<div class="max-h-[72vh] space-y-5 overflow-y-auto px-8 py-6">
<div class="min-h-0 flex-1 space-y-5 overflow-y-auto px-8 py-6">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div>
<label class="mb-2 block text-sm font-medium text-secondary">{{ $t('admin.schedule.form.name') }}</label>
@@ -300,18 +300,31 @@ const showCreateModal = useScheduleCreateModalOpen();
</template>
</div>
<!-- 平台任务参数区:完全由注册表 params_schema 决定,无任务级 v-if -->
<div
v-if="admin.scheduleCreateForm.schedule_type === 'platform_job' && admin.selectedPlatformTaskDefinition"
class="mt-3"
>
<!-- 平台任务参数区:完全由注册表 params_schema 决定,无任务级 v-if。
外层仅按 schedule_type 判定(同步、必然为真),不依赖异步 definitions;
定义解析完成前显示加载提示,完成后立即渲染 DynamicTaskParamsForm(含库存源)。 -->
<div v-if="admin.scheduleCreateForm.schedule_type === 'platform_job'" class="mt-3">
<DynamicTaskParamsForm
v-if="admin.selectedPlatformTaskDefinition"
:definition="admin.selectedPlatformTaskDefinition"
:model-value="admin.scheduleCreateForm.job_params"
:valid="admin.platformJobParamsValid"
@update:model-value="admin.scheduleCreateForm.job_params = $event"
@update:valid="admin.platformJobParamsValid = $event"
/>
<div v-else-if="admin.platformTaskDefinitionsLoading || admin.platformTaskDefinitionsError" class="space-y-2 rounded-xl border border-blue-200 bg-blue-50/40 px-4 py-3 text-sm text-muted">
<p>{{ admin.platformTaskDefinitionsLoading
? $t('admin.schedule.form.dynamicParamsLoading')
: $t('admin.schedule.form.dynamicParamsLoadFailed') }}</p>
<button
v-if="admin.platformTaskDefinitionsError && !admin.platformTaskDefinitionsLoading"
type="button"
class="btn-secondary btn-sm"
@click="admin.loadPlatformTaskDefinitions"
>
{{ $t('admin.schedule.form.dynamicParamsRetry') }}
</button>
</div>
</div>
<div v-if="admin.scheduleTestResult" class="mt-4 rounded-2xl border border-emerald-200 bg-emerald-50/40 p-4">
@@ -463,7 +476,7 @@ const showCreateModal = useScheduleCreateModalOpen();
</div>
</div>
<div class="admin-modal-footer admin-modal-footer--muted justify-end gap-3 px-8 py-5">
<div class="admin-modal-footer admin-modal-footer--muted relative z-10 pointer-events-auto justify-end gap-3 px-8 py-5">
<button
type="button"
class="btn-secondary"
@@ -0,0 +1,26 @@
/**
* features/admin/modules/schedules/components/dynamicParamsLocale.spec.ts
* 回归防护:vue-i18n 会把 {xxx} 当作命名插值;若 locale 文案里出现裸 {(如示例 JSON),
* 会导致 $t() 在渲染 DynamicTaskParamsForm 时抛错("'multipliers' of null"/编译报错),
* 进而整套参数区无法渲染、弹窗按钮失效。本测试确保四语言该占位文案不含花括号。
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
const LOCALES = ['zh-CN', 'zh-TW', 'en', 'th'];
describe('admin.schedule.form.dynamicParamsAdvancedPlaceholder', () => {
LOCALES.forEach((locale) => {
it(`${locale} must NOT contain message-compiler braces`, () => {
const text = readFileSync(resolve(__dirname, `../../../../../locales/${locale}/admin.json`), 'utf8');
const line = text
.split('\n')
.find((l) => l.includes('"dynamicParamsAdvancedPlaceholder"'));
expect(line, `missing key for ${locale}`).toBeTruthy();
// vue-i18n 编译器会把 { 视为插值起始,示例 JSON 的花括号会导致渲染抛错
expect(line!.includes('{')).toBe(false);
expect(line!.includes('}')).toBe(false);
});
});
});
@@ -18,6 +18,8 @@ export function createScheduleAdminState() {
const platformJobs = ref<PlatformJobOption[]>([]);
/** 平台任务完整契约(含 params_schema),供 DynamicTaskParamsForm 渲染 */
const platformTaskDefinitions = ref<PlatformTaskDefinition[]>([]);
const platformTaskDefinitionsLoading = ref(false);
const platformTaskDefinitionsError = ref(false);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmTitle = ref('');
@@ -118,6 +120,8 @@ export function createScheduleAdminState() {
kbGroups,
platformJobs,
platformTaskDefinitions,
platformTaskDefinitionsLoading,
platformTaskDefinitionsError,
showDeleteConfirmDialog,
deleteConfirmTitle,
deleteConfirmMessage,
@@ -22,6 +22,7 @@ import {
type ScheduleCreateForm,
} from '../../types/schedule-admin.types';
import { buildScheduleConfigPayload } from '../../utils/schedule-form-payload.utils';
import { normalizePlatformJobKey } from '../../utils/schedule-job-key.utils';
import { useScheduleCronDesigner } from '../useScheduleCronDesigner';
import type { ScheduleAdminState } from './schedule-admin.state';
import type { ScheduleAdminLookups } from './useScheduleAdminLookups';
@@ -63,7 +64,10 @@ export function useScheduleAdminForm(
const selectedPlatformTaskDefinition = computed(() => {
const form = scheduleCreateForm.value;
if (form.schedule_type !== 'platform_job' || !form.platform_api_path) return null;
return platformTaskDefinitions.value.find((d) => d.task_type === form.platform_api_path) || null;
// 后端保存时经 normalize_job_key 归一化;历史数据可能存下划线/完整路径/大小写差异,
// 前端比较也归一化,避免严格 === 失配导致参数表单(含库存源)被静默隐藏。
const normalized = normalizePlatformJobKey(form.platform_api_path);
return platformTaskDefinitions.value.find((d) => normalizePlatformJobKey(d.task_type) === normalized) || null;
});
/**
@@ -71,8 +75,9 @@ export function useScheduleAdminForm(
* 核心逻辑:由 modal select @change 触发(不用 watch,防止编辑回填被覆盖)。
*/
const handlePlatformJobChange = (): void => {
const normalized = normalizePlatformJobKey(scheduleCreateForm.value.platform_api_path);
const definition = platformTaskDefinitions.value.find(
(d) => d.task_type === scheduleCreateForm.value.platform_api_path,
(d) => normalizePlatformJobKey(d.task_type) === normalized,
);
scheduleCreateForm.value.job_params = definition && Object.keys(definition.defaults || {}).length
? { ...definition.defaults }
@@ -237,11 +242,13 @@ export function useScheduleAdminForm(
data_source_type: task.schedule_type === 'data_pipeline'
? ((task.data_source_type || 'database') as ScheduleCreateForm['data_source_type'])
: null,
platform_api_path: task.schedule_type === 'platform_job' ? (task.platform_api_path || null) : null,
platform_api_path: task.schedule_type === 'platform_job'
? (normalizePlatformJobKey(task.platform_api_path) || null)
: null,
// 历史 FAQ 任务兼容:无 job_params 时把旧 dify_agent_id 迁移为 app_id
job_params: task.schedule_type === 'platform_job'
? (task.job_params
|| (task.platform_api_path === 'faq-aggregate-hot' && task.dify_agent_id
|| (normalizePlatformJobKey(task.platform_api_path) === 'faq-aggregate-hot' && task.dify_agent_id
? { app_id: task.dify_agent_id }
: null))
: null,
@@ -1,6 +1,9 @@
/**
* features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminList.ts
* 任务列表加载、概览统计、启停/立即执行/删除与视图切换。
* 等待轮询策略:点「立即执行」后每 RUN_NOW_POLL_MS 刷新记录与列表,直到任务离开 running;
* 同一任务仅保留一个轮询(重复点击先清旧定时器)、上一轮未返回时跳过本轮,
* 并设 RUN_NOW_POLL_MAX_MS 上限,防止任务长时间不终态造成页面无限请求。
*/
import { computed } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
@@ -15,6 +18,11 @@ import { useMessage } from '@/shared/composables/useMessage';
import type { ScheduleAdminState } from './schedule-admin.state';
import type { ScheduleAdminRuns } from './useScheduleAdminRuns';
/** 立即执行后的等待轮询间隔 */
const RUN_NOW_POLL_MS = 5_000;
/** 等待轮询总上限:与服务端库存导出超时(默认 900s)对齐,超限后停止自动刷新提示手动查询 */
const RUN_NOW_POLL_MAX_MS = 15 * 60_000;
export function useScheduleAdminList(
state: ScheduleAdminState,
runs: Pick<ScheduleAdminRuns, 'viewScheduleRuns'>,
@@ -30,6 +38,11 @@ export function useScheduleAdminList(
openDeleteConfirm,
} = state;
/** 各任务运行中的单实例等待轮询句柄(重复点「立即执行」复用同一句柄) */
const runNowPollTimers = new Map<number, ReturnType<typeof setInterval>>();
/** 正在执行的等待轮询任务(上一轮未返回时跳过 tick,防请求堆叠) */
const runNowPollsInFlight = new Set<number>();
const scheduleEnabledCount = computed(() => schedules.value.filter((item) => item.enabled).length);
const scheduleDisabledCount = computed(() => schedules.value.filter((item) => !item.enabled).length);
const scheduleRunningCount = computed(() => schedules.value.filter((item) => item.last_status === 'running').length);
@@ -77,17 +90,37 @@ export function useScheduleAdminList(
msg.error(err?.message || t('admin.schedule.msg.runNowFailed'));
return;
}
await runs.viewScheduleRuns(taskId);
await runs.viewScheduleRuns(taskId, true);
await loadSchedules();
// 同一任务只保留一个等待轮询:重复点击先停旧定时器,避免多路 interval 并行放大请求频率
const previousPoll = runNowPollTimers.get(taskId);
if (previousPoll) clearInterval(previousPoll);
let elapsedMs = 0;
const pollInterval = setInterval(async () => {
await runs.viewScheduleRuns(taskId);
await loadSchedules();
const target = schedules.value.find((s: ScheduleTask) => s.id === taskId);
if (target && target.last_status && target.last_status !== 'running') {
clearInterval(pollInterval);
// 上一轮尚未返回时跳过本轮;慢后端下每轮耗时可能超过间隔,跳过可避免请求逐轮堆叠
if (runNowPollsInFlight.has(taskId)) return;
runNowPollsInFlight.add(taskId);
try {
await runs.viewScheduleRuns(taskId, true);
await loadSchedules();
elapsedMs += RUN_NOW_POLL_MS;
const target = schedules.value.find((s: ScheduleTask) => s.id === taskId);
const terminal = !!target?.last_status && target.last_status !== 'running';
const timedOut = elapsedMs >= RUN_NOW_POLL_MAX_MS;
if (terminal || timedOut) {
clearInterval(pollInterval);
runNowPollTimers.delete(taskId);
if (timedOut && !terminal) {
msg.warning(t('admin.schedule.msg.runNowWaitTimeout'));
}
}
} finally {
runNowPollsInFlight.delete(taskId);
}
}, 5000);
}, RUN_NOW_POLL_MS);
runNowPollTimers.set(taskId, pollInterval);
};
const setScheduleEnabled = async (taskId: number, enabled: boolean) => {
@@ -8,7 +8,15 @@ import { getKbGroups } from '@/features/kb/api/kb.api';
import type { ScheduleAdminState } from './schedule-admin.state';
export function useScheduleAdminLookups(state: ScheduleAdminState) {
const { agents, users, kbGroups, platformJobs, platformTaskDefinitions } = state;
const {
agents,
users,
kbGroups,
platformJobs,
platformTaskDefinitions,
platformTaskDefinitionsLoading,
platformTaskDefinitionsError,
} = state;
const loadAgents = async (): Promise<void> => {
try {
@@ -55,11 +63,16 @@ export function useScheduleAdminLookups(state: ScheduleAdminState) {
* 核心逻辑:GET /api/admin/platform-tasks/definitions,供 DynamicTaskParamsForm 按 schema 渲染。
*/
const loadPlatformTaskDefinitions = async (): Promise<void> => {
platformTaskDefinitionsLoading.value = true;
platformTaskDefinitionsError.value = false;
try {
platformTaskDefinitions.value = await listAdminPlatformTaskDefinitions();
} catch (e) {
console.error('Failed to load platform task definitions', e);
platformTaskDefinitions.value = [];
platformTaskDefinitionsError.value = true;
} finally {
platformTaskDefinitionsLoading.value = false;
}
};
@@ -1,8 +1,11 @@
/**
* features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts
* 执行批次列表:筛选、列宽、展开详情、Excel 下载与指标派生。
* 执行批次列表:筛选、列宽、展开详情、Excel 下载、指标派生与 RPA Worker 心跳轮询。
* 轮询策略(历史查询与监控职责分离):执行记录列表是纯历史查询,仅切任务/查询/重置时按需加载;
* RPA Worker 在线状态是监控信号,仅在库存排程工作台模式下每 RPA_WORKER_STATUS_POLL_MS 静默轮询一次,
* 后台标签页暂停、请求未返回时跳过(防堆叠),使「在线/离线」徽标及时反映心跳。
*/
import { computed, watch, type Ref } from 'vue';
import { computed, onBeforeUnmount, watch, type Ref } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
import { listAdminScheduleRuns, adminRunInventoryRawZipUrl, getAdminRpaWorkersStatus } from '@/features/admin/api/schedule.api';
import { useMessage } from '@/shared/composables/useMessage';
@@ -33,6 +36,7 @@ export function useScheduleAdminRuns(
scheduleRunColumnDefs,
resizingScheduleCol,
expandedScheduleRunId,
scheduleViewMode,
} = state;
const syncScheduleRunColumnLabels = () => {
@@ -162,21 +166,63 @@ export function useScheduleAdminRuns(
return latest ? formatDateTime(String(latest)) : '-';
});
const refreshRpaWorkerStatus = async () => {
/**
* 拉取 RPA Worker 心跳状态概览(刷新「在线/离线」徽标与最后心跳时间)。
* @param silent - 静默模式:由后台轮询调用,不翻转 loading,避免徽标每轮闪烁「加载中」
*/
const refreshRpaWorkerStatus = async (silent = false) => {
if (!isInventoryRpaSchedule.value) {
rpaWorkerStatus.value = null;
return;
}
rpaWorkerStatusLoading.value = true;
if (!silent) rpaWorkerStatusLoading.value = true;
try {
rpaWorkerStatus.value = await getAdminRpaWorkersStatus();
} catch {
rpaWorkerStatus.value = null;
} finally {
rpaWorkerStatusLoading.value = false;
if (!silent) rpaWorkerStatusLoading.value = false;
}
};
// ── RPA Worker 心跳轮询(监控信号,仅库存排程) ─────────────────────────
// 心跳由 Worker 每约 20s 上报一次(服务端 TTL 默认 90s),UI 每 10s 刷新即足够;
// 2s 固定轮询只有少量时间点在变化,属于对无变化数据的过度请求。
const RPA_WORKER_STATUS_POLL_MS = 10_000;
/** 是否需要前台轮询心跳:仅工作台模式且当前排程为库存类(该徽标仅在此时可见) */
const shouldPollRpaWorkerStatus = computed(
() => scheduleViewMode.value === 'workbench' && isInventoryRpaSchedule.value && !!selectedScheduleId.value,
);
let rpaStatusPollTimer: ReturnType<typeof setInterval> | null = null;
let rpaStatusPollInFlight = false;
const stopRpaStatusPolling = () => {
if (rpaStatusPollTimer) {
clearInterval(rpaStatusPollTimer);
rpaStatusPollTimer = null;
}
};
const startRpaStatusPolling = () => {
stopRpaStatusPolling();
if (!shouldPollRpaWorkerStatus.value) return;
rpaStatusPollTimer = setInterval(async () => {
// 后台标签页不轮询;上一次请求未返回时跳过本轮,防止请求堆叠与旧响应覆盖
if (document.hidden || rpaStatusPollInFlight) return;
rpaStatusPollInFlight = true;
try {
await refreshRpaWorkerStatus(true);
} finally {
rpaStatusPollInFlight = false;
}
}, RPA_WORKER_STATUS_POLL_MS);
};
watch(shouldPollRpaWorkerStatus, startRpaStatusPolling, { immediate: true });
onBeforeUnmount(stopRpaStatusPolling);
const todayStart = () => {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T00:00:00`;
@@ -192,7 +238,12 @@ export function useScheduleAdminRuns(
scheduleRunStartedBefore.value = todayEnd();
};
const viewScheduleRuns = async (taskId: number) => {
/**
* 加载指定排程的执行记录并顺带刷新 RPA Worker 心跳状态。
* @param taskId - 排程任务 ID
* @param silentRpaStatusRefresh - 静默刷新心跳(用于「立即执行」等待轮询),不翻转 loading 徽标避免闪烁
*/
const viewScheduleRuns = async (taskId: number, silentRpaStatusRefresh = false) => {
selectedScheduleId.value = taskId;
scheduleRunsLoading.value = true;
if (!scheduleRunStartedAfter.value && !scheduleRunStartedBefore.value) {
@@ -208,7 +259,7 @@ export function useScheduleAdminRuns(
params.started_before = new Date(scheduleRunStartedBefore.value).toISOString();
}
selectedScheduleRuns.value = await listAdminScheduleRuns(taskId, params);
await refreshRpaWorkerStatus();
await refreshRpaWorkerStatus(silentRpaStatusRefresh);
} finally {
scheduleRunsLoading.value = false;
}
@@ -0,0 +1,35 @@
/**
* features/admin/modules/schedules/utils/schedule-job-key.utils.spec.ts
* 验证 normalizePlatformJobKey 与后端 schedule_contract.normalize_job_key 语义一致,
* 确保 selectedPlatformTaskDefinition 对历史非规范 platform_api_path 仍能命中参数契约。
*/
import { describe, expect, it } from 'vitest';
import { normalizePlatformJobKey } from './schedule-job-key.utils';
describe('normalizePlatformJobKey', () => {
it('保留规范化连字符 key', () => {
expect(normalizePlatformJobKey('shipping-inventory-rpa')).toBe('shipping-inventory-rpa');
});
it('下划线转连字符(历史小写别名)', () => {
expect(normalizePlatformJobKey('shipping_inventory_rpa')).toBe('shipping-inventory-rpa');
});
it('大小写不敏感', () => {
expect(normalizePlatformJobKey('Shipping-Inventory-RPA')).toBe('shipping-inventory-rpa');
});
it('取完整内部路径最后一段', () => {
expect(normalizePlatformJobKey('/api/internal/jobs/shipping-inventory-rpa')).toBe('shipping-inventory-rpa');
});
it('去 query / hash / 首尾斜杠', () => {
expect(normalizePlatformJobKey('/faq-aggregate-hot?x=1#frag')).toBe('faq-aggregate-hot');
});
it('空值与 null 返回空串', () => {
expect(normalizePlatformJobKey('')).toBe('');
expect(normalizePlatformJobKey(null)).toBe('');
expect(normalizePlatformJobKey(undefined)).toBe('');
});
});
@@ -0,0 +1,26 @@
/**
* features/admin/modules/schedules/utils/schedule-job-key.utils.ts
* 平台任务 key 归一化,与后端 schedule_contract.normalize_job_key 保持同一语义。
* 逻辑:小写 → 去 query/hash → 去首尾斜杠 → 取路径最后一段 → 下划线转连字符。
* 用途:openScheduleEditModal 读入 platform_api_path 时归一化,使「平台任务」下拉回显与
* selectedPlatformTaskDefinition 的 task_type 精确匹配不受历史非规范存储值影响。
* 后端在保存时已归一化,历史数据仍可能存下划线(shipping_inventory_rpa)、完整内部路径
* (/api/internal/jobs/shipping-inventory-rpa)或大小写差异;前端此前用严格 === 字符串比较,
* 一旦不匹配即静默隐藏参数表单(含库存源),本工具修复该匹配漏洞。
*/
export function normalizePlatformJobKey(value: string | null | undefined): string {
let raw = String(value || '').trim().toLowerCase();
// 取 query 之前
const queryIdx = raw.indexOf('?');
if (queryIdx >= 0) raw = raw.slice(0, queryIdx);
// 取 hash 之前
const hashIdx = raw.indexOf('#');
if (hashIdx >= 0) raw = raw.slice(0, hashIdx);
// 去首尾斜杠
raw = raw.replace(/^\/+|\/+$/g, '');
// 取最后一段路径
const lastSlash = raw.lastIndexOf('/');
if (lastSlash >= 0) raw = raw.slice(lastSlash + 1);
// 下划线转连字符
return raw.replace(/_/g, '-');
}
@@ -98,6 +98,24 @@
<label><span>{{ t('admin.shippingInventory.username') }}</span><input v-model="profile.username" class="input-field" name="shipping-rpa-credential-user" autocomplete="one-time-code" readonly :placeholder="t('admin.shippingInventory.writeOnlyHint')" @focus="unlockCredentialField"></label>
<label><span>{{ t('admin.shippingInventory.password') }}</span><input v-model="profile.password" class="input-field" name="shipping-rpa-credential-password" type="password" autocomplete="new-password" readonly :placeholder="t('admin.shippingInventory.writeOnlyHint')" @focus="unlockCredentialField"></label>
<div class="switch-field"><span>{{ t('admin.shippingInventory.enabled') }}</span><button type="button" class="status-switch" :class="{ on: profile.enabled }" role="switch" :aria-checked="profile.enabled" @click="profile.enabled = !profile.enabled"><i></i><b>{{ profile.enabled ? t('admin.shippingInventory.enabledState') : t('admin.shippingInventory.disabledState') }}</b></button></div>
<section class="upload-config-section full">
<header class="upload-config-heading">
<b>{{ t('admin.shippingInventory.uploadConfigTitle') }}</b>
<small>{{ t('admin.shippingInventory.uploadConfigHint') }}</small>
</header>
<div class="switch-field"><span>{{ t('admin.shippingInventory.uploadAutoEnabled') }}</span><button type="button" class="status-switch" :class="{ on: profile.upload_config_json.enabled }" role="switch" :aria-checked="profile.upload_config_json.enabled" @click="profile.upload_config_json.enabled = !profile.upload_config_json.enabled"><i></i><b>{{ profile.upload_config_json.enabled ? t('admin.shippingInventory.enabledState') : t('admin.shippingInventory.disabledState') }}</b></button></div>
<label><span>{{ t('admin.shippingInventory.uploadEntryUrl') }}</span><input v-model="profile.upload_config_json.entry_url" class="input-field" type="url"></label>
<label><span>{{ t('admin.shippingInventory.uploadFileSelector') }}</span><input v-model="profile.upload_config_json.file_input_selector" class="input-field"></label>
<label><span>{{ t('admin.shippingInventory.uploadSubmitMode') }}</span><select v-model="profile.upload_config_json.submit_mode" class="select-field"><option value="auto_after_file">{{ t('admin.shippingInventory.uploadSubmitAuto') }}</option><option value="click_submit">{{ t('admin.shippingInventory.uploadSubmitClick') }}</option></select></label>
<label v-if="profile.upload_config_json.submit_mode === 'click_submit'"><span>{{ t('admin.shippingInventory.uploadSubmitSelector') }}</span><input v-model="profile.upload_config_json.submit_selector" class="input-field"></label>
<label><span>{{ t('admin.shippingInventory.uploadResultMode') }}</span><select v-model="profile.upload_config_json.result_mode" class="select-field"><option value="page_notice">{{ t('admin.shippingInventory.uploadResultPageNotice') }}</option><option value="history_record">{{ t('admin.shippingInventory.uploadResultHistory') }}</option></select></label>
<label><span>{{ t('admin.shippingInventory.uploadResultSelector') }}</span><input v-model="profile.upload_config_json.result_selector" class="input-field"></label>
<label><span>{{ t('admin.shippingInventory.uploadSuccessTexts') }}</span><textarea v-model="successTextsInput" class="input-field" rows="2" :placeholder="t('admin.shippingInventory.uploadSuccessTextsHint')"></textarea></label>
<label><span>{{ t('admin.shippingInventory.uploadTimeout') }}</span><input v-model.number="profile.upload_config_json.timeout_seconds" class="input-field" type="number" min="1"></label>
<div class="form-tip full">{{ t('admin.shippingInventory.uploadConfigBoundary') }}</div>
</section>
<div class="form-tip full">{{ t('admin.shippingInventory.connectionBoundary') }}</div>
</template>
@@ -565,7 +583,33 @@ const filenameVariableCandidates = computed(() => {
return filenameVariables.filter((item) => item.key.toLowerCase().includes(query) || t(item.labelKey).toLowerCase().includes(query));
});
const profile = reactive({ profile_code: '', display_name: '', connector_type: 'dbs', login_url: '', username: '', password: '', login_config_json: { auth_mode: 'password' }, enabled: true });
/** 连接级“发货 Excel 自动上传”配置的受控 JSON 形状(字段与后端白名单一致)。 */
interface ProfileUploadConfig {
enabled: boolean;
entry_url: string;
file_input_selector: string;
submit_mode: 'auto_after_file' | 'click_submit';
submit_selector: string | null;
result_mode: 'page_notice' | 'history_record';
result_selector: string | null;
success_texts: string[];
timeout_seconds: number;
}
/** 连接级“发货 Excel 自动上传”默认配置:DSV 为已确认 URL+input#file2;Crane 保持未启用待管理员补全。 */
function defaultUploadConfig(connectorType: string): ProfileUploadConfig {
if (connectorType === 'crane') {
return { enabled: false, entry_url: 'https://wms-portal.craneww.com/#/shipping-order-upload', file_input_selector: 'input[name="OrderFileUpload"]', submit_mode: 'click_submit', submit_selector: null, result_mode: 'page_notice', result_selector: null, success_texts: [], timeout_seconds: 120 };
}
return { enabled: true, entry_url: 'https://s360.dbschenker.com/main/portal/frame/WMSUpload2', file_input_selector: 'input#file2', submit_mode: 'auto_after_file', submit_selector: null, result_mode: 'page_notice', result_selector: null, success_texts: [], timeout_seconds: 120 };
}
const profile = reactive({ profile_code: '', display_name: '', connector_type: 'dbs', login_url: '', username: '', password: '', login_config_json: { auth_mode: 'password' }, enabled: true, upload_config_json: defaultUploadConfig('dbs') });
/** 成功文本以换行分隔的输入视图,写回 success_texts 数组。 */
const successTextsInput = computed<string>({
get: () => (profile.upload_config_json.success_texts || []).join('\n'),
set: (value) => { profile.upload_config_json.success_texts = String(value || '').split(/\r?\n/).map((item) => item.trim()).filter(Boolean); },
});
const parsing = reactive({ profile_code: '', display_name: '', file_format: 'xlsx', sheet_name: '', header_row_index: 1, field_mappings: [] as ParsingFieldMapping[], match_keys: [] as ParsingMatchKey[] });
const inventoryField = reactive<InventoryFieldForm>({ display_name: '', description: '', value_type: 'text', usage_type: 'general', sort_order: 100, status: 'active' });
const excelTemplate = reactive({ template_code: '', display_name: '', filename_pattern: '{business_no}.xlsx', mappings: [] as TemplateMapping[], file: null as File | null });
@@ -868,6 +912,14 @@ watch(
{ immediate: true },
);
/** 新建连接时按货代类型切换上传配置默认值;编辑既有连接不覆盖已保存配置。 */
watch(
() => profile.connector_type,
(nextType) => {
if (!selectedId.value) profile.upload_config_json = defaultUploadConfig(nextType);
},
);
/** 在库存映射内切换解析方案与字段目录,保持左侧业务入口不分裂。 */
function selectInventoryMappingTab(tab: 'parsing' | 'inventoryFields'): void {
activeTab.value = tab;
@@ -877,7 +929,7 @@ function selectInventoryMappingTab(tab: 'parsing' | 'inventoryFields'): void {
/** 重置当前工作区的编辑表单,作为创建新对象的入口。 */
function createNew(): void {
selectedId.value = null;
if (activeTab.value === 'profiles') Object.assign(profile, { profile_code: '', display_name: '', connector_type: 'dbs', login_url: '', username: '', password: '', login_config_json: { auth_mode: 'password' }, enabled: true });
if (activeTab.value === 'profiles') Object.assign(profile, { profile_code: '', display_name: '', connector_type: 'dbs', login_url: '', username: '', password: '', login_config_json: { auth_mode: 'password' }, enabled: true, upload_config_json: defaultUploadConfig('dbs') });
if (activeTab.value === 'parsing') { Object.assign(parsing, { profile_code: '', display_name: '', file_format: 'xlsx', sheet_name: '', header_row_index: 1, field_mappings: [], match_keys: [] }); structureAnalysis.value = null; pendingSampleReplacement.value = null; sampleReplacementConfirmed.value = false; selectedTemporaryInventorySession.value = ''; }
if (activeTab.value === 'inventoryFields') Object.assign(inventoryField, { display_name: '', description: '', value_type: 'text', usage_type: 'general', sort_order: 100, status: 'active' });
if (activeTab.value === 'templates') {
@@ -898,7 +950,7 @@ function createNew(): void {
/** 将列表对象复制到当前编辑表单,凭据字段永远不从列表回填。 */
function selectItem(item: Item): void {
selectedId.value = Number(item.id);
if (activeTab.value === 'profiles') Object.assign(profile, { ...item, username: '', password: '', login_config_json: item.login_config_json || { auth_mode: 'password' } });
if (activeTab.value === 'profiles') Object.assign(profile, { ...item, username: '', password: '', login_config_json: item.login_config_json || { auth_mode: 'password' }, upload_config_json: item.upload_config_json || defaultUploadConfig(item.connector_type) });
if (activeTab.value === 'parsing') Object.assign(parsing, {
profile_code: item.profile_code, display_name: item.display_name, file_format: item.file_format,
sheet_name: item.definition?.sheet_name || '', header_row_index: item.definition?.header_row_index ?? 0,
@@ -1067,7 +1119,7 @@ function closeDrawer(): void {
async function saveCurrent(): Promise<void> {
saving.value = true;
try {
if (activeTab.value === 'profiles') await saveShippingRpaProfile({ ...profile, display_name: profile.display_name || profile.profile_code }, selectedId.value || undefined);
if (activeTab.value === 'profiles') await saveShippingRpaProfile({ ...profile, display_name: profile.display_name || profile.profile_code, upload_config_json: profile.upload_config_json }, selectedId.value || undefined);
if (activeTab.value === 'parsing') {
const payload = {
profile_code: parsing.profile_code, display_name: parsing.display_name || parsing.profile_code, file_format: parsing.file_format,
@@ -1598,6 +1650,7 @@ onMounted(load);
.readiness-optional { border-top: 1px solid #e4edf2; padding-top: 10px; }.readiness-optional summary, .readiness-audit summary { display: flex; align-items: baseline; gap: 8px; color: #61798a; cursor: pointer; list-style: none; }.readiness-optional summary::-webkit-details-marker, .readiness-audit summary::-webkit-details-marker { display: none; }.readiness-optional summary::before, .readiness-audit summary::before { color: #4d849f; content: '›'; font-size: 16px; line-height: .8; transition: transform .15s; }.readiness-optional[open] summary::before, .readiness-audit[open] summary::before { transform: rotate(90deg); }.readiness-optional summary span { color: #516b7d; font-size: 12px; font-weight: 700; }.readiness-optional summary small { color: #8797a5; font-size: 11px; }.readiness-optional .readiness-steps { margin-top: 8px; }
.readiness-action { border: 0; border-radius: 5px; background: #e8f3f9; padding: 6px 8px; color: #16759f; font: inherit; font-size: 11px; font-weight: 700; cursor: pointer; }.readiness-action:hover { background: #d8edf7; }.readiness-run { margin: 0; border-left: 3px solid #74b8d8; background: #f0f8fc; padding: 8px 10px; color: #547185; font-size: 11px; line-height: 1.5; }.readiness-run.failed { border-left-color: #e06a58; background: #fff5f3; color: #9d382b; }.readiness-audit { margin: 0; border-top: 1px solid #e4edf2; padding-top: 10px; }.readiness-audit summary { color: #61798a; font-size: 11px; font-weight: 700; }.readiness-audit dl { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1px; margin: 9px 0 0; overflow: hidden; border: 1px solid #dce8ef; border-radius: 7px; background: #dce8ef; }.readiness-audit dl > div { min-width: 0; background: #fff; padding: 8px 9px; }.readiness-audit dt { color: #7b8998; font-size: 11px; font-weight: 700; }.readiness-audit dd { overflow: hidden; margin: 4px 0 0; color: #3d5366; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11px; font-variant-numeric: tabular-nums; text-overflow: ellipsis; white-space: nowrap; }.readiness-footer { display: flex; justify-content: flex-end; border-top: 1px solid #e6eef4; padding-top: 11px; }
.form-tip { border-radius: 8px; background: #f1f6fa; padding: 11px; color: #5d7084; font-size: 12px; line-height: 1.55; }
.upload-config-section { grid-column: 1 / -1; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; border: 1px solid #e1edf2; border-radius: 9px; background: #fff; padding: 0 12px 12px; }.upload-config-heading { display: grid; gap: 2px; grid-column: 1 / -1; padding: 11px 0 8px; }.upload-config-heading b { color: #385166; font-size: 12px; }.upload-config-heading small { color: #8192a0; font-size: 11px; }.upload-config-section .full { grid-column: 1 / -1; }.upload-config-section textarea.input-field { resize: vertical; }
.configuration-test-verified { margin: 0; border-left: 3px solid #34a56b; background: #effaf3; padding: 9px 10px; color: #256b43; font-size: 12px; font-weight: 600; line-height: 1.45; }
.sample-evidence-card { display: grid; gap: 12px; border: 1px solid #d7e3ed; border-radius: 8px; background: #f8fbfd; padding: 14px; }
.sample-evidence-card > div { display: grid; gap: 3px; }.sample-evidence-card strong { color: #334155; font-size: 13px; }.sample-evidence-card p, .sample-evidence-card > small { margin: 0; color: #6b7f91; font-size: 12px; line-height: 1.55; }