feat(shipping-notice): 添加 RPA 工作者心跳告警开关,更新环境配置以支持样本证据历史记录

This commit is contained in:
hugo committed 2026-07-19 23:15:25 +08:00
1 parent 705971ad03
commit 88408490d7
34 files changed
+1697 -109

No files matched your search

@@ -138,27 +138,50 @@
<label><span>{{ t('admin.shippingInventory.warehouseResolution') }}</span><select v-model="source.warehouse_resolution_mode"><option value="fixed">{{ t('admin.shippingInventory.fixedWarehouse') }}</option><option value="inventory_match">{{ t('admin.shippingInventory.inventoryMatch') }}</option></select></label>
<label v-if="source.warehouse_resolution_mode === 'fixed'"><span>{{ t('admin.shippingInventory.warehouse') }}</span><input v-model="source.fixed_warehouse_id" required></label>
<label><span>{{ t('admin.shippingInventory.snapshotTtl') }}</span><input v-model.number="source.snapshot_ttl_seconds" min="1" type="number" required></label>
<section v-if="selectedId" class="activation-panel full">
<strong>{{ t('admin.shippingInventory.activationStatus') }}</strong>
<p>{{ source.enabled ? t('admin.shippingInventory.activationReady') : t('admin.shippingInventory.activationDraft') }}</p>
<ul v-if="source.activation?.missing_requirements?.length">
<li v-for="requirement in source.activation.missing_requirements" :key="requirement">{{ t(`admin.shippingInventory.activationRequirement.${requirement}`) }}</li>
</ul>
<button v-if="!source.enabled" type="button" class="secondary-action" @click="requestSourceActivation">{{ t('admin.shippingInventory.activateSource') }}</button>
<button v-else type="button" class="secondary-action" @click="requestSourceDeactivation">{{ t('admin.shippingInventory.deactivateSource') }}</button>
</section>
<section v-if="selectedId && !source.enabled" class="activation-panel full">
<strong>{{ t('admin.shippingInventory.configurationTest') }}</strong>
<p>{{ t('admin.shippingInventory.configurationTestHint') }}</p>
<button type="button" class="secondary-action" :disabled="configurationTestLoading" @click="startConfigurationTest">{{ configurationTestLoading ? t('admin.shippingInventory.configurationTestRunning') : t('admin.shippingInventory.startConfigurationTest') }}</button>
<section v-if="selectedId" class="readiness-card full" :class="{ ready: source.enabled }">
<header class="readiness-heading">
<div>
<span class="readiness-kicker">{{ t('admin.shippingInventory.activationStatus') }}</span>
<strong>{{ source.enabled ? t('admin.shippingInventory.activationReady') : t('admin.shippingInventory.activationDraft') }}</strong>
</div>
<span class="readiness-count">{{ readinessSummary }}</span>
</header>
<ol class="readiness-steps">
<li v-for="check in readinessChecks" :key="check.code" :class="`is-${check.status}`">
<span class="readiness-marker" aria-hidden="true">{{ readinessMarker(check.status) }}</span>
<div class="readiness-copy">
<b>{{ t(`admin.shippingInventory.activationRequirement.${check.code}`) }}</b>
<small>{{ readinessDetail(check) }}</small>
</div>
<button
v-if="readinessActionLabel(check) && !source.enabled"
type="button"
class="readiness-action"
:disabled="isReadinessActionBlocked(check)"
:title="isReadinessActionBlocked(check) ? t('admin.shippingInventory.saveBeforeReadinessAction') : undefined"
@click="runReadinessAction(check)"
>{{ readinessActionLabel(check) }}</button>
</li>
</ol>
<p v-if="!source.enabled" class="readiness-note">{{ t('admin.shippingInventory.configurationTestHint') }}</p>
<template v-if="configurationTest">
<p>{{ t(`admin.shippingInventory.configurationTestStage.${configurationTest.stage}`) }}</p>
<p class="readiness-run" :class="{ failed: configurationTest.status === 'failed' }">{{ t(`admin.shippingInventory.configurationTestStage.${configurationTest.stage}`) }}</p>
<dl class="readiness-audit">
<div><dt>{{ t('admin.shippingInventory.configurationTestRunNo') }}</dt><dd>{{ configurationTest.run_no }}</dd></div>
<div><dt>{{ t('admin.shippingInventory.configurationTestConfigVersion') }}</dt><dd>{{ configurationTest.source_config_version }}</dd></div>
<div><dt>{{ t('admin.shippingInventory.configurationTestConnectionVersion') }}</dt><dd>{{ configurationTest.rpa_profile_config_version }}</dd></div>
<div><dt>{{ t('admin.shippingInventory.configurationTestUpdatedAt') }}</dt><dd>{{ formatDate(configurationTest.completed_at || configurationTest.created_at) }}</dd></div>
</dl>
<p v-if="configurationTest.error_message" class="form-tip">{{ configurationTest.error_message }}</p>
<section v-if="configurationTest.status === 'completed'" class="recommendation-list">
<article v-for="candidate in configurationTest.result?.analysis?.match_result?.candidates || []" :key="candidate.profile_id"><b>{{ candidate.display_name }} V{{ candidate.version }}</b><small>{{ t(`admin.shippingInventory.recommendationLevel.${candidate.level}`) }}</small><button type="button" class="secondary-action" @click="confirmTestProfile(candidate.profile_id)">{{ t('admin.shippingInventory.confirmTestProfile') }}</button></article>
<p v-if="!(configurationTest.result?.analysis?.match_result?.candidates || []).length">{{ t('admin.shippingInventory.configurationTestNoRecommendation') }}</p>
</section>
</template>
<footer class="readiness-footer">
<button v-if="!source.enabled" type="button" class="primary-action" :disabled="!source.activation?.ready || sourceDirty" :title="sourceDirty ? t('admin.shippingInventory.saveBeforeReadinessAction') : undefined" @click="requestSourceActivation">{{ t('admin.shippingInventory.activateSource') }}</button>
<button v-else type="button" class="text-action danger" @click="requestSourceDeactivation">{{ t('admin.shippingInventory.deactivateSource') }}</button>
</footer>
</section>
<div v-if="!selectedId" class="form-tip full">{{ t('admin.shippingInventory.sourceSavedDisabledHint') }}</div>
<template v-if="source.connector_type === 'dbs'">
@@ -217,7 +240,20 @@
<label><span>{{ t('admin.shippingInventory.fileFormat') }}</span><select v-model="parsing.file_format"><option value="xls">xls</option><option value="xlsx">xlsx</option><option value="csv">csv</option></select></label>
<label v-if="!selectedId" class="full"><span>{{ t('admin.shippingInventory.temporaryInventorySession') }}</span><select v-model="selectedTemporaryInventorySession" @change="loadTemporaryInventorySession"><option value="">{{ t('admin.shippingInventory.temporaryInventorySessionNone') }}</option><option v-for="item in temporaryInventorySessions" :key="item.session_no" :value="item.session_no">{{ item.source_file_name }} · {{ item.session_no }}</option></select><small>{{ t('admin.shippingInventory.temporaryInventorySessionHint') }}</small></label>
<div v-if="temporaryInventorySessionSelected" class="form-tip full">{{ t('admin.shippingInventory.temporaryInventorySessionSelected', { mapping: temporaryInventorySessionSelected.confirmed_usage?.mapping_origin || '-' }) }}</div>
<label class="full"><span>{{ t('admin.shippingInventory.inventorySampleFile') }}</span><input type="file" accept=".xls,.xlsx,.csv" :disabled="analysisLoading || Boolean(temporaryInventorySessionSelected)" @change="analyseInventorySample"><small>{{ t('admin.shippingInventory.inventorySampleFileHint') }}</small></label>
<label v-if="!selectedId" class="full"><span>{{ t('admin.shippingInventory.inventorySampleFile') }}</span><input type="file" accept=".xls,.xlsx,.csv" :disabled="analysisLoading || Boolean(temporaryInventorySessionSelected)" @change="analyseInventorySample"><small>{{ t('admin.shippingInventory.inventorySampleFileHint') }}</small></label>
<section v-else-if="structureAnalysis" class="sample-evidence-card full">
<div>
<strong>{{ pendingSampleReplacement ? t('admin.shippingInventory.pendingInventorySampleReplacement') : t('admin.shippingInventory.savedInventorySample') }}</strong>
<p>{{ pendingSampleReplacement ? t('admin.shippingInventory.pendingInventorySampleReplacementHint') : t('admin.shippingInventory.savedInventorySampleHint') }}</p>
</div>
<dl>
<div><dt>{{ t('admin.shippingInventory.sampleFileName') }}</dt><dd>{{ structureAnalysis.source_file_name || '-' }}</dd></div>
<div><dt>{{ t('admin.shippingInventory.fileFormat') }}</dt><dd>{{ String(structureAnalysis.file_format || parsing.file_format).toUpperCase() }}</dd></div>
<div><dt>{{ t('admin.shippingInventory.sampleRowsRetained') }}</dt><dd>{{ structureAnalysis.sample_rows?.length || 0 }}</dd></div>
</dl>
<label class="sample-replacement-input"><span>{{ t('admin.shippingInventory.replaceInventorySample') }}</span><input type="file" accept=".xls,.xlsx,.csv" :disabled="analysisLoading" @change="analyseInventorySample"><small>{{ t('admin.shippingInventory.replaceInventorySampleHint') }}</small></label>
<div v-if="pendingSampleReplacement" class="sample-replacement-warning"><p>{{ sampleReplacementNotice }}</p><ul><li v-for="line in sampleReplacementDifferenceLines" :key="line">{{ line }}</li></ul></div>
</section>
<div v-if="analysisLoading" class="form-tip full">{{ t('admin.shippingInventory.inventorySampleAnalysing') }}</div>
<template v-if="structureAnalysis">
<label><span>{{ t('admin.shippingInventory.sheetName') }}</span><select v-model="parsing.sheet_name" @change="applyAnalysisCandidate"><option v-for="candidate in analysisCandidates" :key="candidateKey(candidate)" :value="candidate.sheet_name || ''">{{ candidate.sheet_name || t('admin.shippingInventory.csvFile') }}</option></select></label>
@@ -383,11 +419,13 @@ import {
getShippingExcelTemplateLayout,
createShippingInventoryStructureAnalysis,
createShippingInventoryParsingDraftFromAnalysis,
previewShippingInventorySampleReplacement,
createShippingParsingDraftFromTemporarySession,
adoptShippingInventoryParsingProfile,
listShippingTemporaryInventorySessions,
startShippingInventoryConfigurationTest,
getShippingInventoryConfigurationTest,
getLatestShippingInventoryConfigurationTest,
confirmShippingInventoryConfigurationTestProfile,
downloadShippingInventorySnapshot,
updateShippingExcelTemplate,
@@ -404,6 +442,8 @@ import {
saveShippingInventorySource,
saveShippingRpaProfile,
} from '@/features/admin/api/admin.api';
import type { ShippingInventoryConfigurationTest, ShippingInventoryReadinessCheck } from '@/features/admin/api/admin.api';
import { isConfigurationTestRunning, needsReadinessAction, readinessMarkerKind } from './shippingInventoryReadiness';
type TabKey = 'orderSchema' | 'profiles' | 'parsing' | 'inventoryFields' | 'templates' | 'sources' | 'rules' | 'snapshots' | 'exports' | 'mappings';
type Item = Record<string, any>;
@@ -413,6 +453,7 @@ type ParsingFieldMapping = { inventory_field: string; source_header: string };
type ParsingMatchKey = { order_field_id: string; inventory_field: string };
type TemplateMapping = { sheet: string; row_mode: 'header' | 'line'; start_row: number; target_column: number; source_kind: 'order_field' | 'inventory_field' | 'system_fact' | 'constant'; source_key: string; formatter: string };
type InventoryFieldForm = { display_name: string; description: string; value_type: 'text' | 'integer' | 'decimal' | 'date'; usage_type: 'match_identity' | 'inventory_quantity' | 'warehouse_identity' | 'general'; sort_order: number; status: 'active' | 'retired' };
type SourceActivation = { ready: boolean; checks: ShippingInventoryReadinessCheck[]; missing_requirements: string[] };
const { t } = useI18n();
const message = useMessage();
@@ -423,7 +464,7 @@ const orderSchemaPublished = ref(false);
const saving = ref(false);
const confirmation = reactive({
visible: false,
action: '' as 'delete' | 'retireRule' | 'retireTemplate' | 'retireParsing' | 'retireInventoryField' | 'activateSource' | 'deactivateSource' | '',
action: '' as 'delete' | 'retireRule' | 'retireTemplate' | 'retireParsing' | 'retireInventoryField' | 'activateSource' | 'deactivateSource' | 'replaceInventorySample' | '',
title: '',
message: '',
confirmText: '',
@@ -444,11 +485,13 @@ const auditDetail = ref<{ kind: 'snapshot' | 'export'; item: Item } | null>(null
const parsingProfiles = ref<Item[]>([]);
const inventoryFields = ref<Item[]>([]);
const structureAnalysis = ref<Item | null>(null);
const pendingSampleReplacement = ref<Item | null>(null);
const sampleReplacementConfirmed = ref(false);
const temporaryInventorySessions = ref<Item[]>([]);
const selectedTemporaryInventorySession = ref('');
const analysisLoading = ref(false);
const excelTemplates = ref<Item[]>([]);
const configurationTest = ref<Item | null>(null);
const configurationTest = ref<ShippingInventoryConfigurationTest | null>(null);
const configurationTestLoading = ref(false);
let configurationTestTimer: number | null = null;
const routingFields = ref<Array<{ field_id: string; field_code: string; display_name: string; description?: string; scope: 'header' | 'line' }>>([]);
@@ -482,7 +525,8 @@ const profile = reactive({ profile_code: '', display_name: '', connector_type: '
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 });
const source = reactive({ source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, parsing_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [] as Parameter[], match_aliases_json: [] as string[], enabled: false, activation: { ready: false, missing_requirements: [] as string[] } });
const source = reactive({ source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, parsing_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [] as Parameter[], match_aliases_json: [] as string[], enabled: false, activation: { ready: false, checks: [] as ShippingInventoryReadinessCheck[], missing_requirements: [] as string[] } as SourceActivation });
const sourceBaseline = ref('');
const rule = reactive({ rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', system_fact_key: '', operator: 'prefix', expected: '' }] as RuleCondition[], source_codes: [] as string[] });
const mapping = reactive({ inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true });
const compatibleRoutingFields = computed(() => routingFields.value.filter((item) => item.scope === (rule.scope === 'task' ? 'header' : 'line')));
@@ -498,6 +542,29 @@ const matchingOrderFields = computed(() => routingFields.value.filter((field) =>
const canAddParsingMatchKey = computed(() => Boolean(
structureAnalysis.value && unusedMatchingInventoryFields.value.length && unusedOrderMatchFields.value.length,
));
const sourceDirty = computed(() => Boolean(selectedId.value && sourceBaseline.value && sourceBaseline.value !== serialiseSourceInput()));
const readinessChecks = computed<ShippingInventoryReadinessCheck[]>(() => source.activation?.checks || []);
const readinessSummary = computed(() => {
const total = readinessChecks.value.length;
const passed = readinessChecks.value.filter((item) => item.status === 'passed').length;
return t('admin.shippingInventory.readinessProgress', { passed, total });
});
const sampleReplacementNotice = computed(() => {
const difference = pendingSampleReplacement.value?.difference || {};
const missing = Array.isArray(difference.missing_mapped_headers) ? difference.missing_mapped_headers : [];
if (difference.file_format_changed) return t('admin.shippingInventory.sampleReplacementFileFormatChanged');
return missing.length
? t('admin.shippingInventory.sampleReplacementMappingRequired', { columns: missing.join('、') })
: t('admin.shippingInventory.sampleReplacementReady');
});
const sampleReplacementDifferenceLines = computed(() => {
const difference = pendingSampleReplacement.value?.difference || {};
const lines: string[] = [];
if (Array.isArray(difference.added_columns) && difference.added_columns.length) lines.push(t('admin.shippingInventory.sampleReplacementAddedColumns', { columns: difference.added_columns.join('、') }));
if (Array.isArray(difference.missing_columns) && difference.missing_columns.length) lines.push(t('admin.shippingInventory.sampleReplacementMissingColumns', { columns: difference.missing_columns.join('、') }));
if (difference.column_order_changed) lines.push(t('admin.shippingInventory.sampleReplacementColumnOrderChanged'));
return lines;
});
const operators = [
{ value: 'equals', label: t('admin.shippingInventory.operatorEquals') }, { value: 'not_equals', label: t('admin.shippingInventory.operatorNotEquals') },
{ value: 'in', label: t('admin.shippingInventory.operatorIn') }, { value: 'not_in', label: t('admin.shippingInventory.operatorNotIn') },
@@ -662,14 +729,17 @@ 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 === 'parsing') { Object.assign(parsing, { profile_code: '', display_name: '', file_format: 'xlsx', sheet_name: '', header_row_index: 1, field_mappings: [], match_keys: [] }); structureAnalysis.value = null; selectedTemporaryInventorySession.value = ''; }
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') {
Object.assign(excelTemplate, { template_code: '', display_name: '', filename_pattern: '{business_no}.xlsx', mappings: [], file: null });
templateSheets.value = [];
templateSheetColumns.value = {};
}
if (activeTab.value === 'sources') Object.assign(source, { source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, parsing_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [], match_aliases_json: [], enabled: false, activation: { ready: false, missing_requirements: ['configuration_test'] } });
if (activeTab.value === 'sources') {
Object.assign(source, { source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, parsing_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [], match_aliases_json: [], enabled: false, activation: { ready: false, checks: [], missing_requirements: ['configuration_test'] } });
sourceBaseline.value = '';
}
if (activeTab.value === 'rules') Object.assign(rule, { rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', system_fact_key: '', operator: 'prefix', expected: '' }], source_codes: [] });
if (activeTab.value === 'mappings') Object.assign(mapping, { inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true });
drawerOpen.value = true;
@@ -685,6 +755,13 @@ function selectItem(item: Item): void {
field_mappings: Object.entries(item.definition?.field_mapping || {}).map(([inventory_field, source_header]) => ({ inventory_field, source_header: String(source_header) })),
match_keys: (item.definition?.match_keys || []).map((entry: Record<string, unknown>) => ({ order_field_id: String(entry.order_field_id || ''), inventory_field: String(entry.inventory_field_id || entry.inventory_field || '') })),
});
if (activeTab.value === 'parsing') {
// 草稿恢复保存的最小化样本证据,而不是要求管理员再次上传原始库存文件。
structureAnalysis.value = item.sample_evidence || null;
pendingSampleReplacement.value = null;
sampleReplacementConfirmed.value = false;
selectedTemporaryInventorySession.value = '';
}
if (activeTab.value === 'inventoryFields') Object.assign(inventoryField, {
display_name: item.display_name || '', description: item.description || '', value_type: item.value_type || 'text',
usage_type: item.usage_type || 'general', sort_order: Number(item.sort_order || 100),
@@ -705,7 +782,11 @@ function selectItem(item: Item): void {
templateSheetColumns.value = {};
void loadTemplateLayout(selectedId.value);
}
if (activeTab.value === 'sources') Object.assign(source, { ...item, fixed_warehouse_id: item.fixed_warehouse_id || '', report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '', ...(item.report_path_json || {}) }, query_parameters_json: (item.query_parameters_json || []).map((parameter: Parameter) => ({ ...parameter })), match_aliases_json: [...(item.match_aliases_json || [])] });
if (activeTab.value === 'sources') {
Object.assign(source, { ...item, fixed_warehouse_id: item.fixed_warehouse_id || '', report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '', ...(item.report_path_json || {}) }, query_parameters_json: (item.query_parameters_json || []).map((parameter: Parameter) => ({ ...parameter })), match_aliases_json: [...(item.match_aliases_json || [])] });
sourceBaseline.value = serialiseSourceInput();
void restoreConfigurationTest(Number(item.id));
}
if (activeTab.value === 'rules') Object.assign(rule, {
rule_code: item.rule_code || '', rule_name: item.rule_name || '', scope: item.scope || 'line', priority: item.priority || 0,
conditions: (item.conditions?.length ? item.conditions : [{ source_kind: 'order_field', order_field_id: '', operator: 'prefix', expected_value_json: '' }]).map((condition: Record<string, unknown>) => ({
@@ -734,6 +815,7 @@ function closeDrawer(): void {
if (configurationTestTimer !== null) window.clearTimeout(configurationTestTimer);
configurationTestTimer = null;
configurationTest.value = null;
sourceBaseline.value = '';
drawerOpen.value = false;
selectedId.value = null;
}
@@ -754,7 +836,21 @@ async function saveCurrent(): Promise<void> {
await createShippingParsingDraftFromTemporarySession(selectedTemporaryInventorySession.value, payload);
} else {
if (!structureAnalysis.value) throw new Error(t('admin.shippingInventory.inventorySampleRequired'));
await createShippingInventoryParsingDraftFromAnalysis(Number(structureAnalysis.value.id), { ...payload, profile_id: selectedId.value || undefined });
if (pendingSampleReplacement.value && !sampleReplacementConfirmed.value) {
const preview = await previewShippingInventorySampleReplacement(selectedId.value!, Number(structureAnalysis.value.id), {
field_mapping: payload.field_mapping,
}) as Item;
pendingSampleReplacement.value = preview;
if (!preview.can_confirm) throw new Error(t('admin.shippingInventory.sampleReplacementCannotConfirm'));
confirmation.visible = true;
confirmation.action = 'replaceInventorySample';
confirmation.title = t('admin.shippingInventory.replaceInventorySample');
confirmation.message = t('admin.shippingInventory.replaceInventorySampleConfirm');
confirmation.confirmText = t('admin.shippingInventory.confirmSampleReplacement');
confirmation.tone = 'primary';
return;
}
await createShippingInventoryParsingDraftFromAnalysis(Number(structureAnalysis.value.id), { ...payload, profile_id: selectedId.value || undefined, confirm_sample_replacement: sampleReplacementConfirmed.value });
}
}
if (activeTab.value === 'inventoryFields') {
@@ -846,6 +942,7 @@ async function confirmPendingAction(): Promise<void> {
if (action === 'retireInventoryField') await retireShippingInventoryField(selectedId.value);
if (action === 'activateSource') await activateShippingInventorySource(selectedId.value);
if (action === 'deactivateSource') await deactivateShippingInventorySource(selectedId.value);
if (action === 'replaceInventorySample') { sampleReplacementConfirmed.value = true; await saveCurrent(); return; }
if (action === 'delete' && activeTab.value === 'profiles') await deleteShippingRpaProfile(selectedId.value);
if (action === 'delete' && activeTab.value === 'sources') await deleteShippingInventorySource(selectedId.value);
if (action === 'delete' && activeTab.value === 'templates') await deleteShippingExcelTemplate(selectedId.value);
@@ -885,18 +982,31 @@ async function startConfigurationTest(): Promise<void> {
if (!selectedId.value) return;
configurationTestLoading.value = true;
try {
configurationTest.value = await startShippingInventoryConfigurationTest(selectedId.value) as Item;
configurationTest.value = await startShippingInventoryConfigurationTest(selectedId.value);
await pollConfigurationTest();
} catch (cause) { showError(cause, 'configurationTestFailed'); }
finally { configurationTestLoading.value = false; }
}
/** 恢复当前配置对应的最近测试;只有服务端标记为运行中时才重新启动轮询。 */
async function restoreConfigurationTest(sourceId: number): Promise<void> {
try {
const latest = await getLatestShippingInventoryConfigurationTest(sourceId);
if (selectedId.value !== sourceId) return;
configurationTest.value = latest;
if (isConfigurationTestRunning(latest)) await pollConfigurationTest();
} catch (cause) { showError(cause, 'configurationTestFailed'); }
}
/** 读取测试运行的真实异步阶段;完成或失败后停止轮询。 */
async function pollConfigurationTest(): Promise<void> {
if (!selectedId.value || !configurationTest.value?.run_no) return;
const sourceId = selectedId.value;
const runNo = configurationTest.value?.run_no;
if (!sourceId || !runNo) return;
try {
configurationTest.value = await getShippingInventoryConfigurationTest(selectedId.value, String(configurationTest.value.run_no)) as Item;
if (['awaiting_rpa', 'processing'].includes(String(configurationTest.value.status))) {
const updated = await getShippingInventoryConfigurationTest(sourceId, runNo);
configurationTest.value = updated;
if (isConfigurationTestRunning(updated)) {
configurationTestTimer = window.setTimeout(() => { void pollConfigurationTest(); }, 2000);
}
} catch (cause) { showError(cause, 'configurationTestFailed'); }
@@ -953,12 +1063,23 @@ async function analyseInventorySample(event: Event): Promise<void> {
if (!file) return;
analysisLoading.value = true;
try {
structureAnalysis.value = await createShippingInventoryStructureAnalysis(file) as Item;
const analysis = await createShippingInventoryStructureAnalysis(file) as Item;
if (selectedId.value) {
const preview = await previewShippingInventorySampleReplacement(selectedId.value, Number(analysis.id)) as Item;
pendingSampleReplacement.value = preview;
sampleReplacementConfirmed.value = false;
}
structureAnalysis.value = analysis;
const structure = structureAnalysis.value.structure || {};
parsing.file_format = String(structureAnalysis.value.file_format || 'xlsx');
parsing.sheet_name = String(structure.selected_sheet_name || '');
parsing.header_row_index = Number(structure.selected_header_row_index || 1);
parsing.field_mappings = Object.entries(structureAnalysis.value.suggested_mapping || {}).map(([inventory_field, source_header]) => ({ inventory_field, source_header: String(source_header) }));
if (selectedId.value) {
// 替换样本时保留仍存在的既有映射,避免自动建议覆盖管理员已经确认的业务关系。
applyAnalysisCandidate();
} else {
parsing.field_mappings = Object.entries(structureAnalysis.value.suggested_mapping || {}).map(([inventory_field, source_header]) => ({ inventory_field, source_header: String(source_header) }));
}
} catch (cause) { showError(cause, 'inventoryAnalysisFailed'); }
finally { analysisLoading.value = false; }
}
@@ -1084,6 +1205,61 @@ function formatDate(value: unknown): string { return value ? new Date(String(val
function auditDate(value: unknown): string { return value ? formatDate(value) : t('admin.shippingInventory.historyNotCaptured'); }
function sourceName(sourceCode: unknown): string { return String(sourceCode || t('admin.shippingInventory.historyNotCaptured')); }
function parsingProfileName(profileId: unknown): string { const item = parsingProfiles.value.find((row) => Number(row.id) === Number(profileId)); return String(item?.display_name || item?.profile_code || t('admin.shippingInventory.notGenerated')); }
/** 将会影响测试输入的站点字段稳定序列化,用于阻止管理员针对未保存配置运行测试或启用。 */
function serialiseSourceInput(): string {
return JSON.stringify({
source_code: source.source_code, display_name: source.display_name, connector_type: source.connector_type,
rpa_profile_id: source.rpa_profile_id, parsing_profile_id: source.parsing_profile_id,
excel_template_id: source.excel_template_id, warehouse_resolution_mode: source.warehouse_resolution_mode,
fixed_warehouse_id: source.fixed_warehouse_id, snapshot_ttl_seconds: source.snapshot_ttl_seconds,
report_path_json: source.report_path_json, query_parameters_json: source.query_parameters_json,
match_aliases_json: source.match_aliases_json,
});
}
/** 返回状态轨道的简洁可视标记,文本状态仍由相邻内容提供,避免颜色成为唯一信息来源。 */
function readinessMarker(status: ShippingInventoryReadinessCheck['status']): string {
const marker = readinessMarkerKind(status);
if (marker === 'complete') return '✓';
if (marker === 'attention') return '!';
return '•';
}
/** 将服务端脱敏证据翻译为管理员可理解的当前步骤说明。 */
function readinessDetail(check: ShippingInventoryReadinessCheck): string {
if (check.status === 'passed') return t('admin.shippingInventory.readinessState.passed');
if (check.status === 'stale') return t('admin.shippingInventory.readinessState.stale');
if (check.status === 'failed') return t('admin.shippingInventory.readinessState.failed');
return check.blocking ? t('admin.shippingInventory.readinessState.required') : t('admin.shippingInventory.readinessState.waiting');
}
/** 每项门禁只映射一个推荐动作;已经通过和依赖测试的辅助检查不额外制造操作入口。 */
function readinessActionLabel(check: ShippingInventoryReadinessCheck): string {
if (!needsReadinessAction(check)) return '';
if (check.action === 'run_configuration_test') return configurationTestLoading.value
? t('admin.shippingInventory.configurationTestRunning')
: t('admin.shippingInventory.startConfigurationTest');
return t(`admin.shippingInventory.readinessAction.${check.action}`);
}
/** 未保存的 Source 编辑必须先提交到服务端,确保测试和启用都基于同一配置版本。 */
function isReadinessActionBlocked(check: ShippingInventoryReadinessCheck): boolean {
return sourceDirty.value || (check.action === 'run_configuration_test' && configurationTestLoading.value);
}
/** 将阻断项引导到所属配置区域;测试动作仍停留在当前站点抽屉内执行。 */
function runReadinessAction(check: ShippingInventoryReadinessCheck): void {
if (isReadinessActionBlocked(check)) {
message.warning(t('admin.shippingInventory.saveBeforeReadinessAction'));
return;
}
if (check.action === 'run_configuration_test') { void startConfigurationTest(); return; }
const target: Record<Exclude<ShippingInventoryReadinessCheck['action'], 'run_configuration_test'>, TabKey> = {
configure_connection: 'profiles', configure_parsing_profile: 'parsing',
configure_excel_template: 'templates', configure_warehouse_mapping: 'mappings',
};
selectTab(target[check.action]);
}
function connectionName(sourceCode: unknown): string { const sourceItem = sources.value.find((source) => source.source_code === sourceCode); const profileItem = profiles.value.find((profile) => Number(profile.id) === Number(sourceItem?.rpa_profile_id)); return profileItem?.profile_code || t('admin.shippingInventory.historyNotCaptured'); }
function warehouseName(item: Item): string { return item.warehouse_id || (item.source_code === 'CRANE' ? t('admin.shippingInventory.dynamicWarehouse') : t('admin.shippingInventory.historyNotCaptured')); }
function auditStatus(value: unknown): string { const key = String(value || 'unknown'); return t(`admin.shippingInventory.auditStatus.${key}`); }
@@ -1137,7 +1313,7 @@ onMounted(load);
.workbench-heading p { max-width: 660px; margin: 5px 0 0; color: #64748b; font-size: 13px; }
.primary-action, .secondary-action, .text-action { border: 0; border-radius: 6px; padding: 8px 12px; font-size: 13px; font-weight: 600; cursor: pointer; }
.primary-action { background: #0ea5e9; color: #fff; }
.primary-action:disabled, .text-action:disabled { opacity: .5; cursor: not-allowed; }
.primary-action:disabled, .secondary-action:disabled, .text-action:disabled { opacity: .5; cursor: not-allowed; }
.secondary-action { background: #f1f5f9; color: #475569; }
.text-action { background: transparent; padding: 4px; color: #0284c7; }
.text-action.danger { color: #b42318; }
@@ -1173,7 +1349,15 @@ onMounted(load);
.filename-variable-menu { position: absolute; z-index: 3; top: calc(100% + 5px); left: 0; width: min(440px, 100%); overflow: hidden; border: 1px solid #cfdde7; border-radius: 7px; background: #fff; box-shadow: 0 10px 24px rgb(15 23 42 / 14%); padding: 4px; }
.filename-variable-menu button { display: grid; width: 100%; grid-template-columns: 154px minmax(0, 1fr); gap: 8px; border: 0; border-radius: 4px; background: transparent; padding: 7px 8px; color: #64748b; font: inherit; font-size: 12px; text-align: left; cursor: pointer; }
.filename-variable-menu button:hover, .filename-variable-menu button.active { background: #eef8f7; color: #145f5a; }.filename-variable-menu code { color: #047f76; font-size: 12px; }.filename-variable-menu p { margin: 0; padding: 8px; color: #94a3b8; font-size: 12px; }
.readiness-card { display: grid; gap: 13px; border: 1px solid #d9e6ef; border-radius: 10px; background: linear-gradient(135deg, #fbfdff, #f4f9fc); padding: 15px; }.readiness-card.ready { border-color: #b7e4c7; background: linear-gradient(135deg, #fbfffc, #f2fbf5); }
.readiness-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }.readiness-heading > div { display: grid; gap: 4px; }.readiness-kicker { color: #64748b; font-size: 11px; font-weight: 700; letter-spacing: .05em; text-transform: uppercase; }.readiness-heading strong { color: #263b4e; font-size: 13px; line-height: 1.45; }.readiness-count { flex: 0 0 auto; border-radius: 999px; background: #eaf4fa; padding: 4px 8px; color: #176f9f; font-size: 11px; font-weight: 700; }.readiness-card.ready .readiness-count { background: #e8f7ed; color: #19703a; }
.readiness-steps { display: grid; gap: 0; margin: 0; padding: 0; list-style: none; }.readiness-steps li { display: grid; grid-template-columns: 24px minmax(0, 1fr) auto; align-items: center; gap: 9px; min-height: 48px; border-top: 1px solid #e6eef4; padding: 8px 0; }.readiness-marker { display: inline-grid; width: 20px; height: 20px; place-items: center; border-radius: 50%; background: #e9eef3; color: #6c7d8d; font-size: 12px; font-weight: 800; }.readiness-copy { display: grid; min-width: 0; gap: 2px; }.readiness-copy b { overflow: hidden; color: #425466; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }.readiness-copy small { color: #8190a0; font-size: 11px; line-height: 1.35; }.readiness-steps .is-passed .readiness-marker { background: #dff6e6; color: #16803a; }.readiness-steps .is-passed .readiness-copy b { color: #2d6b40; }.readiness-steps .is-failed .readiness-marker, .readiness-steps .is-stale .readiness-marker { background: #fff0ed; color: #bf4a38; }.readiness-steps .is-failed .readiness-copy b, .readiness-steps .is-stale .readiness-copy b { color: #9d382b; }
.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-note, .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 { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 1px; margin: 0; overflow: hidden; border: 1px solid #dce8ef; border-radius: 7px; background: #dce8ef; }.readiness-audit > div { min-width: 0; background: #fff; padding: 8px 9px; }.readiness-audit dt { color: #7b8998; font-size: 10px; font-weight: 700; letter-spacing: .03em; }.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; }
.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; }
.sample-evidence-card dl { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px 16px; margin: 0; }.sample-evidence-card dl div { min-width: 0; }.sample-evidence-card dt { color: #8190a0; font-size: 11px; }.sample-evidence-card dd { margin: 3px 0 0; overflow-wrap: anywhere; color: #475569; font-size: 12px; font-weight: 600; }
.sample-replacement-input { display: grid; gap: 6px; border-top: 1px solid #e5edf3; padding-top: 11px; color: #52677a; font-size: 12px; font-weight: 600; }.sample-replacement-input input { max-width: 100%; }.sample-replacement-warning { border-left: 3px solid #e5a21a; background: #fff9eb; padding: 8px 10px; color: #855e00 !important; }.sample-replacement-warning p { margin: 0; }.sample-replacement-warning ul { display: grid; gap: 3px; margin: 7px 0 0; padding-left: 17px; }
.parameter-row { display: grid; align-items: center; grid-template-columns: 1.1fr .9fr 1.25fr auto auto auto; gap: 8px; border-radius: 8px; background: #f8fafc; padding: 9px; }
.condition-row, .mapping-row, .template-mapping { display: grid; align-items: center; gap: 8px; border-radius: 8px; background: #f8fafc; padding: 9px; }
.condition-row { grid-template-columns: 1.15fr .9fr 1fr auto; }
@@ -1214,6 +1398,6 @@ onMounted(load);
.audit-detail dl { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 0; margin: 0; padding: 18px 20px; }.audit-detail dt, .audit-detail dd { margin: 0; padding: 11px 0; border-bottom: 1px solid #edf2f7; font-size: 13px; }.audit-detail dt { color: #64748b; }.audit-detail dd { overflow-wrap: anywhere; color: #334155; }
.object-list .empty-state { grid-column: 1 / -1; display: grid; min-height: 260px; place-items: center; }
.empty-state { border: 1px dashed #c9d7e5; border-radius: 10px; background: #f9fbfd; padding: 38px 18px; color: #7b899a; font-size: 13px; text-align: center; }
@media (max-width: 980px) { .console-header { display: block; } .flow-strip { display: inline-flex; margin-top: 18px; } .console-layout { grid-template-columns: 1fr; } .section-nav { flex-direction: row; gap: 12px; overflow-x: auto; } .nav-group { display: flex; align-items: center; gap: 4px; } .nav-group > p { display: none; } .section-nav button { min-width: max-content; border-bottom: 3px solid transparent; border-left: 0; } .section-nav button.active { border-bottom-color: #16877f; border-left: 0; } .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card { grid-template-columns: 1fr 1fr; } .mapping-value-row { grid-template-columns: minmax(0, 1.6fr) minmax(180px, 1fr); } }
@media (max-width: 640px) { .inventory-console { padding: 18px; } .editor-form, .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card, .mapping-value-row, .parsing-mapping-card, .readonly-mapping-section .parsing-mapping-card, .parsing-summary { grid-template-columns: 1fr; } .mapping-arrow { transform: rotate(90deg); }.workbench-heading { display: block; } .workbench-heading .primary-action { margin-top: 12px; } }
@media (max-width: 980px) { .console-header { display: block; } .flow-strip { display: inline-flex; margin-top: 18px; } .console-layout { grid-template-columns: 1fr; } .section-nav { flex-direction: row; gap: 12px; overflow-x: auto; } .nav-group { display: flex; align-items: center; gap: 4px; } .nav-group > p { display: none; } .section-nav button { min-width: max-content; border-bottom: 3px solid transparent; border-left: 0; } .section-nav button.active { border-bottom-color: #16877f; border-left: 0; } .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card { grid-template-columns: 1fr 1fr; } .mapping-value-row { grid-template-columns: minmax(0, 1.6fr) minmax(180px, 1fr); }.readiness-audit { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 640px) { .inventory-console { padding: 18px; } .editor-form, .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card, .mapping-value-row, .parsing-mapping-card, .readonly-mapping-section .parsing-mapping-card, .parsing-summary { grid-template-columns: 1fr; } .mapping-arrow { transform: rotate(90deg); }.workbench-heading { display: block; } .workbench-heading .primary-action { margin-top: 12px; } .readiness-heading { display: grid; }.readiness-count { justify-self: start; }.readiness-steps li { grid-template-columns: 24px minmax(0, 1fr); }.readiness-action { grid-column: 2; justify-self: start; }.readiness-footer { justify-content: stretch; }.readiness-footer .primary-action { width: 100%; } }
</style>
@@ -0,0 +1,36 @@
/**
* features/admin/modules/shipping-inventory/shippingInventoryReadiness.spec.ts
* 用途:覆盖库存站点上线检查与测试恢复的纯状态映射。
* 依赖:shippingInventoryReadiness、vitest。
* 逻辑:防止页面把已完成项目显示为待办,或持续轮询服务端已结束的测试任务。
*/
import { describe, expect, it } from 'vitest';
import type { ShippingInventoryReadinessCheck } from '@/features/admin/api/admin.api';
import { isConfigurationTestRunning, needsReadinessAction, readinessMarkerKind } from './shippingInventoryReadiness';
const check = (status: ShippingInventoryReadinessCheck['status'], blocking: boolean): ShippingInventoryReadinessCheck => ({
code: 'configuration_test', status, blocking, action: 'run_configuration_test', evidence: {},
});
describe('shippingInventoryReadiness', () => {
it('keeps stale checks actionable and visually distinct from ordinary pending work', () => {
// 关键断言:配置已变更的测试不能被渲染成普通待办,管理员必须重新测试。
expect(readinessMarkerKind('stale')).toBe('attention');
expect(needsReadinessAction(check('stale', true))).toBe(true);
});
it('does not offer duplicate actions for passed or non-blocking checks', () => {
// 关键断言:后端已经通过或依赖前置步骤的项目不应再次分散管理员注意力。
expect(needsReadinessAction(check('passed', false))).toBe(false);
expect(needsReadinessAction(check('pending', false))).toBe(false);
});
it('polls only server-declared running test states', () => {
// 关键断言:完成与失败均是终态,页面不得凭前端时间继续请求详情接口。
expect(isConfigurationTestRunning({ run_no: 'RUN-1', status: 'awaiting_rpa', stage: 'waiting_worker' })).toBe(true);
expect(isConfigurationTestRunning({ run_no: 'RUN-2', status: 'processing', stage: 'analysing_structure' })).toBe(true);
expect(isConfigurationTestRunning({ run_no: 'RUN-3', status: 'completed', stage: 'ready_for_confirmation' })).toBe(false);
expect(isConfigurationTestRunning({ run_no: 'RUN-4', status: 'failed', stage: 'failed' })).toBe(false);
});
});
@@ -0,0 +1,42 @@
/**
* features/admin/modules/shipping-inventory/shippingInventoryReadiness.ts
* 用途:归一库存站点上线检查与配置测试的前端展示状态。
* 依赖:admin.api 中的 Inventory Readiness/Test 类型。
* 逻辑:ShippingInventoryPage 调用本文件决定测试轮询、步骤标记和推荐动作;后端仍是门禁真相源。
*/
import type { ShippingInventoryConfigurationTest, ShippingInventoryReadinessCheck } from '@/features/admin/api/admin.api';
export type ReadinessMarker = 'complete' | 'attention' | 'pending';
/**
* 将后端检查状态归类为无障碍视觉标记。
* 核心逻辑:失败和过期都需要管理员处理;完成与待办分别使用稳定语义。
* @param status - 后端 `checks[]` 返回的稳定状态。
* @returns 供页面选择图形和颜色的有限标记,不参与启用门禁计算。
*/
export function readinessMarkerKind(status: ShippingInventoryReadinessCheck['status']): ReadinessMarker {
if (status === 'passed') return 'complete';
if (status === 'failed' || status === 'stale') return 'attention';
return 'pending';
}
/**
* 判断一个检查项是否应展示其唯一推荐操作。
* 核心逻辑:已通过和仅等待其他前置步骤的检查不提供重复入口。
* @param check - 后端权威检查项。
* @returns 为 true 时页面可展示对应的单一下一步动作。
*/
export function needsReadinessAction(check: ShippingInventoryReadinessCheck): boolean {
return check.status !== 'passed' && check.blocking;
}
/**
* 判断测试运行是否需要继续向服务端轮询。
* 核心逻辑:仅运行态轮询;失败与完成均为终态,防止页面无限请求。
* @param test - 当前恢复或新发起的测试运行。
* @returns 是否继续轮询。
*/
export function isConfigurationTestRunning(test: ShippingInventoryConfigurationTest | null): boolean {
return Boolean(test && ['awaiting_rpa', 'processing'].includes(test.status));
}