Merge branch 'dev' into order-delivery-reply

# Conflicts:
#	.env.shared
#	backend/app/api/chat.py
#	backend/app/core/config/settings.py
#	backend/app/models/user.py
#	backend/app/services/admin/permission_service.py
#	docs/demand.md
#	frontend/src/app/router/routes/workspace.routes.ts
#	frontend/src/features/admin/modules/users/components/UserFormModal.vue
#	frontend/src/features/admin/modules/users/composables/useUsersAdmin.ts
#	frontend/src/features/admin/types/user.types.ts
#	frontend/src/features/auth/stores/auth.store.ts
#	frontend/src/features/user/views/UserProfilePage.vue
#	frontend/src/locales/en/admin.json
#	frontend/src/locales/en/errors.json
#	frontend/src/locales/th/admin.json
#	frontend/src/locales/th/errors.json
#	frontend/src/locales/zh-CN/admin.json
#	frontend/src/locales/zh-CN/errors.json
#	frontend/src/locales/zh-TW/admin.json
#	frontend/src/locales/zh-TW/errors.json
#	frontend/src/shared/utils/auth.ts
This commit is contained in:
HTEWJ\26070045 committed 2026-09-22 10:37:59 +08:00
commit 616034a4cd
541 files changed
+43805 -14767

No files matched your search

@@ -129,88 +129,44 @@
<label><span>{{ t('admin.shippingInventory.warehouseResolution') }}</span><select v-model="source.warehouse_resolution_mode" class="select-field"><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" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.snapshotTtl') }}</span><input v-model.number="source.snapshot_ttl_seconds" class="input-field" min="1" type="number" required></label>
<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>{{ readinessHeadline }}</strong>
<p>{{ readinessGuidance }}</p>
</div>
<span class="readiness-count">{{ readinessSummary }}</span>
</header>
<section class="readiness-section">
<div class="readiness-section-heading">
<b>{{ t('admin.shippingInventory.activationRequiredTitle') }}</b>
<small>{{ t('admin.shippingInventory.activationRequiredHint') }}</small>
</div>
<ol v-if="firstBlockingCheck && !source.enabled" class="readiness-steps">
<li :class="`is-${firstBlockingCheck.status}`">
<span class="readiness-marker" aria-hidden="true">{{ readinessMarker(firstBlockingCheck.status) }}</span>
<div class="readiness-copy"><b>{{ t(`admin.shippingInventory.activationRequirement.${firstBlockingCheck.code}`) }}</b><small>{{ readinessDetail(firstBlockingCheck) }}</small></div>
<button v-if="readinessActionLabel(firstBlockingCheck)" type="button" class="readiness-action" :disabled="isReadinessActionBlocked(firstBlockingCheck)" :title="isReadinessActionBlocked(firstBlockingCheck) ? t('admin.shippingInventory.saveBeforeReadinessAction') : undefined" @click="runReadinessAction(firstBlockingCheck)">{{ readinessActionLabel(firstBlockingCheck) }}</button>
</li>
</ol>
</section>
<details v-if="optionalReadinessChecks.length" class="readiness-optional">
<summary><span>{{ t('admin.shippingInventory.activationOptionalTitle') }}</span><small>{{ t('admin.shippingInventory.activationOptionalHint') }}</small></summary>
<ol class="readiness-steps">
<li v-for="check in optionalReadinessChecks" :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>
</li>
</ol>
</details>
<template v-if="configurationTest">
<p class="readiness-run" :class="{ failed: configurationTest.status === 'failed' }">{{ t(`admin.shippingInventory.configurationTestStage.${configurationTest.stage}`) }}</p>
<details class="readiness-audit"><summary>{{ t('admin.shippingInventory.configurationTestRunNo') }} {{ configurationTest.run_no }}</summary><dl><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></details>
<p v-if="configurationTest.error_message" class="form-tip">{{ configurationTest.error_message }}</p>
<p v-if="configurationTest.status === 'completed_empty'" class="form-tip">{{ t('admin.shippingInventory.configurationTestEmptyResult') }}</p>
<section v-if="configurationTest.status === 'completed'" class="recommendation-list">
<p v-if="configurationTest.result?.current_profile_verified" class="configuration-test-verified">{{ t(`admin.shippingInventory.currentProfileVerified.${configurationTest.result.profile_match_level || 'compatible'}`) }}</p>
<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}`) }} · {{ t('admin.shippingInventory.configurationTestCandidateHint') }}</small></article>
<p v-if="!configurationTest.result?.current_profile_verified && !(configurationTest.result?.analysis?.match_result?.candidates || []).length">{{ t('admin.shippingInventory.configurationTestNoRecommendation') }}</p>
</section>
</template>
<footer v-if="source.enabled || source.activation?.ready" class="readiness-footer">
<button v-if="source.enabled" type="button" class="btn-danger btn-sm" @click="requestSourceDeactivation">{{ t('admin.shippingInventory.deactivateSource') }}</button>
<button
v-else
type="button"
class="btn-primary btn-sm"
:disabled="sourceDirty"
:title="sourceDirty ? t('admin.shippingInventory.saveBeforeReadinessAction') : undefined"
@click="requestSourceActivation"
>{{ t('admin.shippingInventory.activateSource') }}</button>
</footer>
</section>
<div v-if="!selectedId" class="form-tip full">{{ t('admin.shippingInventory.sourceSavedDisabledHint') }}</div>
<template v-if="source.connector_type === 'dbs'">
<div class="subsection full">{{ t('admin.shippingInventory.reportPath') }}</div>
<label><span>{{ t('admin.shippingInventory.programGroup') }}</span><input v-model="source.report_path_json.program_group" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.programLabel') }}</span><input v-model="source.report_path_json.program_label" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.reportGroup') }}</span><input v-model="source.report_path_json.report_group" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.reportName') }}</span><input v-model="source.report_path_json.report_name" class="input-field" required></label>
<div class="subsection full">{{ t('admin.shippingInventory.queryParameters') }}</div>
<div v-for="(parameter, index) in source.query_parameters_json" :key="`${index}-${parameter.name}`" class="parameter-row full">
<input v-model="parameter.name" class="input-field" :placeholder="t('admin.shippingInventory.parameterName')">
<select v-model="parameter.mode" class="select-field"><option value="single">{{ t('admin.shippingInventory.single') }}</option><option value="multi_text">{{ t('admin.shippingInventory.multiText') }}</option><option value="multi_select">{{ t('admin.shippingInventory.multiSelect') }}</option></select>
<input class="input-field" :value="parameter.values.join(', ')" :placeholder="t('admin.shippingInventory.parameterValues')" @input="parameter.values = splitValues(($event.target as HTMLInputElement).value)">
<label class="inline-check"><input v-model="parameter.required" type="checkbox">{{ t('admin.shippingInventory.required') }}</label>
<label class="inline-check"><input v-model="parameter.select_all" type="checkbox">{{ t('admin.shippingInventory.selectAll') }}</label>
<button type="button" class="btn-danger btn-sm" @click="source.query_parameters_json.splice(index, 1)">{{ t('admin.delete') }}</button>
<section class="path-card full">
<button type="button" class="path-card-header" :aria-expanded="inventoryPathOpen" @click="inventoryPathOpen = !inventoryPathOpen">
<span class="path-card-title"><b>{{ t('admin.shippingInventory.reportPath') }}</b></span>
<span class="path-card-toggle" aria-hidden="true">{{ inventoryPathOpen ? '▾' : '▸' }}</span>
</button>
<div v-show="inventoryPathOpen" class="path-card-body">
<label><span>{{ t('admin.shippingInventory.programGroup') }}</span><input v-model="source.report_path_json.program_group" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.programLabel') }}</span><input v-model="source.report_path_json.program_label" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.reportGroup') }}</span><input v-model="source.report_path_json.report_group" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.reportName') }}</span><input v-model="source.report_path_json.report_name" class="input-field" required></label>
<div class="subsection full">{{ t('admin.shippingInventory.queryParameters') }}</div>
<div v-for="(parameter, index) in source.query_parameters_json" :key="`${index}-${parameter.name}`" class="parameter-row full">
<input v-model="parameter.name" class="input-field" :placeholder="t('admin.shippingInventory.parameterName')">
<select v-model="parameter.mode" class="select-field"><option value="single">{{ t('admin.shippingInventory.single') }}</option><option value="multi_text">{{ t('admin.shippingInventory.multiText') }}</option><option value="multi_select">{{ t('admin.shippingInventory.multiSelect') }}</option></select>
<input class="input-field" :value="parameter.values.join(', ')" :placeholder="t('admin.shippingInventory.parameterValues')" @input="parameter.values = splitValues(($event.target as HTMLInputElement).value)">
<label class="inline-check"><input v-model="parameter.required" type="checkbox">{{ t('admin.shippingInventory.required') }}</label>
<label class="inline-check"><input v-model="parameter.select_all" type="checkbox">{{ t('admin.shippingInventory.selectAll') }}</label>
<button type="button" class="btn-danger btn-sm" @click="source.query_parameters_json.splice(index, 1)">{{ t('admin.delete') }}</button>
</div>
<button type="button" class="btn-secondary btn-sm full" @click="addParameter">{{ t('admin.shippingInventory.addParameter') }}</button>
</div>
<button type="button" class="btn-secondary btn-sm full" @click="addParameter">{{ t('admin.shippingInventory.addParameter') }}</button>
</template>
<section v-if="selectedId" class="receipt-report-config full">
<div class="subsection">{{ t('admin.shippingInventory.receiptReportConfig') }}<small>{{ t('admin.shippingInventory.receiptReportConfigHint') }}</small></div>
<div class="switch-field"><span>{{ t('admin.shippingInventory.receiptReportEnabled') }}</span><button type="button" class="status-switch" :class="{ on: receiptConfig.enabled }" role="switch" :aria-checked="receiptConfig.enabled" @click="receiptConfig.enabled = !receiptConfig.enabled"><i></i><b>{{ receiptConfig.enabled ? t('admin.shippingInventory.enabledState') : t('admin.shippingInventory.disabledState') }}</b></button></div>
</section>
</template>
<section v-if="selectedId" class="path-card receipt full" :class="{ configured: receiptConfigExists }">
<button type="button" class="path-card-header" :aria-expanded="receiptSectionOpen" @click="toggleReceiptSection">
<span class="path-card-title"><b>{{ t('admin.shippingInventory.receiptReportConfig') }}</b><small>{{ t('admin.shippingInventory.receiptReportConfigHint') }}</small></span>
<span class="path-badge" :class="receiptConfigExists ? 'on' : 'off'">{{ receiptConfigExists ? t('admin.shippingInventory.pathSectionConfigured') : t('admin.shippingInventory.pathSectionNotConfigured') }}</span>
<span class="path-card-toggle" aria-hidden="true">{{ receiptSectionOpen ? '▾' : '▸' }}</span>
</button>
<div v-show="receiptSectionOpen" class="path-card-body">
<template v-if="source.connector_type === 'dbs'">
<label><span>{{ t('admin.shippingInventory.programGroup') }}</span><input v-model="receiptConfig.report_path_json.program_group" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.programLabel') }}</span><input v-model="receiptConfig.report_path_json.program_label" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.reportGroup') }}</span><input v-model="receiptConfig.report_path_json.report_group" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.reportName') }}</span><input v-model="receiptConfig.report_path_json.report_name" class="input-field" required></label>
<label class="full"><span>{{ t('admin.shippingInventory.receiptWarehouses') }}</span><input class="input-field" :value="receiptConfig.warehouse_ids_json.join(', ')" :placeholder="t('admin.shippingInventory.receiptWarehousesHint')" @input="receiptConfig.warehouse_ids_json = splitValues(($event.target as HTMLInputElement).value)"></label>
<div class="subsection full">{{ t('admin.shippingInventory.receiptOptionalParameters') }}</div>
<div class="subsection full">{{ t('admin.shippingInventory.queryParameters') }}<small>{{ t('admin.shippingInventory.receiptQueryParametersHint') }}</small></div>
<div v-for="(parameter, index) in receiptConfig.query_parameters_json" :key="`receipt-${index}-${parameter.name}`" class="parameter-row full">
<input v-model="parameter.name" class="input-field" :placeholder="t('admin.shippingInventory.parameterName')">
<select v-model="parameter.mode" class="select-field"><option value="single">{{ t('admin.shippingInventory.single') }}</option><option value="multi_text">{{ t('admin.shippingInventory.multiText') }}</option><option value="multi_select">{{ t('admin.shippingInventory.multiSelect') }}</option></select>
@@ -222,8 +178,8 @@
<button type="button" class="btn-secondary btn-sm full" @click="addReceiptParameter">{{ t('admin.shippingInventory.addParameter') }}</button>
</template>
<p v-else class="form-tip full">{{ t('admin.shippingInventory.receiptCraneFixedPath') }}</p>
<div class="receipt-config-actions full"><button type="button" class="btn-secondary btn-sm" :disabled="receiptConfigLoading || receiptConfigSaving" @click="saveReceiptConfig">{{ receiptConfigSaving ? t('admin.shippingInventory.saving') : t('admin.shippingInventory.saveReceiptReportConfig') }}</button></div>
</section>
</div>
</section>
</template>
<template v-else-if="activeTab === 'parsing'">
@@ -377,6 +333,48 @@
<div class="switch-field"><span>{{ t('admin.shippingInventory.enabled') }}</span><button type="button" class="status-switch" :class="{ on: mapping.enabled }" role="switch" :aria-checked="mapping.enabled" @click="mapping.enabled = !mapping.enabled"><i></i><b>{{ mapping.enabled ? t('admin.shippingInventory.enabledState') : t('admin.shippingInventory.disabledState') }}</b></button></div>
</template>
<section v-if="selectedId" class="readiness-card full" :class="{ ready: source.enabled }">
<div class="readiness-inline">
<template v-if="source.enabled">
<span class="readiness-marker is-passed" aria-hidden="true">✓</span>
<div class="readiness-copy"><b>{{ t('admin.shippingInventory.activationReady') }}</b><small v-if="configurationTest?.completed_at">{{ t('admin.shippingInventory.readinessLastVerified', { time: formatDate(configurationTest.completed_at) }) }}</small></div>
<button type="button" class="btn-danger btn-sm" @click="requestSourceDeactivation">{{ t('admin.shippingInventory.deactivateSource') }}</button>
</template>
<template v-else-if="firstBlockingCheck">
<span class="readiness-marker" :class="`is-${firstBlockingCheck.status}`" aria-hidden="true">{{ readinessMarker(firstBlockingCheck.status) }}</span>
<div class="readiness-copy"><b>{{ t('admin.shippingInventory.readinessBlockedBy', { requirement: t(`admin.shippingInventory.activationRequirement.${firstBlockingCheck.code}`) }) }}</b><small>{{ t('admin.shippingInventory.readinessAutoEnableHint') }}</small></div>
<button v-if="readinessActionLabel(firstBlockingCheck)" type="button" class="readiness-action" :disabled="isReadinessActionBlocked(firstBlockingCheck)" :title="isReadinessActionBlocked(firstBlockingCheck) ? t('admin.shippingInventory.saveBeforeReadinessAction') : undefined" @click="runReadinessAction(firstBlockingCheck)">{{ readinessActionLabel(firstBlockingCheck) }}</button>
</template>
<template v-else>
<span class="readiness-marker is-passed" aria-hidden="true">✓</span>
<div class="readiness-copy"><b>{{ t('admin.shippingInventory.activationCanEnable') }}</b></div>
<button type="button" class="btn-primary btn-sm" :disabled="sourceDirty" :title="sourceDirty ? t('admin.shippingInventory.saveBeforeReadinessAction') : undefined" @click="requestSourceActivation">{{ t('admin.shippingInventory.activateSource') }}</button>
</template>
</div>
<details v-if="optionalReadinessChecks.length" class="readiness-optional">
<summary><span>{{ t('admin.shippingInventory.activationOptionalTitle') }}</span><small>{{ t('admin.shippingInventory.readinessOptionalPending', { count: optionalReadinessPending }) }}</small></summary>
<ol class="readiness-steps">
<li v-for="check in optionalReadinessChecks" :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>
</li>
</ol>
</details>
<template v-if="configurationTest">
<p v-if="configurationTest.status === 'failed'" class="readiness-run failed">{{ t(`admin.shippingInventory.configurationTestStage.${configurationTest.stage}`) }}</p>
<p v-if="configurationTest.error_message" class="form-tip">{{ configurationTest.error_message }}</p>
<p v-if="configurationTest.status === 'completed_empty'" class="form-tip">{{ t('admin.shippingInventory.configurationTestEmptyResult') }}</p>
<details v-if="configurationTest.status !== 'failed'" class="readiness-audit">
<summary>{{ t('admin.shippingInventory.configurationTestRunNo') }} {{ configurationTest.run_no }} · {{ t(`admin.shippingInventory.configurationTestStage.${configurationTest.stage}`) }}</summary>
<dl><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>
<section v-if="configurationTest.status === 'completed'" class="recommendation-list">
<p v-if="configurationTest.result?.current_profile_verified" class="configuration-test-verified">{{ t(`admin.shippingInventory.currentProfileVerified.${configurationTest.result.profile_match_level || 'compatible'}`) }}</p>
<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}`) }} · {{ t('admin.shippingInventory.configurationTestCandidateHint') }}</small></article>
<p v-if="!configurationTest.result?.current_profile_verified && !(configurationTest.result?.analysis?.match_result?.candidates || []).length">{{ t('admin.shippingInventory.configurationTestNoRecommendation') }}</p>
</section>
</details>
</template>
</section>
<div v-if="isEditableTab" class="form-actions full">
<button v-if="!parsingReadOnly" type="submit" class="btn-primary" :disabled="saving || ruleReadOnly || templateReadOnly || inventoryFieldReadOnly">{{ saving ? t('admin.shippingInventory.saving') : t('admin.save') }}</button>
<button v-if="activeTab === 'rules' && selectedId && selectedRuleStatus === 'draft'" type="button" class="btn-secondary btn-sm" @click="publishCurrentRule">{{ t('admin.shippingInventory.publish') }}</button>
@@ -627,9 +625,12 @@ const bulkBinding = reactive({ visible: false, sourceIds: [] as number[], profil
const batchValidation = reactive({ visible: false, sourceIds: [] as number[], query: '', statusFilter: 'all' as 'all' | 'processing' | 'completed' | 'completed_empty' | 'failed', saving: false, result: null as ShippingInventoryValidationBatch | null });
let batchValidationTimer: number | null = 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[], enabled: false, activation: { ready: false, checks: [] as ShippingInventoryReadinessCheck[], missing_requirements: [] as string[] } as SourceActivation });
const receiptConfig = reactive({ enabled: false, report_path_json: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '' } as Record<string, string>, query_parameters_json: [] as Parameter[], warehouse_ids_json: [] as string[] });
const receiptConfigLoading = ref(false);
const receiptConfigSaving = ref(false);
const receiptConfig = reactive({ report_path_json: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '' } as Record<string, string>, query_parameters_json: [] as Parameter[] });
const receiptConfigExists = ref(false);
const receiptSectionTouched = ref(false);
const receiptSectionOpen = ref(false);
const inventoryPathOpen = ref(true);
const receiptBaseline = ref('');
const sourceBaseline = ref('');
const rule = reactive({ rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', 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 });
@@ -646,26 +647,15 @@ 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 sourceDirty = computed(() => Boolean(selectedId.value && (
(sourceBaseline.value && sourceBaseline.value !== serialiseSourceInput())
|| (receiptConfigExists.value && receiptBaseline.value && receiptBaseline.value !== serialiseReceiptInput())
)));
const readinessChecks = computed<ShippingInventoryReadinessCheck[]>(() => source.activation?.checks || []);
const requiredReadinessChecks = computed(() => readinessChecks.value.filter((item) => item.blocking));
const firstBlockingCheck = computed(() => requiredReadinessChecks.value.find((item) => item.status !== 'passed'));
const optionalReadinessChecks = computed(() => readinessChecks.value.filter((item) => !item.blocking));
const readinessSummary = computed(() => {
const required = requiredReadinessChecks.value;
const total = required.length;
const passed = required.filter((item) => item.status === 'passed').length;
return t('admin.shippingInventory.readinessProgress', { passed, total });
});
const readinessHeadline = computed(() => {
if (source.enabled) return t('admin.shippingInventory.activationReady');
return source.activation?.ready ? t('admin.shippingInventory.activationCanEnable') : t('admin.shippingInventory.activationDraft');
});
const readinessGuidance = computed(() => source.enabled
? t('admin.shippingInventory.activationEnabledHint')
: source.activation?.ready
? t('admin.shippingInventory.activationCanEnableHint')
: t('admin.shippingInventory.activationMissingHint'));
const optionalReadinessPending = computed(() => optionalReadinessChecks.value.filter((item) => item.status !== 'passed').length);
const sampleReplacementNotice = computed(() => {
const difference = pendingSampleReplacement.value?.difference || {};
const missing = Array.isArray(difference.missing_mapped_headers) ? difference.missing_mapped_headers : [];
@@ -848,36 +838,37 @@ async function load(): Promise<void> {
}
}
/** 重置当前站点的独立收料表单,不借用库存报表路径或查询条件。 */
/** 重置当前站点的独立收料表单与卡片状态,与库存同构(路径+查询条件)。 */
function resetReceiptConfig(connectorType: unknown): void {
Object.assign(receiptConfig, {
enabled: false,
report_path_json: String(connectorType || '').toLowerCase() === 'crane'
? { report_name: 'Inbound Details' }
: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '' },
query_parameters_json: [],
warehouse_ids_json: [],
});
}
/** 读取收料独立配置;读取失败不影响库存站点配置和既有库存运行。 */
async function loadReceiptConfig(sourceId: number, connectorType: unknown): Promise<void> {
receiptConfigLoading.value = true;
resetReceiptConfig(connectorType);
receiptConfigExists.value = false;
receiptSectionTouched.value = false;
receiptSectionOpen.value = false;
receiptBaseline.value = '';
try {
const config = await getShippingReceiptReportConfig(sourceId);
if (!config) return;
const isCrane = String(connectorType || '').toLowerCase() === 'crane';
Object.assign(receiptConfig, {
enabled: Boolean(config.enabled),
report_path_json: isCrane
? { report_name: 'Inbound Details' }
: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '', ...((config.report_path_json || {}) as Record<string, string>) },
query_parameters_json: Array.isArray(config.query_parameters_json) ? config.query_parameters_json.map((parameter) => ({ ...parameter })) : [],
warehouse_ids_json: Array.isArray(config.warehouse_ids_json) ? [...config.warehouse_ids_json].map(String) : [],
});
receiptConfigExists.value = true;
receiptSectionOpen.value = true;
} catch (cause) { showError(cause, 'loadFailed'); }
finally { receiptConfigLoading.value = false; }
finally { receiptBaseline.value = serialiseReceiptInput(); }
}
/** 新增 DBS 可选收料条件;Crane 固定默认查询,不维护查询条件。 */
@@ -885,16 +876,10 @@ function addReceiptParameter(): void {
receiptConfig.query_parameters_json.push({ name: '', mode: 'single', values: [], required: false, select_all: false });
}
/** 仅提交白名单收料字段到独立 API,绝不调用库存 Source 保存接口。 */
async function saveReceiptConfig(): Promise<void> {
if (!selectedId.value) return;
receiptConfigSaving.value = true;
try {
await saveShippingReceiptReportConfig(selectedId.value, buildReceiptReportConfigPayload(receiptConfig));
await loadReceiptConfig(selectedId.value, source.connector_type);
message.success(t('admin.shippingInventory.receiptReportSaved'));
} catch (cause) { showError(cause, 'saveFailed'); }
finally { receiptConfigSaving.value = false; }
/** 展开收料卡即视为有配置意图:统一保存时会提交收料配置,避免未展开时误建空配置。 */
function toggleReceiptSection(): void {
receiptSectionOpen.value = !receiptSectionOpen.value;
if (receiptSectionOpen.value) receiptSectionTouched.value = true;
}
/** 切换管理对象时同步深链并清空选择,避免不同对象的数据残留在编辑器中。 */
@@ -949,6 +934,11 @@ function createNew(): void {
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: [], enabled: false, activation: { ready: false, checks: [], missing_requirements: ['configuration_test'] } });
resetReceiptConfig('dbs');
receiptConfigExists.value = false;
receiptSectionTouched.value = false;
receiptSectionOpen.value = false;
inventoryPathOpen.value = true;
receiptBaseline.value = '';
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: '', operator: 'prefix', expected: '' }], source_codes: [] });
@@ -1174,7 +1164,21 @@ async function saveCurrent(): Promise<void> {
await createShippingExcelTemplate(form);
}
}
if (activeTab.value === 'sources') await saveShippingInventorySource({ ...source, enabled: false, fixed_warehouse_id: source.warehouse_resolution_mode === 'fixed' ? source.fixed_warehouse_id : null, report_path_json: normaliseInventoryReportPath(source.connector_type, source.report_path_json) }, selectedId.value || undefined);
if (activeTab.value === 'sources') {
await saveShippingInventorySource({ ...source, enabled: false, fixed_warehouse_id: source.warehouse_resolution_mode === 'fixed' ? source.fixed_warehouse_id : null, report_path_json: normaliseInventoryReportPath(source.connector_type, source.report_path_json) }, selectedId.value || undefined);
// 收料与站点同批保存:仅当已有配置或管理员展开过收料卡时才提交,避免未配置站点被误建空收料配置。
if (selectedId.value && (receiptSectionTouched.value || (receiptConfigExists.value && receiptBaseline.value !== serialiseReceiptInput()))) {
try {
await saveShippingReceiptReportConfig(selectedId.value, buildReceiptReportConfigPayload(receiptConfig));
receiptConfigExists.value = true;
receiptBaseline.value = serialiseReceiptInput();
} catch (cause) {
showError(cause, 'saveFailed');
await load();
return; // 站点已保存但收料保存失败:保持抽屉打开,修正后可直接重试统一保存。
}
}
}
if (activeTab.value === 'rules') await saveShippingInventoryRule({ rule_code: rule.rule_code, rule_name: rule.rule_name || rule.rule_code, scope: rule.scope, priority: rule.priority, match_mode: 'all', action_type: 'add_source_candidates', action_payload_json: { source_codes: splitValues(rule.source_codes) }, conditions: rule.conditions.map((condition) => ({ source_kind: 'order_field', order_field_id: condition.order_field_id, operator: condition.operator, expected_value_json: normalizeExpectedValue(condition) })) }, selectedId.value || undefined);
if (activeTab.value === 'mappings') await saveShippingInventoryExternalMapping({ ...mapping, freight_warehouse_id: mapping.freight_warehouse_id || null, external_organization_code: mapping.external_organization_code || null, external_site_code: mapping.external_site_code || null }, selectedId.value || undefined);
await load();
@@ -1553,6 +1557,14 @@ function serialiseSourceInput(): string {
});
}
/** 将收料配置表单稳定序列化,作为统一保存与启用守卫的收料脏检查基线。 */
function serialiseReceiptInput(): string {
return JSON.stringify({
report_path_json: receiptConfig.report_path_json,
query_parameters_json: receiptConfig.query_parameters_json,
});
}
/** 返回状态轨道的简洁可视标记,文本状态仍由相邻内容提供,避免颜色成为唯一信息来源。 */
function readinessMarker(status: ShippingInventoryReadinessCheck['status']): string {
const marker = readinessMarkerKind(status);
@@ -1673,10 +1685,10 @@ onMounted(load);
.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: 12px; border: 1px solid #cfe2ea; border-radius: 12px; background: #fbfdfe; padding: 16px; }.readiness-card.ready { border-color: #b9dfc4; background: #fcfffd; }
.readiness-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }.readiness-heading > div { display: grid; gap: 5px; }.readiness-kicker { color: #5f798c; font-size: 11px; font-weight: 700; letter-spacing: .04em; }.readiness-heading strong { color: #263b4e; font-size: 14px; line-height: 1.4; }.readiness-heading p { margin: 0; color: #6d8292; font-size: 12px; line-height: 1.45; }.readiness-count { flex: 0 0 auto; border: 1px solid #cce7f1; border-radius: 999px; background: #edf8fc; padding: 5px 9px; color: #176f9f; font-size: 12px; font-weight: 700; white-space: nowrap; }.readiness-card.ready .readiness-count { border-color: #cce8d4; background: #eef9f1; color: #19703a; }
.readiness-section { border: 1px solid #e1edf2; border-radius: 9px; background: #fff; padding: 0 12px; }.readiness-section-heading { display: grid; gap: 2px; padding: 11px 0 8px; }.readiness-section-heading b { color: #385166; font-size: 12px; }.readiness-section-heading small { color: #8192a0; font-size: 11px; }.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: 46px; border-top: 1px solid #edf2f5; padding: 7px 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-inline { display: flex; align-items: center; gap: 10px; }.readiness-inline .readiness-copy { flex: 1 1 auto; }.readiness-inline .readiness-copy b { white-space: normal; }.readiness-inline .readiness-copy small { white-space: normal; }.readiness-inline .btn-sm, .readiness-inline .readiness-action { flex: 0 0 auto; }
.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: 46px; border-top: 1px solid #edf2f5; padding: 7px 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-inline > .readiness-marker.is-passed { background: #dff6e6; color: #16803a; }.readiness-inline > .readiness-marker.is-failed, .readiness-inline > .readiness-marker.is-stale { background: #fff0ed; color: #bf4a38; }
.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; }
.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; }
.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; }
@@ -1685,9 +1697,12 @@ onMounted(load);
.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; }
.receipt-report-config { display: grid; grid-column: 1 / -1; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; border-top: 1px solid #dbe8ee; margin-top: 8px; padding-top: 14px; }
.receipt-report-config .subsection, .receipt-report-config .full { grid-column: 1 / -1; }
.receipt-config-actions { display: flex; justify-content: flex-end; }
.path-card { display: grid; grid-column: 1 / -1; border: 1px solid #dbe8ee; border-radius: 10px; background: #fff; overflow: hidden; }
.path-card-header { display: flex; align-items: center; gap: 10px; border: 0; background: #f7fbfd; padding: 10px 12px; cursor: pointer; font: inherit; text-align: left; }.path-card-header:hover { background: #eff7fa; }
.path-card-title { display: grid; flex: 1 1 auto; min-width: 0; gap: 2px; }.path-card-title b { color: #145f5a; font-size: 12px; font-weight: 800; }.path-card-title small { color: #94a3b8; font-size: 11px; font-weight: 400; }
.path-badge { flex: 0 0 auto; border-radius: 999px; background: #eef2f5; padding: 3px 8px; color: #7b8998; font-size: 11px; font-weight: 700; }.path-card.configured .path-badge.on { background: #e6f6ec; color: #19703a; }
.path-card-toggle { flex: 0 0 auto; color: #4d849f; font-size: 14px; line-height: 1; }
.path-card-body { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; border-top: 1px solid #e6eef4; padding: 14px 12px; }.path-card-body .full { grid-column: 1 / -1; }
.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; }
.mapping-row { grid-template-columns: 1fr 1fr auto; }
@@ -1728,5 +1743,5 @@ onMounted(load);
.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) { .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, .receipt-report-config { grid-template-columns: 1fr; } .mapping-arrow { transform: rotate(90deg); }.workbench-heading { display: block; } .workbench-heading .btn-primary { margin-top: 12px; }.batch-source-list { grid-template-columns: 1fr; }.batch-stat-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }.batch-run { grid-template-columns: 9px minmax(0, 1fr); }.batch-run-error { grid-column: 2; }.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 .btn-primary { width: 100%; } }
@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, .path-card-body { grid-template-columns: 1fr; } .mapping-arrow { transform: rotate(90deg); }.workbench-heading { display: block; } .workbench-heading .btn-primary { margin-top: 12px; }.batch-source-list { grid-template-columns: 1fr; }.batch-stat-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }.batch-run { grid-template-columns: 9px minmax(0, 1fr); }.batch-run-error { grid-column: 2; }.readiness-inline { flex-wrap: wrap; }.readiness-steps li { grid-template-columns: 24px minmax(0, 1fr); }.readiness-action { grid-column: 2; justify-self: start; } }
</style>
@@ -2,7 +2,8 @@
* features/admin/modules/shipping-inventory/receiptReportConfigForm.spec.ts
* 用途:覆盖收料报表表单的独立载荷边界。
* 依赖:receiptReportConfigForm、vitest。
* 逻辑:防止收料配置保存时把库存站点路径、库存查询条件或启停状态误发到库存接口。
* 逻辑:防止收料配置保存时把库存站点路径、库存查询条件或启停状态误发到库存接口;
* 收料无独立启停字段,载荷不得包含 enabled。
*/
import { describe, expect, it } from 'vitest';
@@ -10,24 +11,30 @@ import { buildReceiptReportConfigPayload } from './receiptReportConfigForm';
describe('receiptReportConfigForm', () => {
it('builds a receipt-only payload without inventory source fields', () => {
// 关键断言:收料路径、条件与仓库必须走独立 API,不能夹带库存 RPA 配置。
// 关键断言:收料路径与条件必须走独立 API,不能夹带库存 RPA 配置或启停字段。
const payload = buildReceiptReportConfigPayload({
enabled: true,
report_path_json: { program_group: 'Bison', program_label: 'AWSBI', report_group: 'Inbound', report_name: 'Receipt Detail' },
query_parameters_json: [{ name: 'Owner', mode: 'single', values: ['AWS'], required: false, select_all: false }],
warehouse_ids_json: ['A', 'B'],
query_parameters_json: [
{ name: 'Warehouse', mode: 'multi_text', values: ['AWSDU', 'AWSDU-02'], required: false, select_all: false },
{ name: 'Owner', mode: 'single', values: ['AWS'], required: false, select_all: false },
],
source_code: 'INVENTORY-SHOULD-NOT-LEAK',
snapshot_ttl_seconds: 86400,
enabled: true,
warehouse_ids_json: ['SHOULD-NOT-LEAK'],
inventory_report_path_json: { report_name: 'On Hand' },
});
} as Parameters<typeof buildReceiptReportConfigPayload>[0] & Record<string, unknown>);
expect(payload).toEqual({
enabled: true,
report_path_json: { program_group: 'Bison', program_label: 'AWSBI', report_group: 'Inbound', report_name: 'Receipt Detail' },
query_parameters_json: [{ name: 'Owner', mode: 'single', values: ['AWS'], required: false, select_all: false }],
warehouse_ids_json: ['A', 'B'],
query_parameters_json: [
{ name: 'Warehouse', mode: 'multi_text', values: ['AWSDU', 'AWSDU-02'], required: false, select_all: false },
{ name: 'Owner', mode: 'single', values: ['AWS'], required: false, select_all: false },
],
});
expect(payload).not.toHaveProperty('source_code');
expect(payload).not.toHaveProperty('snapshot_ttl_seconds');
expect(payload).not.toHaveProperty('enabled');
expect(payload).not.toHaveProperty('warehouse_ids_json');
});
});
@@ -2,14 +2,13 @@
* features/admin/modules/shipping-inventory/receiptReportConfigForm.ts
* 用途:构建独立收料报表配置的受限保存载荷。
* 依赖:无外部依赖。
* 逻辑:页面仅将收料路径、可选条件和 Warehouse 列表提交到收料配置 API,隔离库存站点字段。
* 逻辑:页面仅将收料路径与查询条件提交到收料配置 API,与库存同构(Warehouse 为条件之一),
* 隔离库存站点字段;收料无独立启停字段,是否运行统一由库存站点 enabled 决定。
*/
export type ReceiptReportConfigInput = {
enabled: boolean;
report_path_json: Record<string, unknown>;
query_parameters_json: Array<Record<string, unknown>>;
warehouse_ids_json: string[];
};
/**
@@ -20,9 +19,7 @@ export type ReceiptReportConfigInput = {
*/
export function buildReceiptReportConfigPayload(input: ReceiptReportConfigInput): ReceiptReportConfigInput {
return {
enabled: Boolean(input.enabled),
report_path_json: { ...(input.report_path_json || {}) },
query_parameters_json: (input.query_parameters_json || []).map((item) => ({ ...item })),
warehouse_ids_json: [...(input.warehouse_ids_json || [])],
};
}
@@ -613,6 +613,14 @@ const coordinateCanvasActions = computed<OrderProfileCanvasActions>(() => ({
page: (nextPageNo) => { void selectPage(nextPageNo); },
draw: (kind) => startDrawing(kind),
}));
/** 页图 token 失效时自动重签;客户端渲染失败(如 worker MIME)不得超过预算。 */
let previewReauthInFlight = false;
let previewAutoReauthCount = 0;
const PREVIEW_AUTO_REAUTH_LIMIT = 2;
const resetPreviewAutoReauthBudget = () => {
previewAutoReauthCount = 0;
};
/**
* 共享视觉画布模型:模板差异在此处一次性被 adapter 吸收,之后所有画布事件和 props
* 均只消费 visualCanvas。datasets path、集合与拆分规则不属于视觉模型,继续留在 XFA
@@ -659,7 +667,10 @@ const visualCanvas = computed<OrderProfileVisualCanvasAdapter>(() => {
warningVisible: adapterWarningVisible || canvasUnavailable.value,
warningText: adapterWarningText
|| (canvasUnavailable.value ? t('admin.shippingOrderProfiles.workbench.canvasUnavailable') : null),
retryCanvas: () => { void loadPages(); },
retryCanvas: () => {
resetPreviewAutoReauthBudget();
void loadPages();
},
reportCanvasLoadFailed: () => { canvasUnavailable.value = true; },
applyAutomarkCandidates: () => false,
canRender: true,
@@ -814,13 +825,13 @@ const deskCanvasReadonly = computed(() => visualCanvas.value.canvasReadonly);
const deskCanvasWarningVisible = computed(() => visualCanvas.value.warningVisible);
const deskCanvasWarningText = computed(() => visualCanvas.value.warningText || '');
const onDeskCanvasRetry = () => visualCanvas.value.retryCanvas();
/** 页图 token 失效时自动重签一批预览令牌,避免翻页后只能手动点「重试画布」。 */
let previewReauthInFlight = false;
/** 页图/原 PDF 令牌 HTTP 失效时自动重签;客户端渲染失败不得走此路径(见 DocumentCanvas)。 */
const onDeskCanvasLoadFailed = async () => {
if (previewReauthInFlight) {
if (previewReauthInFlight || previewAutoReauthCount >= PREVIEW_AUTO_REAUTH_LIMIT) {
visualCanvas.value.reportCanvasLoadFailed();
return;
}
previewAutoReauthCount += 1;
previewReauthInFlight = true;
try {
await loadPages();
@@ -14,11 +14,12 @@ const { getDocumentMock, getPageMock, renderMock } = vi.hoisted(() => ({
renderMock: vi.fn(),
}));
vi.mock('pdfjs-dist', () => ({
GlobalWorkerOptions: {},
getDocument: (...args: unknown[]) => getDocumentMock(...args),
vi.mock('@/shared/utils/pdfjs', () => ({
loadPdfJs: async () => ({
GlobalWorkerOptions: {},
getDocument: (...args: unknown[]) => getDocumentMock(...args),
}),
}));
vi.mock('pdfjs-dist/build/pdf.worker.min.mjs?url', () => ({ default: '/pdf.worker.min.mjs' }));
vi.mock('@/shared/utils/auth', () => ({ getAuthHeaders: () => ({ Authorization: 'Bearer test' }) }));
describe('OrderProfileDocumentCanvas PDF preview', () => {
@@ -274,4 +275,89 @@ describe('OrderProfileDocumentCanvas PDF preview', () => {
// 使用 PDF.js 原始像素而不是 CSS 缩放后的大小,保证回读与用户框选区域一致。
expect(drawImage).toHaveBeenCalledWith(source, 60, 160, 181, 240, 0, 0, 181, 240);
});
it('keeps pdfCanvas mounted under pdfPreview error overlay and does not reauth on render failure', async () => {
getDocumentMock.mockReturnValue({
promise: Promise.resolve({
numPages: 1,
getPage: vi.fn(async () => {
throw new Error('PDF canvas is unavailable');
}),
}),
});
const wrapper = mount(OrderProfileDocumentCanvas, {
props: {
profileId: 71,
pdfPreview: { preview_token: 'single-use-token' },
regions: [], pageNo: 1, pageCount: 1,
},
global: {
plugins: [createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
admin: { shippingOrderProfiles: { workbench: { canvasUnavailable: '受控 PDF 画布暂不可用', retryCanvas: '重试' } } },
},
},
})],
},
});
await flushPromises();
await flushPromises();
// 关键断言:原 PDF 路径失败不得卸掉 canvas,否则重试/reauth 后 render 仍读到 null。
expect(wrapper.find('canvas.pdf-page').exists()).toBe(true);
expect(wrapper.find('.canvas-error-overlay').exists()).toBe(true);
expect(wrapper.emitted('loadFailed')).toBeUndefined();
});
it('reuses in-memory PDF bytes for the same single-use preview token', async () => {
const wrapper = mount(OrderProfileDocumentCanvas, {
props: {
profileId: 71,
pdfPreview: { preview_token: 'single-use-token' },
regions: [], pageNo: 1, pageCount: 1,
},
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] },
});
await flushPromises();
await flushPromises();
expect(fetch).toHaveBeenCalledTimes(1);
// 改 grant 依赖重入 watch,但 pdfPreview token 不变;必须走内存缓存,否则 getdel 二次 GET=404。
await wrapper.setProps({
grant: { page_no: 1, preview_token: 'png-ignored' },
pdfPreview: { preview_token: 'single-use-token' },
});
await flushPromises();
await flushPromises();
expect(fetch).toHaveBeenCalledTimes(1);
});
it('emits loadFailed only for preview-token HTTP failures', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response('', { status: 404 })));
const wrapper = mount(OrderProfileDocumentCanvas, {
props: {
profileId: 71,
pdfPreview: { preview_token: 'dead-token' },
regions: [], pageNo: 1, pageCount: 1,
},
global: {
plugins: [createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
admin: { shippingOrderProfiles: { workbench: { canvasUnavailable: '受控 PDF 画布暂不可用', retryCanvas: '重试' } } },
},
},
})],
},
});
await flushPromises();
await flushPromises();
expect(wrapper.emitted('loadFailed')).toHaveLength(1);
expect(wrapper.find('canvas.pdf-page').exists()).toBe(true);
});
});
@@ -4,6 +4,9 @@
依赖:浏览器 fetch、认证请求头、OrderProfileCanvasRegion、isUnboundOrderFieldCanvasRegion。
逻辑:父级签发单页令牌并提供分页动作;mode=readonly 时只允许查看/缩放/切页,不允许写入任何标注改动;
PNG 预览 token 为一次性消费,组件内按页缓存 blob,翻页回访不再重新拉 token;
原 PDF(pdf-preview)令牌亦为 Redis getdel 单次消费:同 token 字节必须缓存,且仅 HTTP 401/403/404
才 emit loadFailed 触发父级 reauth;画布/渲染失败不得重签,否则会空转授权风暴;
pdfPreview 错误态用 overlay,禁止 v-if 卸掉 pdfCanvas(否则 renderPdfPage 必失败);
未绑定订单字段框强制高亮(region--unbound),并暴露 scrollRegionIntoView 供横幅定位删除;
选中框用 top/right/bottom/left 定位(避免 height% 在内容撑高容器上失效);
拖拽/缩放进行中忽略滚轮缩放,避免触控板纵向手势把高度调整抢走;
@@ -16,28 +19,11 @@ import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Anchor, ArrowLeft, ArrowRight, Columns3, Copy, Eraser, MessageSquareText, Minus, Plus, Redo2, RotateCcw, Rows3, Save, TableProperties, Tag, TextCursorInput, Trash2, WandSparkles } from 'lucide-vue-next';
import { getAuthHeaders } from '@/shared/utils/auth';
import { loadPdfJs } from '@/shared/utils/pdfjs';
import type { OrderProfileCanvasRegion, OrderProfilePreviewPageGrant } from '@/features/admin/types/shipping-order-document-profile.types';
import { isUnboundOrderFieldCanvasRegion } from '../orderProfileForm.utils';
import type { PDFDocumentProxy } from 'pdfjs-dist';
type PdfJsModule = typeof import('pdfjs-dist');
let pdfjsLoader: Promise<PdfJsModule> | null = null;
/** 动态加载 PDF.js 与 worker;坐标 PDF 与 XFA 在受控管理员画布按需共用。 */
async function loadPdfJs(): Promise<PdfJsModule> {
if (!pdfjsLoader) {
pdfjsLoader = (async () => {
const [pdfjs, workerMod] = await Promise.all([
import('pdfjs-dist'),
import('pdfjs-dist/build/pdf.worker.min.mjs?url'),
]);
pdfjs.GlobalWorkerOptions.workerSrc = workerMod.default;
return pdfjs;
})();
}
return pdfjsLoader;
}
const props = defineProps<{
profileId: number | null;
grant?: OrderProfilePreviewPageGrant | null;
@@ -107,6 +93,12 @@ const viewport = ref<HTMLElement | null>(null);
const zoom = ref(1);
/** 按页缓存已消费 token 拉取的 PNG,翻页回访不再触发一次性 token 失效。 */
const pageImageCache = new Map<string, string>();
/**
* 原 PDF 字节缓存:pdf-preview 令牌是 Redis getdel 单次消费。
* 同 token 的并发/重入 loadPage 若再次 GET 会 404,并误触发父级 reauth 风暴。
*/
let cachedPdfBytes: Uint8Array | null = null;
let cachedPdfToken: string | null = null;
let loadGeneration = 0;
let cachedProfileId: number | null = null;
const zoomPercent = computed(() => Math.round(zoom.value * 100));
@@ -123,17 +115,34 @@ const emptyStateText = computed(() => (
props.emptyHint || t('admin.shippingOrderProfiles.workbench.selectBoundPdf')
));
/**
* 等待 pdfCanvas 进入 DOM。
* 错误态曾用 v-if 卸掉 canvas;清错后仅一次 nextTick 仍可能读到 null,
* 进而抛 "PDF canvas is unavailable",被空 catch 吃掉且 0 console error。
*/
const ensurePdfCanvas = async (): Promise<{ canvas: HTMLCanvasElement; context: CanvasRenderingContext2D }> => {
for (let attempt = 0; attempt < 10; attempt += 1) {
await nextTick();
const el = pdfCanvas.value;
const context = el?.getContext('2d');
if (el && context) return { canvas: el, context };
await new Promise<void>((resolve) => {
if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => resolve());
else window.setTimeout(() => resolve(), 16);
});
}
throw new Error('PDF canvas is unavailable');
};
/**
* 将内存中的原 PDF 按真实页面外观流绘制到 Canvas。
* 核心逻辑:坐标 PDF 与 hybrid XFA 都用 page.render(),不生成可下载 URL。
*/
const renderPdfPage = async (pdf: PDFDocumentProxy) => {
await nextTick();
const targetPage = Math.min(Math.max(props.pageNo, 1), pdf.numPages);
const targetPage = Math.min(Math.max(props.pageNo, 1), pdf.numPages || 1);
if (pdf.numPages < 1) throw new Error('PDF has no pages');
const page = await pdf.getPage(targetPage);
const canvas = pdfCanvas.value;
const context = canvas?.getContext('2d');
if (!canvas || !context) throw new Error('PDF canvas is unavailable');
const { canvas, context } = await ensurePdfCanvas();
const viewport = page.getViewport({ scale: zoom.value });
pdfPageSize.value = { width: viewport.width, height: viewport.height };
canvas.width = Math.ceil(viewport.width);
@@ -142,6 +151,12 @@ const renderPdfPage = async (pdf: PDFDocumentProxy) => {
pdfRendered.value = true;
};
/** 令牌失效类 HTTP 才值得父级 reauth;画布未挂载/渲染失败重签只会空转。 */
const isPreviewTokenHttpError = (error: unknown): boolean => {
if (!(error instanceof Error)) return false;
return /^HTTP (401|403|404)\b/.test(error.message);
};
/**
* 回收某次会话内全部页图 blob;切换样本 Profile 或卸载时调用。
*/
@@ -149,6 +164,8 @@ const clearPageImageCache = () => {
for (const url of pageImageCache.values()) URL.revokeObjectURL(url);
pageImageCache.clear();
inflightPageLoads.clear();
cachedPdfBytes = null;
cachedPdfToken = null;
};
/** 同一页的并发拉取共用一个 Promise,成功后必入缓存(即使请求已过期)。 */
@@ -206,13 +223,21 @@ const loadPage = async () => {
|| `/api/admin/shipping-notice/order-document-profiles/${props.profileId}/preview-pages`;
if (props.pdfPreview) {
imageUrl.value = '';
const response = await fetch(
`${previewPath}?preview_token=${encodeURIComponent(props.pdfPreview.preview_token)}`,
{ headers: getAuthHeaders(), cache: 'no-store' },
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const token = props.pdfPreview.preview_token;
let bytes: Uint8Array;
if (cachedPdfToken === token && cachedPdfBytes) {
bytes = cachedPdfBytes;
} else {
const response = await fetch(
`${previewPath}?preview_token=${encodeURIComponent(token)}`,
{ headers: getAuthHeaders(), cache: 'no-store' },
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
bytes = new Uint8Array(await response.arrayBuffer());
cachedPdfBytes = bytes;
cachedPdfToken = token;
}
const pdfjs = await loadPdfJs();
const bytes = new Uint8Array(await response.arrayBuffer());
pdfDocument = await pdfjs.getDocument({ data: bytes, enableXfa: true }).promise;
if (generation !== loadGeneration) return;
emit('pageCount', pdfDocument.numPages);
@@ -224,7 +249,7 @@ const loadPage = async () => {
const blobUrl = await fetchPageImage(previewPath, grant);
if (generation !== loadGeneration) return;
imageUrl.value = blobUrl;
} catch {
} catch (error) {
if (generation !== loadGeneration) return;
const fallback = props.grant ? pageImageCache.get(String(props.grant.page_no)) : null;
if (fallback) {
@@ -234,7 +259,10 @@ const loadPage = async () => {
}
imageUrl.value = '';
internalLoadError.value = t('admin.shippingOrderProfiles.workbench.canvasUnavailable');
emit('loadFailed');
// 仅令牌 HTTP 失效才通知父级重签;画布未挂载/PDF.js 渲染失败重签只会烧掉单次 token。
if (isPreviewTokenHttpError(error) || (props.grant && error instanceof Error && /^HTTP \d+/.test(error.message))) {
emit('loadFailed');
}
} finally {
if (generation === loadGeneration) loading.value = false;
}
@@ -442,10 +470,20 @@ defineExpose({
watch(() => [props.grant?.page_no, props.grant?.preview_token, props.pdfPreview?.preview_token], () => { void loadPage(); }, { immediate: true });
watch(() => props.pageNo, async (value) => {
pageInput.value = value;
if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument);
if (!(props.pdfPreview && pdfDocument)) return;
try {
await renderPdfPage(pdfDocument);
} catch {
/* 翻页时画布可能短暂卸载;下一次 load/retry 会恢复 */
}
});
watch(zoom, async () => {
if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument);
if (!(props.pdfPreview && pdfDocument)) return;
try {
await renderPdfPage(pdfDocument);
} catch {
/* 缩放同翻页:避免未捕获 Promise 干扰控制台 */
}
});
onBeforeUnmount(() => {
endMove();
@@ -494,7 +532,8 @@ onBeforeUnmount(() => {
</div>
</header>
<div v-if="loading && !pdfPreview" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}</div>
<div v-else-if="displayLoadError" class="canvas-state canvas-state--error" role="alert">
<!-- PNG 路径仍可用整页错误态;原 PDF 路径必须保留 canvas 挂载,否则 renderPdfPage 必抛 canvas unavailable。 -->
<div v-else-if="displayLoadError && !pdfPreview" class="canvas-state canvas-state--error" role="alert">
<p>{{ displayLoadError }}</p>
<button type="button" class="canvas-retry" @click="onRetryClick">
{{ t('admin.shippingOrderProfiles.workbench.retryCanvas') }}
@@ -592,6 +631,12 @@ onBeforeUnmount(() => {
/>
</div>
</div>
<div v-if="displayLoadError && pdfPreview" class="canvas-error-overlay" role="alert">
<p>{{ displayLoadError }}</p>
<button type="button" class="canvas-retry" @click="onRetryClick">
{{ t('admin.shippingOrderProfiles.workbench.retryCanvas') }}
</button>
</div>
</div>
</section>
</template>
@@ -635,7 +680,20 @@ onBeforeUnmount(() => {
cursor: pointer;
}
.canvas-retry:hover { border-color: #60a5fa; background: #26364f; }
.canvas-work-area { display: flex; min-height: 0; flex: 1; gap: .6rem; }
.canvas-work-area { position: relative; display: flex; min-height: 0; flex: 1; gap: .6rem; }
.canvas-error-overlay {
position: absolute;
inset: 0;
z-index: 8;
display: grid;
place-content: center;
gap: .75rem;
background: rgb(15 23 42 / .82);
color: #fecaca;
font-size: .875rem;
text-align: center;
padding: 1rem;
}
.canvas-work-area.readonly { gap: 0; }
.canvas-viewport { position: relative; min-width: 0; flex: 1; overflow: auto; }
.canvas-viewport.panning { cursor: grab; }
@@ -10,7 +10,9 @@ import { useI18n } from 'vue-i18n';
import {
BookOpen,
CheckCircle2,
ChevronDown,
ChevronRight,
ChevronUp,
ClipboardCheck,
Edit,
FileQuestion,
@@ -105,6 +107,19 @@ const directVideoResources = computed(() => contentResources.value.filter((resou
resource.resource_type === 'agent_guide'
&& videoGuideCandidates.value.some((guide) => guide.id === resource.agent_guide_id)
)));
// 培训视频上传列表默认收起:超过阈值仅展示前 N 条,底部按钮可展开查看全部,避免视频过多时页面过长
const DIRECT_VIDEO_PREVIEW_COUNT = 3;
const isDirectVideoExpanded = ref(false);
const hasMoreDirectVideos = computed(() => directVideoResources.value.length > DIRECT_VIDEO_PREVIEW_COUNT);
const directVideoVisibleResources = computed(() => (
hasMoreDirectVideos.value && !isDirectVideoExpanded.value
? directVideoResources.value.slice(0, DIRECT_VIDEO_PREVIEW_COUNT)
: directVideoResources.value
));
/** 切换培训视频上传列表展开/收起:收起仅保留前 N 条,其余视频仍在表单资源中参与保存。 */
const toggleDirectVideoExpanded = () => {
isDirectVideoExpanded.value = !isDirectVideoExpanded.value;
};
const contentResources = computed(() => form.value.resources.filter((resource) => resource.resource_type !== 'inline_questions'));
const trainingLevels: TrainingLevel[] = ['company', 'department', 'team'];
const guideGroups = computed(() => {
@@ -263,6 +278,18 @@ const pushLeanTaskNow = async () => {
if (!leanTask.value || isPushingLeanTask.value) return;
isPushingLeanTask.value = true;
try {
// [STEP] 表单与已保存任务不一致(如刚勾选新视频未发布)时自动先保存再补推:
// 补推只作用于服务端冻结清单,不先保存会按旧清单推送而误报“全部视频已推送完毕”
if (isLeanTaskFormDirty()) {
try {
await persistLeanTask();
msg.success(t('admin.trainingConfig.lean.autoSavedBeforePush'));
} catch (error) {
// 自动保存失败(含周次校验拦截)时终止补推,具体原因已提示
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.saveFailed'));
return;
}
}
const log = await pushAdminLeanTrainingWeeklyTask(leanTask.value.id);
if (log.status === 'completed') {
msg.warning(t('admin.trainingConfig.lean.pushCompleted'));
@@ -318,27 +345,53 @@ const toggleLeanVideo = (resourceId: number) => {
: [...leanVideoResourceIds.value, resourceId];
};
const saveLeanTask = async () => {
/**
* 判断精益周任务表单是否与已保存任务不一致(勾选/周次/截止/对象/每周数量任一变更即视为脏)。
* AI 触发时机:点击【立即新增任务补推】时必须先感知未保存变更并自动保存——补推只作用于服务端冻结清单,
* 不自动保存会按旧清单推送而误报“全部视频已推送完毕”。
*/
const isLeanTaskFormDirty = (): boolean => {
const task = leanTask.value;
if (!task) return false;
if (JSON.stringify(leanVideoResourceIds.value) !== JSON.stringify(task.video_resource_ids || [])) return true;
if (leanWeekKey.value !== (task.week_key || '')) return true;
if (Number(leanWeeklyCount.value) !== Number(task.weekly_count || 1)) return true;
const savedDueAtMs = Date.parse(task.due_at || '');
if (!Number.isNaN(savedDueAtMs) && Math.abs(Date.parse(leanDueAt.value) - savedDueAtMs) > 1000) return true;
const normalizeTargets = (values: Array<string | number> | undefined) => JSON.stringify([...(values || [])].map(String).sort());
if (normalizeTargets(leanTargetRoles.value) !== normalizeTargets(task.target_roles)) return true;
if (normalizeTargets(leanTargetUserIds.value) !== normalizeTargets(task.target_user_ids)) return true;
return false;
};
/**
* 保存精益周任务表单到服务端(【发布周任务】与【补推前自动保存】共用同一持久化入口)。
* 校验失败或接口失败时抛出异常,由调用方决定提示方式与是否继续后续动作。
*/
const persistLeanTask = async () => {
// 任务周必须为周一:date input 允许选任意日期,前端先行拦截,后端同规则兜底校验
if (!leanWeekKey.value || new Date(`${leanWeekKey.value}T00:00:00`).getDay() !== 1) {
msg.warning(t('admin.trainingConfig.lean.weekMustBeMonday'));
return;
throw new Error(t('admin.trainingConfig.lean.weekMustBeMonday'));
}
leanTask.value = await createOrUpdateAdminLeanTrainingWeeklyTask({
// 任务周/截止时间支持修改:按表单所选周创建或更新,发布/补推均作用于所选周任务(周任务规则 7)
week_key: leanWeekKey.value,
due_at: new Date(leanDueAt.value).toISOString(),
// 未勾选任何视频时传空数组,服务端自动按上传时间倒序冻结全部视频(周任务规则 6)
video_resource_ids: leanVideoResourceIds.value,
target_roles: leanTargetRoles.value,
target_user_ids: leanTargetUserIds.value,
weekly_count: leanWeeklyCount.value,
});
// 保存后回填勾选状态(空选择时服务端可能已自动填充全部视频)
leanVideoResourceIds.value = leanTask.value?.video_resource_ids ? [...leanTask.value.video_resource_ids] : [];
await loadLeanPushLogs();
};
const saveLeanTask = async () => {
isSavingLeanTask.value = true;
try {
leanTask.value = await createOrUpdateAdminLeanTrainingWeeklyTask({
// 任务周/截止时间支持修改:按表单所选周创建或更新,发布/补推均作用于所选周任务(周任务规则 7)
week_key: leanWeekKey.value,
due_at: new Date(leanDueAt.value).toISOString(),
// 未勾选任何视频时传空数组,服务端自动按上传时间倒序冻结全部视频(周任务规则 6)
video_resource_ids: leanVideoResourceIds.value,
target_roles: leanTargetRoles.value,
target_user_ids: leanTargetUserIds.value,
weekly_count: leanWeeklyCount.value,
});
// 保存后回填勾选状态(空选择时服务端可能已自动填充全部视频)
leanVideoResourceIds.value = leanTask.value?.video_resource_ids ? [...leanTask.value.video_resource_ids] : [];
await loadLeanPushLogs();
await persistLeanTask();
msg.success(t('admin.trainingConfig.messages.leanTaskSaved'));
} catch (error) {
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.saveFailed'));
@@ -414,6 +467,8 @@ const selectConfig = (config: TrainingConfig) => {
questionJsonText.value = JSON.stringify(questions, null, 2);
questionSourceVersionId.value = null;
questionParseMeta.value = null;
// 切换培训类型时培训视频上传列表恢复默认收起,避免上一配置的展开状态带入
isDirectVideoExpanded.value = false;
void loadLeanTask();
};
@@ -702,6 +757,8 @@ const uploadTrainingVideo = async (event: Event) => {
required_duration: 0,
sort_order: form.value.resources.length,
});
// 新上传的视频排在列表末尾,自动展开避免用户以为上传失败找不到新视频
isDirectVideoExpanded.value = true;
msg.success(t('admin.trainingConfig.messages.videoUploaded'));
} catch (error) {
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.videoUploadFailed'));
@@ -907,11 +964,19 @@ onMounted(() => void load());
</div>
<div class="space-y-3 p-4 md:p-5">
<div v-if="!directVideoResources.length" class="rounded-xl border border-dashed border-default bg-surface-soft/50 px-3 py-8 text-center text-xs text-muted">{{ t('admin.trainingConfig.directVideo.empty') }}</div>
<div v-for="(resource, index) in directVideoResources" v-else :key="resource.id || `direct-video-${index}`" class="grid gap-3 rounded-xl border border-default bg-white p-4 md:grid-cols-[minmax(0,1fr)_180px_auto] md:items-end">
<div class="flex min-w-0 items-center gap-2 text-sm font-medium text-primary"><Video class="h-4 w-4 shrink-0 text-violet-500" /><span class="truncate">{{ resource.title || videoGuideCandidates.find((guide) => guide.id === resource.agent_guide_id)?.file_name || t('admin.trainingConfig.directVideo.unnamed') }}</span></div>
<label class="label-field">{{ t('admin.trainingConfig.fields.requiredDuration') }}<input v-model.number="resource.required_duration" type="number" min="0" class="input-field mt-2" /></label>
<button class="btn-danger btn-sm" type="button" @click="removeResource(resource)"><Trash2 class="h-4 w-4" />{{ t('admin.delete') }}</button>
</div>
<!-- 培训视频上传列表默认收起:超过阈值仅展示前 N 条,底部可展开查看全部 -->
<template v-else>
<div v-for="(resource, index) in directVideoVisibleResources" :key="resource.id || `direct-video-${index}`" class="grid gap-3 rounded-xl border border-default bg-white p-4 md:grid-cols-[minmax(0,1fr)_180px_auto] md:items-end">
<div class="flex min-w-0 items-center gap-2 text-sm font-medium text-primary"><Video class="h-4 w-4 shrink-0 text-violet-500" /><span class="truncate">{{ resource.title || videoGuideCandidates.find((guide) => guide.id === resource.agent_guide_id)?.file_name || t('admin.trainingConfig.directVideo.unnamed') }}</span></div>
<label class="label-field">{{ t('admin.trainingConfig.fields.requiredDuration') }}<input v-model.number="resource.required_duration" type="number" min="0" class="input-field mt-2" /></label>
<button class="btn-danger btn-sm" type="button" @click="removeResource(resource)"><Trash2 class="h-4 w-4" />{{ t('admin.delete') }}</button>
</div>
<button v-if="hasMoreDirectVideos" class="flex w-full items-center justify-center gap-1.5 rounded-xl border border-dashed border-default bg-surface-soft/50 px-3 py-2.5 text-xs font-medium text-secondary transition hover:bg-surface-soft" type="button" @click="toggleDirectVideoExpanded">
<ChevronDown v-if="!isDirectVideoExpanded" class="h-4 w-4" />
<ChevronUp v-else class="h-4 w-4" />
{{ isDirectVideoExpanded ? t('admin.trainingConfig.directVideo.collapseList') : t('admin.trainingConfig.directVideo.expandAll', { count: directVideoResources.length }) }}
</button>
</template>
</div>
</article>
<article
@@ -218,19 +218,13 @@ onMounted(() => {
>
{{ t('admin.role.' + user.role) }}
</span>
<div v-if="user.feature_permissions?.training_hr_manage || user.feature_permissions?.['contract_payment.access']" class="mt-2 flex flex-wrap gap-1.5">
<div v-if="user.feature_permissions?.training_hr_manage" class="mt-2 flex flex-wrap gap-1.5">
<span
v-if="user.feature_permissions?.training_hr_manage"
class="inline-flex rounded-full border border-brand-100 bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700"
>
{{ t('admin.user.fields.trainingHrManage') }}
</span>
<span
v-if="user.feature_permissions?.['contract_payment.access']"
class="inline-flex rounded-full border border-brand-100 bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700"
>
{{ t('admin.user.fields.contractPaymentAccess') }}
</span>
</div>
</td>
<td class="px-6 py-4 text-right">
@@ -1,6 +1,6 @@
/**
* features/admin/modules/users/components/UserFormModal.vue
* 创建/编辑用户弹窗,含角色与功能权限勾选(培训 HR、合同付款预警访问)。
* 创建/编辑用户弹窗,含角色与培训 HR 功能权限勾选。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
@@ -1,7 +1,7 @@
/**
* features/auth/stores/auth.store.ts
* 认证全局状态;Phase 0 仍委托 utils/auth 读写 storage。
* 依赖:shared/utils/auth、contract-payment 权限常量。
* 依赖:shared/utils/auth。
* 逻辑:登录态同步到 Pinia;hasFeaturePermission 供路由守卫与侧栏判断专项权限。
*/
import { defineStore } from 'pinia';
@@ -16,7 +16,6 @@ import {
type AuthUser,
type FeaturePermissions,
} from '@/shared/utils/auth';
import { CONTRACT_PAYMENT_ACCESS_PERMISSION } from '@/features/contract-payment/constants';
export type { AuthUser, FeaturePermissions };
@@ -36,18 +35,15 @@ export const useAuthStore = defineStore('auth', () => {
/**
* 判断当前登录用户是否具备指定功能权限。
* 核心逻辑:读取登录态 feature_permissions 的显式布尔值;键缺失时,合同付款访问与后端角色默认对齐(admin 为 true),避免权限键新增前写入的旧会话被误拦。
* 核心逻辑:读取登录态 feature_permissions 的显式布尔值;键缺失时回退 false。
* @param permissionKey - 后端 User.get_feature_permissions 下发的键
* @returns 显式为 true,或键缺失且命中角色默认时返回 true
* @returns 显式为 true 时返回 true
*/
const hasFeaturePermission = (permissionKey: string): boolean => {
const bag = user.value?.feature_permissions;
if (bag && Object.prototype.hasOwnProperty.call(bag, permissionKey)) {
return Boolean(bag[permissionKey]);
}
if (permissionKey === CONTRACT_PAYMENT_ACCESS_PERMISSION) {
return user.value?.role === 'admin';
}
// 订单交期回复两键与后端角色默认对齐(admin 默认开),同样兜底旧会话缺键的场景。
if (
permissionKey === 'order_delivery_reply.manage' ||
+18 -6
View File
@@ -166,6 +166,16 @@ export const getWorkspaceShippingFreightNoticeGroups = (taskNo: string) =>
{ priority: 'low' },
);
/** 整单 ODM 裁决:保存行级选择(同快照文件行后端同步),随后可重试生成 Excel。 */
export const setWorkspaceShippingTaskOdmChoice = (
taskNo: string,
payload: { snapshot_line_id: string | number; odm_id: string },
) =>
requestJson<{ task_id: number; odm_id: string; synced_line_count: number; odm_values: string[] }>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/odm-choice`,
jsonPost(payload),
);
/**
* 分页拉取任务工作台统一审计时间线(ShippingAuditEvent 单源)。
*/
@@ -1168,7 +1178,7 @@ export async function updateWorkspaceShippingNoticeFields(
taskNo: string,
fields: Partial<ShippingNoticeHeader>,
comment: string | undefined,
options: { expectedOrderDataVersion: number; idempotencyKey?: string; evidence: ShippingReviewEvidence; reason: string },
options: { expectedOrderDataVersion: number; idempotencyKey?: string; evidence?: ShippingReviewEvidence; reason?: string },
) {
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/update-notice-fields`,
@@ -1176,8 +1186,9 @@ export async function updateWorkspaceShippingNoticeFields(
fields,
...(comment ? { comment } : {}),
expected_order_data_version: options.expectedOrderDataVersion,
evidence: options.evidence,
reason: options.reason,
// 证据/理由改为可选:未传时不带字段,与后端免证据编辑通道(Task 2)对齐。
...(options.evidence ? { evidence: options.evidence } : {}),
...(options.reason ? { reason: options.reason } : {}),
...(options.idempotencyKey ? { idempotency_key: options.idempotencyKey } : {}),
}),
);
@@ -1197,7 +1208,7 @@ export async function updateWorkspaceShippingNoticeLine(
lineIndex: number,
patch: Partial<ShippingNoticeLine> & { quantity?: number },
comment: string | undefined,
options: { expectedOrderDataVersion: number; idempotencyKey?: string; evidence: ShippingReviewEvidence; reason: string },
options: { expectedOrderDataVersion: number; idempotencyKey?: string; evidence?: ShippingReviewEvidence; reason?: string },
) {
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/update-notice-line`,
@@ -1206,8 +1217,9 @@ export async function updateWorkspaceShippingNoticeLine(
patch,
...(comment ? { comment } : {}),
expected_order_data_version: options.expectedOrderDataVersion,
evidence: options.evidence,
reason: options.reason,
// 证据/理由改为可选:未传时不带字段,与后端免证据编辑通道(Task 2)对齐。
...(options.evidence ? { evidence: options.evidence } : {}),
...(options.reason ? { reason: options.reason } : {}),
...(options.idempotencyKey ? { idempotency_key: options.idempotencyKey } : {}),
}),
);
@@ -311,6 +311,25 @@ export async function getLeanTrainingDashboard(taskId?: number): Promise<LeanTra
};
}
export async function exportLeanTrainingDashboard(taskId: number): Promise<void> {
const response = await fetch(`/api/admin/lean-training/dashboard/export?task_id=${taskId}`, {
method: 'GET',
headers: getAuthHeaders(),
});
if (!response.ok) {
throw new Error(`Export failed: HTTP ${response.status}`);
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `lean_training_dashboard_${new Date().toISOString().slice(0, 10)}.xlsx`;
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
}
/** HR 对指定成员发起精益培训定向提醒;返回后端实发统计(sent/failed 才是真实送达情况,created 含发送失败)。 */
export async function sendLeanTrainingReminders(weeklyTaskId: number, userIds: number[]): Promise<{ created: number; sent: number; skipped: number; failed: number }> {
return requestJson<{ created: number; sent: number; skipped: number; failed: number }>(`/api/admin/lean-training/weekly-tasks/${weeklyTaskId}/reminders`, {
@@ -4,6 +4,7 @@
* 依赖:lucide 图标、附件完整性判断工具。
* 逻辑:附件卡片位于文本框上方;订单审核结果随对应聊天消息展示,输入区只保留附件处理状态。
* 同时支持采购合同双文件输入控件:底部左区放附件/合同等工具,右区语音与发送并排;采购合同审查用专用上传按钮,不展示通用回形针附件入口。
* 货代订单抽取提交中(isOrderExtractionSubmitting)时发送钮展示 Loader,免责声明区提示提交中。
*/
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
@@ -58,6 +59,8 @@ const props = defineProps<{
isVoiceRecording: boolean;
isVoiceTranscribing: boolean;
isUploadingAttachments: boolean;
/** 货代订单抽取统一提交进行中;为 true 时发送钮 Loader 且禁用。 */
isOrderExtractionSubmitting?: boolean;
canSendMessage: boolean;
isShippingNoticeAgent: boolean;
isProcurementContractAgent?: boolean;
@@ -843,7 +846,7 @@ watch(
</button>
<button
v-if="isThinking && !isUploadingAttachments"
v-if="isThinking && !isUploadingAttachments && !isOrderExtractionSubmitting"
type="button"
class="flex h-10 w-10 items-center justify-center rounded-full border border-rose-300 bg-rose-50 text-rose-600 shadow-sm transition-all duration-200 hover:scale-105 hover:bg-rose-100 active:scale-95"
:title="$t('chat.stopGenerating')"
@@ -862,14 +865,15 @@ watch(
: 'border-brand-500 bg-brand-500 text-white shadow-[0_0_0_4px_rgba(59,130,246,0.18)] hover:scale-105 hover:bg-brand-600 hover:shadow-[0_0_0_6px_rgba(59,130,246,0.24)] active:scale-95'"
@click="emit('send')"
>
<Loader2 v-if="isUploadingAttachments" class="h-4 w-4 animate-spin" />
<Loader2 v-if="isUploadingAttachments || isOrderExtractionSubmitting" class="h-4 w-4 animate-spin" />
<Send v-else class="h-4 w-4" />
</button>
</div>
</div>
</div>
<div class="mt-3 text-center text-[11px] text-muted">
<span v-if="isThinking">{{ $t('chat.thinking') }}</span>
<span v-if="isOrderExtractionSubmitting">{{ $t('chat.shippingNoticeSubmitting') }}</span>
<span v-else-if="isThinking">{{ $t('chat.thinking') }}</span>
<span v-else>{{ $t('chat.disclaimer') }}</span>
</div>
</div>
@@ -54,7 +54,6 @@ const {
pinMessagesToBottom?: boolean;
/** 供父级滚动逻辑绑定 main 元素 */
scrollContainerHolder: { el: Ref<HTMLElement | null> };
compactShippingProgress?: boolean;
}>();
const emit = defineEmits<{
@@ -68,7 +67,6 @@ const emit = defineEmits<{
'maintenance-edit-record': [record: MaintenanceRecord];
'maintenance-view-record-history': [device: MaintenanceDevice];
'maintenance-create-record-for-device': [device: MaintenanceDevice];
'open-batch-workbench': [];
/** 在途仓自动调拨:业务流激活时向上冒泡,父级据此隐藏聊天输入框。 */
'transfer-flow-active': [active: boolean];
}>();
@@ -207,7 +205,6 @@ const hasFollowingShippingProgressCard = (items: ChatMessage[], index: number):
:leave-handlers="leaveHandlers"
:shipping-handlers="shippingHandlers"
:training-handlers="trainingHandlers"
:compact-shipping-progress="compactShippingProgress"
:attachment-summary-only="hasFollowingShippingProgressCard(messages, index)"
@copy="emit('copy', { message: msg, index })"
@edit="emit('edit', $event)"
@@ -217,7 +214,6 @@ const hasFollowingShippingProgressCard = (items: ChatMessage[], index: number):
@maintenance-edit-record="emit('maintenance-edit-record', $event)"
@maintenance-view-record-history="emit('maintenance-view-record-history', $event)"
@maintenance-create-record-for-device="emit('maintenance-create-record-for-device', $event)"
@open-batch-workbench="emit('open-batch-workbench')"
/>
<ToolRunProgressCard
v-if="shouldRenderMessage(msg) && shouldShowToolRunProgressAfterMessage(msg, index)"
@@ -1,6 +1,6 @@
/**
* features/chat/components/ChatMobileHeader.vue
* 移动端顶栏:Agent 名称、学习之窗与 Agent 切换弹层。
* 移动端顶栏:Agent 名称、学习之窗与 Agent 切换弹层。作业面 Agent 可隐藏历史入口。
*/
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue';
@@ -15,6 +15,7 @@ defineProps<{
activeAgentId: number;
hasAgentGuides: boolean;
userAgents: ChatMobileHeaderAgent[];
hideHistory?: boolean;
}>();
const emit = defineEmits<{
@@ -85,6 +86,7 @@ onBeforeUnmount(() => {
<LayoutGrid class="h-5 w-5" />
</button>
<button
v-if="!hideHistory"
type="button"
class="flex h-9 w-9 items-center justify-center rounded-full text-muted transition-colors hover-surface-soft"
:title="$t('chat.history')"
@@ -4,7 +4,7 @@
* 依赖:lucide-vue-next、LocaleToggleButton、ExternalSystemLinks、AgentCategoryList、chat.types。
* 逻辑:由聊天页面传入当前 Agent、历史记录与用户可用 Agent;通过事件把新会话、切换 Agent、反馈、进入管理控制台等操作回传给页面。
* 管理员通过底部右侧工具图标进入管理控制台;用户下拉菜单仅保留退出登录。
* 关联服务入口与主题/语言等底栏图标统一为同尺寸 inline icon 按钮,避免错位。
* 合同付款预警、立账凭证第一期不走对话,hideSessionUi 时隐藏新会话与历史列表。
*/
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
@@ -48,6 +48,7 @@ const props = defineProps<{
userAgents: ChatSidebarAgent[];
currentUser: Record<string, unknown> | null;
appliedTheme: string;
hideSessionUi?: boolean;
}>();
const emit = defineEmits<{
@@ -198,13 +199,16 @@ const orderExtractionAttentionClass = (item: DisplayHistoryItem) => {
</button>
</div>
<div class="px-4 pb-4">
<div v-if="!hideSessionUi" class="px-4 pb-4">
<button type="button" class="chat-sidebar-btn" @click="onNewChat">
<Plus class="h-4 w-4" /> {{ $t('chat.createNewChat') }}
</button>
</div>
<p v-else class="px-4 pb-3 text-xs leading-5 text-muted">
{{ $t('chat.taskAgent.sessionHint') }}
</p>
<div class="flex items-center justify-between px-4 py-2">
<div v-if="!hideSessionUi" class="flex items-center justify-between px-4 py-2">
<span class="text-xs font-semibold text-muted">{{ $t('chat.history') }}</span>
<button
v-if="displayHistory.length > 0"
@@ -216,7 +220,7 @@ const orderExtractionAttentionClass = (item: DisplayHistoryItem) => {
</button>
</div>
<div class="scrollbar-thin flex-1 overflow-y-auto px-2">
<div v-if="!hideSessionUi" class="scrollbar-thin flex-1 overflow-y-auto px-2">
<div v-if="displayHistory.length === 0" class="py-8 text-center text-sm italic text-muted">
{{ $t('chat.noHistory') }}
</div>
@@ -4,17 +4,18 @@
* 用途:对话页主区域,组合侧栏、消息列表、输入栏、货代会话 Workflow 时间线与内置浏览器。
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingWorkflowTimeline、chat.context。
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingWorkflowTimeline、ContractPaymentChatPanel、VoucherCheckChatPanel、chunkLoadRecovery、chat.context。
* 逻辑:本文件只做页面结构编排;货代 Chat 仅上传/进度通知,履约写操作不在本页;
* 右侧「本次处理」由 conversationId 驱动 Workflow projection,extractionRunNo 仅作进度装饰;
* 订单复核工作台异步分包,避免普通对话首屏拉取 PDF.js。
* 订单复核工作台异步分包,避免普通对话首屏拉取 PDF.js;合同付款预警、立账凭证 Agent 用 Tab 作业面替换消息列表与输入框;
* 货代会话主区域:有会话即全屏批次进度中心(常驻),无会话为欢迎页+输入框,会话标题取自侧栏历史并传给中心。
*/
<script setup lang="ts">
import { computed, defineAsyncComponent, provide, ref, watch } from 'vue';
import { computed, provide, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
@@ -34,6 +35,8 @@ import ChatBrowserPanel from '@/features/chat/components/ChatBrowserPanel.vue';
import ShippingWorkflowTimeline from '@/features/chat/components/shipping/ShippingWorkflowTimeline.vue';
import { shouldShowShippingWorkbench } from '@/features/chat/shipping/shippingWorkbenchLayout';
import TrainingWorkspacePanel from '@/features/chat/components/TrainingWorkspacePanel.vue';
import LedgerConfigPanel from '@/features/maintenance/components/LedgerConfigPanel.vue';
@@ -44,7 +47,7 @@ import { useChatPageContext } from '@/features/chat/composables/chat.context';
import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace.utils';
import { agentHasIntentUiProfile, resolveAgentCode, AGENT_CODE_IN_TRANSIT_TRANSFER } from '@/shared/utils/agent-registry.utils';
import { agentHasIntentUiProfile, resolveAgentCode, AGENT_CODE_IN_TRANSIT_TRANSFER, isContractPaymentAgent, isVoucherCheckAgent } from '@/shared/utils/agent-registry.utils';
import {
SHIPPING_WORKFLOW_KEY,
@@ -65,11 +68,21 @@ import {
} from '@/features/maintenance/utils/maintenance-panel-layout.utils';
import { defineRecoverableAsyncComponent } from '@/shared/utils/chunkLoadRecovery';
/** 复核工作台按需分包:仅 order-review 模式加载,避免 Chat 首屏带上 PDF.js。 */
const ShippingOrderReviewView = defineAsyncComponent(
const ShippingOrderReviewView = defineRecoverableAsyncComponent(
() => import('@/features/chat/views/ShippingOrderReviewView.vue'),
);
const ContractPaymentChatPanel = defineRecoverableAsyncComponent(
() => import('@/features/contract-payment/components/ContractPaymentChatPanel.vue'),
);
const VoucherCheckChatPanel = defineRecoverableAsyncComponent(
() => import('@/features/voucher-check/components/VoucherCheckChatPanel.vue'),
);
type MaintenanceRecordPanelCommand = {
mode: 'list' | 'create';
@@ -114,42 +127,32 @@ const isMaintenanceAgentPage = computed(() => agentHasIntentUiProfile(page.curre
/** 在途仓自动调拨 Agent:无消息时展示专属首页入口区(决策:补 Chat 首页入口 A 方案)。 */
const isInTransitTransferAgent = computed(() => resolveAgentCode(page.currentAgent) === AGENT_CODE_IN_TRANSIT_TRANSFER);
/** 合同付款预警 Agent:主区嵌台账 Tab,隐藏对话输入与历史。 */
const isContractPaymentAgentPage = computed(() => isContractPaymentAgent(page.currentAgent));
/** 立账凭证 Agent:主区嵌检核任务 / 企微发送记录 Tab,隐藏对话输入与历史。 */
const isVoucherCheckAgentPage = computed(() => isVoucherCheckAgent(page.currentAgent));
/** builtin 作业面 Agent 共用:隐藏新会话、历史列表与输入框。 */
const hideTaskChatSessionUi = computed(() => isContractPaymentAgentPage.value || isVoucherCheckAgentPage.value);
/** 在途仓自动调拨业务流激活(来源选择/待处理等子视图)时隐藏聊天输入框,模拟业务页。 */
const transferFlowActive = ref(false);
watch(isInTransitTransferAgent, (isTransfer) => { if (!isTransfer) transferFlowActive.value = false; });
/** 批次进度工作台按需打开;关闭时不占用对话区右侧布局。 */
const batchWorkbenchOpen = ref(false);
const showShippingWorkflowTimeline = computed(() => (
page.isShippingNoticeAgent
&& batchWorkbenchOpen.value
&& Boolean(activeShippingConversationId.value)
));
const compactShippingProgress = computed(() => batchWorkbenchOpen.value);
function openBatchWorkbench() {
batchWorkbenchOpen.value = true;
}
function closeBatchWorkbench() {
batchWorkbenchOpen.value = false;
}
/**
* 批次中心只服务于用户主动打开时所在的会话。切换历史会话或 Agent 后必须关闭,
* 否则旧会话的右侧投影会短暂占用新会话的对话区并造成“本次处理”串批错觉。
* 货代发货会话主区域规则(方案 A):
* 有会话 ID → 全屏批次进度中心(常驻不可关闭);无会话 → 欢迎页 + 输入框(唯一提交入口)。
*/
watch(
() => [activeShippingConversationId.value, Number(page.currentAgentId || 0)] as const,
(next, previous) => {
if (!previous || next[0] === previous[0] && next[1] === previous[1]) return;
batchWorkbenchOpen.value = false;
},
);
const showShippingWorkflowTimeline = computed(() => shouldShowShippingWorkbench({
isShippingNoticeAgent: page.isShippingNoticeAgent,
conversationId: activeShippingConversationId.value,
}));
/** 侧栏历史项中的会话标题;批次中心头部直接复用,保持侧栏与中心一致。 */
const activeShippingConversationTitle = computed(() => (
page.displayHistory.find((item) => item.conversation_id === activeShippingConversationId.value)?.title || ''
));
const embeddedIframeSrc = computed(() => {
@@ -391,6 +394,8 @@ watch(() => page.currentAgentId, () => {
:applied-theme="page.appliedTheme"
:hide-session-ui="hideTaskChatSessionUi"
@new-chat="page.handleSidebarNewChat"
@open-guide="page.openGuideModal"
@@ -432,6 +437,8 @@ watch(() => page.currentAgentId, () => {
:user-agents="page.userAgents"
:hide-history="hideTaskChatSessionUi"
@open-guide="page.openGuideModal"
@go-history="page.goToWorkspace('history')"
@@ -474,9 +481,14 @@ watch(() => page.currentAgentId, () => {
<ShippingOrderReviewView v-if="isOrderReviewMode" />
<div v-else class="flex min-h-0 min-w-0 flex-1" :class="showShippingWorkflowTimeline ? 'shipping-workbench-layout' : ''">
<ContractPaymentChatPanel v-else-if="isContractPaymentAgentPage" />
<div class="flex min-h-0 min-w-0 flex-1 flex-col" :class="showShippingWorkflowTimeline ? 'shipping-chat-column' : ''">
<VoucherCheckChatPanel v-else-if="isVoucherCheckAgentPage" />
<div v-else class="flex min-h-0 min-w-0 flex-1">
<!-- 中心展示时对话列整体隐藏(含输入框),新文件提交走新建对话(spec 方案 A 硬性决策)。 -->
<div v-show="!showShippingWorkflowTimeline" class="flex min-h-0 min-w-0 flex-1 flex-col">
<TrainingWorkspacePanel
@@ -556,8 +568,6 @@ watch(() => page.currentAgentId, () => {
:scroll-container-holder="page.scrollContainerHolder"
:compact-shipping-progress="compactShippingProgress"
@copy="page.copyToClipboard($event.message, $event.index)"
@edit="page.input = $event"
@@ -578,8 +588,6 @@ watch(() => page.currentAgentId, () => {
@maintenance-create-record-for-device="openMaintenanceRecordCreate"
@open-batch-workbench="openBatchWorkbench"
@transfer-flow-active="transferFlowActive = $event"
/>
@@ -608,6 +616,8 @@ watch(() => page.currentAgentId, () => {
:is-uploading-attachments="page.isUploadingAttachments"
:is-order-extraction-submitting="page.isOrderExtractionSubmitting"
:can-send-message="page.canSendMessage"
:is-shipping-notice-agent="page.isShippingNoticeAgent"
@@ -666,10 +676,9 @@ watch(() => page.currentAgentId, () => {
<ShippingWorkflowTimeline
v-if="showShippingWorkflowTimeline"
:conversation-id="activeShippingConversationId"
:conversation-title="activeShippingConversationTitle"
:refresh-trigger="page.workflowRefreshTrigger"
:controller="shippingProcessing"
@close="closeBatchWorkbench"
/>
@@ -820,16 +829,3 @@ watch(() => page.currentAgentId, () => {
</template>
<style scoped>
/** 打开批次工作台后,左侧对话保留为压缩入口,右侧取得主工作区宽度。 */
@media (min-width: 1024px) {
.shipping-workbench-layout {
min-width: 0;
}
.shipping-chat-column {
flex: 0 0 clamp(360px, 32vw, 520px);
}
}
</style>
@@ -500,6 +500,17 @@ const stopNonSafetyVideoTimer = () => {
workspace.stopMaterialTimer();
};
/**
* 处理普通培训主视频播放结束事件。
* AI 触发时机:学员完整播放当前主视频到结尾时调用;仅出国规章培训将视频播放结束作为一次学习完成,其他培训类型保持现有阶段推进入口。
*/
const handleNonSafetyVideoEnded = () => {
stopNonSafetyVideoTimer();
if (workspace.isOverseasRegulationsTraining) {
workspace.markVideoCompleted();
}
};
watch([() => workspace.learnerTab, nonSafetyVideoMaterials], () => {
if (!nonSafetyVideoMaterials.value.some((material) => material.id === activeNonSafetyVideoId.value)) {
activeNonSafetyVideoId.value = nonSafetyVideoMaterials.value[0]?.id ?? null;
@@ -589,8 +600,8 @@ const leanStatusMeta: Record<LeanTrainingTaskStatus, { badgeClass: string; label
/** 看板总结弹框上下文:员工姓名 + 完整总结文案;为 null 时弹框关闭。 */
const summaryModal = ref<{ name: string; text: string } | null>(null);
/** 总结列预览截断:最多显示 15 个字,超出部分以省略号收尾,点击可弹框查看全文。 */
const truncateSummary = (text: string) => (text.length > 15 ? `${text.slice(0, 15)}…` : text);
/** 总结列预览截断:最多显示 4 个字,超出部分以省略号收尾,点击可弹框查看全文。 */
const truncateSummary = (text: string) => (text.length > 4 ? `${text.slice(0, 4)}…` : text);
/** 打开总结详情弹框:仅当该行有总结文案时可点击(无总结的行显示 "--" 不可点)。 */
const openSummaryModal = (name: string, text: string) => {
@@ -992,7 +1003,7 @@ const currentSafetyStageText = computed(() => {
:src="activeNonSafetyVideo.resource?.fileUrl"
@play="startNonSafetyVideoTimer"
@pause="stopNonSafetyVideoTimer"
@ended="stopNonSafetyVideoTimer"
@ended="handleNonSafetyVideoEnded"
/>
</div>
<div v-else class="mt-3 rounded-2xl border border-dashed border-default bg-surface-soft px-4 py-10 text-center text-sm text-muted">
@@ -1831,6 +1842,10 @@ const currentSafetyStageText = computed(() => {
>
<option v-for="period in workspace.leanDashboard.periods" :key="period.id" :value="period.id">{{ $t('chat.training.lean.dashboard.periodLabel', { index: period.index }) }}({{ period.weekKey }})</option>
</select>
<button type="button" class="inline-flex items-center gap-1.5 rounded-lg bg-emerald-600 px-2.5 py-1.5 text-xs font-medium text-white transition hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-60" :disabled="workspace.leanExportLoading" @click="workspace.exportLeanDashboard">
<Download class="h-3.5 w-3.5" />
{{ workspace.leanExportLoading ? $t('chat.training.lean.dashboard.exporting') : $t('chat.training.lean.dashboard.export') }}
</button>
</div>
</div>
<div class="rounded-full bg-white px-3 py-1 text-xs font-medium text-emerald-700">{{ $t('chat.training.lean.dueAt', { time: workspace.leanDashboard.task.dueAt.slice(0, 16).replace('T', ' ') }) }}</div>
@@ -1862,7 +1877,7 @@ const currentSafetyStageText = computed(() => {
<td class="border-b border-default px-3 py-2.5 text-secondary"><div v-for="video in row.videos" :key="`${video.name}-${video.watchedAt}`" class="whitespace-nowrap">{{ video.watchedAt ? video.watchedAt.slice(0, 16).replace('T', ' ') : '--' }}</div><span v-if="!row.videos.length">--</span></td>
<!-- 状态徽章三态:已完成(绿)/已延期(红)/进行中(蓝),文案统一中文(含其余三语言),禁止回显原始键。 -->
<td class="border-b border-default px-3 py-2.5"><span class="inline-flex rounded-full px-2.5 py-1 text-xs font-semibold" :class="row.status === 'completed' ? 'bg-emerald-50 text-emerald-700' : row.status === 'overdue' ? 'bg-red-50 text-red-700' : 'bg-blue-50 text-blue-700'">{{ $t(`chat.training.lean.status.${row.status}`) }}</span></td>
<!-- [RULE] 总结列最多显示 15 个字:超出截断并显示省略号,点击弹框查看全部文案;无总结显示 "--"。
<!-- [RULE] 总结列最多显示 4 个字:超出截断并显示省略号,点击弹框查看全部文案;无总结显示 "--"。
常显虚线下划线提示可点击(用户复测反馈点击无效,实为部署版本差异,此处强化可点性视觉)。 -->
<td class="border-b border-default px-3 py-2.5 text-secondary">
<button v-if="row.summaryText" type="button" class="max-w-56 cursor-pointer text-left whitespace-pre-wrap break-words underline decoration-dotted decoration-secondary/60 underline-offset-2 transition hover:decoration-solid hover:text-primary" :title="$t('chat.training.lean.summaryModal.viewHint')" @click="openSummaryModal(row.name, row.summaryText)">{{ truncateSummary(row.summaryText) }}</button>
@@ -75,7 +75,6 @@ const {
leaveHandlers: LeaveMessageHandlers;
shippingHandlers: ShippingMessageHandlers;
trainingHandlers: TrainingHandlers;
compactShippingProgress?: boolean;
/** 下方已有货代进度卡时,用户气泡附件只显示摘要。 */
attachmentSummaryOnly?: boolean;
}>();
@@ -89,7 +88,6 @@ const emit = defineEmits<{
'maintenance-edit-record': [record: MaintenanceRecord];
'maintenance-view-record-history': [device: MaintenanceDevice];
'maintenance-create-record-for-device': [device: MaintenanceDevice];
'open-batch-workbench': [];
}>();
const authStore = useAuthStore();
@@ -747,11 +745,9 @@ function handleInlineDownload(file: InlineDownloadFile): void {
:retrying="retryingOrderExtraction"
:refreshing="refreshingOrderExtraction"
:cancelling="cancellingOrderExtraction"
:compact-progress="compactShippingProgress"
@retry="retryShippingOrderExtraction"
@refresh="refreshShippingOrderExtraction"
@cancel="cancelShippingOrderExtraction"
@open-batch-workbench="emit('open-batch-workbench')"
/>
<LeaveMessageBlock
v-if="isLeaveMessage"
@@ -22,6 +22,7 @@ const i18n = createI18n({
actionCodes: {
reload_inventory_result: '重新读取库存结果',
retry_inventory_preparation: '重新获取库存',
confirm_customer: '确认客户',
},
inventoryActions: {
reloadInventoryResult: '重新读取库存结果',
@@ -337,4 +338,57 @@ describe('ReviewCurrentProcessingCard', () => {
// 关键断言:无 statusDetail 时说明行完全不渲染,不留空壳。
expect(wrapper.find('[data-testid="review-current-task-status-detail"]').exists()).toBe(false);
});
it('renders the suggested next action instead of the reason text when next_action is present', () => {
// v4 语义分离:「下一步」给建议动作(确认客户),原因文案(客户尚未确认)
// 属于阻塞原因位,不得再挤进下一步槽位。
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'order_review',
userStatus: 'waiting_human',
blockingReason: {
code: 'customer_unresolved',
message: '客户尚未确认',
nextAction: 'confirm_customer',
} as any,
},
global: { plugins: [i18n] },
});
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text()).toBe('确认客户');
});
it('hides the generic run-level status detail when a specific blocking reason is shown', () => {
// v4 去重:具体阻断原因已由「下一步」承载时,泛化的「当前步骤需要人工处理」属纯重复。
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'order_review',
userStatus: 'waiting_human',
blockingReason: {
code: 'customer_unresolved',
message: '客户尚未确认',
nextAction: 'confirm_customer',
} as any,
statusDetail: { text: '当前步骤需要人工处理' },
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-current-task-status-detail"]').exists()).toBe(false);
});
it('keeps the run-level status detail when the blocking reason is generic', () => {
// 无具体原因(未知码、无契约文案)时,Run 级等待说明仍是唯一信息,必须保留。
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'order_review',
userStatus: 'waiting_human',
blockingReason: { code: 'internal_gate_reason' } as any,
statusDetail: { text: '当前步骤需要人工处理' },
},
global: { plugins: [i18n] },
});
expect(wrapper.get('[data-testid="review-current-task-status-detail"]').text()).toBe('当前步骤需要人工处理');
});
});
@@ -10,7 +10,9 @@
禁止把读取占位误述为「系统处理中」,也不做骨架→真值的二次刷新;
loading 仅在挂载期抑制可执行动作,等权威投影到达后再放行(fail-closed);
由 ShippingOrderReviewView 在 mountCurrentProcessingCard 时挂载;
v2 新增 statusDetail:状态块内嵌动态说明(隐藏裁决在视图侧,见 spec §5.2)。
v2 新增 statusDetail:状态块内嵌动态说明(隐藏裁决在视图侧,见 spec §5.2);
v4 语义分离:下一步优先消费 blocking_reason.next_action 的建议动作文案,
且具体阻断原因在场时隐藏泛化 statusDetail(防同卡三行「待人工」空话)。
-->
<script setup lang="ts">
import { computed } from 'vue';
@@ -20,7 +22,10 @@ import type {
ShippingProcessingBlockingReason,
ShippingProcessingPrimaryAction,
} from '@/features/chat/types/shipping.api.types';
import { resolveShippingProcessingStageLabel } from '@/features/chat/shipping/shippingProcessingLabels';
import {
isGenericBlockingReason,
resolveShippingProcessingStageLabel,
} from '@/features/chat/shipping/shippingProcessingLabels';
import { resolveGateReasonLabel } from '@/features/shipping-progress/gateReasonLabel';
import { lookupWorkbenchAction, shouldRenderWorkbenchAction } from '@/features/shipping-progress/workbenchActionRegistry';
import { inventoryActionLabelKey, isInternalInventoryAction } from '@/features/shipping-progress/actionPresentation';
@@ -147,9 +152,15 @@ const nextStepText = computed(() => {
// 其余按 user_status/blocking_reason 照常渲染,空态自然落在「状态待确认」,不做骨架二次刷新。
const automationMessage = props.loading ? safeMessage(props.automation?.message) : '';
if (automationMessage) return automationMessage;
// 1) blocking_reason → 用后端给的 i18n_key 渲染具体阻断
// 1) blocking_reason → 先给契约注册的「建议动作」(下一步=做什么),
// 再回退原因文案(i18n_key / Gate 命名空间);禁止裸露内部原因码。
const br = props.blockingReason;
if (br) {
const nextAction = String(br.nextAction || br.next_action || '').trim();
const actionKey = nextAction
? `workspace.shippingNotice.processGate.actionCodes.${nextAction}`
: '';
if (actionKey && te(actionKey)) return t(actionKey);
const i18nKey = String(br.i18nKey || '').trim();
if (i18nKey && te(i18nKey)) {
return t(i18nKey);
@@ -205,6 +216,15 @@ const showNextStep = computed(() => {
return !['completed', 'cancelled'].includes(status);
});
/**
* 状态块内嵌动态说明的显隐:具体阻断原因已由「下一步」承载时,
* Run 级泛化等待说明(如「当前步骤需要人工处理」)属纯重复,隐藏。
*/
const showStatusDetail = computed(() => {
if (!props.statusDetail?.text) return false;
return isGenericBlockingReason(props.blockingReason, te);
});
/**
* 判断当前工作台是否应隐藏后端下发的纯导航动作。
* 批次中心可用它打开工作台;进入工作台后必须复用注册表规则,避免当前阶段再次显示
@@ -382,13 +402,14 @@ type ReviewCurrentUserStatus =
/>
{{ statusLabel }}
</dd>
<!-- v2:状态块内嵌动态说明(弱文本一行,不加标题/图标/区块;显隐裁决在视图侧)。 -->
<!-- v2:状态块内嵌动态说明(弱文本一行,不加标题/图标/区块;
v4:blocking_reason 已含具体原因时隐藏,避免与「下一步」重复)。 -->
<p
v-if="statusDetail?.text"
v-if="showStatusDetail"
class="w-full text-[11px] leading-4 text-muted"
data-testid="review-current-task-status-detail"
aria-live="polite"
>{{ statusDetail.text }}</p>
>{{ statusDetail?.text }}</p>
</div>
</dl>
@@ -173,3 +173,64 @@ describe('ReviewDocumentNavigation', () => {
narrow.unmount();
});
});
describe('ReviewDocumentNavigation queue row status icons', () => {
/**
* 以指定字段挂载单行侧栏队列,返回该行按钮包装器。
*/
function mountRow(item: Partial<ReviewDocumentNavItem>) {
return mount(ReviewDocumentNavigation, {
props: {
items: [{ case_no: 'C-1', file_name: 'f1.pdf', status: 'draft', ...item }],
activeCaseNo: 'C-1',
navAriaLabel: 'nav',
forceMode: 'sidebar',
},
global: { plugins: [i18n] },
}).get('[data-testid="review-doc-nav-C-1"]');
}
it('renders confirmed cases as in-progress spinner instead of done check', () => {
const row = mountRow({ status: 'confirmed' });
// 关键断言:已创建任务是系统在办中间态,必须转圈而非绿勾。
expect(row.find('svg.animate-spin').exists()).toBe(true);
expect(row.find('svg.text-emerald-500').exists()).toBe(false);
});
it('renders ready-to-confirm cases as amber attention icon', () => {
const row = mountRow({ status: 'ready' });
// 关键断言:可确认是等人操作,属于待办而非完成。
expect(row.find('svg.text-amber-500').exists()).toBe(true);
});
it('renders backend gate-blocked cases as amber attention icon', () => {
const row = mountRow({ status: 'confirmed', needs_attention: true });
// 关键断言:needs_attention 是后端门禁裁决,优先于中间态转圈。
expect(row.find('svg.text-amber-500').exists()).toBe(true);
expect(row.find('svg.animate-spin').exists()).toBe(false);
});
it('reserves the green check for terminal upload_complete', () => {
const row = mountRow({ status: 'confirmed', lifecycle_stage: 'upload_complete' });
expect(row.find('svg.text-emerald-500').exists()).toBe(true);
expect(row.find('svg.animate-spin').exists()).toBe(false);
});
it('renders failed and neutral states as before', () => {
expect(mountRow({ status: 'failed' }).find('svg.text-rose-500').exists()).toBe(true);
const idle = mountRow({ status: 'non_order' });
expect(idle.find('svg.text-muted').exists()).toBe(true);
expect(idle.find('svg.animate-spin').exists()).toBe(false);
});
it('keeps the truthful state icon on the selected row', () => {
const row = mountRow({ status: 'draft' });
// 关键断言:选中态由行高亮表达,图标不再被 active 覆盖成灰圈。
expect(row.find('svg.text-amber-500').exists()).toBe(true);
});
it('treats missing needs_attention as false for old queue payloads', () => {
const row = mountRow({ status: 'confirmed', needs_attention: undefined });
expect(row.find('svg.animate-spin').exists()).toBe(true);
});
});
@@ -11,6 +11,7 @@ import {
ChevronLeft,
ChevronRight,
Circle,
LoaderCircle,
Search,
TriangleAlert,
X,
@@ -23,10 +24,12 @@ export type ReviewDocumentNavItem = {
file_name?: string | null;
status: string;
issue_count?: number;
/** 队列接口按当前门禁裁决的"需人工"标志(blocked_manual/blocked_retryable/failed_terminal);前端禁止自行推断阻塞。 */
needs_attention?: boolean | null;
po_number?: string | null;
customer_name?: string | null;
stage_label?: string | null;
/** 队列接口下发的生命周期码;仅用于本地化展示,不参与阶段裁决。 */
/** 队列接口下发的生命周期码;用于阶段文字展示与终态(upload_complete)绿勾判定,不参与阶段裁决。 */
lifecycle_stage?: ReviewLifecycleStageCode | null;
};
@@ -118,17 +121,20 @@ function lifecycleStageLabel(item: ReviewDocumentNavItem): string | null {
}
/**
* 导航状态图标语义。
* 队列状态图标语义,按优先级命中即停:
* 失败 → 需人工(草稿问题数 / needs_attention 门禁阻塞)→ 终态绿勾
* → 等人状态 ⚠ → 系统在办转圈 → 中性灰圈 → 兜底转圈。
* 绿勾只属于终态(upload_complete / closed / completed);选中态由行高亮表达,
* 本函数不感知选中,图标永远如实反映状态。
*/
function navIconKind(item: ReviewDocumentNavItem): 'active' | 'alert' | 'processing' | 'done' | 'failed' | 'idle' {
if (props.activeCaseNo === item.case_no) return 'active';
function navIconKind(item: ReviewDocumentNavItem): 'alert' | 'done' | 'failed' | 'processing' | 'idle' {
const status = String(item.status || '').toLowerCase();
if (item.issue_count && item.issue_count > 0) return 'alert';
if (status === 'failed' || status === 'error') return 'failed';
if (status === 'confirmed' || status === 'completed' || status === 'ready' || status === 'closed') return 'done';
if (status === 'processing' || status === 'reparse_pending' || status === 'queued') return 'processing';
if (status === 'non_order' || status === 'cancelled' || status === 'superseded') return 'idle';
if (status === 'draft' || status === 'pending_review' || status === 'waiting_review') return 'alert';
if ((item.issue_count && item.issue_count > 0) || item.needs_attention === true) return 'alert';
if (item.lifecycle_stage === 'upload_complete' || status === 'completed' || status === 'closed') return 'done';
if (['draft', 'ready', 'unreviewed', 'quality_issue', 'pending_review', 'waiting_review'].includes(status)) return 'alert';
if (['confirmed', 'confirming', 'processing', 'reparse_pending', 'queued'].includes(status)) return 'processing';
if (['non_order', 'cancelled', 'superseded'].includes(status)) return 'idle';
return 'processing';
}
@@ -139,7 +145,7 @@ function matchesStatusFilter(item: ReviewDocumentNavItem): boolean {
if (statusFilter.value === 'all') return true;
const kind = navIconKind(item);
if (statusFilter.value === 'needs_action') return kind === 'alert';
if (statusFilter.value === 'processing') return kind === 'processing' || kind === 'active';
if (statusFilter.value === 'processing') return kind === 'processing';
if (statusFilter.value === 'done') return kind === 'done';
if (statusFilter.value === 'failed') return kind === 'failed';
return true;
@@ -218,6 +224,11 @@ function onSelect(caseNo: string) {
class="h-3.5 w-3.5 shrink-0 text-rose-500"
aria-hidden="true"
/>
<LoaderCircle
v-else-if="navIconKind(item) === 'processing'"
class="h-3.5 w-3.5 shrink-0 animate-spin text-brand-600"
aria-hidden="true"
/>
<Circle
v-else
class="h-3 w-3 shrink-0 text-muted"
@@ -329,6 +340,10 @@ function onSelect(caseNo: string) {
v-else-if="navIconKind(item) === 'failed'"
class="mt-0.5 h-3.5 w-3.5 shrink-0 text-rose-500"
/>
<LoaderCircle
v-else-if="navIconKind(item) === 'processing'"
class="mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin text-brand-600"
/>
<Circle
v-else
class="mt-0.5 h-3 w-3 shrink-0 text-muted"
@@ -9,33 +9,13 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { loadPdfJs } from '@/shared/utils/pdfjs';
import type { ShippingOrderReviewEvidence } from '../../types/shipping.api.types';
import { normalizedTopLeftBBoxToViewportRect } from './pdfHighlightCoords';
/** 有合法 bbox 时四种质量都绘制;颜色只提示可信度,不隐藏取值位置。 */
const DRAWABLE_QUALITIES = new Set(['verified', 'candidate', 'unavailable', 'invalid']);
type PdfJsModule = typeof import('pdfjs-dist');
let pdfjsLoader: Promise<PdfJsModule> | null = null;
/**
* 动态加载 pdfjs 与 worker;同页复用单例 Promise。
*/
async function loadPdfJs(): Promise<PdfJsModule> {
if (!pdfjsLoader) {
pdfjsLoader = (async () => {
const [pdfjs, workerMod] = await Promise.all([
import('pdfjs-dist'),
import('pdfjs-dist/build/pdf.worker.min.mjs?url'),
]);
pdfjs.GlobalWorkerOptions.workerSrc = workerMod.default;
return pdfjs;
})();
}
return pdfjsLoader;
}
const props = withDefaults(defineProps<{
src: string;
evidence?: ShippingOrderReviewEvidence | null;
@@ -1184,4 +1184,86 @@ describe('ShippingConversationProcessingCard', () => {
const row = wrapper.find('[data-testid="shipping-processing-file-DOC-10"]');
expect(row.findAll('button')).toHaveLength(0);
});
it('shows a specific blocking reason once per waiting-human card without header duplication', async () => {
// v4 去重:具体原因由文件行页脚独家承载;任务卡头不再重复同一句。
// ui_state 挂在任务条目上(与后端 EML 聚合下发形态一致:任务级为代表子项原因)。
const projection = buildProjection();
setStatusGroup(projection, 'waiting_human', [{
user_task_no: 'OT-REASON-ONCE', group: 'waiting_human', status_label: 'pending_review',
file_count: 1, run_no: 'RUN-REASON-ONCE', can_append: false,
uiState: {
status: 'waiting_human',
stage: 'order_review',
blocking_reason: { code: 'customer_unresolved', message: '客户尚未确认' },
primary_action: null,
secondary_actions: [],
},
objects: [{
kind: 'document', object_key: 'DOC-REASON', label: 'reason.pdf', filename: 'reason.pdf',
document_id: 91, root_document_id: 91, status_label: 'pending_review',
}],
}]);
const workItem = buildWorkItem('OT-REASON-ONCE', {
sourceSummary: {
emailSubject: null, filename: 'reason.pdf', documentId: 91,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: 'PO-REASON',
},
status: 'waiting_human',
uiState: {
status: 'waiting_human',
stage: 'order_review',
blocking_reason: { code: 'customer_unresolved', message: '客户尚未确认' },
primary_action: null,
secondary_actions: [],
},
});
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [workItem], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
// 关键断言:具体原因全文只出现一次,且带「阻塞原因:」前缀落在文件行页脚。
const matches = wrapper.text().match(/客户尚未确认/g) || [];
expect(matches.length).toBe(1);
expect(wrapper.text()).toContain('阻塞原因:客户尚未确认');
});
it('hides the blocker line when the backend only provides a generic fallback reason', async () => {
// v4:未知原因码不得渲染成「当前步骤需要人工处理」空话;状态芯片已表达待人工。
const projection = buildProjection();
setStatusGroup(projection, 'waiting_human', [{
user_task_no: 'OT-REASON-GENERIC', group: 'waiting_human', status_label: 'pending_review',
file_count: 1, run_no: 'RUN-REASON-GENERIC', can_append: false,
objects: [{
kind: 'document', object_key: 'DOC-GENERIC', label: 'generic.pdf', filename: 'generic.pdf',
document_id: 92, root_document_id: 92, status_label: 'pending_review',
}],
}]);
const workItem = buildWorkItem('OT-REASON-GENERIC', {
sourceSummary: {
emailSubject: null, filename: 'generic.pdf', documentId: 92,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: 'PO-GENERIC',
},
status: 'waiting_human',
uiState: {
status: 'waiting_human',
stage: 'order_review',
blocking_reason: { code: 'mystery_internal_code' },
primary_action: null,
secondary_actions: [],
},
});
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [workItem], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.text()).not.toContain('阻塞原因');
expect(wrapper.text()).not.toContain('当前步骤需要人工处理');
});
});
@@ -30,8 +30,8 @@ import {
toggleTaskDetails,
} from '@/features/chat/shipping/conversationProcessingState';
import {
resolveBlockingReasonText,
resolveShippingProcessingMessage,
resolveShippingProcessingReasonLabel,
resolveShippingProcessingStageLabel,
resolveShippingProcessingStatusLabel,
} from '@/features/chat/shipping/shippingProcessingLabels';
@@ -593,7 +593,8 @@ function workbenchFileReason(file: WorkbenchFileRow, task: ConversationProcessin
const reason = file.projection.uiState
? file.projection.uiState.blocking_reason
: file.projection.blockingReason;
return resolveShippingProcessingReasonLabel(reason, te, t);
// v4:具体原因才展示(Gate 命名空间/契约 message 可解析),通用兜底返回空串隐藏。
return resolveBlockingReasonText(reason, te, t);
}
return taskReasonLabel(task);
}
@@ -686,12 +687,20 @@ function stageLabel(task: ConversationProcessingUserTask): string {
return intakeStageLabel(projection);
}
/** 展示后端 ui_state 已裁决的阻断原因;i18n 仅负责翻译,不映射或猜测业务原因。 */
/** 展示后端 ui_state 已裁决的阻断原因;v4:具体原因才展示,通用兜底返回空串。 */
function taskReasonLabel(task: ConversationProcessingUserTask): string {
const reason = task.uiState
? task.uiState.blocking_reason
: task.blockingReason;
return resolveShippingProcessingReasonLabel(reason, te, t);
return resolveBlockingReasonText(reason, te, t);
}
/**
* 任务卡头原因行显隐:workbench 模式下文件行页脚已逐文件承载原因,
* 卡头不再重复同一句;非 workbench(折叠聚合卡)仍由卡头独家展示。
*/
function taskHeaderReasonVisible(task: ConversationProcessingUserTask): boolean {
return !props.workbenchMode || visibleWorkbenchFileRows(task).length === 0;
}
/** 同一 EML 聚合卡状态计数;仅用后端下发的 aggregateSummary,不从 UI 状态推导。 */
@@ -960,7 +969,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
>
{{ primaryFileLabel(task) }}
</div>
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
<div v-if="taskHeaderReasonVisible(task) && taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
{{ taskReasonLabel(task) }}
</div>
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">
@@ -1056,7 +1065,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
<div v-if="!workbenchMode" class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
</div>
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">{{ taskReasonLabel(task) }}</div>
<div v-if="taskHeaderReasonVisible(task) && taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">{{ taskReasonLabel(task) }}</div>
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">{{ aggregateStatusLabel(task) }}</div>
</button>
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-amber-200/70 pt-2">
@@ -1323,7 +1332,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
>
{{ primaryFileLabel(task) }}
</div>
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
<div v-if="taskHeaderReasonVisible(task) && taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
{{ taskReasonLabel(task) }}
</div>
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-emerald-200/70 pt-2">
@@ -74,7 +74,8 @@ describe('ShippingOrderExtractionCard', () => {
},
});
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
// 方案 A:中心常驻后,对话流不再提供「打开批次进度中心」入口(回归保护:按钮不得复活)。
expect(wrapper.find('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(false);
});
it('does not present historical handling items or CTA as current work when the live projection exists', () => {
@@ -115,16 +116,6 @@ describe('ShippingOrderExtractionCard', () => {
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
});
it('collapses file-level progress when the batch workbench is open', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState(), runNo: 'SNER-COMPACT', compactProgress: true },
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processingWorkItems: ref([]) } } },
});
expect(wrapper.find('[data-testid="shipping-order-extraction-status-groups"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(false);
});
it('uses unified EML aggregation and keeps candidate creation out of completed', async () => {
const aggregate = {
workItemType: 'order_task', workItemNo: 'INTAKE:SNI-1', sourceType: 'eml', rootOrderTaskNo: 'OT-1',
@@ -643,7 +634,8 @@ describe('ShippingOrderExtractionCard', () => {
expect(wrapper.text()).toContain('3 个文件');
expect(wrapper.text()).toContain('系统处理中');
expect(wrapper.text()).toContain('处理时间偏长');
expect(wrapper.text()).toContain('打开批次进度中心');
// 方案 A:中心常驻后,对话流不再提供「打开批次进度中心」入口(回归保护:按钮不得复活)。
expect(wrapper.text()).not.toContain('打开批次进度中心');
expect(wrapper.text()).not.toContain('刷新状态');
expect(wrapper.text()).not.toContain('取消本次识别');
expect(wrapper.text()).not.toContain('PO-450003.pdf');
@@ -731,7 +723,8 @@ describe('ShippingOrderExtractionCard', () => {
});
expect(wrapper.text()).toContain('订单候选已生成');
expect(wrapper.text()).toContain('候选待人工确认 · 2 项');
expect(wrapper.text()).toContain('打开批次进度中心');
// 方案 A:中心常驻后,对话流不再提供「打开批次进度中心」入口(回归保护:按钮不得复活)。
expect(wrapper.text()).not.toContain('打开批次进度中心');
expect(wrapper.text()).not.toContain('部分附件需人工处理');
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-item"]').length).toBe(0);
});
@@ -826,7 +819,8 @@ describe('ShippingOrderExtractionCard', () => {
});
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-order-extraction-view-details"]').exists()).toBe(false);
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
// 方案 A:中心常驻后,对话流不再提供「打开批次进度中心」入口(回归保护:按钮不得复活)。
expect(wrapper.find('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(false);
});
it('does not render multi-OT ChatProgressSummary list', () => {
@@ -914,7 +908,8 @@ describe('ShippingOrderExtractionCard', () => {
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
// 方案 A:中心常驻后,对话流不再提供「打开批次进度中心」入口(回归保护:按钮不得复活)。
expect(wrapper.find('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(false);
});
it('does not render the removed view details link', () => {
@@ -956,7 +951,8 @@ describe('ShippingOrderExtractionCard', () => {
},
},
});
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
// 方案 A:中心常驻后,对话流不再提供「打开批次进度中心」入口(回归保护:按钮不得复活)。
expect(wrapper.find('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(false);
expect(wrapper.text()).toContain('共 1 个文件');
});
@@ -1,14 +1,14 @@
/**
* features/chat/components/shipping/ShippingOrderExtractionCard.vue
* 用途:聊天主区「本次订单文件处理」摘要卡——标题、文件数+状态、一行 handling 摘要、唯一主 CTA、查看详情。
* 用途:聊天主区「本次订单文件处理」摘要卡——标题、文件数+状态、一行 handling 摘要、无对话流 CTA(批次中心常驻,方案 A)。
* 依赖:订单抽取 Run 状态卡 DTO、shipping.api 文档/进度接口、ShippingOrderExtractionDetailsDrawer、vue-router、vue-i18n。
* 逻辑:对话区默认展示状态-EML 聚合;批次工作台打开后切换为紧凑摘要,长进度/Gate/刷新取消由工作台承接。
* 逻辑:对话区默认展示状态-EML 聚合;无对话流 CTA(批次中心常驻,方案 A),长进度/Gate/刷新取消由工作台承接。
*/
<script setup lang="ts">
import { computed, inject, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { AlertCircle, ArrowRight, CheckCircle2, ChevronDown, CircleX, FileText, LoaderCircle, Mail, RefreshCw, TriangleAlert } from 'lucide-vue-next';
import { AlertCircle, CheckCircle2, ChevronDown, CircleX, FileText, LoaderCircle, Mail, RefreshCw, TriangleAlert } from 'lucide-vue-next';
import type {
ShippingOrderExtractionHandlingItemState,
ShippingOrderExtractionFileState,
@@ -44,15 +44,12 @@ const props = defineProps<{
readonlyReason?: string | null;
/** 可选统一投影;摘要卡不再渲染进度,仅保留 prop 兼容宿主。 */
processingProjection?: ShippingProcessingProjection | null;
/** 批次工作台打开时,左侧只保留摘要,避免与工作台重复展示文件明细。 */
compactProgress?: boolean;
}>();
const emit = defineEmits<{
retry: [];
refresh: [];
cancel: [reason?: string];
'open-batch-workbench': [];
}>();
const { t, te } = useI18n();
@@ -425,7 +422,6 @@ const hasAnyStatusGroupTask = computed(() => (
*/
const recognizingPlaceholderVisible = computed(() => (
hasConversationStatusGroups.value
&& !props.compactProgress
&& !hasAnyStatusGroupTask.value
&& (submittedFileCount.value ?? 0) > 0
));
@@ -850,7 +846,7 @@ async function onPrimaryChatAction() {
<div v-if="handlingSummaryLine && !hasConversationStatusGroups" class="mt-1 text-sm text-secondary">{{ handlingSummaryLine }}</div>
</div>
<div v-if="hasConversationStatusGroups && !compactProgress" class="flex flex-col gap-2 bg-surface-soft p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-status-groups">
<div v-if="hasConversationStatusGroups" class="flex flex-col gap-2 bg-surface-soft p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-status-groups">
<div v-if="recognizingPlaceholderVisible" class="flex items-center gap-2 rounded-lg border border-default bg-surface p-3 text-sm text-muted">
<LoaderCircle class="h-4 w-4 animate-spin text-brand-500" />
<span data-testid="shipping-order-extraction-recognizing-placeholder">{{ t('chat.shippingProcessing.recognizingAttachments') }}</span>
@@ -899,7 +895,7 @@ async function onPrimaryChatAction() {
</section>
</template>
</div>
<div v-else-if="!compactProgress && emlAggregate" class="flex flex-col gap-2 bg-surface-soft p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-eml-aggregate">
<div v-else-if="emlAggregate" class="flex flex-col gap-2 bg-surface-soft p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-eml-aggregate">
<article class="overflow-hidden rounded-lg border border-default bg-surface shadow-sm">
<div class="flex items-start gap-3 border-b border-default bg-surface-soft p-3 dark:bg-slate-950/30">
<Mail class="mt-0.5 h-5 w-5 text-brand-500" />
@@ -926,7 +922,7 @@ async function onPrimaryChatAction() {
</div>
</article>
</div>
<div v-else-if="!compactProgress" class="flex flex-col gap-2 bg-surface-soft p-2 dark:bg-slate-950/30">
<div v-else class="flex flex-col gap-2 bg-surface-soft p-2 dark:bg-slate-950/30">
<div v-for="row in activeEmailRows" :key="row.unitId" class="overflow-hidden rounded-lg border border-default bg-surface shadow-sm">
<div class="flex items-start gap-3 border-b border-default bg-surface-soft p-3 dark:bg-slate-950/30"><Mail class="mt-0.5 h-5 w-5 text-brand-500" /><div class="min-w-0 flex-1"><div class="flex items-center justify-between gap-3"><span class="font-medium">{{ t('chat.shippingProcessing.emailPrefix') }}{{ row.fileName }}</span><span class="rounded border px-2 py-0.5 text-xs" :class="isFailedParseRow(row) || emailHasFailedChild(row) ? 'border-rose-200 bg-rose-100/70 text-rose-600' : emailIsCompleted(row) ? 'border-emerald-200 bg-emerald-100/70 text-emerald-600' : 'border-brand-200 bg-brand-100/70 text-brand-600'">{{ isFailedParseRow(row) || emailHasFailedChild(row) ? t('chat.shippingProcessing.batchException') : emailIsCompleted(row) ? t('chat.shippingProcessing.batchExtracted') : t('chat.shippingProcessing.parsingAttachments') }}</span></div><span class="mt-1 block font-mono text-xs text-muted">{{ t('chat.shippingProcessing.emailMeta') }}</span></div></div>
<div class="mx-4 my-2 flex flex-col gap-2 border-l-2 border-default bg-surface-soft p-3 pl-4 dark:border-slate-700 dark:bg-slate-950/30"><div v-for="child in childRows(row)" :key="`child-${child.unitId}`" class="flex items-center justify-between gap-3 text-sm"><span class="flex min-w-0 items-center gap-2"><CheckCircle2 v-if="child.status === 'candidate_ready'" class="h-4 w-4 text-emerald-500" /><LoaderCircle v-else-if="!isFailedParseRow(child)" class="h-4 w-4 animate-spin text-brand-500" /><AlertCircle v-else class="h-4 w-4 text-rose-500" /><span class="truncate">{{ child.fileName }}</span></span><span :class="rowStatusClass(child)">{{ rowStatusLabel(child) }}</span></div></div>
@@ -936,20 +932,6 @@ async function onPrimaryChatAction() {
<div v-for="row in failedRows" :key="`failed-${row.unitId}`" class="rounded-lg border border-rose-200 bg-rose-50 p-3 dark:border-rose-800 dark:bg-rose-950/30"><div class="flex items-center justify-between text-rose-600"><span class="flex items-center gap-2 font-medium"><AlertCircle class="h-5 w-5" />{{ row.fileName }}</span><span class="rounded bg-rose-100 px-2 py-0.5 text-xs">{{ t('chat.shippingProcessing.batchException') }}</span></div><p class="mt-2 pl-7 text-sm">{{ row.explainability?.message || t('chat.shippingProcessing.batchManualVerify') }}</p></div>
</div>
<div class="flex justify-end border-t border-default bg-brand-50/60 p-3 dark:bg-brand-950/20">
<div class="flex items-center gap-3">
<button
v-if="!compactProgress && (hasConversationStatusGroups || String(props.runNo || '').trim())"
type="button"
class="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-5 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-brand-700"
data-testid="shipping-order-extraction-open-batch-workbench"
@click="emit('open-batch-workbench')"
>
{{ t('chat.shippingProcessing.openBatchWorkbench') }}
<ArrowRight class="h-4 w-4" />
</button>
</div>
</div>
<div v-if="false" class="flex items-start gap-3">
<CircleX class="mt-0.5 h-4 w-4 shrink-0" />
<div class="min-w-0 flex-1">
@@ -104,10 +104,11 @@ function buildController(
function mountTimeline(
processing = processingProjection(),
workItems: ShippingProcessingProjection[] = [],
extraProps: Record<string, unknown> = {},
) {
return mount(ShippingWorkflowTimeline, {
attachTo: document.body,
props: { conversationId: 'conv-1', controller: buildController(processing, workItems) },
props: { conversationId: 'conv-1', controller: buildController(processing, workItems), ...extraProps },
global: { plugins: [i18n], stubs: { teleport: true } },
});
}
@@ -124,6 +125,24 @@ describe('ShippingWorkflowTimeline', () => {
gateRecovery.submitPrimaryAction.mockClear();
});
it('has no close button and reuses the conversation title in the header', () => {
const wrapper = mountTimeline(processingProjection(), [], { conversationTitle: 'PO#6075309 09-15' });
// 中心常驻不可关闭(方案 A):关闭按钮必须消失。
expect(wrapper.find('[data-testid="shipping-workflow-close"]').exists()).toBe(false);
// 会话标题直接复用侧栏命名,保持两处一致。
const titleNode = wrapper.find('[data-testid="shipping-workflow-conversation-title"]');
expect(titleNode.exists()).toBe(true);
expect(titleNode.text()).toContain('PO#6075309 09-15');
});
it('omits the title node when no conversation title is provided', () => {
const wrapper = mountTimeline(processingProjection(), []);
expect(wrapper.find('[data-testid="shipping-workflow-conversation-title"]').exists()).toBe(false);
});
it('prefers backend five-stage lifecycle nodes and shows the authorized download toolbar in freight upload', async () => {
const processing = processingProjection({
lifecycle_nodes: [
@@ -205,25 +224,6 @@ describe('ShippingWorkflowTimeline', () => {
expect(wrapper.find('[data-testid="shipping-processing-file-DOC-9"]').exists()).toBe(true);
});
it('labels a manually actionable batch as action needed instead of processing', async () => {
const task = { ...processingProjection().processing[0], group: 'needs_action' };
const processing = processingProjection({
summary: { total_files: 1, processing_files: 0, completed_files: 0, waiting_human_files: 1, failed_files: 0 },
needs_action: [task], processing: [],
status_groups: { failed: [], waiting_human: [task], processing: [], completed: [], cancelled: [], archived: [] },
} as Partial<ConversationProcessingProjection>);
const wrapper = mountTimeline(processing, [fileProjection({
uiState: {
status: 'waiting_human', stage: 'order_review', lifecycleStage: 'order_review',
lifecycleEntries: [], blocking_reason: null, primary_action: null, secondary_actions: [],
},
})]);
await flushPromises();
// 关键断言:锁定表示仍有待办,不得与「处理中 0」形成视觉矛盾。
expect(wrapper.get('[data-testid="shipping-workflow-panel-pinned"]').text()).toBe('待处理');
});
it('navigates only through the backend lifecycle entry', async () => {
const file = fileProjection({
uiState: {
@@ -3,7 +3,7 @@
* 用途:聊天页右侧「批次进度中心」——后端批次投影、五阶段进度和文件行操作。
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow、ShippingConversationProcessingCard、
* ReasonDialog、ProcessGateRecoveryCard。
* 逻辑:顶层以 OT / ShippingProcessing 为主路径;标题栏仅保留批次名称、加载与截断提示,
* 逻辑:顶层以 OT / ShippingProcessing 为主路径;标题栏保留批次名称、会话标题、加载与截断提示;中心常驻不可关闭(方案 A),
* 文件总览和进度仅消费后端批次 summary;
* 文件清单消费后端 conversation_processing.status_groups;work_items 仅用于定位同一
* 展示 DTO 的操作对象;整批操作走 Run API,单文件取消走 Unit API;
@@ -14,7 +14,7 @@
import { computed, inject, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { ChevronDown, ChevronRight, Lock, RefreshCw } from 'lucide-vue-next';
import { RefreshCw } from 'lucide-vue-next';
import {
downloadWorkspaceShippingExcelFile,
downloadWorkspaceShippingExportArchive,
@@ -59,10 +59,8 @@ const props = defineProps<{
refreshTrigger?: number;
/** 测试或父级注入时可直接传入控制器,跳过自建轮询。 */
controller?: UseShippingNoticeWorkflowReturn | null;
}>();
const emit = defineEmits<{
close: [];
/** 当前会话标题;父级从侧栏历史匹配传入,中心头部直接复用(无新增接口)。 */
conversationTitle?: string | null;
}>();
const { t, te } = useI18n();
@@ -91,11 +89,6 @@ const ctl = computed((): UseShippingNoticeWorkflowReturn => (
props.controller || injected || localController
));
/**
* 侧栏折叠态:默认展开。
* 有处理中/待处理/未查看完成任务时强制展开,仅允许收起文件详情。
*/
const collapsed = ref(false);
/** 复核返回对话时展示的聚焦提示(由 focus_notice 触发一次)。 */
const focusTaskBanner = ref<string | null>(null);
const actionBusyItemNo = ref<string | null>(null);
@@ -249,34 +242,6 @@ const initialLoading = computed(() => Boolean(ctl.value.initialLoading?.value));
const manualRefreshing = computed(() => Boolean(ctl.value.manualRefreshing?.value));
const isRefreshing = computed(() => Boolean(ctl.value.isRefreshing?.value));
const error = computed(() => ctl.value.error.value);
/**
* 右侧仍有用户必须持续可见的任务时,禁止收起整个处理面板。
* 核心逻辑:处理中 / 待处理 / 未查看完成均属活跃可见任务;无此类任务才允许收起侧栏。
*/
const hasPinnedProcessingTasks = computed(() => {
const projection = displayProcessing.value;
if (!projection) return false;
return statusGroupTasks('failed', 'waiting_human', 'processing', 'completed').length > 0;
});
/**
* 切换侧栏折叠:活跃任务存在时强制保持展开。
*/
function togglePanelCollapsed() {
if (hasPinnedProcessingTasks.value) {
collapsed.value = false;
return;
}
collapsed.value = !collapsed.value;
}
watch(
hasPinnedProcessingTasks,
(pinned) => {
if (pinned) collapsed.value = false;
},
{ immediate: true },
);
/**
* 移除右侧常驻「批次与文件列表」长列表抽屉(UI-REFACTOR 方案 7)。
@@ -839,7 +804,6 @@ watch(
return;
}
if (!focusedTaskExists.value) return;
collapsed.value = false;
focusTaskBanner.value = normalized;
// [UI-01/UI-02] 真正选中进度卡,禁止只显示提示条。
await onProcessingFocus(normalized);
@@ -856,31 +820,12 @@ watch(
<template>
<aside
class="flex min-w-0 flex-1 shrink-0 flex-col border-l border-default bg-surface shadow-[-16px_0_40px_rgba(15,23,42,0.10)] transition-[width] duration-200"
:class="collapsed ? '!w-14' : ''"
class="flex min-w-0 flex-1 shrink-0 flex-col bg-surface"
data-testid="shipping-workflow-timeline"
>
<div class="flex w-full items-center gap-1 border-b border-default px-2 py-2">
<button
type="button"
class="shrink-0 rounded-md p-1.5 text-muted hover:bg-surface-muted hover:text-primary"
data-testid="shipping-workflow-close"
:title="t('chat.shippingProcessing.closeWorkbench')"
@click="emit('close')"
>
×
</button>
<component
:is="hasPinnedProcessingTasks ? 'div' : 'button'"
:type="hasPinnedProcessingTasks ? undefined : 'button'"
class="flex min-w-0 flex-1 items-center justify-between gap-2 rounded-md px-1 py-1 text-left"
:class="hasPinnedProcessingTasks
? 'cursor-default'
: 'hover:bg-surface-muted/60'"
data-testid="shipping-workflow-panel-toggle"
@click="togglePanelCollapsed"
>
<div v-if="!collapsed" class="min-w-0">
<div class="flex min-w-0 flex-1 items-center justify-between gap-2 rounded-md px-1 py-1 text-left">
<div class="min-w-0">
<div class="flex items-center gap-1.5">
<div class="text-sm font-semibold text-primary">
{{ te('chat.shippingProcessing.panelTitle')
@@ -888,14 +833,11 @@ watch(
: t('chat.shippingProcessing.title') }}
</div>
<span
v-if="hasPinnedProcessingTasks"
class="inline-flex items-center gap-0.5 rounded bg-surface-muted px-1.5 py-0.5 text-[10px] font-medium text-secondary"
data-testid="shipping-workflow-panel-pinned"
:title="t('chat.shippingProcessing.panelPinnedHint')"
>
<Lock class="h-3 w-3 shrink-0" aria-hidden="true" />
{{ t('chat.shippingProcessing.panelPinnedLabel') }}
</span>
v-if="conversationTitle"
class="min-w-0 truncate rounded bg-surface-muted px-1.5 py-0.5 text-xs text-secondary"
data-testid="shipping-workflow-conversation-title"
:title="conversationTitle"
>{{ conversationTitle }}</span>
</div>
<div class="mt-0.5 space-y-0.5 text-xs text-secondary" data-testid="shipping-workflow-panel-summary">
<template v-if="initialLoading && !displayProcessing">
@@ -918,12 +860,7 @@ watch(
</template>
</div>
</div>
<ChevronDown
v-if="!collapsed && !hasPinnedProcessingTasks"
class="h-4 w-4 shrink-0 text-muted"
/>
<ChevronRight v-else-if="collapsed" class="h-4 w-4 shrink-0 text-muted" />
</component>
</div>
<button
type="button"
class="shrink-0 rounded-md p-1.5 text-muted hover:bg-surface-muted hover:text-primary disabled:opacity-50"
@@ -939,7 +876,7 @@ watch(
</button>
</div>
<div v-if="!collapsed" class="min-h-0 flex-1 overflow-y-auto p-5">
<div class="min-h-0 flex-1 overflow-y-auto p-5">
<div
v-if="initialLoading && !displayProcessing"
class="mb-4 space-y-3"
@@ -4,6 +4,7 @@
* 依赖:useChat* composables、shipping(含 openShippingCustomerDialog)、chat.api。
* 逻辑:ChatView provide(CHAT_PAGE_KEY);子树经 inject 打开客户确认等叠层。
* 兼容:同时编排采购合同审查与货代客户确认能力。
* 货代发送禁用态经 hasBlockingNoticeIntake / isOrderExtractionSubmitting 注入 createChatPageSendApi。
*/
import { computed, markRaw, nextTick, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
@@ -446,6 +447,8 @@ export function useChatPage() {
tryHandleProcurementContractSend: procurement.tryHandleProcurementContractSend,
refreshToolRunProgressAfterSend: toolRun.refreshToolRunProgressAfterSend,
prepareToolRunProgressBeforeSend: toolRun.prepareToolRunProgressBeforeSend,
hasBlockingNoticeIntake: shipping.hasBlockingNoticeIntake,
isOrderExtractionSubmitting: shipping.isOrderExtractionSubmitting,
msg,
t,
copiedIndex,
@@ -593,6 +596,7 @@ export function useChatPage() {
messageBubbleHandlers: markdown.messageBubbleHandlers,
shouldRenderMessage: markdown.shouldRenderMessage,
canSendMessage: sendApi.canSendMessage,
isOrderExtractionSubmitting: shipping.isOrderExtractionSubmitting,
handleSend: sendApi.handleSend,
stopActiveGeneration,
pushLocalAssistantMessage,
@@ -5,6 +5,7 @@
* 逻辑:上游由 ChatView/ChatPage 调用本 composable;本文件维护会话任务摘要 + ui_state 同步,
* 以及 focusedConversationTaskNo(提交追加优先级 / 侧栏焦点)。会话恢复唯一使用 task_no;
* 批次进度由 shipping-processing projection 承接,不维护已下线 shipping_batches 的本地快照。
* 对外暴露 isOrderExtractionSubmitting / hasBlockingNoticeIntake,供发送禁用与输入区 loading。
*/
import {
@@ -979,6 +980,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
cancelOrderExtractionUnit: shippingOrderExtractionRuns.cancelUnit,
reparseOrderExtractionRun: shippingOrderExtractionRuns.reparseRun,
getActiveOrderExtractionRunNo: shippingOrderExtractionRuns.getActiveRunNo,
isOrderExtractionSubmitting: shippingOrderExtractionRuns.isOrderExtractionSubmitting,
hasBlockingNoticeIntake: () => shippingIntakes.hasBlockingUploadOrParse.value,
workflowRefreshTrigger,
bumpWorkflowRefresh,
focusedConversationTaskNo,
@@ -11,6 +11,7 @@ import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
exportTrainingRecords,
exportLeanTrainingDashboard,
getMyTrainingConfig,
getMyTrainingProgress,
getMyTrainingTypes,
@@ -82,6 +83,11 @@ export interface UseTrainingWorkspaceOptions {
const DEFAULT_PASS_SCORE = 90;
const DEFAULT_TRAINING_VERSION = 'v1.0';
const OVERSEAS_REGULATIONS_TRAINING_TYPES = new Set([
'overseas_regulations',
'overseas_regulations_training',
'overseas_training',
]);
const formatDate = (value: Date) => value.toISOString().slice(0, 10);
@@ -125,6 +131,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
/** 管理端精益看板当前选中的期次任务 ID;为空表示最新一期,切换后重新拉取对应期看板。 */
const leanDashboardTaskId = ref<number | null>(null);
const leanReminderLoading = ref<Record<number, boolean>>({});
const leanExportLoading = ref(false);
/** 按任务 ID 分组的感悟草稿,支持时间树上多期任务并行编辑。 */
const leanSummaryByTask = ref<Record<number, string>>({});
/** 按任务 ID 分组的观看记录(资源 ID -> 观看时间),提交时随感悟一并交由服务端校验。 */
@@ -136,6 +143,10 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
{ code: 'onboarding', name: t('chat.training.safety.tabs.onboarding') },
{ code: 'safety', name: t('chat.training.safety.tabs.safety') },
]);
const isOverseasRegulationsTraining = computed(() => (
OVERSEAS_REGULATIONS_TRAINING_TYPES.has(learnerTab.value)
|| trainingTypes.value.some((item) => item.code === learnerTab.value && item.name.includes('出国规章'))
));
const trainingVersion = ref<string>(DEFAULT_TRAINING_VERSION);
const examMode = ref<TrainingExamMode>('unified');
const safetyStage = ref<SafetyStage>('company');
@@ -147,6 +158,11 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
});
const stage = ref<TrainingStage>('video');
watch(isOverseasRegulationsTraining, (isOverseas) => {
if (isOverseas) {
stage.value = 'video';
}
});
const currentQuestionIndex = ref(0);
const score = ref(0);
const attemptCount = ref(0);
@@ -665,7 +681,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
safetyViewStage.value = record.safetyStage || 'company';
}
}
stage.value = record.stage;
stage.value = isOverseasRegulationsTraining.value ? 'video' : record.stage;
syncExamQuestionIndex(record.currentQuestionIndex);
score.value = Number(record.score || 0);
attemptCount.value = Number(record.attempts || 0);
@@ -706,7 +722,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
safetyProgress: learnerTab.value === 'safety' ? safetyProgress.value : null,
currentQuestionIndex: currentQuestionIndex.value,
score: score.value,
passed: isPassed.value,
passed: isOverseasRegulationsTraining.value && stage.value === 'result' ? true : isPassed.value,
attemptCount: attemptCount.value,
answerDetails: answerRecords.value,
joinDate: currentJoinDate.value || formatDate(new Date()),
@@ -749,11 +765,14 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
isHydrated.value = true;
return;
}
const requestedTrainingType = learnerTab.value;
try {
const record = await getMyTrainingProgress(learnerTab.value);
const record = await getMyTrainingProgress(requestedTrainingType);
if (learnerTab.value !== requestedTrainingType) return;
hasWarnedLoadFailure.value = false;
applyProgressRecord(record);
} catch (error) {
if (learnerTab.value !== requestedTrainingType) return;
// 退出登录或登录态失效时,培训页可能尚未卸载;这里静默清空状态,避免把正常 401 提示成“读取失败”。
if (error instanceof BusinessError && error.status === 401) {
hasWarnedLoadFailure.value = false;
@@ -782,15 +801,21 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
trainingConfigLoading.value = false;
return;
}
const requestedTrainingType = learnerTab.value;
trainingConfigLoading.value = true;
try {
publishedConfig.value = await getMyTrainingConfig(learnerTab.value);
const config = await getMyTrainingConfig(requestedTrainingType);
if (learnerTab.value === requestedTrainingType) {
publishedConfig.value = config;
}
} catch (error) {
if (!(error instanceof BusinessError && error.status === 401)) {
if (learnerTab.value === requestedTrainingType && !(error instanceof BusinessError && error.status === 401)) {
publishedConfig.value = null;
}
} finally {
trainingConfigLoading.value = false;
if (learnerTab.value === requestedTrainingType) {
trainingConfigLoading.value = false;
}
}
};
@@ -841,6 +866,20 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
await loadLeanDashboard();
};
const exportLeanDashboard = async () => {
const taskId = leanDashboardTaskId.value ?? leanDashboard.value.task?.id;
if (!taskId || leanExportLoading.value) return;
leanExportLoading.value = true;
try {
await exportLeanTrainingDashboard(taskId);
msg.success(t('chat.training.lean.dashboard.exportSuccess'));
} catch {
msg.error(t('chat.training.lean.dashboard.exportFailed'));
} finally {
leanExportLoading.value = false;
}
};
/** 读取学员端全部已发布精益周任务(含状态与播放地址),并以服务端完成记录回填各任务的感悟/观看草稿。 */
const loadLeanTraining = async () => {
if (!isTrainingAgent.value || !hasAuthenticatedUser.value) return;
@@ -966,11 +1005,25 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
);
const markVideoCompleted = () => {
if (!hasPublishedTrainingConfig.value || !videoUrl.value) return;
if (!hasPublishedTrainingConfig.value) return;
if (!isOverseasRegulationsTraining.value && !videoUrl.value) return;
if (learnerTab.value === 'safety') {
checkAndAdvanceStage();
return;
}
if (isOverseasRegulationsTraining.value) {
stage.value = 'result';
score.value = 100;
completionDate.value = formatDate(new Date());
latestSettledResult.value = {
score: 100,
correctCount: 0,
wrongCount: 0,
isPassed: true,
};
void persistProgress();
return;
}
stage.value = 'summary';
void persistProgress();
};
@@ -1252,6 +1305,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
}
void persistProgress();
} else {
if (isOverseasRegulationsTraining.value) return;
const activeStageMaterials = publishedTrainingMaterials.value;
if (!activeStageMaterials.length) return;
const allCompleted = activeStageMaterials.every(m => {
@@ -1357,6 +1411,8 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
leanStats,
leanRows,
leanDashboardTaskId,
leanExportLoading,
exportLeanDashboard,
selectLeanDashboardPeriod,
learnerChatPrompt,
newSessionReminderMessage,
@@ -1364,6 +1420,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
learnerAssistantMessage,
managementChatPrompt,
markVideoCompleted,
isOverseasRegulationsTraining,
startExam,
selectAnswer,
submitTextAnswer,
@@ -2,7 +2,8 @@
* features/chat/page/useChatPageSend.spec.ts
* 用途:验证普通聊天发送时附件失败保留、消息成功后清空的恢复语义。
* 依赖:Vitest、Vue 响应式 API、useChatPageSend。
* 逻辑:构造最小发送上下文,分别模拟上传失败、SSE 发送失败与发送成功。
* 逻辑:构造最小发送上下文,分别模拟上传失败、SSE 发送失败与发送成功;
* 另覆盖货代 blocking / submitting 对 canSendMessage 的早禁用。
*/
import { computed, ref } from 'vue';
import { describe, expect, it, vi } from 'vitest';
@@ -119,3 +120,32 @@ describe('createChatPageSendApi attachment lifecycle', () => {
expect(ctx.clearAttachments).toHaveBeenCalledOnce();
});
});
describe('createChatPageSendApi canSendMessage shipping gates', () => {
it('disables send when hasBlockingNoticeIntake returns true', () => {
const ctx = createContext({
hasBlockingNoticeIntake: () => true,
});
// 解析/上传未完成时必须早禁用,避免点发送后空等。
expect(createChatPageSendApi(ctx).canSendMessage.value).toBe(false);
});
it('disables send while isOrderExtractionSubmitting is true', () => {
const ctx = createContext({
isOrderExtractionSubmitting: ref(true),
});
// 统一提交进行中禁止重复点击。
expect(createChatPageSendApi(ctx).canSendMessage.value).toBe(false);
});
it('allows send when neither blocking nor submitting', () => {
const ctx = createContext({
hasBlockingNoticeIntake: () => false,
isOrderExtractionSubmitting: ref(false),
});
expect(createChatPageSendApi(ctx).canSendMessage.value).toBe(true);
});
});
@@ -4,6 +4,7 @@
* 依赖:统一 BusinessError、剪贴板工具、Chat 消息与附件参数类型。
* 逻辑:附件上传成功后调用 Dify SSE;仅在消息发送成功后清空附件,失败时保留供重试。
* 兼容:依次处理货代附件、采购合同、请假与货代文本前置拦截。
* 货代路径另受 hasBlockingNoticeIntake / isOrderExtractionSubmitting 约束 canSendMessage。
*/
import { computed } from 'vue';
import { BusinessError } from '@/shared/api/client';
@@ -83,10 +84,26 @@ export interface ChatPageSendContext {
copiedIndex: Ref<number | null>;
getChatContext?: () => { task_id?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string };
onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>;
/** 货代 Intake 仍在上传/解析时返回 true,用于早禁用发送。 */
hasBlockingNoticeIntake?: () => boolean;
/** 订单抽取统一提交进行中;为 true 时禁用发送并展示 Loader。 */
isOrderExtractionSubmitting?: Ref<boolean>;
}
/**
* 组装聊天页发送 API:canSendMessage / handleSend / 复制 / 重新生成。
* 核心逻辑:货代 blocking/submitting 优先禁用;附件失败保留、成功后清空。
* @param ctx - 页面发送所需的响应式状态与业务钩子。
* @returns 发送相关计算属性与方法。
*/
export function createChatPageSendApi(ctx: ChatPageSendContext) {
/**
* 是否允许点击发送。
* 核心逻辑:上传中、订单抽取提交中、或 Intake 阻塞解析时一律 false;其余沿用输入/附件/thinking 规则。
*/
const canSendMessage = computed(() => {
if (ctx.isOrderExtractionSubmitting?.value) return false;
if (ctx.hasBlockingNoticeIntake?.()) return false;
const allowSendWhileThinking = canContinueSendWhileThinking(ctx.messages.value);
if (ctx.isUploadingAttachments.value) return false;
if (ctx.input.value.trim()) return !ctx.isThinking.value || allowSendWhileThinking;
@@ -99,11 +116,19 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
return false;
});
/**
* 处理发送:依次尝试货代附件自动流、采购合同、请假、货代文本,否则走通用 SSE。
* @param textOrEvent - 可选字符串覆盖输入框内容,或来自 UI 事件。
*/
const handleSend = async (textOrEvent?: string | Event) => {
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || ctx.input.value;
const trimmed = content.trim();
const hasAttachments = ctx.attachmentPolicy.value.anyEnabled && ctx.attachments.value.length > 0;
const allowSendWhileThinking = canContinueSendWhileThinking(ctx.messages.value);
// [STEP 0] 提交中禁止重复触发(含 Enter);Intake 阻塞仍交给货代 handler 提示,不在此静默吞掉。
if (ctx.isOrderExtractionSubmitting?.value) {
return;
}
if (await ctx.tryHandleShippingAttachmentAutoFlow(textOrEvent, content, trimmed)) {
return;
}
@@ -649,6 +649,42 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.intakeParseLoadFailed.value).toBe(true);
});
it('loads intake parse context for a formal-downstream Case while activeCase stays unloaded', async () => {
// 选法 2:正式下游(货代上传等)切 PDF 不拉 Case/Evidence,activeCase 保持 null。
// 关键断言:接收解析工作面回看已完成阶段时,上下文仍必须按 requestedCaseNo 拉取,
// 不得因 activeCase 为 null 静默跳过(否则面板渲染成空白)。
api.getQueue.mockResolvedValue({
summary: { total: 1, needs_action: 0, processing: 0, completed: 1 },
items: [{
case_no: 'CASE-2', document_id: 2, status: 'confirmed',
has_formal_ot: true,
lifecycle_stage: 'freight_upload',
lifecycle_entries: [
{ code: 'intake_parse', state: 'available' },
{ code: 'order_review', state: 'available' },
{ code: 'fulfillment_prep', state: 'available' },
{ code: 'freight_upload', state: 'current' },
],
}],
});
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-2');
api.getCase.mockClear();
api.getEvidence.mockClear();
await review.selectCase('CASE-2');
// 选法 2 关键断言:正式下游切换不拉复核 Case/Evidence,activeCase 为空。
expect(api.getCase).not.toHaveBeenCalled();
expect(review.activeCase.value).toBeNull();
expect(review.requestedCaseNo.value).toBe('CASE-2');
await expect(review.ensureIntakeParseContextLoaded('CASE-2')).resolves.toBe(true);
expect(api.getIntakeParseContext).toHaveBeenLastCalledWith('CASE-2');
expect(review.intakeParseContext.value?.case_no).toBe('CASE-2');
expect(review.intakeParseLoading.value).toBe(false);
expect(review.intakeParseLoadFailed.value).toBe(false);
});
it('keeps the latest same-Case intake context when an older success resolves last', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
@@ -771,6 +807,48 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.reviewProgressContext.value?.user_task_authoritative).toBe(false);
});
it('beginCrossRunSwitch drops the previous file intake context and rejects its stale success', async () => {
// 关键断言:跨 Run 切文件(如 PO_6075309 → PO_6075316)切换即清空接收解析上下文,
// 迟到的旧 Case 上下文成功响应也不得把旧附件名/邮件正文写回新文件工作面。
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await review.ensureIntakeParseContextLoaded('CASE-1');
expect(review.intakeParseContext.value?.attachment.filename).toBe('order.pdf');
let resolveStale: ((value: Record<string, unknown>) => void) | null = null;
api.getIntakeParseContext.mockImplementationOnce(
() => new Promise((resolve) => { resolveStale = resolve; }),
);
const pendingStale = review.ensureIntakeParseContextLoaded('CASE-1');
review.beginCrossRunSwitch('CASE-2');
expect(review.intakeParseContext.value).toBeNull();
expect(review.intakeParseLoading.value).toBe(false);
expect(review.intakeParseLoadFailed.value).toBe(false);
resolveStale?.({
case_no: 'CASE-1',
attachment: { document_id: 1, filename: 'order.pdf', mime_type: 'application/pdf', preview_kind: 'pdf' },
email: null,
});
await pendingStale;
expect(review.intakeParseContext.value).toBeNull();
});
it('load fast path drops the stale intake context when the target Case changes', async () => {
// 关键断言:稳定工作台直达 load 换 Case(重解析落位/重试等入口)同样撤销旧上下文。
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await review.ensureIntakeParseContextLoaded('CASE-1');
expect(review.intakeParseContext.value?.case_no).toBe('CASE-1');
api.getCase.mockResolvedValue(buildCase({ case_no: 'CASE-2', document: { id: 2, file_name: 'second.pdf' } }));
await review.load('RUN-1', 'CASE-2');
expect(review.activeCase.value?.case_no).toBe('CASE-2');
expect(review.intakeParseContext.value).toBeNull();
expect(review.intakeParseLoading.value).toBe(false);
});
it('discards stale selectCase responses when switching PDFs quickly', async () => {
// 关键断言:A 后发先至不得覆盖后选的 B;切换时先清空瞬态。
let resolveA: ((value: ShippingOrderReviewCase) => void) | null = null;
@@ -993,10 +993,13 @@ export function useShippingOrderReview(options: {
/**
* 仅在用户打开接收解析工作面时按需读取当前 Case 的附件与邮件正文。
* Case/代次双校验避免迟到响应把旧附件或 EML 写回当前工作面;失败保持空上下文。
* 选法 2(正式下游)下 activeCase 刻意为 null,此时以 requestedCaseNo 校验目标,
* 与 ensurePreviewLoaded 的兜底口径一致;否则回看已完成接收解析阶段会静默跳过加载。
*/
const ensureIntakeParseContextLoaded = async (caseNo: string): Promise<boolean> => {
const target = String(caseNo || '').trim();
if (!target || activeCase.value?.case_no !== target) {
const expectedCaseNo = String(requestedCaseNo.value || activeCase.value?.case_no || '').trim();
if (!target || target !== expectedCaseNo) {
++intakeParseRequestGeneration;
intakeParseContext.value = null;
intakeParseLoading.value = false;
@@ -1014,7 +1017,7 @@ export function useShippingOrderReview(options: {
if (
requestGeneration !== intakeParseRequestGeneration
|| generation !== caseLoadGeneration
|| activeCase.value?.case_no !== target
|| String(requestedCaseNo.value || activeCase.value?.case_no || '').trim() !== target
) return false;
intakeParseContext.value = context;
return true;
@@ -1022,7 +1025,7 @@ export function useShippingOrderReview(options: {
if (
requestGeneration === intakeParseRequestGeneration
&& generation === caseLoadGeneration
&& activeCase.value?.case_no === target
&& String(requestedCaseNo.value || activeCase.value?.case_no || '').trim() === target
) {
intakeParseContext.value = null;
intakeParseLoadFailed.value = true;
@@ -1032,7 +1035,7 @@ export function useShippingOrderReview(options: {
if (
requestGeneration === intakeParseRequestGeneration
&& generation === caseLoadGeneration
&& activeCase.value?.case_no === target
&& String(requestedCaseNo.value || activeCase.value?.case_no || '').trim() === target
) {
intakeParseLoading.value = false;
}
@@ -1096,6 +1099,13 @@ export function useShippingOrderReview(options: {
// 已有稳定工作台且路由明确目标 PDF 时,目标详情是用户切换的关键路径;
// Run/Queue 只负责后续更新导航和阶段摘要,不能用其慢投影阻塞当前文件显示。
if (hasStableWorkbench && preferredCaseNo) {
// 稳定工作台直达 load 换 Case 时(如重解析落位/重试),同样必须撤销旧文件的
// 接收解析上下文;新上下文由视图层 Case 变化 watcher 按目标 Case 重载。
if (String(preferredCaseNo || '').trim() !== String(activeCase.value?.case_no || '').trim()) {
intakeParseContext.value = null;
intakeParseLoading.value = false;
intakeParseLoadFailed.value = false;
}
const [caseSnapshot, caseEvidence] = await Promise.all([
getWorkspaceShippingOrderReviewCase(preferredCaseNo),
getWorkspaceShippingOrderReviewEvidence(preferredCaseNo),
@@ -1176,8 +1186,11 @@ export function useShippingOrderReview(options: {
statusMessage.value = null;
}
} finally {
if (generation !== caseLoadGeneration) return;
// [2026-09-17] initialLoading 仅由 isInitialLoad 的本 load 置位,必须无条件收尾:
// 被 loadReviewCase 等懒加载路径接管代际时,代际守卫之后的清旗会被跳过,
// 首屏永久卡在「正在加载复核结果...」。
if (isInitialLoad) initialLoading.value = false;
if (generation !== caseLoadGeneration) return;
runLoading.value = false;
// 跨 Run 的 beginCrossRunSwitch 会提前打开 caseSwitchLoading;整页 load 收尾必须关掉。
caseSwitchLoading.value = false;
@@ -1189,6 +1202,8 @@ export function useShippingOrderReview(options: {
* 核心逻辑:保留 activeCase/工作台壳(避免大骨架闪动),但清空 user_task_no,
* 让 shippingProcessingProjection 立即丢弃上一份 PDF 的右卡/库存态;目标 Case
* 仍由随后的 load(preferredCaseNo) 目标优先路径写入。
* 接收解析上下文必须与预览一并撤销:Run 变更即 Case 变更,旧文件的附件名/邮件正文
* 不得残留在新文件工作面(新上下文由视图层 Case 变化 watcher 重载)。
* @param caseNo - 目标复核 Case 编号
*/
const beginCrossRunSwitch = (caseNo: string) => {
@@ -1212,6 +1227,9 @@ export function useShippingOrderReview(options: {
};
}
clearPreview();
intakeParseContext.value = null;
intakeParseLoading.value = false;
intakeParseLoadFailed.value = false;
};
/**
@@ -108,6 +108,46 @@ describe('normalizeShippingProcessingProjection', () => {
expect(normalized?.stageNodes?.[1]?.absoluteIndex).toBe(2);
});
it('preserves explainability message and next_action on blocking_reason', () => {
// v4 阻塞原因具体化:冻结 explainability 契约透传的 message / next_action
// 是「阻塞原因行」与「下一步建议动作」的数据源,归一化不得剥离。
const normalized = normalizeShippingProcessingProjection({
work_item_no: 'OT-REASON',
work_item_type: 'order_task',
status: 'waiting_human',
stage: 'order_review',
ui_state: {
status: 'waiting_human',
stage: 'order_review',
blocking_reason: {
code: 'customer_unresolved',
message: '客户尚未确认',
next_action: 'confirm_customer',
},
primary_action: null,
secondary_actions: [],
},
source_summary: {
email_subject: null,
filename: 'reason.pdf',
document_id: 91,
document_count: 1,
parsed_document_count: 1,
candidate_count: 1,
customer_name: null,
po_number: null,
failure_reason_code: null,
parse_attempt_count: 0,
asset_status: 'ready',
},
child_order_tasks: [],
});
const reason = normalized?.uiState?.blocking_reason;
expect(reason?.code).toBe('customer_unresolved');
expect(reason?.message).toBe('客户尚未确认');
expect(reason?.nextAction).toBe('confirm_customer');
});
it('normalizes the EML status-partition file count', () => {
const normalized = normalizeShippingProcessingProjection({
work_item_no: 'INTAKE:SNI-EML',
@@ -108,12 +108,16 @@ function normalizeStageNode(raw: unknown): ShippingProcessingStageNode | null {
/**
* [T9 用户态 Projection] 规范 blocking_reason(后端 snake_case {code, i18n_key, details})。
* v4:保留冻结 explainability 契约透传的 message(中文兜底文案)与
* next_action(下一步建议动作码,camel/snake 兼容),供「阻塞原因行」与
* 「下一步」槽位消费;禁止剥离,否则 UI 退化为通用状态文案。
*/
function normalizeBlockingReason(raw: unknown): ShippingProcessingBlockingReason | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const code = String(item.code ?? '').trim();
if (!code) return null;
const nextAction = item.next_action ?? item.nextAction;
return {
code,
i18nKey: item.i18n_key != null ? String(item.i18n_key) : null,
@@ -121,6 +125,8 @@ function normalizeBlockingReason(raw: unknown): ShippingProcessingBlockingReason
typeof item.details === 'object' && item.details != null
? (item.details as Record<string, unknown>)
: {},
message: item.message != null ? String(item.message) : null,
nextAction: nextAction != null ? String(nextAction) : null,
};
}
@@ -6,7 +6,9 @@
import { describe, expect, it } from 'vitest';
import {
extractExtractionProgressReasonCode,
isGenericBlockingReason,
isRedundantExtractionDetail,
resolveBlockingReasonText,
resolveExtractionActivityMessage,
resolveRunLifecycleUserStatus,
resolveShippingProcessingReasonLabel,
@@ -175,3 +177,38 @@ describe('extraction lifecycle display (v2 状态展示统一)', () => {
expect(isRedundantExtractionDetail('', 'waiting_human')).toBe(false);
});
});
describe('blocking reason text resolution (v4 阻塞原因具体化)', () => {
// 仅登记通用兜底与一个 Gate 命名空间码,验证解析链与隐藏判定
const REASON_TEXT: Record<string, string> = {
'chat.shippingProcessing.reasonCode.unknown': '当前步骤需要人工处理',
'workspace.shippingNotice.processGate.reasons.customer_unresolved': '客户尚未确认',
};
const te = (key: string) => key in REASON_TEXT;
const t = (key: string) => REASON_TEXT[key] ?? key;
it('resolveBlockingReasonText:Gate 命名空间可解析的原因码返回具体文案', () => {
expect(resolveBlockingReasonText({ code: 'customer_unresolved' }, te, t)).toBe('客户尚未确认');
});
it('resolveBlockingReasonText:命名空间未命中时回退契约透传 message', () => {
// 关键断言:后端 explainability.message 是 i18n 之后的最后兜底,不是首选
expect(resolveBlockingReasonText({
code: 'budget_stopped',
message: '订单识别预算已用尽,请检查文档后进入复核',
}, te, t)).toBe('订单识别预算已用尽,请检查文档后进入复核');
});
it('resolveBlockingReasonText:通用兜底返回空串,调用方据此隐藏原因行', () => {
expect(resolveBlockingReasonText({ code: 'internal_gate_reason' }, te, t)).toBe('');
expect(resolveBlockingReasonText(null, te, t)).toBe('');
expect(resolveBlockingReasonText(undefined, te, t)).toBe('');
});
it('isGenericBlockingReason:Gate 命名空间可解析即非通用;仅未知码为通用', () => {
// 关键断言:i18n 命名空间可解析(四语言齐备)才算具体原因
expect(isGenericBlockingReason({ code: 'customer_unresolved' }, te)).toBe(false);
expect(isGenericBlockingReason({ code: 'internal_gate_reason' }, te)).toBe(true);
expect(isGenericBlockingReason(null, te)).toBe(true);
});
});
@@ -87,6 +87,44 @@ export function resolveShippingProcessingReasonLabel(
return te(unknownKey) ? t(unknownKey) : '当前步骤需要人工处理';
}
/** Gate 原因码的多命名空间查找键(与 resolveGateReasonLabel 保持同源顺序)。 */
function gateReasonNamespaceKeys(code: string): string[] {
return [
`chat.shippingProcessing.gateReasons.${code}`,
`workspace.shippingNotice.workflowReasons.${code}`,
`workspace.shippingNotice.processGate.reasons.${code}`,
];
}
/**
* 解析批次中心行内「阻塞原因」文案;通用兜底返回空串(调用方隐藏原因行)。
* 核心逻辑:i18n_key → reasonCode 专用键 → Gate 三命名空间 → 契约透传 message;
* 与 isGenericBlockingReason 同一判据,保证「隐藏的」与「展示的」口径一致。
*/
export function resolveBlockingReasonText(
reason: {
code?: string | null;
i18nKey?: string | null;
i18n_key?: string | null;
message?: string | null;
} | null | undefined,
te: (key: string) => boolean,
t: (key: string) => string,
): string {
if (isGenericBlockingReason(reason, te)) return '';
const i18nKey = String(reason?.i18nKey || reason?.i18n_key || '').trim();
if (i18nKey && te(i18nKey)) return t(i18nKey);
const code = String(reason?.code || '').trim();
if (code) {
const reasonCodeKey = `chat.shippingProcessing.reasonCode.${code}`;
if (te(reasonCodeKey)) return t(reasonCodeKey);
for (const key of gateReasonNamespaceKeys(code)) {
if (te(key)) return t(key);
}
}
return String(reason?.message || '').trim();
}
/**
* 解析统一处理文案。
*
@@ -197,22 +235,33 @@ export function resolveShippingLifecycleStageLabel(
/**
* 判定阻塞原因是否为「通用兜底」(应在行内隐藏,避免与状态芯片重复)。
*
* 三方约定:仅当下发到具体、非兜底的阻塞原因(有真实 i18n 文案)才展示原因行;
* 进到 reasonCode.unknown / 无 i18n_key 的通用码一律视为重复信息。
* 三方约定:仅当下发到具体、非兜底的阻塞原因才展示原因行。具体判据:
* i18n_key 命中、reasonCode 专用键命中、Gate 三命名空间任一命中
* (四语言齐备),或契约透传了具体 message(无命名空间时的最后兜底)。
* 进到 unknown / 全部未命中的一律视为重复信息。
*
* @param reason - 后端 blocking_reason(code / i18n_key)
* @param reason - 后端 blocking_reason(code / i18n_key / message)
* @param te - i18n te
* @returns true=通用兜底(应隐藏)
*/
export function isGenericBlockingReason(
reason: { code?: string | null; i18nKey?: string | null; i18n_key?: string | null } | null | undefined,
reason: {
code?: string | null;
i18nKey?: string | null;
i18n_key?: string | null;
message?: string | null;
} | null | undefined,
te: (key: string) => boolean,
): boolean {
if (!reason) return true;
const i18nKey = String(reason.i18nKey || reason.i18n_key || '').trim();
if (i18nKey && te(i18nKey)) return false;
const code = String(reason.code || '').trim();
if (code && code !== 'unknown' && te(`chat.shippingProcessing.reasonCode.${code}`)) return false;
if (code && code !== 'unknown') {
if (te(`chat.shippingProcessing.reasonCode.${code}`)) return false;
if (gateReasonNamespaceKeys(code).some((key) => te(key))) return false;
}
if (String(reason.message || '').trim()) return false;
return true;
}
@@ -0,0 +1,24 @@
/**
* features/chat/shipping/shippingWorkbenchLayout.spec.ts
* 用途:锁定货代会话主区域显隐规则(有会话即全屏批次进度中心,方案 A)。
* 依赖:Vitest、纯函数。
* 逻辑:判定必须同时满足货代智能体与非空会话 ID;普通智能体与新会话一律回落欢迎页。
*/
import { describe, expect, it } from 'vitest';
import { shouldShowShippingWorkbench } from './shippingWorkbenchLayout';
describe('shouldShowShippingWorkbench', () => {
it('renders the workbench for the shipping agent once a conversation exists', () => {
expect(shouldShowShippingWorkbench({ isShippingNoticeAgent: true, conversationId: 'conv-1' })).toBe(true);
});
it('keeps the welcome composer before a conversation is created', () => {
expect(shouldShowShippingWorkbench({ isShippingNoticeAgent: true, conversationId: '' })).toBe(false);
expect(shouldShowShippingWorkbench({ isShippingNoticeAgent: true, conversationId: null })).toBe(false);
});
it('never switches other agents to the workbench', () => {
expect(shouldShowShippingWorkbench({ isShippingNoticeAgent: false, conversationId: 'conv-1' })).toBe(false);
});
});
@@ -0,0 +1,21 @@
/**
* features/chat/shipping/shippingWorkbenchLayout.ts
* 用途:货代发货会话主区域显隐判定(批次进度中心优先,方案 A)。
* 依赖:无(纯函数)。
* 逻辑:货代智能体且存在非空会话 ID 时全屏渲染批次进度中心;
* 否则(新会话欢迎页)显示欢迎页 + 输入框(唯一附件提交入口)。
*/
export interface ShippingWorkbenchLayoutInput {
isShippingNoticeAgent: boolean;
conversationId: string | null | undefined;
}
/**
* 判定是否以批次进度中心作为会话主区域。
* @param input - 智能体身份与当前会话 ID(路由 query 与 page 回填同源优先级)。
* @returns true 表示全屏渲染批次进度中心;false 表示欢迎页 + 输入框。
*/
export function shouldShowShippingWorkbench(input: ShippingWorkbenchLayoutInput): boolean {
return Boolean(input.isShippingNoticeAgent && String(input.conversationId || '').trim());
}
@@ -250,6 +250,31 @@ describe('useChatShippingSendHandler', () => {
expect(ctx.msg.warning).toHaveBeenCalledWith('run create failed');
});
it('blocks order extraction when notice attachments exceed chat snapshot limit', async () => {
const many = Array.from({ length: 201 }, (_, i) => ({
id: `notice-${i}`,
kind: 'shipping_notice' as const,
type: 'document' as const,
uploadStatus: 'uploaded' as const,
parseStatus: 'parsed' as const,
uploadProgress: 100,
originalFilename: `orders-${i}.eml`,
fileSize: 100,
intakeNo: `SNI-${i}`,
}));
const startOrderExtractionRun = vi.fn(async () => true);
const ctx = createContext({
attachments: ref(many),
getParsedIntakeNos: () => many.map((item) => item.intakeNo),
startOrderExtractionRun,
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const handled = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(handled).toBe(true);
expect(startOrderExtractionRun).not.toHaveBeenCalled();
expect(ctx.msg.warning).toHaveBeenCalled();
});
it('warns and consumes send when user tries batch task switching (co8 batch API retired)', async () => {
const ctx = createContext({
});
@@ -15,7 +15,7 @@ import {
import { resolveShippingDecisionFromText, resolveShippingNumericChoice } from './shippingMenu';
import { isShippingSpreadsheetFile, isTemporaryInventoryDeclaration } from './shippingUploadPrompt';
import { extractExt } from '../constants/shipping';
import { createChatMessageAttachmentSnapshots } from '../utils/attachmentCard.utils';
import { CHAT_USER_ATTACHMENT_LIMIT, createChatMessageAttachmentSnapshots } from '../utils/attachmentCard.utils';
import type { SendMessageLifecycleHooks } from '../composables/useChat';
import type { ChatMessageSendResult, StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
@@ -101,6 +101,15 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
return true;
};
/**
* 拦截发货通知附件自动流程(订单抽取、本地表格/邮件入队)。
*
* 核心逻辑:已解析 Intake 走 startOrderExtractionRun;快照数超 CHAT_USER_ATTACHMENT_LIMIT 时 warning 并消费发送。
* @param textOrEvent - 发送触发源(按钮或文本)
* @param _content - 原始输入(保留供后续分支)
* @param trimmed - 去空白后的用户正文
* @returns 已消费本次发送时为 true
*/
const tryHandleShippingAttachmentAutoFlow = async (
textOrEvent: string | Event | undefined,
_content: string,
@@ -132,6 +141,10 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
&& submittedIntakes.has(item.intakeNo.trim().toUpperCase()),
),
);
if (userAttachments.length > CHAT_USER_ATTACHMENT_LIMIT) {
ctx.msg.warning(ctx.t('chat.attachmentsUi.limitReached', { limit: CHAT_USER_ATTACHMENT_LIMIT }));
return true;
}
// 空备注不伪造用户正文;订单抽取动作由结构化 Run 提交承载,用户消息只保留附件快照。
const query = trimmed;
ctx.shippingAutoFlowRequested.value = false;
@@ -2,7 +2,8 @@
* features/chat/shipping/useShippingOrderExtractionRuns.spec.ts
* 用途:验证订单抽取 Run 的状态映射、单状态卡消息持久化与轮询生命周期。
* 依赖:Vitest、Vue refs、shipping.api mock、useShippingOrderExtractionRuns。
* 逻辑:覆盖新建/追加提交不生成重复反馈气泡、状态契约、无变化轮询及恢复隔离。
* 逻辑:覆盖新建/追加提交不生成重复反馈气泡、状态契约、无变化轮询及恢复隔离;
* 另覆盖 startRun 期间 isOrderExtractionSubmitting 的 true→false(含失败 finally)。
*/
import { computed, ref } from 'vue';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -136,6 +137,52 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
harness.runs.stopPolling();
});
it('sets isOrderExtractionSubmitting true during startRun and false after success', async () => {
const submissionGate = deferred<{
decision: string;
user_task_no: string;
run_no: string;
created_new: boolean;
operation_id: string;
}>();
api.createSubmission.mockReturnValue(submissionGate.promise);
api.getRun.mockResolvedValue(run({
run_no: 'SNER-SUBMIT',
conversation_id: 'conv-submit',
user_task_no: 'OT-SUBMIT',
}));
const harness = createHarness();
const pending = harness.runs.startRun('提交中', ['SNI-1'], [], 'batch-submit');
// 断言:请求尚未返回时必须处于提交中,驱动发送钮 loading。
expect(harness.runs.isOrderExtractionSubmitting.value).toBe(true);
submissionGate.resolve({
decision: 'created',
user_task_no: 'OT-SUBMIT',
run_no: 'SNER-SUBMIT',
created_new: true,
operation_id: 'op-submit',
});
await pending;
// 断言:成功结束后清除 submitting;用户气泡仅在成功路径出现。
expect(harness.runs.isOrderExtractionSubmitting.value).toBe(false);
expect(harness.messages.value.some((item) => item.role === 'user')).toBe(true);
harness.runs.stopPolling();
});
it('clears isOrderExtractionSubmitting in finally when startRun fails', async () => {
api.createSubmission.mockRejectedValue(new Error('submit failed'));
const harness = createHarness();
await expect(harness.runs.startRun('失败', ['SNI-1'], [])).rejects.toThrow('submit failed');
// 断言:失败路径不得残留 submitting,且不得插入用户气泡。
expect(harness.runs.isOrderExtractionSubmitting.value).toBe(false);
expect(harness.messages.value).toHaveLength(0);
});
it('keeps the submitted Run card independent from sibling Runs in the same upload batch', async () => {
const first = Object.assign(run({
run_no: 'SNER-BATCH-1',
@@ -9,7 +9,7 @@
* 持久化去重签名必须包含 handling_items / primary_notice,避免处理说明变化后历史会话仍读到旧卡。
* 会话恢复锚定 submission primary(client_submission_id)或已有进度卡,禁止 sibling Run 再写第二张卡。
*/
import { getCurrentInstance, onBeforeUnmount, type ComputedRef, type Ref } from 'vue';
import { getCurrentInstance, onBeforeUnmount, ref, type ComputedRef, type Ref } from 'vue';
import {
cancelWorkspaceShippingOrderExtractionDocument,
cancelWorkspaceShippingOrderExtractionRun,
@@ -221,6 +221,8 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
/** 输入区短生命周期上下文;切会话时轮换,同会话多次发送可命中追加优先级第 1 档。 */
let composerContextId = createComposerContextId();
let composerBoundConversationId = String(options.conversationId.value || '').trim();
/** 统一提交进行中:驱动发送钮 loading,并禁止重复点击;成功后才 push 用户气泡。 */
const isOrderExtractionSubmitting = ref(false);
/**
* 确保 composer_context_id 绑定当前会话;会话变化时轮换。
@@ -462,6 +464,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
/**
* 启动订单抽取统一提交:后端裁决 append/create,并只持久化用户操作与唯一 Run 状态卡。
* 核心逻辑:进入时置 submitting,API 成功后再 push 用户气泡与进度卡;finally 清 submitting(含失败)。
* @param query - 用户本次备注;为空时用户消息仅展示附件,不伪造默认正文。
* @param intakeNos - 本次冻结的 Intake 编号。
* @param attachments - 用户消息中的安全附件快照。
@@ -475,57 +478,62 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
uploadBatchId?: string,
): Promise<boolean> => {
stopPolling();
const submissionId = createShippingSubmissionId();
const composerContext = ensureComposerContext();
const focusedUserTaskNo = String(options.getFocusedUserTaskNo?.() || '').trim() || null;
const submission = await createWorkspaceOrderExtractionSubmission({
agent_id: options.currentAgentId.value,
conversation_id: options.conversationId.value || '',
intake_nos: intakeNos,
submission_id: submissionId,
upload_batch_id: uploadBatchId || undefined,
composer_context_id: composerContext,
focused_user_task_no: focusedUserTaskNo,
});
// 统一提交只返回决策摘要;再拉 Run 投影供状态卡与轮询。
const submittedRun = await getWorkspaceShippingOrderExtractionRun(submission.run_no);
const run = await loadDisplayRun(submittedRun);
if (!options.conversationId.value) {
options.conversationId.value = run.conversation_id;
composerBoundConversationId = run.conversation_id;
isOrderExtractionSubmitting.value = true;
try {
const submissionId = createShippingSubmissionId();
const composerContext = ensureComposerContext();
const focusedUserTaskNo = String(options.getFocusedUserTaskNo?.() || '').trim() || null;
const submission = await createWorkspaceOrderExtractionSubmission({
agent_id: options.currentAgentId.value,
conversation_id: options.conversationId.value || '',
intake_nos: intakeNos,
submission_id: submissionId,
upload_batch_id: uploadBatchId || undefined,
composer_context_id: composerContext,
focused_user_task_no: focusedUserTaskNo,
});
// 统一提交只返回决策摘要;再拉 Run 投影供状态卡与轮询。
const submittedRun = await getWorkspaceShippingOrderExtractionRun(submission.run_no);
const run = await loadDisplayRun(submittedRun);
if (!options.conversationId.value) {
options.conversationId.value = run.conversation_id;
composerBoundConversationId = run.conversation_id;
}
const userMessage: ChatMessage = {
role: 'user',
type: 'text',
content: query,
attachments,
local_id: options.newLocalMessageId('shipping-order-extraction-user'),
local_only: true,
payload: {
formId: `shipping-order-extraction-user:${run.run_no}`,
order_extraction_run_no: run.run_no,
user_task_no: submission.user_task_no,
submission_decision: submission.decision,
},
};
options.messages.value.push(userMessage);
await options.saveLocalMessageToBackend(userMessage, query || undefined);
// 新建任务自动聚焦;追加则保持/回写当前 OT。
options.setFocusedUserTaskNo?.(submission.user_task_no || null);
await upsertRunMessage(run);
await acknowledgeTerminalRunWhenVisible(run);
await options.onConversationResolved(run.conversation_id);
options.onWorkflowRefresh?.();
if (ACTIVE_RUN_STATUSES.has(run.status)) {
beginPolling(submittedRun.run_no, 1000);
} else {
const reviewAttachments = await refreshTerminalFacts(run);
await upsertRunMessage(run, reviewAttachments);
}
return true;
} finally {
isOrderExtractionSubmitting.value = false;
}
const userMessage: ChatMessage = {
role: 'user',
type: 'text',
content: query,
attachments,
local_id: options.newLocalMessageId('shipping-order-extraction-user'),
local_only: true,
payload: {
formId: `shipping-order-extraction-user:${run.run_no}`,
order_extraction_run_no: run.run_no,
user_task_no: submission.user_task_no,
submission_decision: submission.decision,
},
};
options.messages.value.push(userMessage);
await options.saveLocalMessageToBackend(userMessage, query || undefined);
// 新建任务自动聚焦;追加则保持/回写当前 OT。
options.setFocusedUserTaskNo?.(submission.user_task_no || null);
await upsertRunMessage(run);
await acknowledgeTerminalRunWhenVisible(run);
await options.onConversationResolved(run.conversation_id);
options.onWorkflowRefresh?.();
if (ACTIVE_RUN_STATUSES.has(run.status)) {
beginPolling(submittedRun.run_no, 1000);
} else {
const reviewAttachments = await refreshTerminalFacts(run);
await upsertRunMessage(run, reviewAttachments);
}
return true;
};
/** 复用原 Run 的冻结附件重新识别,并恢复同一状态卡的轮询。 */
@@ -803,5 +811,6 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
clearActiveRun,
updateCandidateReviewSnapshot,
getActiveRunNo: () => activeRunNo,
isOrderExtractionSubmitting,
};
}
@@ -167,6 +167,11 @@ export interface ShippingProcessingBlockingReason {
code: string;
i18nKey?: string | null;
details?: Record<string, unknown>;
/** 建单前资格快照回退透传(冻结 explainability 契约):中文兜底文案,前端优先 i18n。 */
message?: string | null;
/** 契约注册的下一步动作码(processGate.actionCodes.*),camel/snake 兼容读取。 */
nextAction?: string | null;
next_action?: string | null;
}
/**
* 用户态统一 Projection 主动作(T8 决策 F2;后端对象 {code, i18n_key, parameters})。
@@ -955,7 +960,8 @@ export interface ShippingRpaRuntime {
}
export interface ShippingCurrentStepProgress {
step_key?: string;
/** 15 阶契约阶段码(CheckPoint 时代 stepN_* 遗留键已清除)。 */
stage?: string;
step_title?: string;
status?: 'running' | 'completed' | 'needs_human' | 'pending' | string;
message?: string;
@@ -1498,6 +1504,15 @@ export interface ShippingTaskUiState {
}>;
/** 人工覆写库存源(方案 3·放开):全部已启用源,供行级下拉人工指定。 */
source_options?: Array<{ source_code?: string | null; display_name?: string | null }>;
/**
* 整单 ODM 裁决摘要:conflict=true 表示范围限定后仍有多行存在多值,
* 由行内 odm 下发候选,用户改任一行后同一快照文件的其他行同步。
*/
odm_options?: {
conflict?: boolean;
customer_odm_ids?: Array<string>;
whitelist_applied?: boolean;
};
/** 阶段能力(Task 2 下发);prep 工作台能力工具条消费,scope=task 级。 */
capabilities?: ShippingStageCapability[];
/** 仅当前任务活动关联的库存快照才可下载。 */
@@ -1523,6 +1538,10 @@ export interface ShippingTaskUiState {
/** 多文件冲突行(D5):候选源列表供行内下拉,选定后走 override_line_inventory_source。 */
source_ambiguous?: boolean;
source_candidates?: Array<string>;
/** 整单 ODM 裁决:本行候选(经客户范围过滤);同快照文件行同步同一 chosen 值。 */
odm_values?: Array<string>;
chosen_odm_id?: string | null;
odm_conflict?: boolean;
}>;
artifact?: { file_name?: string | null; status?: string | null } | null;
} | null;
@@ -2307,6 +2326,8 @@ export interface ShippingOrderReviewCaseSummary {
intake_parse_authorized?: boolean;
draft_version?: number | null;
issue_count: number;
/** 队列后端按当前门禁裁决:blocked_manual/blocked_retryable/failed_terminal 为 true;前端禁止自行推断阻塞。 */
needs_attention?: boolean;
available_actions: string[];
/** 仅 parse_failed 时由后端下发,供当前阶段卡调用原 Intake retry API。 */
intake_no?: string | null;
@@ -8,6 +8,9 @@ import type { ChatMessageAttachment } from '../types/chat.types';
import type { AttachmentUiStatus, PendingAttachment } from '../types/shipping.types';
import { isShippingNoticeAttachmentParseIncomplete } from '../shipping/shippingNoticeAttachmentIntegrity';
/** 与后端 CHAT_USER_ATTACHMENT_LIMIT 对齐;超过则发送前拦截,禁止静默截断。 */
export const CHAT_USER_ATTACHMENT_LIMIT = 200;
export interface AttachmentCardStatus {
state: AttachmentUiStatus;
labelKey: string;
@@ -993,6 +993,47 @@ describe('ShippingOrderReviewView layout phase 1', () => {
}
});
it('reloads the intake parse context by requested Case when activeCase is unloaded (formal downstream)', async () => {
// 用户场景:正式下游文件(货代上传 · 已创建任务)切进后 activeCase 为 null(选法 2),
// 此时回看「接收解析」已完成阶段,上下文必须按 requestedCaseNo 发起请求;
// 静默跳过会让 ReviewIntakeParsePanel 以空 context 渲染成整块空白。
const originalQueue = reviewQueue.value;
const originalActiveCase = activeCase.value;
const originalRequested = requestedCaseNo.value;
try {
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0],
has_formal_ot: true,
lifecycle_stage: 'freight_upload',
lifecycle_entries: [
{ code: 'intake_parse', state: 'available' },
{ code: 'order_review', state: 'available' },
{ code: 'fulfillment_prep', state: 'available' },
{ code: 'freight_upload', state: 'current' },
],
}],
};
activeCase.value = null;
requestedCaseNo.value = 'CASE-1';
const wrapper = await mountView({ lifecycle_stage: 'freight_upload' });
ensureIntakeParseContextLoaded.mockClear();
await (wrapper.vm as any).selectLifecycleStage('intake_parse');
await flushPromises();
expect((wrapper.vm as { $route: { query: Record<string, string> } }).$route.query.lifecycle_stage)
.toBe('intake_parse');
// 关键断言:activeCase 为 null 时不得跳过上下文加载,且以目标 Case 请求。
expect(ensureIntakeParseContextLoaded).toHaveBeenCalledWith('CASE-1');
} finally {
reviewQueue.value = originalQueue;
activeCase.value = originalActiveCase;
requestedCaseNo.value = originalRequested;
}
});
it('stops the pending reparse navigation when the user selects another PDF', async () => {
const originalQueue = reviewQueue.value;
try {
@@ -12,12 +12,14 @@
逻辑:建单前订单检查为主卡;正式 OT 后保持 standard,不自动切 formal_task 空壳;
当前 Case 的明确恢复动作优先右栏 CurrentProcessingCard,
不回落至底栏;库存动作仅明细行浮层;表单保存校验仅底栏;
STP waiting_to_start/queued/running 时 automating=true 且后端剥离 edit_draft;
货代上传确认成功后须 refreshReviewQueue,左侧本批阶段与五阶段对齐。
-->
<script setup lang="ts">
import { computed, defineAsyncComponent, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import type { Component } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Bot, Check, ChevronDown, Crosshair, Download, MoreHorizontal, Plus, RefreshCw, Undo2, Copy, Trash2 } from 'lucide-vue-next';
import { Bot, Check, ChevronDown, Crosshair, Download, MoreHorizontal, Pencil, Plus, RefreshCw, Undo2, Copy, Trash2, X } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
@@ -36,7 +38,9 @@ import {
retryWorkspaceShippingOrderStpAutoCreate,
retryShippingNoticeIntake,
decideWorkspaceShippingOrderReviewLineFulfillment,
updateWorkspaceShippingNoticeLine,
waveWorkspaceShippingOrderReviewLineFulfillment,
setWorkspaceShippingTaskOdmChoice,
viewWorkspaceShippingOrderReviewHighlightDiagnostic,
} from '../api/shipping.api';
import type {
@@ -324,7 +328,9 @@ const lifecycleUiState = computed(() => {
};
}
// [STEP 3] 建单前:Run/Queue 项仍由后端下发生命周期入口。
const currentCaseNo = String(activeCase.value?.case_no || '').trim();
// 选法 2(正式下游回看)下 activeCase 刻意为 null,此时以切换管线的 requestedCaseNo
// 定位队列项,否则 entries 永远为空、阶段导航整体退化为 blocked。
const currentCaseNo = String(activeCase.value?.case_no || requestedCaseNo.value || '').trim();
const reviewEntry = (reviewQueue.value?.items || reviewRun.value?.items || []).find(
(item) => String(item.case_no || '').trim() === currentCaseNo,
);
@@ -397,6 +403,13 @@ const intakeParseContextAuthorized = computed(() => {
|| lifecycleEntryIsEnterable(entry)
);
});
/**
* 接收解析工作面的目标 Case:选法 2(正式下游回看)下 activeCase 刻意为 null,
* 必须以切换管线的 requestedCaseNo 兜底,否则上下文加载会被静默跳过(面板空白)。
*/
const intakeTargetCaseNo = computed(() => (
String(activeCase.value?.case_no || requestedCaseNo.value || '').trim()
));
const lifecycleStageItems = computed<ReviewLifecycleStageItem[]>(() => {
const blocker = lifecycleUiState.value.blocker;
const entries = lifecycleUiState.value.entries;
@@ -482,8 +495,8 @@ async function retryCurrentIntakeParse(): Promise<void> {
await Promise.all([
reloadLatestDraft(),
refreshShippingProcessing(),
activeCase.value?.case_no
? ensureIntakeParseContextLoaded(activeCase.value.case_no)
intakeTargetCaseNo.value
? ensureIntakeParseContextLoaded(intakeTargetCaseNo.value)
: Promise.resolve(false),
]);
} catch (error) {
@@ -574,8 +587,8 @@ async function selectLifecycleStage(code: ReviewLifecycleStageCode, options: { r
pendingReleaseAutoAdvanceCaseNo.value = null;
}
}
if (code === 'intake_parse' && intakeParseContextAuthorized.value && activeCase.value?.case_no) {
void ensureIntakeParseContextLoaded(activeCase.value.case_no);
if (code === 'intake_parse' && intakeParseContextAuthorized.value && intakeTargetCaseNo.value) {
void ensureIntakeParseContextLoaded(intakeTargetCaseNo.value);
}
const mode: ReviewWorkbenchMode = code === 'order_review' || code === 'intake_parse'
? 'standard'
@@ -1352,6 +1365,9 @@ onMounted(() => {
document.addEventListener('keydown', onExceptionNavKeydown, true);
// [PERF] 深链进入时尽早并行发起任务详情,与 load() 重叠,削减首屏串行加载。
prefetchDeepLinkedTaskDetail();
// OT 直链(无 case_no)下 confirmedNoticeTaskNo 恒空、watch(hasFormalOt) 永不触发;
// 挂载即消费深链预取(复用同一请求,不重复拉取),任务详情才能落地驱动五阶段页签。
if (deepLinkOrderTaskNo.value) void loadFormalTaskDetail();
});
onBeforeUnmount(() => {
@@ -1916,7 +1932,8 @@ async function handleCurrentTaskAction(
break;
case 'open_inventory_match_review':
if (hasFormalOt.value) {
scrollWorkbenchAnchor('review-order-lines-table');
// 正式 OT 后匹配/缺口语境的真实宿主是通知准备工作区;订单明细表不承载库存结果。
scrollWorkbenchAnchor('review-fulfillment-prep-workspace');
} else {
workbenchMode.value = 'inventory';
scrollWorkbenchAnchor('review-inventory-issue-list');
@@ -2163,11 +2180,11 @@ const customerResolutionWideRef = ref<{ openSelectDialog: () => Promise<void> }
const fieldConflictPanelRef = ref<{ focusFirstConflict: () => void } | null>(null);
const duplicatePanelRef = ref<{ focusAdjudication: () => void } | null>(null);
/** 系统自动推进中:仅当存在确认 Job 时隐藏主写按钮;资格达标不算 automating。 */
/** 系统自动推进中:STP 等待入队/排队/执行时隐藏主写按钮。 */
const isProcessingAutomating = computed(() => {
// STP 建单前没有正式 OT 投影;已入队/运行时由 Case automation 作为唯一运行事实。
// STP 建单前没有正式 OT 投影;等待入队与已入队/运行均由 Case automation 作为唯一运行事实。
const stpStatus = String(activeCase.value?.automation?.status || '').trim().toLowerCase();
if (!hasFormalOt.value && ['queued', 'running'].includes(stpStatus)) return true;
if (!hasFormalOt.value && ['waiting_to_start', 'queued', 'running'].includes(stpStatus)) return true;
if (!hasConfirmedAutomationJob.value) return false;
const status = String(
shippingProcessingProjection.value?.uiState?.status
@@ -2419,6 +2436,15 @@ const confirmedNoticeTaskNo = computed(() => String(
|| '',
).trim());
/**
* 深链显式携带的 OT 号(任务中心抽屉等 OT 直链)。
* 仅认 OT- 前缀;Notice 的 SN 号不是 work-item 键,与 externalOrderTaskNo 同一口径。
*/
const deepLinkOrderTaskNo = computed(() => {
const taskNo = String(route.query.task_no || '').trim();
return taskNo.startsWith('OT-') ? taskNo : '';
});
const freightNoticeGroups = ref<ShippingFreightNoticeGroup[]>([]);
const freightNoticeGroupsLoading = ref(false);
const freightNoticeGroupsReason = ref<string | null>(null);
@@ -2580,9 +2606,8 @@ function formalPreparationLineSource(line: {
/** 锁定边界 = Excel 生成(D7):后端 preparation.source_locked 下发,生成后行源只读。 */
const formalPreparationSourceLocked = computed(() => Boolean(formalPreparationContext.value?.source_locked));
/** 多文件冲突行的行内选源暂存(line_no → 选定 source_code),提交后由后端映射快照行并重匹配。 */
const lineSourceSelections = ref<Record<string, string>>({});
const lineSourceBusy = ref(false);
/** 库存源选择不再有独立确认流:行进入就地编辑态后在下拉中改选,随行级「保存」统一提交
* (override_line_inventory_source Gate 动作,见 saveInlineEdit);展示态回退为文本。 */
/** 选源下拉项文案:源编码始终可见(等宽语义由样式层保证)。 */
function lineSourceOptionLabel(code: string): string {
@@ -2590,55 +2615,43 @@ function lineSourceOptionLabel(code: string): string {
return String(code || '').trim().toUpperCase();
}
/**
* 提交歧义行选定源:走正式 Gate 动作 override_line_inventory_source(方案 3·放开,唯一选源入口),
* 后端校验启用/Excel 锁并仅重匹配该行;成功后清空行内暂存并刷新任务详情。
*/
async function submitLineSourceSelection(line: { snapshot_line_id?: number | null; line_no?: string | number | null }) {
const selectionKey = String(line.snapshot_line_id ?? '');
const sourceCode = String(lineSourceSelections.value[selectionKey] || '').trim();
const lineNo = Number(line.line_no);
if (!sourceCode || !Number.isInteger(lineNo) || lineNo < 1 || lineSourceBusy.value) return;
lineSourceBusy.value = true;
try {
await submitFormalGateAction('override_line_inventory_source', {
line_no: lineNo,
source_code: sourceCode,
});
delete lineSourceSelections.value[selectionKey];
} finally {
lineSourceBusy.value = false;
}
}
/** 人工覆写库存源(方案 3·放开):后端下发全部已启用源 source_options,供行级下拉人工指定。 */
const formSourceOptions = computed(() => formalPreparationContext.value?.source_options || []);
const overrideSourceSelections = ref<Record<string, string>>({});
const overrideSourceBusy = ref(false);
function overrideSourceOptionLabel(code: string): string {
// 兜底:下拉只展示源编码(如 DSV360_AWSSG),不展示冗长 display_name,便于快速识别。
return String(code || '').trim().toUpperCase();
}
/** 整单 ODM 裁决列可见性:任一行候选多于一个时展示(候选已经客户范围过滤)。 */
const formalPreparationOdmColumnVisible = computed(() =>
(formalPreparationContext.value?.lines || []).some((line) => (line.odm_values?.length || 0) > 1),
);
const lineOdmSelections = ref<Record<string, string>>({});
const lineOdmBusy = ref(false);
/**
* 提交人工覆写行库存源:走正式 Gate 动作 override_line_inventory_source(方案 3·放开),
* 后端校验源启用/Excel 锁并仅重匹配该行;成功后清空暂存并刷新任务详情。
* 提交行级 ODM 选择:后端把同一快照文件的全部当前匹配行同步为同一值,
* 刷新详情后其他行回显同步结果,并在门禁仍授权时自动重试生成 Excel。
*/
async function submitOverrideSource(line: { snapshot_line_id?: number | null; line_no?: string | number | null }) {
async function submitLineOdmChoice(line: { snapshot_line_id?: number | null }) {
const selectionKey = String(line.snapshot_line_id ?? '');
const sourceCode = String(overrideSourceSelections.value[selectionKey] || '').trim();
const lineNo = Number(line.line_no);
if (!sourceCode || !Number.isInteger(lineNo) || lineNo < 1 || overrideSourceBusy.value) return;
overrideSourceBusy.value = true;
const odmId = String(lineOdmSelections.value[selectionKey] || '').trim();
const taskNo = String(confirmedNoticeTaskNo.value || '').trim();
if (!odmId || !taskNo || lineOdmBusy.value) return;
lineOdmBusy.value = true;
try {
await submitFormalGateAction('override_line_inventory_source', {
line_no: lineNo,
source_code: sourceCode,
});
delete overrideSourceSelections.value[selectionKey];
await setWorkspaceShippingTaskOdmChoice(taskNo, { snapshot_line_id: selectionKey, odm_id: odmId });
delete lineOdmSelections.value[selectionKey];
await loadFormalTaskDetail();
const canRegenerate = formalTaskActions.value.some(
(action) => action.enabled && String(action.code || '').trim() === 'regenerate_excel_artifact',
);
if (canRegenerate) await submitFormalGateAction('regenerate_excel_artifact');
} catch (error) {
msg.error(resolveReviewErrorMessage(error));
} finally {
overrideSourceBusy.value = false;
lineOdmBusy.value = false;
}
}
@@ -2706,7 +2719,7 @@ async function confirmReleaseInventoryShortage() {
const caseNo = activeCase.value?.case_no;
const reason = releaseInventoryReason.value.trim();
const requiredFields = line?.release_required_fields || [];
if (!line || !caseNo || !reason || requiredFields.some((field) => !releaseInventoryFieldValues.value[field.field_id]?.trim()) || releaseInventoryBusy.value) return;
if (!line || !caseNo || requiredFields.some((field) => !releaseInventoryFieldValues.value[field.field_id]?.trim()) || releaseInventoryBusy.value) return;
releaseInventoryBusy.value = true;
try {
await decideWorkspaceShippingOrderReviewLineFulfillment(caseNo, {
@@ -2733,6 +2746,170 @@ function formalPreparationLineInventoryFileNo(line: { snapshot_line_id?: number
return String(line.inventory_file_no || fulfillment?.inventory_file_no || '').trim();
}
/** 行内放行补录条(常显子行):短缺行携带必填放行字段时直接在行下补填,替代弹窗。 */
const releaseBarValues = ref<Record<string, Record<string, string>>>({});
const releaseBarBusy = ref<Record<string, boolean>>({});
function releaseBarKey(line: { snapshot_line_id?: number | null }): string {
return String(line.snapshot_line_id ?? '');
}
/** 放行必填字段:仅短缺行且投影声明了必填补录项(有候选缺失才需要补录)。 */
function releaseBarLineRequiredFields(line: { snapshot_line_id?: number | null }) {
const fulfillment = formalPreparationLineFulfillment(line);
return fulfillment?.release_required_fields || [];
}
/**
* 缺失徽标文案:前缀 + 数量 + 后缀(纯文本键拼接)。
* 【注】不用 vue-i18n 命名插值 `{n}`——11.4.7 对该实例深层键+插值组合存在解析异常
* (te=false、t 回原始 key,已用 vitest 分层断言复现,见 src/i18n.spec.ts)。
*/
function releaseMissingBadgeLabel(line: { snapshot_line_id?: number | null }): string {
const n = releaseBarLineRequiredFields(line).length;
return `${t('chat.shippingOrderReview.releaseBar.missingPrefix')}${n}${t('chat.shippingOrderReview.releaseBar.missingSuffix')}`;
}
/** 缺字段型短缺行:放行走行内补录(而非仅原因的旧弹窗路径)。 */
function releaseBarHasFields(line: {
snapshot_line_id?: number | null;
shortage_qty?: string | number | null;
}): boolean {
return Number(line.shortage_qty || 0) > 0 && releaseBarLineRequiredFields(line).length > 0;
}
/** 补录条展开态:默认收起(表格保持干净),由 ⋯ 菜单「放行缺口」或缺 N 项徽标点击展开。 */
const releaseBarExpandedFor = ref<string | null>(null);
function expandReleaseBar(line: { snapshot_line_id?: number | null }) {
if (inlineEditBusy.value) {
msg.warning(t('chat.shippingOrderReview.inlineEdit.busy'));
return;
}
releaseBarExpandedFor.value = releaseBarKey(line);
}
function releaseBarValue(
line: { snapshot_line_id?: number | null },
field: { field_id?: string | null },
): string {
return releaseBarValues.value[releaseBarKey(line)]?.[String(field.field_id)] ?? '';
}
function updateReleaseBarValue(
line: { snapshot_line_id?: number | null },
field: { field_id?: string | null },
value: string,
) {
const key = releaseBarKey(line);
releaseBarValues.value = {
...releaseBarValues.value,
[key]: { ...(releaseBarValues.value[key] || {}), [String(field.field_id)]: value },
};
}
/** 放行按钮可用性:后端授权 + 必填补录项全部已填 + 非保存中。 */
function releaseBarReadyFor(line: { snapshot_line_id?: number | null }): boolean {
const fulfillment = formalPreparationLineFulfillment(line);
const required = releaseBarLineRequiredFields(line);
return Boolean(
fulfillment?.line_allowed_actions?.includes('release_inventory_shortage')
&& required.every((field) => releaseBarValue(line, field).trim())
&& !releaseBarBusy.value[releaseBarKey(line)],
);
}
/** 行内放行提交:走既有 decide 通道;原因可选(人工放行事实由审计链记录)。 */
async function confirmReleaseBar(line: { snapshot_line_id?: number | null }) {
const caseNo = activeCase.value?.case_no;
const fulfillment = formalPreparationLineFulfillment(line);
const key = releaseBarKey(line);
const required = releaseBarLineRequiredFields(line);
if (
!caseNo || !fulfillment?.draft_line_id
|| !required.every((field) => releaseBarValue(line, field).trim())
|| releaseBarBusy.value[key]
) return;
releaseBarBusy.value = { ...releaseBarBusy.value, [key]: true };
try {
await decideWorkspaceShippingOrderReviewLineFulfillment(caseNo, {
draft_line_id: String(fulfillment.draft_line_id || ''),
decision_code: 'release_inventory_shortage',
reason: '',
release_field_values: { ...(releaseBarValues.value[key] || {}) },
expected_draft_version: activeCase.value?.draft?.draft_version,
});
const next = { ...releaseBarValues.value };
delete next[key];
releaseBarValues.value = next;
// 放行写入成功即结束用户交互;Notice/Excel 由后端 Job 异步创建(与原弹窗通道一致)。
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
} finally {
releaseBarBusy.value = { ...releaseBarBusy.value, [key]: false };
}
}
/** 行结案弹窗状态;与放行缺口弹窗同款交互(原因必填),走 line-fulfillment decide 通道。 */
const closeLineDialogLine = ref<ShippingOrderReviewLineFulfillmentLine | null>(null);
const closeLineReason = ref('');
const closeLineBusy = ref(false);
/**
* 结案按钮可见性:仅「无货可发」的未终态 prep 行开放。
* 核心逻辑:line_allowed_actions 由后端投影下发(终态行返回空数组,天然排除已结案/
* 已放行/已入波次行),前端再叠加短缺信号(is_shortage / 缺量>0 / not_found)过滤;
* 后端 decide API 才是权威闸门,这里只做入口收敛。
*/
function formalPreparationLineCloseVisible(line: { snapshot_line_id?: number | null; shortage_qty?: string | number | null }): boolean {
if (!formalPreparationLineAllows(line, 'close_unfulfillable')) return false;
const fulfillment = formalPreparationLineFulfillment(line);
if (fulfillment?.decision?.decision_code === 'close_unfulfillable') return false;
const notFound = String(fulfillment?.match_result || '').trim().toLowerCase() === 'not_found';
const shortageQty = Number(line.shortage_qty ?? fulfillment?.shortage_qty ?? 0) > 0;
return Boolean(fulfillment?.is_shortage) || shortageQty || notFound;
}
/**
* 打开行结案弹窗:按快照行身份定位履约投影行(携带 draft_line_id)。
* 核心逻辑:与行内编辑互斥——弹窗打开即取消该行编辑态,避免两套写路径叠加。
*/
function openCloseLineDialog(line: { snapshot_line_id?: number | null }) {
const fulfillment = formalPreparationLineFulfillment(line);
if (!fulfillment) return;
cancelInlineEdit();
closeLineDialogLine.value = fulfillment;
closeLineReason.value = '';
}
/**
* 提交行结案决定(decision_code='close_unfulfillable',原因必填)。
* 核心逻辑:复用既有 line-fulfillment decide API;成功后走恢复协调刷新三投影,
* prep 表即时反映已结案状态(后端拒绝无效流转时以 BusinessError 文案提示)。
*/
async function confirmCloseLine() {
const line = closeLineDialogLine.value;
const caseNo = activeCase.value?.case_no;
const reason = closeLineReason.value.trim();
if (!line || !caseNo || !reason || closeLineBusy.value) return;
closeLineBusy.value = true;
try {
await decideWorkspaceShippingOrderReviewLineFulfillment(caseNo, {
draft_line_id: String(line.draft_line_id || ''),
decision_code: 'close_unfulfillable',
reason,
expected_draft_version: activeCase.value?.draft?.draft_version,
});
closeLineDialogLine.value = null;
handleGateRecoveryAccepted();
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
} finally {
closeLineBusy.value = false;
}
}
/** 下载行级实际匹配快照,禁止退回到任务级 active link。 */
async function downloadFormalPreparationLineInventoryFile(line: {
snapshot_line_id?: number | null;
@@ -2757,6 +2934,257 @@ async function retryFormalPreparationLine(
await submitFormalGateAction(actionCode, { snapshot_line_id: Number(snapshotLineId) });
}
/**
* 库存 RPA 是否运行中(就地编辑的 busy 禁用条件)。
* 核心逻辑:后端 preparation 摘要当前未下发 inventory_rpa_is_running(仅内部计算),
* 故先消费可选下发字段(后端补发即生效),缺失时以 status==='processing'
* (尚无匹配结果且无门禁 → 首轮抓取进行中)兜底;重匹配期间的写冲突由
* 后端 SHIPPING.EDIT_WINDOW_SYSTEM_BUSY 守卫兜底。
*/
const inlineEditBusy = computed(() => {
const preparation = formalTaskDetail.value?.ui_state?.stage_context?.preparation;
if (!preparation) return false;
const running = (preparation as { inventory_rpa_is_running?: unknown }).inventory_rpa_is_running;
if (typeof running === 'boolean') return running;
return preparation.status === 'processing';
});
/** 就地编辑状态:仅一行处于编辑态;保存走既有 update-notice-line 通道(免证据人工修订)。
* 编辑入口 = 行级「编辑」按钮(防单元格误触);编辑态下更多操作列替换为保存/取消。 */
const editingLine = ref<{
snapshot_line_id: number;
line_no: number;
part_number: string;
reservation_id: string;
required_qty: string;
source_code: string;
} | null>(null);
const inlineEditSaving = ref(false);
/**
* 就地编辑草稿种子值:把展示占位「—」还原为空串,避免占位符被当作真实值提交。
* @param value - prep 行展示值(可能为 null / '—' / 数字)
* @returns 可直接进入输入框的字符串
*/
function inlineEditSeedValue(value: unknown): string {
const text = String(value ?? '').trim();
return text === '—' ? '' : text;
}
/**
* 进入单个准备行的就地编辑(料号 / 预约号 / 需求数量三个值列)。
* @param line - prep 展示行;snapshot_line_id 定位编辑行,line_no-1 与后端 line_index 0 基对齐
*/
function startInlineEdit(line: {
snapshot_line_id?: number | null;
line_no?: string | number | null;
part_number?: string | null;
reservation_id?: string | null;
required_qty?: string | number | null;
selected_source_code?: string | null;
source_code?: string | null;
}) {
if (!line.snapshot_line_id || inlineEditSaving.value) return;
// 库存 RPA 运行中禁止改值:匹配进行中修改会与重匹配竞态。
if (inlineEditBusy.value) {
msg.warning(t('chat.shippingOrderReview.inlineEdit.busy'));
return;
}
editingLine.value = {
snapshot_line_id: Number(line.snapshot_line_id),
line_no: Number(line.line_no || 0),
part_number: inlineEditSeedValue(line.part_number),
reservation_id: inlineEditSeedValue(line.reservation_id),
required_qty: inlineEditSeedValue(line.required_qty),
source_code: inlineEditSeedValue(line.selected_source_code || line.source_code),
};
}
/** 行是否处于就地编辑态(统一 Number 收敛,避免模板严格等于的类型漂移)。 */
function isInlineEditing(line: { snapshot_line_id?: number | null }): boolean {
return editingLine.value?.snapshot_line_id === Number(line.snapshot_line_id);
}
/**
* 编辑态库存源下拉选项:多文件冲突行优先取候选源,其余行取全部已启用源;
* 无可用项返回空——此时编辑态库存源保持文本展示(无可选即不可改)。
*/
function inlineSourceOptions(line: {
source_ambiguous?: boolean;
source_candidates?: Array<string>;
}): Array<{ value: string; label: string }> {
if (line.source_ambiguous && (line.source_candidates?.length || 0) > 0) {
return (line.source_candidates || []).map((code) => ({ value: String(code), label: lineSourceOptionLabel(String(code)) }));
}
if (formSourceOptions.value.length) {
return formSourceOptions.value.map((s) => ({ value: String(s.source_code), label: overrideSourceOptionLabel(String(s.source_code)) }));
}
return [];
}
/** 同步编辑态库存源草稿(与三个值列一致:改动仅在保存时提交)。 */
function updateInlineEditSource(value: string) {
if (editingLine.value) editingLine.value.source_code = value;
}
/** 行级动作收纳菜单(⋯)打开状态:键 = snapshot_line_id,单行互斥;坐标视口固定定位,
* Teleport 到 body——表格祖先容器 overflow-auto 会裁剪 absolute 浮层并转为滚动高度。 */
const overflowMenuOpenFor = ref<string | null>(null);
const overflowMenuPos = ref<{ top: number; left: number }>({ top: 0, left: 0 });
function toggleOverflowMenu(key: string, event?: MouseEvent) {
if (overflowMenuOpenFor.value === key) {
overflowMenuOpenFor.value = null;
return;
}
const rect = (event?.currentTarget as HTMLElement | undefined)?.getBoundingClientRect();
const menuWidth = 176;
overflowMenuPos.value = {
top: rect ? Math.min(rect.bottom + 4, window.innerHeight - 8) : 0,
left: rect ? Math.max(8, Math.min(rect.right - menuWidth, window.innerWidth - menuWidth - 8)) : 0,
};
overflowMenuOpenFor.value = key;
}
/**
* 行级收纳菜单项:低频/诊断类动作入口(守卫条件与原常显按钮完全一致),
* 高频的「编辑」保持常显;无可用项时 ⋯ 整体不渲染。
*/
function overflowItems(line: {
snapshot_line_id?: number | null;
shortage_qty?: string | number | null;
}): Array<{ key: string; icon: Component; labelKey: string; run: () => void | Promise<void> }> {
const items: Array<{ key: string; icon: Component; labelKey: string; run: () => void | Promise<void> }> = [];
if (formalPreparationLineAllows(line, 'retry_inventory_matching')) {
items.push({
key: 'retry_inventory_matching',
icon: RefreshCw,
labelKey: inventoryActionLabelKey('retry_inventory_matching')!,
run: () => retryFormalPreparationLine(Number(line.snapshot_line_id), 'retry_inventory_matching'),
});
}
// 放行缺口:缺字段型短缺行 → 行内展开补录条(替代弹窗);仅缺原因的行 → 旧弹窗(原因已可选)。
if (formalPreparationLineAllows(line, 'release_inventory_shortage')) {
items.push({
key: 'release_inventory_shortage',
icon: Check,
labelKey: inventoryActionLabelKey('release_inventory_shortage')!,
run: () => {
if (releaseBarHasFields(line)) expandReleaseBar(line);
else openReleaseInventoryShortage(line);
},
});
}
if (formalPreparationLineCloseVisible(line)) {
items.push({
key: 'close_unfulfillable',
icon: X,
labelKey: 'chat.shippingOrderReview.lineActions.closeLine',
run: () => openCloseLineDialog(line),
});
}
if (formalPreparationLineAllows(line, 'retry_inventory_preparation')) {
items.push({
key: 'retry_inventory_preparation',
icon: Bot,
labelKey: inventoryActionLabelKey('retry_inventory_preparation')!,
run: () => retryFormalPreparationLine(Number(line.snapshot_line_id), 'retry_inventory_preparation'),
});
}
if (formalPreparationLineInventoryFileNo(line)) {
items.push({
key: 'download_inventory_file',
icon: Download,
labelKey: inventoryActionLabelKey('download_inventory_file') || 'chat.shippingOrderReview.lifecycle.prepare.downloadInventory',
run: () => downloadFormalPreparationLineInventoryFile(line),
});
}
return items;
}
/** 同步需求数量输入:数字输入框经 @input 手动回写,避免 v-model 的隐式 number 转型。 */
function updateInlineEditQty(value: string) {
if (editingLine.value) editingLine.value.required_qty = value;
}
/** 退出就地编辑并丢弃未保存修改。 */
function cancelInlineEdit() {
editingLine.value = null;
}
/**
* 保存就地编辑:仅提交有变化且非空的字段(part_number / reservation_id / qty),
* 成功后提示「请点击重新匹配库存」并刷新任务详情(值列即刻显示新值,重匹配仍需手动触发)。
* @param line - 当前编辑行,用于与编辑起始值比对计算差量补丁
*/
async function saveInlineEdit(line: {
snapshot_line_id?: number | null;
part_number?: string | null;
reservation_id?: string | null;
required_qty?: string | number | null;
selected_source_code?: string | null;
source_code?: string | null;
}) {
const draft = editingLine.value;
if (!draft || !draft.snapshot_line_id || inlineEditSaving.value) return;
// 编辑态行与触发行的快照身份不一致(如刷新后错位)时直接丢弃,禁止错行提交。
if (draft.snapshot_line_id !== Number(line.snapshot_line_id)) {
cancelInlineEdit();
return;
}
const taskNo = String(formalTaskDetail.value?.task_no || '').trim();
const lineIndex = Number(draft.line_no) - 1;
if (!taskNo || !Number.isInteger(lineIndex) || lineIndex < 0) {
cancelInlineEdit();
return;
}
const patch: Record<string, string> = {};
const nextPartNumber = draft.part_number.trim();
if (nextPartNumber !== inlineEditSeedValue(line.part_number)) patch.part_number = nextPartNumber;
const nextReservationId = draft.reservation_id.trim();
if (nextReservationId !== inlineEditSeedValue(line.reservation_id)) patch.reservation_id = nextReservationId;
const nextQty = draft.required_qty.trim();
if (nextQty !== inlineEditSeedValue(line.required_qty) && nextQty) patch.qty = nextQty;
// 库存源草稿与进入编辑时的种子值比对:变化即随保存提交行级源覆写。
const seedSourceCode = inlineEditSeedValue(line.selected_source_code || line.source_code);
const nextSourceCode = draft.source_code.trim();
const sourceChanged = Boolean(nextSourceCode) && nextSourceCode !== seedSourceCode;
if (!Object.keys(patch).length && !sourceChanged) {
cancelInlineEdit();
return;
}
inlineEditSaving.value = true;
try {
// 字段值先落库(update-notice-line);随后的源覆写会触发单行重匹配,读到的是修正后的字段值。
if (Object.keys(patch).length) {
await updateWorkspaceShippingNoticeLine(
taskNo,
lineIndex,
patch,
undefined,
// 免证据人工修订(后端 Task 2 已放宽 evidence/reason);乐观锁版本缺失时
// 退回后端初值 1,冲突由后端 ORDER_DATA_VERSION_MISMATCH 的 409 语义兜底。
{ expectedOrderDataVersion: Number(formalTaskDetail.value?.order_data_version ?? 1) },
);
}
// 库存源覆写沿用既有 Gate 动作(override_line_inventory_source),后端校验后仅重匹配该行。
if (sourceChanged) {
await submitFormalGateAction('override_line_inventory_source', {
line_no: draft.line_no,
source_code: nextSourceCode,
});
}
cancelInlineEdit();
msg.success(t('chat.shippingOrderReview.inlineEdit.saved'));
await loadFormalTaskDetail();
} catch (error) {
// BusinessError.message 即后端业务文案(版本冲突 / 系统处理中),复用既有提示通道。
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
} finally {
inlineEditSaving.value = false;
}
}
/**
* 人工上传登记是后端 Gate 的受控写动作;仅进入「货代上传」工作面不构成授权。
* [§2 单源] 授权从 A(shippingProcessingProjection.ui_state)读 —— §2.5 差异① 已归一,A 的
@@ -2802,7 +3230,12 @@ async function handleManualUploadSuccess() {
* 拉取确认后的 Notice 履约详情,供 Gate Action 与 Artifact 视图使用。
*/
async function loadFormalTaskDetail() {
const taskNo = confirmedNoticeTaskNo.value;
// 深链 OT 兜底:无 case_no 的 OT 直链下选法 2 不拉 Case,activeCase/displayCase
// 均为空、confirmedNoticeTaskNo 恒空;此时必须消费深链 task_no,否则挂载预取的
// 任务详情被丢弃、五阶段页签无身份可裁决(全锁死)。一旦存在任何 Case 上下文
// 则禁止回退,防止深链 OT 串到用户切换后的其他文件。
const taskNo = confirmedNoticeTaskNo.value
|| (displayCase.value ? '' : deepLinkOrderTaskNo.value);
const generation = ++formalTaskDetailGeneration;
if (!taskNo) {
formalTaskDetail.value = null;
@@ -4044,13 +4477,10 @@ const closeAuxiliaryPanelsForCaseSwitch = () => {
llmSuggestionOpen: false,
versionHistoryOpen: false,
};
// [NO-OPTIMISTIC MEMORY] 行级选源/覆写是「点保存才生效」的实提交,未保存的暂存选择
// 不得跨文件/切换残留(否则会把上一文件的未保存意图带进新行)。切换即清空暂存,
// 行回到后端 selected_source_code / source_code,用户须重新选择并点保存。
lineSourceSelections.value = {};
lineSourceBusy.value = false;
overrideSourceSelections.value = {};
overrideSourceBusy.value = false;
// [NO-OPTIMISTIC MEMORY] 行级就地编辑是「点保存才生效」的实提交,未保存的编辑草稿
// 不得跨文件/切换残留(否则会把上一文件的未保存意图带进新行)。切换即丢弃草稿,
// 行回到后端 selected_source_code / source_code,用户须重新进入编辑并保存。
cancelInlineEdit();
};
/**
@@ -4396,7 +4826,14 @@ watch(
);
watch(
[lifecycleActiveStageCode, hasFormalOt, intakeParseContextAuthorized],
[
lifecycleActiveStageCode,
hasFormalOt,
intakeParseContextAuthorized,
// 接收解析文件互切时 stage/授权通常不变;必须以 Case 变化触发新附件/邮件上下文重载,
// 否则接收解析工作面停留上一份 PDF 的附件名且预览不再自动加载。
() => String(activeCase.value?.case_no || '').trim(),
],
([code, , intakeAuthorized]) => {
// 确认进度是当前阶段内的短暂辅助视图,不由生命周期页签覆盖。
if (workbenchMode.value === 'confirm_progress') return;
@@ -4404,8 +4841,8 @@ watch(
// surface 反向成为前端阶段裁决。
if (code === null) return;
syncLifecycleWorkbenchMode(code);
if (code === 'intake_parse' && intakeAuthorized && activeCase.value?.case_no) {
void ensureIntakeParseContextLoaded(activeCase.value.case_no);
if (code === 'intake_parse' && intakeAuthorized && intakeTargetCaseNo.value) {
void ensureIntakeParseContextLoaded(intakeTargetCaseNo.value);
}
},
{ immediate: true },
@@ -4486,10 +4923,20 @@ function retryFormalTaskDetail() {
*/
const REVIEW_EDITOR_NEEDED_STAGES: ReviewLifecycleStageCode[] = ['intake_parse', 'order_review', 'fulfillment_prep'];
watch(
lifecycleCurrentStageCode,
(stage) => {
// 用户查看面(含回看已完成阶段)驱动 Case 懒加载:选法 2 正式下游切 PDF 后 activeCase
// 为 null,回看接收解析/订单复核/通知准备时必须按需补拉目标 Case,否则这些工作面
// 只能渲染空白或残留上一份 PDF 的数据。
// [2026-09-17] 初次装配(initialLoading/runLoading)未完成前必须让位:loadReviewCase
// 会自增 caseLoadGeneration,令在途 load() 的 finally 跳过 initialLoading 清旗,
// 首屏永久卡在「正在加载复核结果...」且 run/queue 永不装配。装配完成后由旗标
// 翻转重新触发本 watcher,按当前 stage 补拉 Case。
[lifecycleActiveStageCode, initialLoading, runLoading],
([stage]) => {
if (initialLoading.value || runLoading.value) return;
if (!stage || !REVIEW_EDITOR_NEEDED_STAGES.includes(stage)) return;
const caseNo = String(displayCase.value?.case_no || '').trim();
// 禁止使用 displayCase 兜底:它可能停留在上一份 PDF 的快照上造成串味;
// 目标一律取当前工作面的 activeCase 或切换管线的 requestedCaseNo。
const caseNo = String(activeCase.value?.case_no || requestedCaseNo.value || '').trim();
if (!caseNo) return;
if (stage === 'fulfillment_prep') {
if (activeCase.value) return;
@@ -4856,12 +5303,12 @@ watch(
class="rounded-full bg-brand-50 px-2.5 py-1 text-xs font-medium text-brand-700 dark:bg-brand-950/30 dark:text-brand-300"
>{{ formalPreparationStatusLabel(formalPreparationContext?.status) }}</span>
</div>
<div v-if="formalPreparationDisplayLines.length" class="review-fulfillment-prep-workspace mt-4 rounded-lg border border-default" data-testid="review-fulfillment-prep-workspace">
<!-- 标题与选行操作条固定不参与横向滚动,仅表头/表体横向滑动。 -->
<div class="flex items-center justify-between gap-3 border-b border-default bg-surface-muted/30 px-3 py-2">
<div class="text-xs font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.prepare.matchWorkspace') }}</div>
<span class="text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineCount', { count: formalPreparationDisplayLines.length }) }}</span>
</div>
<div v-if="formalPreparationDisplayLines.length" class="review-fulfillment-prep-workspace mt-4 rounded-lg border border-default" data-testid="review-fulfillment-prep-workspace">
<!-- 标题与选行操作条固定不参与横向滚动,仅表头/表体横向滑动。 -->
<div class="flex items-center justify-between gap-3 border-b border-default bg-surface-muted/30 px-3 py-2">
<div class="text-xs font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.prepare.matchWorkspace') }}</div>
<span class="text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineCount', { count: formalPreparationDisplayLines.length }) }}</span>
</div>
<div v-if="preparationEditable && formalHeaderEditable()" class="flex flex-wrap items-center justify-between gap-2 border-b border-default bg-brand-50/50 px-3 py-2 text-xs dark:bg-brand-950/20">
<div class="flex items-center gap-3 text-secondary">
<span class="font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.selectReady') }}</span>
@@ -4871,8 +5318,8 @@ watch(
</div>
<div class="overflow-x-auto overscroll-x-contain" data-testid="review-fulfillment-prep-table-scroll">
<table class="review-fulfillment-prep-table min-w-[1060px] text-xs">
<thead class="border-b border-default bg-surface-muted/50 text-left"><tr><th v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="allPreparationWaveSelected" :disabled="!preparationWaveSelectableLines.length || preparationWaveBusy" :aria-label="t('chat.shippingOrderReview.fulfillmentDecision.selectReady')" @change="toggleAllPreparationLineSelection(($event.target as HTMLInputElement).checked)"></th><th v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationCustomerPoLineLabel() }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.inventorySource') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineStatus') }}</th><th class="review-fulfillment-sticky-action-head whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lineOps.moreActions') }}</th></tr></thead>
<tbody><tr v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`" :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary">{{ line.reservation_id || '—' }}</td><td class="max-w-[220px] truncate px-3 py-2" :title="line.part_number || '—'">{{ line.part_number || '—' }}</td><td class="whitespace-nowrap px-3 py-2">{{ line.required_qty ?? '—' }}</td><td class="max-w-[220px] px-3 py-2"><div v-if="line.source_ambiguous && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-source-ambiguous-${line.snapshot_line_id || lineIndex}`" :title="t('chat.shippingOrderReview.lifecycle.prepare.sourceAmbiguous')"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-source-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="lineSourceSelections[String(line.snapshot_line_id || lineIndex)] || line.source_code || ''" @change="lineSourceSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.lifecycle.prepare.selectSource') }}</option><option v-for="code in line.source_candidates || []" :key="code" :value="code">{{ lineSourceOptionLabel(code) }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-source-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineSourceSelections[String(line.snapshot_line_id || lineIndex)] || lineSourceBusy || !preparationEditable" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" @click="submitLineSourceSelection(line)"><Check class="h-3.5 w-3.5" /></button></div><span v-else-if="line.source_ambiguous && formalPreparationSourceLocked" class="text-xs text-secondary" :title="t('chat.shippingOrderReview.lifecycle.prepare.sourceLocked')">{{ t('chat.shippingOrderReview.lifecycle.prepare.sourceLocked') }}</span><span v-else-if="!formalPreparationSourceLocked && formSourceOptions.length" class="flex items-center gap-1" :data-testid="`review-line-source-override-${line.snapshot_line_id || lineIndex}`" :title="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-source-override-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="overrideSourceSelections[String(line.snapshot_line_id || lineIndex)] || line.selected_source_code || line.source_code || ''" @change="overrideSourceSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.lifecycle.prepare.selectSource') }}</option><option v-for="s in formSourceOptions" :key="String(s.source_code)" :value="String(s.source_code)">{{ overrideSourceOptionLabel(String(s.source_code)) }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-source-override-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!overrideSourceSelections[String(line.snapshot_line_id || lineIndex)] || overrideSourceBusy" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :data-line-index="lineIndex" @click="submitOverrideSource(line)"><Check class="h-3.5 w-3.5" /></button></span><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) }}</span></td><td class="whitespace-nowrap px-3 py-2">{{ line.available_qty ?? '—' }}</td><td class="whitespace-nowrap px-3 py-2 font-medium" :class=Line truncated
<thead class="border-b border-default bg-surface-muted/50 text-left"><tr><th v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="allPreparationWaveSelected" :disabled="!preparationWaveSelectableLines.length || preparationWaveBusy" :aria-label="t('chat.shippingOrderReview.fulfillmentDecision.selectReady')" @change="toggleAllPreparationLineSelection(($event.target as HTMLInputElement).checked)"></th><th v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationCustomerPoLineLabel() }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.inventorySource') }}</th><th v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.odmConflict.column') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineStatus') }}</th><th class="review-fulfillment-sticky-action-head whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lineOps.moreActions') }}</th></tr></thead>
<tbody><template v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`"><tr :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.reservation_id" type="text" class="w-28 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultReservation')" :data-testid="`review-fulfillment-line-edit-reservation-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.reservation_id || '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.part_number" type="text" class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultPartNumber')" :data-testid="`review-fulfillment-line-edit-part-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else class="block max-w-[220px] truncate" :title="line.part_number || '—'">{{ line.part_number || '—' }}</span></td><td class="whitespace-nowrap px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input :value="editingLine.required_qty" type="number" min="0" step="any" class="w-20 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.requiredQty')" :data-testid="`review-fulfillment-line-edit-qty-${line.snapshot_line_id}`" @input="updateInlineEditQty(($event.target as HTMLInputElement).value)" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.required_qty ?? '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="isInlineEditing(line) && inlineSourceOptions(line).length"><select class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-fulfillment-line-edit-source-${line.snapshot_line_id}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="editingLine?.source_code" :disabled="inlineEditSaving" @change="updateInlineEditSource(($event.target as HTMLSelectElement).value)"><option v-for="option in inlineSourceOptions(line)" :key="option.value" :value="option.value">{{ option.label }}</option></select></template><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) || '—' }}</span></td><td v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2"><div v-if="(line.odm_values?.length || 0) > 1 && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-odm-${line.snapshot_line_id || lineIndex}`"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-odm-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.odmConflict.title')" :value="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || line.chosen_odm_id || ''" @change="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.odmConflict.placeholder') }}</option><option v-for="value in line.odm_values" :key="value" :value="value">{{ value }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-odm-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || lineOdmBusy" :aria-label="t('chat.shippingOrderReLine truncated
</table>
</div>
</div>
@@ -5078,8 +5525,8 @@ watch(
:load-failed="intakeParseLoadFailed"
:preview-url="previewUrl || null"
:preview-loading="previewLoading"
@retry-context="() => { if (activeCase?.case_no) void ensureIntakeParseContextLoaded(activeCase.case_no); }"
@load-preview="() => { if (activeCase?.case_no) void ensurePreviewLoaded(activeCase.case_no); }"
@retry-context="() => { if (intakeTargetCaseNo) void ensureIntakeParseContextLoaded(intakeTargetCaseNo); }"
@load-preview="() => { if (intakeTargetCaseNo) void ensurePreviewLoaded(intakeTargetCaseNo); }"
/>
<!-- 仅「固定为侧栏」时 PDF 占网格列;默认浮窗挂在根节点,不挤压订单区。 -->
<div
@@ -5651,7 +6098,31 @@ watch(
</label>
<div class="mt-4 flex justify-end gap-2">
<button type="button" class="rounded border border-default px-3 py-1.5 text-sm" :disabled="releaseInventoryBusy" @click="releaseInventoryLine = null">{{ t('chat.shippingOrderReview.workbench.close') }}</button>
<button type="button" class="rounded bg-amber-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50" :disabled="releaseInventoryBusy || !releaseInventoryReason.trim() || (releaseInventoryLine.release_required_fields || []).some((field) => !releaseInventoryFieldValues[field.field_id]?.trim())" @click="confirmReleaseInventoryShortage">{{ t('chat.shippingOrderReview.lifecycle.prepare.releaseConfirm') }}</button>
<button type="button" class="rounded bg-amber-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50" :disabled="releaseInventoryBusy || (releaseInventoryLine.release_required_fields || []).some((field) => !releaseInventoryFieldValues[field.field_id]?.trim())" @click="confirmReleaseInventoryShortage">{{ t('chat.shippingOrderReview.lifecycle.prepare.releaseConfirm') }}</button>
</div>
</div>
</div>
<div
v-if="closeLineDialogLine"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-4"
data-testid="review-close-line-dialog"
@click.self="closeLineDialogLine = null"
>
<div class="w-full max-w-md rounded-xl border border-default bg-surface p-4 shadow-xl">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.lineActions.closeLine') }}</h2>
<p class="mt-1 text-xs text-muted">{{ t('chat.shippingOrderReview.closeFulfillment.subtitle') }}</p>
<textarea
v-model="closeLineReason"
rows="3"
class="mt-3 w-full rounded-md border border-default bg-surface px-2.5 py-2 text-sm"
data-testid="review-close-line-reason"
:placeholder="t('chat.shippingOrderReview.lineActions.closeLineReason')"
:disabled="closeLineBusy"
/>
<div class="mt-4 flex justify-end gap-2">
<button type="button" class="rounded border border-default px-3 py-1.5 text-sm" :disabled="closeLineBusy" @click="closeLineDialogLine = null">{{ t('chat.shippingOrderReview.workbench.close') }}</button>
<button type="button" class="rounded bg-rose-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50" data-testid="review-close-line-submit" :disabled="closeLineBusy || !closeLineReason.trim()" @click="confirmCloseLine">{{ t('chat.shippingOrderReview.lineActions.closeLineConfirm') }}</button>
</div>
</div>
</div>
@@ -21,11 +21,11 @@ export interface ContractPaymentContract {
status: string; parse_status: string; plan_status: string; parse_issues?: string[]; nodes: PaymentNode[]; alerts?: PaymentAlert[]; attachments?: ContractAttachment[];
}
export interface ContractListResponse { total: number; page: number; page_size: number; pages: number; items: ContractPaymentContract[]; }
export type LedgerFocus = 'due' | 'overdue' | 'needs_completion' | 'due_this_month';
export type LedgerFocus = 'due' | 'overdue' | 'active' | 'due_this_month';
export interface LedgerSummary {
due: number;
overdue: number;
needs_completion: number;
active: number;
due_this_month: number;
}
export interface AlertBatch { id: number; batch_no: string; week_key: string; status: string; summary?: { total?: number; stages?: Record<string, number> }; excel_file_name?: string | null; excel_file_size?: number | null; sent_at?: string | null; }
@@ -33,11 +33,11 @@ export interface AlertSummary { pending_count: number; next_send_at?: string | n
/**
* 分页查询合同付款台账或待确认合同。
* 核心逻辑:keyword 同时匹配合同号、流程号、采购单号和供应商;reviewOnly 走待确认列表。
* 核心逻辑:keyword 同时匹配合同号、流程号、采购单号、供应商和申请人;reviewOnly 走待确认列表。
* @param params.keyword - 模糊检索词,可为空。
* @param params.parse_status - 解析状态精确筛选。
* @param params.reviewOnly - 为 true 时只查 needs_review。
* @param params.focus - 汇总卡口径:即将到期 / 逾期未付 / 待补充 / 本月应付。
* @param params.focus - 汇总卡口径:即将到期 / 逾期未付 / 进行中 / 本月应付。
* @returns 分页后的合同列表。
*/
export const listContractPaymentContracts = (params?: { keyword?: string; parse_status?: string; reviewOnly?: boolean; focus?: LedgerFocus; page?: number; pageSize?: number }) => {
@@ -61,7 +61,7 @@ export const getContractPaymentAlertSummary = () => requestJson<AlertSummary>('/
/**
* 查询合同台账四张汇总卡的合同份数。
* 核心逻辑:始终统计全部已解析台账,不跟当前 keyword;与点卡片过滤共用 focus 口径。
* @returns due / overdue / needs_completion / due_this_month。
* @returns due / overdue / active / due_this_month。
*/
export const getContractPaymentLedgerSummary = () => requestJson<LedgerSummary>('/api/contract-payment/contracts/summary');
export const listContractPaymentAlertBatches = () => requestJson<{ items: AlertBatch[] }>('/api/contract-payment/alert-batches');
@@ -0,0 +1,202 @@
<!--
features/contract-payment/components/ContractPaymentChatPanel.vue
用途:合同付款预警 Chat 主区:管理员按钮、三 Tab、当前 Tab 内详情下钻。
依赖:contract-payment 三页与详情、useContractPaymentAdminActions、vue-router query。
逻辑:由 ChatViewContent 在 agent_code=contract_payment 时替换消息列表与输入框;
view / contractId 写入 /chat/:agentId 查询参数,旧工作台地址重定向后仍可深链打开。
-->
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { CalendarClock, RefreshCw, Send } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { listContractPaymentContracts } from '../api/contract-payment.api';
import { useContractPaymentAdminActions } from '../composables/useContractPaymentAdminActions';
import type { ContractPaymentView } from '../constants';
import {
buildContractPaymentChatQuery,
parseContractPaymentChatQuery,
} from '../utils/contractPaymentChat.utils';
import ContractPaymentPage from '../views/ContractPaymentPage.vue';
import ContractPaymentReviewPage from '../views/ContractPaymentReviewPage.vue';
import ContractPaymentWeeklyBatchesPage from '../views/ContractPaymentWeeklyBatchesPage.vue';
import ContractPaymentDetailPage from '../views/ContractPaymentDetailPage.vue';
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const parsedQuery = computed(() => parseContractPaymentChatQuery(route.query.view, route.query.contractId));
const activeView = computed<ContractPaymentView>(() => parsedQuery.value.view);
const detailId = computed(() => parsedQuery.value.contractId);
const reviewCount = ref(0);
const {
isAdmin,
actionLoading,
showForceSyncConfirm,
showReparseExistingConfirm,
run,
confirmForceSync,
confirmReparseExisting,
} = useContractPaymentAdminActions();
const tabs = computed(() => ([
{ key: 'ledger' as const, label: t('admin.contractPayment.ledger') },
{ key: 'review' as const, label: t('admin.contractPaymentReview.title'), count: reviewCount.value },
{ key: 'batches' as const, label: t('admin.contractPayment.weeklyBatchesTitle') },
]));
/**
* 把当前 Tab / 详情写入 Chat 路由,保持刷新与旧地址重定向可用。
* 核心逻辑:replace 避免 Tab 切换堆积历史;切 Tab 时清掉 contractId。
*/
async function syncQuery(view: ContractPaymentView, contractId: number | null): Promise<void> {
const nextQuery = buildContractPaymentChatQuery(view, contractId);
const currentView = String(route.query.view || '');
const currentContractId = String(route.query.contractId || '');
if (currentView === nextQuery.view && currentContractId === (nextQuery.contractId || '')) return;
const query = { ...route.query, ...nextQuery };
if (!contractId) delete query.contractId;
await router.replace({ params: { ...route.params }, query });
}
/**
* 切换主 Tab;详情下钻随 Tab 关闭,避免第四个隐形页。
*/
function selectView(view: ContractPaymentView): void {
void syncQuery(view, null);
}
/**
* 在当前 Tab 内打开合同详情。
*/
function openDetail(contractId: number): void {
void syncQuery(activeView.value, contractId);
}
/**
* 从详情返回当前 Tab 列表。
*/
function closeDetail(): void {
void syncQuery(activeView.value, null);
}
/**
* 读取待确认合同数量,供 Tab 角标展示。
* 核心逻辑:只取 total,不拉列表正文,失败时角标归零不打断主区。
*/
async function loadReviewCount(): Promise<void> {
try {
const result = await listContractPaymentContracts({
reviewOnly: true,
page: 1,
pageSize: 1,
});
reviewCount.value = result.total || 0;
} catch {
reviewCount.value = 0;
}
}
onMounted(() => {
void loadReviewCount();
});
watch(
() => route.query.view,
(rawView) => {
if (rawView) return;
void syncQuery(activeView.value, detailId.value);
},
{ immediate: true },
);
</script>
<template>
<section class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-[var(--surface-muted,#f4f7fb)]">
<div class="flex flex-wrap items-start justify-between gap-3 px-5 pt-5">
<div class="min-w-0">
<h1 class="text-xl font-bold text-primary">{{ t('admin.contractPayment.title') }}</h1>
<p class="mt-1 text-sm text-muted">{{ t('admin.contractPayment.subtitle') }}</p>
</div>
<div v-if="isAdmin" class="flex flex-wrap gap-2">
<button class="btn-secondary-ds" type="button" :disabled="actionLoading" @click="run('sync')">
<RefreshCw class="h-4 w-4" />{{ t('admin.contractPayment.sync') }}
</button>
<button class="btn-secondary-ds" type="button" :disabled="actionLoading" @click="run('force-sync')">
<RefreshCw class="h-4 w-4" />{{ t('admin.contractPayment.forceSync') }}
</button>
<button class="btn-secondary-ds" type="button" :disabled="actionLoading" @click="run('reparse-existing')">
<RefreshCw class="h-4 w-4" />{{ t('admin.contractPayment.reparseExisting') }}
</button>
<button class="btn-secondary-ds" type="button" :disabled="actionLoading" @click="run('scan')">
<CalendarClock class="h-4 w-4" />{{ t('admin.contractPayment.scanAlerts') }}
</button>
<button class="btn-primary" type="button" :disabled="actionLoading" @click="run('weekly')">
<Send class="h-4 w-4" />{{ t('admin.contractPayment.weeklySend') }}
</button>
</div>
</div>
<div class="mt-4 flex gap-0 border-b border-default px-5">
<button
v-for="tab in tabs"
:key="tab.key"
type="button"
class="mb-[-1px] border-b-2 px-4 py-2.5 text-sm font-bold"
:class="activeView === tab.key
? 'border-brand-500 text-brand-600'
: 'border-transparent text-muted hover:text-secondary'"
@click="selectView(tab.key)"
>
{{ tab.label }}
<span
v-if="tab.key === 'review' && tab.count"
class="ml-1 inline-grid h-[18px] min-w-[18px] place-items-center rounded-full bg-amber-50 px-1.5 text-[11px] text-amber-700"
>{{ tab.count }}</span>
</button>
</div>
<div class="min-h-0 flex-1 overflow-auto px-5 py-4">
<ContractPaymentDetailPage
v-if="detailId"
:contract-id="detailId"
embedded
@close="closeDetail"
/>
<ContractPaymentPage
v-else-if="activeView === 'ledger'"
embedded
@open-detail="openDetail"
/>
<ContractPaymentReviewPage
v-else-if="activeView === 'review'"
embedded
@open-detail="openDetail"
/>
<ContractPaymentWeeklyBatchesPage
v-else
embedded
/>
</div>
<DeleteConfirmDialog
v-if="isAdmin"
v-model="showForceSyncConfirm"
:title="t('admin.contractPayment.forceSync')"
:message="t('admin.contractPayment.forceSyncConfirm')"
confirm-tone="primary"
@confirm="confirmForceSync"
/>
<DeleteConfirmDialog
v-if="isAdmin"
v-model="showReparseExistingConfirm"
:title="t('admin.contractPayment.reparseExisting')"
:message="t('admin.contractPayment.reparseExistingConfirm')"
confirm-tone="primary"
@confirm="confirmReparseExisting"
/>
</section>
</template>
@@ -0,0 +1,88 @@
/**
* features/contract-payment/composables/useContractPaymentAdminActions.ts
* 用途:合同付款预警管理员异步任务(同步 / 重解析 / 扫描 / 发送)共用入口。
* 依赖:contract-payment.api、useAuthStore、useMessage、i18n。
* 逻辑:Chat 顶栏与旧台账页共用;非管理员直接忽略,强制覆盖和存量重解析先走确认框。
*/
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import {
enqueueContractPaymentAlertScan,
enqueueContractPaymentReparse,
enqueueContractPaymentSync,
enqueueContractPaymentWeeklyAlert,
} from '../api/contract-payment.api';
export type ContractPaymentAdminAction = 'sync' | 'force-sync' | 'reparse-existing' | 'scan' | 'weekly';
/**
* 提供合同付款预警管理员操作状态与提交函数。
* 核心逻辑:仅 role=admin 可提交;入队成功只提示任务已提交,不阻塞等待 Worker。
* @param onAfterScanOrWeekly - 扫描或发送后刷新本周待发送摘要的回调
*/
export function useContractPaymentAdminActions(onAfterScanOrWeekly?: () => Promise<void> | void) {
const { t } = useI18n();
const auth = useAuthStore();
const msg = useMessage();
const isAdmin = computed(() => auth.isAdmin);
const actionLoading = ref(false);
const showForceSyncConfirm = ref(false);
const showReparseExistingConfirm = ref(false);
/**
* 提交合同付款预警后台任务。
* 核心逻辑:按操作类型调用相应异步接口;扫描和发送成功后刷新摘要。
*/
async function submitAction(action: ContractPaymentAdminAction): Promise<void> {
if (!isAdmin.value) return;
actionLoading.value = true;
try {
if (action === 'sync' || action === 'force-sync') {
await enqueueContractPaymentSync(action === 'force-sync');
} else if (action === 'reparse-existing') {
await enqueueContractPaymentReparse();
} else if (action === 'scan') {
await enqueueContractPaymentAlertScan();
} else {
await enqueueContractPaymentWeeklyAlert();
}
msg.success(t('admin.contractPayment.jobSubmitted'));
if ((action === 'scan' || action === 'weekly') && onAfterScanOrWeekly) {
await onAfterScanOrWeekly();
}
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.contractPayment.actionFailed'));
} finally {
actionLoading.value = false;
}
}
/**
* 触发任务入口;强制覆盖和存量重解析先弹出确认框。
*/
function run(action: ContractPaymentAdminAction): void {
if (!isAdmin.value) return;
if (action === 'force-sync') {
showForceSyncConfirm.value = true;
return;
}
if (action === 'reparse-existing') {
showReparseExistingConfirm.value = true;
return;
}
void submitAction(action);
}
return {
isAdmin,
actionLoading,
showForceSyncConfirm,
showReparseExistingConfirm,
run,
confirmForceSync: () => void submitAction('force-sync'),
confirmReparseExisting: () => void submitAction('reparse-existing'),
};
}
@@ -1,7 +1,9 @@
/**
* features/contract-payment/constants.ts
* 用途:合同付款预警前端权限键与路由 meta 共用常量。
* 用途:合同付款预警 Chat 视图与查询参数常量。
* 依赖:无。
* 逻辑:路由守卫、侧栏与用户管理勾选读取同一键,须与后端 User._role_default_feature_permissions 一致。
* 逻辑:Chat Tab、工作台旧地址重定向与详情下钻共用同一套 view 名。
*/
export const CONTRACT_PAYMENT_ACCESS_PERMISSION = 'contract_payment.access' as const;
export const CONTRACT_PAYMENT_VIEWS = ['ledger', 'review', 'batches'] as const;
export type ContractPaymentView = (typeof CONTRACT_PAYMENT_VIEWS)[number];
@@ -0,0 +1,42 @@
/**
* features/contract-payment/utils/contractPaymentChat.utils.test.ts
* 用途:锁定合同付款预警 Chat 深链 query 的解析与回写规则。
*/
import { describe, expect, it } from 'vitest';
import {
buildContractPaymentChatQuery,
parseContractPaymentChatQuery,
} from './contractPaymentChat.utils';
describe('parseContractPaymentChatQuery', () => {
it('accepts ledger / review / batches and a positive contractId', () => {
expect(parseContractPaymentChatQuery('review', '12')).toEqual({
view: 'review',
contractId: 12,
});
});
it('falls back to ledger for unknown view and ignores invalid contractId', () => {
expect(parseContractPaymentChatQuery('unknown', 'abc')).toEqual({
view: 'ledger',
contractId: null,
});
expect(parseContractPaymentChatQuery(undefined, '0')).toEqual({
view: 'ledger',
contractId: null,
});
});
});
describe('buildContractPaymentChatQuery', () => {
it('always writes view and omits contractId on list pages', () => {
expect(buildContractPaymentChatQuery('batches', null)).toEqual({ view: 'batches' });
});
it('keeps the current tab when drilling into a contract', () => {
expect(buildContractPaymentChatQuery('review', 9)).toEqual({
view: 'review',
contractId: '9',
});
});
});
@@ -0,0 +1,46 @@
/**
* features/contract-payment/utils/contractPaymentChat.utils.ts
* 用途:解析合同付款预警 Chat 的 view / contractId 查询参数。
* 依赖:contract-payment/constants。
* 逻辑:旧工作台重定向与 Chat Tab 共用;非法 view 回退台账。
*/
import { CONTRACT_PAYMENT_VIEWS, type ContractPaymentView } from '../constants';
export interface ContractPaymentChatQuery {
view: ContractPaymentView;
contractId: number | null;
}
/**
* 把路由 query 归一成 Chat 台账视图。
* 核心逻辑:只接受 ledger / review / batches;contractId 必须是正整数才进入详情下钻。
* @param rawView - 路由 query.view
* @param rawContractId - 路由 query.contractId
* @returns 可安全写入 Tab 与详情状态的查询对象
*/
export function parseContractPaymentChatQuery(
rawView: unknown,
rawContractId: unknown,
): ContractPaymentChatQuery {
const view = CONTRACT_PAYMENT_VIEWS.includes(String(rawView) as ContractPaymentView)
? String(rawView) as ContractPaymentView
: 'ledger';
const parsed = Number(rawContractId);
const contractId = Number.isInteger(parsed) && parsed > 0 ? parsed : null;
return { view, contractId };
}
/**
* 把台账视图写回 Chat 路由 query,便于刷新与旧工作台重定向共用同一深链。
* 核心逻辑:始终带 view;仅在下钻详情时带 contractId,避免空 query 污染地址栏。
* @param view - 当前 Tab
* @param contractId - 详情合同 ID;列表态传 null
*/
export function buildContractPaymentChatQuery(
view: ContractPaymentView,
contractId: number | null,
): Record<string, string> {
const query: Record<string, string> = { view };
if (contractId) query.contractId = String(contractId);
return query;
}
@@ -0,0 +1,77 @@
<!--
features/contract-payment/views/ContractPaymentChatRedirect.vue
用途:把旧工作台合同付款预警 URL 转到对应 Chat Agent 深链。
依赖:listUserAgents、isContractPaymentAgent、contractPaymentChat.utils。
逻辑:按路径还原 view / contractId,再在当前用户 Agent 列表中定位 contract_payment;
未授权时提示并回应用管理。本页不渲染业务 UI。
-->
<script setup lang="ts">
import { onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { listUserAgents } from '@/features/auth/api/user.api';
import { useMessage } from '@/shared/composables/useMessage';
import { isContractPaymentAgent } from '@/shared/utils/agent-registry.utils';
import { WORKSPACE_PATHS } from '@/features/workspace/constants/routes';
import type { ContractPaymentView } from '../constants';
import { buildContractPaymentChatQuery } from '../utils/contractPaymentChat.utils';
const route = useRoute();
const router = useRouter();
const { t } = useI18n();
const msg = useMessage();
/**
* 从旧工作台路径还原 Chat Tab 与详情合同。
* 核心逻辑:review / weekly-batches / contracts/:id 分别对应三个 Tab 与台账下钻。
*/
function resolveLegacyTarget(): { view: ContractPaymentView; contractId: number | null } {
const path = String(route.path || '');
if (path.includes('/contract-payment/review')) {
return { view: 'review', contractId: null };
}
if (path.includes('/contract-payment/weekly-batches')) {
return { view: 'batches', contractId: null };
}
const detailMatch = path.match(/\/contract-payment\/contracts\/(\d+)/);
if (detailMatch) {
return { view: 'ledger', contractId: Number(detailMatch[1]) };
}
return { view: 'ledger', contractId: null };
}
/**
* 查找当前用户可用的合同付款预警 Agent 并跳转 Chat。
* 核心逻辑:admin 与已授权用户都能在 /api/agents 看到该 Agent;找不到则视为无权限。
*/
async function redirectToChat(): Promise<void> {
const { view, contractId } = resolveLegacyTarget();
try {
const agents = await listUserAgents();
const agent = Array.isArray(agents) ? agents.find((item) => isContractPaymentAgent(item)) : null;
const agentId = Number(agent?.id);
if (!Number.isInteger(agentId) || agentId <= 0) {
msg.warning(t('errors.codes.CONTRACT_PAYMENT_FORBIDDEN'));
await router.replace(WORKSPACE_PATHS.applications);
return;
}
await router.replace({
path: `/chat/${agentId}`,
query: buildContractPaymentChatQuery(view, contractId),
});
} catch {
msg.warning(t('errors.codes.CONTRACT_PAYMENT_FORBIDDEN'));
await router.replace(WORKSPACE_PATHS.applications);
}
}
onMounted(() => {
void redirectToChat();
});
</script>
<template>
<div class="flex min-h-[40vh] items-center justify-center text-sm text-muted">
{{ t('chat.loadingAgent') }}
</div>
</template>
@@ -1,12 +1,11 @@
<!--
features/contract-payment/views/ContractPaymentDetailPage.vue
用途:展示单份采购合同的概览、原文附件、付款计划及企业微信预警审计。
依赖:contract-payment.api、vue-router、统一消息提示;由合同付款台账的行点击进入。
依赖:contract-payment.api、统一消息提示;由 Chat 台账/待确认行点击在当前 Tab 内下钻。
逻辑:以合同 ID 调用已有详情接口,所有付款任务按付款节点和预警轮次聚合呈现。
-->
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { computed, onMounted, ref, watch } from 'vue';
import { ArrowLeft, CircleHelp, Download, FileText, RefreshCw } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
@@ -20,20 +19,26 @@ import {
type ContractPaymentContract,
type PaymentNode,
} from '../api/contract-payment.api';
import { WORKSPACE_PATHS } from '@/features/workspace/constants/routes';
import { displayCurrency } from '../utils/currency';
import { isNodeNearDue, isNodeOverdue, nodeDueReference } from '../utils/paymentStatus';
const props = withDefaults(defineProps<{
contractId: number;
embedded?: boolean;
}>(), { embedded: false });
const emit = defineEmits<{
close: [];
}>();
const { t, te } = useI18n();
const route = useRoute();
const router = useRouter();
const msg = useMessage();
const contract = ref<ContractPaymentContract | null>(null);
const loading = ref(false);
const downloadingId = ref<number | null>(null);
const reparsing = ref(false);
const activeTab = ref<'plan' | 'attachments' | 'alerts'>('plan');
const contractId = computed(() => Number(route.params.contractId));
const contractId = computed(() => Number(props.contractId));
const orderedNodes = computed(() => {
const order = ['prepayment', 'shipment', 'acceptance', 'warranty'];
return [...(contract.value?.nodes || [])].sort((left, right) => order.indexOf(left.node_type) - order.indexOf(right.node_type));
@@ -189,13 +194,13 @@ function alertsForNode(node: PaymentNode) {
}
/**
* 加载当前路由合同的完整详情。
* 核心逻辑:ID 非法时返回台账;接口失败保留空态并展示统一业务错误。
* 加载当前合同的完整详情。
* 核心逻辑:ID 非法时通知父级关闭下钻;接口失败保留空态并展示统一业务错误。
* @returns 完成后更新详情数据及加载状态。
*/
async function load(): Promise<void> {
if (!Number.isInteger(contractId.value) || contractId.value <= 0) {
await router.replace(WORKSPACE_PATHS.contractPayment);
emit('close');
return;
}
loading.value = true;
@@ -254,14 +259,17 @@ async function reparseContract(): Promise<void> {
}
/**
* 返回合同付款预警台账。
* 核心逻辑:使用路由常量而非浏览器历史,避免从周汇总或外部链接进入详情时返回错误页面。
* @returns 路由跳转完成。
* 返回当前 Tab 的合同列表。
* 核心逻辑:由 Chat 父级清掉 contractId,避免从待确认下钻后误回到台账。
*/
async function backToLedger(): Promise<void> {
await router.push(WORKSPACE_PATHS.contractPayment);
function backToLedger(): void {
emit('close');
}
watch(contractId, () => {
void load();
});
onMounted(() => void load());
</script>
@@ -1,23 +1,17 @@
<!--
合同付款预警工作台:展示汇总卡、合同台账、付款阶段字段、本周待发送摘要;同步/扫描/发送仅管理员可见。
依赖:contract-payment.api、PaginationBar、useAuthStore、统一消息提示;周汇总批次由独立页面展示。
features/contract-payment/views/ContractPaymentPage.vue
用途:合同付款预警台账列表、汇总卡与本周待发送摘要。
依赖:contract-payment.api、PaginationBar、统一消息提示。
逻辑:Chat Tab 以 embedded 嵌入时隐藏页头;点行通过 open-detail 交给父级下钻详情;关键词可搜合同号、流程号、采购单号、供应商和申请人。
-->
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { CalendarClock, RefreshCw, Search, Send } from 'lucide-vue-next';
import { Search } from 'lucide-vue-next';
import { BusinessError } from '@/shared/api/client';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import { useMessage } from '@/shared/composables/useMessage';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import { WORKSPACE_PATHS } from '@/features/workspace/constants/routes';
import {
enqueueContractPaymentAlertScan,
enqueueContractPaymentReparse,
enqueueContractPaymentSync,
enqueueContractPaymentWeeklyAlert,
getContractPaymentAlertSummary,
getContractPaymentLedgerSummary,
listContractPaymentContracts,
@@ -29,22 +23,25 @@ import {
import { displayCurrency } from '../utils/currency';
import { aggregateContractNodeStatus, type ContractNodeStatusCode } from '../utils/paymentStatus';
const props = withDefaults(defineProps<{
embedded?: boolean;
}>(), { embedded: false });
const emit = defineEmits<{
'open-detail': [contractId: number];
}>();
const { t } = useI18n();
const router = useRouter();
const auth = useAuthStore();
const isAdmin = computed(() => auth.isAdmin);
const msg = useMessage(); const keyword = ref(''); const loading = ref(false); const actionLoading = ref(false);
const showForceSyncConfirm = ref(false);
const showReparseExistingConfirm = ref(false);
const msg = useMessage(); const keyword = ref(''); const loading = ref(false);
const contracts = ref<ContractPaymentContract[]>([]);
const alertSummary = ref<AlertSummary | null>(null);
const ledgerSummary = ref<LedgerSummary>({ due: 0, overdue: 0, needs_completion: 0, due_this_month: 0 });
const ledgerSummary = ref<LedgerSummary>({ due: 0, overdue: 0, active: 0, due_this_month: 0 });
const ledgerFocus = ref<LedgerFocus | ''>('');
const page = ref(1); const pageSize = ref(20); const total = ref(0); const pages = ref(1);
const ledgerFocusCards = computed(() => ([
{ key: 'due' as const, label: t('admin.contractPayment.ledgerFocus.due'), hint: t('admin.contractPayment.ledgerFocus.dueHint'), value: ledgerSummary.value.due, tone: 'due' },
{ key: 'overdue' as const, label: t('admin.contractPayment.ledgerFocus.overdue'), hint: '', value: ledgerSummary.value.overdue, tone: 'overdue' },
{ key: 'needs_completion' as const, label: t('admin.contractPayment.ledgerFocus.needsCompletion'), hint: '', value: ledgerSummary.value.needs_completion, tone: 'needs' },
{ key: 'active' as const, label: t('admin.contractPayment.ledgerFocus.active'), hint: '', value: ledgerSummary.value.active, tone: 'in-progress' },
{ key: 'due_this_month' as const, label: t('admin.contractPayment.ledgerFocus.dueThisMonth'), hint: t('admin.contractPayment.ledgerFocus.dueThisMonthHint'), value: ledgerSummary.value.due_this_month, tone: 'month' },
]));
const stage = (item: ContractPaymentContract, name: string) => item.nodes.find((node) => node.node_type === name);
@@ -150,7 +147,7 @@ async function refreshLedgerSummary(): Promise<void> {
}
/**
* 加载当前页合同台账。
* 核心逻辑:合同列表使用服务端分页;关键词同时匹配合同号、流程号、采购单号和供应商;
* 核心逻辑:合同列表使用服务端分页;关键词同时匹配合同号、流程号、采购单号、供应商和申请人;
* 汇总卡 focus 与关键词叠加;搜索、点卡片和每页条数变化均从第一页开始,并并行刷新待发送摘要与汇总卡。
* @param resetPage - 为 true 时重置为第一页,用于关键词查询或切换汇总卡。
* @returns 完成后更新当前列表、分页元数据、待发送摘要和汇总卡。
@@ -189,80 +186,27 @@ function toggleLedgerFocus(key: LedgerFocus): void {
void load(true);
}
/**
* 提交合同付款预警后台任务。
* 核心逻辑:仅管理员可提交;按操作类型调用相应的异步接口,任务入队成功后仅展示任务编号,不等待长耗时同步或发送完成。
* @param action - sync 同步 OA、force-sync 强制覆盖、reparse-existing 刷新存量解析、scan 扫描预警、weekly 周汇总。
* @returns 任务提交完成后显示成功或失败提示。
* 打开合同详情。
* 核心逻辑:Chat 父级用 open-detail 在当前 Tab 内下钻;不再跳工作台路由。
*/
async function submitAction(action: 'sync' | 'force-sync' | 'reparse-existing' | 'scan' | 'weekly'): Promise<void> {
if (!isAdmin.value) return;
actionLoading.value = true;
try {
if (action === 'sync' || action === 'force-sync') {
await enqueueContractPaymentSync(action === 'force-sync');
} else if (action === 'reparse-existing') {
await enqueueContractPaymentReparse();
} else if (action === 'scan') {
await enqueueContractPaymentAlertScan();
} else {
await enqueueContractPaymentWeeklyAlert();
}
msg.success(t('admin.contractPayment.jobSubmitted'));
if (action === 'scan' || action === 'weekly') {
await refreshSummary();
}
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.contractPayment.actionFailed'));
} finally {
actionLoading.value = false;
}
}
/**
* 触发任务入口;强制覆盖同步先弹出统一确认框,其余直接提交。
* 核心逻辑:用公共确认组件替代原生 confirm,避免浏览器差异;确认后仍走统一的提交逻辑。
* @param action - 待提交的预警任务类型。
*/
function run(action: 'sync' | 'force-sync' | 'reparse-existing' | 'scan' | 'weekly'): void {
if (!isAdmin.value) return;
if (action === 'force-sync') {
showForceSyncConfirm.value = true;
return;
}
if (action === 'reparse-existing') {
showReparseExistingConfirm.value = true;
return;
}
void submitAction(action);
}
/** 强制覆盖同步确认后的提交回调。 */
function confirmForceSync(): void {
void submitAction('force-sync');
}
/** 存量合同批量重解析确认后的提交回调。 */
function confirmReparseExisting(): void {
void submitAction('reparse-existing');
}
/**
* 进入所选合同的付款计划和预警审计详情。
* 核心逻辑:仅使用台账已返回的内部主键构造路由,合同编号为空时仍可安全查看详情。
* @param contractId - 合同台账主键。
* @returns 详情路由跳转完成。
*/
async function openContractDetail(contractId: number): Promise<void> {
await router.push(WORKSPACE_PATHS.contractPaymentDetail(contractId));
function openContractDetail(contractId: number): void {
emit('open-detail', contractId);
}
onMounted(() => void load());
</script>
<template>
<section class="section-gap animate-fade-in-up">
<div class="flex flex-wrap items-start justify-between gap-4"><div><h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPayment.title') }}</h2><p class="text-sm text-muted mt-1">{{ t('admin.contractPayment.subtitle') }}</p></div><div v-if="isAdmin" class="flex flex-wrap gap-2"><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('sync')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.sync') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('force-sync')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.forceSync') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('reparse-existing')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.reparseExisting') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('scan')"><CalendarClock class="w-4 h-4" />{{ t('admin.contractPayment.scanAlerts') }}</button><button class="btn-primary" :disabled="actionLoading" @click="run('weekly')"><Send class="w-4 h-4" />{{ t('admin.contractPayment.weeklySend') }}</button></div></div>
<div v-if="!props.embedded" class="mb-4">
<h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPayment.title') }}</h2>
<p class="text-sm text-muted mt-1">{{ t('admin.contractPayment.subtitle') }}</p>
</div>
<div class="contract-stat-grid">
<button
v-for="card in ledgerFocusCards"
:key="card.key"
type="button"
class="contract-stat-card"
:class="[card.tone, { active: ledgerFocus === card.key }]"
:class="[card.tone, { 'is-selected': ledgerFocus === card.key }]"
@click="toggleLedgerFocus(card.key)"
>
<span class="contract-stat-label">{{ card.label }}<small v-if="card.hint">({{ card.hint }})</small></span>
@@ -302,22 +246,6 @@ onMounted(() => void load());
</table>
</div>
<PaginationBar v-model:page="page" v-model:page-size="pageSize" :total="total" :pages="pages" :visible="total > 0 || !!keyword.trim() || !!ledgerFocus" @update:page="() => load()" @update:page-size="() => load()" />
<DeleteConfirmDialog
v-if="isAdmin"
v-model="showForceSyncConfirm"
:title="t('admin.contractPayment.forceSync')"
:message="t('admin.contractPayment.forceSyncConfirm')"
confirm-tone="primary"
@confirm="confirmForceSync"
/>
<DeleteConfirmDialog
v-if="isAdmin"
v-model="showReparseExistingConfirm"
:title="t('admin.contractPayment.reparseExisting')"
:message="t('admin.contractPayment.reparseExistingConfirm')"
confirm-tone="primary"
@confirm="confirmReparseExisting"
/>
</section>
</template>
<style scoped>
@@ -340,13 +268,13 @@ onMounted(() => void load());
text-align: left;
cursor: pointer;
}
.contract-stat-card.active { border-color: #93c5fd; box-shadow: 0 0 0 2px rgba(59, 130, 246, .16); }
.contract-stat-card.is-selected { border-color: #93c5fd; box-shadow: 0 0 0 2px rgba(59, 130, 246, .16); }
.contract-stat-label { color: #8aa0bd; font-size: 12px; font-weight: 600; line-height: 1.35; }
.contract-stat-label small { margin-left: 2px; font-size: 12px; font-weight: 600; }
.contract-stat-value { margin-top: 8px; font-size: 28px; font-weight: 800; line-height: 1; }
.contract-stat-card.due .contract-stat-value { color: #d97706; }
.contract-stat-card.overdue .contract-stat-value { color: #dc2626; }
.contract-stat-card.needs .contract-stat-value { color: #0f172a; }
.contract-stat-card.in-progress .contract-stat-value { color: #2563eb; }
.contract-stat-card.month .contract-stat-value { color: #16a34a; }
@media (max-width: 900px) { .contract-stat-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.contract-filter-bar {
@@ -1,21 +1,25 @@
<!--
features/contract-payment/views/ContractPaymentReviewPage.vue
用途:集中展示关键解析事实缺失或冲突的合同,供管理员下载原文并人工确认。
依赖:contract-payment.api、PaginationBar、工作台路由与统一消息提示。
逻辑:后端以 review_only 过滤 needs_review 合同;页面不推导付款节点,也不触发预警任务。
依赖:contract-payment.api、PaginationBar、统一消息提示。
逻辑:后端以 review_only 过滤 needs_review 合同;关键词可搜合同号、采购单号、供应商和申请人;Chat 父级通过 open-detail 下钻详情。
-->
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { Search } from 'lucide-vue-next';
import { BusinessError } from '@/shared/api/client';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import { useMessage } from '@/shared/composables/useMessage';
import { WORKSPACE_PATHS } from '@/features/workspace/constants/routes';
import { listContractPaymentContracts, type ContractPaymentContract } from '../api/contract-payment.api';
const router = useRouter();
const props = withDefaults(defineProps<{
embedded?: boolean;
}>(), { embedded: false });
const emit = defineEmits<{
'open-detail': [contractId: number];
}>();
const { t } = useI18n();
const msg = useMessage();
const keyword = ref('');
@@ -28,7 +32,7 @@ const pages = ref(1);
/**
* 读取需要人工确认的合同列表。
* 核心逻辑:明确传入 reviewOnly,避免前端仅按显示状态过滤而遗漏后端新产生的待确认合同;关键词同样匹配供应商。
* 核心逻辑:明确传入 reviewOnly,避免前端仅按显示状态过滤而遗漏后端新产生的待确认合同;关键词同样匹配供应商和申请人。
* @param resetPage - 为 true 时重置到第一页,供关键词查询使用。
* @returns 请求完成后更新分页数据;失败时保留已有列表并提示原因。
*/
@@ -56,8 +60,8 @@ async function load(resetPage = false): Promise<void> {
* @param contractId - 合同付款台账主键。
* @returns 路由跳转完成。
*/
async function openContractDetail(contractId: number): Promise<void> {
await router.push(WORKSPACE_PATHS.contractPaymentDetail(contractId));
function openContractDetail(contractId: number): void {
emit('open-detail', contractId);
}
onMounted(() => void load());
@@ -65,7 +69,10 @@ onMounted(() => void load());
<template>
<section class="section-gap animate-fade-in-up">
<div><h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPaymentReview.title') }}</h2><p class="mt-1 text-sm text-muted">{{ t('admin.contractPaymentReview.subtitle') }}</p></div>
<div v-if="!props.embedded">
<h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPaymentReview.title') }}</h2>
<p class="mt-1 text-sm text-muted">{{ t('admin.contractPaymentReview.subtitle') }}</p>
</div>
<div class="contract-filter-bar">
<div class="contract-filter-search">
<Search class="contract-filter-icon" />
@@ -1,31 +1,30 @@
<!--
features/contract-payment/views/ContractPaymentWeeklyBatchesPage.vue
用途:独立展示合同付款预警的周汇总批次及其企业微信发送审计摘要,并下载 Excel 明细。
依赖:contract-payment.api、useAuthStore、统一消息提示;由工作台“合同付款预警 > 周汇总批次”路由加载。
逻辑:后端扫描产生的批次在此集中查看;Excel 经受控接口下载;手动发送仅管理员可见并提交异步任务。
依赖:contract-payment.api、统一消息提示。
逻辑:后端扫描产生的批次在此集中查看;Excel 经受控接口下载;Chat 顶栏共用发送入口,本页 embedded 时隐藏页头与发送按钮。
-->
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { CalendarClock, Download, Send } from 'lucide-vue-next';
import { onMounted, ref } from 'vue';
import { CalendarClock, Download } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { formatLocalDateTime } from '@/shared/utils/dateTime';
import { useMessage } from '@/shared/composables/useMessage';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import {
downloadContractPaymentAlertBatchExcel,
enqueueContractPaymentWeeklyAlert,
listContractPaymentAlertBatches,
type AlertBatch,
} from '../api/contract-payment.api';
const props = withDefaults(defineProps<{
embedded?: boolean;
}>(), { embedded: false });
const { t, te } = useI18n();
const auth = useAuthStore();
const isAdmin = computed(() => auth.isAdmin);
const msg = useMessage();
const batches = ref<AlertBatch[]>([]);
const loading = ref(false);
const actionLoading = ref(false);
const downloadingId = ref<number | null>(null);
/**
@@ -45,25 +44,6 @@ async function load(): Promise<void> {
}
}
/**
* 手动提交本周汇总发送任务。
* 核心逻辑:仅管理员可调用异步入队接口,避免浏览器等待企业微信发送和 Excel 文件生成完成。
* @returns 提交结果通过统一消息提示反馈,成功后刷新批次列表。
*/
async function runWeeklyAlert(): Promise<void> {
if (!isAdmin.value) return;
actionLoading.value = true;
try {
await enqueueContractPaymentWeeklyAlert();
msg.success(t('admin.contractPayment.weeklyBatchSubmitted'));
await load();
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.contractPayment.actionFailed'));
} finally {
actionLoading.value = false;
}
}
/**
* 判断批次是否已归档 Excel,供下载按钮启用。
* 核心逻辑:文件名或大小任一存在即视为可下载;真正有无字节由下载接口校验。
@@ -127,16 +107,9 @@ onMounted(() => void load());
<template>
<section class="section-gap animate-fade-in-up">
<div class="flex flex-wrap items-start justify-between gap-4">
<div>
<h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPayment.weeklyBatchesTitle') }}</h2>
<p class="mt-1 text-sm text-muted">{{ t('admin.contractPayment.weeklyBatchesSubtitle') }}</p>
</div>
<div v-if="isAdmin" class="flex gap-2">
<button class="btn-primary" :disabled="actionLoading" @click="runWeeklyAlert">
<Send class="h-4 w-4" />{{ t('admin.contractPayment.weeklySend') }}
</button>
</div>
<div v-if="!props.embedded">
<h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPayment.weeklyBatchesTitle') }}</h2>
<p class="mt-1 text-sm text-muted">{{ t('admin.contractPayment.weeklyBatchesSubtitle') }}</p>
</div>
<div class="surface-panel mt-5 overflow-x-auto rounded-2xl">
@@ -9,7 +9,7 @@
* 业务员(部门副文案) → 客户订单 → 规格 → 单位;独立的部门列/品名列已并入合并展示。
* 浏览体验:页面高度收敛至视口(滚动全部发生在表格容器内 → 列头 sticky 固定、横向滚动条
* 常驻表格底缘);左侧冻结前四列标识区(勾选/客户编号/订单日期/订单单号:项次,
* 冻结单元格用实色背景防透出);筛选区与工具栏字号与表格统一(text-xs)并压缩高度。
* 冻结单元格用实色背景防透出);筛选区与工具栏字号与表格统一(text-sm 14px)并压缩高度。
*/
<script setup lang="ts">
@@ -318,14 +318,15 @@ onMounted(() => {
</script>
<template>
<!-- 全页统一字号:与表头一致(text-xs 12px),根容器设定基准,子元素不再覆写 -->
<!-- 全页统一字号:与表头一致(text-sm 14px),根容器设定基准,子元素不再覆写;
唯一例外:交期回复状态/交期已锁定徽标保持 text-xs(12px)加粗 -->
<!-- 高度收敛至视口(h-screen + overflow-hidden):页面自身不滚动,滚动全部在表格容器内,
列头 sticky 固定、横向滚动条常驻表格底缘;聊天壳 iframe 与独立路由均适用 -->
<div class="flex h-screen flex-col gap-4 overflow-hidden p-6 text-xs">
<div class="flex h-screen flex-col gap-4 overflow-hidden p-6 text-sm">
<!-- 页头:标题 + 最近同步 + 手动刷新 -->
<div class="flex flex-wrap items-center gap-3">
<h1 class="font-bold text-primary">{{ t('workspace.nav.orderDeliveryReply') }}</h1>
<span class="rounded-full px-3 py-1 text-xs" :class="latestSyncFailed ? 'bg-rose-50 text-rose-600' : 'bg-blue-50 text-blue-600'">
<span class="rounded-full px-3 py-1" :class="latestSyncFailed ? 'bg-rose-50 text-rose-600' : 'bg-blue-50 text-blue-600'">
{{ latestSyncText }}
</span>
<div class="flex-1" />
@@ -334,20 +335,20 @@ onMounted(() => {
</button>
</div>
<!-- 搜索区:合并关键词搜索(订单/产品/客户命中任一字段),字号与表格统一(text-xs),shrink-0 防压缩 -->
<!-- 搜索区:合并关键词搜索(订单/产品/客户命中任一字段),字号与表格统一(text-sm),shrink-0 防压缩 -->
<div class="flex shrink-0 flex-wrap items-end gap-3 rounded-2xl border border-default bg-surface px-4 py-2.5">
<label class="flex flex-col gap-1 text-xs text-muted">
<label class="flex flex-col gap-1 text-muted">
{{ t('workspace.orderDeliveryReply.filterKeyword') }}
<input v-model="filters.keyword" class="h-8 min-w-[340px] rounded-lg border border-default px-3 text-xs text-primary outline-none focus:border-blue-500" :placeholder="t('workspace.orderDeliveryReply.filterKeywordPh')" @keyup.enter="doSearch" />
<input v-model="filters.keyword" class="h-8 min-w-[340px] rounded-lg border border-default px-3 text-primary outline-none focus:border-blue-500" :placeholder="t('workspace.orderDeliveryReply.filterKeywordPh')" @keyup.enter="doSearch" />
</label>
<label class="flex flex-col gap-1 text-xs text-muted">
<label class="flex flex-col gap-1 text-muted">
{{ t('workspace.orderDeliveryReply.filterOrderDate') }}
<input v-model="filters.order_date" type="date" class="h-8 rounded-lg border border-default px-3 text-xs text-primary outline-none focus:border-blue-500" />
<input v-model="filters.order_date" type="date" class="h-8 rounded-lg border border-default px-3 text-primary outline-none focus:border-blue-500" />
</label>
<label class="flex flex-col gap-1 text-xs text-muted">
<label class="flex flex-col gap-1 text-muted">
{{ t('workspace.orderDeliveryReply.filterStatus') }}
<!-- 状态筛选选择即生效(无需再点查询);其余条件仍由「查询」统一提交 -->
<select v-model="filters.status" class="h-8 min-w-[140px] rounded-lg border border-default bg-white px-3 text-xs text-primary outline-none focus:border-blue-500" @change="doSearch">
<select v-model="filters.status" class="min-w-[140px] rounded-lg border border-default bg-white px-3 py-[5px] text-sm leading-5 text-primary outline-none focus:border-blue-500" @change="doSearch">
<option value="">{{ t('workspace.orderDeliveryReply.statusAll') }}</option>
<option value="replied">{{ t('workspace.orderDeliveryReply.statusReplied') }}</option>
<option value="not_fully_replied">{{ t('workspace.orderDeliveryReply.statusNotFully') }}</option>
@@ -356,7 +357,7 @@ onMounted(() => {
<button type="button" class="btn-primary h-8" @click="doSearch">{{ t('workspace.orderDeliveryReply.search') }}</button>
<button type="button" class="btn-ghost h-8" @click="doReset">{{ t('workspace.orderDeliveryReply.reset') }}</button>
<div class="flex-1" />
<span class="text-xs text-muted">{{ t('workspace.orderDeliveryReply.totalCount', { count: total }) }}</span>
<span class="text-muted">{{ t('workspace.orderDeliveryReply.totalCount', { count: total }) }}</span>
</div>
<!-- 工具栏:全选 + 联合回复 + 批量通知(shrink-0 防压缩,py-2 紧凑高度) -->
@@ -375,14 +376,14 @@ onMounted(() => {
</button>
</template>
<div class="flex-1" />
<span class="whitespace-nowrap rounded-full bg-slate-100 px-3 py-1 text-xs text-muted">{{ t('workspace.orderDeliveryReply.toolbarHint') }}</span>
<span class="whitespace-nowrap rounded-full bg-slate-100 px-3 py-1 text-muted">{{ t('workspace.orderDeliveryReply.toolbarHint') }}</span>
</div>
<!-- 列表 -->
<div class="min-h-0 flex-1 overflow-auto rounded-2xl border border-default bg-surface">
<table class="w-full border-collapse">
<!-- z-30 高于表体冻结单元格(z-20):纵向滚动时冻结列不会盖住表头 -->
<thead class="sticky top-0 z-30 bg-slate-50 text-xs text-muted [&_th]:whitespace-nowrap">
<thead class="sticky top-0 z-30 bg-slate-50 text-muted [&_th]:whitespace-nowrap">
<tr>
<!-- 左侧冻结标识区(前四列):勾选/客户编号/订单日期/订单单号:项次,宽度固定保证偏移对齐 -->
<th class="sticky left-0 z-30 w-8 bg-slate-50 px-2 py-2" />
@@ -422,21 +423,21 @@ onMounted(() => {
:title="line.customer_full_name || line.customer_short_name || ''"
>
<div>{{ line.customer_no || '—' }}</div>
<div class="truncate text-xs text-muted">{{ line.customer_short_name || '' }}</div>
<div class="truncate text-muted">{{ line.customer_short_name || '' }}</div>
</td>
<td
class="sticky left-[10rem] z-20 w-24 min-w-[6rem] max-w-[6rem] overflow-hidden px-2 py-1.5"
:class="selected.includes(lineKey(line)) ? 'bg-blue-100 group-hover:bg-blue-200' : 'bg-white group-hover:bg-slate-100'"
>{{ line.order_date || '—' }}</td>
<td
class="sticky left-[16rem] z-20 w-40 min-w-[10rem] max-w-[10rem] overflow-hidden whitespace-nowrap border-r border-default px-2 py-1.5 font-mono text-xs shadow-[2px_0_6px_-2px_rgba(15,23,42,0.12)]"
class="sticky left-[16rem] z-20 w-40 min-w-[10rem] max-w-[10rem] overflow-hidden whitespace-nowrap border-r border-default px-2 py-1.5 font-mono shadow-[2px_0_6px_-2px_rgba(15,23,42,0.12)]"
:class="selected.includes(lineKey(line)) ? 'bg-blue-100 group-hover:bg-blue-200' : 'bg-white group-hover:bg-slate-100'"
>{{ line.order_no }}:{{ line.line_no }}</td>
<td class="px-2 py-1.5" :title="line.part_name || ''">
<div class="max-w-[10rem] truncate font-mono text-xs">{{ line.part_no || '—' }}</div>
<div class="max-w-[14rem] truncate text-xs text-muted">{{ line.part_name || '' }}</div>
<div class="max-w-[10rem] truncate font-mono">{{ line.part_no || '—' }}</div>
<div class="max-w-[14rem] truncate text-muted">{{ line.part_name || '' }}</div>
</td>
<td class="whitespace-nowrap px-2 py-1.5 font-mono text-xs">{{ line.customer_part_no || '—' }}</td>
<td class="whitespace-nowrap px-2 py-1.5 font-mono">{{ line.customer_part_no || '—' }}</td>
<td class="px-2 py-2 text-right tabular-nums">{{ line.qty ?? '—' }}</td>
<td class="whitespace-nowrap px-2 py-1.5">{{ line.agreed_date || '—' }}</td>
<td class="px-2 py-1.5">
@@ -449,19 +450,19 @@ onMounted(() => {
<template v-if="line.batches.length === 0">
<span class="text-muted">{{ t('workspace.orderDeliveryReply.statusNotReplied') }}</span>
<div v-if="canManage" class="mt-0.5">
<button type="button" class="rounded-md border border-blue-200 bg-blue-50 px-2 py-0.5 text-xs text-blue-600" @click="openSingleReply(line)">
<button type="button" class="rounded-md border border-blue-200 bg-blue-50 px-2 py-0.5 text-blue-600" @click="openSingleReply(line)">
{{ t('workspace.orderDeliveryReply.replyAction') }}
</button>
</div>
</template>
<template v-else>
<div class="flex items-center gap-2">
<span class="whitespace-nowrap rounded-full border border-default bg-slate-50 px-2 py-0.5 text-xs text-muted">
<span class="whitespace-nowrap rounded-full border border-default bg-slate-50 px-2 py-0.5 text-muted">
{{ t('workspace.orderDeliveryReply.batchCount', { count: line.batches.length }) }} ·
{{ t('workspace.orderDeliveryReply.repliedOf', { replied: repliedQty(line), remain: undelivered(line) }) }}
<span v-if="repliedQty(line) > undelivered(line)" class="ml-1 font-semibold text-orange-500">{{ t('workspace.orderDeliveryReply.overTag') }}</span>
</span>
<button v-if="line.batches.length > 1" type="button" class="rounded-full border border-default px-2 py-0.5 text-xs text-blue-600" @click="toggleExpand(lineKey(line))">
<button v-if="line.batches.length > 1" type="button" class="rounded-full border border-default px-2 py-0.5 text-blue-600" @click="toggleExpand(lineKey(line))">
{{ expanded.includes(lineKey(line)) ? t('workspace.orderDeliveryReply.collapse') : t('workspace.orderDeliveryReply.expand', { count: line.batches.length - 1 }) }}
</button>
</div>
@@ -470,7 +471,7 @@ onMounted(() => {
v-for="(batch, idx) in line.batches"
:key="batch.seq ?? idx"
v-show="expanded.includes(lineKey(line)) || idx === 0"
class="max-w-[230px] truncate rounded border-l-[3px] border-blue-500 bg-blue-50/50 px-2 py-0.5 text-xs text-secondary"
class="max-w-[230px] truncate rounded border-l-[3px] border-blue-500 bg-blue-50/50 px-2 py-0.5 text-secondary"
>
{{ batch.planned_date }} · <b class="text-blue-600">{{ batch.qty }}</b> {{ line.unit }}
<i v-if="batch.remark" class="ml-1 not-italic text-muted">{{ batch.remark }}</i>
@@ -478,7 +479,7 @@ onMounted(() => {
</div>
<div class="mt-0.5">
<span v-if="line.locked" class="rounded-full bg-emerald-50 px-2.5 py-0.5 text-xs font-semibold text-emerald-600">{{ t('workspace.orderDeliveryReply.lockedTag') }}</span>
<button v-else-if="canManage" type="button" class="rounded-md border border-blue-200 bg-blue-50 px-2 py-0.5 text-xs text-blue-600" @click="openSingleReply(line)">
<button v-else-if="canManage" type="button" class="rounded-md border border-blue-200 bg-blue-50 px-2 py-0.5 text-blue-600" @click="openSingleReply(line)">
{{ t('workspace.orderDeliveryReply.editReplyAction') }}
</button>
</div>
@@ -487,9 +488,9 @@ onMounted(() => {
<!-- 交期回复人员:锁定行附带已通知对象与时间(原「通知业务部门」列已取消,信息并入此处) -->
<td class="px-2 py-1.5">
<template v-if="line.notified_employee_id || line.notified_user_name">
<div class="font-mono text-xs">{{ line.notified_employee_id || '' }}</div>
<div class="text-xs text-muted">{{ line.notified_user_name || '' }}</div>
<div v-if="line.locked" class="text-xs text-emerald-600">
<div class="font-mono">{{ line.notified_employee_id || '' }}</div>
<div class="text-muted">{{ line.notified_user_name || '' }}</div>
<div v-if="line.locked" class="text-emerald-600">
{{ t('workspace.orderDeliveryReply.notifiedTag', { name: line.salesperson_name || line.salesperson_code || '' }) }}
<span class="text-muted">{{ line.notified_at || '' }}</span>
</div>
@@ -499,9 +500,9 @@ onMounted(() => {
<!-- 业务员(副文案部门):与客户编号/简称同款合并展示,独立部门列已取消 -->
<td class="px-2 py-1.5" :title="line.salesperson_code || ''">
<div class="whitespace-nowrap">{{ line.salesperson_name || line.salesperson_code || '—' }}</div>
<div class="text-xs text-muted">{{ line.dept_name || line.dept_code || '' }}</div>
<div class="text-muted">{{ line.dept_name || line.dept_code || '' }}</div>
</td>
<td class="px-2 py-1.5 font-mono text-xs" :title="line.customer_po || ''"><span class="block max-w-[10rem] truncate">{{ line.customer_po || '—' }}</span></td>
<td class="px-2 py-1.5 font-mono" :title="line.customer_po || ''"><span class="block max-w-[10rem] truncate">{{ line.customer_po || '—' }}</span></td>
<td class="px-2 py-1.5" :title="line.spec || ''"><span class="block max-w-[10rem] truncate">{{ line.spec || '—' }}</span></td>
<td class="px-2 py-1.5">{{ line.unit || '—' }}</td>
</tr>
@@ -514,7 +515,7 @@ onMounted(() => {
<!-- 分页:复用管理控制台-数据报表的 PaginationBar(摘要 + 每页条数 + 页码按钮) -->
<PaginationBar
class="[&_*]:!text-xs"
class="[&_*]:!text-sm"
:page="page"
:page-size="pageSize"
:total="total"
@@ -534,18 +535,18 @@ onMounted(() => {
<div class="flex-1 overflow-auto px-5 py-4">
<!-- 快速统一交期 -->
<div class="mb-4 flex flex-wrap items-end gap-3 rounded-xl border border-default bg-blue-50/40 px-4 py-3">
<label class="flex flex-col gap-1 text-xs text-muted">
<label class="flex flex-col gap-1 text-muted">
{{ t('workspace.orderDeliveryReply.quickDate') }}
<input v-model="quickDate" type="date" class="h-9 rounded-lg border border-default px-3 text-primary" />
</label>
<button type="button" class="h-9 rounded-lg border border-default px-3 text-primary" @click="applyQuickDate">
{{ t('workspace.orderDeliveryReply.applyQuickDate') }}
</button>
<span class="text-xs text-muted">{{ t('workspace.orderDeliveryReply.modalHint') }}</span>
<span class="text-muted">{{ t('workspace.orderDeliveryReply.modalHint') }}</span>
</div>
<!-- 每行批次编辑器 -->
<div v-for="entry in modalLines" :key="lineKey(entry.line)" class="mb-4 overflow-hidden rounded-xl border border-default">
<div class="flex flex-wrap items-center gap-2 bg-slate-50 px-3 py-2 text-xs">
<div class="flex flex-wrap items-center gap-2 bg-slate-50 px-3 py-2">
<span class="rounded bg-indigo-50 px-2 py-0.5 font-semibold text-indigo-600">{{ entry.line.order_no }}</span>
<span>{{ t('workspace.orderDeliveryReply.itemLabel', { item: entry.line.line_no }) }}</span>
<span class="text-muted">{{ entry.line.customer_no }} · {{ entry.line.customer_short_name }}</span>
@@ -566,7 +567,7 @@ onMounted(() => {
</button>
</div>
</div>
<p v-if="overQtyEntries.length" class="text-xs text-orange-500">
<p v-if="overQtyEntries.length" class="text-orange-500">
{{ t('workspace.orderDeliveryReply.overWarning', { detail: overQtyEntries.map(({ entry, total }) => `${entry.line.order_no}:${entry.line.line_no} ${total} > ${undelivered(entry.line)}`).join(';') }) }}
</p>
</div>
@@ -58,16 +58,21 @@ onMounted(() => { void Promise.all([admin.loadCustomers(), admin.loadShadowRepor
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.name') }}</th>
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.shortCode') }}</th>
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.status') }}</th>
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.odmIds') }}</th>
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.identityEvidences') }}</th>
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.notices') }}</th>
<th class="px-5 py-4 text-right">{{ t('admin.shippingCustomers.headers.actions') }}</th>
</tr></thead>
<tbody>
<tr v-if="admin.customers.value.length === 0"><td colspan="6" class="admin-table-empty px-5">{{ t('admin.shippingCustomers.empty') }}</td></tr>
<tr v-if="admin.customers.value.length === 0"><td colspan="7" class="admin-table-empty px-5">{{ t('admin.shippingCustomers.empty') }}</td></tr>
<tr v-for="customer in admin.customers.value" :key="customer.id">
<td class="px-5 py-4"><div class="font-medium text-primary">{{ customer.standard_name }}</div><div v-if="customer.remark" class="text-xs text-muted truncate max-w-sm">{{ customer.remark }}</div></td>
<td class="px-5 py-4 font-mono text-sm">{{ customer.short_code }}</td>
<td class="px-5 py-4"><span class="text-sm" :class="customer.status === 'active' ? 'text-emerald-600' : 'text-muted'">{{ t(`admin.shippingCustomers.status.${customer.status}`) }}</span></td>
<td class="px-5 py-4 text-sm">
<span v-if="customer.odm_ids?.length" class="font-mono text-xs">{{ customer.odm_ids.join(', ') }}</span>
<span v-else class="text-xs text-muted">{{ t('admin.shippingCustomers.fields.odmIdsUnlimited') }}</span>
</td>
<td class="px-5 py-4 text-sm">{{ customer.identity_evidence_count || 0 }}</td>
<td class="px-5 py-4 text-sm">{{ customer.notice_count }}</td>
<td class="px-5 py-4"><div class="flex justify-end gap-1">
@@ -42,6 +42,16 @@ const { t } = useI18n();
<span class="label-field">{{ t('admin.shippingCustomers.fields.remark') }}</span>
<textarea v-model="form.remark" rows="3" class="input-field text-sm resize-y" />
</label>
<label class="block space-y-1.5">
<span class="label-field">{{ t('admin.shippingCustomers.fields.odmIds') }}</span>
<textarea
v-model="form.odm_ids_text"
rows="3"
class="input-field text-sm resize-y font-mono"
:placeholder="t('admin.shippingCustomers.fields.odmIdsHint')"
/>
<span class="text-xs text-muted">{{ t('admin.shippingCustomers.fields.odmIdsHint') }}</span>
</label>
<label v-if="form.id" class="block space-y-1.5">
<span class="label-field">{{ t('admin.shippingCustomers.fields.changeReason') }}</span>
<textarea v-model="form.reason" rows="2" class="input-field text-sm resize-y" :placeholder="t('admin.shippingCustomers.fields.changeReasonHint')" />
@@ -158,11 +158,21 @@ export function useShippingCustomersAdmin() {
}
isSaving.value = true;
try {
// ODM ID 清单:文本域逐行解析,去空去重;整体为空提交 null 表示不限定。
const odmIds = Array.from(
new Set(
form.odm_ids_text
.split(/\r?\n/)
.map((item) => item.trim())
.filter(Boolean),
),
);
const payload = {
standard_name: form.standard_name.trim(),
short_code: form.short_code.trim().toUpperCase(),
status: form.status,
remark: form.remark.trim(),
odm_ids: odmIds.length ? odmIds : null,
reason: form.reason.trim(),
};
if (form.id) await updateShippingCustomer(form.id, payload);
@@ -29,6 +29,8 @@ export interface ShippingCustomerRow {
status: ShippingCustomerStatus;
merged_into_customer_id?: number | null;
remark?: string | null;
/** 客户可用的 ODM ID 清单;null/空数组表示不限定。 */
odm_ids?: string[] | null;
notice_count: number;
identifier_count: number;
identity_evidence_count?: number;
@@ -282,6 +284,8 @@ export interface ShippingCustomerFormState {
short_code: string;
status: ShippingCustomerStatus;
remark: string;
/** 文本域原文:每行一个 ODM ID;保存时解析为 odm_ids 数组。 */
odm_ids_text: string;
reason: string;
}
@@ -309,6 +313,7 @@ export const createEmptyShippingCustomerForm = (): ShippingCustomerFormState =>
short_code: '',
status: 'active',
remark: '',
odm_ids_text: '',
reason: '',
});
@@ -319,6 +324,7 @@ export const shippingCustomerToForm = (customer: ShippingCustomerRow): ShippingC
short_code: customer.short_code,
status: customer.status,
remark: customer.remark || '',
odm_ids_text: (customer.odm_ids || []).join('\n'),
reason: '',
});
@@ -1,17 +1,50 @@
<script setup lang="ts">
/**
* features/user/views/UserProfilePage.vue
* 閻劑鈧棑绱扮仦鏇犮仛閸滃瞼绱潏鎴濈秼閸撳秶鏁ら幋鐤カ閺傛瑣鈧浇顕㈢懛鈧?娑撳顣介崑蹇撱偨閿涘苯鑻熼幓鎰返娣囶喗鏁肩€靛棛鐖滈崗銉ュ經閵? * 娓氭繆绂嗛敍姝秙er-profile.context閵嗕勾ucide 閸ョ偓鐖i妴涔倁e i18n閵? * 闁槒绶敍姘矝閻?/workspace/profile 鐠侯垳鏁遍幍鑳祰閿涘奔绲炬い鐢告桨閸滃奔绗熼崝鈥崇秺鐏?user feature閵? */
import { inject } from 'vue';
* 用途:工作台个人中心,展示与编辑当前用户资料、语言/主题偏好,并提供修改密码入口。
* 依赖:workspace.context(WORKSPACE_KEY)、lucide 图标、vue-i18n。
* 逻辑:路由 /workspace/profile 懒加载本页;资料状态由 useWorkspaceProfile 经工作台注入,避免与工作台分叉。
*/
import { computed, inject } from 'vue';
import { useI18n } from 'vue-i18n';
import {
User, Mail, Building, CreditCard, Globe, Save, Palette,
} from 'lucide-vue-next';
import { getUserAvatarLabel } from '@/shared/utils/user-avatar';
import { WORKSPACE_KEY } from '@/features/workspace/composables/workspace.context';
// 个人资料与改密状态由工作台 useWorkspaceProfile 编排,经 WORKSPACE_KEY 注入。
// 这里复用同一份 ws 上下文(含 profileUser/主题/移动端/登出能力),避免与工作台状态分叉。
const { t } = useI18n();
const userProfile = inject(WORKSPACE_KEY)!;
/** 只读字段值:与 input-field 同高,正文统一 14px。 */
const fieldValueClass = 'flex min-h-11 items-center rounded-xl border border-default bg-surface-soft px-4 text-sm font-medium text-secondary';
/** 表单标签:与分区标题区分层级,全页统一 14px。 */
const fieldLabelClass = 'mb-1.5 flex items-center gap-1.5 text-sm font-medium text-muted';
/**
* 身份主标题:优先真实姓名,缺失时回退用户名。
*/
const displayName = computed(() => {
return userProfile.profileUser.real_name || userProfile.profileUser.username || '-';
});
/**
* 角色展示文案。
*/
const roleLabel = computed(() => {
return userProfile.profileUser.role === 'admin' ? t('profile.roleAdmin') : t('profile.roleUser');
});
/**
* 身份副标题:用户名(与主标题不同时)、部门、角色用间隔点拼接,空项省略。
*/
const identityMeta = computed(() => {
const username = userProfile.profileUser.username;
const showUsername = Boolean(username && username !== displayName.value);
return [showUsername ? username : '', userProfile.profileUser.department, roleLabel.value]
.filter(Boolean)
.join(' · ');
});
</script>
<template>
@@ -26,145 +59,178 @@ const userProfile = inject(WORKSPACE_KEY)!;
<div class="flex h-24 w-24 shrink-0 items-center justify-center rounded-full bg-brand-100 text-4xl font-bold text-brand-600" :class="userProfile.isMobile ? 'h-14 w-14 text-2xl' : ''">
{{ getUserAvatarLabel(userProfile.profileUser) }}
</div>
<div class="grid flex-1 text-left" :class="userProfile.isMobile ? 'grid-cols-2 gap-x-4 gap-y-1' : 'grid-cols-1 gap-x-12 gap-y-3 sm:grid-cols-2'">
<div :class="userProfile.isMobile ? '' : ''">
<div :class="userProfile.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ userProfile.isMobile ? $t('profile.realName') : (userProfile.profileUser.username || '-') }}</div>
<div v-if="userProfile.isMobile" class="text-sm font-medium text-primary truncate">{{ userProfile.profileUser.real_name || userProfile.profileUser.username || '-' }}</div>
</div>
<div>
<div :class="userProfile.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ userProfile.isMobile ? $t('profile.employeeId') : (userProfile.profileUser.employee_id || '-') }}</div>
<div v-if="userProfile.isMobile" class="text-sm font-medium text-primary truncate">{{ userProfile.profileUser.employee_id || '-' }}</div>
</div>
<div>
<div :class="userProfile.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ userProfile.isMobile ? $t('profile.department') : (userProfile.profileUser.department || '-') }}</div>
<div v-if="userProfile.isMobile" class="text-sm font-medium text-primary truncate">{{ userProfile.profileUser.department || '-' }}</div>
</div>
<div>
<div :class="userProfile.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ userProfile.isMobile ? $t('profile.role') : (userProfile.profileUser.role === 'admin' ? ($t('profile.roleAdmin') || 'Administrator') : ($t('profile.roleUser') || 'User')) }}</div>
<div v-if="userProfile.isMobile" class="text-sm font-medium text-primary truncate">{{ userProfile.profileUser.role === 'admin' ? ($t('profile.roleAdmin') || 'Administrator') : ($t('profile.roleUser') || 'User') }}</div>
</div>
<div :class="userProfile.isMobile ? 'col-span-2' : 'sm:col-span-2'">
<div :class="userProfile.isMobile ? 'text-xs text-muted' : 'break-all text-lg font-semibold text-primary'">{{ userProfile.isMobile ? $t('profile.email') : (userProfile.profileUser.email || '-') }}</div>
<div v-if="userProfile.isMobile" class="text-sm font-medium text-primary truncate">{{ userProfile.profileUser.email || '-' }}</div>
<div class="min-w-0 space-y-0.5">
<div class="truncate text-lg font-semibold text-primary">{{ displayName }}</div>
<div v-if="identityMeta" class="truncate text-sm text-muted">{{ identityMeta }}</div>
<div v-if="userProfile.profileUser.email" class="break-all text-sm text-muted">
{{ userProfile.profileUser.email }}
</div>
</div>
</div>
<div v-if="!userProfile.isMobile" class="flex shrink-0 items-center gap-2 self-start lg:ml-6">
<button @click="userProfile.handleChangePasswordClick" class="btn-primary px-6 py-3 text-base">
<div v-if="!userProfile.isMobile" class="shrink-0">
<button type="button" class="btn-primary btn-sm" @click="userProfile.handleChangePasswordClick">
{{ $t('profile.changePassword') }}
</button>
</div>
</div>
<div v-if="userProfile.isMobile" class="mt-4 flex items-center justify-center gap-4">
<button @click="userProfile.handleChangePasswordClick" class="btn-primary flex-1 py-2.5 text-sm text-center">
<div v-if="userProfile.isMobile" class="mt-4 flex items-center gap-3">
<button
type="button"
class="btn-primary btn-sm flex-1"
@click="userProfile.handleChangePasswordClick"
>
{{ $t('profile.changePassword') }}
</button>
<button @click="userProfile.handleLogout" class="btn-secondary flex-1 py-2.5 text-sm text-center text-red-600 hover:bg-red-50">
<button
type="button"
class="btn-secondary btn-sm flex-1 text-red-600 hover:bg-red-50"
@click="userProfile.handleLogout"
>
{{ $t('workspace.nav.logout') }}
</button>
</div>
</div>
<div class="space-y-6">
<div class="rounded-3xl border border-default bg-surface p-8 shadow-sm" :class="userProfile.isMobile ? 'p-4' : ''">
<div class="mb-8 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between" :class="userProfile.isMobile ? 'mb-4 gap-2' : ''">
<div class="flex items-center" :class="userProfile.isMobile ? 'w-full justify-center gap-2' : ''">
<h3 class="flex items-center gap-3 text-3xl font-bold text-primary" :class="userProfile.isMobile ? 'text-lg gap-2' : ''">
<User class="h-6 w-6 text-brand-500" :class="userProfile.isMobile ? 'h-4 w-4' : ''" />
<div class="rounded-2xl border border-default bg-surface p-5 shadow-sm md:p-6">
<div class="mb-5 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div class="flex items-center gap-2" :class="userProfile.isMobile ? 'w-full justify-between' : ''">
<h3 class="section-title flex items-center gap-2">
<User class="h-5 w-5 text-brand-500" />
{{ $t('profile.basicInfo') }}
</h3>
<button v-if="userProfile.isMobile && !userProfile.isProfileEditing" @click="userProfile.startProfileEditing" class="btn-secondary px-3 py-1 text-xs">
<button
v-if="userProfile.isMobile && !userProfile.isProfileEditing"
type="button"
class="btn-secondary btn-sm"
@click="userProfile.startProfileEditing"
>
{{ $t('profile.edit') }}
</button>
</div>
<p v-if="!userProfile.isMobile" class="mt-2 text-sm text-muted">
<p v-if="!userProfile.isMobile" class="section-desc">
{{ userProfile.isProfileEditing ? $t('profile.directEditHint') : $t('profile.switchEditHint') }}
</p>
<div v-if="!userProfile.isMobile" class="flex items-center gap-2">
<button v-if="!userProfile.isProfileEditing" @click="userProfile.startProfileEditing" class="btn-secondary px-5 py-2.5 text-sm">
<button
v-if="!userProfile.isProfileEditing"
type="button"
class="btn-secondary btn-sm"
@click="userProfile.startProfileEditing"
>
{{ $t('profile.edit') }}
</button>
<template v-else>
<button @click="userProfile.cancelProfileEditing" class="btn-secondary px-5 py-2.5 text-sm">
{{ $t('profile.cancel') || 'Cancel' }}
<button type="button" class="btn-secondary btn-sm" @click="userProfile.cancelProfileEditing">
{{ $t('profile.cancel') }}
</button>
<button
@click="userProfile.saveProfile"
type="button"
class="btn-primary btn-sm disabled:cursor-not-allowed disabled:opacity-50"
:disabled="userProfile.isProfileSaving || !userProfile.hasProfileUnsavedChanges"
class="btn-primary px-5 py-2.5 text-sm disabled:opacity-50 disabled:cursor-not-allowed"
@click="userProfile.saveProfile"
>
<Save class="w-4 h-4" />
<Save class="h-4 w-4" />
<span>{{ userProfile.isProfileSaving ? $t('profile.saving') : $t('workspace.save') }}</span>
</button>
</template>
</div>
</div>
<div class="grid grid-cols-1 gap-5 md:grid-cols-2" :class="userProfile.isMobile ? 'gap-3' : ''">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="userProfile.isMobile ? 'text-xs mb-1' : ''">
<label :class="fieldLabelClass">
<User class="h-4 w-4" /> {{ $t('profile.username') }}
</label>
<div class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="userProfile.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
<div :class="fieldValueClass">
{{ userProfile.profileUser.username || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="userProfile.isMobile ? 'text-xs mb-1' : ''">
<label :class="fieldLabelClass">
<CreditCard class="h-4 w-4" /> {{ $t('profile.employeeId') }}
</label>
<input v-if="userProfile.isProfileEditing" v-model="userProfile.profileUser.employee_id" type="text" class="input-field" :class="userProfile.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="userProfile.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
<input
v-if="userProfile.isProfileEditing"
v-model="userProfile.profileUser.employee_id"
type="text"
class="input-field text-sm"
>
<div v-else :class="fieldValueClass">
{{ userProfile.profileUser.employee_id || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="userProfile.isMobile ? 'text-xs mb-1' : ''">
<label :class="fieldLabelClass">
<User class="h-4 w-4" /> {{ $t('profile.realName') }}
</label>
<input v-if="userProfile.isProfileEditing" v-model="userProfile.profileUser.real_name" type="text" class="input-field" :class="userProfile.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="userProfile.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
<input
v-if="userProfile.isProfileEditing"
v-model="userProfile.profileUser.real_name"
type="text"
class="input-field text-sm"
>
<div v-else :class="fieldValueClass">
{{ userProfile.profileUser.real_name || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="userProfile.isMobile ? 'text-xs mb-1' : ''">
<label :class="fieldLabelClass">
<Building class="h-4 w-4" /> {{ $t('profile.department') }}
</label>
<input v-if="userProfile.isProfileEditing" v-model="userProfile.profileUser.department" type="text" class="input-field" :class="userProfile.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="userProfile.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
<input
v-if="userProfile.isProfileEditing"
v-model="userProfile.profileUser.department"
type="text"
class="input-field text-sm"
>
<div v-else :class="fieldValueClass">
{{ userProfile.profileUser.department || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="userProfile.isMobile ? 'text-xs mb-1' : ''">
<label :class="fieldLabelClass">
<Mail class="h-4 w-4" /> {{ $t('profile.email') }}
</label>
<input v-if="userProfile.isProfileEditing" v-model="userProfile.profileUser.email" type="email" class="input-field" :class="userProfile.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="userProfile.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
<input
v-if="userProfile.isProfileEditing"
v-model="userProfile.profileUser.email"
type="email"
class="input-field text-sm"
>
<div v-else :class="fieldValueClass">
{{ userProfile.profileUser.email || '-' }}
</div>
</div>
<div>
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="userProfile.isMobile ? 'text-xs mb-1' : ''">
<label :class="fieldLabelClass">
<Globe class="h-4 w-4" /> {{ $t('profile.phoneNumber') }}
</label>
<input v-if="userProfile.isProfileEditing" v-model="userProfile.profileUser.phone_number" type="text" class="input-field" :class="userProfile.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="userProfile.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
<input
v-if="userProfile.isProfileEditing"
v-model="userProfile.profileUser.phone_number"
type="text"
class="input-field text-sm"
>
<div v-else :class="fieldValueClass">
{{ userProfile.profileUser.phone_number || '-' }}
</div>
</div>
</div>
</div>
<div class="rounded-3xl border border-default bg-surface p-8 shadow-sm">
<h3 class="mb-6 flex items-center gap-3 text-2xl font-bold text-primary">
<div class="rounded-2xl border border-default bg-surface p-5 shadow-sm md:p-6">
<h3 class="section-title mb-5 flex items-center gap-2">
<Palette class="h-5 w-5 text-brand-500" />
{{ $t('profile.preferences') }}
</h3>
<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div>
<label class="mb-2 block text-sm font-medium text-muted">{{ $t('workspace.languageLabel') }}</label>
<select v-model="userProfile.profileUser.language" :disabled="!userProfile.isProfileEditing" class="input-field h-[58px]">
<label class="mb-1.5 block text-sm font-medium text-muted">{{ $t('workspace.languageLabel') }}</label>
<select
v-model="userProfile.profileUser.language"
class="select-field text-sm"
:disabled="!userProfile.isProfileEditing"
>
<option value="en">English</option>
<option value="zh-CN">{{ $t('workspace.lang.zhCN') }}</option>
<option value="zh-TW">{{ $t('workspace.lang.zhTW') }}</option>
@@ -172,7 +238,7 @@ const userProfile = inject(WORKSPACE_KEY)!;
</select>
</div>
<div>
<label class="mb-2 block text-sm font-medium text-muted">{{ $t('profile.theme') }}</label>
<label class="mb-1.5 block text-sm font-medium text-muted">{{ $t('profile.theme') }}</label>
<div
class="segment-control segment-control--cols-3 segment-control--md"
role="radiogroup"
@@ -183,9 +249,9 @@ const userProfile = inject(WORKSPACE_KEY)!;
:key="item.value"
type="button"
role="radio"
class="segment-item"
:aria-checked="userProfile.profileUser.theme_preference === item.value"
:disabled="!userProfile.isProfileEditing"
class="segment-item"
:class="userProfile.profileUser.theme_preference === item.value ? 'segment-item--active' : ''"
@click="userProfile.profileUser.theme_preference = item.value"
>
@@ -195,7 +261,6 @@ const userProfile = inject(WORKSPACE_KEY)!;
</div>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,153 @@
<!--
features/voucher-check/components/VoucherCheckChatPanel.vue
用途:立账凭证 Chat 主区:检核任务 / 企微发送记录 / 通知配置 Tab,当前 Tab 内批次明细下钻。
依赖:workspace 立账凭证列表与详情、VoucherCheckNotifyConfigPanel、voucherCheckChat.utils、vue-router query、auth.store。
逻辑:由 ChatViewContent 在 agent_code=voucher_check 时替换消息列表与输入框;
view / runId / runNo 写入 /chat/:agentId 查询参数;通知配置仅平台管理员可见可改。
-->
<script setup lang="ts">
import { computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import AccountingVoucherCheckDetailView from '@/features/workspace/views/AccountingVoucherCheckDetailView.vue';
import AccountingVoucherCheckView from '@/features/workspace/views/AccountingVoucherCheckView.vue';
import type { VoucherCheckChatView } from '../constants';
import {
buildVoucherCheckChatQuery,
parseVoucherCheckChatQuery,
} from '../utils/voucherCheckChat.utils';
import VoucherCheckNotifyConfigPanel from './VoucherCheckNotifyConfigPanel.vue';
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const auth = useAuthStore();
const isAdmin = computed(() => Boolean(auth.isAdmin));
const parsedQuery = computed(() => parseVoucherCheckChatQuery(
route.query.view,
route.query.runId,
route.query.runNo,
));
const activeView = computed<VoucherCheckChatView>(() => parsedQuery.value.view);
const detailRunId = computed(() => parsedQuery.value.runId);
const detailRunNo = computed(() => parsedQuery.value.runNo);
const tabs = computed(() => {
const items: Array<{ key: VoucherCheckChatView; label: string }> = [
{ key: 'tasks', label: t('workspace.voucherCheck.tabTasks') },
{ key: 'notifications', label: t('workspace.voucherCheck.tabNotifications') },
];
if (isAdmin.value) {
items.push({ key: 'notifyConfig', label: t('workspace.voucherCheck.tabNotifyConfig') });
}
return items;
});
/**
* 把当前 Tab / 批次明细写入 Chat 路由,保持刷新与旧地址重定向可用。
* 核心逻辑:replace 避免 Tab 切换堆积历史;切 Tab 时清掉 runId。
*/
async function syncQuery(
view: VoucherCheckChatView,
runId: number | null,
runNo: string | null = null,
): Promise<void> {
const nextQuery = buildVoucherCheckChatQuery(view, runId, runNo);
const currentView = String(route.query.view || '');
const currentRunId = String(route.query.runId || '');
const currentRunNo = String(route.query.runNo || '');
if (
currentView === nextQuery.view
&& currentRunId === (nextQuery.runId || '')
&& currentRunNo === (nextQuery.runNo || '')
) return;
const query = { ...route.query, ...nextQuery };
if (!runId) {
delete query.runId;
delete query.runNo;
}
await router.replace({ params: { ...route.params }, query });
}
/**
* 切换主 Tab;详情下钻随 Tab 关闭,避免第四个隐形页。
*/
function selectView(view: VoucherCheckChatView): void {
void syncQuery(view, null);
}
/**
* 在当前 Tab 内打开批次明细。
*/
function openDetail(payload: { runId: number; runNo?: string | null }): void {
void syncQuery(activeView.value, payload.runId, payload.runNo || null);
}
/**
* 从明细返回当前 Tab 列表。
*/
function closeDetail(): void {
void syncQuery(activeView.value, null);
}
watch(
() => route.query.view,
(rawView) => {
if (rawView) return;
void syncQuery(activeView.value, detailRunId.value, detailRunNo.value);
},
{ immediate: true },
);
watch(
[isAdmin, activeView],
() => {
if (!isAdmin.value && activeView.value === 'notifyConfig') {
void syncQuery('tasks', null);
}
},
);
</script>
<template>
<section class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-[var(--surface-muted,#f4f7fb)]">
<div class="px-5 pt-5">
<h1 class="text-xl font-bold text-primary">{{ t('workspace.voucherCheck.title') }}</h1>
<p class="mt-1 text-sm text-muted">{{ t('workspace.voucherCheck.subtitle') }}</p>
</div>
<div class="mt-4 flex gap-0 border-b border-default px-5">
<button
v-for="tab in tabs"
:key="tab.key"
type="button"
class="mb-[-1px] border-b-2 px-4 py-2.5 text-sm font-bold"
:class="activeView === tab.key
? 'border-brand-500 text-brand-600'
: 'border-transparent text-muted hover:text-secondary'"
@click="selectView(tab.key)"
>
{{ tab.label }}
</button>
</div>
<div class="min-h-0 flex-1 overflow-auto px-5 py-4">
<VoucherCheckNotifyConfigPanel v-if="activeView === 'notifyConfig' && isAdmin" />
<AccountingVoucherCheckDetailView
v-else-if="detailRunId"
:run-id="detailRunId"
:run-no="detailRunNo"
embedded
@close="closeDetail"
/>
<AccountingVoucherCheckView
v-else
:active-tab="activeView === 'notifications' ? 'notifications' : 'tasks'"
embedded
@open-detail="openDetail"
/>
</div>
</section>
</template>
@@ -0,0 +1,201 @@
<!--
features/voucher-check/components/VoucherCheckNotifyConfigPanel.vue
用途:立账凭证 Chat「通知配置」Tab:按六类必检文件分别选择企微接收人。
依赖:voucherCheck.api、UserPickerDialog、vue-i18n、useMessage。
逻辑:仅平台管理员可见;规则来自销售 Profile,接收人写入独立配置表;
行内只展示标签 +「选择」,点选打开公共选人弹窗;未绑企微的人可勾选但发送时会被跳过。
-->
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Loader2 } from 'lucide-vue-next';
import { useMessage } from '@/shared/composables/useMessage';
import UserPickerDialog from '@/shared/components/UserPickerDialog.vue';
import { userPickerLabel } from '@/shared/utils/userPicker.utils';
import {
getVoucherCheckNotifyConfig,
saveVoucherCheckNotifyConfig,
type VoucherCheckNotifyRule,
type VoucherCheckNotifyUser,
} from '@/features/workspace/api/voucherCheck.api';
const { t } = useI18n();
const msg = useMessage();
const loading = ref(false);
const saving = ref(false);
const profileCode = ref('sales');
const rules = ref<VoucherCheckNotifyRule[]>([]);
const users = ref<VoucherCheckNotifyUser[]>([]);
const updatedAt = ref<string | null>(null);
const pickerOpen = ref(false);
const pickerRuleCode = ref<string | null>(null);
const userMap = computed(() => {
const next = new Map<number, VoucherCheckNotifyUser>();
for (const user of users.value) next.set(user.id, user);
return next;
});
const pickerRule = computed(() =>
rules.value.find((rule) => rule.code === pickerRuleCode.value) || null,
);
const pickerSelectedIds = computed(() => pickerRule.value?.user_ids || []);
/**
* 打开某文件类型的公共选人弹窗。
*/
function openPicker(ruleCode: string): void {
pickerRuleCode.value = ruleCode;
pickerOpen.value = true;
}
/**
* 弹窗确定后写回该行接收人。
*/
function applyPickerSelection(userIds: number[]): void {
const row = rules.value.find((rule) => rule.code === pickerRuleCode.value);
if (row) row.user_ids = [...userIds];
pickerRuleCode.value = null;
}
/**
* 从行内标签移除接收人,不必打开弹窗。
*/
function removeUser(ruleCode: string, userId: number): void {
const row = rules.value.find((rule) => rule.code === ruleCode);
if (!row) return;
row.user_ids = row.user_ids.filter((id) => id !== userId);
}
/**
* 加载六行规则与候选人。
*/
async function loadConfig(): Promise<void> {
loading.value = true;
try {
const data = await getVoucherCheckNotifyConfig(profileCode.value);
profileCode.value = data.profile_code || 'sales';
rules.value = (data.rules || []).map((rule) => ({
...rule,
user_ids: Array.isArray(rule.user_ids) ? [...rule.user_ids] : [],
}));
users.value = data.users || [];
updatedAt.value = data.updated_at || null;
} catch (error: any) {
msg.error(error?.message || t('workspace.voucherCheck.notifyConfigLoadFailed'));
} finally {
loading.value = false;
}
}
/**
* 保存当前六行选人结果。
*/
async function saveConfig(): Promise<void> {
saving.value = true;
try {
const recipients: Record<string, number[]> = {};
for (const rule of rules.value) recipients[rule.code] = [...rule.user_ids];
const data = await saveVoucherCheckNotifyConfig({
profile_code: profileCode.value,
recipients,
});
rules.value = (data.rules || []).map((rule) => ({
...rule,
user_ids: Array.isArray(rule.user_ids) ? [...rule.user_ids] : [],
}));
users.value = data.users || [];
updatedAt.value = data.updated_at || null;
msg.success(t('workspace.voucherCheck.notifyConfigSaved'));
} catch (error: any) {
msg.error(error?.message || t('workspace.voucherCheck.notifyConfigSaveFailed'));
} finally {
saving.value = false;
}
}
onMounted(() => {
void loadConfig();
});
</script>
<template>
<article class="overflow-hidden rounded-2xl border border-default bg-surface">
<div class="flex flex-wrap items-start justify-between gap-3 border-b border-default px-4 py-3">
<div>
<h2 class="text-sm font-semibold text-primary">{{ t('workspace.voucherCheck.notifyConfigTitle') }}</h2>
<p class="mt-1 text-sm text-muted">{{ t('workspace.voucherCheck.notifyConfigSubtitle') }}</p>
<p v-if="updatedAt" class="mt-1 text-xs text-muted">
{{ t('workspace.voucherCheck.notifyConfigUpdatedAt', { time: updatedAt }) }}
</p>
</div>
<button
type="button"
class="inline-flex items-center gap-1 rounded-xl bg-brand-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
:disabled="loading || saving"
@click="saveConfig"
>
<Loader2 v-if="saving" class="h-3.5 w-3.5 animate-spin" />
{{ t('workspace.voucherCheck.notifyConfigSave') }}
</button>
</div>
<div v-if="loading" class="flex items-center justify-center gap-2 px-4 py-10 text-sm text-muted">
<Loader2 class="h-4 w-4 animate-spin" />
{{ t('workspace.voucherCheck.loading') }}
</div>
<div v-else class="divide-y divide-default">
<div
v-for="rule in rules"
:key="rule.code"
class="grid gap-3 px-4 py-3 md:grid-cols-[220px_minmax(0,1fr)] md:items-center"
>
<div>
<p class="text-sm font-semibold text-primary">{{ rule.name }}</p>
<p class="mt-0.5 text-xs text-muted">
{{ t('workspace.voucherCheck.notifyConfigFolder', { folder: rule.type_folder || '—' }) }}
</p>
</div>
<div class="inline-flex w-fit min-w-[18rem] max-w-full flex-wrap items-center gap-1.5 rounded-xl border border-default bg-surface px-2 py-1.5">
<span
v-for="userId in rule.user_ids"
:key="userId"
class="inline-flex items-center gap-1 rounded-lg bg-blue-50 px-2 py-0.5 text-xs font-medium text-blue-700"
>
{{ userPickerLabel(userMap.get(userId), userId) }}
<span
v-if="userMap.get(userId) && !userMap.get(userId)?.wecom_bound"
class="text-amber-600"
>!</span>
<button
type="button"
class="ml-0.5 text-blue-400 hover:text-blue-600"
@click="removeUser(rule.code, userId)"
>✕</button>
</span>
<span v-if="rule.user_ids.length === 0" class="text-sm text-muted">
{{ t('workspace.voucherCheck.notifyConfigEmptyUsers') }}
</span>
<button
type="button"
class="ml-auto shrink-0 rounded-lg border border-blue-200 bg-blue-50 px-2.5 py-1 text-xs font-semibold text-brand-600 hover:bg-blue-100"
@click="openPicker(rule.code)"
>
{{ t('common.userPicker.select') }}
</button>
</div>
</div>
</div>
<UserPickerDialog
v-model="pickerOpen"
:users="users"
:selected-ids="pickerSelectedIds"
:title="t('workspace.voucherCheck.notifyConfigPickerTitle')"
@confirm="applyPickerSelection"
/>
</article>
</template>
@@ -0,0 +1,10 @@
/**
* features/voucher-check/constants.ts
* 用途:立账凭证 Chat Tab 与深链约定。
* 依赖:无。
* 逻辑:Chat 主区 Tab 与旧工作台重定向共用 view;详情用 runId,可选 runNo 仅作标题展示。
* notifyConfig 仅管理员可见,解析仍接受该值以便深链打开后由面板做权限回退。
*/
export const VOUCHER_CHECK_CHAT_VIEWS = ['tasks', 'notifications', 'notifyConfig'] as const;
export type VoucherCheckChatView = (typeof VOUCHER_CHECK_CHAT_VIEWS)[number];
@@ -0,0 +1,51 @@
/**
* features/voucher-check/utils/voucherCheckChat.utils.test.ts
* 用途:锁定立账凭证 Chat 深链 query 的解析与回写规则。
*/
import { describe, expect, it } from 'vitest';
import {
buildVoucherCheckChatQuery,
parseVoucherCheckChatQuery,
} from './voucherCheckChat.utils';
describe('parseVoucherCheckChatQuery', () => {
it('accepts tasks / notifications / notifyConfig and a positive runId', () => {
expect(parseVoucherCheckChatQuery('notifications', '12', 'VC-202608-001')).toEqual({
view: 'notifications',
runId: 12,
runNo: 'VC-202608-001',
});
expect(parseVoucherCheckChatQuery('notifyConfig', null, null)).toEqual({
view: 'notifyConfig',
runId: null,
runNo: null,
});
});
it('falls back to tasks for unknown view and ignores invalid runId', () => {
expect(parseVoucherCheckChatQuery('unknown', 'abc', ' ')).toEqual({
view: 'tasks',
runId: null,
runNo: null,
});
expect(parseVoucherCheckChatQuery(undefined, '0', undefined)).toEqual({
view: 'tasks',
runId: null,
runNo: null,
});
});
});
describe('buildVoucherCheckChatQuery', () => {
it('always writes view and omits runId on list pages', () => {
expect(buildVoucherCheckChatQuery('notifications', null)).toEqual({ view: 'notifications' });
});
it('keeps the current tab when drilling into a run', () => {
expect(buildVoucherCheckChatQuery('notifications', 9, 'VC-9')).toEqual({
view: 'notifications',
runId: '9',
runNo: 'VC-9',
});
});
});
@@ -0,0 +1,52 @@
/**
* features/voucher-check/utils/voucherCheckChat.utils.ts
* 用途:解析立账凭证 Chat 的 view / runId / runNo 查询参数。
* 依赖:voucher-check/constants。
* 逻辑:旧工作台重定向与 Chat Tab 共用;非法 view 回退检核任务。notifyConfig 为管理员通知配置页。
*/
import { VOUCHER_CHECK_CHAT_VIEWS, type VoucherCheckChatView } from '../constants';
export interface VoucherCheckChatQuery {
view: VoucherCheckChatView;
runId: number | null;
runNo: string | null;
}
/**
* 把路由 query 归一成立账凭证 Chat 视图。
* 核心逻辑:只接受 tasks / notifications / notifyConfig;runId 必须是正整数才进入批次明细;runNo 仅展示。
* @param rawView - 路由 query.view
* @param rawRunId - 路由 query.runId
* @param rawRunNo - 路由 query.runNo
*/
export function parseVoucherCheckChatQuery(
rawView: unknown,
rawRunId: unknown,
rawRunNo: unknown,
): VoucherCheckChatQuery {
const view = VOUCHER_CHECK_CHAT_VIEWS.includes(String(rawView) as VoucherCheckChatView)
? String(rawView) as VoucherCheckChatView
: 'tasks';
const parsed = Number(rawRunId);
const runId = Number.isInteger(parsed) && parsed > 0 ? parsed : null;
const runNo = typeof rawRunNo === 'string' && rawRunNo.trim() ? rawRunNo.trim() : null;
return { view, runId, runNo };
}
/**
* 把立账凭证视图写回 Chat 路由 query,便于刷新与旧工作台重定向共用同一深链。
* 核心逻辑:始终带 view;仅在下钻明细时带 runId / runNo,避免空 query 污染地址栏。
* @param view - 当前 Tab
* @param runId - 明细批次排程 ID;列表态传 null
* @param runNo - 批次号,仅详情标题使用
*/
export function buildVoucherCheckChatQuery(
view: VoucherCheckChatView,
runId: number | null,
runNo: string | null = null,
): Record<string, string> {
const query: Record<string, string> = { view };
if (runId) query.runId = String(runId);
if (runId && runNo) query.runNo = runNo;
return query;
}
@@ -0,0 +1,85 @@
<!--
features/voucher-check/views/VoucherCheckChatRedirect.vue
用途:把旧工作台立账凭证 URL 转到对应 Chat Agent 深链。
依赖:listUserAgents、isVoucherCheckAgent、voucherCheckChat.utils。
逻辑:按路径还原 view / runId / runNo,再在当前用户 Agent 列表中定位 voucher_check;
未授权时提示并回应用管理。本页不渲染业务 UI。
-->
<script setup lang="ts">
import { onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { listUserAgents } from '@/features/auth/api/user.api';
import { useMessage } from '@/shared/composables/useMessage';
import { isVoucherCheckAgent } from '@/shared/utils/agent-registry.utils';
import { WORKSPACE_PATHS } from '@/features/workspace/constants/routes';
import type { VoucherCheckChatView } from '../constants';
import { buildVoucherCheckChatQuery } from '../utils/voucherCheckChat.utils';
const route = useRoute();
const router = useRouter();
const { t } = useI18n();
const msg = useMessage();
/**
* 从旧工作台路径还原 Chat Tab 与批次明细。
* 核心逻辑:runs/:runId 进入当前 Tab 下钻;?run_id= 兼容旧列表深链;?view=notifications 打开发送记录。
*/
function resolveLegacyTarget(): {
view: VoucherCheckChatView;
runId: number | null;
runNo: string | null;
} {
const path = String(route.path || '');
const view: VoucherCheckChatView = String(route.query.view || '') === 'notifications'
? 'notifications'
: 'tasks';
const runNo = typeof route.query.runNo === 'string' && route.query.runNo.trim()
? route.query.runNo.trim()
: null;
const detailMatch = path.match(/\/accounting-voucher-check\/runs\/(\d+)/);
if (detailMatch) {
return { view, runId: Number(detailMatch[1]), runNo };
}
const queryRunId = Number(Array.isArray(route.query.run_id) ? route.query.run_id[0] : route.query.run_id);
if (Number.isInteger(queryRunId) && queryRunId > 0) {
return { view, runId: queryRunId, runNo };
}
return { view, runId: null, runNo: null };
}
/**
* 查找当前用户可用的立账凭证 Agent 并跳转 Chat。
* 核心逻辑:admin 与已授权用户都能在 /api/agents 看到该 Agent;找不到则视为无权限。
*/
async function redirectToChat(): Promise<void> {
const { view, runId, runNo } = resolveLegacyTarget();
try {
const agents = await listUserAgents();
const agent = Array.isArray(agents) ? agents.find((item) => isVoucherCheckAgent(item)) : null;
const agentId = Number(agent?.id);
if (!Number.isInteger(agentId) || agentId <= 0) {
msg.warning(t('errors.codes.VOUCHER_CHECK_FORBIDDEN'));
await router.replace(WORKSPACE_PATHS.applications);
return;
}
await router.replace({
path: `/chat/${agentId}`,
query: buildVoucherCheckChatQuery(view, runId, runNo),
});
} catch {
msg.warning(t('errors.codes.VOUCHER_CHECK_FORBIDDEN'));
await router.replace(WORKSPACE_PATHS.applications);
}
}
onMounted(() => {
void redirectToChat();
});
</script>
<template>
<div class="flex min-h-[40vh] items-center justify-center text-sm text-muted">
{{ t('chat.loadingAgent') }}
</div>
</template>
@@ -24,11 +24,57 @@ export interface ShippingMyTodosCount {
processing: number;
done: number;
total_pending_badge: number;
/** 待处理桶按可动作生命周期阶段的全量聚合计数(阶段筛选 tab)。 */
stage_counts?: {
intake_parse: number;
order_review: number;
fulfillment_prep: number;
freight_upload: number;
};
/** done 桶终态拆分:通知完成 vs 复核驳回/作废。 */
done_counts?: {
upload_complete: number;
reject_void: number;
};
}
/** 已完成通知明细行(通知完成报表):标准 12 字段 + 溯源编号。 */
export interface ShippingDoneLineItem {
task_no: string;
business_no: string | null;
customer_name: string | null;
customer_code: string | null;
order_date: string | null;
line_no: number;
part_number: string | null;
qty: number | null;
required_date: string | null;
customer_po_number: string | null;
/** 无数据源,契约占位恒为 null(页面与导出留空)。 */
used_qty: number | null;
open_qty: number | null;
source_order_number: string | null;
unit_price: number | null;
}
export interface ShippingDoneLinesPage {
items: ShippingDoneLineItem[];
page: number;
page_size: number;
total: number;
}
export interface ShippingDoneLineFilters {
customer?: string;
part_number?: string;
notice_date_from?: string;
notice_date_to?: string;
}
/**
* 分页拉取「我的待办」。
* @param params.bucket - pending | processing | done
* @param params.terminal_kind - done 桶终态子视图(upload_complete | reject_void)
*/
export function listWorkspaceShippingMyTodos(params?: {
bucket?: 'pending' | 'processing' | 'done' | string;
@@ -37,6 +83,7 @@ export function listWorkspaceShippingMyTodos(params?: {
todo_category?: string;
customer?: string;
task_no?: string;
terminal_kind?: string;
}) {
const sp = new URLSearchParams();
if (params?.bucket) sp.set('bucket', params.bucket);
@@ -45,6 +92,7 @@ export function listWorkspaceShippingMyTodos(params?: {
if (params?.todo_category) sp.set('todo_category', params.todo_category);
if (params?.customer) sp.set('customer', params.customer);
if (params?.task_no) sp.set('task_no', params.task_no);
if (params?.terminal_kind) sp.set('terminal_kind', params.terminal_kind);
const q = sp.toString();
return requestJson<ShippingMyTodosPage>(
`/api/workspace/shipping-tasks/my-todos${q ? `?${q}` : ''}`,
@@ -58,6 +106,68 @@ export function countWorkspaceShippingMyTodos() {
return requestJson<ShippingMyTodosCount>('/api/workspace/shipping-tasks/my-todos/count');
}
/**
* 分页拉取已完成通知的平铺明细行(通知完成报表)。
* 明细行跨 Notice 混排、不按 OT 聚合,仅含已核验上传成功的通知。
*/
export function listWorkspaceShippingDoneLines(params?: {
page?: number;
page_size?: number;
} & ShippingDoneLineFilters) {
const sp = new URLSearchParams();
if (params?.page) sp.set('page', String(params.page));
if (params?.page_size) sp.set('page_size', String(params.page_size));
if (params?.customer) sp.set('customer', params.customer);
if (params?.part_number) sp.set('part_number', params.part_number);
if (params?.notice_date_from) sp.set('notice_date_from', params.notice_date_from);
if (params?.notice_date_to) sp.set('notice_date_to', params.notice_date_to);
const q = sp.toString();
return requestJson<ShippingDoneLinesPage>(
`/api/workspace/shipping-tasks/my-todos/done-lines${q ? `?${q}` : ''}`,
);
}
/**
* 下载当前筛选下的已完成通知明细 Excel(固定 12 列标准格式,不含 OT 编号)。
* 核心逻辑:浏览器受控 a[download] 下载,后端复核可见性与筛选参数。
*/
export async function downloadWorkspaceShippingDoneLinesExcel(
filters?: ShippingDoneLineFilters,
): Promise<void> {
const sp = new URLSearchParams();
if (filters?.customer) sp.set('customer', filters.customer);
if (filters?.part_number) sp.set('part_number', filters.part_number);
if (filters?.notice_date_from) sp.set('notice_date_from', filters.notice_date_from);
if (filters?.notice_date_to) sp.set('notice_date_to', filters.notice_date_to);
const q = sp.toString();
const url = `/api/workspace/shipping-tasks/my-todos/done-lines/export${q ? `?${q}` : ''}`;
const { getAuthHeaders } = await import('@/shared/utils/auth');
const res = await fetch(url, { headers: getAuthHeaders() });
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(
(body as { error?: string; message?: string })?.error
|| (body as { message?: string })?.message
|| res.statusText,
);
}
const disposition = res.headers.get('content-disposition');
const blob = await res.blob();
const objectUrl = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = objectUrl;
const rawName = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || 'done-lines.xlsx';
try {
anchor.download = decodeURIComponent(rawName);
} catch {
anchor.download = rawName;
}
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
URL.revokeObjectURL(objectUrl);
}
export {
downloadWorkspaceShippingExcelFile,
markWorkspaceShippingManualUploaded,
@@ -1,8 +1,9 @@
/**
* features/workspace/api/voucherCheck.api.ts
* 用途:工作台立账凭证检核任务列表、批次明细、企微发送记录与强制重检 API 客户端。
* 用途:工作台立账凭证检核任务列表、最近一次检核、批次明细、企微发送记录、通知配置与强制重检 API 客户端。
* 依赖:@/shared/api/client、getAuthHeaders。
* 逻辑:AccountingVoucherCheckView / DetailView 调用;对应 /api/workspace/accounting-voucher-check/* 与排程 Excel 下载。
* 逻辑:AccountingVoucherCheckView / DetailView / VoucherCheckNotifyConfigPanel 调用;
* 对应 /api/workspace/accounting-voucher-check/* 与排程 Excel 下载。
*/
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
@@ -71,8 +72,45 @@ export interface VoucherCheckForceRunResponse {
status: string;
}
export interface VoucherCheckLatestStep {
step: string;
label?: string | null;
processed_count: number;
}
export interface VoucherCheckLatestRun {
schedule_run_id: number | null;
engine_run_id?: number | null;
run_no: string;
period_month: string | null;
mode: string;
status: string;
progress_percent: number;
subject_count: number;
archived_file_count: number;
missing_file_count: number;
missing_invoice_count: number;
processed_count: number;
started_at?: string | null;
finished_at?: string | null;
error_message?: string | null;
current_step?: VoucherCheckLatestStep | null;
}
/**
* 读取最近一次立账凭证检核(含排队/执行中),不跟列表 period/status。
* @returns 无任何批次时为 null
*/
export function getLatestVoucherCheckRun() {
return requestJson<VoucherCheckLatestRun | null>(
'/api/workspace/accounting-voucher-check/runs/latest',
{ headers: getAuthHeaders() },
);
}
/**
* 分页查询检核任务列表。
* @param params.period - YYYY 表示该年全部月份,YYYY-MM 表示单月
*/
export function listVoucherCheckRuns(params: {
period?: string;
@@ -136,6 +174,7 @@ export interface VoucherCheckNotificationsResponse {
/**
* 分页查询企微缺件汇总发送记录。
* @param params.period - YYYY 表示该年全部月份,YYYY-MM 表示单月
*/
export function listVoucherCheckNotifications(params?: {
period?: string;
@@ -184,6 +223,60 @@ export async function downloadVoucherCheckExcel(scheduleRunId: number, filename?
URL.revokeObjectURL(url);
}
export interface VoucherCheckNotifyUser {
id: number;
username: string;
real_name?: string | null;
employee_id?: string | null;
department?: string | null;
wecom_bound: boolean;
}
export interface VoucherCheckNotifyRule {
code: string;
name: string;
type_folder: string;
user_ids: number[];
}
export interface VoucherCheckNotifyConfig {
profile_code: string;
rules: VoucherCheckNotifyRule[];
users: VoucherCheckNotifyUser[];
updated_at?: string | null;
updated_by?: number | null;
}
/**
* 读取按文件类型的企微接收人(仅平台管理员)。
*/
export function getVoucherCheckNotifyConfig(profileCode?: string) {
const q = new URLSearchParams();
if (profileCode) q.set('profile_code', profileCode);
const qs = q.toString();
return requestJson<VoucherCheckNotifyConfig>(
`/api/workspace/accounting-voucher-check/notify-config${qs ? `?${qs}` : ''}`,
{ headers: getAuthHeaders() },
);
}
/**
* 保存按文件类型的企微接收人(仅平台管理员)。
*/
export function saveVoucherCheckNotifyConfig(payload: {
profile_code?: string;
recipients: Record<string, number[]>;
}) {
return requestJson<VoucherCheckNotifyConfig>(
'/api/workspace/accounting-voucher-check/notify-config',
{
method: 'PUT',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
},
);
}
/**
* 强制重检上一个自然月(不走增量跳过)。
*/
@@ -1,23 +1,21 @@
<script setup lang="ts">
/**
* features/workspace/components/WorkspaceSidebar.vue
* 工作台左侧导航:子路由链接、货代/合同付款二级菜单、关联服务入口、返回聊天与退出登录。
* 依赖:WORKSPACE_PATHS、workspace.context、ExternalSystemLinks、auth.store、contract-payment 权限常量。
* 逻辑:底部关联服务复用 ws-nav-btn,与返回聊天/退出登录对齐;合同付款菜单仅在具备 contract_payment.access 时展示。
* 工作台左侧导航:子路由链接、货代二级菜单、关联服务入口、返回聊天与退出登录。
* 依赖:WORKSPACE_PATHS、workspace.context、ExternalSystemLinks。
* 逻辑:底部关联服务复用 ws-nav-btn,与返回聊天/退出登录对齐。合同付款、立账凭证已迁入 Chat Agent,不再在此展示。
* 矮屏时中间导航独立滚动,底部返回聊天/退出登录始终留在视口内。
*/
import { computed, inject, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import {
LayoutGrid, Bot, FileText, User, LogOut, Edit, Megaphone, Clock, Package, PanelLeftClose, PanelLeftOpen, ClipboardCheck, CalendarClock,
LayoutGrid, Bot, FileText, User, LogOut, Edit, Megaphone, Clock, Package, PanelLeftClose, PanelLeftOpen,
ChevronDown, ChevronRight, ContactRound, Inbox, FileDown,
} from 'lucide-vue-next';
import { WORKSPACE_PATHS } from '../constants/routes';
import { WORKSPACE_KEY } from '../composables/workspace.context';
import { useShippingTodoBadge } from '../composables/useShippingTodoBadge';
import { ExternalSystemLinks } from '@/features/sso';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import { CONTRACT_PAYMENT_ACCESS_PERMISSION } from '@/features/contract-payment/constants';
const props = defineProps<{
collapsed?: boolean;
@@ -27,15 +25,7 @@ const ws = inject(WORKSPACE_KEY)! as any;
const route = useRoute();
const shippingRouteNames = ['workspace-shipping-customers', 'workspace-shipping-tasks', 'workspace-shipping-my-tasks'] as const;
const shippingExpanded = ref(false);
const contractPaymentRouteNames = ['workspace-contract-payment', 'workspace-contract-payment-review', 'workspace-contract-payment-weekly-batches'] as const;
const contractPaymentExpanded = ref(false);
const isAdmin = computed(() => String(ws.currentUser?.role || '').trim().toLowerCase() === 'admin');
const auth = useAuthStore();
/**
* 当前用户是否可看见并进入合同付款预警工作台。
* 核心逻辑:读取登录态 feature_permissions.contract_payment.access;admin 默认 true,普通用户需显式授予。
*/
const canAccessContractPayment = computed(() => auth.hasFeaturePermission(CONTRACT_PAYMENT_ACCESS_PERMISSION));
const { pendingBadge, startShippingTodoBadgePolling, stopShippingTodoBadgePolling } = useShippingTodoBadge();
const primaryLinkItems = [
@@ -46,7 +36,6 @@ const primaryLinkItems = [
] as const;
const secondaryLinkItems = [
{ path: WORKSPACE_PATHS.accountingVoucherCheck, labelKey: 'workspace.nav.accountingVoucherCheck', icon: ClipboardCheck, match: ['workspace-accounting-voucher-check', 'workspace-accounting-voucher-check-detail'] },
{ path: WORKSPACE_PATHS.feedback, labelKey: 'workspace.nav.feedback', icon: Edit, match: ['workspace-feedback'] },
{ path: WORKSPACE_PATHS.updates, labelKey: 'workspace.nav.updates', icon: Megaphone, match: ['workspace-updates'] },
] as const;
@@ -61,16 +50,13 @@ function isActive(match: readonly string[]) {
return match.includes(String(route.name || ''));
}
/** 当前路由进入货代或合同付款子页面时自动展开对应一级菜单,保证激活项可见。 */
/** 当前路由进入货代子页面时自动展开对应一级菜单,保证激活项可见。 */
watch(
() => route.name,
(routeName) => {
if (shippingRouteNames.includes(String(routeName || '') as typeof shippingRouteNames[number])) {
shippingExpanded.value = true;
}
if (contractPaymentRouteNames.includes(String(routeName || '') as typeof contractPaymentRouteNames[number])) {
contractPaymentExpanded.value = true;
}
},
{ immediate: true },
);
@@ -84,15 +70,6 @@ const toggleShippingMenu = (): void => {
shippingExpanded.value = !shippingExpanded.value;
};
/** 展开或收起合同付款预警目录;侧栏折叠时图标直接进入合同台账。 */
const toggleContractPaymentMenu = (): void => {
if (props.collapsed) {
void ws.router.push(WORKSPACE_PATHS.contractPayment);
return;
}
contractPaymentExpanded.value = !contractPaymentExpanded.value;
};
onMounted(() => {
startShippingTodoBadgePolling();
});
@@ -199,48 +176,6 @@ onBeforeUnmount(() => {
</RouterLink>
</div>
</div>
<div v-if="canAccessContractPayment">
<button
type="button"
class="ws-nav-btn w-full"
:class="[
{ 'ws-nav-btn--active': isActive(contractPaymentRouteNames) },
collapsed ? 'justify-center px-0' : '',
]"
:title="$t('workspace.nav.contractPayment')"
@click="toggleContractPaymentMenu"
>
<CalendarClock class="h-[18px] w-[18px]" />
<span v-if="!collapsed" class="flex-1">{{ $t('workspace.nav.contractPayment') }}</span>
<component v-if="!collapsed" :is="contractPaymentExpanded ? ChevronDown : ChevronRight" class="h-4 w-4" />
</button>
<div v-if="!collapsed && contractPaymentExpanded" class="mt-1 space-y-1 pl-5">
<RouterLink
:to="WORKSPACE_PATHS.contractPayment"
class="ws-nav-btn py-2.5 text-[13px]"
:class="{ 'ws-nav-btn--active': isActive(['workspace-contract-payment']) }"
>
<CalendarClock class="h-4 w-4" />
<span>{{ $t('workspace.nav.contractPaymentLedger') }}</span>
</RouterLink>
<RouterLink
:to="WORKSPACE_PATHS.contractPaymentReview"
class="ws-nav-btn py-2.5 text-[13px]"
:class="{ 'ws-nav-btn--active': isActive(['workspace-contract-payment-review']) }"
>
<ClipboardCheck class="h-4 w-4" />
<span>{{ $t('workspace.nav.contractPaymentReview') }}</span>
</RouterLink>
<RouterLink
:to="WORKSPACE_PATHS.contractPaymentWeeklyBatches"
class="ws-nav-btn py-2.5 text-[13px]"
:class="{ 'ws-nav-btn--active': isActive(['workspace-contract-payment-weekly-batches']) }"
>
<Inbox class="h-4 w-4" />
<span>{{ $t('workspace.nav.contractPaymentWeeklyBatches') }}</span>
</RouterLink>
</div>
</div>
<RouterLink
v-for="item in secondaryLinkItems"
:key="item.path"
@@ -1,7 +1,8 @@
/**
* features/workspace/constants/routes.ts
* 工作台子路由 path 常量,以及旧 ?view= 查询参数到新 path 的映射。
* 立账凭证批次明细:accountingVoucherCheckDetail(scheduleRunId)。
* 立账凭证路径仍保留,供旧书签落到 Chat 重定向页。
* 合同付款路径仍保留,供旧书签落到 Chat 重定向页。
*/
export const WORKSPACE_PATHS = {
root: '/workspace',
@@ -0,0 +1,181 @@
<!--
features/workspace/shipping-task-center/ShippingDoneLineReport.vue
用途:已完成桶「通知完成」子视图——跨 OT 平铺的明细行报表(13 列 + 筛选 + 导出)。
依赖:shipping-tasks.api 类型;导出下载由父级执行。
逻辑:只读报表(无抽屉、无行操作);首列 OT/business 编号仅页面展示,
导出为固定 12 列标准格式(后端裁决);分页按明细行计。
-->
<script setup lang="ts">
import { Download } from 'lucide-vue-next';
import type { ShippingDoneLineItem } from '@/features/workspace/api/shipping-tasks.api';
import type { ShippingDoneLineFilters } from '@/features/workspace/api/shipping-tasks.api';
const props = defineProps<{
items: ShippingDoneLineItem[];
total: number;
page: number;
pageSize: number;
loading?: boolean;
exportBusy?: boolean;
filters?: ShippingDoneLineFilters;
}>();
const emit = defineEmits<{
(event: 'update:filters', value: ShippingDoneLineFilters): void;
(event: 'apply'): void;
(event: 'page-change', page: number): void;
(event: 'export'): void;
}>();
const totalPages = () => Math.max(1, Math.ceil(props.total / props.pageSize));
function setFilter(key: keyof ShippingDoneLineFilters, event: Event) {
const value = String((event.target as HTMLInputElement).value || '');
emit('update:filters', { ...props.filters, [key]: value });
}
function onExport(): void {
emit('export');
}
</script>
<template>
<div class="space-y-3">
<div class="flex flex-wrap items-end gap-3 rounded-2xl border border-default bg-surface px-4 py-3">
<label class="space-y-1">
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.customer') }}</span>
<input
type="text"
class="input-field text-sm min-w-[10rem]"
:value="filters?.customer || ''"
:placeholder="$t('workspace.shippingNotice.myTodos.filters.customerPlaceholder')"
data-testid="done-lines-filter-customer"
@change="setFilter('customer', $event)"
@keyup.enter="emit('apply')"
>
</label>
<label class="space-y-1">
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.partNumber') }}</span>
<input
type="text"
class="input-field text-sm min-w-[10rem]"
:value="filters?.part_number || ''"
data-testid="done-lines-filter-part"
@change="setFilter('part_number', $event)"
@keyup.enter="emit('apply')"
>
</label>
<label class="space-y-1">
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.dateFrom') }}</span>
<input
type="date"
class="input-field text-sm"
:value="filters?.notice_date_from || ''"
data-testid="done-lines-filter-date-from"
@change="setFilter('notice_date_from', $event)"
>
</label>
<label class="space-y-1">
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.dateTo') }}</span>
<input
type="date"
class="input-field text-sm"
:value="filters?.notice_date_to || ''"
data-testid="done-lines-filter-date-to"
@change="setFilter('notice_date_to', $event)"
>
</label>
<div class="flex gap-2">
<button
type="button"
class="rounded-xl bg-brand-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
:disabled="loading"
@click="emit('apply')"
>
{{ $t('workspace.shippingNotice.myTodos.filters.apply') }}
</button>
<button
type="button"
class="inline-flex items-center gap-1.5 rounded-xl border border-brand-300 px-3 py-1.5 text-sm font-medium text-brand-700 hover:bg-brand-50 disabled:opacity-50"
:disabled="exportBusy || loading || !total"
data-testid="done-lines-export"
@click="onExport"
>
<Download class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.myTodos.doneReport.export') }}
</button>
</div>
</div>
<div v-if="loading" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">
{{ $t('workspace.shippingNotice.loading') }}
</div>
<div v-else-if="!items.length" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">
{{ $t('workspace.shippingNotice.myTodos.empty') }}
</div>
<div v-else class="overflow-x-auto rounded-2xl border border-default bg-surface">
<table class="w-full min-w-[1200px] border-collapse text-[13px]" data-testid="done-lines-table">
<thead>
<tr class="border-b border-default bg-surface-soft/60 text-left text-xs text-muted">
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.taskNo') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.customer') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.customerCode') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.orderDate') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.lineNo') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.partNumber') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.qty') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.requiredDate') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.customerPo') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.usedQty') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.openQty') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.sourceOrderNo') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.unitPrice') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="line in items"
:key="`${line.task_no}-${line.line_no}`"
class="border-b border-[#f0f3f8]"
>
<td class="px-3 py-2 font-mono text-xs font-semibold text-primary">
{{ line.business_no || line.task_no }}
</td>
<td class="px-3 py-2">{{ line.customer_name || '—' }}</td>
<td class="px-3 py-2">{{ line.customer_code || '—' }}</td>
<td class="px-3 py-2 tabular-nums">{{ line.order_date || '—' }}</td>
<td class="px-3 py-2 tabular-nums">{{ line.line_no }}</td>
<td class="px-3 py-2 font-mono">{{ line.part_number || '—' }}</td>
<td class="px-3 py-2 tabular-nums">{{ line.qty ?? '' }}</td>
<td class="px-3 py-2 tabular-nums">{{ line.required_date || '—' }}</td>
<td class="px-3 py-2">{{ line.customer_po_number || '—' }}</td>
<td class="px-3 py-2 tabular-nums">{{ line.used_qty ?? '' }}</td>
<td class="px-3 py-2 tabular-nums">{{ line.open_qty ?? '' }}</td>
<td class="px-3 py-2 font-mono">{{ line.source_order_number || '—' }}</td>
<td class="px-3 py-2 tabular-nums">{{ line.unit_price ?? '' }}</td>
</tr>
</tbody>
</table>
</div>
<div v-if="totalPages() > 1" class="flex items-center justify-between gap-2 text-xs text-muted">
<button
type="button"
class="rounded-lg border border-default px-2 py-1 disabled:opacity-50"
:disabled="page <= 1 || loading"
@click="emit('page-change', page - 1)"
>
{{ $t('workspace.shippingNotice.pagination.previous') }}
</button>
<span>{{ page }}/{{ totalPages() }}</span>
<button
type="button"
class="rounded-lg border border-default px-2 py-1 disabled:opacity-50"
:disabled="page >= totalPages() || loading"
@click="emit('page-change', page + 1)"
>
{{ $t('workspace.shippingNotice.pagination.next') }}
</button>
</div>
</div>
</template>
@@ -0,0 +1,63 @@
<!--
features/workspace/shipping-task-center/ShippingStageTabs.vue
用途:阶段筛选 tab(全部 + 四个可动作阶段),计数来自后端全量聚合。
依赖:shippingTaskCenterShared 的 ACTIONABLE_TODO_STAGES 口径。
逻辑:点击切换筛选并向上同步;「通知完成」不再作为筛选维度(归 done 桶终态子视图)。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { ACTIONABLE_TODO_STAGES, type LifecycleStageCode } from './shippingTaskCenterShared';
const { t } = useI18n();
const props = defineProps<{
modelValue: 'all' | LifecycleStageCode;
/** 后端聚合的阶段计数(缺省按 0 展示)。 */
counts?: Partial<Record<LifecycleStageCode, number>>;
}>();
const emit = defineEmits<{
(event: 'update:modelValue', value: 'all' | LifecycleStageCode): void;
}>();
function countOf(stage: LifecycleStageCode): number {
return Number(props.counts?.[stage] ?? 0);
}
function stageLabel(stage: LifecycleStageCode): string {
return t(`workspace.shippingNotice.myTodos.lifecycleStages.${stage}`);
}
</script>
<template>
<div
class="flex flex-wrap gap-2"
data-testid="my-todos-lifecycle-stage-filter"
>
<button
type="button"
class="rounded-full px-3.5 py-1.5 text-sm font-medium transition-colors"
:class="modelValue === 'all'
? 'bg-brand-600 text-white'
: 'border border-default text-secondary hover:bg-surface-soft'"
data-testid="my-todos-stage-filter-all"
@click="emit('update:modelValue', 'all')"
>
{{ $t('workspace.shippingNotice.myTodos.filters.all') }}
</button>
<button
v-for="stage in ACTIONABLE_TODO_STAGES"
:key="stage"
type="button"
class="rounded-full px-3.5 py-1.5 text-sm font-medium transition-colors"
:class="modelValue === stage
? 'bg-brand-600 text-white'
: 'border border-default text-secondary hover:bg-surface-soft'"
:data-testid="`my-todos-stage-filter-${stage}`"
@click="emit('update:modelValue', stage)"
>
{{ stageLabel(stage) }}
<span class="ml-1 font-mono text-xs opacity-80">{{ countOf(stage) }}</span>
</button>
</div>
</template>
@@ -1,8 +1,10 @@
/**
* features/workspace/shipping-task-center/ShippingTaskCenterPage.notice-batch.spec.ts
* 用途:验收任务中心只按发货通知单 business_no 展示与执行货代批量操作。
* 用途:验收任务中心改版——紧凑表格、货代上传阶段限定批量、阶段 tab 后端计数、
* done 桶子视图(通知完成明细报表 / 驳回作废任务表)与详情抽屉。
* 依赖:ShippingTaskCenterPage、货代 API、我的待办 API、Vue Test Utils。
* 逻辑:正式 Notice 可选择并传 business_nos;Review/Intake 不能进入选择集;列表行只显示服务端投影的通知明细。
* 逻辑:批量仅正式 Notice 且货代上传阶段可选;明细行详情进抽屉(Teleport 到 body);
* 通知完成子视图消费 done-lines 平铺报表;驳回作废子视图带 terminal_kind 过滤。
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import { flushPromises, mount } from '@vue/test-utils';
@@ -14,6 +16,11 @@ const batchConfirm = vi.fn(async () => ({ results: [{ status: 'confirmed' }] }))
const batchRpa = vi.fn(async () => ({ results: [{ status: 'accepted' }] }));
const downloadArchive = vi.fn(async () => undefined);
const listTodos = vi.fn(async () => ({ items: [], page: 1, page_size: 20, total: 0 }));
const listDoneLines = vi.fn(async () => ({ items: [], page: 1, page_size: 50, total: 0 }));
const downloadDoneLinesExcel = vi.fn(async () => undefined);
const countTodos = vi.fn(async () => ({
pending: 0, processing: 0, done: 0, total_pending_badge: 0,
}));
vi.mock('@/features/chat/api/shipping.api', () => ({
SHIPPING_NOTICE_AGENT_CODE: 'shipping_notice',
@@ -26,7 +33,9 @@ vi.mock('@/features/chat/api/shipping.api', () => ({
vi.mock('@/features/workspace/api/shipping-tasks.api', () => ({
listWorkspaceShippingMyTodos: (...args: unknown[]) => listTodos(...args),
countWorkspaceShippingMyTodos: vi.fn(async () => ({ pending: 0, processing: 0, done: 0, total_pending_badge: 0 })),
countWorkspaceShippingMyTodos: (...args: unknown[]) => countTodos(...args),
listWorkspaceShippingDoneLines: (...args: unknown[]) => listDoneLines(...args),
downloadWorkspaceShippingDoneLinesExcel: (...args: unknown[]) => downloadDoneLinesExcel(...args),
}));
vi.mock('@/features/workspace/composables/useShippingTodoBadge', () => ({
@@ -53,6 +62,7 @@ const i18n = createI18n({
subtitle: '按文件查看进度',
lifecycleStages: {
filterLabel: '阶段',
viewStage: '查看阶段',
intake_parse: '接收解析',
order_review: '订单复核',
fulfillment_prep: '通知准备',
@@ -60,6 +70,12 @@ const i18n = createI18n({
upload_complete: '通知完成',
},
buckets: { pending: '待处理', processing: '处理中', done: '已完成' },
subTabs: { uploadComplete: '通知完成', rejectVoid: '复核驳回 / 已作废' },
table: {
no: '编号', stage: '阶段', summary: '状态摘要', lines: '项次',
lineUnit: '项', shortage: '缺 {count}', freightStatus: '货代状态',
},
terminal: { uploadComplete: '上传完成', rejectVoid: '复核驳回' },
filters: {
todoCategory: '待办类型', all: '全部', review: '待复核', exception: '异常',
manualUpload: '人工上传', intakeParse: '接收解析', customer: '客户',
@@ -75,9 +91,44 @@ const i18n = createI18n({
intakeParseBadge: '材料解析',
progressSummary: '当前阶段:{stage}',
progressBlocker: '当前阻断:{reason}',
viewStage: '查看阶段',
drawer: {
details: '逐行明细',
files: '文件',
close: '关闭',
exportExcel: '导出 Excel',
lineTable: {
lineNo: '行', partNumber: '料号', customerPartNumber: '客户料号',
reservationId: '预约号', shipmentQty: '本次发货', availableQty: '可用库存',
shortageQty: '缺口', status: '状态',
},
},
doneReport: {
export: '导出 Excel(当前筛选)',
exportStarted: '已开始下载',
filters: { customer: '客户', partNumber: '料号', dateFrom: '通知日期起', dateTo: '通知日期止' },
columns: {
taskNo: 'OT 编号', customer: '客户', customerCode: '客户编号', orderDate: '订单日期',
lineNo: '订单项次', partNumber: '料号', qty: '数量', requiredDate: '约定出货日期',
customerPo: '客户PO', usedQty: '已用数量', openQty: 'open qty',
sourceOrderNo: '订单单号', unitPrice: '单价',
},
},
},
openChat: '打开对话',
batch: {
selectAll: '全选当前页通知单',
selected: '已选 {count} 张',
download: '批量下载 Excel',
confirm: '批量确认已上传',
rpa: '批量发起 RPA',
clearSelection: '清除选择',
downloadStarted: '已开始下载',
success: '成功 {count} 张',
partialResult: '部分成功 {accepted}/{accepted}/{blocked}',
},
todo: { adminViewOnlyShort: '只读' },
actions: { failed: '操作失败' },
pagination: { previous: '上一页', next: '下一页' },
},
},
},
@@ -90,12 +141,17 @@ const routes = [{
component: ShippingTaskCenterPage,
}];
/** 待处理货代上传阶段 Notice:批量可选 + 列表投影。 */
function notice(businessNo: string, poNumber: string, partNumber: string) {
return {
id: Number(businessNo.slice(-2)), task_no: `SN-${businessNo}`, business_no: businessNo,
item_kind: 'task', todo_ref: `SN-${businessNo}`, source_type: 'post_ot_fulfillment_wave',
po_number: poNumber, customer_name: 'Customer', upload_status: 'pending',
notice_line_summary: [{ line_no: '10', part_number: partNumber, shipment_qty: '4', available_qty: '9' }],
ui_state: { stage: { code: 'freight_upload', label: '货代上传' }, lifecycle_entries: [] },
notice_line_summary: [
{ line_no: '10', part_number: partNumber, shipment_qty: '4', available_qty: '9' },
{ line_no: '20', part_number: `${partNumber}-B`, shipment_qty: '2', available_qty: '9', shortage_qty: 1 },
],
artifact_summary: { export_file_name: `${businessNo}.xlsx` },
};
}
@@ -115,12 +171,17 @@ async function mountPage() {
});
}
function drawerText(): string {
return document.body.querySelector('[data-testid="my-todos-drawer"]')?.textContent || '';
}
describe('ShippingTaskCenterPage notice batch operations', () => {
afterEach(() => {
vi.clearAllMocks();
document.body.innerHTML = '';
});
it('only makes formal Notices selectable and displays each Notice projection', async () => {
it('only makes freight-upload Notices selectable and shows line details in drawer', async () => {
listTodos.mockResolvedValueOnce({
items: [
notice('WYC26082301', 'PO-100', 'PART-A'),
@@ -132,13 +193,20 @@ describe('ShippingTaskCenterPage notice batch operations', () => {
const wrapper = await mountPage();
await flushPromises();
// 断言:货代上传阶段 Notice 可勾选;Review/Intake 行无复选框。
expect(wrapper.get('[aria-label="WYC26082301"]').exists()).toBe(true);
expect(wrapper.get('[aria-label="WYC26082302"]').exists()).toBe(true);
expect(wrapper.find('[aria-label="SNRC-30"]').exists()).toBe(false);
// 断言:表格副行展示 客户 · PO · 文件。
expect(wrapper.text()).toContain('PO-100');
expect(wrapper.text()).toContain('PART-A');
expect(wrapper.text()).toContain('PART-B');
expect(wrapper.text()).toContain('WYC26082301.xlsx');
// 断言:点行打开抽屉,逐行明细承载料号(列表不再堆明细)。
await wrapper.get('[data-testid="my-todos-row-WYC26082301"]').trigger('click');
await flushPromises();
expect(document.body.querySelector('[data-testid="my-todos-drawer"]')).not.toBeNull();
const drawer = drawerText();
expect(drawer).toContain('PART-A');
expect(drawer).toContain('PART-A-B');
wrapper.unmount();
});
@@ -152,53 +220,106 @@ describe('ShippingTaskCenterPage notice batch operations', () => {
await wrapper.get('[aria-label="WYC26082301"]').setValue(true);
await wrapper.get('[aria-label="WYC26082302"]').setValue(true);
const toolbar = wrapper.get('[data-testid="shipping-notice-batch-toolbar"]');
const buttons = toolbar.findAll('button');
// 断言:勾选后浮出操作条,三个动作按序对应 download/confirm/rpa。
// 每次 action 后列表会静默重载(表格重挂载),因此逐次重新查询按钮。
const toolbarButtons = () => wrapper
.get('[data-testid="shipping-notice-batch-toolbar"]')
.findAll('button');
const buttons = toolbarButtons();
expect(buttons.length).toBeGreaterThanOrEqual(3);
await buttons[0].trigger('click');
expect(downloadArchive).toHaveBeenCalledWith(['WYC26082301', 'WYC26082302']);
await buttons[1].trigger('click');
await flushPromises();
await toolbarButtons()[1].trigger('click');
await flushPromises();
expect(batchConfirm).toHaveBeenCalledWith(['WYC26082301', 'WYC26082302']);
await buttons[2].trigger('click');
await toolbarButtons()[2].trigger('click');
await flushPromises();
expect(batchRpa).toHaveBeenCalledWith(['WYC26082301', 'WYC26082302']);
wrapper.unmount();
});
it('keeps all five lifecycle stage filters on one wide-screen row', async () => {
it('renders one row of stage tabs covering all plus four actionable stages', async () => {
const wrapper = await mountPage();
await flushPromises();
const track = wrapper.get('[data-testid="my-todos-lifecycle-stage-filter"]');
expect(track.classes()).toContain('xl:grid-cols-5');
// 断言:全部 + 四个可动作阶段;「通知完成」不再是筛选维度。
expect(track.findAll('button')).toHaveLength(5);
expect(track.text()).toContain('货代上传');
expect(track.text()).not.toContain('通知完成');
expect(track.text()).not.toContain('workspace.shippingNotice.myTodos.lifecycleStages.freight_upload');
wrapper.unmount();
});
it('counts a pending review item from its backend stage even without an enterable lifecycle entry', async () => {
listTodos.mockResolvedValueOnce({
items: [{
item_kind: 'review_case',
task_no: '',
review_run_no: 'RUN-1',
review_case_no: 'CASE-1',
ui_state: {
stage: { code: 'order_review', label: '订单复核', index: 2, total: 5 },
lifecycle_entries: [],
},
}],
page: 1,
page_size: 20,
total: 1,
it('shows backend aggregated stage counts instead of current-page counting', async () => {
countTodos.mockResolvedValueOnce({
pending: 13, processing: 0, done: 0, total_pending_badge: 13,
stage_counts: { intake_parse: 2, order_review: 4, fulfillment_prep: 3, freight_upload: 4 },
done_counts: { upload_complete: 0, reject_void: 0 },
});
listTodos.mockResolvedValueOnce({ items: [], page: 1, page_size: 20, total: 0 });
const wrapper = await mountPage();
await flushPromises();
expect(wrapper.get('[data-testid="my-todos-stage-filter-order_review"]').text()).toContain('1');
// 断言:阶段计数来自后端聚合(当前页为空列表也显示全量计数)。
expect(wrapper.get('[data-testid="my-todos-stage-filter-order_review"]').text()).toContain('4');
expect(wrapper.get('[data-testid="my-todos-stage-filter-fulfillment_prep"]').text()).toContain('3');
wrapper.unmount();
});
it('defaults done bucket to the flat done-lines report and exports current filters', async () => {
listDoneLines.mockResolvedValue({
items: [{
task_no: 'SN-DONE-1', business_no: 'BIZ-1', customer_name: 'HYVE CS', customer_code: 'HC001',
order_date: '2026-06-01', line_no: 1, part_number: 'B3-A08AR1', qty: 80,
required_date: '2026-06-15', customer_po_number: '306085', used_qty: null,
open_qty: null, source_order_number: '8301-1', unit_price: 1525.08,
}],
page: 1, page_size: 50, total: 1,
});
const wrapper = await mountPage();
await flushPromises();
await wrapper.get('[data-testid="my-todos-bucket-done"]').trigger('click');
await flushPromises();
// 断言:done 桶默认进入通知完成明细报表,消费 done-lines 接口。
expect(listDoneLines).toHaveBeenCalled();
const table = wrapper.get('[data-testid="done-lines-table"]');
expect(table.text()).toContain('B3-A08AR1');
expect(table.text()).toContain('8301-1');
// 断言:导出按钮把当前筛选交给受控下载。
await wrapper.get('[data-testid="done-lines-export"]').trigger('click');
await flushPromises();
expect(downloadDoneLinesExcel).toHaveBeenCalled();
wrapper.unmount();
});
it('loads reject_void sub tab with terminal_kind filter and badges rows', async () => {
listTodos.mockResolvedValue({
items: [{
id: 41, task_no: 'SN-REJ-1', business_no: 'BIZ-R1', item_kind: 'task',
todo_ref: 'SN-REJ-1', todo_category: 'done',
ui_state: { stage: { code: 'upload_complete', label: '通知完成' }, lifecycle_entries: [] },
}],
page: 1, page_size: 20, total: 1,
});
const wrapper = await mountPage();
await flushPromises();
await wrapper.get('[data-testid="my-todos-bucket-done"]').trigger('click');
await flushPromises();
const subtabs = wrapper.findAll('[data-testid="my-todos-done-subtabs"] button');
await subtabs[1].trigger('click');
await flushPromises();
// 断言:驳回/作废子视图按 terminal_kind 拉任务表,行带终态角标。
expect(listTodos).toHaveBeenCalledWith(expect.objectContaining({
bucket: 'done',
terminal_kind: 'reject_void',
}));
expect(wrapper.get('[data-testid="my-todos-row-BIZ-R1"]').text()).toContain('复核驳回');
wrapper.unmount();
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,400 @@
<!--
features/workspace/shipping-task-center/ShippingTaskDrawer.vue
用途:任务详情抽屉——分诊决策面板(头部阻断 + 逐行明细 + 文件 + 底部操作)。
依赖:shippingTaskCenterShared(阶段口径)、gateReasonLabel。
逻辑:review/intake/task 三分支迁移自原任务中心右侧入口卡,行为与深链契约不变;
深链/重试只向上 emit,由页面统一执行;阶段目标下拉仍由后端
ui_state.lifecycle_entries 裁决(current/available 才可进)。
-->
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Download, ExternalLink, RefreshCw, X } from 'lucide-vue-next';
import type {
ShippingTaskDetail,
ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import {
canOpenIntakeParse,
defaultLifecycleTarget,
lifecycleEntriesOf,
lifecycleEntryFor,
lifecycleEntryIsEnterable,
todoBlockerText,
todoDisplayNo,
type LifecycleStageCode,
type TodoLike,
} from './shippingTaskCenterShared';
const { t, te } = useI18n();
const props = defineProps<{
open: boolean;
item: ShippingTaskSummary | ShippingTaskDetail | null;
loading?: boolean;
chatAgentId: number | null;
/** 重试 STP 进行中(页面持有状态)。 */
stpRetrying?: boolean;
}>();
const emit = defineEmits<{
(event: 'close'): void;
(event: 'open-intake', item: TodoLike): void;
(event: 'open-processing', item: TodoLike, stage: Exclude<LifecycleStageCode, 'intake_parse'>): void;
(event: 'open-chat', item: TodoLike): void;
(event: 'retry-stp', item: TodoLike): void;
}>();
type EnterableStage = Exclude<LifecycleStageCode, 'intake_parse'>;
const stageTarget = ref<EnterableStage>('order_review');
const isReviewItem = computed(() => {
const item = props.item as ShippingTaskSummary | null;
if (!item) return false;
return item.item_kind === 'review_case' || Boolean(item.review_run_no && !item.task_no);
});
const isIntakeItem = computed(() => {
const item = props.item as ShippingTaskSummary | null;
if (!item) return false;
return item.item_kind === 'order_intake'
|| Boolean(item.intake_no && !item.task_no && !item.review_run_no);
});
const displayNo = computed(() => {
if (!props.item) return '—';
if ('task_no' in props.item && props.item.task_no
&& !isReviewItem.value && !isIntakeItem.value) {
return String(props.item.task_no);
}
return todoDisplayNo(props.item as ShippingTaskSummary);
});
const subTitle = computed(() => {
const item = props.item;
if (!item) return '';
const segments = [
String(item.customer_name || '').trim(),
String(item.po_number || '').trim() ? `PO ${String(item.po_number).trim()}` : '',
String(item.source_file_name || '').trim()
|| String(item.artifact_summary?.export_file_name || '').trim(),
].filter(Boolean);
return segments.join(' · ');
});
const stageLabel = computed(() => {
const item = props.item;
if (!item) return '';
const code = String(item.ui_state?.stage?.code || '').trim();
const key = code ? `workspace.shippingNotice.myTodos.lifecycleStages.${code}` : '';
if (key && te(key)) return t(key);
return String(item.ui_state?.stage?.label || '');
});
const blocker = computed(() => (props.item ? todoBlockerText(props.item, t, te) : ''));
const summaryMessage = computed(() => String(
props.item?.ui_state?.summary?.message
|| props.item?.ui_state?.summary?.current_todo
|| '',
));
const stageTargetOptions = computed(() => {
if (!props.item) return [];
return lifecycleEntriesOf(props.item)
.filter((entry) => entry.code !== 'intake_parse')
.map((entry) => ({
code: entry.code as EnterableStage,
disabled: entry.state !== 'current' && entry.state !== 'available',
}));
});
/** 后端仅授权 current/available;目标不可进时主按钮禁用。 */
function canOpenProcessing(stage: EnterableStage | null): boolean {
const item = props.item;
if (!item) return false;
const runNo = String(item.review_run_no || '').trim();
const agentId = Number(item.owner_agent_id || props.chatAgentId || 0);
const target = stage || defaultLifecycleTarget(item);
if (!target) return false;
return Boolean(runNo && agentId && lifecycleEntryIsEnterable(lifecycleEntryFor(item, target)));
}
const canOpenIntake = computed(() => canOpenIntakeParse(props.item, props.chatAgentId));
/** 摘要允许动作里是否含 STP 自动推进重试(与工作台底栏同一契约)。 */
const canRetryStp = computed(() => {
const item = props.item as ShippingTaskSummary | null;
if (!item || item.can_handle === false) return false;
if (!String(item.review_case_no || '').trim()) return false;
const summaryActions = item.ui_state?.summary?.allowed_actions || [];
const actions = [item.ui_state?.actions?.primary, ...(item.ui_state?.actions?.secondary || [])]
.filter(Boolean)
.map((action) => String(action?.code || ''));
return summaryActions.includes('retry_stp_auto_create') || actions.includes('retry_stp_auto_create');
});
const exportFileName = computed(() => String(
props.item?.artifact_summary?.export_file_name || '',
));
const lineRows = computed(() => {
const item = props.item as ShippingTaskSummary | null;
return Array.isArray(item?.notice_line_summary) ? item!.notice_line_summary : [];
});
/**
* 数量/缺口展示值:后端 Numeric(24,8) 透出形如 "24.00000000",
* 统一转 number 去尾零(24.00000000→24、2.50000000→2.5),缺失保持 —。
*/
function formatQty(value: unknown): string {
if (value === null || value === undefined || value === '') return '—';
const num = Number(value);
return Number.isFinite(num) ? String(num) : String(value);
}
watch(() => props.item, (item) => {
if (!item) return;
const stage = defaultLifecycleTarget(item);
if (stage) stageTarget.value = stage;
}, { immediate: true });
function onEsc(event: KeyboardEvent) {
if (event.key === 'Escape') emit('close');
}
// Esc 关闭抽屉;打开时挂监听,关闭/卸载时移除,避免监听串扰。
watch(() => props.open, (open) => {
if (open) document.addEventListener('keydown', onEsc);
else document.removeEventListener('keydown', onEsc);
}, { immediate: true });
onBeforeUnmount(() => document.removeEventListener('keydown', onEsc));
</script>
<template>
<Teleport to="body">
<div
v-if="open"
class="fixed inset-0 z-50 flex"
data-testid="my-todos-drawer"
>
<div
class="flex-1 bg-[rgba(23,32,51,0.35)]"
data-testid="my-todos-drawer-scrim"
@click="emit('close')"
/>
<aside class="flex w-[52rem] max-w-[94vw] flex-col bg-surface shadow-2xl">
<div class="border-b border-default px-5 py-4">
<div class="flex items-start justify-between gap-3">
<h3 class="break-all font-mono text-base font-bold text-primary" data-testid="my-todos-drawer-title">
{{ displayNo }}
</h3>
<button
type="button"
class="rounded-lg bg-surface-soft px-2 py-1 text-xs text-secondary hover:bg-surface-soft/70"
:aria-label="$t('workspace.shippingNotice.myTodos.drawer.close')"
data-testid="my-todos-drawer-close"
@click="emit('close')"
>
<X class="h-4 w-4" />
</button>
</div>
<p v-if="subTitle" class="mt-1 text-xs text-muted">{{ subTitle }}</p>
<div class="mt-2 flex flex-wrap items-center gap-2">
<span
v-if="stageLabel"
class="rounded-full bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-800"
data-testid="my-todos-drawer-stage"
>
{{ stageLabel }}
</span>
<span
v-if="isReviewItem"
class="rounded bg-amber-50 px-1.5 py-0.5 text-[10px] text-amber-700"
>{{ $t('workspace.shippingNotice.myTodos.openReview') }}</span>
<span
v-else-if="isIntakeItem"
class="rounded bg-violet-50 px-1.5 py-0.5 text-[10px] text-violet-700"
>{{ $t('workspace.shippingNotice.myTodos.intakeParseBadge') }}</span>
</div>
</div>
<div class="flex-1 overflow-y-auto px-5 py-4">
<div v-if="loading" class="py-16 text-center text-sm text-muted">
{{ $t('workspace.shippingNotice.loading') }}
</div>
<template v-else-if="item">
<div
v-if="blocker"
class="mb-4 rounded-xl border border-red-200 bg-red-50 px-3.5 py-2.5 text-[13px] text-red-700"
data-testid="my-todos-progress-blocker"
>
{{ $t('workspace.shippingNotice.myTodos.progressBlocker', { reason: blocker }) }}
</div>
<p
v-if="stageLabel"
class="mb-2 text-sm font-medium text-primary"
data-testid="my-todos-progress-summary"
>
{{ $t('workspace.shippingNotice.myTodos.progressSummary', { stage: stageLabel }) }}
</p>
<p v-if="summaryMessage" class="text-sm text-secondary">{{ summaryMessage }}</p>
<template v-if="lineRows.length">
<h4 class="mb-2 mt-5 text-[13px] font-bold text-primary">
{{ $t('workspace.shippingNotice.myTodos.drawer.details') }}
</h4>
<div class="overflow-x-auto rounded-xl border border-default">
<table class="w-full border-collapse text-xs" data-testid="my-todos-drawer-lines">
<thead>
<tr class="border-b border-default bg-surface-soft/60 text-left text-muted">
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.lineNo') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.partNumber') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.customerPartNumber') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.reservationId') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.shipmentQty') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.availableQty') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.shortageQty') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.status') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="line in lineRows"
:key="`${line.line_no}-${line.part_number}`"
class="border-b border-[#f0f3f8]"
>
<td class="px-2.5 py-2 font-mono">{{ line.line_no }}</td>
<td class="whitespace-nowrap px-2.5 py-2 font-mono">{{ line.part_number || '—' }}</td>
<td class="whitespace-nowrap px-2.5 py-2">{{ line.customer_part_number || '—' }}</td>
<td class="whitespace-nowrap px-2.5 py-2 font-mono">{{ line.reservation_id || '—' }}</td>
<td class="whitespace-nowrap px-2.5 py-2 tabular-nums">{{ formatQty(line.shipment_qty) }}</td>
<td class="whitespace-nowrap px-2.5 py-2 tabular-nums">{{ formatQty(line.available_qty) }}</td>
<td
class="whitespace-nowrap px-2.5 py-2 tabular-nums"
:class="Number(line.shortage_qty || 0) > 0 ? 'font-bold text-red-600' : ''"
>
{{ formatQty(line.shortage_qty) }}
</td>
<td class="whitespace-nowrap px-2.5 py-2">{{ line.inventory_status || '—' }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<template v-if="exportFileName">
<h4 class="mb-2 mt-5 text-[13px] font-bold text-primary">
{{ $t('workspace.shippingNotice.myTodos.drawer.files') }}
</h4>
<div class="rounded-xl border border-default px-3 py-2 text-[13px] text-secondary">
<span class="mr-2 rounded bg-brand-50 px-1.5 py-0.5 text-[10px] text-brand-800">Excel</span>
{{ exportFileName }}
</div>
</template>
<p class="mt-5 text-xs text-muted">
{{ $t('workspace.shippingNotice.myTodos.openProcessingHint') }}
</p>
</template>
<div v-else class="py-16 text-center text-sm text-muted">
{{ $t('workspace.shippingNotice.selectCase') }}
</div>
</div>
<div v-if="item && !loading" class="space-y-2.5 border-t border-default px-5 py-4">
<div class="flex flex-wrap gap-2">
<label class="sr-only" for="drawer-stage-target">{{ $t('workspace.shippingNotice.myTodos.lifecycleStages.viewStage') }}</label>
<select
v-if="stageTargetOptions.length"
id="drawer-stage-target"
v-model="stageTarget"
class="input-field max-w-40 text-sm"
data-testid="my-todos-lifecycle-stage-target"
>
<option
v-for="option in stageTargetOptions"
:key="option.code"
:value="option.code"
:disabled="option.disabled"
>
{{ $t(`workspace.shippingNotice.myTodos.lifecycleStages.${option.code}`) }}
</option>
</select>
<button
v-if="canOpenIntake"
type="button"
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
data-testid="my-todos-open-intake-parse"
@click="emit('open-intake', item)"
>
<ExternalLink class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.myTodos.openIntakeParse') }}
</button>
<button
v-else-if="!isIntakeItem"
type="button"
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
:disabled="!canOpenProcessing(stageTarget)"
data-testid="my-todos-open-order-processing"
@click="emit('open-processing', item, stageTarget)"
>
<ExternalLink class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.myTodos.openLifecycleWorkbench') }}
</button>
<button
v-else
type="button"
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
:disabled="!(item.owner_agent_id || chatAgentId)"
data-testid="my-todos-open-intake-conversation"
@click="emit('open-chat', item)"
>
<ExternalLink class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.myTodos.openConversation') }}
</button>
<button
v-if="chatAgentId && !isIntakeItem"
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-1.5 text-xs font-medium text-secondary hover:bg-surface-soft"
@click="emit('open-chat', item)"
>
<ExternalLink class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.openChat') }}
</button>
</div>
<div class="flex flex-wrap items-center gap-3">
<button
v-if="canRetryStp"
type="button"
class="inline-flex items-center gap-1.5 rounded-xl border border-amber-400 bg-amber-50 px-4 py-2 text-sm font-medium text-amber-950 hover:bg-amber-100 disabled:opacity-50 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100"
:disabled="stpRetrying"
data-testid="my-todos-retry-stp-auto-create"
@click="emit('retry-stp', item)"
>
<RefreshCw class="h-3.5 w-3.5" />
{{ $t('chat.shippingOrderReview.autoProgress.retryStp') }}
</button>
<a
v-if="exportFileName"
class="inline-flex cursor-pointer items-center gap-1 text-xs text-brand-700 hover:underline"
:href="`/api/workspace/shipping-notices/${encodeURIComponent(String(item.business_no || ''))}/export`"
target="_blank"
rel="noopener"
>
<Download class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.myTodos.drawer.exportExcel') }}
</a>
<p
v-if="!canOpenIntake && !canOpenProcessing(stageTarget) && !isIntakeItem"
class="text-xs text-amber-700 dark:text-amber-300"
data-testid="my-todos-open-processing-unavailable"
>
{{ $t('workspace.shippingNotice.myTodos.openProcessingUnavailable') }}
</p>
</div>
</div>
</aside>
</div>
</Teleport>
</template>
@@ -0,0 +1,240 @@
<!--
features/workspace/shipping-task-center/ShippingTaskTable.vue
用途:任务中心紧凑表格(一行一待办):编号/阶段/状态摘要/项次缺口/货代状态。
依赖:shippingTaskCenterShared(编号、阶段、批量可选口径)。
逻辑:行点击向上冒泡选中;复选框仅「货代上传」阶段的正式 Notice 行存在;
勾选 ≥1 后浮出深色批量操作条(低频操作不常驻);分页由父级渲染。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { CheckSquare, Download, Upload, X } from 'lucide-vue-next';
import type { ShippingTaskSummary } from '@/features/chat/api/shipping.api';
import {
isFreightUploadRow,
lifecycleStageCodeOf,
todoBlockerText,
todoDisplayNo,
todoItemKey,
todoLineBrief,
todoSubTitleText,
todoTitleText,
} from './shippingTaskCenterShared';
const { t, te } = useI18n();
const props = defineProps<{
items: ShippingTaskSummary[];
/** 当前选中行主键(抽屉联动)。 */
selectedKey?: string | null;
/** 是否渲染复选框列(仅待处理桶)。 */
selectable?: boolean;
/** 已勾选 business_no 集合。 */
selectedBusinessNos?: string[];
/** 批量动作进行中标记,禁用按钮。 */
batchBusy?: 'download' | 'confirm' | 'rpa' | null;
/** done 桶行统一终态角标(驳回/作废子视图由服务端过滤保证)。 */
terminalBadge?: 'upload_complete' | 'reject_void' | null;
}>();
const emit = defineEmits<{
(event: 'select', item: ShippingTaskSummary): void;
(event: 'toggle', item: ShippingTaskSummary): void;
(event: 'toggle-all'): void;
(event: 'clear-selection'): void;
(event: 'batch', action: 'download' | 'confirm' | 'rpa'): void;
}>();
const selectedSet = computed(() => new Set(props.selectedBusinessNos || []));
const selectableRows = computed(() => props.items.filter((item) => isFreightUploadRow(item)));
const hasSelection = computed(() => (props.selectedBusinessNos?.length || 0) > 0);
const allSelectableChecked = computed(() => (
selectableRows.value.length > 0
&& selectableRows.value.every((item) => selectedSet.value.has(String(item.business_no)))
));
/** 阶段徽章文案:优先本地化阶段名,后端 label 兜底。 */
function stageLabel(item: ShippingTaskSummary): string {
const code = lifecycleStageCodeOf(item);
const key = code ? `workspace.shippingNotice.myTodos.lifecycleStages.${code}` : '';
if (key && te(key)) return t(key);
return String(item.ui_state?.stage?.label || '—');
}
function rowTitle(item: ShippingTaskSummary): string {
return todoTitleText(item);
}
function rowBlocker(item: ShippingTaskSummary): string {
return todoBlockerText(item, t, te);
}
function lineBriefText(item: ShippingTaskSummary): string {
const brief = todoLineBrief(item);
if (!brief.total) return '—';
return `${brief.total} ${t('workspace.shippingNotice.myTodos.table.lineUnit')}`;
}
function onToggleAll(): void {
emit('toggle-all');
}
</script>
<template>
<div class="overflow-hidden rounded-2xl border border-default bg-surface">
<div
v-if="hasSelection"
class="flex flex-wrap items-center gap-2 bg-[#1b2740] px-4 py-2.5 text-sm text-slate-100"
data-testid="shipping-notice-batch-toolbar"
>
<span class="rounded-full bg-brand-600 px-3 py-0.5 text-xs font-semibold">
{{ $t('workspace.shippingNotice.batch.selected', { count: selectedBusinessNos?.length || 0 }) }}
</span>
<button
type="button"
class="rounded-lg border border-white/20 px-2.5 py-1 text-xs hover:bg-white/10 disabled:opacity-50"
:disabled="Boolean(batchBusy)"
@click="emit('batch', 'download')"
>
<Download class="mr-1 inline h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.batch.download') }}
</button>
<button
type="button"
class="rounded-lg border border-white/20 px-2.5 py-1 text-xs hover:bg-white/10 disabled:opacity-50"
:disabled="Boolean(batchBusy)"
@click="emit('batch', 'confirm')"
>
<CheckSquare class="mr-1 inline h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.batch.confirm') }}
</button>
<button
type="button"
class="rounded-lg border border-white/20 px-2.5 py-1 text-xs hover:bg-white/10 disabled:opacity-50"
:disabled="Boolean(batchBusy)"
@click="emit('batch', 'rpa')"
>
<Upload class="mr-1 inline h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.batch.rpa') }}
</button>
<span class="flex-1" />
<button
type="button"
class="rounded-lg px-2.5 py-1 text-xs text-slate-300 hover:text-white"
@click="emit('clear-selection')"
>
<X class="mr-1 inline h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.batch.clearSelection') }}
</button>
</div>
<div class="overflow-x-auto">
<table class="w-full border-collapse text-sm">
<thead>
<tr class="border-b border-default bg-surface-soft/60 text-left text-xs text-muted">
<th v-if="selectable" class="w-10 px-3 py-2.5">
<input
type="checkbox"
:checked="allSelectableChecked"
:aria-label="$t('workspace.shippingNotice.batch.selectAll')"
@change="onToggleAll"
>
</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.table.no') }}</th>
<th class="w-24 px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.table.stage') }}</th>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.table.summary') }}</th>
<th class="w-28 px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.table.lines') }}</th>
<th class="w-24 px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.table.freightStatus') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="item in items"
:key="todoItemKey(item)"
class="cursor-pointer border-b border-[#f0f3f8] transition-colors hover:bg-brand-50/40"
:class="selectedKey === todoItemKey(item) ? 'bg-brand-50/70 dark:bg-brand-950/30' : ''"
:data-testid="`my-todos-row-${todoDisplayNo(item)}`"
@click="emit('select', item)"
>
<td v-if="selectable" class="px-3 py-2.5 align-middle">
<input
v-if="isFreightUploadRow(item)"
type="checkbox"
:checked="selectedSet.has(String(item.business_no))"
:aria-label="String(item.business_no)"
@click.stop
@change="emit('toggle', item)"
>
</td>
<td class="max-w-[22rem] px-3 py-2.5 align-middle">
<div class="flex items-center gap-2">
<span class="truncate font-mono text-[13px] font-semibold text-primary">{{ todoDisplayNo(item) }}</span>
<span
v-if="item.todo_category === 'review' || item.item_kind === 'review_case'"
class="shrink-0 rounded bg-amber-50 px-1.5 py-0.5 text-[10px] text-amber-700"
>
{{ $t('workspace.shippingNotice.myTodos.openReview') }}
</span>
<span
v-else-if="item.todo_category === 'intake_parse' || item.item_kind === 'order_intake'"
class="shrink-0 rounded bg-violet-50 px-1.5 py-0.5 text-[10px] text-violet-700"
>
{{ $t('workspace.shippingNotice.myTodos.intakeParseBadge') }}
</span>
<span
v-else-if="item.can_handle === false"
class="shrink-0 rounded bg-slate-100 px-1.5 py-0.5 text-[10px] text-slate-600"
>
{{ $t('workspace.shippingNotice.todo.adminViewOnlyShort') }}
</span>
<span
v-else-if="terminalBadge === 'upload_complete'"
class="shrink-0 rounded bg-emerald-50 px-1.5 py-0.5 text-[10px] text-emerald-700"
>
{{ $t('workspace.shippingNotice.myTodos.terminal.uploadComplete') }}
</span>
<span
v-else-if="terminalBadge === 'reject_void'"
class="shrink-0 rounded bg-red-50 px-1.5 py-0.5 text-[10px] text-red-700"
>
{{ $t('workspace.shippingNotice.myTodos.terminal.rejectVoid') }}
</span>
</div>
<div class="mt-0.5 truncate text-xs text-muted">{{ todoSubTitleText(item) || '—' }}</div>
</td>
<td class="px-3 py-2.5 align-middle">
<span class="whitespace-nowrap rounded-full bg-brand-50 px-2 py-0.5 text-xs text-brand-800">
{{ stageLabel(item) }}
</span>
</td>
<td class="max-w-[18rem] px-3 py-2.5 align-middle">
<div class="truncate text-[13px] text-secondary">{{ rowTitle(item) }}</div>
<div
v-if="rowBlocker(item)"
class="mt-0.5 truncate text-xs text-red-600"
data-testid="my-todos-row-blocker"
>
{{ rowBlocker(item) }}
</div>
</td>
<td class="px-3 py-2.5 align-middle text-xs">
<template v-if="item.business_no">
<span>{{ lineBriefText(item) }}</span>
<span
v-if="todoLineBrief(item).shortage"
class="ml-1 font-semibold text-red-600"
>
{{ $t('workspace.shippingNotice.myTodos.table.shortage', { count: todoLineBrief(item).shortage }) }}
</span>
</template>
<span v-else class="text-muted">—</span>
</td>
<td class="px-3 py-2.5 align-middle text-xs text-secondary">
{{ item.business_no ? (item.upload_status || '—') : '—' }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
@@ -1,11 +1,15 @@
/**
* features/workspace/shipping-task-center/shippingTaskCenterPolling.spec.ts
* 用途:锁定任务中心自动轮询的边界,避免人工待处理任务被误判为持续处理中。
* 依赖:isShippingTodoListItemInProgress。
* 逻辑:只有后端明确的进行中状态继续轮询;复核草稿、失败和完成任务停止轮询。
* 依赖:isShippingTodoListItemInProgress、resolveTodoCenterPollIntervalMs。
* 逻辑:只有系统 running 继续高频轮询;复核草稿、失败和完成停止;人工等待 30s。
*/
import { describe, expect, it } from 'vitest';
import { isShippingTodoListItemInProgress } from './shippingTaskCenterPolling';
import {
HUMAN_WAIT_POLL_MS,
isShippingTodoListItemInProgress,
resolveTodoCenterPollIntervalMs,
} from './shippingTaskCenterPolling';
describe('isShippingTodoListItemInProgress', () => {
it('does not poll a review case that is waiting for human editing', () => {
@@ -17,6 +21,32 @@ describe('isShippingTodoListItemInProgress', () => {
} as never)).toBe(false);
});
it('does not poll waiting_review or needs_action as system running', () => {
expect(isShippingTodoListItemInProgress({
item_kind: 'task',
task_no: 'OT-1',
shipping_processing_status: 'waiting_review',
} as never)).toBe(false);
expect(isShippingTodoListItemInProgress({
item_kind: 'task',
task_no: 'OT-2',
shipping_processing_status: 'needs_action',
} as never)).toBe(false);
expect(isShippingTodoListItemInProgress({
item_kind: 'task',
task_no: 'OT-3',
shipping_processing_status: 'blocked',
} as never)).toBe(false);
});
it('does not treat a non-complete lifecycle stage as running', () => {
expect(isShippingTodoListItemInProgress({
item_kind: 'task',
task_no: 'OT-STAGE',
ui_state: { stage: { code: 'order_review', label: '订单复核', index: 1, total: 5 } },
} as never)).toBe(false);
});
it('continues polling a review case with an explicit processing status', () => {
expect(isShippingTodoListItemInProgress({
item_kind: 'review_case',
@@ -26,4 +56,47 @@ describe('isShippingTodoListItemInProgress', () => {
review_run_no: 'RUN-1',
} as never)).toBe(true);
});
it('continues polling queued automating or running execution', () => {
expect(isShippingTodoListItemInProgress({
item_kind: 'task',
task_no: 'OT-Q',
shipping_processing_status: 'queued',
} as never)).toBe(true);
expect(isShippingTodoListItemInProgress({
item_kind: 'task',
task_no: 'OT-A',
shipping_processing_status: 'automating',
} as never)).toBe(true);
expect(isShippingTodoListItemInProgress({
item_kind: 'task',
task_no: 'OT-E',
ui_state: { process_gate: { status: 'active' } },
} as never)).toBe(true);
expect(isShippingTodoListItemInProgress({
item_kind: 'task',
task_no: 'OT-U',
user_status: 'running',
} as never)).toBe(true);
});
});
describe('resolveTodoCenterPollIntervalMs', () => {
it('reuses batch intervals while system work is running', () => {
expect(resolveTodoCenterPollIntervalMs({
hasRunning: true, hasHumanWait: false, elapsedMs: 0, visibility: 'visible', failureCount: 0,
})).toBe(2000);
expect(resolveTodoCenterPollIntervalMs({
hasRunning: true, hasHumanWait: false, elapsedMs: 15000, visibility: 'visible', failureCount: 0,
})).toBe(5000);
});
it('uses 30s for human wait and stops when idle', () => {
expect(resolveTodoCenterPollIntervalMs({
hasRunning: false, hasHumanWait: true, elapsedMs: 0, visibility: 'visible', failureCount: 0,
})).toBe(HUMAN_WAIT_POLL_MS);
expect(resolveTodoCenterPollIntervalMs({
hasRunning: false, hasHumanWait: false, elapsedMs: 0, visibility: 'visible', failureCount: 0,
})).toBeNull();
});
});
@@ -1,18 +1,20 @@
/**
* features/workspace/shipping-task-center/shippingTaskCenterPolling.ts
* 用途:任务中心列表项是否仍需前台轮询(纯函数,供页面与单测共用)。
* 依赖:ShippingTaskSummary、shippingProcessingFulfillment 状态集合。
* 逻辑:ShippingTaskCenterPage 用本函数决定 poll;Intake created/queued/parsing 必须轮询,
* parse_failed 停止;review_case 持续轮询;OT/Notice 走统一投影状态。
* 用途:任务中心列表项是否系统在跑、以及待办页轮询间隔(纯函数)。
* 依赖:ShippingTaskSummary、useShippingNoticeWorkflow 间隔函数。
* 逻辑:ShippingTaskCenterPage 用本模块决定 poll;仅 queued/processing/automating/running
* 或 Execution active/waiting_external 算系统在跑;人工等待走 30s;间隔复用批次函数。
*/
import type { ShippingTaskSummary } from '@/features/chat/api/shipping.api';
import {
IN_PROGRESS_PROCESSING_STATUSES,
TERMINAL_PROCESSING_STATUSES,
} from '@/features/chat/shipping/shippingProcessingFulfillment';
resolveProcessingPollBackoffMs,
resolveProcessingPollIntervalMs,
type ProcessingPollContext,
} from '@/features/chat/shipping/useShippingNoticeWorkflow';
import { TERMINAL_PROCESSING_STATUSES } from '@/features/chat/shipping/shippingProcessingFulfillment';
/** 历史轮询状态集合;正常任务中心优先消费统一 ui_state。 */
/** 历史轮询状态集合;正常任务中心不再用它判定系统处理中。 */
export const IN_PROGRESS_PROCESS = new Set([
'parsing',
'parsed',
@@ -26,41 +28,78 @@ export const IN_PROGRESS_PROCESS = new Set([
'pending_void',
]);
/** Intake 仍在解析、必须轮询的状态。 */
/** Intake 仍在解析、必须高频轮询的状态。 */
export const INTAKE_POLLING_PARSE_STATUSES = new Set([
'created',
'queued',
'parsing',
]);
/** 系统正在自动跑的统一 processing status;不含人工等待。 */
export const SYSTEM_RUNNING_PROCESSING_STATUSES = new Set([
'queued',
'processing',
'automating',
'running',
]);
/** Execution.status 中表示系统仍在推进。 */
const RUNNING_EXECUTION_STATUSES = new Set([
'active',
'waiting_external',
]);
/** 仅人工等待时的待办轮询间隔,与批次中心后台档一致。 */
export const HUMAN_WAIT_POLL_MS = 30000;
/**
* 判断列表项是否应触发轮询刷新。
* 核心逻辑:review_case 持续轮询;order_intake 仅 created/queued/parsing;
* 其余优先 shipping_processing_status,再按统一 ui_state.stage;
* 不复用 WorkflowItem lifecycle。
* 判断列表项是否仍有系统在自动跑,从而需要高频轮询。
* 核心逻辑:Intake created/queued/parsing;其余只认 running 投影
* (shipping_processing_status / user_status / Execution active),
* 不把 waiting_review / needs_action / blocked / 阶段码当成处理中。
* @param item - 我的待办列表项
* @returns 是否需要继续轮询
* @returns 是否系统处理中
*/
export function isShippingTodoListItemInProgress(item: ShippingTaskSummary): boolean {
if (item.item_kind === 'review_case' || (item.review_run_no && !item.task_no)) {
const unified = String(item.shipping_processing_status || '').trim().toLowerCase();
if (unified) {
if (TERMINAL_PROCESSING_STATUSES.has(unified)) return false;
return IN_PROGRESS_PROCESSING_STATUSES.has(unified);
}
return false;
}
if (item.item_kind === 'order_intake') {
const intakeStatus = String(
item.intake_parse_status || '',
).trim().toLowerCase();
if (item.item_kind === 'order_intake' || (item.intake_no && !item.task_no && !item.review_run_no)) {
const intakeStatus = String(item.intake_parse_status || '').trim().toLowerCase();
return INTAKE_POLLING_PARSE_STATUSES.has(intakeStatus);
}
const unified = String(item.shipping_processing_status || '').trim().toLowerCase();
if (unified) {
if (TERMINAL_PROCESSING_STATUSES.has(unified)) return false;
return IN_PROGRESS_PROCESSING_STATUSES.has(unified);
return SYSTEM_RUNNING_PROCESSING_STATUSES.has(unified);
}
const stage = String(item.ui_state?.stage?.code || '').trim();
return Boolean(stage) && stage !== 'upload_complete';
const userStatus = String(
(item as { user_status?: string | null }).user_status
|| (item.ui_state as { user_status?: string; status?: string } | undefined)?.user_status
|| (item.ui_state as { status?: string } | undefined)?.status
|| '',
).trim().toLowerCase();
if (userStatus === 'running') return true;
const executionStatus = String(item.ui_state?.process_gate?.status || '').trim().toLowerCase();
return RUNNING_EXECUTION_STATUSES.has(executionStatus);
}
/**
* 待办页轮询间隔:系统在跑复用批次函数;仅人工等待 30s;否则停。
*/
export function resolveTodoCenterPollIntervalMs(context: {
hasRunning: boolean;
hasHumanWait: boolean;
elapsedMs: number;
visibility: ProcessingPollContext['visibility'];
failureCount: number;
}): number | null {
if (context.hasRunning) {
return resolveProcessingPollIntervalMs({
elapsedMs: context.elapsedMs,
visibility: context.visibility,
hasProcessing: true,
failureCount: context.failureCount,
});
}
if (!context.hasHumanWait) return null;
if (context.failureCount > 0) return resolveProcessingPollBackoffMs(context.failureCount);
return HUMAN_WAIT_POLL_MS;
}
@@ -0,0 +1,174 @@
/**
* features/workspace/shipping-task-center/shippingTaskCenterShared.ts
* 用途:任务中心列表 / 表格 / 抽屉共用的纯函数与类型(阶段口径、编号、选择)。
* 依赖:chat shipping.api 类型、gateReasonLabel。
* 逻辑:阶段只消费后端 ui_state.lifecycle_entries / ui_state.stage(与页面同口径);
* 本模块不发起请求、不操作路由,供 TaskTable / Drawer / Page 复用。
*/
import type { ShippingTaskDetail, ShippingTaskSummary } from '@/features/chat/api/shipping.api';
import { resolveGateReasonLabel } from '@/features/shipping-progress/gateReasonLabel';
export type LifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep'
| 'freight_upload' | 'upload_complete';
/** 五阶段完整序列(抽屉阶段下拉消费后端 entries,仍需全集做过滤)。 */
export const LIFECYCLE_STAGES: LifecycleStageCode[] = [
'intake_parse',
'order_review',
'fulfillment_prep',
'freight_upload',
'upload_complete',
];
/** 阶段筛选 tab 仅覆盖四个可动作阶段;「通知完成」归 done 桶终态。 */
export const ACTIONABLE_TODO_STAGES: Exclude<LifecycleStageCode, 'upload_complete'>[] = [
'intake_parse',
'order_review',
'fulfillment_prep',
'freight_upload',
];
export type TodoLike = ShippingTaskSummary | ShippingTaskDetail;
/**
* 待办列表项稳定主键:复核用 case_no,Intake 用 intake_no,任务用 task_no。
*/
export function todoItemKey(item: ShippingTaskSummary): string {
if (item.item_kind === 'review_case' || item.review_case_no) {
return String(item.todo_ref || item.review_case_no || item.review_run_no || '');
}
if (item.item_kind === 'order_intake' || item.intake_no) {
return String(item.todo_ref || item.intake_no || '');
}
return String(item.todo_ref || item.task_no || '');
}
/**
* 列表展示编号:复核显示 case_no,Intake 显示 intake_no,任务显示业务编号/SN。
*/
export function todoDisplayNo(item: ShippingTaskSummary): string {
if (item.item_kind === 'review_case' || item.review_case_no) {
return String(item.review_case_no || item.review_run_no || item.todo_ref || '—');
}
if (item.item_kind === 'order_intake' || item.intake_no) {
return String(item.intake_no || item.todo_ref || '—');
}
return String(item.business_no || item.task_no || item.todo_ref || '—');
}
/**
* 读取后端已裁决的生命周期入口;缺失即无授权,绝不按 task/case/intake 身份补造入口。
*/
export function lifecycleEntriesOf(item: TodoLike) {
const entries = item.ui_state?.lifecycle_entries;
if (!Array.isArray(entries)) return [];
return entries.filter((entry) => LIFECYCLE_STAGES.includes(entry.code as LifecycleStageCode));
}
/** 当前阶段只取后端标为 current 的入口,必要时回退 ui_state.stage(仅统计口径)。 */
export function lifecycleStageCodeOf(item: TodoLike): LifecycleStageCode | null {
const current = lifecycleEntriesOf(item).find((entry) => entry.state === 'current');
if (current) return current.code as LifecycleStageCode;
// [AUTHORITY] 待人工处理的 Review Case 可能没有可进入工作台的 lifecycle entry,
// 但后端仍会下发 ui_state.stage 作为当前业务阶段;统计与筛选必须保留该阶段。
const stage = String(item.ui_state?.stage?.code || '').trim();
return LIFECYCLE_STAGES.includes(stage as LifecycleStageCode)
? stage as LifecycleStageCode
: null;
}
/** 可进入工作台的业务阶段仅由后端 entry.state 授权。 */
export function lifecycleEntryFor(
item: TodoLike,
stage: Exclude<LifecycleStageCode, 'intake_parse'>,
) {
return lifecycleEntriesOf(item).find((entry) => entry.code === stage) || null;
}
/** 后端仅以 current / available 表示可进入工作台;未知状态一律拒绝深链。 */
export function lifecycleEntryIsEnterable(
entry: ReturnType<typeof lifecycleEntryFor>,
): boolean {
return entry?.state === 'current' || entry?.state === 'available';
}
/** 阶段目标下拉默认值:优先 current,其次 available。 */
export function defaultLifecycleTarget(
item: TodoLike,
): Exclude<LifecycleStageCode, 'intake_parse'> | null {
const current = lifecycleEntriesOf(item).find(
(entry) => entry.code !== 'intake_parse' && entry.state === 'current',
);
const available = lifecycleEntriesOf(item).find(
(entry) => entry.code !== 'intake_parse' && entry.state === 'available',
);
return (current || available)?.code as Exclude<LifecycleStageCode, 'intake_parse'> | undefined || null;
}
/** 接收解析入口只消费后端独立授权 + run/agent 前提,不从阶段名称推导可写权限。 */
export function canOpenIntakeParse(item: TodoLike | null, chatAgentId: number | null): boolean {
if (!item) return false;
const runNo = String(item.review_run_no || '').trim();
const agentId = Number(item.owner_agent_id || chatAgentId || 0);
return Boolean(
runNo
&& agentId
&& item.ui_state?.intake_parse_authorized === true,
);
}
/**
* 行状态摘要标题:后端待办标题优先,逐级回退到阶段标签。
*/
export function todoTitleText(item: ShippingTaskSummary): string {
return String(
item.ui_state?.todo?.title
|| item.ui_state?.summary?.current_todo
|| item.ui_state?.summary?.title
|| item.ui_state?.stage?.label
|| '—',
);
}
/**
* 行阻断原因文本:优先后端 reason.message,其次 Gate 原因码的本地化标签。
* 空串表示当前无阻断(调用方据此决定红色高亮)。
*/
export function todoBlockerText(
item: TodoLike,
t: (key: string, named?: Record<string, unknown>) => string,
te: (key: string) => boolean,
): string {
const reason = item.ui_state?.reason;
const text = String(reason?.message || '').trim();
if (text) return text;
const code = String(reason?.code || '').trim();
if (!code) return '';
return resolveGateReasonLabel(code, { t, te });
}
/** 表格副行:客户 · PO · 源文件/导出文件,缺省段自动跳过。 */
export function todoSubTitleText(item: ShippingTaskSummary): string {
const segments = [
String(item.customer_name || '').trim(),
String(item.po_number || '').trim() ? `PO ${String(item.po_number).trim()}` : '',
String(item.source_file_name || '').trim()
|| String(item.artifact_summary?.export_file_name || '').trim(),
].filter(Boolean);
return segments.join(' · ');
}
/** 项次/缺口摘要:total 项 + 缺 n(缺口>0 的行数)。 */
export function todoLineBrief(item: ShippingTaskSummary): { total: number; shortage: number } {
const lines = Array.isArray(item.notice_line_summary) ? item.notice_line_summary : [];
const shortage = lines.filter((line) => Number(line.shortage_qty || 0) > 0).length;
return { total: lines.length, shortage };
}
/**
* 批量可选行:正式 Notice 且处于货代上传阶段(业务约束:批量操作仅该阶段可用)。
*/
export function isFreightUploadRow(item: ShippingTaskSummary): boolean {
return Boolean(String(item.business_no || '').trim())
&& lifecycleStageCodeOf(item) === 'freight_upload';
}
@@ -24,7 +24,6 @@ export type WorkspaceSidebarItem =
| 'schedule_runs'
| 'receipt_reports'
| 'shipping_notice'
| 'contract_payment'
| 'history';
export interface WorkspaceAgent {
@@ -1,6 +1,6 @@
/**
* features/workspace/utils/voucherCheck.display.ts
* 用途:立账凭证检核列表与明细页共用的状态文案、缺件列表、缺件数、缺失占比与企微发送状态展示。
* 用途:立账凭证检核列表、最近一次检核卡片与明细页共用的状态/模式/步骤文案。
* 依赖:vue-i18n 的 t()。
* 逻辑:AccountingVoucherCheckView / AccountingVoucherCheckDetailView 调用。
*/
@@ -18,9 +18,37 @@ export function voucherCheckStatusLabel(t: (key: string) => string, value: strin
if (value === 'technical_error' || value === 'technical_failed') return t('workspace.voucherCheck.statusTechError');
if (value === 'failed') return t('workspace.voucherCheck.statusTechError');
if (value === 'pending') return t('workspace.voucherCheck.statusPending');
if (value === 'queued') return t('workspace.voucherCheck.statusQueued');
if (value === 'running') return t('workspace.voucherCheck.statusRunning');
return value || '-';
}
/**
* 将批次执行模式映射为工作台文案。
* @param t - i18n 翻译函数
* @param value - incremental / force_all / single
*/
export function voucherCheckModeLabel(t: (key: string) => string, value: string): string {
if (value === 'force_all') return t('workspace.voucherCheck.modeForceAll');
if (value === 'single') return t('workspace.voucherCheck.modeSingle');
return t('workspace.voucherCheck.modeIncremental');
}
/**
* 将 runner 步骤码映射为工作台当前步骤文案。
* @param t - i18n 翻译函数
* @param step - current_step.step
*/
export function voucherCheckStepLabel(t: (key: string) => string, step?: string | null): string {
if (step === 'queued') return t('workspace.voucherCheck.stepQueued');
if (step === 'fetch_erp') return t('workspace.voucherCheck.stepFetchErp');
if (step === 'scan_dms') return t('workspace.voucherCheck.stepScanDms');
if (step === 'persist') return t('workspace.voucherCheck.stepPersist');
if (step === 'notify') return t('workspace.voucherCheck.stepNotify');
if (step === 'done') return t('workspace.voucherCheck.stepDone');
return step || '-';
}
/**
* 将企微汇总发送状态码映射为工作台文案。
* @param t - i18n 翻译函数
@@ -3,7 +3,8 @@
* features/workspace/views/AccountingVoucherCheckDetailView.vue
* 用途:立账凭证检核批次明细独立页,支持按 invoice 或按文件类型汇总。
* 依赖:voucherCheck.api、PaginationBar、vue-router、vue-i18n、useMessage、voucherCheck.display。
* 逻辑:路由 /workspace/accounting-voucher-check/runs/:runId;标题下用下划线 Tab 切换汇总维度;状态筛选仅在按 invoice 时出现。
* 逻辑:独立路由或 Chat 嵌入;标题下用下划线 Tab 切换汇总维度;状态筛选仅在按 invoice 时出现。
* Chat 嵌入时 runId / runNo 由父级传入,返回列表通过 close 事件。
*/
import { computed, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
@@ -24,6 +25,20 @@ import {
voucherCheckStatusLabel,
} from '../utils/voucherCheck.display';
const props = withDefaults(defineProps<{
embedded?: boolean;
runId?: number;
runNo?: string | null;
}>(), {
embedded: false,
runId: 0,
runNo: null,
});
const emit = defineEmits<{
close: [];
}>();
const { t } = useI18n();
const msg = useMessage();
const route = useRoute();
@@ -40,12 +55,17 @@ const runNo = ref('');
const viewMode = ref<'invoice' | 'fileType'>('invoice');
const scheduleRunId = computed(() => {
if (props.embedded) {
const id = Number(props.runId);
return Number.isInteger(id) && id > 0 ? id : 0;
}
const raw = route.params.runId;
const id = Number(Array.isArray(raw) ? raw[0] : raw);
return Number.isFinite(id) && id > 0 ? id : 0;
});
const titleRunId = computed(() => {
if (props.embedded && props.runNo) return props.runNo;
const q = route.query.runNo;
if (typeof q === 'string' && q.trim()) return q.trim();
return runNo.value || String(scheduleRunId.value || '');
@@ -111,6 +131,10 @@ function setViewMode(mode: 'invoice' | 'fileType') {
* 返回立账凭证检核任务列表。
*/
function backToList() {
if (props.embedded) {
emit('close');
return;
}
void router.push(WORKSPACE_PATHS.accountingVoucherCheck);
}
@@ -1,28 +1,50 @@
<script setup lang="ts">
/**
* features/workspace/views/AccountingVoucherCheckView.vue
* 用途:立账凭证检核任务列表——按资料所属期间查看批次统计。
* 依赖:voucherCheck.api、vue-i18n、useMessage、DeleteConfirmDialog、PaginationBar、formatLocalDateTime、voucherCheck.display。
* 逻辑:路由 /workspace/accounting-voucher-check;Tab 切换检核任务与企微发送记录;查看详情进入独立明细页;企微 ?run_id= 重定向到明细路由。
* 用途:立账凭证检核任务列表——按资料所属期间(年 + 月)查看批次统计,并展示最近一次检核。
* 依赖:voucherCheck.api、vue-i18n、useMessage、DeleteConfirmDialog、PaginationBar、formatLocalDateTime、voucherCheck.display、auth。
* Chat 嵌入时由 VoucherCheckChatPanel 传入 embedded / activeTab。
* 逻辑:独立路由或 Chat 嵌入;进页默认上一个自然月;「最近一次检核」不跟筛选;强制重检仅 admin,进度在本卡轮询。
* 终态用矮指标格;排队/执行中才展开进度条与当前步骤。Chat 嵌入时隐藏页头与内层 Tab。
*/
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { Download, Loader2, RefreshCw, RotateCcw, Search } from 'lucide-vue-next';
import { ChevronDown, Download, Loader2, RotateCcw, Search } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import { useMessage } from '@/shared/composables/useMessage';
import { getStoredAuthUser } from '@/shared/utils/auth';
import { formatLocalDateTime } from '@/shared/utils/dateTime';
import { WORKSPACE_PATHS } from '../constants/routes';
import {
downloadVoucherCheckExcel,
getLatestVoucherCheckRun,
listVoucherCheckNotifications,
listVoucherCheckRuns,
triggerVoucherCheckForceAll,
type VoucherCheckLatestRun,
type VoucherCheckNotificationItem,
type VoucherCheckRunItem,
} from '../api/voucherCheck.api';
import { voucherCheckNotifyStatusLabel, voucherCheckStatusLabel } from '../utils/voucherCheck.display';
import {
voucherCheckModeLabel,
voucherCheckNotifyStatusLabel,
voucherCheckStatusLabel,
voucherCheckStepLabel,
} from '../utils/voucherCheck.display';
const props = withDefaults(defineProps<{
embedded?: boolean;
activeTab?: 'tasks' | 'notifications';
}>(), {
embedded: false,
activeTab: 'tasks',
});
const emit = defineEmits<{
'open-detail': [payload: { runId: number; runNo?: string | null }];
}>();
const { t } = useI18n();
const msg = useMessage();
@@ -36,28 +58,98 @@ const items = ref<VoucherCheckRunItem[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(50);
const period = ref('');
const periodYear = ref('');
const periodMonth = ref('');
const status = ref('');
const listTab = ref<'tasks' | 'notifications'>('tasks');
const listTab = ref<'tasks' | 'notifications'>(props.activeTab);
const notifyLoading = ref(false);
const notifyItems = ref<VoucherCheckNotificationItem[]>([]);
const notifyTotal = ref(0);
const notifyPage = ref(1);
const notifyPageSize = ref(50);
const notifyStatus = ref('');
const latestRun = ref<VoucherCheckLatestRun | null>(null);
const latestLoading = ref(false);
let forcePollTimer: ReturnType<typeof setInterval> | null = null;
const isAdmin = computed(() => String(getStoredAuthUser()?.role || '').trim().toLowerCase() === 'admin');
const latestInProgress = computed(() => {
const cardStatus = latestRun.value?.status;
return cardStatus === 'queued' || cardStatus === 'running';
});
const latestHasMissing = computed(() => {
const row = latestRun.value;
if (!row) return false;
return (row.missing_file_count || 0) > 0 || (row.missing_invoice_count || 0) > 0;
});
const latestCanOpenDetail = computed(() => {
const row = latestRun.value;
if (!row?.schedule_run_id) return false;
return row.status === 'missing' || row.status === 'completed';
});
/**
* 默认资料所属期间为上一个自然月 YYYY-MM。
* 最近一次检核的四个指标格,终态矮格与执行中共用。
* 核心逻辑:缺件时后两项(缺件文件 / 缺件 invoice)标红。
*/
function previousPeriod(): string {
const latestMetrics = computed(() => {
const row = latestRun.value;
if (!row) return [];
const warn = latestHasMissing.value;
return [
{ key: 'subject', value: row.subject_count, labelKey: 'workspace.voucherCheck.subjectCount', warn: false },
{ key: 'archived', value: row.archived_file_count, labelKey: 'workspace.voucherCheck.archivedFiles', warn: false },
{ key: 'missingFiles', value: row.missing_file_count, labelKey: 'workspace.voucherCheck.missingFiles', warn },
{ key: 'missingInvoices', value: row.missing_invoice_count, labelKey: 'workspace.voucherCheck.missingInvoices', warn },
];
});
/**
* 终态是否展示失败原因:仅技术失败或带 error_message 时占一行,完整/缺件不再重复完成提示。
*/
const latestShowFailureHint = computed(() => {
const row = latestRun.value;
if (!row || latestInProgress.value) return false;
return row.status === 'technical_failed' || Boolean(row.error_message);
});
const MONTH_VALUES = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'] as const;
/**
* 进页默认资料所属期间为上一个自然月。
*/
function previousYearMonth(): { year: string; month: string } {
const d = new Date();
d.setDate(1);
d.setMonth(d.getMonth() - 1);
const m = String(d.getMonth() + 1).padStart(2, '0');
return `${d.getFullYear()}-${m}`;
return {
year: String(d.getFullYear()),
month: String(d.getMonth() + 1).padStart(2, '0'),
};
}
/**
* 组装列表查询 period:有月份则为 YYYY-MM,否则为 YYYY。
*/
const periodQuery = computed(() => {
if (!periodYear.value) return undefined;
if (periodMonth.value) return `${periodYear.value}-${periodMonth.value}`;
return periodYear.value;
});
const yearOptions = computed(() => {
const now = new Date().getFullYear();
const years: string[] = [];
for (let year = now - 5; year <= now; year += 1) {
years.push(String(year));
}
if (periodYear.value && !years.includes(periodYear.value)) {
years.unshift(periodYear.value);
years.sort();
}
return years;
});
const statusOptions = computed(() => [
{ value: '', label: t('workspace.voucherCheck.statusAll') },
{ value: 'missing', label: t('workspace.voucherCheck.statusMissing') },
@@ -89,7 +181,7 @@ async function loadNotifications() {
notifyLoading.value = true;
try {
const data = await listVoucherCheckNotifications({
period: period.value || undefined,
period: periodQuery.value,
send_status: notifyStatus.value || undefined,
page: notifyPage.value,
page_size: notifyPageSize.value,
@@ -117,6 +209,7 @@ function setListTab(tab: 'tasks' | 'notifications') {
}
page.value = 1;
void loadRuns();
void loadLatestRun();
}
/**
@@ -132,17 +225,6 @@ function searchCurrentTab() {
void loadNotifications();
}
/**
* 当前 Tab 刷新列表,不重置页码。
*/
function refreshCurrentTab() {
if (listTab.value === 'tasks') {
void loadRuns();
return;
}
void loadNotifications();
}
/**
* 下载该发送记录对应批次的 Excel。
* @param row - 企微发送记录
@@ -175,6 +257,20 @@ function formatRecipientNames(names?: string[]): string {
return names.join('、');
}
/**
* 打开批次明细:Chat 嵌入时回传父级,独立页则跳转工作台详情路由。
*/
function navigateToDetail(runId: number, runNo?: string | null) {
if (props.embedded) {
emit('open-detail', { runId, runNo: runNo || null });
return;
}
void router.push({
path: WORKSPACE_PATHS.accountingVoucherCheckDetail(runId),
query: runNo ? { runNo } : undefined,
});
}
/**
* 从发送记录跳转对应批次明细。
* @param row - 企微发送记录
@@ -184,10 +280,7 @@ function openNotifyDetail(row: VoucherCheckNotificationItem) {
msg.error(t('workspace.voucherCheck.loadFailed'));
return;
}
void router.push({
path: WORKSPACE_PATHS.accountingVoucherCheckDetail(row.schedule_run_id),
query: row.run_no ? { runNo: row.run_no } : undefined,
});
navigateToDetail(row.schedule_run_id, row.run_no);
}
/**
@@ -197,7 +290,7 @@ async function loadRuns() {
loading.value = true;
try {
const data = await listVoucherCheckRuns({
period: period.value || undefined,
period: periodQuery.value,
status: status.value || undefined,
page: page.value,
page_size: pageSize.value,
@@ -231,22 +324,100 @@ function openRunDetail(row: VoucherCheckRunItem) {
msg.error(t('workspace.voucherCheck.loadFailed'));
return;
}
void router.push({
path: WORKSPACE_PATHS.accountingVoucherCheckDetail(row.schedule_run_id),
query: row.run_no ? { runNo: row.run_no } : undefined,
});
navigateToDetail(row.schedule_run_id, row.run_no);
}
/**
* 停止强制重检后的列表轮询。
* 停止最近一次检核的进度轮询。
*/
function stopForcePoll() {
function stopLatestPoll() {
if (forcePollTimer) {
clearInterval(forcePollTimer);
forcePollTimer = null;
}
}
/**
* 拉取最近一次检核卡片;不跟下方列表的年/月/状态筛选。
* @param options.silent - 轮询时不切换卡片 loading,避免进度条闪烁
*/
async function loadLatestRun(options?: { silent?: boolean }) {
if (!options?.silent) latestLoading.value = true;
try {
latestRun.value = await getLatestVoucherCheckRun();
} catch (e: any) {
if (!options?.silent) {
msg.error(e?.message || t('workspace.voucherCheck.latestLoadFailed'));
}
} finally {
if (!options?.silent) latestLoading.value = false;
}
}
/**
* 排队或执行中时轮询卡片;进入终态后刷新下方列表。
*/
function syncLatestPoll() {
stopLatestPoll();
if (listTab.value !== 'tasks' || !latestInProgress.value) return;
forcePollTimer = setInterval(() => {
void (async () => {
const previous = latestRun.value?.status;
await loadLatestRun({ silent: true });
const next = latestRun.value?.status;
if ((previous === 'queued' || previous === 'running') && next !== 'queued' && next !== 'running') {
stopLatestPoll();
void loadRuns();
}
})();
}, 3000);
}
/**
* 最近一次检核状态徽章样式。
* @param value - 卡片状态
*/
function latestBadgeClass(value: string): string {
if (value === 'missing' || value === 'technical_failed') return 'bg-rose-50 text-rose-700';
if (value === 'completed') return 'bg-emerald-50 text-emerald-700';
if (value === 'queued' || value === 'running') return 'bg-blue-50 text-blue-700';
return 'bg-surface-soft text-secondary';
}
/**
* 卡片当前步骤主文案:终态用完成提示,其余按步骤码翻译。
* @param row - 最近一次检核
*/
function latestStepText(row: VoucherCheckLatestRun): string {
if (row.status === 'queued') return t('workspace.voucherCheck.stepQueued');
if (row.status === 'missing' && (row.current_step?.step === 'done' || !row.current_step)) {
return t('workspace.voucherCheck.latestDoneHint');
}
if (row.status === 'completed' && (row.current_step?.step === 'done' || !row.current_step)) {
return t('workspace.voucherCheck.latestCompleteHint');
}
if (row.status === 'technical_failed' && row.current_step?.step === 'fetch_erp') {
return t('workspace.voucherCheck.stepFetchErpIncomplete');
}
return voucherCheckStepLabel(t, row.current_step?.step);
}
/**
* 卡片步骤辅文案:失败原因、排队等待或扫描进度。
* @param row - 最近一次检核
*/
function latestHintText(row: VoucherCheckLatestRun): string {
if (row.error_message) return row.error_message;
if (row.status === 'queued') return t('workspace.voucherCheck.stepQueuedHint');
if (row.status === 'running' && row.current_step?.step === 'scan_dms' && row.subject_count > 0) {
return t('workspace.voucherCheck.processedHint', {
processed: row.processed_count,
total: row.subject_count,
});
}
return '';
}
/**
* 打开强制重检确认框;用公共 DeleteConfirmDialog 替代原生 window.confirm。
*/
@@ -264,13 +435,8 @@ async function forceRecheck() {
try {
const data = await triggerVoucherCheckForceAll();
msg.success(t('workspace.voucherCheck.forceQueued', { runNo: data.run_no }));
await loadRuns();
stopForcePoll();
const started = Date.now();
forcePollTimer = setInterval(() => {
void loadRuns();
if (Date.now() - started > 120_000) stopForcePoll();
}, 5000);
await loadLatestRun({ silent: true });
syncLatestPoll();
} catch (e: any) {
msg.error(e?.message || t('workspace.voucherCheck.forceFailed'));
} finally {
@@ -278,27 +444,62 @@ async function forceRecheck() {
}
}
/**
* 从最近一次检核卡片打开本批明细。
*/
function openLatestDetail() {
const row = latestRun.value;
if (!row?.schedule_run_id) {
msg.error(t('workspace.voucherCheck.loadFailed'));
return;
}
navigateToDetail(row.schedule_run_id, row.run_no);
}
/**
* 仅在检核任务 Tab 且最近一批仍在排队/执行时轮询卡片。
*/
watch([listTab, latestInProgress], () => {
syncLatestPoll();
});
watch(
() => props.activeTab,
(tab) => {
if (!props.embedded) return;
if (listTab.value === tab) return;
setListTab(tab);
},
);
onMounted(async () => {
if (redirectLegacyRunQuery()) return;
period.value = previousPeriod();
if (!props.embedded && redirectLegacyRunQuery()) return;
const previous = previousYearMonth();
periodYear.value = previous.year;
periodMonth.value = previous.month;
const qStatus = route.query.status;
if (typeof qStatus === 'string' && qStatus) status.value = qStatus;
await loadRuns();
if (props.embedded) listTab.value = props.activeTab;
if (listTab.value === 'notifications') {
await loadNotifications();
return;
}
await Promise.all([loadRuns(), loadLatestRun()]);
});
onUnmounted(() => {
stopForcePoll();
stopLatestPoll();
});
</script>
<template>
<div class="space-y-5 animate-fade-in-up">
<header class="space-y-1">
<div class="space-y-4 animate-fade-in-up">
<header v-if="!embedded" class="space-y-1">
<h1 class="text-2xl font-bold text-primary">{{ $t('workspace.voucherCheck.title') }}</h1>
<p class="text-sm text-muted">{{ $t('workspace.voucherCheck.subtitle') }}</p>
</header>
<div class="flex gap-1 border-b border-default" role="tablist">
<div v-if="!embedded" class="flex gap-1 border-b border-default" role="tablist">
<button
type="button"
role="tab"
@@ -321,22 +522,137 @@ onUnmounted(() => {
</button>
</div>
<article
v-if="listTab === 'tasks'"
class="overflow-hidden rounded-2xl border border-default bg-surface"
aria-live="polite"
>
<div
class="flex flex-wrap items-start justify-between gap-3 px-4 py-2.5"
:class="latestInProgress ? 'bg-blue-50' : ''"
>
<div>
<h2 class="text-sm font-semibold text-primary">{{ $t('workspace.voucherCheck.latestTitle') }}</h2>
<p v-if="latestRun" class="mt-0.5 text-xs text-muted">
<span class="mr-3">{{ $t('workspace.voucherCheck.latestBatch', { runNo: latestRun.run_no }) }}</span>
<span class="mr-3">{{ $t('workspace.voucherCheck.latestPeriod', { period: latestRun.period_month || '-' }) }}</span>
<span>{{ voucherCheckModeLabel(t, latestRun.mode) }}</span>
</p>
</div>
<div class="flex shrink-0 items-center gap-2">
<button
v-if="latestCanOpenDetail"
type="button"
class="text-sm font-semibold text-brand-700 hover:underline"
@click="openLatestDetail"
>
{{ $t('workspace.voucherCheck.viewLatestDetail') }}
</button>
<span
v-if="latestRun"
class="inline-flex rounded-full px-2.5 py-0.5 text-xs font-semibold"
:class="latestBadgeClass(latestRun.status)"
>
{{ voucherCheckStatusLabel(t, latestRun.status) }}
</span>
<button
v-if="isAdmin"
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-amber-300 bg-amber-50 px-3 py-1.5 text-sm font-medium text-amber-900 transition-colors hover:bg-amber-100 disabled:opacity-50"
:disabled="forcing || latestInProgress"
@click="openForceRecheck()"
>
<Loader2 v-if="forcing" class="h-3.5 w-3.5 animate-spin" />
<RotateCcw v-else class="h-3.5 w-3.5" />
{{ $t('workspace.voucherCheck.forceRecheck') }}
</button>
</div>
</div>
<div v-if="latestLoading && !latestRun" class="flex items-center justify-center gap-2 px-4 py-6 text-sm text-muted">
<Loader2 class="h-4 w-4 animate-spin" />
{{ $t('workspace.voucherCheck.loading') }}
</div>
<p v-else-if="!latestRun" class="px-4 py-6 text-center text-sm text-muted">
{{ $t('workspace.voucherCheck.latestEmpty') }}
</p>
<div v-else class="px-4 pb-3">
<template v-if="latestInProgress">
<div class="h-2 overflow-hidden rounded-full bg-slate-200">
<div
class="h-full rounded-full bg-teal-700 transition-[width] duration-300"
:style="{ width: `${latestRun.progress_percent || 0}%` }"
/>
</div>
<div class="mt-1.5 mb-2.5 flex flex-wrap justify-between gap-3 text-xs text-muted">
<span>{{ $t('workspace.voucherCheck.progress', { percent: latestRun.progress_percent || 0 }) }}</span>
<span>
{{ $t('workspace.voucherCheck.startedAt') }}:{{ formatLocalDateTime(latestRun.started_at) }}
 {{ $t('workspace.voucherCheck.finishedAt') }}:{{ $t('workspace.voucherCheck.inProgress') }}
</span>
</div>
<p class="mb-2.5 text-[13px] text-slate-700">
{{ latestStepText(latestRun) }}
<small v-if="latestHintText(latestRun)" class="mt-0.5 block text-muted">{{ latestHintText(latestRun) }}</small>
</p>
</template>
<div class="grid grid-cols-2 gap-2 md:grid-cols-4">
<div
v-for="metric in latestMetrics"
:key="metric.key"
class="rounded-[10px] border border-default bg-slate-50 px-2.5 py-2"
>
<b
class="block text-lg font-semibold leading-tight tabular-nums"
:class="metric.warn ? 'text-rose-700' : 'text-primary'"
>{{ metric.value }}</b>
<span class="text-[11px] text-muted">{{ $t(metric.labelKey) }}</span>
</div>
</div>
<p v-if="latestShowFailureHint" class="mt-2 text-[13px] text-slate-700">
{{ latestStepText(latestRun) }}
<small v-if="latestHintText(latestRun)" class="mt-0.5 block text-muted">{{ latestHintText(latestRun) }}</small>
</p>
</div>
</article>
<section class="flex flex-wrap items-end gap-3 rounded-2xl border border-default/80 bg-surface/70 px-4 py-3 shadow-sm">
<label class="flex flex-col gap-1 text-xs font-medium text-muted">
{{ $t('workspace.voucherCheck.period') }}
<input v-model="period" type="month" class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-primary" />
<span class="flex items-center gap-2">
<span class="period-select">
<select v-model="periodYear" class="period-select__control w-[4.75rem]">
<option v-for="year in yearOptions" :key="year" :value="year">{{ year }}</option>
</select>
<ChevronDown class="period-select__icon" aria-hidden="true" />
</span>
<span class="period-select">
<select v-model="periodMonth" class="period-select__control w-[4.75rem]">
<option value="">{{ $t('workspace.voucherCheck.periodMonthAll') }}</option>
<option v-for="month in MONTH_VALUES" :key="month" :value="month">
{{ $t('workspace.voucherCheck.periodMonthValue', { n: Number(month) }) }}
</option>
</select>
<ChevronDown class="period-select__icon" aria-hidden="true" />
</span>
</span>
</label>
<label v-if="listTab === 'tasks'" class="flex flex-col gap-1 text-xs font-medium text-muted">
{{ $t('workspace.voucherCheck.status') }}
<select v-model="status" class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-primary">
<option v-for="opt in statusOptions" :key="opt.value || 'all'" :value="opt.value">{{ opt.label }}</option>
</select>
<span class="period-select">
<select v-model="status" class="period-select__control w-[6rem]">
<option v-for="opt in statusOptions" :key="opt.value || 'all'" :value="opt.value">{{ opt.label }}</option>
</select>
<ChevronDown class="period-select__icon" aria-hidden="true" />
</span>
</label>
<label v-else class="flex flex-col gap-1 text-xs font-medium text-muted">
{{ $t('workspace.voucherCheck.notifyStatus') }}
<select v-model="notifyStatus" class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-primary">
<option v-for="opt in notifyStatusOptions" :key="opt.value || 'all'" :value="opt.value">{{ opt.label }}</option>
</select>
<span class="period-select">
<select v-model="notifyStatus" class="period-select__control w-[7.25rem]">
<option v-for="opt in notifyStatusOptions" :key="opt.value || 'all'" :value="opt.value">{{ opt.label }}</option>
</select>
<ChevronDown class="period-select__icon" aria-hidden="true" />
</span>
</label>
<button
type="button"
@@ -346,25 +662,6 @@ onUnmounted(() => {
<Search class="h-3.5 w-3.5" />
{{ $t('workspace.voucherCheck.search') }}
</button>
<button
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft"
@click="refreshCurrentTab"
>
<RefreshCw class="h-3.5 w-3.5" />
{{ $t('workspace.voucherCheck.refresh') }}
</button>
<button
v-if="listTab === 'tasks'"
type="button"
class="ml-auto inline-flex items-center gap-1 rounded-xl border border-amber-300 bg-amber-50 px-3 py-1.5 text-sm font-medium text-amber-900 transition-colors hover:bg-amber-100 disabled:opacity-50"
:disabled="forcing"
@click="openForceRecheck()"
>
<Loader2 v-if="forcing" class="h-3.5 w-3.5 animate-spin" />
<RotateCcw v-else class="h-3.5 w-3.5" />
{{ $t('workspace.voucherCheck.forceRecheck') }}
</button>
</section>
<section v-if="listTab === 'tasks'" class="overflow-hidden rounded-2xl border border-default bg-surface">
@@ -524,3 +821,51 @@ onUnmounted(() => {
/>
</div>
</template>
<style scoped>
/**
* 隐藏系统原生下拉箭头(含 Chromium ::picker-icon / Edge ::-ms-expand)。
* 只保留模板里的 ChevronDown,避免 Windows 下年份与月份箭头叠在一起。
*/
.period-select {
position: relative;
display: inline-flex;
align-items: center;
}
.period-select__control {
box-sizing: border-box;
border-radius: 0.75rem;
border: 1px solid var(--border-default);
background-color: var(--bg-surface);
background-image: none;
padding: 0.375rem 1.75rem 0.375rem 0.625rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--text-primary);
font-size: 0.875rem;
line-height: 1.25rem;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
.period-select__control::-ms-expand {
display: none;
}
.period-select__control::picker-icon {
display: none;
content: none;
}
.period-select__icon {
pointer-events: none;
position: absolute;
right: 0.5rem;
height: 0.875rem;
width: 0.875rem;
color: var(--text-muted);
}
</style>