feat(shipping-notice): 落地字段资产治理与唯一 Schema,自动建单随版本冻结
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
b7307fc573
commit
3a1dbf7ce5
144 files changed
+15167
-4480
No files matched your search
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* features/admin/api/shipping-field-assets.api.ts
|
||||
* 用途:全局字段资产库 JSON API。
|
||||
* 依赖:shared/api/client、shared/utils/auth、字段资产 DTO。
|
||||
* 逻辑:字段资产库页面通过本模块加载目录、维护扩展字段与影响分析。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type {
|
||||
CreateShippingFieldExtensionPayload,
|
||||
ShippingFieldAsset,
|
||||
ShippingFieldAssetAuditPage,
|
||||
ShippingFieldAssetImpact,
|
||||
ShippingFieldAssetListResponse,
|
||||
UpdateShippingFieldExtensionPayload,
|
||||
} from '../types/shipping-field-assets.types';
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||
|
||||
/** 列出全局字段资产,支持搜索与类型/状态/范围筛选。 */
|
||||
export const listShippingFieldAssets = (params?: {
|
||||
q?: string;
|
||||
asset_kind?: 'system_standard' | 'extension';
|
||||
status?: 'active' | 'retired';
|
||||
scope?: 'header' | 'line';
|
||||
}) => {
|
||||
const query = new URLSearchParams();
|
||||
if (params?.q) query.set('q', params.q);
|
||||
if (params?.asset_kind) query.set('asset_kind', params.asset_kind);
|
||||
if (params?.status) query.set('status', params.status);
|
||||
if (params?.scope) query.set('scope', params.scope);
|
||||
const suffix = query.toString() ? `?${query.toString()}` : '';
|
||||
return requestJson<ShippingFieldAssetListResponse>(`/api/admin/shipping-field-assets${suffix}`, auth());
|
||||
};
|
||||
|
||||
/** 读取单个字段资产详情。 */
|
||||
export const getShippingFieldAsset = (fieldId: string) =>
|
||||
requestJson<ShippingFieldAsset>(`/api/admin/shipping-field-assets/${fieldId}`, auth());
|
||||
|
||||
/** 新建扩展字段资产。 */
|
||||
export const createShippingFieldExtension = (payload: CreateShippingFieldExtensionPayload) =>
|
||||
requestJson<ShippingFieldAsset>('/api/admin/shipping-field-assets', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
...jsonAuth(),
|
||||
});
|
||||
|
||||
/** 更新扩展字段显示属性;标准字段只读;须带 expected_updated_at 乐观锁。 */
|
||||
export const updateShippingFieldExtension = (fieldId: string, payload: UpdateShippingFieldExtensionPayload) =>
|
||||
requestJson<ShippingFieldAsset>(`/api/admin/shipping-field-assets/${fieldId}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(payload),
|
||||
...jsonAuth(),
|
||||
});
|
||||
|
||||
/** 弃用扩展字段;原因必填;有阻断下游时须 confirmImpact。 */
|
||||
export const retireShippingFieldExtension = (
|
||||
fieldId: string,
|
||||
reason: string,
|
||||
options?: { confirmImpact?: boolean },
|
||||
) =>
|
||||
requestJson<ShippingFieldAsset>(`/api/admin/shipping-field-assets/${fieldId}/retire`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
reason,
|
||||
confirm_impact: Boolean(options?.confirmImpact),
|
||||
}),
|
||||
...jsonAuth(),
|
||||
});
|
||||
|
||||
/** 恢复已弃用扩展字段;原因必填。 */
|
||||
export const restoreShippingFieldExtension = (fieldId: string, reason: string) =>
|
||||
requestJson<ShippingFieldAsset>(`/api/admin/shipping-field-assets/${fieldId}/restore`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ reason }),
|
||||
...jsonAuth(),
|
||||
});
|
||||
|
||||
/** 单字段影响分析:阻断下游与历史只读提示。 */
|
||||
export const getShippingFieldAssetImpact = (fieldId: string) =>
|
||||
requestJson<ShippingFieldAssetImpact>(`/api/admin/shipping-field-assets/${fieldId}/impact`, auth());
|
||||
|
||||
/** 读取字段资产审计时间线。 */
|
||||
export const listShippingFieldAssetAudits = (fieldId: string, limit = 50) =>
|
||||
requestJson<ShippingFieldAssetAuditPage>(
|
||||
`/api/admin/shipping-field-assets/${fieldId}/audits?limit=${limit}`,
|
||||
auth(),
|
||||
);
|
||||
@@ -250,7 +250,6 @@ export const generateOrderProfileOcrCoordinateEvidence = (documentId: number, ta
|
||||
|
||||
/** 三步向导的唯一落库动作:原子创建草稿、主样本、Revision 和编辑租约。 */
|
||||
export const completeOrderDocumentProfileWizard = (payload: {
|
||||
profile_code: string;
|
||||
display_name: string;
|
||||
schema_version_id: number;
|
||||
document_id: number;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/admin/api/shipping-order-schema.api.ts
|
||||
* 用途:订单 Schema 管理 JSON API。
|
||||
* 用途:单一发货订单 Schema 管理 JSON API。
|
||||
* 依赖:shared/api/client、shared/utils/auth、订单 Schema DTO。
|
||||
* 逻辑:页面通过本模块加载状态、维护字段与草稿、发布不可变版本。
|
||||
* 逻辑:页面加载状态、维护草稿与发布版本;无多族参数。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
@@ -24,17 +24,15 @@ import type {
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||
|
||||
/** 读取唯一订单 Schema、字段目录和版本。 */
|
||||
/** 读取发货订单 Schema 工作台状态。 */
|
||||
export const getShippingOrderSchemaState = () =>
|
||||
requestJson<ShippingOrderSchemaState>('/api/admin/shipping-order-schema', auth());
|
||||
|
||||
/** 保存订单字段模板中的自动建单总开关。 */
|
||||
export const saveShippingOrderAutoCreationPolicy = (enabled: boolean) =>
|
||||
requestJson<{ enabled: boolean }>('/api/admin/shipping-order-schema/auto-creation-policy', {
|
||||
method: 'PUT', body: JSON.stringify({ enabled }), ...jsonAuth(),
|
||||
});
|
||||
/** 读取已发布生效的自动建单策略。 */
|
||||
export const getShippingOrderAutoCreationPolicy = () =>
|
||||
requestJson<{ enabled: boolean }>('/api/admin/shipping-order-schema/auto-creation-policy', auth());
|
||||
|
||||
/** 初始化全局唯一订单 Schema。 */
|
||||
/** 初始化默认订单 Schema。 */
|
||||
export const initializeShippingOrderSchema = (payload: { display_name: string; description?: string }) =>
|
||||
requestJson<ShippingOrderSchemaState>('/api/admin/shipping-order-schema', {
|
||||
method: 'POST', body: JSON.stringify(payload), ...jsonAuth(),
|
||||
@@ -78,13 +76,21 @@ export const deleteShippingOrderField = (fieldId: string) =>
|
||||
});
|
||||
|
||||
/** 创建下一 Schema 草稿,可复制指定版本。 */
|
||||
export const createShippingOrderSchemaDraft = (payload: { copy_from_version_id?: number; change_note?: string }) =>
|
||||
export const createShippingOrderSchemaDraft = (
|
||||
payload: { copy_from_version_id?: number; change_note?: string },
|
||||
) =>
|
||||
requestJson<ShippingOrderSchemaVersion>('/api/admin/shipping-order-schema/versions', {
|
||||
method: 'POST', body: JSON.stringify(payload), ...jsonAuth(),
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
...jsonAuth(),
|
||||
});
|
||||
|
||||
/** 分页读取版本历史概要,完整定义由详情接口按需加载。 */
|
||||
export const listShippingOrderSchemaVersions = (page = 1, pageSize = 20, versionNumber?: number) =>
|
||||
export const listShippingOrderSchemaVersions = (
|
||||
page = 1,
|
||||
pageSize = 20,
|
||||
versionNumber?: number,
|
||||
) =>
|
||||
requestJson<ShippingOrderSchemaVersionPage>(
|
||||
`/api/admin/shipping-order-schema/versions?page=${page}&page_size=${pageSize}${versionNumber ? `&version_number=${versionNumber}` : ''}`,
|
||||
auth(),
|
||||
@@ -92,10 +98,16 @@ export const listShippingOrderSchemaVersions = (page = 1, pageSize = 20, version
|
||||
|
||||
/** 读取一个版本的完整不可变快照。 */
|
||||
export const getShippingOrderSchemaVersion = (versionId: number) =>
|
||||
requestJson<ShippingOrderSchemaVersion>(`/api/admin/shipping-order-schema/versions/${versionId}`, auth());
|
||||
requestJson<ShippingOrderSchemaVersion>(
|
||||
`/api/admin/shipping-order-schema/versions/${versionId}`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 比较两个已保存版本,字段级变更由服务端按稳定 field_id 计算。 */
|
||||
export const getShippingOrderSchemaVersionDiff = (versionId: number, againstVersionId: number) =>
|
||||
export const getShippingOrderSchemaVersionDiff = (
|
||||
versionId: number,
|
||||
againstVersionId: number,
|
||||
) =>
|
||||
requestJson<ShippingOrderSchemaVersionDiff>(
|
||||
`/api/admin/shipping-order-schema/versions/${versionId}/diff?against_version_id=${againstVersionId}`,
|
||||
auth(),
|
||||
@@ -108,8 +120,22 @@ export const listShippingOrderSchemaAuditEvents = (page = 1, pageSize = 20) =>
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 读取当前已发布字段契约。 */
|
||||
export const getShippingOrderPublishedContract = () =>
|
||||
requestJson<{
|
||||
schema_version_id: number;
|
||||
schema_code: string;
|
||||
version: number;
|
||||
checksum: string;
|
||||
fields: ShippingOrderFieldConfig[];
|
||||
}>('/api/admin/shipping-order-schema/published-contract', auth());
|
||||
|
||||
/** 分页读取实际使用指定 Schema 版本的订单解析记录与状态汇总。 */
|
||||
export const getShippingOrderSchemaVersionUsage = (versionId: number, page = 1, pageSize = 20) =>
|
||||
export const getShippingOrderSchemaVersionUsage = (
|
||||
versionId: number,
|
||||
page = 1,
|
||||
pageSize = 20,
|
||||
) =>
|
||||
requestJson<ShippingOrderSchemaVersionUsage>(
|
||||
`/api/admin/shipping-order-schema/versions/${versionId}/usage?page=${page}&page_size=${pageSize}`,
|
||||
auth(),
|
||||
@@ -118,7 +144,8 @@ export const getShippingOrderSchemaVersionUsage = (versionId: number, page = 1,
|
||||
/** 只读评估目标 Schema 版本对已发布订单文档模板的字段级影响。 */
|
||||
export const getShippingOrderSchemaProfileImpact = (versionId: number) =>
|
||||
requestJson<ShippingOrderSchemaProfileImpact>(
|
||||
`/api/admin/shipping-order-schema/versions/${versionId}/profile-impact`, auth(),
|
||||
`/api/admin/shipping-order-schema/versions/${versionId}/profile-impact`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 读取单次动态订单解析冻结输入、LLM 输出、裁决和证据的只读审计详情。 */
|
||||
@@ -128,17 +155,23 @@ export const getShippingOrderExtractionAudit = (extractionId: number) =>
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 整体保存草稿字段配置及每个字段的版本纳入状态。 */
|
||||
/** 整体保存草稿字段配置、自动建单策略及每个字段的版本纳入状态。 */
|
||||
export const saveShippingOrderSchemaDraft = (
|
||||
versionId: number,
|
||||
payload: {
|
||||
fields: ShippingOrderFieldConfig[];
|
||||
auto_creation_policy?: { enabled: boolean };
|
||||
change_note?: string;
|
||||
expected_lock_version: number;
|
||||
},
|
||||
) => requestJson<ShippingOrderSchemaVersion>(`/api/admin/shipping-order-schema/versions/${versionId}`, {
|
||||
method: 'PUT', body: JSON.stringify(payload), ...jsonAuth(),
|
||||
});
|
||||
) => requestJson<ShippingOrderSchemaVersion>(
|
||||
`/api/admin/shipping-order-schema/versions/${versionId}`,
|
||||
{
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(payload),
|
||||
...jsonAuth(),
|
||||
},
|
||||
);
|
||||
|
||||
/** 删除错误草稿;发布版本由服务端拒绝删除。 */
|
||||
export const deleteShippingOrderSchemaDraft = (versionId: number) =>
|
||||
@@ -148,27 +181,56 @@ export const deleteShippingOrderSchemaDraft = (versionId: number) =>
|
||||
|
||||
/** 发布草稿并自动退役上一当前版本。 */
|
||||
export const publishShippingOrderSchemaDraft = (
|
||||
versionId: number, expectedLockVersion: number, confirmProfileImpact = false,
|
||||
versionId: number,
|
||||
expectedLockVersion: number,
|
||||
confirmProfileImpact = false,
|
||||
) =>
|
||||
requestJson<ShippingOrderSchemaVersion>(
|
||||
`/api/admin/shipping-order-schema/versions/${versionId}/publish`,
|
||||
{ method: 'POST', body: JSON.stringify({ expected_lock_version: expectedLockVersion, confirm_profile_impact: confirmProfileImpact }), ...jsonAuth() },
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
expected_lock_version: expectedLockVersion,
|
||||
confirm_profile_impact: confirmProfileImpact,
|
||||
}),
|
||||
...jsonAuth(),
|
||||
},
|
||||
);
|
||||
|
||||
/** 读取受控履约能力目录及策略版本,页面不提供任意表达式配置。 */
|
||||
export const getShippingFulfillmentPolicyState = () =>
|
||||
requestJson<ShippingFulfillmentPolicyState>('/api/admin/shipping-fulfillment-policies', auth());
|
||||
requestJson<ShippingFulfillmentPolicyState>(
|
||||
'/api/admin/shipping-fulfillment-policies',
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 创建按稳定字段 ID 绑定的下一履约策略草稿。 */
|
||||
export const createShippingFulfillmentPolicyDraft = (payload: {
|
||||
field_bindings: Array<{ capability_code: string; field_id: string }>;
|
||||
change_note?: string;
|
||||
}) => requestJson<ShippingFulfillmentPolicy>('/api/admin/shipping-fulfillment-policies', {
|
||||
method: 'POST', body: JSON.stringify(payload), ...jsonAuth(),
|
||||
});
|
||||
export const createShippingFulfillmentPolicyDraft = (
|
||||
payload: {
|
||||
field_bindings: Array<{ capability_code: string; field_id: string }>;
|
||||
change_note?: string;
|
||||
},
|
||||
) => requestJson<ShippingFulfillmentPolicy>(
|
||||
'/api/admin/shipping-fulfillment-policies',
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
...jsonAuth(),
|
||||
},
|
||||
);
|
||||
|
||||
/** 显式发布策略草稿;服务端原子退役上一发布版本。 */
|
||||
export const publishShippingFulfillmentPolicy = (policyId: number, expectedLockVersion: number) =>
|
||||
requestJson<ShippingFulfillmentPolicy>(`/api/admin/shipping-fulfillment-policies/${policyId}/publish`, {
|
||||
method: 'POST', body: JSON.stringify({ expected_lock_version: expectedLockVersion }), ...jsonAuth(),
|
||||
});
|
||||
export const publishShippingFulfillmentPolicy = (
|
||||
policyId: number,
|
||||
expectedLockVersion: number,
|
||||
) =>
|
||||
requestJson<ShippingFulfillmentPolicy>(
|
||||
`/api/admin/shipping-fulfillment-policies/${policyId}/publish`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
expected_lock_version: expectedLockVersion,
|
||||
}),
|
||||
...jsonAuth(),
|
||||
},
|
||||
);
|
||||
@@ -69,7 +69,7 @@ const navigateWecom = (routeName: string): void => {
|
||||
const isShippingNavActive = (item: typeof SHIPPING_CONFIG_SUB_MODULE_METAS[number]): boolean => {
|
||||
if (route.name !== item.routeName) return false;
|
||||
if (!item.query) return true;
|
||||
const section = typeof route.query.section === 'string' ? route.query.section : 'orderSchema';
|
||||
const section = typeof route.query.section === 'string' ? route.query.section : 'parsing';
|
||||
if (item.query.section === 'parsing') return section === 'parsing' || section === 'inventoryFields';
|
||||
return section === item.query.section;
|
||||
};
|
||||
@@ -178,7 +178,7 @@ watch(
|
||||
v-for="sub in SHIPPING_CONFIG_SUB_MODULE_METAS.filter((entry) => entry.groupKey === groupKey)"
|
||||
:key="sub.id"
|
||||
type="button"
|
||||
class="admin-nav-subitem py-1.5 pl-3"
|
||||
class="admin-nav-subitem w-[8em] whitespace-nowrap py-1.5 pl-3"
|
||||
:class="{ 'admin-nav-subitem--active': isShippingNavActive(sub) }"
|
||||
@click="navigateShipping(sub)"
|
||||
>
|
||||
|
||||
@@ -15,11 +15,23 @@ export interface AdminModuleMeta {
|
||||
|
||||
export interface ShippingConfigSubModuleMeta {
|
||||
id: ShippingConfigSubModuleId;
|
||||
routeName: 'AdminShippingInventory' | 'AdminShippingIdentityRules' | 'AdminShippingOrderExtractionRuns' | 'AdminShippingOrderDocumentProfiles';
|
||||
path: 'shipping-notice' | 'shipping-identity-rules' | 'shipping-order-extraction-runs' | 'shipping-order-document-profiles';
|
||||
routeName:
|
||||
| 'AdminShippingInventory'
|
||||
| 'AdminShippingFieldAssets'
|
||||
| 'AdminShippingOrderSchema'
|
||||
| 'AdminShippingIdentityRules'
|
||||
| 'AdminShippingOrderExtractionRuns'
|
||||
| 'AdminShippingOrderDocumentProfiles';
|
||||
path:
|
||||
| 'shipping-notice'
|
||||
| 'shipping-field-assets'
|
||||
| 'shipping-order-schema'
|
||||
| 'shipping-identity-rules'
|
||||
| 'shipping-order-extraction-runs'
|
||||
| 'shipping-order-document-profiles';
|
||||
labelKey: string;
|
||||
groupKey: 'admin.nav.shippingOrderRecognition' | 'admin.nav.shippingInventoryManagement' | 'admin.nav.shippingRunAudit';
|
||||
query?: { section: 'orderSchema' | 'parsing' | 'profiles' | 'sources' | 'mappings' | 'rules' | 'templates' | 'snapshots' | 'exports' };
|
||||
query?: { section: 'parsing' | 'profiles' | 'sources' | 'mappings' | 'rules' | 'templates' | 'snapshots' | 'exports' };
|
||||
}
|
||||
|
||||
/** 已独立拆分的模块(全部 admin 模块均已拆分) */
|
||||
@@ -46,7 +58,8 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
|
||||
|
||||
/** 货代管理的业务导航唯一真相源;按基础定义、适配规则、运行任务的依赖顺序排列。 */
|
||||
export const SHIPPING_CONFIG_SUB_MODULE_METAS: ShippingConfigSubModuleMeta[] = [
|
||||
{ id: 'order_fields', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.nav.shippingOrderFields', groupKey: 'admin.nav.shippingOrderRecognition', query: { section: 'orderSchema' } },
|
||||
{ id: 'field_assets', routeName: 'AdminShippingFieldAssets', path: 'shipping-field-assets', labelKey: 'admin.nav.shippingFieldAssets', groupKey: 'admin.nav.shippingOrderRecognition' },
|
||||
{ id: 'order_schema', routeName: 'AdminShippingOrderSchema', path: 'shipping-order-schema', labelKey: 'admin.nav.shippingOrderSchema', groupKey: 'admin.nav.shippingOrderRecognition' },
|
||||
{ id: 'order_document_profiles', routeName: 'AdminShippingOrderDocumentProfiles', path: 'shipping-order-document-profiles', labelKey: 'admin.nav.shippingOrderDocumentProfiles', groupKey: 'admin.nav.shippingOrderRecognition' },
|
||||
{ id: 'identity_rules', routeName: 'AdminShippingIdentityRules', path: 'shipping-identity-rules', labelKey: 'admin.nav.shippingIdentityRules', groupKey: 'admin.nav.shippingOrderRecognition' },
|
||||
{ id: 'order_extraction_runs', routeName: 'AdminShippingOrderExtractionRuns', path: 'shipping-order-extraction-runs', labelKey: 'admin.nav.shippingOrderExtractionRuns', groupKey: 'admin.nav.shippingOrderRecognition' },
|
||||
|
||||
+864
@@ -0,0 +1,864 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-field-assets/ShippingFieldAssetsPage.vue
|
||||
* 用途:字段资产库主工作台——标准/扩展列表、详情、扩展弃用恢复、影响与审计。
|
||||
* 依赖:shipping-field-assets.api、BusinessError、useMessage、Vue I18n。
|
||||
* 逻辑:由 Admin 路由挂载;视觉与订单 Schema 页对齐(页眉、双栏工作台、选中态、主次按钮);
|
||||
* 采用记录可跳转唯一发货订单 Schema 的历史版本;Schema 采用规则在独立页面编辑;
|
||||
* 审计优先展示属性级差异摘要,原始 JSON 折叠为技术详情。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import { RouterLink } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
createShippingFieldExtension,
|
||||
getShippingFieldAsset,
|
||||
getShippingFieldAssetImpact,
|
||||
listShippingFieldAssetAudits,
|
||||
listShippingFieldAssets,
|
||||
restoreShippingFieldExtension,
|
||||
retireShippingFieldExtension,
|
||||
updateShippingFieldExtension,
|
||||
} from '@/features/admin/api/shipping-field-assets.api';
|
||||
import type {
|
||||
CreateShippingFieldExtensionPayload,
|
||||
ShippingFieldAsset,
|
||||
ShippingFieldAssetAuditEvent,
|
||||
ShippingFieldAssetImpact,
|
||||
} from '@/features/admin/types/shipping-field-assets.types';
|
||||
|
||||
const { t } = useI18n();
|
||||
const message = useMessage();
|
||||
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
const items = ref<ShippingFieldAsset[]>([]);
|
||||
const selectedId = ref<string | null>(null);
|
||||
const q = ref('');
|
||||
const kindFilter = ref<'system_standard' | 'extension' | ''>('');
|
||||
const statusFilter = ref<'active' | 'retired' | ''>('');
|
||||
const impact = ref<ShippingFieldAssetImpact | null>(null);
|
||||
const audits = ref<ShippingFieldAssetAuditEvent[]>([]);
|
||||
const selectedDetail = ref<ShippingFieldAsset | null>(null);
|
||||
const showCreate = ref(false);
|
||||
const showReasonDialog = ref(false);
|
||||
const reasonAction = ref<'retire' | 'restore'>('retire');
|
||||
const reasonText = ref('');
|
||||
const confirmImpactChecked = ref(false);
|
||||
const createForm = ref<CreateShippingFieldExtensionPayload>({
|
||||
field_code: '',
|
||||
scope: 'header',
|
||||
value_type: 'string',
|
||||
display_name: '',
|
||||
semantic_description: '',
|
||||
});
|
||||
const editName = ref('');
|
||||
const editSemantic = ref('');
|
||||
|
||||
const selected = computed(() => selectedDetail.value || items.value.find((item) => item.id === selectedId.value) || null);
|
||||
const standardItems = computed(() => items.value.filter((item) => item.asset_kind === 'system_standard'));
|
||||
const extensionItems = computed(() => items.value.filter((item) => item.asset_kind === 'extension'));
|
||||
|
||||
/**
|
||||
* 加载字段资产列表并保持当前选中项。
|
||||
* 核心逻辑:调用 listShippingFieldAssets;若选中项消失则回退到首项。
|
||||
*/
|
||||
async function loadList(): Promise<void> {
|
||||
loading.value = true;
|
||||
try {
|
||||
const data = await listShippingFieldAssets({
|
||||
q: q.value.trim() || undefined,
|
||||
asset_kind: kindFilter.value || undefined,
|
||||
status: statusFilter.value || undefined,
|
||||
});
|
||||
items.value = data.items;
|
||||
if (!selectedId.value || !items.value.some((item) => item.id === selectedId.value)) {
|
||||
selectedId.value = items.value[0]?.id ?? null;
|
||||
}
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingFieldAssets.loadFailed'));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载选中资产的影响分析与审计时间线;两者独立失败,互不拖垮。
|
||||
*/
|
||||
async function loadDetailSidePanels(fieldId: string): Promise<void> {
|
||||
impact.value = null;
|
||||
audits.value = [];
|
||||
const [impactResult, auditResult] = await Promise.allSettled([
|
||||
getShippingFieldAssetImpact(fieldId),
|
||||
listShippingFieldAssetAudits(fieldId),
|
||||
]);
|
||||
if (impactResult.status === 'fulfilled') {
|
||||
impact.value = impactResult.value;
|
||||
} else {
|
||||
message.error(
|
||||
impactResult.reason instanceof BusinessError
|
||||
? impactResult.reason.message
|
||||
: t('admin.shippingFieldAssets.impactFailed'),
|
||||
);
|
||||
}
|
||||
if (auditResult.status === 'fulfilled') {
|
||||
audits.value = auditResult.value.items;
|
||||
} else {
|
||||
message.error(
|
||||
auditResult.reason instanceof BusinessError
|
||||
? auditResult.reason.message
|
||||
: t('admin.shippingFieldAssets.auditFailed'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成管理员可读的存储落点文案。
|
||||
*/
|
||||
function storageLabel(item: ShippingFieldAsset): string {
|
||||
if (item.storage_path) {
|
||||
if (item.storage_kind === 'typed_column') {
|
||||
return t('admin.shippingFieldAssets.storageTypedPath', { path: item.storage_path });
|
||||
}
|
||||
if (item.storage_kind === 'standard_json') {
|
||||
return t('admin.shippingFieldAssets.storageStandardJsonPath', { path: item.storage_path });
|
||||
}
|
||||
return t('admin.shippingFieldAssets.storageExtensionJsonPath', { path: item.storage_path });
|
||||
}
|
||||
if (item.storage_mode === 'typed_column' && item.storage_column) {
|
||||
return t('admin.shippingFieldAssets.storageTypedPath', { path: item.storage_column });
|
||||
}
|
||||
return item.asset_kind === 'system_standard'
|
||||
? t('admin.shippingFieldAssets.storageStandardJson')
|
||||
: t('admin.shippingFieldAssets.storageExtensionJson');
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建扩展字段并刷新列表。
|
||||
*/
|
||||
async function submitCreate(): Promise<void> {
|
||||
saving.value = true;
|
||||
try {
|
||||
const created = await createShippingFieldExtension({
|
||||
...createForm.value,
|
||||
field_code: createForm.value.field_code.trim().toLowerCase(),
|
||||
display_name: createForm.value.display_name.trim(),
|
||||
});
|
||||
showCreate.value = false;
|
||||
createForm.value = {
|
||||
field_code: '',
|
||||
scope: 'header',
|
||||
value_type: 'string',
|
||||
display_name: '',
|
||||
semantic_description: '',
|
||||
};
|
||||
message.success(t('admin.shippingFieldAssets.createSuccess'));
|
||||
await loadList();
|
||||
selectedId.value = created.id;
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingFieldAssets.saveFailed'));
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存扩展字段显示名与语义说明(带 updated_at 乐观锁)。
|
||||
*/
|
||||
async function saveExtensionMeta(): Promise<void> {
|
||||
if (!selected.value || selected.value.asset_kind !== 'extension') return;
|
||||
if (!selected.value.updated_at) {
|
||||
message.error(t('admin.shippingFieldAssets.lockMissing'));
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
try {
|
||||
selectedDetail.value = await updateShippingFieldExtension(selected.value.id, {
|
||||
display_name: editName.value.trim(),
|
||||
semantic_description: editSemantic.value.trim() || undefined,
|
||||
expected_updated_at: selected.value.updated_at,
|
||||
});
|
||||
message.success(t('admin.shippingFieldAssets.updateSuccess'));
|
||||
await loadList();
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingFieldAssets.saveFailed'));
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开弃用/恢复原因对话框;弃用前确保已加载影响分析。
|
||||
*/
|
||||
async function openReasonDialog(action: 'retire' | 'restore'): Promise<void> {
|
||||
reasonAction.value = action;
|
||||
reasonText.value = '';
|
||||
confirmImpactChecked.value = false;
|
||||
if (action === 'retire' && selectedId.value) {
|
||||
if (!impact.value) {
|
||||
await loadDetailSidePanels(selectedId.value);
|
||||
}
|
||||
}
|
||||
showReasonDialog.value = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交弃用或恢复;弃用时若有阻断下游必须勾选确认影响。
|
||||
*/
|
||||
async function submitReasonAction(): Promise<void> {
|
||||
if (!selected.value) return;
|
||||
const reason = reasonText.value.trim();
|
||||
if (!reason) {
|
||||
message.error(t('admin.shippingFieldAssets.reasonRequired'));
|
||||
return;
|
||||
}
|
||||
if (reasonAction.value === 'retire') {
|
||||
const blocked = (impact.value?.blocking_count || 0) > 0;
|
||||
if (blocked && !confirmImpactChecked.value) {
|
||||
message.error(t('admin.shippingFieldAssets.retireConfirmRequired'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
saving.value = true;
|
||||
try {
|
||||
if (reasonAction.value === 'retire') {
|
||||
await retireShippingFieldExtension(selected.value.id, reason, {
|
||||
confirmImpact: confirmImpactChecked.value || (impact.value?.blocking_count || 0) === 0,
|
||||
});
|
||||
message.success(t('admin.shippingFieldAssets.retireSuccess'));
|
||||
} else {
|
||||
await restoreShippingFieldExtension(selected.value.id, reason);
|
||||
message.success(t('admin.shippingFieldAssets.restoreSuccess'));
|
||||
}
|
||||
showReasonDialog.value = false;
|
||||
await loadList();
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof BusinessError
|
||||
&& error.code === 'SHIPPING.FIELD_ASSET_RETIRE_IMPACT_CONFIRM_REQUIRED'
|
||||
&& error.details
|
||||
) {
|
||||
impact.value = error.details as ShippingFieldAssetImpact;
|
||||
message.error(t('admin.shippingFieldAssets.retireConfirmRequired'));
|
||||
} else {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingFieldAssets.saveFailed'));
|
||||
}
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 资产显示名:默认名优先,否则 field_code。
|
||||
*/
|
||||
function displayLabel(item: ShippingFieldAsset): string {
|
||||
return item.display_name_default || item.field_code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将影响 kind 映射为可读文案。
|
||||
*/
|
||||
function blockingLabel(kind: string): string {
|
||||
const key = `admin.shippingFieldAssets.impactKind.${kind}`;
|
||||
const translated = t(key);
|
||||
return translated !== key ? translated : kind;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将审计事件类型映射为可读文案。
|
||||
*/
|
||||
function auditEventLabel(eventType: string): string {
|
||||
const key = `admin.shippingFieldAssets.auditEvent.${eventType}`;
|
||||
const translated = t(key);
|
||||
return translated !== key ? translated : eventType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算审计前后快照的顶层属性差异,优先给管理员看变更摘要。
|
||||
* @param before - 变更前快照
|
||||
* @param after - 变更后快照
|
||||
* @returns 发生变更的属性列表
|
||||
*/
|
||||
function snapshotPropertyDiffs(
|
||||
before: Record<string, unknown> | null | undefined,
|
||||
after: Record<string, unknown> | null | undefined,
|
||||
): Array<{ key: string; before: unknown; after: unknown }> {
|
||||
const left = before && typeof before === 'object' ? before : {};
|
||||
const right = after && typeof after === 'object' ? after : {};
|
||||
const keys = new Set([...Object.keys(left), ...Object.keys(right)]);
|
||||
return [...keys]
|
||||
.sort()
|
||||
.filter((key) => JSON.stringify(left[key]) !== JSON.stringify(right[key]))
|
||||
.map((key) => ({ key, before: left[key], after: right[key] }));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将快照属性值格式化为短文本;复杂对象缩略为 JSON。
|
||||
*/
|
||||
function formatSnapshotValue(value: unknown): string {
|
||||
if (value === undefined) return '—';
|
||||
if (value === null) return 'null';
|
||||
if (typeof value === 'string') return value || '""';
|
||||
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
|
||||
try {
|
||||
return JSON.stringify(value);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化审计变更摘要为可读短句。
|
||||
*/
|
||||
function auditSummaryText(event: ShippingFieldAssetAuditEvent): string {
|
||||
const summary = event.change_summary || {};
|
||||
const parts: string[] = [];
|
||||
if (typeof summary.reason === 'string' && summary.reason.trim()) {
|
||||
parts.push(t('admin.shippingFieldAssets.auditReason', { reason: summary.reason }));
|
||||
}
|
||||
if (typeof summary.action === 'string' && summary.action.trim()) {
|
||||
parts.push(String(summary.action));
|
||||
}
|
||||
if (typeof summary.schema_version === 'number') {
|
||||
parts.push(t('admin.shippingFieldAssets.auditSchemaVersion', { version: summary.schema_version }));
|
||||
}
|
||||
if (typeof summary.field_code === 'string') {
|
||||
parts.push(String(summary.field_code));
|
||||
}
|
||||
if (typeof summary.blocking_count === 'number' && summary.blocking_count > 0) {
|
||||
parts.push(t('admin.shippingFieldAssets.blockingCount', { count: summary.blocking_count }));
|
||||
}
|
||||
return parts.join(' · ') || t('admin.shippingFieldAssets.auditSummaryEmpty');
|
||||
}
|
||||
|
||||
/**
|
||||
* 列表行治理标签:范围 / 类型 / 采用 / 状态。
|
||||
*/
|
||||
function listMeta(item: ShippingFieldAsset): string {
|
||||
const scope = item.scope === 'header'
|
||||
? t('admin.shippingFieldAssets.scopeHeader')
|
||||
: t('admin.shippingFieldAssets.scopeLine');
|
||||
const adoption = item.adoption_summary?.published
|
||||
? t('admin.shippingFieldAssets.adoptedPublished', { count: item.adoption_summary.published })
|
||||
: item.adoption_summary?.draft
|
||||
? t('admin.shippingFieldAssets.adoptedDraft', { count: item.adoption_summary.draft })
|
||||
: t('admin.shippingFieldAssets.adoptedNone');
|
||||
const status = item.status === 'retired'
|
||||
? t('admin.shippingFieldAssets.statusRetired')
|
||||
: t('admin.shippingFieldAssets.statusActive');
|
||||
return `${scope} · ${item.value_type} · ${adoption} · ${status}`;
|
||||
}
|
||||
|
||||
watch(selectedId, async (id) => {
|
||||
selectedDetail.value = null;
|
||||
impact.value = null;
|
||||
audits.value = [];
|
||||
if (!id) return;
|
||||
const row = items.value.find((item) => item.id === id);
|
||||
if (row) {
|
||||
editName.value = row.display_name_default || '';
|
||||
editSemantic.value = row.semantic_description || '';
|
||||
}
|
||||
try {
|
||||
selectedDetail.value = await getShippingFieldAsset(id);
|
||||
editName.value = selectedDetail.value.display_name_default || '';
|
||||
editSemantic.value = selectedDetail.value.semantic_description || '';
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingFieldAssets.detailFailed'));
|
||||
}
|
||||
void loadDetailSidePanels(id);
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
void loadList();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="mx-auto max-w-7xl space-y-6 p-6">
|
||||
<header class="page-header">
|
||||
<div>
|
||||
<p class="text-xs font-bold uppercase tracking-widest text-brand-600">
|
||||
{{ t('admin.shippingFieldAssets.eyebrow') }}
|
||||
</p>
|
||||
<h1 class="mt-2 text-2xl font-bold text-primary">{{ t('admin.shippingFieldAssets.title') }}</h1>
|
||||
<p class="mt-2 text-sm text-muted">{{ t('admin.shippingFieldAssets.subtitle') }}</p>
|
||||
</div>
|
||||
<button type="button" class="primary-button" @click="showCreate = true">
|
||||
{{ t('admin.shippingFieldAssets.createExtension') }}
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div class="toolbar">
|
||||
<input
|
||||
v-model="q"
|
||||
type="search"
|
||||
class="toolbar-input"
|
||||
:placeholder="t('admin.shippingFieldAssets.search')"
|
||||
@keyup.enter="loadList"
|
||||
>
|
||||
<select v-model="kindFilter" class="toolbar-select" @change="loadList">
|
||||
<option value="">{{ t('admin.shippingFieldAssets.kindAll') }}</option>
|
||||
<option value="system_standard">{{ t('admin.shippingFieldAssets.kindStandard') }}</option>
|
||||
<option value="extension">{{ t('admin.shippingFieldAssets.kindExtension') }}</option>
|
||||
</select>
|
||||
<select v-model="statusFilter" class="toolbar-select" @change="loadList">
|
||||
<option value="">{{ t('admin.shippingFieldAssets.statusAll') }}</option>
|
||||
<option value="active">{{ t('admin.shippingFieldAssets.statusActive') }}</option>
|
||||
<option value="retired">{{ t('admin.shippingFieldAssets.statusRetired') }}</option>
|
||||
</select>
|
||||
<button type="button" class="secondary-button" :disabled="loading" @click="loadList">
|
||||
{{ t('admin.shippingFieldAssets.refresh') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="assets-workbench">
|
||||
<aside class="list-panel">
|
||||
<div class="panel-heading">
|
||||
<div>
|
||||
<h2>{{ t('admin.shippingFieldAssets.title') }}</h2>
|
||||
<p>{{ t('admin.shippingFieldAssets.selectHint') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="loading" class="panel-empty">{{ t('admin.shippingFieldAssets.loading') }}</p>
|
||||
<div v-else class="field-list">
|
||||
<section class="field-group">
|
||||
<div class="field-group-toggle">
|
||||
<span class="field-group-title">{{ t('admin.shippingFieldAssets.standardGroup', { count: standardItems.length }) }}</span>
|
||||
</div>
|
||||
<button
|
||||
v-for="item in standardItems"
|
||||
:key="item.id"
|
||||
type="button"
|
||||
class="list-item"
|
||||
:class="{ selected: item.id === selectedId }"
|
||||
@click="selectedId = item.id"
|
||||
>
|
||||
<span class="list-identity">
|
||||
<strong>{{ displayLabel(item) }}</strong>
|
||||
<code>{{ item.field_code }}</code>
|
||||
<small>{{ listMeta(item) }}</small>
|
||||
</span>
|
||||
</button>
|
||||
</section>
|
||||
<section class="field-group">
|
||||
<div class="field-group-toggle">
|
||||
<span class="field-group-title">{{ t('admin.shippingFieldAssets.extensionGroup', { count: extensionItems.length }) }}</span>
|
||||
</div>
|
||||
<button
|
||||
v-for="item in extensionItems"
|
||||
:key="item.id"
|
||||
type="button"
|
||||
class="list-item"
|
||||
:class="{ selected: item.id === selectedId }"
|
||||
@click="selectedId = item.id"
|
||||
>
|
||||
<span class="list-identity">
|
||||
<strong>{{ displayLabel(item) }}</strong>
|
||||
<code>{{ item.field_code }}</code>
|
||||
<small>{{ listMeta(item) }}</small>
|
||||
</span>
|
||||
</button>
|
||||
</section>
|
||||
<p v-if="!items.length" class="panel-empty">{{ t('admin.shippingFieldAssets.empty') }}</p>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section v-if="selected" class="detail-panel">
|
||||
<div class="detail-heading">
|
||||
<div class="detail-heading-copy">
|
||||
<p>{{ selected.asset_kind === 'system_standard' ? t('admin.shippingFieldAssets.kindStandard') : t('admin.shippingFieldAssets.kindExtension') }}</p>
|
||||
<div class="field-title-line">
|
||||
<h2>{{ displayLabel(selected) }}</h2>
|
||||
<code>{{ selected.field_code }}</code>
|
||||
</div>
|
||||
</div>
|
||||
<span v-if="selected.asset_kind === 'system_standard'" class="read-only-badge">
|
||||
{{ t('admin.shippingFieldAssets.kindStandard') }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="detail-body">
|
||||
<div class="asset-readonly">
|
||||
<h3>{{ t('admin.shippingFieldAssets.kind') }}</h3>
|
||||
<dl class="meta">
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingFieldAssets.kind') }}</dt>
|
||||
<dd>{{ selected.asset_kind === 'system_standard' ? t('admin.shippingFieldAssets.kindStandard') : t('admin.shippingFieldAssets.kindExtension') }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingFieldAssets.storage') }}</dt>
|
||||
<dd>{{ storageLabel(selected) }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingFieldAssets.scope') }}</dt>
|
||||
<dd>{{ selected.scope }} / {{ selected.value_type }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingFieldAssets.status') }}</dt>
|
||||
<dd>{{ selected.status === 'retired' ? t('admin.shippingFieldAssets.statusRetired') : t('admin.shippingFieldAssets.statusActive') }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p v-if="selected.asset_kind === 'system_standard'" class="hint-banner">
|
||||
{{ t('admin.shippingFieldAssets.standardReadonlyHint') }}
|
||||
</p>
|
||||
<p v-if="selected.storage_kind === 'standard_json'" class="hint-banner">
|
||||
{{ t('admin.shippingFieldAssets.standardJsonHint') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="section-card">
|
||||
<h3>{{ t('admin.shippingFieldAssets.adoptionTitle') }}</h3>
|
||||
<ul v-if="selected.adoptions?.length" class="link-list">
|
||||
<li v-for="item in selected.adoptions" :key="item.schema_version_id">
|
||||
<RouterLink
|
||||
class="adoption-link"
|
||||
:to="{
|
||||
path: '/admin/shipping-order-schema',
|
||||
query: { version: String(item.version) },
|
||||
}"
|
||||
>
|
||||
{{ item.schema_display_name || item.schema_code || 'Schema' }}
|
||||
V{{ item.version }} ({{ item.status }})
|
||||
</RouterLink>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="muted">{{ t('admin.shippingFieldAssets.adoptionEmpty') }}</p>
|
||||
</div>
|
||||
|
||||
<template v-if="selected.asset_kind === 'extension'">
|
||||
<div class="section-card edit-card">
|
||||
<label>
|
||||
<span>{{ t('admin.shippingFieldAssets.displayName') }}</span>
|
||||
<input v-model="editName" type="text">
|
||||
</label>
|
||||
<label>
|
||||
<span>{{ t('admin.shippingFieldAssets.semantic') }}</span>
|
||||
<textarea v-model="editSemantic" rows="3" />
|
||||
</label>
|
||||
<div class="actions">
|
||||
<button type="button" class="secondary-button" :disabled="saving" @click="saveExtensionMeta">
|
||||
{{ t('admin.shippingFieldAssets.saveMeta') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="selected.status === 'active'"
|
||||
type="button"
|
||||
class="danger-button"
|
||||
:disabled="saving"
|
||||
@click="openReasonDialog('retire')"
|
||||
>
|
||||
{{ t('admin.shippingFieldAssets.retire') }}
|
||||
</button>
|
||||
<button
|
||||
v-else
|
||||
type="button"
|
||||
class="secondary-button"
|
||||
:disabled="saving"
|
||||
@click="openReasonDialog('restore')"
|
||||
>
|
||||
{{ t('admin.shippingFieldAssets.restore') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div v-if="impact" class="section-card">
|
||||
<h3>{{ t('admin.shippingFieldAssets.impactTitle') }}</h3>
|
||||
<p>{{ t('admin.shippingFieldAssets.blockingCount', { count: impact.blocking_count }) }}</p>
|
||||
<ul v-if="impact.blocking_items?.length" class="object-list">
|
||||
<li v-for="item in impact.blocking_items" :key="`${item.kind}-${item.object_id}-${item.reference_path}`">
|
||||
<strong>{{ blockingLabel(item.kind) }} · {{ item.display_name }}</strong>
|
||||
<small>
|
||||
#{{ item.object_id }}
|
||||
<template v-if="item.version != null"> · v{{ item.version }}</template>
|
||||
· {{ item.status }}
|
||||
</small>
|
||||
<code>{{ item.reference_path }}</code>
|
||||
</li>
|
||||
</ul>
|
||||
<ul v-else-if="impact.blocking_kinds.length" class="plain-list">
|
||||
<li v-for="kind in impact.blocking_kinds" :key="kind">{{ blockingLabel(kind) }}</li>
|
||||
</ul>
|
||||
<p class="muted">
|
||||
{{ t('admin.shippingFieldAssets.historicalHint', {
|
||||
runs: impact.historical.observation_count,
|
||||
versions: impact.historical.immutable_schema_version_count,
|
||||
}) }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="section-card">
|
||||
<h3>{{ t('admin.shippingFieldAssets.auditTitle') }}</h3>
|
||||
<p v-if="!audits.length" class="muted">{{ t('admin.shippingFieldAssets.auditEmpty') }}</p>
|
||||
<ul v-else class="audit-list">
|
||||
<li v-for="event in audits" :key="event.id" class="audit-item">
|
||||
<div class="audit-head">
|
||||
<strong>{{ auditEventLabel(event.event_type) }}</strong>
|
||||
<time>{{ event.created_at || '—' }}</time>
|
||||
</div>
|
||||
<p class="audit-meta">
|
||||
{{ t('admin.shippingFieldAssets.auditActor', { name: event.actor_display_name || t('admin.shippingFieldAssets.auditActorUnknown') }) }}
|
||||
<template v-if="event.request_id"> · {{ t('admin.shippingFieldAssets.auditRequestId', { id: event.request_id }) }}</template>
|
||||
</p>
|
||||
<p class="audit-summary">{{ auditSummaryText(event) }}</p>
|
||||
<ul
|
||||
v-if="snapshotPropertyDiffs(event.before, event.after).length"
|
||||
class="audit-diff-list"
|
||||
>
|
||||
<li
|
||||
v-for="diff in snapshotPropertyDiffs(event.before, event.after)"
|
||||
:key="`${event.id}-${diff.key}`"
|
||||
>
|
||||
<code>{{ diff.key }}</code>
|
||||
<span>{{ formatSnapshotValue(diff.before) }}</span>
|
||||
<span aria-hidden="true">→</span>
|
||||
<span>{{ formatSnapshotValue(diff.after) }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
<details v-if="event.before || event.after" class="audit-snap">
|
||||
<summary>{{ t('admin.shippingFieldAssets.auditSnapshotRaw') }}</summary>
|
||||
<pre v-if="event.before">before: {{ JSON.stringify(event.before, null, 2) }}</pre>
|
||||
<pre v-if="event.after">after: {{ JSON.stringify(event.after, null, 2) }}</pre>
|
||||
</details>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-else class="detail-panel detail-empty">
|
||||
<p class="muted">{{ t('admin.shippingFieldAssets.selectHint') }}</p>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div v-if="showCreate" class="impact-overlay" @click.self="showCreate = false">
|
||||
<div class="impact-dialog">
|
||||
<header>
|
||||
<h2>{{ t('admin.shippingFieldAssets.createExtension') }}</h2>
|
||||
<button type="button" class="text-button" @click="showCreate = false">{{ t('admin.shippingFieldAssets.cancel') }}</button>
|
||||
</header>
|
||||
<label>
|
||||
<span>{{ t('admin.shippingFieldAssets.fieldCode') }}</span>
|
||||
<input v-model="createForm.field_code">
|
||||
</label>
|
||||
<label>
|
||||
<span>{{ t('admin.shippingFieldAssets.displayName') }}</span>
|
||||
<input v-model="createForm.display_name">
|
||||
</label>
|
||||
<label>
|
||||
<span>{{ t('admin.shippingFieldAssets.scope') }}</span>
|
||||
<select v-model="createForm.scope">
|
||||
<option value="header">header</option>
|
||||
<option value="line">line</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>{{ t('admin.shippingFieldAssets.valueType') }}</span>
|
||||
<select v-model="createForm.value_type">
|
||||
<option value="string">string</option>
|
||||
<option value="decimal">decimal</option>
|
||||
<option value="integer">integer</option>
|
||||
<option value="date">date</option>
|
||||
<option value="boolean">boolean</option>
|
||||
<option value="enum">enum</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>{{ t('admin.shippingFieldAssets.semantic') }}</span>
|
||||
<textarea v-model="createForm.semantic_description" rows="3" />
|
||||
</label>
|
||||
<footer>
|
||||
<button type="button" class="secondary-button" @click="showCreate = false">{{ t('admin.shippingFieldAssets.cancel') }}</button>
|
||||
<button type="button" class="primary-button" :disabled="saving" @click="submitCreate">{{ t('admin.shippingFieldAssets.confirm') }}</button>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="showReasonDialog" class="impact-overlay" @click.self="showReasonDialog = false">
|
||||
<div class="impact-dialog">
|
||||
<header>
|
||||
<h2>{{ reasonAction === 'retire' ? t('admin.shippingFieldAssets.retire') : t('admin.shippingFieldAssets.restore') }}</h2>
|
||||
<button type="button" class="text-button" @click="showReasonDialog = false">{{ t('admin.shippingFieldAssets.cancel') }}</button>
|
||||
</header>
|
||||
<p class="muted">{{ t('admin.shippingFieldAssets.reasonHint') }}</p>
|
||||
<template v-if="reasonAction === 'retire'">
|
||||
<div class="impact-summary">
|
||||
<p>{{ t('admin.shippingFieldAssets.retireImpactSummary', { count: impact?.blocking_count || 0 }) }}</p>
|
||||
<ul v-if="impact?.blocking_items?.length">
|
||||
<li v-for="item in impact.blocking_items" :key="`${item.kind}-${item.object_id}`">
|
||||
{{ blockingLabel(item.kind) }} · {{ item.display_name }} ({{ item.status }})
|
||||
</li>
|
||||
</ul>
|
||||
<label v-if="(impact?.blocking_count || 0) > 0" class="confirm-row">
|
||||
<input v-model="confirmImpactChecked" type="checkbox">
|
||||
{{ t('admin.shippingFieldAssets.retireConfirmCheckbox') }}
|
||||
</label>
|
||||
</div>
|
||||
</template>
|
||||
<textarea v-model="reasonText" rows="4" />
|
||||
<footer>
|
||||
<button type="button" class="secondary-button" @click="showReasonDialog = false">{{ t('admin.shippingFieldAssets.cancel') }}</button>
|
||||
<button type="button" class="primary-button" :disabled="saving" @click="submitReasonAction">{{ t('admin.shippingFieldAssets.confirm') }}</button>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.page-header { display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: space-between; gap: 16px; }
|
||||
.primary-button, .secondary-button, .danger-button, .text-button {
|
||||
border: 0; border-radius: 6px; padding: 8px 12px; font: inherit; font-size: 13px; font-weight: 600; cursor: pointer;
|
||||
}
|
||||
.primary-button { background: #0ea5e9; color: #fff; }
|
||||
.secondary-button { border: 1px solid #d7e0ea; background: #fff; color: #475569; }
|
||||
.danger-button { border: 1px solid #fca5a5; background: #fff; color: #b91c1c; }
|
||||
.text-button { background: transparent; color: #64748b; }
|
||||
.primary-button:disabled, .secondary-button:disabled, .danger-button:disabled { cursor: not-allowed; opacity: .55; }
|
||||
|
||||
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
.toolbar-input, .toolbar-select {
|
||||
min-width: 160px; border: 1px solid #d9e2ec; border-radius: 6px; background: #fff;
|
||||
padding: 7px 9px; color: #334155; font: inherit; font-size: 12px; outline: none;
|
||||
}
|
||||
.toolbar-input { min-width: 220px; flex: 1 1 220px; }
|
||||
.toolbar-input:focus, .toolbar-select:focus { border-color: #38bdf8; box-shadow: 0 0 0 2px rgb(56 189 248 / 12%); }
|
||||
|
||||
.assets-workbench {
|
||||
display: grid; height: min(700px, calc(100vh - 280px)); min-height: 540px;
|
||||
grid-template-columns: 320px minmax(0, 1fr); overflow: hidden;
|
||||
border: 1px solid #dfe7ef; border-radius: 10px; background: #fff;
|
||||
box-shadow: 0 1px 2px rgb(15 23 42 / 3%);
|
||||
}
|
||||
.list-panel {
|
||||
display: flex; min-width: 0; min-height: 0; flex-direction: column;
|
||||
border-right: 1px solid #e5ebf1; background: #fbfcfe;
|
||||
}
|
||||
.panel-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 16px 16px 10px; }
|
||||
.panel-heading h2 { margin: 0; color: #1e293b; font-size: 15px; font-weight: 600; }
|
||||
.panel-heading p, .panel-empty, .muted { margin: 5px 0 0; color: #94a3b8; font-size: 12px; line-height: 1.5; }
|
||||
.panel-empty { padding: 24px 16px; text-align: center; }
|
||||
.field-list { min-height: 0; flex: 1 1 auto; overflow-y: auto; overscroll-behavior: contain; padding: 0 8px 12px; }
|
||||
.field-group { margin-top: 4px; }
|
||||
.field-group-toggle {
|
||||
position: sticky; z-index: 2; top: 0; display: flex; width: 100%; align-items: center;
|
||||
border: 0; border-bottom: 1px solid #edf1f5; background: rgb(251 252 254 / 96%);
|
||||
padding: 9px 8px 7px; color: #64748b; font: inherit; font-size: 11px; font-weight: 700; text-align: left;
|
||||
backdrop-filter: blur(5px);
|
||||
}
|
||||
.list-item {
|
||||
display: flex; width: 100%; align-items: center; gap: 8px; margin-top: 2px;
|
||||
border: 0; border-radius: 7px; background: transparent; padding: 6px 8px; color: #475569;
|
||||
text-align: left; cursor: pointer;
|
||||
}
|
||||
.list-item:hover { background: #f1f6fa; }
|
||||
.list-item.selected { background: #e8f5fc; color: #0369a1; box-shadow: inset 3px 0 #0ea5e9; }
|
||||
.list-identity { display: grid; min-width: 0; flex: 1; gap: 2px; }
|
||||
.list-identity strong { overflow: hidden; color: #334155; font-size: 12.5px; font-weight: 650; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.list-identity code { overflow: hidden; color: #94a3b8; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 10px; font-weight: 400; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.list-identity small { color: #64748b; font-size: 10px; line-height: 1.35; }
|
||||
.list-item.selected .list-identity strong,
|
||||
.list-item.selected .list-identity code { color: #0369a1; }
|
||||
|
||||
.detail-panel { display: flex; min-width: 0; min-height: 0; flex-direction: column; overflow: hidden; background: #fff; }
|
||||
.detail-empty { place-content: center; padding: 32px; text-align: center; }
|
||||
.detail-heading {
|
||||
display: flex; min-height: 92px; flex: 0 0 auto; align-items: center; justify-content: space-between;
|
||||
gap: 18px; border-bottom: 1px solid #e5ebf1; padding: 16px 24px;
|
||||
}
|
||||
.detail-heading-copy { min-width: 0; }
|
||||
.detail-heading-copy > p { margin: 0 0 4px; color: #94a3b8; font-size: 12px; }
|
||||
.field-title-line { display: flex; min-width: 0; align-items: baseline; gap: 10px; }
|
||||
.field-title-line h2 { margin: 0; overflow: hidden; color: #1e293b; font-size: 17px; font-weight: 600; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.field-title-line code { color: #64748b; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 11px; }
|
||||
.read-only-badge { border: 1px solid #cbd5e1; border-radius: 999px; background: #f8fafc; padding: 4px 9px; color: #64748b; font-size: 11px; font-weight: 600; }
|
||||
.detail-body {
|
||||
display: grid; min-height: 0; flex: 1 1 auto; align-content: start; gap: 18px;
|
||||
overflow-x: hidden; overflow-y: auto; overscroll-behavior: contain; padding: 22px 24px 30px; scrollbar-gutter: stable;
|
||||
}
|
||||
.asset-readonly, .section-card {
|
||||
border: 1px solid #edf1f5; border-radius: 9px; background: #f8fafc; padding: 16px 18px;
|
||||
}
|
||||
.section-card { background: #fcfdff; }
|
||||
.asset-readonly h3, .section-card h3 {
|
||||
margin: 0 0 12px; color: #64748b; font-size: 12px; font-weight: 700; letter-spacing: .04em; text-transform: uppercase;
|
||||
}
|
||||
.meta { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px 18px; margin: 0; }
|
||||
.meta dt { color: #64748b; font-size: 12px; }
|
||||
.meta dd { margin: 5px 0 0; color: #334155; font-size: 13px; }
|
||||
.hint-banner {
|
||||
margin: 12px 0 0; border: 1px solid #bae6fd; border-radius: 8px; background: #f0f9ff;
|
||||
padding: 12px; color: #0369a1; font-size: 12px; line-height: 1.5;
|
||||
}
|
||||
.edit-card { display: grid; gap: 14px; }
|
||||
.edit-card label, .impact-dialog label {
|
||||
display: grid; gap: 5px; color: #64748b; font-size: 12px;
|
||||
}
|
||||
.edit-card input, .edit-card textarea, .impact-dialog input, .impact-dialog select, .impact-dialog textarea {
|
||||
min-width: 0; border: 1px solid #d9e2ec; border-radius: 6px; background: #fff;
|
||||
padding: 8px 9px; color: #334155; font: inherit; font-size: 13px; outline: none;
|
||||
}
|
||||
.edit-card input:focus, .edit-card textarea:focus, .impact-dialog input:focus,
|
||||
.impact-dialog select:focus, .impact-dialog textarea:focus {
|
||||
border-color: #38bdf8; box-shadow: 0 0 0 2px rgb(56 189 248 / 12%);
|
||||
}
|
||||
.actions, .impact-dialog footer { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.impact-dialog footer { justify-content: flex-end; }
|
||||
.link-list, .plain-list { margin: 0; padding-left: 1.1rem; color: #475569; font-size: 13px; }
|
||||
.adoption-link { color: #0369a1; text-decoration: underline; text-underline-offset: 2px; }
|
||||
.adoption-link:hover { color: #0c4a6e; }
|
||||
.object-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
|
||||
.object-list li {
|
||||
display: grid; gap: 2px; border: 1px solid #e2e8f0; border-radius: 8px;
|
||||
background: #fff; padding: 10px 12px;
|
||||
}
|
||||
.object-list small, .object-list code { color: #64748b; font-size: 12px; word-break: break-all; }
|
||||
.audit-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
|
||||
.audit-diff-list {
|
||||
list-style: none;
|
||||
margin: 6px 0 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
font-size: 11px;
|
||||
color: #334155;
|
||||
}
|
||||
.audit-diff-list li {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(88px, auto) 1fr auto 1fr;
|
||||
gap: 6px;
|
||||
align-items: start;
|
||||
}
|
||||
.audit-diff-list code { color: #0f766e; font-size: 11px; word-break: break-all; }
|
||||
.audit-item { border: 1px solid #e2e8f0; border-radius: 8px; background: #fff; padding: 10px 12px; }
|
||||
.audit-head { display: flex; justify-content: space-between; gap: 12px; align-items: baseline; }
|
||||
.audit-head time, .audit-meta, .audit-summary { margin: 4px 0 0; color: #64748b; font-size: 12px; }
|
||||
.audit-snap { margin-top: 6px; color: #475569; font-size: 11px; }
|
||||
.audit-snap pre {
|
||||
margin: 6px 0 0; max-height: 10rem; overflow: auto; border-radius: 6px;
|
||||
background: #f8fafc; padding: 8px; white-space: pre-wrap; word-break: break-word;
|
||||
}
|
||||
|
||||
.impact-overlay {
|
||||
position: fixed; z-index: 60; inset: 0; display: grid; place-items: center;
|
||||
background: rgb(15 23 42 / .42); padding: 24px;
|
||||
}
|
||||
.impact-dialog {
|
||||
display: grid; width: min(520px, 96vw); max-height: 82vh; gap: 14px; overflow: auto;
|
||||
border-radius: 12px; background: #fff; padding: 18px; box-shadow: 0 24px 64px rgb(15 23 42 / .24);
|
||||
}
|
||||
.impact-dialog header { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.impact-dialog h2, .impact-dialog p { margin: 0; }
|
||||
.impact-summary {
|
||||
display: grid; gap: 8px; border: 1px solid #fecaca; border-radius: 8px;
|
||||
background: #fef2f2; padding: 12px; color: #991b1b; font-size: 13px;
|
||||
}
|
||||
.confirm-row { display: flex !important; align-items: flex-start; gap: 8px; color: #334155; font-size: 13px; }
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.assets-workbench { grid-template-columns: 1fr; height: auto; min-height: 0; }
|
||||
.list-panel { border-right: 0; border-bottom: 1px solid #e5ebf1; max-height: 320px; }
|
||||
}
|
||||
</style>
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-field-assets/components/FieldImpactDrawer.vue
|
||||
用途:展示单字段影响分析(阻断对象明细/警告/历史只读),资产库与 Schema 页共用。
|
||||
依赖:ShippingFieldAssetImpact DTO、Vue I18n、Vue Router。
|
||||
逻辑:只读抽屉;列出具体配置对象与引用位置;不含订单正文或证据原文。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRouter } from 'vue-router';
|
||||
import type { ShippingFieldAssetImpact, ShippingFieldImpactItem } from '@/features/admin/types/shipping-field-assets.types';
|
||||
|
||||
defineProps<{
|
||||
modelValue: boolean;
|
||||
impact: ShippingFieldAssetImpact | null;
|
||||
loading: boolean;
|
||||
}>();
|
||||
|
||||
defineEmits<{ 'update:modelValue': [value: boolean] }>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const router = useRouter();
|
||||
|
||||
/**
|
||||
* 将后端 blocking kind 映射为管理员可读的下游对象名称。
|
||||
*/
|
||||
function blockingLabel(kind: string): string {
|
||||
const key = `admin.shippingFieldAssets.impactKind.${kind}`;
|
||||
const translated = t(key);
|
||||
return translated !== key ? translated : kind;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开下游配置处理入口(若提供 admin_path)。
|
||||
*/
|
||||
function openAdminPath(item: ShippingFieldImpactItem): void {
|
||||
if (!item.admin_path) return;
|
||||
void router.push(item.admin_path);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="modelValue" class="impact-overlay" @click.self="$emit('update:modelValue', false)">
|
||||
<aside class="impact-drawer" role="dialog" aria-modal="true">
|
||||
<header>
|
||||
<h2>{{ t('admin.shippingFieldAssets.impactTitle') }}</h2>
|
||||
<button type="button" class="text-button" @click="$emit('update:modelValue', false)">{{ t('common.close') }}</button>
|
||||
</header>
|
||||
<div v-if="loading" class="impact-loading">{{ t('common.loading') }}</div>
|
||||
<template v-else-if="impact">
|
||||
<section v-if="impact.blocking_items?.length" class="impact-section blocked">
|
||||
<h3>{{ t('admin.shippingFieldAssets.impactBlocked') }}</h3>
|
||||
<p class="muted">{{ t('admin.shippingFieldAssets.blockingCount', { count: impact.blocking_count }) }}</p>
|
||||
<ul class="object-list">
|
||||
<li v-for="item in impact.blocking_items" :key="`${item.kind}-${item.object_id}-${item.reference_path}`">
|
||||
<strong>{{ blockingLabel(item.kind) }} · {{ item.display_name }}</strong>
|
||||
<small>
|
||||
#{{ item.object_id }}
|
||||
<template v-if="item.version != null"> · v{{ item.version }}</template>
|
||||
· {{ item.status }}
|
||||
</small>
|
||||
<code>{{ item.reference_path }}</code>
|
||||
<button
|
||||
v-if="item.admin_path"
|
||||
type="button"
|
||||
class="link-button"
|
||||
@click="openAdminPath(item)"
|
||||
>
|
||||
{{ t('admin.shippingFieldAssets.impactOpenTarget') }}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
<section v-else class="impact-section ok">
|
||||
<p>{{ t('admin.shippingFieldAssets.impactNoBlocking') }}</p>
|
||||
</section>
|
||||
<section class="impact-section historical">
|
||||
<h3>{{ t('admin.shippingFieldAssets.impactHistorical') }}</h3>
|
||||
<ul>
|
||||
<li>{{ t('admin.shippingFieldAssets.impactHistoricalVersions', { count: impact.historical.immutable_schema_version_count }) }}</li>
|
||||
<li>{{ t('admin.shippingFieldAssets.impactHistoricalObservations', { count: impact.historical.observation_count }) }}</li>
|
||||
<li>{{ t('admin.shippingFieldAssets.impactHistoricalValues', { count: impact.historical.value_count }) }}</li>
|
||||
</ul>
|
||||
<ul v-if="impact.historical.immutable_schema_versions?.length" class="object-list compact">
|
||||
<li
|
||||
v-for="item in impact.historical.immutable_schema_versions"
|
||||
:key="item.schema_version_id"
|
||||
>
|
||||
{{ item.schema_display_name || item.schema_code || 'Schema' }}
|
||||
V{{ item.version }} ({{ item.status }})
|
||||
</li>
|
||||
</ul>
|
||||
<small>{{ t('admin.shippingFieldAssets.impactHistoricalHint') }}</small>
|
||||
</section>
|
||||
</template>
|
||||
</aside>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.impact-overlay { position: fixed; z-index: 60; inset: 0; display: flex; justify-content: flex-end; background: rgb(15 23 42 / 38%); }
|
||||
.impact-drawer { display: grid; width: min(520px, 96vw); height: 100%; grid-template-rows: auto 1fr; gap: 12px; overflow: hidden; background: #fff; padding: 18px; box-shadow: -12px 0 40px rgb(15 23 42 / 18%); }
|
||||
.impact-drawer header { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.impact-drawer h2, .impact-drawer h3 { margin: 0; color: #1e293b; font-size: 15px; }
|
||||
.impact-drawer h3 { font-size: 13px; }
|
||||
.text-button, .link-button { border: 0; background: transparent; color: #64748b; font: inherit; font-size: 13px; cursor: pointer; }
|
||||
.link-button { color: #1d4ed8; padding: 0; text-align: left; }
|
||||
.impact-loading, .muted { color: #64748b; font-size: 13px; }
|
||||
.impact-section { border: 1px solid #e2e8f0; border-radius: 8px; padding: 12px; overflow-y: auto; }
|
||||
.impact-section.blocked { border-color: #fecaca; background: #fef2f2; }
|
||||
.impact-section.ok { border-color: #bbf7d0; background: #f0fdf4; color: #166534; font-size: 13px; }
|
||||
.impact-section.historical { background: #f8fafc; }
|
||||
.impact-section ul { margin: 8px 0 0; padding-left: 18px; color: #475569; font-size: 12px; }
|
||||
.object-list { list-style: none; padding-left: 0 !important; display: grid; gap: 0.75rem; }
|
||||
.object-list li { display: grid; gap: 0.2rem; border: 1px solid #fecaca; border-radius: 0.5rem; background: #fff; padding: 0.65rem 0.75rem; }
|
||||
.object-list.compact li { border-color: #e2e8f0; }
|
||||
.object-list small, .object-list code { color: #64748b; font-size: 11px; word-break: break-all; }
|
||||
.impact-section small { display: block; margin-top: 8px; color: #94a3b8; font-size: 11px; line-height: 1.4; }
|
||||
</style>
|
||||
@@ -1,7 +1,7 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-inventory/ShippingInventoryPage.vue
|
||||
用途:以统一货代管理工作台维护订单字段、库存接入、Excel 导出和运行审计。
|
||||
依赖:admin.api、ShippingOrderSchemaPage、Vue Router、Vue Composition API、Vue I18n。
|
||||
用途:货代库存管理工作台,维护解析方案、连接、站点、模板与运行审计。
|
||||
依赖:admin.api、Vue Router、Vue Composition API、Vue I18n。
|
||||
逻辑:由 AdminLayout 统一业务目录选择工作区;section 深链与当前工作区双向同步。
|
||||
-->
|
||||
<template>
|
||||
@@ -22,7 +22,7 @@
|
||||
|
||||
<div class="console-layout">
|
||||
<main class="workbench">
|
||||
<div v-if="activeTab !== 'orderSchema'" class="workbench-heading">
|
||||
<div class="workbench-heading">
|
||||
<div>
|
||||
<h2>{{ t(currentSection.labelKey) }}</h2>
|
||||
<p>{{ t(currentSection.helpKey) }}</p>
|
||||
@@ -43,7 +43,6 @@
|
||||
{{ t('admin.shippingInventory.orderSchemaRequired') }}
|
||||
</p>
|
||||
|
||||
<ShippingOrderSchemaPage v-if="activeTab === 'orderSchema'" embedded />
|
||||
|
||||
<nav v-else-if="isInventoryMappingSection" class="inventory-mapping-tabs" :aria-label="t('admin.shippingInventory.inventoryMapping')">
|
||||
<button type="button" :class="{ active: activeTab === 'parsing' }" @click="selectInventoryMappingTab('parsing')">{{ t('admin.shippingInventory.inventoryMappingPlans') }}</button>
|
||||
@@ -77,7 +76,7 @@
|
||||
<PaginationBar v-model:page="exportPage" v-model:page-size="auditPageSize" :total="exports.length" />
|
||||
</div>
|
||||
|
||||
<div v-else-if="activeTab !== 'orderSchema'" class="object-list-panel">
|
||||
<div v-else class="object-list-panel">
|
||||
<div class="object-list">
|
||||
<div v-if="!currentItems.length" class="empty-state">{{ t('admin.shippingInventory.emptyConfig') }}</div>
|
||||
<button
|
||||
@@ -426,7 +425,6 @@ import * as XLSX from 'xlsx';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import ShippingOrderSchemaPage from '@/features/admin/modules/shipping-order-schema/ShippingOrderSchemaPage.vue';
|
||||
import {
|
||||
createShippingInventoryField,
|
||||
deleteShippingInventoryExternalMapping,
|
||||
@@ -478,7 +476,7 @@ import type { ShippingInventoryConfigurationTest, ShippingInventoryReadinessChec
|
||||
import { isConfigurationTestRunning, needsReadinessAction, readinessMarkerKind } from './shippingInventoryReadiness';
|
||||
import { normaliseInventoryReportPath } from './shippingInventorySourceForm';
|
||||
|
||||
type TabKey = 'orderSchema' | 'profiles' | 'parsing' | 'inventoryFields' | 'templates' | 'sources' | 'rules' | 'snapshots' | 'exports' | 'mappings';
|
||||
type TabKey = 'profiles' | 'parsing' | 'inventoryFields' | 'templates' | 'sources' | 'rules' | 'snapshots' | 'exports' | 'mappings';
|
||||
type Item = Record<string, any>;
|
||||
type Parameter = { name: string; mode: 'single' | 'multi_text' | 'multi_select'; values: string[]; required: boolean; select_all: boolean; joiner?: string };
|
||||
type RuleCondition = { source_kind: 'order_field'; order_field_id: string; operator: string; expected: string };
|
||||
@@ -492,7 +490,7 @@ const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const message = useMessage();
|
||||
const activeTab = ref<TabKey>('orderSchema');
|
||||
const activeTab = ref<TabKey>('parsing');
|
||||
const selectedId = ref<number | null>(null);
|
||||
const drawerOpen = ref(false);
|
||||
const orderSchemaPublished = ref(false);
|
||||
@@ -626,7 +624,6 @@ const operators = [
|
||||
];
|
||||
|
||||
const tabs = computed(() => [
|
||||
{ key: 'orderSchema' as const, group: 'order', labelKey: 'admin.shippingInventory.orderFields', helpKey: '', count: null },
|
||||
{ key: 'parsing' as const, group: 'inventory', labelKey: 'admin.shippingInventory.parsingProfiles', helpKey: 'admin.shippingInventory.parsingProfilesHelp', count: parsingProfiles.value.length },
|
||||
{ key: 'profiles' as const, group: 'inventory', labelKey: 'admin.shippingInventory.connections', helpKey: 'admin.shippingInventory.connectionsHelp', count: profiles.value.length },
|
||||
{ key: 'sources' as const, group: 'inventory', labelKey: 'admin.shippingInventory.sources', helpKey: 'admin.shippingInventory.sourcesHelp', count: sources.value.length },
|
||||
@@ -796,6 +793,10 @@ function selectTab(tab: TabKey): void {
|
||||
watch(
|
||||
() => route.query.section,
|
||||
(section) => {
|
||||
if (section === 'orderSchema') {
|
||||
void router.replace({ name: 'AdminShippingOrderSchema' });
|
||||
return;
|
||||
}
|
||||
if (typeof section === 'string' && tabs.value.some((tab) => tab.key === section)) {
|
||||
activeTab.value = section as TabKey;
|
||||
}
|
||||
|
||||
+151
-17
@@ -1,13 +1,14 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileCreateWizardPage.vue
|
||||
用途:订单模板三步创建向导。
|
||||
依赖:Schema/样本/表格 API、三个步骤组件、Router。
|
||||
逻辑:身份、样本、主表格均在浏览器内暂存;仅第三步完成调用原子 wizard-complete 接口。
|
||||
用途:以三步向导创建订单文档模板草稿。
|
||||
依赖:Schema/样本/表格 API、步骤组件和 Vue Router。
|
||||
逻辑:首步仅收集业务名称和 Schema;最后一步由服务端生成系统编码并原子创建草稿、样本绑定、Revision 与 Lease。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ArrowLeft, ArrowRight, Check, FileText, Layers3, Sparkles } from 'lucide-vue-next';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { getShippingOrderSchemaState } from '@/features/admin/api/shipping-order-schema.api';
|
||||
@@ -17,23 +18,156 @@ import OrderProfileIdentityStep from './components/OrderProfileIdentityStep.vue'
|
||||
import OrderProfileSampleStep from './components/OrderProfileSampleStep.vue';
|
||||
import OrderProfileModelStartStep from './components/OrderProfileModelStartStep.vue';
|
||||
|
||||
const { t } = useI18n(); const router = useRouter(); const message = useMessage();
|
||||
const step = ref(1); const saving = ref(false); const schemas = ref<ShippingOrderSchemaVersion[]>([]);
|
||||
const samples = ref<Array<{ document_id:number; intake_no:string; filename?:string|null; table_count:number }>>([]);
|
||||
const tables = ref<Array<{ table_id:string; page_no:number; row_count:number; column_count:number; rows:string[][] }>>([]);
|
||||
const identity = reactive({ displayName:'', profileCode:'', schemaId:0 }); const documentId = ref(0); const tableId = ref('');
|
||||
type Identity = { displayName: string; schemaId: number };
|
||||
|
||||
const { t } = useI18n();
|
||||
const router = useRouter();
|
||||
const message = useMessage();
|
||||
const step = ref(1);
|
||||
const saving = ref(false);
|
||||
const schemas = ref<ShippingOrderSchemaVersion[]>([]);
|
||||
const samples = ref<Array<{ document_id: number; intake_no: string; filename?: string | null; table_count: number }>>([]);
|
||||
const tables = ref<Array<{ table_id: string; page_no: number; row_count: number; column_count: number; rows: string[][] }>>([]);
|
||||
const identity = reactive<Identity>({ displayName: '', schemaId: 0 });
|
||||
const documentId = ref(0);
|
||||
const tableId = ref('');
|
||||
const browserSessionId = crypto.randomUUID();
|
||||
const canNext = computed(() => step.value === 1 ? Boolean(identity.displayName.trim() && identity.profileCode.trim() && identity.schemaId) : step.value === 2 ? Boolean(documentId.value) : Boolean(tableId.value));
|
||||
const publishedSchemas = computed(() => schemas.value.filter((item) => item.status === 'published'));
|
||||
const canNext = computed(() => step.value === 1
|
||||
? Boolean(identity.displayName.trim() && identity.schemaId)
|
||||
: step.value === 2 ? Boolean(documentId.value) : Boolean(tableId.value));
|
||||
const steps = computed(() => [
|
||||
{ number: 1, label: t('admin.shippingOrderProfiles.wizard.identityStep'), icon: FileText },
|
||||
{ number: 2, label: t('admin.shippingOrderProfiles.wizard.sampleStep'), icon: Layers3 },
|
||||
{ number: 3, label: t('admin.shippingOrderProfiles.wizard.tableStep'), icon: Sparkles },
|
||||
]);
|
||||
|
||||
/** 接收首步身份快照;父级单一状态驱动下一步校验,避免子组件对象替换造成状态不同步。 */
|
||||
function updateIdentity(next: Identity): void {
|
||||
identity.displayName = next.displayName;
|
||||
identity.schemaId = next.schemaId;
|
||||
}
|
||||
/** 加载可用 Schema 与已解析样本;失败不创建或缓存任何 Profile。 */
|
||||
async function loadContext(): Promise<void> { try { const [state, nextSamples] = await Promise.all([getShippingOrderSchemaState(), listOrderProfileSamples()]); schemas.value = state.versions || []; samples.value = nextSamples; } catch (error) { message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.loadFailed')); } }
|
||||
async function loadContext(): Promise<void> {
|
||||
try {
|
||||
const [state, nextSamples] = await Promise.all([getShippingOrderSchemaState(), listOrderProfileSamples()]);
|
||||
schemas.value = state.versions || [];
|
||||
samples.value = nextSamples;
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.loadFailed'));
|
||||
}
|
||||
}
|
||||
/** 刷新上传后的样本库;样本解析未完成时只会留在样本库,不能产出半成品模板。 */
|
||||
async function refreshSamples(): Promise<void> { try { samples.value = await listOrderProfileSamples(); } catch { message.error(t('admin.shippingOrderProfiles.wizard.loadFailed')); } }
|
||||
watch(documentId, async (id) => { tableId.value=''; tables.value=[]; if (!id) return; try { const preview = await getOrderProfileSampleTables(id); tables.value = preview.tables; } catch (error) { message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.tableLoadFailed')); } });
|
||||
/** 前进仅校验本地步骤状态;最后一步才拥有正式落库权限。 */
|
||||
function next(): void { if (!canNext.value) { message.error(t('admin.shippingOrderProfiles.wizard.incomplete')); return; } if (step.value < 3) step.value += 1; }
|
||||
async function refreshSamples(): Promise<void> {
|
||||
try { samples.value = await listOrderProfileSamples(); }
|
||||
catch { message.error(t('admin.shippingOrderProfiles.wizard.loadFailed')); }
|
||||
}
|
||||
/** 加载选定样本的可用表格;单表场景由下一步直接作为订单明细表。 */
|
||||
async function loadTables(id: number): Promise<void> {
|
||||
try { tables.value = (await getOrderProfileSampleTables(id)).tables; }
|
||||
catch (error) { message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.tableLoadFailed')); }
|
||||
}
|
||||
watch(documentId, async (id) => {
|
||||
tableId.value = '';
|
||||
tables.value = [];
|
||||
if (!id) return;
|
||||
await loadTables(id);
|
||||
});
|
||||
/** 前进仅校验当前步骤;单表直接创建,多表才要求管理员确认订单明细表。 */
|
||||
async function next(): Promise<void> {
|
||||
if (!canNext.value) {
|
||||
message.error(step.value === 1 && !publishedSchemas.value.length
|
||||
? t('admin.shippingOrderProfiles.wizard.schemaRequired')
|
||||
: t('admin.shippingOrderProfiles.wizard.incomplete'));
|
||||
return;
|
||||
}
|
||||
if (step.value === 2) {
|
||||
if (!tables.value.length) await loadTables(documentId.value);
|
||||
const onlyTable = tables.value.length === 1 ? tables.value[0] : undefined;
|
||||
if (onlyTable) {
|
||||
tableId.value = onlyTable.table_id;
|
||||
await finish(true);
|
||||
return;
|
||||
}
|
||||
if (!tables.value.length) {
|
||||
message.error(t('admin.shippingOrderProfiles.wizard.noTable'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (step.value < 3) step.value += 1;
|
||||
}
|
||||
/** 单事务完成后进入草稿编辑路由;创建草稿和创建并进入标注共享同一审计动作。 */
|
||||
async function finish(enterEditor: boolean): Promise<void> { if (!canNext.value) return; saving.value=true; try { const profile = await completeOrderDocumentProfileWizard({ profile_code:identity.profileCode, display_name:identity.displayName, schema_version_id:identity.schemaId, document_id:documentId.value, main_table_id:tableId.value, browser_session_id:browserSessionId, operation_id:crypto.randomUUID() }); message.success(t('admin.shippingOrderProfiles.created')); if (enterEditor) router.push({ name:'AdminShippingOrderDocumentProfileEdit', params:{ profileCode:profile.profile_code, profileId:profile.id }, query:{ editorSessionId:browserSessionId } }); else router.push({ name:'AdminShippingOrderDocumentProfiles' }); } catch (error) { message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.createFailed')); } finally { saving.value=false; } }
|
||||
async function finish(enterEditor: boolean): Promise<void> {
|
||||
if (!canNext.value) return;
|
||||
saving.value = true;
|
||||
try {
|
||||
const profile = await completeOrderDocumentProfileWizard({
|
||||
display_name: identity.displayName,
|
||||
schema_version_id: identity.schemaId, document_id: documentId.value, main_table_id: tableId.value,
|
||||
browser_session_id: browserSessionId, operation_id: crypto.randomUUID(),
|
||||
});
|
||||
message.success(t('admin.shippingOrderProfiles.created'));
|
||||
await router.push(enterEditor
|
||||
? { name: 'AdminShippingOrderDocumentProfileEdit', params: { profileCode: profile.profile_code, profileId: profile.id }, query: { editorSessionId: browserSessionId } }
|
||||
: { name: 'AdminShippingOrderDocumentProfiles' });
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.createFailed'));
|
||||
} finally { saving.value = false; }
|
||||
}
|
||||
onMounted(loadContext);
|
||||
</script>
|
||||
<template><section class="wizard"><header><button type="button" @click="router.push({ name:'AdminShippingOrderDocumentProfiles' })">{{ t('admin.cancel') }}</button><h1>{{ t('admin.shippingOrderProfiles.wizard.title') }}</h1><p>{{ t('admin.shippingOrderProfiles.wizard.steps', { step }) }}</p></header><OrderProfileIdentityStep v-if="step===1" v-model="identity" :schemas="schemas"/><OrderProfileSampleStep v-else-if="step===2" v-model="documentId" :samples="samples" @uploaded="refreshSamples"/><OrderProfileModelStartStep v-else v-model="tableId" :tables="tables"/><footer><button v-if="step>1" type="button" @click="step-=1">{{ t('admin.shippingOrderProfiles.wizard.previous') }}</button><span/><button v-if="step<3" class="primary" type="button" :disabled="!canNext" @click="next">{{ t('admin.shippingOrderProfiles.wizard.next') }}</button><template v-else><button type="button" :disabled="saving||!canNext" @click="finish(false)">{{ t('admin.shippingOrderProfiles.wizard.createDraft') }}</button><button class="primary" type="button" :disabled="saving||!canNext" @click="finish(true)">{{ t('admin.shippingOrderProfiles.wizard.createAndEdit') }}</button></template></footer></section></template>
|
||||
<style scoped>.wizard{display:grid;gap:1.5rem;max-width:58rem;margin:0 auto;padding:1.5rem}.wizard header{display:grid;gap:.5rem}.wizard h1,.wizard p{margin:0}.wizard p{color:#64748b}.wizard footer{display:flex;gap:.75rem;align-items:center}.wizard footer span{flex:1}.wizard button{padding:.55rem .8rem;border:1px solid #cbd5e1;border-radius:.4rem;background:#fff}.wizard .primary{background:#2563eb;color:#fff;border-color:#2563eb}.wizard button:disabled{opacity:.5;cursor:not-allowed}</style>
|
||||
|
||||
<template>
|
||||
<section class="wizard-page">
|
||||
<div class="wizard-shell">
|
||||
<header class="wizard-heading">
|
||||
<div class="wizard-eyebrow"><Sparkles :size="16" /> {{ t('admin.shippingOrderProfiles.title') }}</div>
|
||||
<h1>{{ t('admin.shippingOrderProfiles.wizard.title') }}</h1>
|
||||
<p>{{ t('admin.shippingOrderProfiles.wizard.description') }}</p>
|
||||
</header>
|
||||
|
||||
<ol class="stepper" :aria-label="t('admin.shippingOrderProfiles.wizard.steps', { step })">
|
||||
<li v-for="item in steps" :key="item.number" :class="{ active: item.number === step, complete: item.number < step }">
|
||||
<span class="stepper-icon"><Check v-if="item.number < step" :size="16" /><component :is="item.icon" v-else :size="16" /></span>
|
||||
<span><small>{{ t('admin.shippingOrderProfiles.wizard.stepLabel', { step: item.number }) }}</small>{{ item.label }}</span>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<main class="wizard-card">
|
||||
<div class="wizard-card__heading">
|
||||
<span>{{ t('admin.shippingOrderProfiles.wizard.stepLabel', { step }) }}</span>
|
||||
<h2>{{ steps[step - 1]?.label || '' }}</h2>
|
||||
</div>
|
||||
<OrderProfileIdentityStep
|
||||
v-if="step === 1"
|
||||
:model-value="identity"
|
||||
:schemas="schemas"
|
||||
@update:model-value="updateIdentity"
|
||||
/>
|
||||
<OrderProfileSampleStep v-else-if="step === 2" v-model="documentId" :samples="samples" @uploaded="refreshSamples" />
|
||||
<OrderProfileModelStartStep v-else v-model="tableId" :tables="tables" />
|
||||
</main>
|
||||
|
||||
<footer class="wizard-actions">
|
||||
<button type="button" class="button button--secondary" @click="router.push({ name: 'AdminShippingOrderDocumentProfiles' })">{{ t('admin.cancel') }}</button>
|
||||
<span class="wizard-actions__spacer" />
|
||||
<button v-if="step > 1" type="button" class="button button--ghost" @click="step -= 1"><ArrowLeft :size="17" />{{ t('admin.shippingOrderProfiles.wizard.previous') }}</button>
|
||||
<button v-if="step < 3" type="button" class="button button--primary" :disabled="!canNext" @click="next">{{ t('admin.shippingOrderProfiles.wizard.next') }}<ArrowRight :size="17" /></button>
|
||||
<template v-else>
|
||||
<button type="button" class="button button--secondary" :disabled="saving || !canNext" @click="finish(false)">{{ t('admin.shippingOrderProfiles.wizard.createDraft') }}</button>
|
||||
<button type="button" class="button button--primary" :disabled="saving || !canNext" @click="finish(true)">{{ t('admin.shippingOrderProfiles.wizard.createAndEdit') }}<ArrowRight :size="17" /></button>
|
||||
</template>
|
||||
</footer>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.wizard-page { min-height: 100%; padding: 24px; background: #f6f8fc; }
|
||||
.wizard-shell { width: 100%; }
|
||||
.wizard-heading { margin-bottom: 28px; }.wizard-eyebrow { display: flex; align-items: center; gap: 7px; color: #1677d2; font-size: .82rem; font-weight: 750; letter-spacing: .04em; }.wizard-heading h1 { margin: 10px 0 7px; color: #15213b; font-size: clamp(1.75rem, 3vw, 2.35rem); letter-spacing: -.035em; }.wizard-heading p { margin: 0; color: #64748b; }
|
||||
.stepper { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0; margin: 0 0 18px; padding: 0; list-style: none; }.stepper li { display: flex; align-items: center; gap: 10px; color: #94a3b8; font-size: .86rem; font-weight: 650; }.stepper li:not(:last-child)::after { width: 100%; height: 1px; margin-left: 10px; background: #dbe4f0; content: ''; }.stepper li.active { color: #1677d2; }.stepper li.complete { color: #0f8a65; }.stepper-icon { display: inline-grid; flex: 0 0 auto; width: 32px; height: 32px; place-items: center; border: 1px solid currentColor; border-radius: 50%; background: #fff; }.stepper .complete .stepper-icon { color: #fff; border-color: #0f8a65; background: #0f8a65; }.stepper small { display: block; margin-bottom: 1px; color: #94a3b8; font-size: .68rem; font-weight: 700; text-transform: uppercase; }
|
||||
.wizard-card { min-height: 360px; padding: clamp(24px, 4vw, 44px); border: 1px solid #e1e8f2; border-radius: 12px; background: #fff; box-shadow: 0 8px 24px rgb(15 23 42 / .06); }.wizard-card__heading { margin-bottom: 28px; padding-bottom: 18px; border-bottom: 1px solid #edf1f7; }.wizard-card__heading span { color: #1677d2; font-size: .76rem; font-weight: 750; letter-spacing: .06em; text-transform: uppercase; }.wizard-card__heading h2 { margin: 6px 0 0; color: #1e293b; font-size: 1.25rem; }
|
||||
.wizard-actions { display: flex; align-items: center; gap: 10px; margin-top: 18px; }.wizard-actions__spacer { flex: 1; }.button { display: inline-flex; align-items: center; justify-content: center; gap: 7px; min-height: 42px; padding: 0 15px; border: 1px solid transparent; border-radius: 9px; font-weight: 700; cursor: pointer; transition: transform .15s ease, box-shadow .15s ease, background .15s ease; }.button:hover:not(:disabled) { transform: translateY(-1px); }.button:focus-visible { outline: 3px solid rgb(22 119 210 / .25); outline-offset: 2px; }.button:disabled { opacity: .48; cursor: not-allowed; }.button--primary { color: #fff; border-color: #1668dc; background: #1677d2; box-shadow: 0 6px 16px rgb(22 119 210 / .2); }.button--secondary { color: #34445d; border-color: #d6e0ed; background: #fff; }.button--ghost { color: #47617e; background: transparent; }
|
||||
@media (max-width: 640px) { .wizard-page { padding: 24px 16px; }.stepper { grid-template-columns: 1fr; gap: 10px; }.stepper li:not(:last-child)::after { display: none; }.wizard-card { min-height: 300px; border-radius: 14px; }.wizard-actions { flex-wrap: wrap; }.wizard-actions__spacer { display: none; }.button--secondary:first-child { margin-right: auto; } }
|
||||
</style>
|
||||
+19
-8
@@ -1,19 +1,30 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileIdentityStep.vue
|
||||
用途:收集创建向导第一步的模板身份与 Schema。
|
||||
用途:收集模板名称与已发布 Schema。
|
||||
依赖:Schema DTO、Vue I18n。
|
||||
逻辑:仅双向绑定浏览器状态,不调用创建 API,profile_code 在完成后由服务端永久冻结。
|
||||
逻辑:系统编码由服务端在创建时生成;父级拥有唯一表单状态,避免 v-model 对象替换丢失首步校验状态。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderSchemaVersion } from '@/features/admin/types/shipping-order-schema.types';
|
||||
const props = defineProps<{ modelValue: { displayName: string; profileCode: string; schemaId: number }; schemas: ShippingOrderSchemaVersion[] }>();
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: { displayName: string; profileCode: string; schemaId: number }] }>();
|
||||
type Identity = { displayName: string; schemaId: number };
|
||||
const props = defineProps<{ modelValue: Identity; schemas: ShippingOrderSchemaVersion[] }>();
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: Identity] }>();
|
||||
const { t } = useI18n();
|
||||
const publishedSchemas = computed(() => props.schemas.filter((item) => item.status === 'published'));
|
||||
/** 更新单个身份字段但不触发创建;向导刷新前没有正式 Profile。 */
|
||||
function update(key: 'displayName' | 'profileCode' | 'schemaId', value: string | number): void { emit('update:modelValue', { ...props.modelValue, [key]: value }); }
|
||||
/** 每次更新都提交完整快照,确保父级的下一步校验始终读取最新值。 */
|
||||
function update(key: keyof Identity, value: string | number): void { emit('update:modelValue', { ...props.modelValue, [key]: value }); }
|
||||
</script>
|
||||
<template><div class="wizard-step"><label>{{ t('admin.shippingOrderProfiles.name') }}<input :value="modelValue.displayName" @input="update('displayName', ($event.target as HTMLInputElement).value)"></label><label>{{ t('admin.shippingOrderProfiles.code') }}<input :value="modelValue.profileCode" @input="update('profileCode', ($event.target as HTMLInputElement).value.toUpperCase())"></label><small>{{ t('admin.shippingOrderProfiles.wizard.codeHint') }}</small><label>{{ t('admin.shippingOrderProfiles.schema') }}<select :value="modelValue.schemaId" @change="update('schemaId', Number(($event.target as HTMLSelectElement).value))"><option :value="0">{{ t('admin.shippingOrderProfiles.wizard.selectSchema') }}</option><option v-for="schema in publishedSchemas" :key="schema.id" :value="schema.id">v{{ schema.version }}</option></select></label></div></template>
|
||||
<style scoped>.wizard-step{display:grid;gap:1rem;max-width:36rem}.wizard-step label{display:grid;gap:.35rem;font-weight:600}.wizard-step input,.wizard-step select{padding:.6rem;border:1px solid #cbd5e1;border-radius:.4rem}small{color:#64748b}</style>
|
||||
|
||||
<template>
|
||||
<div class="identity-step">
|
||||
<label class="field"><span>{{ t('admin.shippingOrderProfiles.name') }}<b>*</b></span><input :value="modelValue.displayName" :placeholder="t('admin.shippingOrderProfiles.wizard.namePlaceholder')" @input="update('displayName', ($event.target as HTMLInputElement).value)" /></label>
|
||||
<div class="system-code"><strong>{{ t('admin.shippingOrderProfiles.code') }}</strong><span>{{ t('admin.shippingOrderProfiles.wizard.systemCodeHint') }}</span></div>
|
||||
<label class="field"><span>{{ t('admin.shippingOrderProfiles.schema') }}<b>*</b></span><select :value="modelValue.schemaId" @change="update('schemaId', Number(($event.target as HTMLSelectElement).value))"><option :value="0">{{ t('admin.shippingOrderProfiles.wizard.selectSchema') }}</option><option v-for="schema in publishedSchemas" :key="schema.id" :value="schema.id">v{{ schema.version }}</option></select><small v-if="!publishedSchemas.length" class="field-warning">{{ t('admin.shippingOrderProfiles.wizard.schemaRequired') }}</small></label>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.identity-step { display: grid; gap: 22px; max-width: 560px; }.field { display: grid; gap: 8px; color: #263650; font-weight: 700; }.field > span { display: flex; gap: 4px; }.field b { color: #d14343; }.field input,.field select { width: 100%; min-height: 44px; box-sizing: border-box; border: 1px solid #ccd8e6; border-radius: 9px; padding: 0 12px; color: #172033; background: #fff; font: inherit; outline: none; transition: border-color .15s ease, box-shadow .15s ease; }.field input:focus,.field select:focus { border-color: #1677d2; box-shadow: 0 0 0 3px rgb(22 119 210 / .13); }.field small { color: #71829a; font-size: .8rem; font-weight: 500; }.system-code { display: grid; gap: 4px; padding: 13px 14px; border: 1px solid #dbe7f5; border-radius: 9px; color: #52657d; background: #f7fbff; font-size: .86rem; }.system-code strong { color: #263650; }.field-warning { color: #b45309 !important; }
|
||||
</style>
|
||||
+4
-4
@@ -1,8 +1,8 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileModelStartStep.vue
|
||||
用途:确认样本文档中作为建模起点的主表格。
|
||||
用途:在多表样本中选择用于订单明细标注的表格。
|
||||
依赖:样本表格预览 DTO、Vue I18n。
|
||||
逻辑:只让用户选定服务端已发现的 table_id;缺少有效表格时禁止完成向导。
|
||||
逻辑:只让用户选定服务端已发现的 table_id;预览限制在容器内横向滚动,避免宽表撑破页面。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
@@ -10,5 +10,5 @@ const props = defineProps<{ tables: Array<{ table_id: string; page_no: number; r
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: string] }>();
|
||||
const { t } = useI18n();
|
||||
</script>
|
||||
<template><div class="wizard-step"><label>{{ t('admin.shippingOrderProfiles.table') }}<select :value="modelValue" @change="emit('update:modelValue', ($event.target as HTMLSelectElement).value)"><option value="">{{ t('admin.shippingOrderProfiles.selectTable') }}</option><option v-for="table in tables" :key="table.table_id" :value="table.table_id">{{ t('admin.shippingOrderProfiles.wizard.tableOption', { page: table.page_no, rows: table.row_count, columns: table.column_count }) }}</option></select></label><p v-if="!tables.length">{{ t('admin.shippingOrderProfiles.wizard.noTable') }}</p><table v-else-if="modelValue"><tbody><tr v-for="row in tables.find((item) => item.table_id === modelValue)?.rows.slice(0, 4) || []" :key="row.join('|')"><td v-for="cell in row" :key="cell">{{ cell }}</td></tr></tbody></table></div></template>
|
||||
<style scoped>.wizard-step{display:grid;gap:1rem}.wizard-step label{display:grid;gap:.35rem;font-weight:600}.wizard-step select{padding:.6rem;border:1px solid #cbd5e1;border-radius:.4rem}table{border-collapse:collapse}td{padding:.35rem;border:1px solid #e2e8f0}p{color:#b45309}</style>
|
||||
<template><div class="wizard-step"><div><label>{{ t('admin.shippingOrderProfiles.wizard.orderLineTable') }}<select :value="modelValue" @change="emit('update:modelValue', ($event.target as HTMLSelectElement).value)"><option value="">{{ t('admin.shippingOrderProfiles.selectTable') }}</option><option v-for="table in tables" :key="table.table_id" :value="table.table_id">{{ t('admin.shippingOrderProfiles.wizard.tableOption', { page: table.page_no, rows: table.row_count, columns: table.column_count }) }}</option></select></label><p class="field-hint">{{ t('admin.shippingOrderProfiles.wizard.orderLineTableHint') }}</p></div><p v-if="!tables.length" class="warning">{{ t('admin.shippingOrderProfiles.wizard.noTable') }}</p><div v-else-if="modelValue" class="table-preview"><table><tbody><tr v-for="row in tables.find((item) => item.table_id === modelValue)?.rows.slice(0, 4) || []" :key="row.join('|')"><td v-for="cell in row" :key="cell">{{ cell }}</td></tr></tbody></table></div></div></template>
|
||||
<style scoped>.wizard-step{display:grid;min-width:0;gap:1rem}.wizard-step label{display:grid;gap:.35rem;font-weight:600}.wizard-step select{min-width:0;padding:.6rem;border:1px solid #cbd5e1;border-radius:.4rem}.field-hint{margin:.45rem 0 0;color:#64748b;font-size:.875rem}.warning{color:#b45309}.table-preview{max-width:100%;overflow-x:auto;border:1px solid #e2e8f0;border-radius:.5rem}.table-preview table{width:max-content;min-width:100%;border-collapse:collapse}.table-preview td{max-width:16rem;padding:.55rem;border:1px solid #e2e8f0;overflow-wrap:anywhere;vertical-align:top}</style>
|
||||
+93
-12
@@ -1,21 +1,102 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileSampleStep.vue
|
||||
用途:选择或上传模板样本,并显示其异步解析状态。
|
||||
依赖:模板样本 API、文件资产上传 API、Vue I18n。
|
||||
逻辑:上传只创建样本库 Intake;此步骤不创建 Profile,解析完成后才允许选择样本文档。
|
||||
用途:上传新模板样本或复用已解析样本,并自动选择上传后解析完成的文档。
|
||||
依赖:模板样本 Intake 状态 API、文件资产上传 API、Vue I18n。
|
||||
逻辑:上传后轮询同一 Intake;只有 ready 样本进入父级选择值,避免要求管理员重复选择刚上传的文件。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import { computed, onBeforeUnmount, ref } from 'vue';
|
||||
import { CheckCircle2, Clock3, UploadCloud } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
import { createOrderProfileSample } from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
const props = defineProps<{ samples: Array<{ document_id: number; filename?: string | null; table_count: number; intake_no: string }>; modelValue: number }>();
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: number]; uploaded: [] }>();
|
||||
const { t } = useI18n(); const message = useMessage(); const uploading = ref(false);
|
||||
/** 上传文件后仅投递样本解析;父级轮询并刷新可选样本列表。 */
|
||||
async function upload(event: Event): Promise<void> { const file = (event.target as HTMLInputElement).files?.[0]; if (!file) return; if (!/\.(pdf|eml)$/i.test(file.name)) { message.error(t('admin.shippingOrderProfiles.sampleFileTypeInvalid')); return; } uploading.value = true; try { const asset = await uploadFileAsset(file); await createOrderProfileSample(asset.asset_no); emit('uploaded'); } catch (error) { message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.uploadFailed')); } finally { uploading.value = false; } }
|
||||
import { createOrderProfileSample, getOrderProfileSampleStatus } from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
|
||||
type Sample = { document_id: number; filename?: string | null; table_count: number; intake_no: string };
|
||||
const props = defineProps<{ samples: Sample[]; modelValue: number }>();
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: number]; uploaded: []; }>();
|
||||
const { t } = useI18n();
|
||||
const message = useMessage();
|
||||
const uploading = ref(false);
|
||||
const pendingIntake = ref<{ intakeNo: string; filename: string; state: 'parsing' | 'failed' } | null>(null);
|
||||
let pollingTimer: number | null = null;
|
||||
const selectedSample = computed(() => props.samples.find((item) => item.document_id === props.modelValue) || null);
|
||||
|
||||
/** 停止当前轮询;离开步骤或开始新上传时都不保留后台计时器。 */
|
||||
function stopPolling(): void { if (pollingTimer) window.clearTimeout(pollingTimer); pollingTimer = null; }
|
||||
/** 刷新样本列表后按 Intake 精确定位新文档,防止同名历史文件被误选。 */
|
||||
function selectUploadedSample(intakeNo: string): boolean {
|
||||
const sample = props.samples.find((item) => item.intake_no === intakeNo);
|
||||
if (!sample) return false;
|
||||
emit('update:modelValue', sample.document_id);
|
||||
pendingIntake.value = null;
|
||||
return true;
|
||||
}
|
||||
/** 查询异步解析状态,完成后请求父级刷新列表并自动选中当前上传的样本。 */
|
||||
async function pollIntake(intakeNo: string): Promise<void> {
|
||||
try {
|
||||
const result = await getOrderProfileSampleStatus(intakeNo);
|
||||
if (result.parse_status === 'parsed' && result.document_count > 0) {
|
||||
emit('uploaded');
|
||||
window.setTimeout(() => {
|
||||
if (selectUploadedSample(intakeNo)) message.success(t('admin.shippingOrderProfiles.wizard.sampleReady'));
|
||||
else pollingTimer = window.setTimeout(() => void pollIntake(intakeNo), 800);
|
||||
}, 350);
|
||||
return;
|
||||
}
|
||||
if (['failed', 'error'].includes(result.parse_status)) {
|
||||
pendingIntake.value = { intakeNo, filename: pendingIntake.value?.filename || '', state: 'failed' };
|
||||
return;
|
||||
}
|
||||
pollingTimer = window.setTimeout(() => void pollIntake(intakeNo), 1500);
|
||||
} catch {
|
||||
pollingTimer = window.setTimeout(() => void pollIntake(intakeNo), 2000);
|
||||
}
|
||||
}
|
||||
/** 上传后立即显示解析状态;此处不创建 Profile,解析成功才自动选择样本文档。 */
|
||||
async function upload(event: Event): Promise<void> {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
input.value = '';
|
||||
if (!file || uploading.value) return;
|
||||
if (!/\.(pdf|eml)$/i.test(file.name)) { message.error(t('admin.shippingOrderProfiles.sampleFileTypeInvalid')); return; }
|
||||
stopPolling();
|
||||
uploading.value = true;
|
||||
try {
|
||||
const asset = await uploadFileAsset(file);
|
||||
const intake = await createOrderProfileSample(asset.asset_no);
|
||||
pendingIntake.value = { intakeNo: intake.intake_no, filename: file.name, state: 'parsing' };
|
||||
void pollIntake(intake.intake_no);
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.uploadFailed'));
|
||||
} finally { uploading.value = false; }
|
||||
}
|
||||
onBeforeUnmount(stopPolling);
|
||||
</script>
|
||||
<template><div class="wizard-step"><label>{{ t('admin.shippingOrderProfiles.uploadSample') }}<input type="file" accept=".pdf,.eml,application/pdf,message/rfc822" :disabled="uploading" @change="upload"></label><p>{{ t('admin.shippingOrderProfiles.wizard.sampleHint') }}</p><label>{{ t('admin.shippingOrderProfiles.selectSample') }}<select :value="modelValue" @change="emit('update:modelValue', Number(($event.target as HTMLSelectElement).value))"><option :value="0">{{ t('admin.shippingOrderProfiles.selectSample') }}</option><option v-for="sample in samples" :key="sample.document_id" :value="sample.document_id">{{ sample.filename || sample.intake_no }} · {{ sample.table_count }} {{ t('admin.shippingOrderProfiles.tablesUnit') }}</option></select></label></div></template>
|
||||
<style scoped>.wizard-step{display:grid;gap:1rem;max-width:36rem}.wizard-step label{display:grid;gap:.35rem;font-weight:600}.wizard-step select{padding:.6rem;border:1px solid #cbd5e1;border-radius:.4rem}p{margin:0;color:#64748b}</style>
|
||||
|
||||
<template>
|
||||
<div class="sample-step">
|
||||
<section class="upload-panel">
|
||||
<div class="upload-panel__icon"><UploadCloud :size="22" /></div>
|
||||
<div><h3>{{ t('admin.shippingOrderProfiles.wizard.uploadNewSample') }}</h3><p>{{ t('admin.shippingOrderProfiles.wizard.uploadNewSampleHint') }}</p></div>
|
||||
<label class="upload-action"><input type="file" accept=".pdf,.eml,application/pdf,message/rfc822" :disabled="uploading" @change="upload"><span>{{ uploading ? t('admin.shippingOrderProfiles.wizard.uploading') : t('admin.shippingOrderProfiles.uploadSample') }}</span></label>
|
||||
</section>
|
||||
|
||||
<div v-if="pendingIntake" class="parse-status" :class="{ failed: pendingIntake.state === 'failed' }">
|
||||
<Clock3 v-if="pendingIntake.state === 'parsing'" :size="19" /><span v-else>!</span>
|
||||
<div><strong>{{ pendingIntake.filename }}</strong><p>{{ pendingIntake.state === 'parsing' ? t('admin.shippingOrderProfiles.wizard.sampleParsing') : t('admin.shippingOrderProfiles.wizard.sampleParseFailed') }}</p></div>
|
||||
</div>
|
||||
|
||||
<div v-if="selectedSample" class="selected-sample"><CheckCircle2 :size="20" /><div><strong>{{ t('admin.shippingOrderProfiles.wizard.sampleSelected') }}</strong><span>{{ selectedSample.filename || selectedSample.intake_no }} · {{ selectedSample.table_count }} {{ t('admin.shippingOrderProfiles.tablesUnit') }}</span></div></div>
|
||||
|
||||
<section class="reuse-panel">
|
||||
<div class="reuse-panel__heading"><h3>{{ t('admin.shippingOrderProfiles.wizard.reuseSample') }}</h3><p>{{ t('admin.shippingOrderProfiles.wizard.reuseSampleHint') }}</p></div>
|
||||
<label class="field"><span>{{ t('admin.shippingOrderProfiles.selectSample') }}</span><select :value="modelValue" @change="emit('update:modelValue', Number(($event.target as HTMLSelectElement).value))"><option :value="0">{{ t('admin.shippingOrderProfiles.selectSample') }}</option><option v-for="sample in samples" :key="sample.document_id" :value="sample.document_id">{{ sample.filename || sample.intake_no }} · {{ sample.table_count }} {{ t('admin.shippingOrderProfiles.tablesUnit') }}</option></select></label>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.sample-step { display: grid; gap: 18px; max-width: 640px; }.upload-panel,.reuse-panel,.parse-status,.selected-sample { border: 1px solid #dce6f2; border-radius: 12px; background: #fff; }.upload-panel { display: grid; grid-template-columns: auto 1fr auto; gap: 14px; align-items: center; padding: 18px; background: linear-gradient(110deg, #f6fbff, #fff); }.upload-panel__icon { display: grid; width: 42px; height: 42px; place-items: center; border-radius: 10px; color: #1677d2; background: #e6f4ff; }.upload-panel h3,.reuse-panel h3,.parse-status p,.selected-sample span { margin: 0; }.upload-panel h3,.reuse-panel h3 { color: #263650; font-size: 1rem; }.upload-panel p,.reuse-panel p { margin: 5px 0 0; color: #71829a; font-size: .84rem; }.upload-action { display: inline-flex; min-height: 38px; align-items: center; border-radius: 8px; padding: 0 13px; color: #fff; background: #1677d2; font-weight: 700; cursor: pointer; }.upload-action input { position: absolute; width: 1px; height: 1px; overflow: hidden; opacity: 0; }.parse-status,.selected-sample { display: flex; gap: 10px; align-items: center; padding: 13px 15px; color: #1677d2; background: #f7fbff; }.parse-status strong,.selected-sample strong { display: block; color: #263650; }.parse-status p,.selected-sample span { display: block; margin-top: 3px; color: #64748b; font-size: .83rem; }.parse-status.failed { color: #cf4b4b; border-color: #f0caca; background: #fff8f8; }.parse-status.failed > span { display: grid; width: 19px; height: 19px; place-items: center; border-radius: 50%; color: #fff; background: #cf4b4b; font-weight: 800; }.selected-sample { color: #0f8a65; border-color: #c6eadc; background: #f3fcf8; }.reuse-panel { padding: 18px; }.reuse-panel__heading { margin-bottom: 14px; }.field { display: grid; gap: 7px; color: #475c78; font-size: .88rem; font-weight: 700; }.field select { min-height: 44px; border: 1px solid #ccd8e6; border-radius: 9px; padding: 0 12px; color: #263650; background: #fff; font: inherit; }.field select:focus { outline: 3px solid rgb(22 119 210 / .13); border-color: #1677d2; } @media (max-width: 640px) { .upload-panel { grid-template-columns: auto 1fr; }.upload-action { grid-column: 1 / -1; justify-content: center; } }
|
||||
</style>
|
||||
+1095
-782
File diff suppressed because it is too large.
Load diff
@@ -12,6 +12,8 @@ import type { ShippingManagementGroupKey } from './stores/admin-nav.store';
|
||||
|
||||
const shippingRoutes = adminRoutes[0].children?.filter((route) =>
|
||||
route.name === 'AdminShippingInventory'
|
||||
|| route.name === 'AdminShippingFieldAssets'
|
||||
|| route.name === 'AdminShippingOrderSchema'
|
||||
|| route.name === 'AdminShippingIdentityRules'
|
||||
|| route.name === 'AdminShippingOrderExtractionRuns'
|
||||
|| route.name === 'AdminShippingOrderDocumentProfiles',
|
||||
@@ -31,7 +33,8 @@ describe('shipping configuration navigation contract', () => {
|
||||
it('registers all shipping configuration subpages with discoverable deep links', () => {
|
||||
// 关键断言:导航注册表与深链路由必须一一对应,避免后台入口不可发现。
|
||||
expect(SHIPPING_CONFIG_SUB_MODULE_METAS).toEqual([
|
||||
{ id: 'order_fields', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.nav.shippingOrderFields', groupKey: 'admin.nav.shippingOrderRecognition', query: { section: 'orderSchema' } },
|
||||
{ id: 'field_assets', routeName: 'AdminShippingFieldAssets', path: 'shipping-field-assets', labelKey: 'admin.nav.shippingFieldAssets', groupKey: 'admin.nav.shippingOrderRecognition' },
|
||||
{ id: 'order_schema', routeName: 'AdminShippingOrderSchema', path: 'shipping-order-schema', labelKey: 'admin.nav.shippingOrderSchema', groupKey: 'admin.nav.shippingOrderRecognition' },
|
||||
{ id: 'order_document_profiles', routeName: 'AdminShippingOrderDocumentProfiles', path: 'shipping-order-document-profiles', labelKey: 'admin.nav.shippingOrderDocumentProfiles', groupKey: 'admin.nav.shippingOrderRecognition' },
|
||||
{ id: 'identity_rules', routeName: 'AdminShippingIdentityRules', path: 'shipping-identity-rules', labelKey: 'admin.nav.shippingIdentityRules', groupKey: 'admin.nav.shippingOrderRecognition' },
|
||||
{ id: 'order_extraction_runs', routeName: 'AdminShippingOrderExtractionRuns', path: 'shipping-order-extraction-runs', labelKey: 'admin.nav.shippingOrderExtractionRuns', groupKey: 'admin.nav.shippingOrderRecognition' },
|
||||
@@ -44,7 +47,7 @@ describe('shipping configuration navigation contract', () => {
|
||||
{ id: 'inventory_snapshots', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.snapshots', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'snapshots' } },
|
||||
{ id: 'export_records', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.exports', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'exports' } },
|
||||
]);
|
||||
expect(shippingRoutes).toHaveLength(4);
|
||||
expect(shippingRoutes).toHaveLength(6);
|
||||
});
|
||||
|
||||
it('keeps exactly three ordered accordion groups', () => {
|
||||
@@ -61,6 +64,8 @@ describe('shipping configuration navigation contract', () => {
|
||||
// 关键断言:菜单可见性不是授权;所有页面均须保留 requiresAdmin 和共享模块权限标识。
|
||||
expect(shippingRoutes.map((route) => route.meta)).toEqual([
|
||||
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'inventory' }),
|
||||
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'field_assets' }),
|
||||
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'order_schema' }),
|
||||
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'identity_rules' }),
|
||||
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'order_extraction_runs' }),
|
||||
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'order_document_profiles' }),
|
||||
|
||||
@@ -22,7 +22,8 @@ export type AdminModuleId =
|
||||
|
||||
/** 货代管理领域下可由侧栏展示和高亮的稳定业务页面。 */
|
||||
export type ShippingConfigSubModuleId =
|
||||
| 'order_fields'
|
||||
| 'field_assets'
|
||||
| 'order_schema'
|
||||
| 'order_document_profiles'
|
||||
| 'identity_rules'
|
||||
| 'order_extraction_runs'
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* features/admin/types/shipping-field-assets.types.ts
|
||||
* 用途:字段资产库管理 API 的 DTO 类型。
|
||||
* 依赖:无。
|
||||
* 逻辑:shipping-field-assets API 与字段资产库页面共享这些稳定类型。
|
||||
*/
|
||||
|
||||
export type ShippingFieldAssetKind = 'system_standard' | 'extension';
|
||||
export type ShippingFieldStorageMode = 'typed_column' | 'json_only';
|
||||
export type ShippingFieldAssetStatus = 'active' | 'retired';
|
||||
|
||||
export interface ShippingFieldAssetAdoption {
|
||||
schema_version_id: number;
|
||||
version: number;
|
||||
status: string;
|
||||
schema_id: number;
|
||||
schema_code?: string | null;
|
||||
schema_display_name?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingFieldAsset {
|
||||
id: string;
|
||||
field_code: string;
|
||||
scope: 'header' | 'line';
|
||||
value_type: 'string' | 'decimal' | 'integer' | 'date' | 'boolean' | 'enum';
|
||||
field_category: 'order_header' | 'order_line';
|
||||
collection_mode: 'deterministic_context' | 'llm_extraction';
|
||||
asset_kind: ShippingFieldAssetKind;
|
||||
storage_mode: ShippingFieldStorageMode;
|
||||
storage_column: string | null;
|
||||
storage_table?: string | null;
|
||||
storage_path?: string | null;
|
||||
storage_kind?: 'typed_column' | 'standard_json' | 'extension_json' | null;
|
||||
semantic_description: string | null;
|
||||
display_name_default: string | null;
|
||||
fulfillment_role: string | null;
|
||||
display_sequence: number;
|
||||
status: ShippingFieldAssetStatus;
|
||||
published_once: boolean;
|
||||
retired_reason: string | null;
|
||||
retired_at: string | null;
|
||||
restored_at: string | null;
|
||||
created_at: string | null;
|
||||
updated_at: string | null;
|
||||
adoption_summary?: {
|
||||
total: number;
|
||||
published: number;
|
||||
draft: number;
|
||||
retired: number;
|
||||
};
|
||||
adoptions?: ShippingFieldAssetAdoption[];
|
||||
}
|
||||
|
||||
export interface ShippingFieldAssetListResponse {
|
||||
items: ShippingFieldAsset[];
|
||||
standard_count: number;
|
||||
extension_count: number;
|
||||
locked_standard_codes: string[];
|
||||
}
|
||||
|
||||
export interface ShippingFieldImpactItem {
|
||||
kind: string;
|
||||
object_id: string | number;
|
||||
display_name: string;
|
||||
status: string;
|
||||
version?: number | string | null;
|
||||
reference_path: string;
|
||||
admin_path?: string | null;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ShippingFieldAssetImpact {
|
||||
field_id: string;
|
||||
field_code: string | null;
|
||||
blocking_items: ShippingFieldImpactItem[];
|
||||
blocking_kinds: string[];
|
||||
blocking_count: number;
|
||||
historical: {
|
||||
observation_count: number;
|
||||
decision_count: number;
|
||||
value_count: number;
|
||||
immutable_schema_version_count: number;
|
||||
immutable_schema_versions?: Array<{
|
||||
schema_version_id: number;
|
||||
version: number;
|
||||
status: string;
|
||||
schema_code?: string | null;
|
||||
schema_display_name?: string | null;
|
||||
}>;
|
||||
blocks_publish: boolean;
|
||||
};
|
||||
can_unadopt: boolean;
|
||||
can_retire_extension: boolean;
|
||||
}
|
||||
|
||||
export interface ShippingFieldAssetAuditEvent {
|
||||
id: number;
|
||||
event_type: string;
|
||||
actor_id: number | null;
|
||||
actor_display_name?: string | null;
|
||||
request_id: string | null;
|
||||
before: Record<string, unknown> | null;
|
||||
after: Record<string, unknown> | null;
|
||||
change_summary: Record<string, unknown>;
|
||||
created_at: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingFieldAssetAuditPage {
|
||||
field_id: string;
|
||||
items: ShippingFieldAssetAuditEvent[];
|
||||
}
|
||||
|
||||
export interface CreateShippingFieldExtensionPayload {
|
||||
field_code: string;
|
||||
scope: 'header' | 'line';
|
||||
value_type: ShippingFieldAsset['value_type'];
|
||||
display_name: string;
|
||||
semantic_description?: string;
|
||||
}
|
||||
|
||||
export interface UpdateShippingFieldExtensionPayload {
|
||||
display_name?: string;
|
||||
semantic_description?: string | null;
|
||||
expected_updated_at: string;
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
/**
|
||||
* features/admin/types/shipping-order-schema.types.ts
|
||||
* 用途:订单 Schema 管理 API 的字段、版本和能力目录类型。
|
||||
* 用途:单一发货订单 Schema 管理 API 的字段、版本和能力目录类型。
|
||||
* 依赖:无。
|
||||
* 逻辑:shipping-order-schema API 与管理页面共享这些稳定 DTO。
|
||||
* 逻辑:shipping-order-schema API 与管理页面共享这些稳定 DTO;无多族字段。
|
||||
*/
|
||||
export type ShippingFieldAssetKind = 'system_standard' | 'extension';
|
||||
export type ShippingFieldStorageMode = 'typed_column' | 'json_only';
|
||||
|
||||
export interface ShippingOrderField {
|
||||
id: string;
|
||||
field_code: string;
|
||||
@@ -11,9 +14,16 @@ export interface ShippingOrderField {
|
||||
value_type: 'string' | 'decimal' | 'integer' | 'date' | 'boolean' | 'enum';
|
||||
field_category: 'general_context' | 'order_header' | 'order_line';
|
||||
collection_mode: 'deterministic_context' | 'llm_extraction';
|
||||
asset_kind?: ShippingFieldAssetKind;
|
||||
storage_mode?: ShippingFieldStorageMode;
|
||||
storage_column?: string | null;
|
||||
semantic_description?: string | null;
|
||||
display_name_default?: string | null;
|
||||
fulfillment_role?: string | null;
|
||||
display_sequence: number;
|
||||
status: 'active' | 'retired';
|
||||
published_once: boolean;
|
||||
retired_reason?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderFieldConfig {
|
||||
@@ -78,7 +88,10 @@ export interface ShippingOrderSchemaVersion {
|
||||
created_by?: SchemaVersionActor | null;
|
||||
published_by?: SchemaVersionActor | null;
|
||||
field_count: number;
|
||||
definition?: { fields: ShippingOrderFieldConfig[] };
|
||||
definition?: {
|
||||
fields: ShippingOrderFieldConfig[];
|
||||
auto_creation_policy?: { enabled: boolean };
|
||||
};
|
||||
}
|
||||
|
||||
export interface SchemaVersionActor {
|
||||
@@ -116,6 +129,12 @@ export interface ShippingOrderSchemaVersionDiff {
|
||||
compare_version: ShippingOrderSchemaVersion;
|
||||
summary: Record<'added' | 'removed' | 'modified' | 'unchanged', number>;
|
||||
fields: ShippingOrderSchemaFieldDiff[];
|
||||
auto_creation_policy?: {
|
||||
key: string;
|
||||
kind: 'value';
|
||||
before: boolean;
|
||||
after: boolean;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderSchemaAuditEvent {
|
||||
@@ -202,6 +221,7 @@ export interface ShippingOrderSchemaState {
|
||||
status: string;
|
||||
auto_creation_policy: { enabled: boolean };
|
||||
};
|
||||
suggested_adoption_codes?: string[];
|
||||
fields: ShippingOrderField[];
|
||||
versions: ShippingOrderSchemaVersion[];
|
||||
catalog: {
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
* features/chat/api/shipping.api.ts
|
||||
* 用途:封装发货通知相关 HTTP API,包括任务/批次查询、人工决策与 Excel 导出。
|
||||
* 依赖:统一 requestJson / BusinessError、shipping.api.types 类型定义。
|
||||
* 逻辑:上游由 useChatShipping 与 shipping/* handler 调用本文件;本文件统一请求工作台后端 `/api/workspace/*` 路由并抛出标准错误。
|
||||
* 逻辑:上游由 useChatShipping、shipping-task-center 与 shipping/* handler 调用;
|
||||
* 「我的待办」列表/徽标见 features/workspace/api/shipping-tasks.api.ts。
|
||||
*/
|
||||
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
|
||||
@@ -1,400 +1,829 @@
|
||||
/**
|
||||
|
||||
* features/chat/components/ChatViewContent.vue
|
||||
* 用途:对话页主区域,组合侧栏、发货批次进度区、消息列表、输入栏与内置浏览器。
|
||||
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingBatchProgressPanel、ShippingBatchWorkspaceDrawer、chat.context。
|
||||
* 逻辑:本文件只做页面结构编排;发货批次进度样式与任务续办交互下沉到独立面板组件。
|
||||
|
||||
* 用途:对话页主区域,组合侧栏、消息列表、输入栏、货代会话任务摘要与内置浏览器。
|
||||
|
||||
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingSessionSummaryPanel、chat.context。
|
||||
|
||||
* 逻辑:本文件只做页面结构编排;货代 Chat 仅上传/进度通知,履约写操作不在本页;右侧摘要只读展示后端 ui_state/summary。
|
||||
|
||||
*/
|
||||
|
||||
<script setup lang="ts">
|
||||
|
||||
import { computed, ref, watch } from 'vue';
|
||||
|
||||
import { useRoute } from 'vue-router';
|
||||
|
||||
import { Maximize2, Minimize2, Loader2 } from 'lucide-vue-next';
|
||||
|
||||
import ChatShell from '@/shared/layouts/ChatShell.vue';
|
||||
|
||||
import ChatSidebar from '@/features/chat/components/ChatSidebar.vue';
|
||||
|
||||
import ChatInputBar from '@/features/chat/components/ChatInputBar.vue';
|
||||
|
||||
import ChatMessageList from '@/features/chat/components/ChatMessageList.vue';
|
||||
|
||||
import ChatMobileHeader from '@/features/chat/components/ChatMobileHeader.vue';
|
||||
|
||||
import ChatBrowserPanel from '@/features/chat/components/ChatBrowserPanel.vue';
|
||||
import ShippingBatchProgressPanel from '@/features/chat/components/ShippingBatchProgressPanel.vue';
|
||||
import ShippingBatchWorkspaceDrawer from '@/features/chat/components/ShippingBatchWorkspaceDrawer.vue';
|
||||
|
||||
import ShippingSessionSummaryPanel from '@/features/chat/components/ShippingSessionSummaryPanel.vue';
|
||||
|
||||
import TrainingWorkspacePanel from '@/features/chat/components/TrainingWorkspacePanel.vue';
|
||||
|
||||
import LedgerConfigPanel from '@/features/maintenance/components/LedgerConfigPanel.vue';
|
||||
|
||||
import MaintenanceRecordManagerPanel from '@/features/maintenance/components/MaintenanceRecordManagerPanel.vue';
|
||||
|
||||
import ShippingOrderReviewView from '@/features/chat/views/ShippingOrderReviewView.vue';
|
||||
|
||||
import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
|
||||
import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace.utils';
|
||||
|
||||
import { agentHasIntentUiProfile } from '@/shared/utils/agent-registry.utils';
|
||||
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
|
||||
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
|
||||
|
||||
import {
|
||||
|
||||
MAINTENANCE_PANEL_DEFAULT_WIDTH,
|
||||
|
||||
buildMaintenancePanelWidthStyle,
|
||||
|
||||
clampMaintenancePanelWidth,
|
||||
|
||||
} from '@/features/maintenance/utils/maintenance-panel-layout.utils';
|
||||
|
||||
|
||||
|
||||
type MaintenanceRecordPanelCommand = {
|
||||
|
||||
mode: 'list' | 'create';
|
||||
|
||||
device: MaintenanceDevice;
|
||||
|
||||
nonce: number;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
const page = useChatPageContext();
|
||||
|
||||
const route = useRoute();
|
||||
|
||||
const isOrderReviewMode = computed(() => route.query.mode === 'order-review' && typeof route.query.run_no === 'string' && route.query.run_no.length > 0);
|
||||
|
||||
const isTrainingAgentPage = computed(() => matchesTrainingAgent(page.currentAgent));
|
||||
|
||||
const isMaintenanceAgentPage = computed(() => agentHasIntentUiProfile(page.currentAgent, 'maintenance'));
|
||||
const embeddedIframeSrc = computed(() => {
|
||||
const agent = page.currentAgent;
|
||||
if (!agent) return undefined;
|
||||
const url = agent.iframe_url;
|
||||
return url ? String(url) : undefined;
|
||||
});
|
||||
const canManageMaintenance = computed(() => ['admin', 'maintenance_manager'].includes(String(page.currentUser?.role || '')));
|
||||
const hideWelcomePanel = computed(() => false);
|
||||
const hideWelcomeTitle = computed(() => isTrainingAgentPage.value);
|
||||
const isTrainingWorkspaceExpanded = ref(false);
|
||||
const maintenancePanel = ref<'ledger' | 'record' | null>(null);
|
||||
const maintenanceEditRecord = ref<MaintenanceRecord | null>(null);
|
||||
const maintenanceRecordPanelCommand = ref<MaintenanceRecordPanelCommand | null>(null);
|
||||
const maintenancePanelWidth = ref(MAINTENANCE_PANEL_DEFAULT_WIDTH);
|
||||
const isMaintenancePanelFullscreen = ref(false);
|
||||
const isMaintenancePanelResizing = ref(false);
|
||||
const maintenancePanelStyle = computed(() => {
|
||||
if (isMaintenancePanelFullscreen.value) {
|
||||
return { width: '100%', minWidth: '100%', maxWidth: '100%' };
|
||||
|
||||
const activeExtractionRunNo = computed(() => {
|
||||
|
||||
// [STEP 1] 优先从消息流中的抽取状态卡取 run_no(终态后仍在消息里)。
|
||||
// page 经 reactive provide 后 messages 已解包为数组,禁止再读 .value。
|
||||
const messages = Array.isArray(page.messages) ? page.messages : [];
|
||||
|
||||
for (let i = messages.length - 1; i >= 0; i -= 1) {
|
||||
|
||||
const item = messages[i];
|
||||
|
||||
if (!item || item.role !== 'assistant') continue;
|
||||
|
||||
const payload = item.payload && typeof item.payload === 'object' ? item.payload : null;
|
||||
|
||||
const fromPayload = payload && typeof (payload as { order_extraction_run_no?: unknown }).order_extraction_run_no === 'string'
|
||||
|
||||
? String((payload as { order_extraction_run_no: string }).order_extraction_run_no).trim()
|
||||
|
||||
: '';
|
||||
|
||||
if (fromPayload) return fromPayload;
|
||||
|
||||
if (item.shipping_order_extraction_state) {
|
||||
|
||||
const fromGetter = String(page.getActiveOrderExtractionRunNo?.() || '').trim();
|
||||
|
||||
if (fromGetter) return fromGetter;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
return buildMaintenancePanelWidthStyle(maintenancePanelWidth.value);
|
||||
|
||||
// [STEP 2] 回退活动 Run(轮询中)与路由深链。
|
||||
|
||||
try {
|
||||
|
||||
const fromActive = String(page.getActiveOrderExtractionRunNo?.() || '').trim();
|
||||
|
||||
if (fromActive) return fromActive;
|
||||
|
||||
} catch {
|
||||
|
||||
/* ignore */
|
||||
|
||||
}
|
||||
|
||||
const fromQuery = typeof route.query.run_no === 'string' ? route.query.run_no.trim() : '';
|
||||
|
||||
return fromQuery;
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
const showShippingSessionSummary = computed(() => (
|
||||
|
||||
page.isShippingNoticeAgent
|
||||
|
||||
&& Boolean(
|
||||
|
||||
page.shippingBatchSummary
|
||||
|
||||
|| page.shippingConversationWorkspace?.batches?.length
|
||||
|
||||
|| activeExtractionRunNo.value
|
||||
|
||||
)
|
||||
|
||||
));
|
||||
|
||||
const embeddedIframeSrc = computed(() => {
|
||||
|
||||
const agent = page.currentAgent;
|
||||
|
||||
if (!agent) return undefined;
|
||||
|
||||
const url = agent.iframe_url;
|
||||
|
||||
return url ? String(url) : undefined;
|
||||
|
||||
});
|
||||
|
||||
const canManageMaintenance = computed(() => ['admin', 'maintenance_manager'].includes(String(page.currentUser?.role || '')));
|
||||
|
||||
const hideWelcomePanel = computed(() => false);
|
||||
|
||||
const hideWelcomeTitle = computed(() => isTrainingAgentPage.value);
|
||||
|
||||
const isTrainingWorkspaceExpanded = ref(false);
|
||||
|
||||
const maintenancePanel = ref<'ledger' | 'record' | null>(null);
|
||||
|
||||
const maintenanceEditRecord = ref<MaintenanceRecord | null>(null);
|
||||
|
||||
const maintenanceRecordPanelCommand = ref<MaintenanceRecordPanelCommand | null>(null);
|
||||
|
||||
const maintenancePanelWidth = ref(MAINTENANCE_PANEL_DEFAULT_WIDTH);
|
||||
|
||||
const isMaintenancePanelFullscreen = ref(false);
|
||||
|
||||
const isMaintenancePanelResizing = ref(false);
|
||||
|
||||
const maintenancePanelStyle = computed(() => {
|
||||
|
||||
if (isMaintenancePanelFullscreen.value) {
|
||||
|
||||
return { width: '100%', minWidth: '100%', maxWidth: '100%' };
|
||||
|
||||
}
|
||||
|
||||
return buildMaintenancePanelWidthStyle(maintenancePanelWidth.value);
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 开始拖拽设备维保右侧面板左边缘,允许管理员按表格内容临时调宽。
|
||||
|
||||
* @param event - 鼠标按下事件。
|
||||
|
||||
*/
|
||||
|
||||
const startMaintenancePanelResize = (event: MouseEvent): void => {
|
||||
|
||||
if (isMaintenancePanelFullscreen.value) return;
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
isMaintenancePanelResizing.value = true;
|
||||
|
||||
const startX = event.clientX;
|
||||
|
||||
const startWidth = maintenancePanelWidth.value;
|
||||
|
||||
const handleMove = (moveEvent: MouseEvent) => {
|
||||
|
||||
const nextWidth = startWidth + (startX - moveEvent.clientX);
|
||||
|
||||
maintenancePanelWidth.value = clampMaintenancePanelWidth(nextWidth, window.innerWidth);
|
||||
|
||||
};
|
||||
|
||||
const stopResize = () => {
|
||||
|
||||
isMaintenancePanelResizing.value = false;
|
||||
|
||||
window.removeEventListener('mousemove', handleMove);
|
||||
|
||||
window.removeEventListener('mouseup', stopResize);
|
||||
|
||||
};
|
||||
|
||||
window.addEventListener('mousemove', handleMove);
|
||||
|
||||
window.addEventListener('mouseup', stopResize);
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 打开右侧维修记录面板并进入指定记录的编辑表单。
|
||||
|
||||
* @param record - 会话结果表格中选中的维修记录。
|
||||
|
||||
*/
|
||||
|
||||
const openMaintenanceRecordEdit = (record: MaintenanceRecord): void => {
|
||||
|
||||
maintenanceEditRecord.value = record;
|
||||
|
||||
maintenanceRecordPanelCommand.value = null;
|
||||
|
||||
maintenancePanel.value = 'record';
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 鎵撳紑鍙充晶缁翠慨璁板綍鍒楄〃锛屽苟鎸夊綋鍓嶈澶囩紪鍙风瓫閫夊巻鍙茶褰曘€?
|
||||
* @param device - 浼氳瘽缁撴灉涓懡涓殑璁惧銆?
|
||||
|
||||
* 打开右侧维修记录列表,并按当前设备编号筛选历史记录。
|
||||
|
||||
* @param device - 会话结果中命中的设备。
|
||||
|
||||
*/
|
||||
|
||||
const openMaintenanceRecordHistory = (device: MaintenanceDevice): void => {
|
||||
|
||||
maintenanceEditRecord.value = null;
|
||||
|
||||
maintenanceRecordPanelCommand.value = { mode: 'list', device, nonce: Date.now() };
|
||||
|
||||
maintenancePanel.value = 'record';
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 鎵撳紑鍙充晶缁翠慨璁板綍鏂板琛ㄥ崟锛屽苟棰勫~褰撳墠璁惧缂栧彿銆?
|
||||
* @param device - 浼氳瘽缁撴灉涓懡涓殑璁惧銆?
|
||||
|
||||
* 打开右侧维修记录新增表单,并预填当前设备编号。
|
||||
|
||||
* @param device - 会话结果中命中的设备。
|
||||
|
||||
*/
|
||||
|
||||
const openMaintenanceRecordCreate = (device: MaintenanceDevice): void => {
|
||||
|
||||
maintenanceEditRecord.value = null;
|
||||
|
||||
maintenanceRecordPanelCommand.value = { mode: 'create', device, nonce: Date.now() };
|
||||
|
||||
maintenancePanel.value = 'record';
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 打开空白维修记录新增表单(不预填设备)。
|
||||
|
||||
*/
|
||||
|
||||
const openBlankMaintenanceRecordCreate = (): void => {
|
||||
|
||||
maintenanceEditRecord.value = null;
|
||||
|
||||
maintenanceRecordPanelCommand.value = null;
|
||||
|
||||
maintenancePanel.value = 'record';
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
// 切换非培训 Agent 时,重置工作区展开状态;培训 Agent 的默认展开策略交给 TrainingWorkspacePanel 按角色决定。
|
||||
|
||||
watch(() => page.currentAgentId, () => {
|
||||
|
||||
if (!isTrainingAgentPage.value) {
|
||||
|
||||
isTrainingWorkspaceExpanded.value = false;
|
||||
|
||||
}
|
||||
|
||||
maintenancePanel.value = null;
|
||||
|
||||
isMaintenancePanelFullscreen.value = false;
|
||||
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
<template>
|
||||
|
||||
<ChatShell>
|
||||
|
||||
<template #overlay>
|
||||
|
||||
<div
|
||||
|
||||
v-if="page.isSidebarOpen && !page.isMobile"
|
||||
|
||||
class="fixed inset-0 z-40 bg-overlay backdrop-blur-sm transition-opacity md:hidden"
|
||||
|
||||
@click="page.isSidebarOpen = false"
|
||||
|
||||
/>
|
||||
|
||||
</template>
|
||||
|
||||
|
||||
|
||||
<template #sidebar>
|
||||
|
||||
<ChatSidebar
|
||||
|
||||
v-if="!page.isMobile"
|
||||
|
||||
v-model:collapsed="page.sidebarCollapsed"
|
||||
|
||||
v-model:agent-panel-open="page.showAgentPanel"
|
||||
|
||||
:is-open="page.isSidebarOpen"
|
||||
|
||||
:current-agent="page.currentAgent"
|
||||
|
||||
:current-agent-id="page.currentAgentId"
|
||||
|
||||
:agent-description="page.agentDescription"
|
||||
|
||||
:has-agent-guides="page.agentGuides.length > 0"
|
||||
|
||||
:display-history="page.displayHistory"
|
||||
|
||||
:active-history-key="page.activeHistoryKey"
|
||||
|
||||
:user-agents="page.userAgents"
|
||||
|
||||
:current-user="page.currentUser"
|
||||
|
||||
:applied-theme="page.appliedTheme"
|
||||
|
||||
@new-chat="page.handleSidebarNewChat"
|
||||
|
||||
@open-guide="page.openGuideModal"
|
||||
|
||||
@history-select="page.handleHistorySelect"
|
||||
|
||||
@clear-all-history="page.clearAllHistory"
|
||||
|
||||
@delete-history-item="page.deleteHistoryItem"
|
||||
|
||||
@switch-agent="page.switchToAgent"
|
||||
|
||||
@toggle-theme="page.toggleLightDark"
|
||||
|
||||
@open-feedback="page.showGeneralFeedbackDialog = true"
|
||||
|
||||
@go-workspace="page.goToWorkspace()"
|
||||
|
||||
@go-admin="page.goToAdmin"
|
||||
|
||||
@logout="page.handleLogout"
|
||||
|
||||
/>
|
||||
|
||||
</template>
|
||||
|
||||
|
||||
|
||||
<ChatMobileHeader
|
||||
|
||||
v-if="page.isMobile && page.currentAgent"
|
||||
|
||||
:agent-name="page.currentAgent?.name || 'AI'"
|
||||
|
||||
:active-agent-id="page.currentAgentId"
|
||||
|
||||
:has-agent-guides="page.agentGuides.length > 0"
|
||||
|
||||
:user-agents="page.userAgents"
|
||||
|
||||
@open-guide="page.openGuideModal"
|
||||
|
||||
@go-history="page.goToWorkspace('history')"
|
||||
|
||||
@open-agent-popover="page.loadUserAgents"
|
||||
|
||||
@switch-agent="page.switchToAgent"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
|
||||
<div v-if="!page.currentAgent" class="flex flex-1 flex-col items-center justify-center space-y-4">
|
||||
|
||||
<Loader2 class="h-10 w-10 animate-spin text-brand-500" />
|
||||
|
||||
<p class="text-sm animate-pulse text-muted">{{ $t('chat.loadingAgent') }}</p>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div v-else-if="page.currentAgent.runtime_provider === 'iframe' || page.currentAgent.conversation_mode === 'embedded'" class="relative h-full w-full flex-1">
|
||||
|
||||
<iframe
|
||||
|
||||
:src="embeddedIframeSrc"
|
||||
|
||||
class="h-full w-full border-0 bg-surface"
|
||||
|
||||
allow="microphone; camera; clipboard-read; clipboard-write"
|
||||
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<template v-else>
|
||||
|
||||
<ShippingOrderReviewView v-if="isOrderReviewMode" />
|
||||
|
||||
<div v-else class="flex min-h-0 min-w-0 flex-1">
|
||||
|
||||
<div class="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
|
||||
<TrainingWorkspacePanel
|
||||
|
||||
:current-agent="page.currentAgent"
|
||||
|
||||
:current-user="page.currentUser"
|
||||
|
||||
:agent-guides="page.agentGuides"
|
||||
|
||||
:new-session-tick="page.viewId"
|
||||
|
||||
:training="page.training"
|
||||
|
||||
@open-guide="page.openGuideModal"
|
||||
|
||||
@update:expanded="isTrainingWorkspaceExpanded = $event"
|
||||
|
||||
/>
|
||||
|
||||
<ShippingBatchProgressPanel
|
||||
v-if="page.showShippingProgressWorkspace && (page.shippingBatchSummary || page.activeShippingTaskDetail)"
|
||||
:conversation-workspace="page.shippingConversationWorkspace"
|
||||
:active-batch-no="page.activeShippingBatchNo"
|
||||
:batch-summary="page.shippingBatchSummary"
|
||||
:batch-tasks="page.shippingBatchTasks"
|
||||
:active-task-detail="page.activeShippingTaskDetail"
|
||||
:workspace-open="page.shippingWorkspaceOpen"
|
||||
@switch-batch="page.switchShippingBatch"
|
||||
@toggle-workspace="page.shippingWorkspaceOpen = !page.shippingWorkspaceOpen"
|
||||
/>
|
||||
|
||||
|
||||
<ChatMessageList
|
||||
|
||||
v-show="!isTrainingWorkspaceExpanded"
|
||||
|
||||
:messages="page.messages"
|
||||
|
||||
:agent-name="page.currentAgent?.name || 'AI'"
|
||||
|
||||
:suggested-questions-style="page.suggestedQuestionsStyle"
|
||||
|
||||
:styled-sections="page.styledSuggestedQuestionSections"
|
||||
|
||||
:suggested-questions="page.agentSuggestedQuestions"
|
||||
|
||||
:show-thinking-bubble="page.shouldShowThinkingBubble"
|
||||
|
||||
:is-thinking="page.isThinking"
|
||||
|
||||
:show-chat-rating="page.showChatRating"
|
||||
|
||||
:copied-index="page.copiedIndex"
|
||||
|
||||
:is-shipping-notice-agent="page.isShippingNoticeAgent"
|
||||
|
||||
:handlers="page.messageBubbleHandlers"
|
||||
|
||||
:leave-handlers="page.leaveMessageHandlers"
|
||||
|
||||
:shipping-handlers="page.shippingMessageHandlers"
|
||||
|
||||
:training-handlers="page.trainingHandlers"
|
||||
|
||||
:should-render-message="page.shouldRenderMessage"
|
||||
|
||||
:should-show-tool-run-progress-after-message="page.shouldShowToolRunProgressAfterMessage"
|
||||
|
||||
:get-message-run-progress="page.getMessageRunProgress"
|
||||
|
||||
:get-message-run-progress-error="page.getMessageRunProgressError"
|
||||
|
||||
:is-message-run-progress-loading="page.isMessageRunProgressLoading"
|
||||
|
||||
:tool-run-progress="page.toolRunProgress"
|
||||
|
||||
:tool-run-progress-title="page.toolRunProgressTitle"
|
||||
|
||||
:show-scroll-to-bottom="page.showScrollToBottom"
|
||||
|
||||
:hide-welcome-panel="hideWelcomePanel"
|
||||
|
||||
:hide-welcome-title="hideWelcomeTitle"
|
||||
|
||||
:pin-messages-to-bottom="!isTrainingAgentPage"
|
||||
|
||||
:scroll-container-holder="page.scrollContainerHolder"
|
||||
|
||||
@copy="page.copyToClipboard($event.message, $event.index)"
|
||||
|
||||
@edit="page.input = $event"
|
||||
|
||||
@resend="page.handleSend($event)"
|
||||
|
||||
@regenerate="page.regenerate"
|
||||
|
||||
@open-feedback="page.handleOpenFeedback($event)"
|
||||
|
||||
@select-question="page.handleSend"
|
||||
|
||||
@scroll-to-bottom="page.scrollToBottom"
|
||||
|
||||
@maintenance-edit-record="openMaintenanceRecordEdit"
|
||||
|
||||
@maintenance-view-record-history="openMaintenanceRecordHistory"
|
||||
|
||||
@maintenance-create-record-for-device="openMaintenanceRecordCreate"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
|
||||
<ChatInputBar
|
||||
|
||||
v-show="!isTrainingWorkspaceExpanded"
|
||||
|
||||
:key="`${page.currentAgentId}-${page.conversationId || 'draft'}-${page.messages.length}`"
|
||||
|
||||
v-model="page.input"
|
||||
|
||||
v-model:selected-kb="page.selectedKb"
|
||||
|
||||
:attachments="page.attachments"
|
||||
|
||||
:attachment-policy="page.attachmentPolicy"
|
||||
|
||||
:available-kb-options="page.availableKbOptions"
|
||||
|
||||
:kb-dropdown-disabled="page.kbDropdownDisabled"
|
||||
|
||||
:is-thinking="page.isThinking"
|
||||
|
||||
:is-voice-recording="page.isVoiceRecording"
|
||||
|
||||
:is-voice-transcribing="page.isVoiceTranscribing"
|
||||
|
||||
:is-uploading-attachments="page.isUploadingAttachments"
|
||||
|
||||
:can-send-message="page.canSendMessage"
|
||||
|
||||
:is-shipping-notice-agent="page.isShippingNoticeAgent"
|
||||
|
||||
:is-maintenance-agent="isMaintenanceAgentPage"
|
||||
|
||||
:can-manage-maintenance="canManageMaintenance"
|
||||
|
||||
:can-force-create-shipping-duplicate="page.canForceCreateShippingDuplicate"
|
||||
|
||||
:shipping-suggested-prompt="page.shippingSuggestedPrompt"
|
||||
:shipping-focus-task-no="page.focusedShippingTaskNo"
|
||||
:shipping-focus-reason="page.shippingFocusReason"
|
||||
|
||||
:shipping-picker-ref-holder="page.shippingPickerRefHolder"
|
||||
|
||||
:shipping-notice-picker-ref-holder="page.shippingNoticePickerRefHolder"
|
||||
|
||||
:get-kb-label="page.getKbLabel"
|
||||
|
||||
@send="page.handleSend()"
|
||||
|
||||
@stop="page.stopActiveGeneration()"
|
||||
|
||||
@voice-click="page.handleVoiceFeatureClick"
|
||||
|
||||
@remove-attachment="page.removeAttachment"
|
||||
|
||||
@retry-attachment="page.retryAttachment"
|
||||
|
||||
@retry-shipping-notice-attachment="page.retryShippingNoticeAttachment"
|
||||
|
||||
@resolve-shipping-notice-duplicate="page.openShippingDuplicateDialog"
|
||||
|
||||
@select-shipping-candidate="page.setShippingCandidateSelected"
|
||||
|
||||
@resolve-shipping-candidate-duplicate="page.resolveShippingCandidateDuplicate"
|
||||
|
||||
@local-files-selected="page.handleLocalFilesSelected"
|
||||
|
||||
@add-remote-url="page.addRemoteUrlAttachment"
|
||||
|
||||
@shipping-inventory-selected="page.handleShippingInventorySelected"
|
||||
|
||||
@use-shipping-suggested-prompt="page.useShippingSuggestedPrompt"
|
||||
|
||||
@maintenance-ledger-config="maintenancePanel = 'ledger'"
|
||||
|
||||
@maintenance-create-record="openBlankMaintenanceRecordCreate"
|
||||
@clear-shipping-focus="page.clearShippingFocus"
|
||||
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<ShippingSessionSummaryPanel
|
||||
|
||||
v-if="showShippingSessionSummary"
|
||||
|
||||
:conversation-workspace="page.shippingConversationWorkspace"
|
||||
|
||||
:active-batch-no="page.activeShippingBatchNo"
|
||||
|
||||
:batch-summary="page.shippingBatchSummary"
|
||||
|
||||
:batch-tasks="page.shippingBatchTasks"
|
||||
|
||||
:active-task-detail="page.activeShippingTaskDetail"
|
||||
|
||||
:extraction-run-no="activeExtractionRunNo"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
|
||||
<aside
|
||||
|
||||
v-if="isMaintenanceAgentPage && canManageMaintenance && maintenancePanel"
|
||||
|
||||
class="relative flex flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.06)]"
|
||||
|
||||
:class="[
|
||||
|
||||
isMaintenancePanelFullscreen ? 'absolute inset-y-0 right-0 z-30' : '',
|
||||
|
||||
isMaintenancePanelResizing ? 'select-none' : '',
|
||||
|
||||
]"
|
||||
|
||||
:style="maintenancePanelStyle"
|
||||
|
||||
>
|
||||
|
||||
<button
|
||||
|
||||
v-if="!isMaintenancePanelFullscreen"
|
||||
|
||||
type="button"
|
||||
|
||||
class="absolute inset-y-0 left-[-4px] z-10 w-2 cursor-col-resize bg-transparent hover:bg-brand-200/60"
|
||||
|
||||
:title="$t('maintenance.panel.resizeTitle')"
|
||||
|
||||
@mousedown="startMaintenancePanelResize"
|
||||
|
||||
/>
|
||||
|
||||
<div class="flex items-start justify-between gap-3 border-b border-default px-4 py-3">
|
||||
|
||||
<div>
|
||||
|
||||
<h2 class="text-base font-semibold text-primary">
|
||||
|
||||
{{ maintenancePanel === 'ledger' ? $t('maintenance.panel.ledgerTitle') : $t('maintenance.panel.recordTitle') }}
|
||||
|
||||
</h2>
|
||||
|
||||
<p class="mt-1 text-xs text-secondary">
|
||||
|
||||
{{ maintenancePanel === 'ledger' ? $t('maintenance.panel.ledgerSubtitle') : $t('maintenance.panel.recordSubtitle') }}
|
||||
|
||||
</p>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
|
||||
<button
|
||||
|
||||
type="button"
|
||||
|
||||
class="inline-flex h-8 w-8 items-center justify-center rounded-lg border border-default text-secondary hover:bg-surface-soft"
|
||||
|
||||
:title="isMaintenancePanelFullscreen ? $t('maintenance.panel.exitFullscreen') : $t('maintenance.panel.fullscreen')"
|
||||
|
||||
@click="isMaintenancePanelFullscreen = !isMaintenancePanelFullscreen"
|
||||
|
||||
>
|
||||
|
||||
<Minimize2 v-if="isMaintenancePanelFullscreen" class="h-4 w-4" />
|
||||
|
||||
<Maximize2 v-else class="h-4 w-4" />
|
||||
|
||||
</button>
|
||||
|
||||
<button
|
||||
|
||||
type="button"
|
||||
|
||||
class="inline-flex h-8 w-8 items-center justify-center rounded-lg border border-default text-sm text-secondary hover:bg-surface-soft"
|
||||
|
||||
:title="$t('maintenance.panel.close')"
|
||||
|
||||
@click="maintenancePanel = null"
|
||||
|
||||
>
|
||||
|
||||
×
|
||||
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="min-h-0 flex-1 overflow-auto p-4">
|
||||
|
||||
<LedgerConfigPanel v-if="maintenancePanel === 'ledger'" />
|
||||
|
||||
<MaintenanceRecordManagerPanel
|
||||
|
||||
v-else
|
||||
|
||||
:edit-record="maintenanceEditRecord"
|
||||
|
||||
:command="maintenanceRecordPanelCommand"
|
||||
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
</aside>
|
||||
|
||||
|
||||
|
||||
<ChatBrowserPanel
|
||||
|
||||
v-model:open="page.browserPanelOpen"
|
||||
|
||||
v-model:draft-url="page.browserDraftUrl"
|
||||
|
||||
:current-url="page.browserCurrentUrl"
|
||||
|
||||
:frame-key="page.browserFrameKey"
|
||||
|
||||
:panel-style="page.browserPanelStyle"
|
||||
|
||||
:is-resizing="page.isBrowserResizing"
|
||||
|
||||
@load="page.browser.loadPage"
|
||||
|
||||
@refresh="page.browser.refreshPage"
|
||||
|
||||
@open-new-tab="page.browser.openInNewTab"
|
||||
|
||||
@url-enter="page.browser.onUrlEnter"
|
||||
|
||||
@start-resize="page.browser.startResize"
|
||||
|
||||
@close="page.browser.close"
|
||||
|
||||
/>
|
||||
|
||||
<ShippingBatchWorkspaceDrawer
|
||||
v-if="page.showShippingProgressWorkspace && (page.shippingConversationWorkspace || page.shippingBatchSummary)"
|
||||
v-model:open="page.shippingWorkspaceOpen"
|
||||
:conversation-workspace="page.shippingConversationWorkspace"
|
||||
:active-batch-no="page.activeShippingBatchNo"
|
||||
:focused-task-no="page.focusedShippingTaskNo"
|
||||
:batch-summary="page.shippingBatchSummary"
|
||||
:batch-tasks="page.shippingBatchTasks"
|
||||
:active-task-detail="page.activeShippingTaskDetail"
|
||||
:retrying-pending="page.retryingShippingPendingTasks"
|
||||
:action-busy="page.shippingActionBusy"
|
||||
@switch-batch="page.switchShippingBatch"
|
||||
@focus-task="page.switchShippingFocusTask"
|
||||
@workspace-action="page.handleShippingWorkspaceAction"
|
||||
@query-shortage="page.queryShippingShortageDetails"
|
||||
@retry-pending="page.openRetryFailedConfirm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
</template>
|
||||
|
||||
</ChatShell>
|
||||
|
||||
</template>
|
||||
|
||||
|
||||
@@ -1,239 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/components/ShippingBatchProgressPanel.vue
|
||||
* 用途:发货通知聊天顶部轻量批次状态条,展示当前批次进度与工作台入口。
|
||||
* 依赖:shipping.api.types、vue-i18n、批次 retry API。
|
||||
* 逻辑:生成式执行摘要由聊天消息流承载;本组件只提供固定状态 chrome 和明确范围的批次操作。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { AlertTriangle, List, RefreshCw } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { retryWorkspaceShippingBatchPending } from '@/features/chat/api/shipping.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { resolveShippingWorkflowSteps } from '@/features/chat/shipping';
|
||||
import type {
|
||||
ShippingBatchSummary,
|
||||
ShippingConversationWorkspace,
|
||||
ShippingTaskDetail,
|
||||
ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
|
||||
const props = defineProps<{
|
||||
conversationWorkspace: ShippingConversationWorkspace | null;
|
||||
activeBatchNo: string;
|
||||
batchSummary: ShippingBatchSummary | null;
|
||||
batchTasks: ShippingTaskSummary[];
|
||||
activeTaskDetail: ShippingTaskDetail | null;
|
||||
workspaceOpen: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'switch-batch': [batchNo: string];
|
||||
'toggle-workspace': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const retryingPending = ref(false);
|
||||
|
||||
const COMPLETED_PROCESS_STATUSES = new Set(['uploaded', 'completed', 'closed']);
|
||||
const FAILED_PROCESS_STATUSES = new Set(['rejected', 'upload_failed']);
|
||||
const workspaceBatches = computed(() => props.conversationWorkspace?.batches || []);
|
||||
const activeBatchNo = computed(() =>
|
||||
String(props.activeBatchNo || props.batchSummary?.batch_no || workspaceBatches.value[0]?.batch_no || '').trim(),
|
||||
);
|
||||
const focusedTaskNo = computed(() =>
|
||||
String(
|
||||
props.activeTaskDetail?.task_no
|
||||
|| props.batchSummary?.current_focus_task_no
|
||||
|| props.batchSummary?.process_summary?.current_task_no
|
||||
|| '',
|
||||
).trim(),
|
||||
);
|
||||
|
||||
const processSummary = computed(() => {
|
||||
const summary = props.batchSummary?.process_summary || null;
|
||||
const total = Number(summary?.total || props.batchSummary?.file_count || props.batchTasks.length || 0);
|
||||
const completed = Number(
|
||||
summary?.completed
|
||||
|| props.batchTasks.filter((task) => COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim())).length
|
||||
|| 0,
|
||||
);
|
||||
const runningFallback = props.batchTasks.some(
|
||||
(task) => !COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim()),
|
||||
) ? 1 : 0;
|
||||
const running = Number(summary?.running || runningFallback || 0);
|
||||
const taskAbnormal = props.batchTasks.filter((task) => {
|
||||
const status = String(task.process_status || '').trim();
|
||||
return FAILED_PROCESS_STATUSES.has(status)
|
||||
|| task.upload_status === 'failed'
|
||||
|| Boolean(task.review_status || task.pending_human_reason);
|
||||
}).length;
|
||||
const summaryAbnormal = Number(summary?.failed || 0) + Number((summary as { needs_human?: number })?.needs_human || 0);
|
||||
const abnormal = Math.max(taskAbnormal, summaryAbnormal);
|
||||
const pending = Math.max(0, Number(summary?.pending ?? (total - completed - running - abnormal)));
|
||||
return { total, completed, running, pending, abnormal };
|
||||
});
|
||||
|
||||
const abnormalCount = computed(() => processSummary.value.abnormal);
|
||||
|
||||
const progressPercent = computed(() =>
|
||||
processSummary.value.total
|
||||
? Math.round((processSummary.value.completed / processSummary.value.total) * 100)
|
||||
: 0,
|
||||
);
|
||||
|
||||
const executionStateMeta = computed(() => {
|
||||
if (abnormalCount.value > 0) {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.needsIntervention'),
|
||||
className: 'border-amber-100 bg-amber-50 text-amber-700',
|
||||
};
|
||||
}
|
||||
if (processSummary.value.running > 0 || processSummary.value.pending > 0) {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.runningState'),
|
||||
className: 'border-sky-100 bg-sky-50 text-brand-700',
|
||||
};
|
||||
}
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.completedState'),
|
||||
className: 'border-emerald-100 bg-emerald-50 text-emerald-700',
|
||||
};
|
||||
});
|
||||
|
||||
const activeTaskSteps = computed(() => (
|
||||
resolveShippingWorkflowSteps(props.activeTaskDetail)
|
||||
));
|
||||
const activeStepIndex = computed(() => {
|
||||
const index = activeTaskSteps.value.findIndex((step) => step.status === 'current' || step.status === 'blocked');
|
||||
return index >= 0 ? index : Math.max(0, activeTaskSteps.value.length - 1);
|
||||
});
|
||||
const activeStepLabel = computed(() => {
|
||||
const step = activeTaskSteps.value[activeStepIndex.value];
|
||||
return step ? t('chat.shippingNoticeUi.stepHeadline', {
|
||||
current: activeStepIndex.value + 1,
|
||||
total: activeTaskSteps.value.length,
|
||||
label: step.label.startsWith('chat.') ? t(step.label) : step.label,
|
||||
}) : '--';
|
||||
});
|
||||
|
||||
const blockingMeta = computed(() => {
|
||||
const task = props.activeTaskDetail;
|
||||
if (!task) return null;
|
||||
const reason = String(task.pending_human_reason || '').trim();
|
||||
const reviewStatus = String(task.review_status || '').trim();
|
||||
const processStatus = String(task.process_status || '').trim();
|
||||
if (processStatus === 'upload_failed' || task.upload_status === 'failed') {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.blockedUploadRetryable'),
|
||||
className: 'border-rose-200 bg-rose-50 text-rose-700',
|
||||
};
|
||||
}
|
||||
if (reason === 'shortage' || reason === 'shortage_review' || reviewStatus === 'shortage_review') {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.blockedShortage'),
|
||||
className: 'border-amber-200 bg-amber-50 text-amber-700',
|
||||
};
|
||||
}
|
||||
if (reason === 'low_confidence' || reviewStatus === 'parse_review') {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.blockedParseReview'),
|
||||
className: 'border-amber-200 bg-amber-50 text-amber-700',
|
||||
};
|
||||
}
|
||||
if (reason || reviewStatus) {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.blockedWaitingHuman'),
|
||||
className: 'border-amber-200 bg-amber-50 text-amber-700',
|
||||
};
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const handleRetryPending = async () => {
|
||||
const batchNo = String(props.batchSummary?.batch_no || '').trim();
|
||||
if (!batchNo || retryingPending.value) return;
|
||||
retryingPending.value = true;
|
||||
try {
|
||||
const result = await retryWorkspaceShippingBatchPending(batchNo);
|
||||
msg.success(result.message || t('chat.shippingNoticeUi.retryPendingDone'));
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('chat.shippingNoticeUi.retryFailed'));
|
||||
} finally {
|
||||
retryingPending.value = false;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="w-full px-3 pt-3 md:px-8 md:pr-10">
|
||||
<div
|
||||
class="mx-auto w-full max-w-4xl rounded-2xl border border-default bg-gradient-to-r from-sky-50 via-white to-emerald-50 px-6 py-4 shadow-sm"
|
||||
>
|
||||
<div class="flex flex-wrap items-start justify-between gap-3">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex flex-wrap items-center gap-2 text-xs text-slate-500">
|
||||
<span class="font-mono font-semibold text-brand-700">{{ activeBatchNo || '--' }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.fileCount') }} {{ processSummary.total }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.completedCount') }} {{ processSummary.completed }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.runningCount') }} {{ processSummary.running }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.pendingCount') }} {{ processSummary.pending }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.needsIntervention') }} {{ abnormalCount }}</span>
|
||||
<span
|
||||
class="rounded-full border px-2 py-0.5 text-[11px] font-semibold"
|
||||
:class="executionStateMeta.className"
|
||||
>
|
||||
{{ executionStateMeta.text }}
|
||||
</span>
|
||||
<span
|
||||
v-if="blockingMeta"
|
||||
class="inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-semibold"
|
||||
:class="blockingMeta.className"
|
||||
>
|
||||
<AlertTriangle class="h-3 w-3" />
|
||||
{{ blockingMeta.text }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-secondary">
|
||||
<span>
|
||||
<span class="text-muted">{{ t('chat.shippingNoticeUi.currentFocus') }}</span>
|
||||
<span class="font-mono font-semibold text-primary">{{ focusedTaskNo || '--' }}</span>
|
||||
</span>
|
||||
<span>
|
||||
<span class="text-muted">{{ t('chat.shippingNoticeUi.currentStepLabel') }}:</span>
|
||||
<span class="font-medium text-primary">{{ activeStepLabel }}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-2 h-1.5 max-w-md overflow-hidden rounded-full bg-slate-200">
|
||||
<div
|
||||
class="h-full rounded-full bg-brand-500 transition-all"
|
||||
:style="{ width: `${progressPercent}%` }"
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<button
|
||||
v-if="batchSummary?.batch_no"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-lg border border-default bg-white/80 px-2.5 py-1 text-xs font-medium text-secondary transition hover:border-brand-300 hover:bg-brand-50 hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:disabled="retryingPending"
|
||||
@click="handleRetryPending"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" :class="retryingPending ? 'animate-spin' : ''" />
|
||||
{{ retryingPending ? t('chat.shippingNoticeUi.retrying') : t('chat.shippingNoticeUi.retryPendingTasks') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-lg border border-default bg-white/80 px-2.5 py-1 text-xs font-medium text-secondary transition hover:border-brand-300 hover:bg-brand-50 hover:text-brand-700"
|
||||
@click="emit('toggle-workspace')"
|
||||
>
|
||||
<List class="h-3.5 w-3.5" />
|
||||
{{ workspaceOpen ? t('chat.shippingNoticeUi.collapseTaskList') : t('chat.shippingNoticeUi.expandTaskList') }}
|
||||
<span class="text-brand-600">{{ workspaceOpen ? '▲' : '▼' }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -1,798 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/components/ShippingBatchWorkspaceDrawer.vue
|
||||
* 用途:发货通知 Agent 的右侧批次工作台抽屉,承载多批次切换、任务筛选、步骤诊断与统一动作入口。
|
||||
* 依赖:shippingStepper、shippingMenu、shipping.api.types、vue-i18n、lucide-vue-next。
|
||||
* 逻辑:上游传入会话级 workspace 与当前批次任务;本组件只渲染后端 `ui_state.action_buttons` 和查看类辅助入口。
|
||||
* 解析阶段诊断优先展示 `ui_state.summary.issues` 完整问题列表;「重试所有失败」仅 emit `retry-pending`,由父级打开确认弹窗后再调用 useChatShipping 执行。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { RefreshCw, Target, X } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
resolveShippingWorkflowSteps,
|
||||
type ShippingWorkflowStepItem,
|
||||
} from '@/features/chat/shipping';
|
||||
import { sanitizeShippingRuntimeStatusText } from '@/features/chat/shipping/shippingText';
|
||||
import { reportShippingDebugEvent } from '@/features/chat/shipping/shippingDebugReporter';
|
||||
import {
|
||||
isShippingWorkspaceTerminalTask,
|
||||
resolveShippingWorkspaceActionButtons,
|
||||
} from '@/features/chat/shipping/shippingWorkspaceActions';
|
||||
import { hasShortageLines } from '@/features/chat/shipping/shippingShortageDetails';
|
||||
import type {
|
||||
ShippingBatchSummary,
|
||||
ShippingConversationWorkspace,
|
||||
ShippingChatAction,
|
||||
ShippingTaskDetail,
|
||||
ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import ShippingTaskParsedResultCard from '@/features/chat/components/ShippingTaskParsedResultCard.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
conversationWorkspace: ShippingConversationWorkspace | null;
|
||||
activeBatchNo: string;
|
||||
focusedTaskNo: string;
|
||||
batchSummary: ShippingBatchSummary | null;
|
||||
batchTasks: ShippingTaskSummary[];
|
||||
activeTaskDetail: ShippingTaskDetail | null;
|
||||
retryingPending?: boolean;
|
||||
actionBusy?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean];
|
||||
'switch-batch': [batchNo: string];
|
||||
'focus-task': [taskNo: string];
|
||||
'workspace-action': [taskNo: string, action: ShippingChatAction];
|
||||
'query-shortage': [taskNo: string];
|
||||
'retry-pending': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const activeFilter = ref<'all' | 'abnormal' | 'waitingHuman' | 'resumable' | 'completed'>('all');
|
||||
|
||||
// #region debug-point A:workspace-click
|
||||
const reportRetryRpaDebug = (hypothesisId: string, msg: string, data: Record<string, unknown>) =>
|
||||
reportShippingDebugEvent('ShippingBatchWorkspaceDrawer.vue', hypothesisId, msg, data);
|
||||
// #endregion
|
||||
|
||||
const workspaceBatches = computed(() => props.conversationWorkspace?.batches || []);
|
||||
const activeBatchNo = computed(() =>
|
||||
String(props.activeBatchNo || props.batchSummary?.batch_no || workspaceBatches.value[0]?.batch_no || '').trim(),
|
||||
);
|
||||
|
||||
const isFailedTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
task.upload_status === 'failed' || String(task.process_status || '').trim() === 'upload_failed';
|
||||
|
||||
const isCompletedTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
isShippingWorkspaceTerminalTask(task);
|
||||
|
||||
const isAbnormalTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
!isCompletedTask(task)
|
||||
&& (isFailedTask(task)
|
||||
|| Boolean(task.review_status || task.pending_human_reason)
|
||||
|| String(task.process_status || '').trim() === 'waiting_inventory');
|
||||
|
||||
const isWaitingHumanTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
!isCompletedTask(task) && !isFailedTask(task) && Boolean(task.review_status || task.pending_human_reason);
|
||||
|
||||
const isResumableTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
!isCompletedTask(task) && !isWaitingHumanTask(task) && (
|
||||
isFailedTask(task)
|
||||
|| ['created', 'parsed', 'inventory_ready', 'matched', 'waiting_upload'].includes(String(task.process_status || '').trim())
|
||||
);
|
||||
|
||||
const resolveWorkspaceActionButtons = (task: ShippingTaskSummary | ShippingTaskDetail): ShippingChatAction[] =>
|
||||
resolveShippingWorkspaceActionButtons(task);
|
||||
|
||||
const rpaRuntimeMode = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
String(task.rpa_runtime?.mode || '').trim().toLowerCase();
|
||||
|
||||
const rpaRuntimeLabel = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
const mode = rpaRuntimeMode(task);
|
||||
if (mode === 'mock') return t('chat.shippingNoticeUi.rpaModeMock');
|
||||
if (mode === 'browser') return t('chat.shippingNoticeUi.rpaModeBrowser');
|
||||
return String(task.rpa_runtime?.label || '').trim() || t('chat.shippingNoticeUi.rpaModeUnknown');
|
||||
};
|
||||
|
||||
const rpaRuntimeBadgeClass = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
rpaRuntimeMode(task) === 'mock'
|
||||
? 'border-amber-200 bg-amber-50 text-amber-700'
|
||||
: 'border-emerald-200 bg-emerald-50 text-emerald-700';
|
||||
|
||||
/**
|
||||
* 渲染工作台任务卡中的辅助动作按钮样式。
|
||||
* 核心逻辑:把“聚焦当前任务 / 查询缺口明细”降级成轻量辅助入口,避免与后端主业务动作抢视觉权重。
|
||||
* @param kind - 当前辅助动作的视觉类型
|
||||
* @returns 对应的 Tailwind class 字符串
|
||||
*/
|
||||
const resolveWorkspaceAssistButtonClass = (kind: 'focus' | 'shortage') => {
|
||||
if (kind === 'shortage') {
|
||||
return 'inline-flex min-h-[32px] items-center justify-center gap-1.5 rounded-lg border border-amber-200 bg-amber-50/90 px-2.5 py-1.5 text-xs font-semibold text-amber-700 transition-all hover:border-amber-300 hover:bg-amber-100 disabled:cursor-not-allowed disabled:opacity-60';
|
||||
}
|
||||
return 'inline-flex min-h-[32px] items-center justify-center gap-1.5 rounded-lg border border-slate-200 bg-slate-50/90 px-2.5 py-1.5 text-xs font-semibold text-slate-700 transition-all hover:border-brand-200 hover:bg-white hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60';
|
||||
};
|
||||
|
||||
/**
|
||||
* 渲染工作台任务卡中的业务动作按钮样式。
|
||||
* 核心逻辑:主动作在右侧工作台里使用更强的卡片式按钮承载,优先突出 primary,secondary/danger 维持次级密度。
|
||||
* @param action - 后端返回的结构化动作按钮
|
||||
* @param total - 当前任务业务动作总数,用于控制按钮跨列布局
|
||||
* @returns 对应的 Tailwind class 字符串
|
||||
*/
|
||||
const resolveWorkspaceTaskActionClass = (action: ShippingChatAction, total: number) => {
|
||||
const spanClass = action.variant === 'primary' || total === 1 ? 'col-span-2' : 'col-span-1';
|
||||
if (action.variant === 'primary') {
|
||||
return `${spanClass} inline-flex min-h-[36px] items-center justify-center rounded-lg bg-gradient-to-r from-brand-600 to-sky-500 px-3 py-1.5 text-sm font-semibold text-white shadow-sm transition-all hover:-translate-y-[1px] hover:from-brand-700 hover:to-sky-600 disabled:cursor-not-allowed disabled:opacity-60`;
|
||||
}
|
||||
if (action.variant === 'danger') {
|
||||
return `${spanClass} inline-flex min-h-[36px] items-center justify-center rounded-lg border border-rose-200 bg-rose-50 px-3 py-1.5 text-sm font-semibold text-rose-700 transition-all hover:border-rose-300 hover:bg-rose-100 disabled:cursor-not-allowed disabled:opacity-60`;
|
||||
}
|
||||
return `${spanClass} inline-flex min-h-[36px] items-center justify-center rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-sm font-semibold text-slate-700 shadow-sm transition-all hover:border-brand-200 hover:bg-brand-50 hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60`;
|
||||
};
|
||||
|
||||
// #region debug-point A:workspace-action
|
||||
const emitWorkspaceAction = (
|
||||
task: ShippingTaskSummary | ShippingTaskDetail,
|
||||
action: ShippingChatAction,
|
||||
) => {
|
||||
void reportRetryRpaDebug('A', 'workspace action clicked', {
|
||||
actionId: String(action.id || ''),
|
||||
actionBusy: Boolean(props.actionBusy),
|
||||
taskNo: String(task.task_no || '').trim().toUpperCase(),
|
||||
processStatus: String(task.process_status || ''),
|
||||
pendingHumanReason: String(task.pending_human_reason || ''),
|
||||
focusedTaskNo: String(props.focusedTaskNo || props.activeTaskDetail?.task_no || '').trim().toUpperCase(),
|
||||
});
|
||||
emit('workspace-action', task.task_no, action);
|
||||
};
|
||||
// #endregion
|
||||
|
||||
// #region debug-point A:workspace-busy-state
|
||||
watch(
|
||||
() => [Boolean(props.actionBusy), String(props.focusedTaskNo || ''), String(props.activeTaskDetail?.task_no || '')].join('|'),
|
||||
() => {
|
||||
void reportRetryRpaDebug('A', 'workspace busy state snapshot', {
|
||||
actionBusy: Boolean(props.actionBusy),
|
||||
focusedTaskNo: String(props.focusedTaskNo || '').trim().toUpperCase(),
|
||||
activeDetailTaskNo: String(props.activeTaskDetail?.task_no || '').trim().toUpperCase(),
|
||||
activeDetailStatus: String(props.activeTaskDetail?.process_status || ''),
|
||||
activeDetailPendingReason: String(props.activeTaskDetail?.pending_human_reason || ''),
|
||||
open: props.open,
|
||||
});
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
// #endregion
|
||||
|
||||
const batchAbnormalCount = (batch: ShippingBatchSummary) => {
|
||||
const summary = batch.process_summary || {};
|
||||
return Number(summary.failed || 0) + Number((summary as { needs_human?: number }).needs_human || 0);
|
||||
};
|
||||
|
||||
const batchCompletedCount = (batch: ShippingBatchSummary) =>
|
||||
Number(batch.process_summary?.completed || 0);
|
||||
|
||||
const batchTotalCount = (batch: ShippingBatchSummary) =>
|
||||
Number(batch.process_summary?.total || batch.file_count || 0);
|
||||
|
||||
const taskCounts = computed(() => {
|
||||
const tasks = props.batchTasks || [];
|
||||
const completed = tasks.filter(isCompletedTask).length;
|
||||
const abnormal = tasks.filter(isAbnormalTask).length;
|
||||
const waitingHuman = tasks.filter(isWaitingHumanTask).length;
|
||||
const resumable = tasks.filter(isResumableTask).length;
|
||||
return {
|
||||
total: tasks.length,
|
||||
abnormal,
|
||||
waitingHuman,
|
||||
resumable,
|
||||
completed,
|
||||
};
|
||||
});
|
||||
|
||||
const filteredTasks = computed(() => {
|
||||
const tasks = props.batchTasks || [];
|
||||
if (activeFilter.value === 'abnormal') return tasks.filter(isAbnormalTask);
|
||||
if (activeFilter.value === 'waitingHuman') return tasks.filter(isWaitingHumanTask);
|
||||
if (activeFilter.value === 'resumable') return tasks.filter(isResumableTask);
|
||||
if (activeFilter.value === 'completed') return tasks.filter(isCompletedTask);
|
||||
return tasks;
|
||||
});
|
||||
|
||||
const isCurrentTask = (taskNo?: string | null) =>
|
||||
String(taskNo || '').trim().toUpperCase() === String(props.focusedTaskNo || props.activeTaskDetail?.task_no || '').trim().toUpperCase();
|
||||
|
||||
const resolveTaskStateMeta = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
if (isCompletedTask(task)) {
|
||||
return { text: t('chat.shippingNoticeUi.completedState'), className: 'border-emerald-100 bg-emerald-50 text-emerald-700' };
|
||||
}
|
||||
if (isFailedTask(task)) {
|
||||
return { text: t('chat.shippingNoticeUi.status.uploadFailed'), className: 'border-rose-100 bg-rose-50 text-rose-700' };
|
||||
}
|
||||
if (isAbnormalTask(task)) {
|
||||
return { text: t('chat.shippingNoticeUi.pendingState'), className: 'border-amber-100 bg-amber-50 text-amber-700' };
|
||||
}
|
||||
return { text: t('chat.shippingNoticeUi.runningState'), className: 'border-sky-100 bg-sky-50 text-brand-700' };
|
||||
};
|
||||
|
||||
const taskWorkflowSteps = (task: ShippingTaskSummary | ShippingTaskDetail) => (
|
||||
resolveShippingWorkflowSteps(task)
|
||||
);
|
||||
|
||||
const taskStepNumber = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
resolveActiveStep(taskWorkflowSteps(task)) + 1;
|
||||
|
||||
const taskStepHeadline = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
const steps = taskWorkflowSteps(task);
|
||||
const index = resolveActiveStep(steps);
|
||||
const step = steps[index];
|
||||
return step ? t('chat.shippingNoticeUi.stepHeadline', {
|
||||
current: index + 1,
|
||||
total: steps.length,
|
||||
label: step.label.startsWith('chat.') ? t(step.label) : step.label,
|
||||
}) : t('chat.shippingNoticeUi.stepFraction', { current: index + 1, total: steps.length });
|
||||
};
|
||||
|
||||
const currentStepProgress = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
task.step_payload?.current_step_progress || null;
|
||||
|
||||
/**
|
||||
* 规范化工作台中的运行态诊断文案。
|
||||
* 核心逻辑:右侧工作台属于业务操作面,不展示“第几次重试”这类过程计数,只保留状态与建议。
|
||||
* @param text - 后端返回的 summary / progress / error 文本
|
||||
* @returns 面向业务用户的净化后文案
|
||||
*/
|
||||
const sanitizeDiagnosisCopy = (text: string | null | undefined) =>
|
||||
sanitizeShippingRuntimeStatusText(String(text || '').trim());
|
||||
|
||||
/**
|
||||
* 读取任务诊断卡要展示的全部问题列表。
|
||||
* 核心逻辑:优先消费后端 `ui_state.summary.issues`(解析阶段已汇总库存源+warnings);
|
||||
* 若缺失则回退到单一 error_message,保证旧数据仍有可读文案。
|
||||
*/
|
||||
const resolveTaskDiagnosisIssues = (task: ShippingTaskSummary | ShippingTaskDetail): string[] => {
|
||||
const uiIssues = task.ui_state?.summary?.issues;
|
||||
if (Array.isArray(uiIssues) && uiIssues.length) {
|
||||
return uiIssues
|
||||
.map((item) => sanitizeDiagnosisCopy(item))
|
||||
.filter(Boolean);
|
||||
}
|
||||
const fallback = sanitizeDiagnosisCopy(task.ui_state?.summary?.error_message || task.error_message);
|
||||
return fallback ? [fallback] : [];
|
||||
};
|
||||
|
||||
/**
|
||||
* 解析右侧工作台诊断标题/建议/问题列表。
|
||||
* 核心逻辑:解析阶段若 issues 多于 1 条,使用「发现问题」标题并列出全部条目,避免只显示库存源一条。
|
||||
*/
|
||||
const resolveTaskDiagnosis = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
const uiSummary = task.ui_state?.summary;
|
||||
const issues = resolveTaskDiagnosisIssues(task);
|
||||
if (uiSummary?.title || uiSummary?.message || uiSummary?.error_message || issues.length) {
|
||||
const multiIssue = issues.length > 1;
|
||||
return {
|
||||
title: multiIssue
|
||||
? t('chat.shippingNoticeUi.diagnosisIssuesTitle', { count: issues.length })
|
||||
: (
|
||||
sanitizeDiagnosisCopy(issues[0] || uiSummary?.error_message || uiSummary?.title)
|
||||
|| t('chat.shippingNoticeUi.diagnosisStepWaitingTitle', { step: taskStepNumber(task) })
|
||||
),
|
||||
advice: multiIssue
|
||||
? t('chat.shippingNoticeUi.diagnosisIssuesAdvice')
|
||||
: (sanitizeDiagnosisCopy(uiSummary?.message) || t('chat.shippingNoticeUi.diagnosisStepWaitingAdvice')),
|
||||
issues: multiIssue ? issues : [],
|
||||
};
|
||||
}
|
||||
const reason = String(task.pending_human_reason || '').trim();
|
||||
const reviewStatus = String(task.review_status || '').trim();
|
||||
const processStatus = String(task.process_status || '').trim();
|
||||
const explicitError = String(task.error_message || '').trim();
|
||||
const progress = currentStepProgress(task);
|
||||
const progressMessage = String(progress?.message || '').trim();
|
||||
const progressDetail = String(progress?.detail || '').trim();
|
||||
const step = taskStepNumber(task);
|
||||
|
||||
if (isCompletedTask(task)) {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisCompletedTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisCompletedAdvice'),
|
||||
};
|
||||
}
|
||||
if (progressMessage && reason === 'rpa_pending') {
|
||||
return {
|
||||
title: sanitizeDiagnosisCopy(progressMessage),
|
||||
advice: sanitizeDiagnosisCopy(progressDetail) || t('chat.shippingNoticeUi.diagnosisInventoryRpaAdvice'),
|
||||
};
|
||||
}
|
||||
if (explicitError) {
|
||||
return {
|
||||
title: sanitizeDiagnosisCopy(explicitError),
|
||||
advice: sanitizeDiagnosisCopy(progressDetail) || t('chat.shippingNoticeUi.diagnosisAdviceRetryOrFocus'),
|
||||
};
|
||||
}
|
||||
if (progressMessage && (isAbnormalTask(task) || progress?.status === 'needs_human')) {
|
||||
return {
|
||||
title: sanitizeDiagnosisCopy(progressMessage),
|
||||
advice: sanitizeDiagnosisCopy(progressDetail) || t('chat.shippingNoticeUi.diagnosisStepWaitingAdvice'),
|
||||
};
|
||||
}
|
||||
if (isFailedTask(task) || reason === 'upload_rpa_failed') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisUploadFailedTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisUploadFailedAdvice'),
|
||||
};
|
||||
}
|
||||
if (reason === 'shortage' || reason === 'shortage_review' || reviewStatus === 'shortage_review') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisShortageTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisShortageAdvice'),
|
||||
};
|
||||
}
|
||||
if (reason === 'rpa_exhausted' || reason === 'rpa_pending' || reason === 'inv_unavail') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisInventoryRpaTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisInventoryRpaAdvice'),
|
||||
};
|
||||
}
|
||||
if (reason === 'low_confidence' || reviewStatus === 'parse_review') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisParseReviewTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisParseReviewAdvice'),
|
||||
};
|
||||
}
|
||||
if (reason === 'rsv_required' || reviewStatus === 'rsv_required') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisReservationRequiredTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisReservationRequiredAdvice'),
|
||||
};
|
||||
}
|
||||
if (reason === 'inventory_source_unresolved') {
|
||||
const resolution = (task as ShippingTaskDetail).inventory_source_resolution;
|
||||
const status = resolution && typeof resolution === 'object'
|
||||
? String((resolution as { status?: unknown }).status || '').trim()
|
||||
: '';
|
||||
const isAmbiguous = status === 'ambiguous';
|
||||
return {
|
||||
title: t(isAmbiguous
|
||||
? 'chat.shippingNoticeUi.diagnosisInventorySourceAmbiguousTitle'
|
||||
: 'chat.shippingNoticeUi.diagnosisInventorySourceTitle'),
|
||||
advice: t(isAmbiguous
|
||||
? 'chat.shippingNoticeUi.diagnosisInventorySourceAmbiguousAdvice'
|
||||
: 'chat.shippingNoticeUi.diagnosisInventorySourceAdvice'),
|
||||
};
|
||||
}
|
||||
if (processStatus === 'waiting_inventory') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisInventoryWaitingTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisInventoryWaitingAdvice'),
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisStepWaitingTitle', { step }),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisStepWaitingAdvice'),
|
||||
};
|
||||
};
|
||||
|
||||
const resolveSuggestedAction = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
const actions = resolveWorkspaceActionButtons(task);
|
||||
if (actions.length) {
|
||||
return actions.map((action) => action.label).join(' / ');
|
||||
}
|
||||
const reason = String(task.pending_human_reason || '').trim();
|
||||
const reviewStatus = String(task.review_status || '').trim();
|
||||
if (hasShortageLines(task) || reason === 'shortage' || reviewStatus === 'shortage_review') {
|
||||
return t('chat.shippingNoticeUi.suggestShortageActions');
|
||||
}
|
||||
if (reason === 'low_confidence' || reviewStatus === 'parse_review') {
|
||||
return t('chat.shippingNoticeUi.suggestReviewParse');
|
||||
}
|
||||
if (reason === 'inventory_source_unresolved') {
|
||||
return t('chat.shippingNoticeUi.suggestConfirmInventorySource');
|
||||
}
|
||||
if (isFailedTask(task)) {
|
||||
return t('chat.shippingNoticeUi.suggestRetryStep');
|
||||
}
|
||||
if (isCompletedTask(task)) {
|
||||
return t('chat.shippingNoticeUi.suggestViewOnly');
|
||||
}
|
||||
return t('chat.shippingNoticeUi.suggestContinue');
|
||||
};
|
||||
|
||||
const resolveActiveStep = (steps: Array<ShippingWorkflowStepItem | { status: string }>) => {
|
||||
const activeIndex = steps.findIndex((step) => step.status === 'current' || step.status === 'blocked');
|
||||
return activeIndex >= 0 ? activeIndex : Math.max(0, steps.length - 1);
|
||||
};
|
||||
|
||||
const handleSwitchBatch = (batchNo: string) => {
|
||||
if (!batchNo || batchNo === activeBatchNo.value) return;
|
||||
activeFilter.value = 'all';
|
||||
emit('switch-batch', batchNo);
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside
|
||||
v-if="open"
|
||||
class="hidden h-full w-[520px] shrink-0 flex-col border-l border-default bg-surface shadow-[-12px_0_40px_rgba(15,23,42,0.08)] lg:flex"
|
||||
>
|
||||
<header class="flex h-[92px] shrink-0 items-center justify-between border-b border-default px-6">
|
||||
<div>
|
||||
<div class="flex items-center gap-2 text-lg font-bold text-primary">
|
||||
<span class="grid h-5 w-5 grid-cols-2 gap-0.5 text-brand-500">
|
||||
<span class="rounded-sm bg-current"></span>
|
||||
<span class="rounded-sm border border-current"></span>
|
||||
<span class="rounded-sm border border-current"></span>
|
||||
<span class="rounded-sm bg-current"></span>
|
||||
</span>
|
||||
{{ t('chat.shippingNoticeUi.batchWorkspaceTitle') }}
|
||||
</div>
|
||||
<p class="mt-1 text-[11px] text-muted">{{ t('chat.shippingNoticeUi.batchWorkspaceSubtitle') }}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-9 w-9 items-center justify-center rounded-full text-muted transition hover:bg-surface-soft hover:text-primary"
|
||||
@click="emit('update:open', false)"
|
||||
>
|
||||
<X class="h-5 w-5" />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div class="border-b border-default px-6 py-5">
|
||||
<div class="flex gap-3 overflow-x-auto pb-1">
|
||||
<button
|
||||
v-for="batch in workspaceBatches"
|
||||
:key="batch.batch_no"
|
||||
type="button"
|
||||
class="relative w-44 shrink-0 overflow-hidden rounded-xl border p-3 text-left transition-colors"
|
||||
:class="batch.batch_no === activeBatchNo ? 'border-brand-300 bg-surface shadow-sm ring-1 ring-brand-100' : 'border-default bg-transparent hover:bg-surface-soft'"
|
||||
@click="handleSwitchBatch(batch.batch_no)"
|
||||
>
|
||||
<div
|
||||
v-if="batch.batch_no === activeBatchNo"
|
||||
class="absolute left-0 top-0 h-1 w-full bg-brand-500"
|
||||
></div>
|
||||
<div class="mb-1 truncate font-mono text-xs font-bold text-primary">{{ batch.batch_no }}</div>
|
||||
<div class="text-[10px] font-medium text-muted">
|
||||
{{
|
||||
batchAbnormalCount(batch) > 0
|
||||
? t('chat.shippingNoticeUi.batchTabAbnormal', { completed: batchCompletedCount(batch), abnormal: batchAbnormalCount(batch) })
|
||||
: t('chat.shippingNoticeUi.batchTabNormal', { total: batchTotalCount(batch) })
|
||||
}}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 overflow-y-auto px-6 py-6">
|
||||
<section class="rounded-lg border border-default bg-surface p-4 shadow-sm">
|
||||
<h3 class="text-sm font-bold text-primary">{{ t('chat.shippingNoticeUi.taskQueueTitle') }}</h3>
|
||||
<p class="mt-1 text-xs leading-5 text-muted">{{ t('chat.shippingNoticeUi.taskQueueHint') }}</p>
|
||||
<div class="mt-4">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex w-full items-center justify-center gap-2 rounded-lg border border-default bg-white py-2 text-xs font-medium text-secondary transition hover:border-brand-300 hover:bg-brand-50 hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:disabled="retryingPending || actionBusy"
|
||||
@click="emit('retry-pending')"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" :class="retryingPending ? 'animate-spin' : ''" />
|
||||
{{ retryingPending ? t('chat.shippingNoticeUi.retrying') : t('chat.shippingNoticeUi.retryFailedTasks') }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="mt-3 rounded-lg border border-indigo-100 bg-indigo-50 p-3 text-xs leading-5 text-indigo-900/80">
|
||||
{{ t('chat.shippingNoticeUi.batchActionSafetyNotice') }}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="mt-6">
|
||||
<div class="mb-3 flex items-center justify-between gap-3">
|
||||
<h3 class="text-sm font-bold text-primary">
|
||||
{{ t('chat.shippingNoticeUi.taskDetailCount', { count: filteredTasks.length }) }}
|
||||
</h3>
|
||||
<div class="flex flex-wrap rounded-lg bg-slate-100 p-1 text-xs">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
:class="activeFilter === 'all' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
|
||||
@click="activeFilter = 'all'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.filterAll') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
:class="activeFilter === 'abnormal' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
|
||||
@click="activeFilter = 'abnormal'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.filterAbnormal', { count: taskCounts.abnormal }) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
:class="activeFilter === 'waitingHuman' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
|
||||
@click="activeFilter = 'waitingHuman'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.filterWaitingHuman', { count: taskCounts.waitingHuman }) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
:class="activeFilter === 'resumable' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
|
||||
@click="activeFilter = 'resumable'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.filterResumable', { count: taskCounts.resumable }) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
:class="activeFilter === 'completed' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
|
||||
@click="activeFilter = 'completed'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.filterCompleted', { count: taskCounts.completed }) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!filteredTasks.length" class="py-10 text-center text-sm text-muted">
|
||||
{{ t('chat.shippingNoticeUi.emptyFilteredTasks') }}
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-3">
|
||||
<article
|
||||
v-for="task in filteredTasks"
|
||||
:key="task.task_no"
|
||||
class="relative overflow-hidden rounded-lg border bg-white p-3 shadow-sm transition-colors"
|
||||
:class="[
|
||||
isFailedTask(task) ? 'border-rose-100' : isAbnormalTask(task) ? 'border-amber-100' : 'border-default',
|
||||
isCurrentTask(task.task_no) ? 'ring-1 ring-brand-200' : '',
|
||||
]"
|
||||
>
|
||||
<div
|
||||
class="absolute left-0 top-0 h-full w-1"
|
||||
:class="isFailedTask(task) ? 'bg-rose-500' : isAbnormalTask(task) ? 'bg-amber-500' : 'bg-emerald-500'"
|
||||
></div>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="truncate font-mono text-sm font-bold text-primary">
|
||||
{{ task.business_no || task.task_no }}
|
||||
</div>
|
||||
<div v-if="task.business_no" class="mt-0.5 truncate font-mono text-[10px] text-muted">
|
||||
{{ t('chat.shippingNoticeUi.technicalTaskNo', { taskNo: task.task_no }) }}
|
||||
</div>
|
||||
<div class="mt-0.5 truncate text-xs text-muted">
|
||||
{{ task.source_file_name || task.customer_name || t('chat.shippingNoticeUi.currentNotice') }}
|
||||
</div>
|
||||
<div class="mt-1 flex flex-wrap items-center gap-1.5 text-xs font-medium text-secondary">
|
||||
<span>{{ taskStepHeadline(task) }}</span>
|
||||
<span
|
||||
v-if="task.rpa_runtime"
|
||||
class="rounded border px-1.5 py-0.5 text-[10px] font-bold leading-none"
|
||||
:class="rpaRuntimeBadgeClass(task)"
|
||||
>
|
||||
{{ rpaRuntimeLabel(task) }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<span class="rounded border px-2 py-1 text-[10px] font-bold" :class="resolveTaskStateMeta(task).className">
|
||||
{{ resolveTaskStateMeta(task).text }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="my-3">
|
||||
<div class="scheme-stepper">
|
||||
<template v-for="(step, index) in taskWorkflowSteps(task)" :key="step.id">
|
||||
<div
|
||||
class="scheme-step-node"
|
||||
:class="{
|
||||
done: step.status === 'completed',
|
||||
active: step.status === 'current',
|
||||
blocked: step.status === 'blocked',
|
||||
}"
|
||||
>
|
||||
<div class="scheme-step-dot">
|
||||
<span v-if="step.status === 'completed'">✓</span>
|
||||
<X v-else-if="step.status === 'blocked' && isFailedTask(task)" class="h-3 w-3" />
|
||||
<span v-else-if="step.status === 'blocked'">!</span>
|
||||
<span v-else>{{ index + 1 }}</span>
|
||||
</div>
|
||||
<div class="scheme-step-label">{{ step.label.startsWith('chat.') ? t(step.label) : step.label }}</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-for="diagnosis in [resolveTaskDiagnosis(task)]"
|
||||
:key="`${task.task_no}-diagnosis`"
|
||||
class="mb-2 rounded-lg border p-2.5 text-xs font-medium leading-5"
|
||||
:class="isFailedTask(task) ? 'border-rose-100 bg-rose-50 text-rose-700' : isAbnormalTask(task) ? 'border-amber-100 bg-amber-50 text-amber-700' : 'border-emerald-100 bg-emerald-50 text-emerald-700'"
|
||||
>
|
||||
<div class="font-semibold">{{ diagnosis.title }}</div>
|
||||
<ul
|
||||
v-if="(diagnosis.issues || []).length"
|
||||
class="mt-1.5 list-disc space-y-1 pl-4 font-normal text-slate-700"
|
||||
>
|
||||
<li
|
||||
v-for="(issue, issueIndex) in diagnosis.issues"
|
||||
:key="`${task.task_no}-issue-${issueIndex}`"
|
||||
>
|
||||
{{ issue }}
|
||||
</li>
|
||||
</ul>
|
||||
<div class="mt-1 font-normal text-slate-600">{{ diagnosis.advice }}</div>
|
||||
</div>
|
||||
<ShippingTaskParsedResultCard
|
||||
v-if="isCurrentTask(task.task_no) && activeTaskDetail"
|
||||
class="mb-3"
|
||||
:task-no="activeTaskDetail.task_no"
|
||||
:po-number="activeTaskDetail.po_number"
|
||||
:lines="activeTaskDetail.lines"
|
||||
:order-header="activeTaskDetail.order_header"
|
||||
:order-header-fields="activeTaskDetail.order_header_fields"
|
||||
:order-line-fields="activeTaskDetail.order_line_fields"
|
||||
:parse-validation="activeTaskDetail.parse_validation || activeTaskDetail.step_payload?.parse_validation || null"
|
||||
:process-field-gate="activeTaskDetail.process_field_gate || null"
|
||||
:source-candidate="activeTaskDetail.source_candidate || null"
|
||||
:field-conflicts="activeTaskDetail.field_conflicts || []"
|
||||
:order-data-version="activeTaskDetail.order_data_version"
|
||||
:default-expanded="isAbnormalTask(task) || isWaitingHumanTask(task)"
|
||||
compact
|
||||
@refreshed="emit('focus-task', activeTaskDetail.task_no)"
|
||||
/>
|
||||
<div v-if="!resolveWorkspaceActionButtons(task).length" class="mb-3 text-xs leading-5 text-muted">
|
||||
<span class="font-semibold text-secondary">{{ t('chat.shippingNoticeUi.suggestedAction') }}</span>
|
||||
{{ resolveSuggestedAction(task) }}
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-1.5">
|
||||
<button
|
||||
v-if="hasShortageLines(task)"
|
||||
type="button"
|
||||
:class="`${resolveWorkspaceAssistButtonClass('shortage')} col-span-2`"
|
||||
:disabled="actionBusy"
|
||||
@click="emit('query-shortage', task.task_no)"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.queryShortageDetails') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:class="`${resolveWorkspaceAssistButtonClass('focus')} col-span-2`"
|
||||
:disabled="actionBusy"
|
||||
@click="emit('focus-task', task.task_no)"
|
||||
>
|
||||
<Target class="h-3.5 w-3.5" />
|
||||
{{ isCompletedTask(task) ? t('chat.shippingNoticeUi.viewDetail') : t('chat.shippingNoticeUi.switchCurrentTask') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="resolveWorkspaceActionButtons(task).length" class="mt-2 rounded-xl border border-slate-200/80 bg-slate-50/70 p-2">
|
||||
<div class="mb-1.5 px-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-slate-500">
|
||||
{{ t('chat.shippingNoticeActionsHint') }}
|
||||
</div>
|
||||
<div class="grid grid-cols-2 gap-1.5">
|
||||
<button
|
||||
v-for="action in resolveWorkspaceActionButtons(task)"
|
||||
:key="`${task.task_no}-workspace-action-${action.id}-${action.source_code || ''}`"
|
||||
type="button"
|
||||
:class="resolveWorkspaceTaskActionClass(action, resolveWorkspaceActionButtons(task).length)"
|
||||
:disabled="actionBusy"
|
||||
@click="emitWorkspaceAction(task, action)"
|
||||
>
|
||||
{{ action.label }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-[90] bg-slate-900/30 backdrop-blur-sm lg:hidden"
|
||||
@click="emit('update:open', false)"
|
||||
>
|
||||
<aside
|
||||
class="ml-auto flex h-full w-[min(92vw,520px)] flex-col border-l border-default bg-surface shadow-2xl"
|
||||
@click.stop
|
||||
>
|
||||
<header class="flex h-16 shrink-0 items-center justify-between border-b border-default px-4">
|
||||
<div class="font-bold text-primary">{{ t('chat.shippingNoticeUi.batchWorkspaceTitle') }}</div>
|
||||
<button type="button" class="rounded-full p-2 text-muted hover:bg-surface-soft" @click="emit('update:open', false)">
|
||||
<X class="h-5 w-5" />
|
||||
</button>
|
||||
</header>
|
||||
<div class="flex-1 overflow-y-auto p-4 text-sm text-muted">
|
||||
{{ t('chat.shippingNoticeUi.mobileWorkspaceHint') }}
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.scheme-stepper {
|
||||
display: flex;
|
||||
overflow-x: auto;
|
||||
padding-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.scheme-step-node {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
min-width: 52px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.scheme-step-node:not(:last-child)::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
left: calc(50% + 11px);
|
||||
width: calc(100% - 22px);
|
||||
height: 2px;
|
||||
background: #e2e8f0;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.scheme-step-node.done:not(:last-child)::after {
|
||||
background: #0284c7;
|
||||
}
|
||||
|
||||
.scheme-step-node.active:not(:last-child)::after {
|
||||
background: linear-gradient(90deg, #0284c7 50%, #e2e8f0 50%);
|
||||
}
|
||||
|
||||
.scheme-step-dot {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
margin: 0 auto 0.25rem;
|
||||
border: 2px solid #e2e8f0;
|
||||
border-radius: 9999px;
|
||||
background: #fff;
|
||||
color: #64748b;
|
||||
font-size: 0.55rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.scheme-step-node.done .scheme-step-dot {
|
||||
border-color: #0284c7;
|
||||
background: #0284c7;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.scheme-step-node.active .scheme-step-dot {
|
||||
border-color: #0284c7;
|
||||
box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.18);
|
||||
color: #0284c7;
|
||||
}
|
||||
|
||||
.scheme-step-node.blocked .scheme-step-dot {
|
||||
border-color: #f59e0b;
|
||||
background: #fff;
|
||||
color: #f59e0b;
|
||||
box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.18);
|
||||
}
|
||||
|
||||
.scheme-step-node.blocked .scheme-step-label {
|
||||
color: #d97706;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.scheme-step-label {
|
||||
color: #64748b;
|
||||
font-size: 0.58rem;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.scheme-step-node.active .scheme-step-label {
|
||||
color: #0284c7;
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,472 @@
|
||||
/**
|
||||
* features/chat/components/ShippingSessionSummaryPanel.vue
|
||||
* 用途:聊天页右侧「本次处理」唯一状态面——每 PDF 实时状态、异常原因与复核/已有任务深链。
|
||||
* 依赖:vue-i18n、vue-router、lucide、shipping.api(含 extraction documents)。
|
||||
* 逻辑:合并批次 Task 行与抽取 Run 文档行;open_existing 分流为「重复处理中 + 查看已有任务」。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ChevronDown, ChevronRight, ExternalLink } from 'lucide-vue-next';
|
||||
import {
|
||||
getWorkspaceShippingOrderReviewRun,
|
||||
listWorkspaceShippingOrderExtractionDocuments,
|
||||
type ShippingBatchSummary,
|
||||
type ShippingConversationWorkspace,
|
||||
type ShippingTaskDetail,
|
||||
type ShippingTaskSummary,
|
||||
type ShippingTaskUiState,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import type { ShippingOrderExtractionDocumentResult } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
conversationWorkspace: ShippingConversationWorkspace | null;
|
||||
activeBatchNo: string;
|
||||
batchSummary: ShippingBatchSummary | null;
|
||||
batchTasks: ShippingTaskSummary[];
|
||||
activeTaskDetail: ShippingTaskDetail | null;
|
||||
/** 当前会话活跃抽取 Run;有值时右侧轮询每 PDF 状态 */
|
||||
extractionRunNo?: string | null;
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const collapsed = ref(false);
|
||||
const extractionDocs = ref<ShippingOrderExtractionDocumentResult[]>([]);
|
||||
const docsLoading = ref(false);
|
||||
let docsTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const workspaceBatches = computed(() => props.conversationWorkspace?.batches || []);
|
||||
const activeBatchNo = computed(() =>
|
||||
String(props.activeBatchNo || props.batchSummary?.batch_no || workspaceBatches.value[0]?.batch_no || '').trim(),
|
||||
);
|
||||
|
||||
/**
|
||||
* 判断文档是否为「打开已有任务」分流。
|
||||
*/
|
||||
function isOpenExistingDoc(doc: ShippingOrderExtractionDocumentResult): boolean {
|
||||
const taskNo = String(doc.existing_task_no || '').trim();
|
||||
return Boolean(
|
||||
taskNo
|
||||
&& (
|
||||
doc.duplicate_resolution === 'open_existing'
|
||||
|| doc.available_actions.includes('open_existing')
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const processSummary = computed(() => {
|
||||
const summary = props.batchSummary?.process_summary || props.conversationWorkspace?.summary || null;
|
||||
const fromDocs = extractionDocs.value;
|
||||
const total = Number(
|
||||
(summary as { total?: number } | null)?.total
|
||||
|| props.batchSummary?.file_count
|
||||
|| props.batchTasks.length
|
||||
|| fromDocs.length
|
||||
|| 0,
|
||||
);
|
||||
const reviewFromDocs = fromDocs.filter((d) =>
|
||||
!isOpenExistingDoc(d)
|
||||
&& (
|
||||
d.status === 'review_required'
|
||||
|| d.available_actions.some((a) => a === 'review_candidate' || a === 'manual_review')
|
||||
),
|
||||
).length;
|
||||
const openExistingFromDocs = fromDocs.filter((d) => isOpenExistingDoc(d)).length;
|
||||
return {
|
||||
total,
|
||||
completed: Number((summary as { completed?: number } | null)?.completed || 0),
|
||||
running: Number((summary as { running?: number } | null)?.running || 0),
|
||||
failed: Number((summary as { failed?: number } | null)?.failed
|
||||
|| fromDocs.filter((d) => d.status === 'failed').length
|
||||
|| 0),
|
||||
needsHuman: Number(
|
||||
(summary as { needs_human?: number } | null)?.needs_human
|
||||
|| props.conversationWorkspace?.summary?.needs_human
|
||||
|| reviewFromDocs
|
||||
|| 0,
|
||||
),
|
||||
openExisting: openExistingFromDocs,
|
||||
pending: Number((summary as { pending?: number } | null)?.pending || 0),
|
||||
};
|
||||
});
|
||||
|
||||
type SummaryRow = {
|
||||
key: string;
|
||||
fileName: string;
|
||||
taskNo: string;
|
||||
runNo: string;
|
||||
caseNo: string;
|
||||
index: number;
|
||||
total: number;
|
||||
stage: string;
|
||||
message: string;
|
||||
entrySurface: string;
|
||||
/** exception=需人工异常;duplicate=已识别重复关联;none=无标签 */
|
||||
badge: 'exception' | 'duplicate' | 'none';
|
||||
kind: 'task' | 'document';
|
||||
};
|
||||
|
||||
/**
|
||||
* 将 Task ui_state 映射为右侧行。
|
||||
*/
|
||||
function mapTaskRow(task: ShippingTaskSummary, index: number, total: number): SummaryRow {
|
||||
const uiState: ShippingTaskUiState | null | undefined =
|
||||
(props.activeTaskDetail?.task_no === task.task_no ? props.activeTaskDetail.ui_state : null)
|
||||
|| task.ui_state;
|
||||
const summary = uiState?.summary;
|
||||
const kind = String(uiState?.checkpoint_kind || summary?.checkpoint_kind || '');
|
||||
const stage = String(summary?.stage || summary?.title || task.process_status || '').trim();
|
||||
let normalizedStage = stage;
|
||||
if (kind === 'wait_manual_upload') normalizedStage = t('chat.shippingSessionSummary.waitingUpload');
|
||||
else if (kind === 'auto_continue') normalizedStage = t('chat.shippingSessionSummary.autoProcessing');
|
||||
else if (kind === 'must_human') normalizedStage = stage || t('chat.shippingSessionSummary.needsReview');
|
||||
return {
|
||||
key: `task:${task.task_no || index}`,
|
||||
fileName: String(task.source_file_name || '').trim(),
|
||||
taskNo: String(task.task_no || '').trim(),
|
||||
runNo: '',
|
||||
caseNo: '',
|
||||
index: Number(task.batch_index || index + 1),
|
||||
total: Number(task.batch_total || total || 1),
|
||||
stage: normalizedStage,
|
||||
message: String(summary?.message || summary?.current_todo || summary?.pause_reason || '').trim(),
|
||||
entrySurface: String(summary?.entry_surface || 'none').trim(),
|
||||
badge: (
|
||||
summary?.pause_reason
|
||||
|| task.pending_human_reason
|
||||
|| task.error_message
|
||||
|| kind === 'must_human'
|
||||
|| ['rejected', 'upload_failed'].includes(String(task.process_status || ''))
|
||||
) ? 'exception' : 'none',
|
||||
kind: 'task',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 reason_code / review_details 拼成用户可读原因。
|
||||
*/
|
||||
function formatDocumentReason(doc: ShippingOrderExtractionDocumentResult): string {
|
||||
const reasonKey = `chat.shippingOrderExtractionReason.${doc.reason_code || ''}`;
|
||||
const reasonText = doc.reason_code && te(reasonKey)
|
||||
? t(reasonKey)
|
||||
: String(doc.reason_code || doc.activity_event_code || '').trim();
|
||||
const detailParts: string[] = [];
|
||||
for (const detail of (doc.review_details || []).slice(0, 2)) {
|
||||
const fieldCode = String(detail.field_code || '').trim();
|
||||
const fieldKey = `chat.shippingOrderExtractionReviewField.${fieldCode || 'unknown'}`;
|
||||
const fieldLabel = te(fieldKey) ? t(fieldKey) : (fieldCode || t('chat.shippingOrderExtractionReviewField.unknown'));
|
||||
const detailReasonKey = `chat.shippingOrderExtractionReason.${detail.reason_code || ''}`;
|
||||
const detailReason = detail.reason_code && te(detailReasonKey)
|
||||
? t(detailReasonKey)
|
||||
: String(detail.reason_code || '').trim();
|
||||
detailParts.push(
|
||||
t('chat.shippingOrderExtractionReviewDetail', {
|
||||
line: detail.line_number,
|
||||
field: fieldLabel,
|
||||
}) + (detailReason ? `(${detailReason})` : ''),
|
||||
);
|
||||
}
|
||||
if (reasonText && detailParts.length) return `${reasonText};${detailParts.join(';')}`;
|
||||
if (detailParts.length) return detailParts.join(';');
|
||||
return reasonText;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将抽取文档映射为建单前右侧行;open_existing 走任务深链。
|
||||
*/
|
||||
function mapDocumentRow(
|
||||
doc: ShippingOrderExtractionDocumentResult,
|
||||
index: number,
|
||||
total: number,
|
||||
runNo: string,
|
||||
caseNo = '',
|
||||
): SummaryRow {
|
||||
const existingTaskNo = String(doc.existing_task_no || '').trim();
|
||||
const openExisting = isOpenExistingDoc(doc);
|
||||
const needsReview = !openExisting && (
|
||||
doc.status === 'review_required'
|
||||
|| doc.available_actions.some((a) => a === 'review_candidate' || a === 'manual_review')
|
||||
|| Boolean(caseNo)
|
||||
);
|
||||
const failed = doc.status === 'failed';
|
||||
const reasonText = formatDocumentReason(doc);
|
||||
let stage = t('chat.shippingSessionSummary.autoProcessing');
|
||||
let entrySurface = 'none';
|
||||
let message = reasonText;
|
||||
let taskNo = '';
|
||||
if (openExisting && existingTaskNo) {
|
||||
stage = t('chat.shippingSessionSummary.duplicateProcessing');
|
||||
entrySurface = 'task_workbench';
|
||||
taskNo = existingTaskNo;
|
||||
message = reasonText
|
||||
? `${t('chat.shippingSessionSummary.existingTaskNo', { taskNo: existingTaskNo })} · ${reasonText}`
|
||||
: t('chat.shippingSessionSummary.existingTaskNo', { taskNo: existingTaskNo });
|
||||
} else if (needsReview) {
|
||||
stage = t('chat.shippingSessionSummary.needsReview');
|
||||
entrySurface = 'review_workbench';
|
||||
} else if (failed) {
|
||||
stage = t('chat.shippingOrderExtractionDocumentStatus.failed');
|
||||
}
|
||||
return {
|
||||
key: `doc:${doc.unit_id || doc.document_id || index}`,
|
||||
fileName: String(doc.file_name || '').trim(),
|
||||
taskNo,
|
||||
runNo,
|
||||
caseNo,
|
||||
index: index + 1,
|
||||
total,
|
||||
stage,
|
||||
message,
|
||||
entrySurface,
|
||||
badge: openExisting ? 'duplicate' : (needsReview || failed ? 'exception' : 'none'),
|
||||
kind: 'document',
|
||||
};
|
||||
}
|
||||
|
||||
const caseNoByDocumentId = ref<Record<number, string>>({});
|
||||
|
||||
const taskRows = computed((): SummaryRow[] => {
|
||||
const runNo = String(props.extractionRunNo || '').trim();
|
||||
// [STEP 1] 建单前:有抽取 Run 时优先展示每 PDF 文档行(含复核/已有任务深链)。
|
||||
if (runNo && extractionDocs.value.length) {
|
||||
return extractionDocs.value.map((doc, index) =>
|
||||
mapDocumentRow(
|
||||
doc,
|
||||
index,
|
||||
extractionDocs.value.length,
|
||||
runNo,
|
||||
caseNoByDocumentId.value[Number(doc.document_id)] || '',
|
||||
));
|
||||
}
|
||||
// [STEP 2] 建单后:展示 Task 行。
|
||||
const tasks = props.batchTasks.length
|
||||
? props.batchTasks
|
||||
: (workspaceBatches.value.find((b) => b.batch_no === activeBatchNo.value)?.tasks || []);
|
||||
if (tasks.length) {
|
||||
return tasks.map((task, index) => mapTaskRow(task, index, processSummary.value.total || tasks.length));
|
||||
}
|
||||
return [];
|
||||
});
|
||||
|
||||
/**
|
||||
* 拉取当前 Run 文档与复核 Case,保证右侧可深链 case_no/run_no/existing_task_no。
|
||||
*/
|
||||
async function refreshExtractionDocs() {
|
||||
const runNo = String(props.extractionRunNo || '').trim();
|
||||
if (!runNo || docsLoading.value) return;
|
||||
docsLoading.value = true;
|
||||
try {
|
||||
const [docsResponse, reviewResponse] = await Promise.all([
|
||||
listWorkspaceShippingOrderExtractionDocuments(runNo),
|
||||
getWorkspaceShippingOrderReviewRun(runNo).catch(() => null),
|
||||
]);
|
||||
extractionDocs.value = docsResponse.items || [];
|
||||
const mapping: Record<number, string> = {};
|
||||
for (const item of reviewResponse?.items || []) {
|
||||
const docId = Number(item.document_id);
|
||||
const caseNo = String(item.case_no || '').trim();
|
||||
if (docId && caseNo) mapping[docId] = caseNo;
|
||||
}
|
||||
caseNoByDocumentId.value = mapping;
|
||||
} catch {
|
||||
/* 右侧失败不打断聊天 */
|
||||
} finally {
|
||||
docsLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function stopDocsPolling() {
|
||||
if (docsTimer) clearInterval(docsTimer);
|
||||
docsTimer = null;
|
||||
}
|
||||
|
||||
function restartDocsPolling() {
|
||||
stopDocsPolling();
|
||||
const runNo = String(props.extractionRunNo || '').trim();
|
||||
if (!runNo) {
|
||||
extractionDocs.value = [];
|
||||
return;
|
||||
}
|
||||
void refreshExtractionDocs();
|
||||
docsTimer = setInterval(() => void refreshExtractionDocs(), 2000);
|
||||
}
|
||||
|
||||
watch(() => props.extractionRunNo, () => restartDocsPolling(), { immediate: true });
|
||||
onBeforeUnmount(stopDocsPolling);
|
||||
|
||||
/**
|
||||
* 打开任务处理工作台。
|
||||
*/
|
||||
async function openTaskWorkbench(taskNo: string) {
|
||||
const normalized = String(taskNo || '').trim();
|
||||
if (!normalized) return;
|
||||
await router.push({
|
||||
path: '/workspace/shipping-notice/my-tasks',
|
||||
query: { task_no: normalized },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开人工复核(Chat order-review 模式);携带 case_no 精确定位 PDF。
|
||||
*/
|
||||
async function openReview(runNo: string, caseNo = '') {
|
||||
const normalized = String(runNo || '').trim();
|
||||
if (!normalized) return;
|
||||
const query: Record<string, string> = {
|
||||
...Object.fromEntries(
|
||||
Object.entries(route.query).filter(([, v]) => typeof v === 'string') as Array<[string, string]>,
|
||||
),
|
||||
mode: 'order-review',
|
||||
run_no: normalized,
|
||||
};
|
||||
const caseNormalized = String(caseNo || '').trim();
|
||||
if (caseNormalized) query.case_no = caseNormalized;
|
||||
await router.push({
|
||||
name: 'Chat',
|
||||
params: { agentId: String(route.params.agentId || '') },
|
||||
query,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 entry_surface 分发深链;复核必须有 run_no,禁止空 task 跳转。
|
||||
*/
|
||||
async function openEntrySurface(row: SummaryRow) {
|
||||
if (row.entrySurface === 'review_workbench') {
|
||||
const runNo = row.runNo || String(props.extractionRunNo || '');
|
||||
if (!runNo) return;
|
||||
await openReview(runNo, row.caseNo);
|
||||
return;
|
||||
}
|
||||
if (row.entrySurface === 'task_workbench' && row.taskNo) {
|
||||
await openTaskWorkbench(row.taskNo);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside
|
||||
class="flex w-72 shrink-0 flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.04)]"
|
||||
data-testid="shipping-session-summary"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center justify-between gap-2 border-b border-default px-3 py-3 text-left"
|
||||
@click="collapsed = !collapsed"
|
||||
>
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ t('chat.shippingSessionSummary.title') }}
|
||||
</div>
|
||||
<div class="mt-0.5 text-xs text-secondary">
|
||||
{{ t('chat.shippingSessionSummary.pdfCount', { count: processSummary.total || taskRows.length }) }}
|
||||
</div>
|
||||
</div>
|
||||
<ChevronDown v-if="!collapsed" class="h-4 w-4 shrink-0 text-muted" />
|
||||
<ChevronRight v-else class="h-4 w-4 shrink-0 text-muted" />
|
||||
</button>
|
||||
|
||||
<div v-if="!collapsed" class="min-h-0 flex-1 overflow-auto p-3">
|
||||
<div class="mb-3 flex flex-wrap gap-1.5 text-[11px]">
|
||||
<span class="rounded-md bg-emerald-50 px-2 py-0.5 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-200">
|
||||
{{ t('chat.shippingSessionSummary.completed', { count: processSummary.completed }) }}
|
||||
</span>
|
||||
<span class="rounded-md bg-sky-50 px-2 py-0.5 text-sky-700 dark:bg-sky-950/40 dark:text-sky-200">
|
||||
{{ t('chat.shippingSessionSummary.running', { count: processSummary.running }) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="processSummary.needsHuman > 0"
|
||||
class="rounded-md bg-amber-50 px-2 py-0.5 text-amber-700 dark:bg-amber-950/40 dark:text-amber-200"
|
||||
>
|
||||
{{ t('chat.shippingSessionSummary.needsHuman', { count: processSummary.needsHuman }) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="processSummary.openExisting > 0"
|
||||
class="rounded-md bg-violet-50 px-2 py-0.5 text-violet-700 dark:bg-violet-950/40 dark:text-violet-200"
|
||||
>
|
||||
{{ t('chat.shippingSessionSummary.openExistingCount', { count: processSummary.openExisting }) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="processSummary.failed > 0"
|
||||
class="rounded-md bg-rose-50 px-2 py-0.5 text-rose-700 dark:bg-rose-950/40 dark:text-rose-200"
|
||||
>
|
||||
{{ t('chat.shippingSessionSummary.failed', { count: processSummary.failed }) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="!taskRows.length" class="text-xs text-muted">
|
||||
{{ docsLoading ? t('chat.shippingOrderExtractionDocumentsLoading') : t('chat.shippingSessionSummary.empty') }}
|
||||
</div>
|
||||
|
||||
<ul v-else class="space-y-2">
|
||||
<li
|
||||
v-for="row in taskRows"
|
||||
:key="row.key"
|
||||
class="rounded-lg border border-default bg-surface-soft/80 px-2.5 py-2"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<div class="min-w-0">
|
||||
<div class="truncate text-xs font-semibold text-primary">
|
||||
{{ row.fileName || row.taskNo || t('chat.shippingSessionSummary.unnamedPdf') }}
|
||||
</div>
|
||||
<div class="mt-0.5 text-[11px] text-muted">
|
||||
{{ t('chat.shippingSessionSummary.progressIndex', {
|
||||
current: row.index,
|
||||
total: row.total || processSummary.total || 1,
|
||||
}) }}
|
||||
<!-- 重复态任务号已在原因行「已有任务 SN-xxx」展示,序号行不再重复 -->
|
||||
<span
|
||||
v-if="row.taskNo && row.badge !== 'duplicate'"
|
||||
class="ml-1 font-mono"
|
||||
>{{ row.taskNo }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<span
|
||||
v-if="row.badge === 'duplicate'"
|
||||
class="shrink-0 rounded-full bg-violet-100 px-1.5 py-0.5 text-[10px] font-medium text-violet-800 dark:bg-violet-900/50 dark:text-violet-100"
|
||||
>
|
||||
{{ t('chat.shippingSessionSummary.duplicateBadge') }}
|
||||
</span>
|
||||
<span
|
||||
v-else-if="row.badge === 'exception'"
|
||||
class="shrink-0 rounded-full bg-amber-100 px-1.5 py-0.5 text-[10px] font-medium text-amber-800 dark:bg-amber-900/50 dark:text-amber-100"
|
||||
>
|
||||
{{ t('chat.shippingSessionSummary.exception') }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="row.stage" class="mt-1 text-[11px] text-secondary">
|
||||
{{ row.stage }}
|
||||
</div>
|
||||
<div v-if="row.message" class="mt-0.5 line-clamp-3 text-[11px] text-muted">
|
||||
{{ row.message }}
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap gap-2">
|
||||
<button
|
||||
v-if="row.entrySurface === 'review_workbench'"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline"
|
||||
@click="openEntrySurface(row)"
|
||||
>
|
||||
<ExternalLink class="h-3 w-3" />
|
||||
{{ t('chat.shippingSessionSummary.openReview') }}
|
||||
</button>
|
||||
<button
|
||||
v-else-if="row.entrySurface === 'task_workbench' && row.taskNo"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline"
|
||||
@click="openTaskWorkbench(row.taskNo)"
|
||||
>
|
||||
<ExternalLink class="h-3 w-3" />
|
||||
{{ row.kind === 'document'
|
||||
? t('chat.shippingSessionSummary.openExistingTask')
|
||||
: t('chat.shippingSessionSummary.openTask') }}
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</aside>
|
||||
</template>
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/chat/components/messages/ChatMessageBubble.vue
|
||||
* 用途:渲染单条聊天消息,统一承接用户气泡、助手 Markdown、内嵌文件下载、请假/出货子组件与操作栏。
|
||||
* 依赖:Vue computed、lucide 图标、消息附件/Leave/Shipping 子组件、chat.types 与页面级 handlers。
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;用户附件与文字共用同一气泡,助手正文与特殊交互委托页面 handlers。
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;货代履约写按钮不在气泡内渲染,仅展示只读卡与深链通知。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
@@ -45,8 +45,6 @@ export interface ChatMessageBubbleHandlers {
|
||||
canOpenQueryPreview: (msg: ChatMessage) => boolean;
|
||||
getQueryPreviewSummary: (msg: ChatMessage) => string;
|
||||
openQueryPreviewDialog: (msg: ChatMessage) => void;
|
||||
shippingActionButtonClass: (variant?: string) => string;
|
||||
onShippingActionClick: (msg: ChatMessage, action: NonNullable<ChatMessage['shipping_actions']>[number]) => void;
|
||||
getDisplayRetrieverResources: (msg: ChatMessage) => Array<Record<string, unknown>>;
|
||||
getSourceLinks: (resources: Array<Record<string, unknown>>) => SourceFileLink[];
|
||||
shouldExpandSourceDetails: (msg: ChatMessage) => boolean;
|
||||
@@ -63,7 +61,6 @@ const {
|
||||
isThinking,
|
||||
showChatRating,
|
||||
copiedIndex,
|
||||
isShippingNoticeAgent,
|
||||
isLatestAssistantMessage,
|
||||
handlers,
|
||||
leaveHandlers,
|
||||
@@ -127,11 +124,6 @@ const showActions = computed(() => (
|
||||
message.type !== 'leave-form'
|
||||
&& (message.role !== 'user' || hasUserContent.value)
|
||||
));
|
||||
const showShippingActionsPanel = computed(() =>
|
||||
isShippingNoticeAgent
|
||||
&& !!message.shipping_actions?.length
|
||||
&& message.type !== 'shipping-match-result',
|
||||
);
|
||||
const shippingOrderExtractionState = computed(() => message.shipping_order_extraction_state);
|
||||
const retryingOrderExtraction = ref(false);
|
||||
const shippingOrderExtractionRunNo = computed(() => {
|
||||
@@ -695,10 +687,6 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
:match-status="handlers.getShippingMatchResultPayload(message)!.match_status"
|
||||
:line-results="handlers.getShippingMatchResultPayload(message)!.line_results"
|
||||
:shortage-lines="handlers.getShippingMatchResultPayload(message)!.shortage_lines"
|
||||
:action-buttons="handlers.getShippingMatchResultPayload(message)!.action_buttons"
|
||||
:action-busy="isThinking || message.shipping_actions_used"
|
||||
:action-button-class="handlers.shippingActionButtonClass"
|
||||
:on-action-click="(action) => handlers.onShippingActionClick(message, action)"
|
||||
/>
|
||||
<MaintenanceDeviceResultCard
|
||||
v-else-if="message.type === 'maintenance-device-result'"
|
||||
@@ -786,24 +774,6 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="showShippingActionsPanel"
|
||||
class="mt-4 space-y-2 border-t border-default pt-4"
|
||||
>
|
||||
<div class="text-xs font-medium text-muted">{{ $t('chat.shippingNoticeActionsHint') }}</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="(action, actionIndex) in message.shipping_actions"
|
||||
:key="`${message.local_id || index}-shipping-action-${action.id}-${actionIndex}`"
|
||||
type="button"
|
||||
:class="handlers.shippingActionButtonClass(action.variant)"
|
||||
:disabled="isThinking || message.shipping_actions_used"
|
||||
@click="handlers.onShippingActionClick(message, action)"
|
||||
>
|
||||
{{ action.label }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
+44
-393
@@ -1,33 +1,15 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingOrderExtractionCard.spec.ts
|
||||
* 用途:覆盖订单解析摘要卡、详情抽屉和单 PDF 结果项的关键交互。
|
||||
* 用途:覆盖聊天主区一句过程通知卡(无逐 PDF 列表、无复核按钮、无重复统计)。
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n、本域组件与 DTO 类型。
|
||||
* 逻辑:验证按钮由后端 available_actions 驱动,详情抽屉按需加载并支持键盘关闭。
|
||||
* 逻辑:断言 processNotice 文案与技术失败重试;复核深链由右侧摘要面板承担。
|
||||
*/
|
||||
import { nextTick } from 'vue';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { createMemoryHistory, createRouter } from 'vue-router';
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';
|
||||
import ShippingOrderDocumentResultItem from './ShippingOrderDocumentResultItem.vue';
|
||||
import ShippingOrderExtractionCard from './ShippingOrderExtractionCard.vue';
|
||||
import ShippingOrderExtractionDetailsDrawer from './ShippingOrderExtractionDetailsDrawer.vue';
|
||||
import type { ShippingOrderExtractionState } from '../../types/chat.types';
|
||||
import type {
|
||||
ShippingOrderExtractionDocumentResult,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
} from '../../types/shipping.api.types';
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
listDocuments: vi.fn(),
|
||||
listProgressEvents: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../api/shipping.api', () => ({
|
||||
listWorkspaceShippingOrderExtractionDocuments: api.listDocuments,
|
||||
listWorkspaceShippingOrderExtractionProgressEvents: api.listProgressEvents,
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
@@ -39,28 +21,15 @@ const i18n = createI18n({
|
||||
},
|
||||
});
|
||||
|
||||
const flushUi = async () => {
|
||||
await Promise.resolve();
|
||||
await nextTick();
|
||||
};
|
||||
|
||||
const makeRouter = () => createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/chat/:agentId', name: 'Chat', component: { template: '<div />' } },
|
||||
{ path: '/chat/:agentId/order-review/:runNo', name: 'ShippingOrderReview', component: { template: '<div />' } },
|
||||
],
|
||||
});
|
||||
|
||||
const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): ShippingOrderExtractionState => ({
|
||||
status: 'processing',
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 1,
|
||||
completedDocuments: 2,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
completedDocuments: 1,
|
||||
reviewRequiredDocuments: 1,
|
||||
failedDocuments: 1,
|
||||
candidateCount: 2,
|
||||
},
|
||||
currentActivity: {
|
||||
@@ -68,7 +37,7 @@ const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): Shipping
|
||||
fileName: 'PO-450003.pdf',
|
||||
eventCode: 'profile_matching',
|
||||
},
|
||||
availableActions: ['view_details'],
|
||||
availableActions: [],
|
||||
terminal: false,
|
||||
refreshFailed: false,
|
||||
errorCode: null,
|
||||
@@ -77,383 +46,65 @@ const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): Shipping
|
||||
...patch,
|
||||
});
|
||||
|
||||
const buildDocument = (
|
||||
patch: Partial<ShippingOrderExtractionDocumentResult> = {},
|
||||
): ShippingOrderExtractionDocumentResult => ({
|
||||
unit_id: 11,
|
||||
document_id: 85,
|
||||
file_name: 'PO-450001.pdf',
|
||||
status: 'candidate_ready',
|
||||
po_number: '450001',
|
||||
line_count: 4,
|
||||
profile: {
|
||||
code: 'vendor_a_po',
|
||||
name: 'Vendor A Purchase Order',
|
||||
version: 2,
|
||||
},
|
||||
email_supplement: {
|
||||
status: 'merged',
|
||||
relation_codes: ['po_mpn'],
|
||||
conflict_count: 0,
|
||||
reservation_id_status: 'merged',
|
||||
source_type_status: 'unavailable',
|
||||
},
|
||||
reason_code: null,
|
||||
available_actions: ['view_evidence', 'review_candidate'],
|
||||
...patch,
|
||||
});
|
||||
|
||||
const buildProgressEvent = (
|
||||
patch: Partial<ShippingOrderExtractionProgressEvent> = {},
|
||||
): ShippingOrderExtractionProgressEvent => ({
|
||||
event_code: 'expansion_wave_started',
|
||||
status: 'completed',
|
||||
unit_id: null,
|
||||
document_id: null,
|
||||
reason_code: null,
|
||||
summary: {
|
||||
selection_batch: 2,
|
||||
reason_codes: ['required_field_missing'],
|
||||
},
|
||||
occurred_at: '2026-07-28T10:30:00Z',
|
||||
...patch,
|
||||
});
|
||||
|
||||
describe('ShippingOrderExtractionCard', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
document.body.innerHTML = '';
|
||||
it('renders one-line process notice without per-PDF list, review CTA, or count stats', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-1' },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).toContain('正在处理附件');
|
||||
expect(wrapper.text()).toContain('右侧');
|
||||
expect(wrapper.text()).not.toContain('自动推进');
|
||||
expect(wrapper.text()).not.toContain('进入人工复核');
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-document-result"]').length).toBe(0);
|
||||
});
|
||||
|
||||
it('refreshes documents whenever the details drawer is opened', async () => {
|
||||
api.listDocuments.mockResolvedValue({ items: [buildDocument()] });
|
||||
api.listProgressEvents.mockResolvedValue({ items: [buildProgressEvent()] });
|
||||
it('renders duplicate-linked notice when only open_existing results remain', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
selectionPlan: {
|
||||
maxInitialAttachments: 2,
|
||||
maxInitialConcurrency: 2,
|
||||
expansionBatchSize: 2,
|
||||
maxTotalAttachments: 6,
|
||||
totalAttachmentCount: 5,
|
||||
eligibleAttachmentCount: 3,
|
||||
selectedAttachmentCount: 2,
|
||||
plannedAttachmentCount: 3,
|
||||
pendingExpansionAttachmentCount: 1,
|
||||
pendingExpansionBatches: { '2': 1 },
|
||||
skippedAttachmentCount: 3,
|
||||
duplicateAttachmentCount: 1,
|
||||
budgetLimitedAttachmentCount: 1,
|
||||
groupCount: 2,
|
||||
},
|
||||
unitSummary: {
|
||||
totalUnits: 2,
|
||||
selectedUnits: 2,
|
||||
retryingUnits: 1,
|
||||
pendingRetryUnits: 0,
|
||||
failedUnits: 0,
|
||||
reviewRequiredUnits: 0,
|
||||
succeededUnits: 0,
|
||||
selectionBatches: { '1': 2 },
|
||||
reviewRequiredReasonCodes: ['required_field_missing'],
|
||||
expansionTriggerReasonCodes: ['missing_reservation_id'],
|
||||
technicalFailureReasonCodes: [],
|
||||
},
|
||||
}),
|
||||
runNo: 'SNER-001',
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const detailButton = wrapper.findAll('button').find((item) => item.text().includes('查看处理详情'));
|
||||
expect(detailButton).toBeTruthy();
|
||||
|
||||
await detailButton!.trigger('click');
|
||||
await flushUi();
|
||||
|
||||
expect(api.listDocuments).toHaveBeenCalledTimes(1);
|
||||
expect(api.listProgressEvents).toHaveBeenCalledTimes(1);
|
||||
expect(api.listDocuments).toHaveBeenCalledWith('SNER-001');
|
||||
expect(api.listProgressEvents).toHaveBeenCalledWith('SNER-001');
|
||||
expect(wrapper.text()).toContain('处理详情');
|
||||
expect(wrapper.text()).toContain('运行时间线');
|
||||
expect(wrapper.text()).toContain('系统已开始分析下一轮候选附件。');
|
||||
expect(wrapper.text()).toContain('当前批次:第 2 轮');
|
||||
expect(wrapper.text()).toContain('当前原因:订单关键字段不完整。');
|
||||
expect(wrapper.text()).toContain('PO-450001.pdf');
|
||||
expect(wrapper.text()).toContain('本轮从 5 个附件中规划 2 个订单组');
|
||||
expect(wrapper.text()).toContain('已选 2 个附件');
|
||||
expect(wrapper.text()).toContain('待扩展 1 个附件');
|
||||
expect(wrapper.text()).toContain('预算受限 1 个');
|
||||
expect(wrapper.text()).toContain('技术重试 1 个');
|
||||
expect(wrapper.text()).toContain('待复核原因:订单关键字段不完整。');
|
||||
expect(wrapper.text()).toContain('扩批触发:仍缺少 Reservation 字段,需要后续附件补证。');
|
||||
|
||||
await detailButton!.trigger('click');
|
||||
await flushUi();
|
||||
|
||||
expect(api.listDocuments).toHaveBeenCalledTimes(2);
|
||||
expect(api.listProgressEvents).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('routes manual review directly to the dedicated workspace', async () => {
|
||||
const router = makeRouter();
|
||||
await router.push({ name: 'Chat', params: { agentId: 'agent-1' } });
|
||||
await router.isReady();
|
||||
const pushSpy = vi.spyOn(router, 'push');
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
availableActions: ['enter_manual_review'],
|
||||
}),
|
||||
runNo: 'SNER-002',
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n, router],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const reviewButton = wrapper.findAll('button').find((item) => item.text().includes('进入人工复核'));
|
||||
expect(reviewButton).toBeTruthy();
|
||||
|
||||
await reviewButton!.trigger('click');
|
||||
|
||||
await vi.waitFor(() => expect(pushSpy).toHaveBeenCalled());
|
||||
expect(pushSpy).toHaveBeenCalledWith({
|
||||
name: 'Chat',
|
||||
params: { agentId: 'agent-1' },
|
||||
query: { mode: 'order-review', run_no: 'SNER-002' },
|
||||
});
|
||||
expect(api.listDocuments).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('preserves the originating conversation when entering manual review', async () => {
|
||||
const router = makeRouter();
|
||||
await router.push({ name: 'Chat', params: { agentId: 'agent-1' }, query: { conversation_id: 'conv-123' } });
|
||||
await router.isReady();
|
||||
const pushSpy = vi.spyOn(router, 'push');
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState({ availableActions: ['enter_manual_review'] }), runNo: 'SNER-003' },
|
||||
global: { plugins: [i18n, router], stubs: { teleport: true } },
|
||||
});
|
||||
|
||||
const reviewButton = wrapper.findAll('button').find((item) => item.text().includes('进入人工复核'));
|
||||
expect(reviewButton).toBeTruthy();
|
||||
await reviewButton!.trigger('click');
|
||||
|
||||
await vi.waitFor(() => expect(pushSpy).toHaveBeenCalled());
|
||||
expect(pushSpy).toHaveBeenCalledWith({
|
||||
name: 'Chat',
|
||||
params: { agentId: 'agent-1' },
|
||||
query: { conversation_id: 'conv-123', mode: 'order-review', run_no: 'SNER-003' },
|
||||
});
|
||||
});
|
||||
|
||||
it('emits retry for failed attachments without mutating state locally', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
status: 'failed',
|
||||
terminal: true,
|
||||
status: 'review_required',
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
totalDocuments: 2,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 2,
|
||||
completedDocuments: 0,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 1,
|
||||
candidateCount: 2,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 0,
|
||||
openedExistingCount: 2,
|
||||
},
|
||||
currentActivity: null,
|
||||
availableActions: ['retry_failed_attachments'],
|
||||
availableActions: ['view_details'],
|
||||
}),
|
||||
runNo: 'SNER-003',
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
runNo: 'SNER-DUP',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
const retryButton = wrapper.findAll('button').find((item) => item.text().includes('重试失败附件'));
|
||||
expect(retryButton).toBeTruthy();
|
||||
|
||||
await retryButton!.trigger('click');
|
||||
|
||||
expect(wrapper.emitted('retry')).toHaveLength(1);
|
||||
expect(wrapper.text()).toContain('发现重复文件');
|
||||
expect(wrapper.text()).toContain('已关联已有任务');
|
||||
expect(wrapper.text()).not.toContain('需人工处理');
|
||||
});
|
||||
|
||||
it('renders run-level activity text without forcing an unknown file label', async () => {
|
||||
it('emits retry for failed attachments only', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
currentActivity: {
|
||||
unitId: 0,
|
||||
fileName: null,
|
||||
eventCode: 'plan_created',
|
||||
selectionBatch: 2,
|
||||
reasonCodes: ['required_field_missing'],
|
||||
availableActions: ['retry_failed_attachments'],
|
||||
summary: {
|
||||
totalDocuments: 2,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 1,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 1,
|
||||
candidateCount: 0,
|
||||
},
|
||||
}),
|
||||
runNo: 'SNER-004',
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
runNo: 'SNER-2',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('识别计划已创建,正在准备首轮附件。');
|
||||
expect(wrapper.text()).toContain('当前批次:第 2 轮');
|
||||
expect(wrapper.text()).toContain('当前原因:订单关键字段不完整。');
|
||||
expect(wrapper.text()).not.toContain('未命名 PDF');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ShippingOrderExtractionDetailsDrawer', () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('closes on Escape when the drawer is open', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionDetailsDrawer, {
|
||||
attachTo: document.body,
|
||||
props: {
|
||||
open: false,
|
||||
state: buildState({
|
||||
status: 'partially_completed',
|
||||
terminal: true,
|
||||
availableActions: ['view_details', 'enter_manual_review'],
|
||||
}),
|
||||
documents: [buildDocument()],
|
||||
progressEvents: [buildProgressEvent()],
|
||||
loading: false,
|
||||
loadFailed: false,
|
||||
progressLoading: false,
|
||||
progressLoadFailed: false,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
},
|
||||
});
|
||||
|
||||
await wrapper.setProps({ open: true });
|
||||
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
|
||||
await nextTick();
|
||||
|
||||
expect(wrapper.emitted('close')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('renders run timeline entries with batch and reason context', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionDetailsDrawer, {
|
||||
props: {
|
||||
open: true,
|
||||
state: buildState(),
|
||||
documents: [buildDocument()],
|
||||
progressEvents: [buildProgressEvent()],
|
||||
loading: false,
|
||||
loadFailed: false,
|
||||
progressLoading: false,
|
||||
progressLoadFailed: false,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('运行时间线');
|
||||
expect(wrapper.text()).toContain('业务复核');
|
||||
expect(wrapper.text()).toContain('系统已开始分析下一轮候选附件。');
|
||||
expect(wrapper.text()).toContain('当前批次:第 2 轮');
|
||||
expect(wrapper.text()).toContain('当前原因:订单关键字段不完整。');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ShippingOrderDocumentResultItem', () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('renders business reason and server-declared actions for a review-required PDF', async () => {
|
||||
const wrapper = mount(ShippingOrderDocumentResultItem, {
|
||||
props: {
|
||||
document: buildDocument({
|
||||
status: 'review_required',
|
||||
reason_code: 'multiple_po_detected',
|
||||
po_number: null,
|
||||
line_count: 0,
|
||||
email_supplement: {
|
||||
status: 'conflict',
|
||||
relation_codes: ['po_mpn'],
|
||||
conflict_count: 2,
|
||||
reservation_id_status: 'conflict',
|
||||
source_type_status: 'none',
|
||||
},
|
||||
available_actions: ['view_evidence', 'manual_review'],
|
||||
}),
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('需要人工复核');
|
||||
expect(wrapper.text()).toContain('一份 PDF 中检测到多个不同 PO');
|
||||
expect(wrapper.text()).toContain('正文冲突 2 项');
|
||||
|
||||
const actionButtons = wrapper.findAll('button');
|
||||
expect(actionButtons.map((item) => item.text())).toEqual(
|
||||
expect.arrayContaining(['查看证据', '人工复核']),
|
||||
);
|
||||
|
||||
await actionButtons[0].trigger('click');
|
||||
|
||||
expect(wrapper.emitted('enterManualReview')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('renders a user-safe retry hint rather than a technical failure code for a failed attachment', async () => {
|
||||
const wrapper = mount(ShippingOrderDocumentResultItem, {
|
||||
props: {
|
||||
document: buildDocument({
|
||||
status: 'failed',
|
||||
reason_code: 'technical_failure',
|
||||
selection_batch: 2,
|
||||
group_key: 'PO-GRP-02',
|
||||
retry_status: 'failed',
|
||||
technical_failure_reason_code: 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
|
||||
budget_cost: {
|
||||
initial_attachment_budget: 2,
|
||||
initial_concurrency_budget: 2,
|
||||
selected_in_batch: 1,
|
||||
},
|
||||
available_actions: [],
|
||||
}),
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('选择批次:第 2 轮');
|
||||
expect(wrapper.text()).toContain('订单组:PO-GRP-02');
|
||||
expect(wrapper.text()).toContain('系统暂未完成处理,您可以稍后重试。');
|
||||
expect(wrapper.text()).toContain('首轮预算:附件 2 个,并发 2 个,本轮已选 1 个');
|
||||
expect(wrapper.text()).not.toContain('SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT');
|
||||
await wrapper.get('button').trigger('click');
|
||||
expect(wrapper.emitted('retry')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,24 +1,14 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingOrderExtractionCard.vue
|
||||
* 用途:渲染聊天中的订单抽取摘要卡,并在需要时打开 PDF 详情抽屉。
|
||||
* 依赖:订单抽取 Run 状态卡 DTO、documents API、详情抽屉。
|
||||
* 逻辑:卡片只显示 Run 汇总、当前活动和下一步动作;逐 PDF 结果与 Run 事实时间线延迟到抽屉内按需加载。
|
||||
* 用途:聊天主区一句过程通知——不重复右侧统计,无逐 PDF 列表、无复核按钮。
|
||||
* 依赖:订单抽取 Run 状态卡 DTO、vue-i18n。
|
||||
* 逻辑:右侧 ShippingSessionSummaryPanel 为唯一状态与跳转面;纯 open_existing 时用重复关联文案。
|
||||
*/
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { CircleCheck, CircleX, LoaderCircle, TriangleAlert } from 'lucide-vue-next';
|
||||
import {
|
||||
listWorkspaceShippingOrderExtractionDocuments,
|
||||
listWorkspaceShippingOrderExtractionProgressEvents,
|
||||
} from '../../api/shipping.api';
|
||||
import type { ShippingOrderExtractionState } from '../../types/chat.types';
|
||||
import type {
|
||||
ShippingOrderExtractionDocumentResult,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
} from '../../types/shipping.api.types';
|
||||
import ShippingOrderExtractionDetailsDrawer from './ShippingOrderExtractionDetailsDrawer.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
state: ShippingOrderExtractionState;
|
||||
@@ -27,50 +17,25 @@ const props = defineProps<{
|
||||
|
||||
const emit = defineEmits<{
|
||||
retry: [];
|
||||
enterManualReview: [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
const detailsOpen = ref(false);
|
||||
const documents = ref<ShippingOrderExtractionDocumentResult[]>([]);
|
||||
const progressEvents = ref<ShippingOrderExtractionProgressEvent[]>([]);
|
||||
const loadingDocuments = ref(false);
|
||||
const documentsLoadFailed = ref(false);
|
||||
const documentsLoadedForRun = ref('');
|
||||
const loadingProgressEvents = ref(false);
|
||||
const progressEventsLoadFailed = ref(false);
|
||||
const progressEventsLoadedForRun = ref('');
|
||||
let detailsRefreshTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const detailsFreshnessKey = computed(() => JSON.stringify({
|
||||
runNo: props.runNo || '',
|
||||
status: props.state.status,
|
||||
phase: props.state.currentActivity?.eventCode || '',
|
||||
total: props.state.summary.totalDocuments,
|
||||
completed: props.state.summary.completedDocuments,
|
||||
reviewRequired: props.state.summary.reviewRequiredDocuments,
|
||||
failed: props.state.summary.failedDocuments,
|
||||
}));
|
||||
|
||||
watch(
|
||||
() => props.runNo,
|
||||
() => {
|
||||
detailsOpen.value = false;
|
||||
documents.value = [];
|
||||
progressEvents.value = [];
|
||||
loadingDocuments.value = false;
|
||||
loadingProgressEvents.value = false;
|
||||
documentsLoadFailed.value = false;
|
||||
progressEventsLoadFailed.value = false;
|
||||
documentsLoadedForRun.value = '';
|
||||
progressEventsLoadedForRun.value = '';
|
||||
},
|
||||
);
|
||||
/**
|
||||
* 是否为「仅重复关联已有任务、无需人工复核」终态通知。
|
||||
*/
|
||||
const isDuplicateOnlyNotice = computed(() => {
|
||||
const opened = Math.max(0, Number(props.state.summary.openedExistingCount || 0));
|
||||
if (opened <= 0) return false;
|
||||
const review = Math.max(0, Number(props.state.summary.reviewRequiredDocuments || 0));
|
||||
const failed = Math.max(0, Number(props.state.summary.failedDocuments || 0));
|
||||
return review === 0 && failed === 0;
|
||||
});
|
||||
|
||||
const toneClass = computed(() => {
|
||||
if (isDuplicateOnlyNotice.value) {
|
||||
return 'border-violet-200 bg-violet-50/80 text-violet-950 dark:border-violet-800 dark:bg-violet-950/35 dark:text-violet-100';
|
||||
}
|
||||
switch (props.state.status) {
|
||||
case 'completed':
|
||||
return 'border-emerald-200 bg-emerald-50/80 text-emerald-950 dark:border-emerald-800 dark:bg-emerald-950/35 dark:text-emerald-100';
|
||||
@@ -85,272 +50,80 @@ const toneClass = computed(() => {
|
||||
}
|
||||
});
|
||||
|
||||
const titleKey = computed(() => `chat.shippingOrderExtractionCardTitle.${props.state.status}`);
|
||||
/**
|
||||
* 一句过程通知;纯重复关联不误报「需人工处理」。
|
||||
*/
|
||||
const compactLine = computed(() => {
|
||||
if (isDuplicateOnlyNotice.value) {
|
||||
return t('chat.shippingSessionSummary.processNoticeDuplicateLinked');
|
||||
}
|
||||
switch (props.state.status) {
|
||||
case 'completed':
|
||||
return t('chat.shippingSessionSummary.processNoticeCompleted');
|
||||
case 'partially_completed':
|
||||
case 'review_required':
|
||||
return t('chat.shippingSessionSummary.processNoticeNeedsAction');
|
||||
case 'failed':
|
||||
case 'cancelled':
|
||||
return t('chat.shippingSessionSummary.processNoticeFailed');
|
||||
default:
|
||||
return t('chat.shippingSessionSummary.processNoticeProcessing');
|
||||
}
|
||||
});
|
||||
|
||||
const activityKey = computed(() => {
|
||||
const code = String(props.state.currentActivity?.eventCode || '').trim();
|
||||
const key = `chat.shippingOrderExtractionActivity.${code}`;
|
||||
return code && te(key) ? key : 'chat.shippingOrderExtractionActivity.generic_processing';
|
||||
});
|
||||
const completedLabel = computed(() => `${props.state.summary.completedDocuments} / ${props.state.summary.totalDocuments}`);
|
||||
const selectionSummaryItems = computed(() => {
|
||||
const selectionPlan = props.state.selectionPlan;
|
||||
const unitSummary = props.state.unitSummary;
|
||||
return [
|
||||
selectionPlan?.selectedAttachmentCount
|
||||
? t('chat.shippingOrderExtractionPlanSelected', { count: selectionPlan.selectedAttachmentCount })
|
||||
: '',
|
||||
selectionPlan?.pendingExpansionAttachmentCount
|
||||
? t('chat.shippingOrderExtractionPlanPendingExpansion', { count: selectionPlan.pendingExpansionAttachmentCount })
|
||||
: '',
|
||||
selectionPlan?.skippedAttachmentCount
|
||||
? t('chat.shippingOrderExtractionPlanSkipped', { count: selectionPlan.skippedAttachmentCount })
|
||||
: '',
|
||||
selectionPlan?.budgetLimitedAttachmentCount
|
||||
? t('chat.shippingOrderExtractionPlanBudgetLimited', { count: selectionPlan.budgetLimitedAttachmentCount })
|
||||
: '',
|
||||
unitSummary?.retryingUnits
|
||||
? t('chat.shippingOrderExtractionPlanRetrying', { count: unitSummary.retryingUnits })
|
||||
: '',
|
||||
unitSummary?.failedUnits
|
||||
? t('chat.shippingOrderExtractionPlanTechnicalFailures', { count: unitSummary.failedUnits })
|
||||
: '',
|
||||
].filter(Boolean);
|
||||
});
|
||||
const selectionPlanHint = computed(() => {
|
||||
const selectionPlan = props.state.selectionPlan;
|
||||
if (!selectionPlan?.totalAttachmentCount) return '';
|
||||
return t('chat.shippingOrderExtractionPlanSummary', {
|
||||
total: selectionPlan.totalAttachmentCount,
|
||||
groups: selectionPlan.groupCount || 0,
|
||||
attachments: selectionPlan.maxInitialAttachments || 0,
|
||||
concurrency: selectionPlan.maxInitialConcurrency || 0,
|
||||
});
|
||||
return code && te(key) ? key : '';
|
||||
});
|
||||
|
||||
const translateReasonCodes = (codes: string[] | undefined): string[] => (
|
||||
(codes || [])
|
||||
.map((code) => {
|
||||
const normalized = String(code || '').trim();
|
||||
if (!normalized) return '';
|
||||
const key = `chat.shippingOrderExtractionReason.${normalized}`;
|
||||
return te(key) ? t(key) : normalized;
|
||||
})
|
||||
.filter(Boolean)
|
||||
);
|
||||
|
||||
const reviewReasonSummary = computed(() => {
|
||||
const labels = translateReasonCodes(props.state.unitSummary?.reviewRequiredReasonCodes);
|
||||
return labels.length
|
||||
? t('chat.shippingOrderExtractionReviewReasonCodes', { codes: labels.join(' / ') })
|
||||
: '';
|
||||
});
|
||||
|
||||
const expansionTriggerSummary = computed(() => {
|
||||
const labels = translateReasonCodes(props.state.unitSummary?.expansionTriggerReasonCodes);
|
||||
return labels.length
|
||||
? t('chat.shippingOrderExtractionExpansionTriggerCodes', { codes: labels.join(' / ') })
|
||||
: '';
|
||||
});
|
||||
|
||||
const currentActivityContextSummary = computed(() => {
|
||||
const parts: string[] = [];
|
||||
const batch = Number(props.state.currentActivity?.selectionBatch || 0);
|
||||
if (batch > 0) {
|
||||
parts.push(t('chat.shippingOrderExtractionActivitySelectionBatch', { batch }));
|
||||
}
|
||||
const labels = translateReasonCodes(props.state.currentActivity?.reasonCodes);
|
||||
if (labels.length) {
|
||||
parts.push(t('chat.shippingOrderExtractionActivityReasonCodes', { codes: labels.join(' / ') }));
|
||||
}
|
||||
return parts.join(' · ');
|
||||
});
|
||||
|
||||
/**
|
||||
* 刷新抽屉中的 Run 详情。
|
||||
*
|
||||
* 文档列表可能在布局 Job 完成后才落库;抽屉绝不能缓存首次打开时的空结果,
|
||||
* 否则聊天卡已显示新状态而详情仍停留在旧的“暂无结果”。
|
||||
*/
|
||||
const refreshDetails = async () => {
|
||||
if (!props.runNo) return;
|
||||
const tasks: Promise<void>[] = [];
|
||||
if (!loadingDocuments.value) {
|
||||
loadingDocuments.value = true;
|
||||
documentsLoadFailed.value = false;
|
||||
tasks.push(
|
||||
listWorkspaceShippingOrderExtractionDocuments(props.runNo)
|
||||
.then((response) => {
|
||||
documents.value = response.items;
|
||||
documentsLoadedForRun.value = props.runNo || '';
|
||||
})
|
||||
.catch(() => {
|
||||
documentsLoadFailed.value = true;
|
||||
})
|
||||
.finally(() => {
|
||||
loadingDocuments.value = false;
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (!loadingProgressEvents.value) {
|
||||
loadingProgressEvents.value = true;
|
||||
progressEventsLoadFailed.value = false;
|
||||
tasks.push(
|
||||
listWorkspaceShippingOrderExtractionProgressEvents(props.runNo)
|
||||
.then((response) => {
|
||||
progressEvents.value = response.items;
|
||||
progressEventsLoadedForRun.value = props.runNo || '';
|
||||
})
|
||||
.catch(() => {
|
||||
progressEventsLoadFailed.value = true;
|
||||
})
|
||||
.finally(() => {
|
||||
loadingProgressEvents.value = false;
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (tasks.length) {
|
||||
await Promise.all(tasks);
|
||||
}
|
||||
};
|
||||
|
||||
const openDetails = async () => {
|
||||
if (!props.runNo) return;
|
||||
detailsOpen.value = true;
|
||||
await refreshDetails();
|
||||
};
|
||||
|
||||
/** 详情打开期间独立刷新,避免长任务只在聊天卡状态变更时才显示新阶段。 */
|
||||
const stopDetailsRefresh = () => {
|
||||
if (detailsRefreshTimer) clearInterval(detailsRefreshTimer);
|
||||
detailsRefreshTimer = null;
|
||||
};
|
||||
|
||||
watch(detailsOpen, (open) => {
|
||||
stopDetailsRefresh();
|
||||
if (!open || !props.runNo || !['queued', 'processing'].includes(props.state.status)) return;
|
||||
detailsRefreshTimer = setInterval(() => void refreshDetails(), 2000);
|
||||
});
|
||||
|
||||
watch(() => props.state.status, (status) => {
|
||||
if (!['queued', 'processing'].includes(status)) stopDetailsRefresh();
|
||||
});
|
||||
|
||||
onBeforeUnmount(stopDetailsRefresh);
|
||||
|
||||
watch(detailsFreshnessKey, () => {
|
||||
if (detailsOpen.value) void refreshDetails();
|
||||
});
|
||||
|
||||
/** 新建单前复核统一进入独立工作台,不能再落入聊天内旧 Candidate 编辑区。 */
|
||||
const openReviewWorkspace = async () => {
|
||||
if (!props.runNo) return;
|
||||
await router.push({
|
||||
name: 'Chat',
|
||||
params: { agentId: String(route.params.agentId || '') },
|
||||
query: {
|
||||
...route.query,
|
||||
mode: 'order-review',
|
||||
run_no: props.runNo,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const handleActionClick = async (action: string) => {
|
||||
switch (action) {
|
||||
case 'view_details':
|
||||
await openDetails();
|
||||
return;
|
||||
case 'enter_manual_review':
|
||||
await openReviewWorkspace();
|
||||
return;
|
||||
case 'retry_failed_attachments':
|
||||
emit('retry');
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
};
|
||||
const showRetry = computed(() => (
|
||||
props.state.availableActions.includes('retry_failed_attachments')
|
||||
|| props.state.summary.failedDocuments > 0
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="mb-3 rounded-lg border px-3.5 py-3" :class="toneClass">
|
||||
<div
|
||||
class="mb-3 rounded-lg border px-3.5 py-2.5"
|
||||
:class="toneClass"
|
||||
data-testid="shipping-order-extraction-card"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<LoaderCircle
|
||||
v-if="state.status === 'queued' || state.status === 'processing'"
|
||||
class="mt-0.5 h-5 w-5 shrink-0 animate-spin"
|
||||
class="mt-0.5 h-4 w-4 shrink-0 animate-spin"
|
||||
/>
|
||||
<CircleCheck
|
||||
v-else-if="state.status === 'completed' || isDuplicateOnlyNotice"
|
||||
class="mt-0.5 h-4 w-4 shrink-0"
|
||||
/>
|
||||
<CircleCheck v-else-if="state.status === 'completed'" class="mt-0.5 h-5 w-5 shrink-0" />
|
||||
<TriangleAlert
|
||||
v-else-if="state.status === 'partially_completed' || state.status === 'review_required'"
|
||||
class="mt-0.5 h-5 w-5 shrink-0"
|
||||
class="mt-0.5 h-4 w-4 shrink-0"
|
||||
/>
|
||||
<CircleX v-else class="mt-0.5 h-5 w-5 shrink-0" />
|
||||
<CircleX v-else class="mt-0.5 h-4 w-4 shrink-0" />
|
||||
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="text-sm font-semibold">{{ t(titleKey) }}</div>
|
||||
<div class="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-xs opacity-90">
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.total', { count: state.summary.totalDocuments }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.completedProgress', { value: completedLabel }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.reviewRequired', { count: state.summary.reviewRequiredDocuments }) }}</span>
|
||||
<span v-if="state.summary.failedDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.failed', { count: state.summary.failedDocuments }) }}
|
||||
</span>
|
||||
<div class="text-sm font-medium">{{ compactLine }}</div>
|
||||
<div v-if="state.currentActivity?.fileName" class="mt-1 text-xs opacity-80">
|
||||
{{ t('chat.shippingOrderExtractionCurrentFile', {
|
||||
fileName: state.currentActivity.fileName || t('chat.shippingOrderExtractionUnknownDocument'),
|
||||
}) }}
|
||||
<span v-if="activityKey"> · {{ t(activityKey) }}</span>
|
||||
</div>
|
||||
<div v-if="state.currentActivity?.fileName" class="mt-2 text-xs font-medium opacity-90">
|
||||
{{ t('chat.shippingOrderExtractionCurrentFile', { fileName: state.currentActivity.fileName || t('chat.shippingOrderExtractionUnknownDocument') }) }}
|
||||
</div>
|
||||
<div v-if="state.currentActivity" class="mt-1 text-xs opacity-80">
|
||||
{{ t(activityKey) }}
|
||||
</div>
|
||||
<div v-if="currentActivityContextSummary" class="mt-1 text-xs opacity-80">
|
||||
{{ currentActivityContextSummary }}
|
||||
</div>
|
||||
<div v-if="selectionPlanHint" class="mt-2 text-xs opacity-85">
|
||||
{{ selectionPlanHint }}
|
||||
</div>
|
||||
<div v-if="reviewReasonSummary" class="mt-2 text-xs opacity-85">
|
||||
{{ reviewReasonSummary }}
|
||||
</div>
|
||||
<div v-if="expansionTriggerSummary" class="mt-1 text-xs opacity-85">
|
||||
{{ expansionTriggerSummary }}
|
||||
</div>
|
||||
<div v-if="selectionSummaryItems.length" class="mt-2 flex flex-wrap gap-2 text-[11px] font-medium opacity-90">
|
||||
<span
|
||||
v-for="item in selectionSummaryItems"
|
||||
:key="item"
|
||||
class="rounded-full bg-black/10 px-2 py-0.5 dark:bg-white/10"
|
||||
>
|
||||
{{ item }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="state.refreshFailed" class="mt-2 text-xs font-medium opacity-90">
|
||||
<div v-if="state.refreshFailed" class="mt-1 text-xs font-medium opacity-90">
|
||||
{{ t('chat.shippingOrderExtractionRefreshFailed') }}
|
||||
</div>
|
||||
<div class="mt-3 flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="action in state.availableActions"
|
||||
:key="action"
|
||||
type="button"
|
||||
class="inline-flex items-center rounded-md border border-current/20 px-2.5 py-1 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/5"
|
||||
@click="handleActionClick(action)"
|
||||
>
|
||||
{{ t(`chat.shippingOrderExtractionAction.${action}`) }}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
v-if="showRetry"
|
||||
type="button"
|
||||
class="mt-2 inline-flex items-center rounded-md border border-current/20 px-2.5 py-1 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/5"
|
||||
@click="emit('retry')"
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionAction.retry_failed_attachments') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ShippingOrderExtractionDetailsDrawer
|
||||
:open="detailsOpen"
|
||||
:state="state"
|
||||
:documents="documents"
|
||||
:progress-events="progressEvents"
|
||||
:loading="loadingDocuments"
|
||||
:load-failed="documentsLoadFailed"
|
||||
:progress-loading="loadingProgressEvents"
|
||||
:progress-load-failed="progressEventsLoadFailed"
|
||||
@close="detailsOpen = false"
|
||||
@enter-manual-review="openReviewWorkspace"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -78,12 +78,12 @@ const buildBatchUiStateEvent = (
|
||||
});
|
||||
|
||||
describe('useChat shipping_ui_state SSE', () => {
|
||||
it('hydrates focus task ui state from batch payload and does not reattach used actions', () => {
|
||||
it('hydrates ui_state for notifications and never attaches chat fulfillment actions', () => {
|
||||
const message: ChatMessage = {
|
||||
role: 'assistant',
|
||||
content: '当前正在处理批次任务',
|
||||
type: 'shipping-match-result',
|
||||
payload: { action_buttons: [] },
|
||||
payload: { action_buttons: [{ id: 'legacy' }] },
|
||||
};
|
||||
|
||||
const batchEvent = buildBatchUiStateEvent('SN-UNIT-001', 'SB-UNIT-001', 'generate_excel');
|
||||
@@ -91,22 +91,12 @@ describe('useChat shipping_ui_state SSE', () => {
|
||||
applyShippingUiStateToMessage(message, batchEvent);
|
||||
|
||||
expect(message.shipping_ui_state?.task_no).toBe('SN-UNIT-001');
|
||||
expect(message.shipping_actions?.map((item) => item.id)).toEqual(['generate_excel']);
|
||||
expect((message.payload as { action_buttons?: unknown[] }).action_buttons).toHaveLength(1);
|
||||
expect((message.payload as { shipping_batch_ui_state?: { batch_no?: string } }).shipping_batch_ui_state?.batch_no).toBe('SB-UNIT-001');
|
||||
|
||||
message.shipping_actions_used = true;
|
||||
message.shipping_actions = undefined;
|
||||
(message.payload as { action_buttons?: unknown[] }).action_buttons = [];
|
||||
|
||||
applyShippingUiStateToMessage(message, batchEvent);
|
||||
|
||||
expect(message.shipping_ui_state?.checkpoint).toBe('ready_export');
|
||||
expect(message.shipping_actions).toBeUndefined();
|
||||
expect((message.payload as { action_buttons?: unknown[] }).action_buttons).toEqual([]);
|
||||
expect((message.payload as { shipping_batch_ui_state?: { batch_no?: string } }).shipping_batch_ui_state?.batch_no).toBe('SB-UNIT-001');
|
||||
});
|
||||
|
||||
it('switches buttons when batch focus task changes from A to B', () => {
|
||||
it('updates ui_state when batch focus task changes without remounting action buttons', () => {
|
||||
const message: ChatMessage = {
|
||||
role: 'assistant',
|
||||
content: '请继续处理当前批次',
|
||||
@@ -116,12 +106,12 @@ describe('useChat shipping_ui_state SSE', () => {
|
||||
applyShippingUiStateToMessage(message, buildBatchUiStateEvent('SN-FOCUS-A', 'SB-FOCUS-001', 'generate_excel'));
|
||||
|
||||
expect(message.shipping_ui_state?.task_no).toBe('SN-FOCUS-A');
|
||||
expect(message.shipping_actions?.map((item) => item.id)).toEqual(['generate_excel']);
|
||||
expect(message.shipping_actions).toBeUndefined();
|
||||
|
||||
applyShippingUiStateToMessage(message, buildBatchUiStateEvent('SN-FOCUS-B', 'SB-FOCUS-001', 'retry_upload'));
|
||||
|
||||
expect(message.shipping_ui_state?.task_no).toBe('SN-FOCUS-B');
|
||||
expect(message.shipping_actions?.map((item) => item.id)).toEqual(['retry_upload']);
|
||||
expect(message.shipping_actions).toBeUndefined();
|
||||
expect((message.payload as { shipping_batch_ui_state?: { current_focus_task_no?: string } }).shipping_batch_ui_state?.current_focus_task_no)
|
||||
.toBe('SN-FOCUS-B');
|
||||
});
|
||||
|
||||
@@ -113,7 +113,7 @@ const addAttributionParts = (msg: ChatMessage, value: unknown) => {
|
||||
* 解析发货通知 SSE 事件中的统一 UI State 载荷。
|
||||
*
|
||||
* 核心逻辑:优先读取单票 `ui_state`,批次事件则下钻 `batch_ui_state.focus_task_ui_state`;
|
||||
* 同时保留批次态原文,供右侧工作台和后续兼容逻辑继续消费。
|
||||
* 同时保留批次态原文,供会话上传摘要与后续同步逻辑继续消费。
|
||||
* @param data - SSE 事件 JSON
|
||||
* @returns 提炼后的单票 UI State 与原始批次 UI State
|
||||
*/
|
||||
@@ -141,23 +141,17 @@ export const resolveShippingUiStatePayload = (data: Record<string, unknown>): {
|
||||
/**
|
||||
* 将发货通知状态机事件同步到当前助手消息。
|
||||
*
|
||||
* 说明:shipping_ui_state 是 HXOPS 自有 SSE 事件,不依赖 Dify 正文;收到后立即挂按钮,
|
||||
* 让用户无需等待 `message_end` 才拿到状态机结果。若该消息按钮已被消费,则只更新状态快照,
|
||||
* 不重新挂出可点击按钮,避免首帧旧状态覆盖。
|
||||
* 说明:shipping_ui_state 是 HXOPS 自有 SSE 事件;收到后写入状态快照供会话摘要/通知展示,
|
||||
* 不再把 action_buttons 挂到聊天消息(履约写操作改由任务处理工作台承接)。
|
||||
*/
|
||||
export const applyShippingUiStateToMessage = (msg: ChatMessage, data: Record<string, unknown>) => {
|
||||
const { uiState, batchUiState } = resolveShippingUiStatePayload(data);
|
||||
if (!uiState) return;
|
||||
const nextActions = Array.isArray(uiState.action_buttons) && uiState.action_buttons.length
|
||||
? uiState.action_buttons
|
||||
: undefined;
|
||||
|
||||
msg.shipping_ui_state = uiState;
|
||||
if (!msg.shipping_actions_used) {
|
||||
msg.shipping_actions = nextActions;
|
||||
}
|
||||
if (msg.type === 'shipping-match-result' && msg.payload && typeof msg.payload === 'object' && !msg.shipping_actions_used) {
|
||||
(msg.payload as { action_buttons?: ChatMessage['shipping_actions'] }).action_buttons = nextActions;
|
||||
msg.shipping_actions = undefined;
|
||||
if (msg.type === 'shipping-match-result' && msg.payload && typeof msg.payload === 'object') {
|
||||
(msg.payload as { action_buttons?: ChatMessage['shipping_actions'] }).action_buttons = [];
|
||||
}
|
||||
msg.payload = {
|
||||
...(msg.payload && typeof msg.payload === 'object' ? msg.payload as Record<string, unknown> : {}),
|
||||
|
||||
@@ -304,10 +304,9 @@ export function useChatPage() {
|
||||
resetShippingConversationState = shipping.resetShippingConversationState;
|
||||
|
||||
/**
|
||||
* Drawer「重试所有失败」点击:仅打开确认弹窗,不立刻发请求。
|
||||
* 打开批次失败重试确认弹窗(会话摘要场景的兜底入口)。
|
||||
*/
|
||||
const openRetryFailedConfirmDialog = () => {
|
||||
if (shipping.retryingShippingPendingTasks.value) return;
|
||||
openRetryFailedConfirm(() => confirmRetryFailedTasks());
|
||||
};
|
||||
|
||||
@@ -315,15 +314,22 @@ export function useChatPage() {
|
||||
* 确认后执行批次失败任务重试,并以非阻塞 toast 反馈结果。
|
||||
* 核心逻辑:调用 useChatShipping.retryCurrentShippingBatchPendingTasks,成功后刷新已内置;仅补 toast。
|
||||
*/
|
||||
const retryingShippingPendingTasks = ref(false);
|
||||
const confirmRetryFailedTasks = async () => {
|
||||
const result = await shipping.retryCurrentShippingBatchPendingTasks();
|
||||
if (!result) return;
|
||||
showShippingToast(
|
||||
t('chat.shippingNoticeUi.retryFailedStarted', {
|
||||
started: result.started,
|
||||
skipped: result.skipped,
|
||||
}),
|
||||
);
|
||||
if (retryingShippingPendingTasks.value) return;
|
||||
retryingShippingPendingTasks.value = true;
|
||||
try {
|
||||
const result = await shipping.retryCurrentShippingBatchPendingTasks();
|
||||
if (!result) return;
|
||||
showShippingToast(
|
||||
t('chat.shippingNoticeUi.retryFailedStarted', {
|
||||
started: result.started,
|
||||
skipped: result.skipped,
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
retryingShippingPendingTasks.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const conversationApi = createChatPageConversationApi({
|
||||
@@ -398,8 +404,6 @@ export function useChatPage() {
|
||||
canOpenQueryPreview: queryPreview.canOpen,
|
||||
getQueryPreviewSummary: queryPreview.getSummary,
|
||||
openQueryPreviewDialog: queryPreview.openDialog,
|
||||
shippingActionButtonClass: shipping.shippingActionButtonClass,
|
||||
onShippingActionClick: shipping.handleShippingActionClick,
|
||||
});
|
||||
|
||||
const sendApi = createChatPageSendApi({
|
||||
@@ -610,26 +614,20 @@ export function useChatPage() {
|
||||
closeRetryFailedConfirm: dialogs.closeRetryFailedConfirm,
|
||||
handleRetryFailedConfirm: dialogs.handleRetryFailedConfirm,
|
||||
openRetryFailedConfirm: openRetryFailedConfirmDialog,
|
||||
retryingShippingPendingTasks,
|
||||
shippingToastMessage: dialogs.shippingToastMessage,
|
||||
clearShippingToast: dialogs.clearShippingToast,
|
||||
showChatRating,
|
||||
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
|
||||
showShippingProgressWorkspace: shipping.showShippingProgressWorkspace,
|
||||
shippingBatchSummary: shipping.shippingBatchSummary,
|
||||
shippingConversationWorkspace: shipping.shippingConversationWorkspace,
|
||||
activeShippingBatchNo: shipping.activeShippingBatchNo,
|
||||
focusedShippingTaskNo: shipping.focusedShippingTaskNo,
|
||||
shippingFocusReason: shipping.shippingFocusReason,
|
||||
shippingBatchTasks: shipping.shippingBatchTasks,
|
||||
activeShippingTaskDetail: shipping.activeShippingTaskDetail,
|
||||
shippingWorkspaceOpen: shipping.shippingWorkspaceOpen,
|
||||
retryingShippingPendingTasks: shipping.retryingShippingPendingTasks,
|
||||
getActiveOrderExtractionRunNo: shipping.getActiveOrderExtractionRunNo,
|
||||
shippingInventorySelectionActive: shipping.shippingInventorySelectionActive,
|
||||
shippingInventorySelectionTaskId: shipping.shippingInventorySelectionTaskId,
|
||||
switchShippingBatch: shipping.switchShippingBatch,
|
||||
switchShippingFocusTask: shipping.switchShippingFocusTask,
|
||||
clearShippingFocus: shipping.clearShippingFocus,
|
||||
handleShippingWorkspaceAction: shipping.handleShippingWorkspaceAction,
|
||||
retryCurrentShippingBatchPendingTasks: shipping.retryCurrentShippingBatchPendingTasks,
|
||||
queryShippingShortageDetails: shipping.queryShippingShortageDetails,
|
||||
selectShippingInventoryUploadTask: shipping.selectShippingInventoryUploadTask,
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
* features/chat/composables/useChatShipping.ts
|
||||
* 用途:发货通知聊天编排入口,组合 shipping/* 子模块并对 ChatView 暴露统一交互能力。
|
||||
* 依赖:shipping.api、shipping/ 下各 handler 工厂、chat.deps、chat.types、Vue refs/computed/watch。
|
||||
* 逻辑:上游由 ChatView/ChatPage 调用本 composable;本文件再把任务状态、动作刷新、文件上传、决策与发送拦截分发给 shipping 子模块。
|
||||
* 批次「重试所有失败」成功后不弹居中 msg.success,由页面级 toast 展示 started/skipped。
|
||||
* 逻辑:上游由 ChatView/ChatPage 调用本 composable;本文件维护会话任务摘要 + ui_state 同步,
|
||||
* 不再管理批次抽屉/焦点条/聊天履约写按钮(履约写改由任务处理工作台承接)。
|
||||
*/
|
||||
|
||||
import {
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
type Ref,
|
||||
} from 'vue';
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
import { agentUsesWorkspaceStepperProgress, isShippingNoticeAgent as resolveShippingNoticeAgent } from '@/shared/utils/agent-registry.utils';
|
||||
import { isShippingNoticeAgent as resolveShippingNoticeAgent } from '@/shared/utils/agent-registry.utils';
|
||||
import type { AgentRegistryFields } from '@/shared/utils/agent-registry.utils';
|
||||
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
|
||||
|
||||
@@ -34,9 +34,7 @@ import {
|
||||
getShippingMatchResultPayload,
|
||||
getShippingParseReviewPayload,
|
||||
sanitizeShippingConversationText,
|
||||
shippingActionButtonClass,
|
||||
} from '../shipping';
|
||||
import { reportShippingDebugEvent } from '../shipping/shippingDebugReporter';
|
||||
import { isShippingSpreadsheetFile } from '../shipping/shippingUploadPrompt';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
import {
|
||||
@@ -45,7 +43,6 @@ import {
|
||||
getWorkspaceShippingTask,
|
||||
listWorkspaceShippingCustomerOptions,
|
||||
confirmWorkspaceShippingCustomer,
|
||||
switchWorkspaceShippingBatchFocusTask,
|
||||
type ShippingBatchUiState,
|
||||
type ShippingBatchSummary,
|
||||
type ShippingConversationWorkspace,
|
||||
@@ -62,7 +59,7 @@ import {
|
||||
import type { ChatMessage, ChatRun, ChatSessionItem, ShippingMessageRecoveryPayload } from '../types/chat.types';
|
||||
import type { SendMessageLifecycleHooks } from './useChat';
|
||||
import type { ChatMessageSendResult } from '../types/chat-turn.types';
|
||||
import type { ChatUploadFileSpec, PendingAttachment, ShippingActionButton } from '../types/shipping.types';
|
||||
import type { ChatUploadFileSpec, PendingAttachment } from '../types/shipping.types';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
import { listChatMessages } from '../api/chat.api';
|
||||
|
||||
@@ -269,7 +266,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
|
||||
// ── 功能开关与 UI refs ────────────────────────────────────
|
||||
const isShippingNoticeAgent = computed(() => resolveShippingNoticeAgent(currentAgent.value));
|
||||
const showShippingProgressWorkspace = computed(() => agentUsesWorkspaceStepperProgress(currentAgent.value));
|
||||
const isShippingActionBusy = computed(() => {
|
||||
if (shippingActionBusy.value) return true;
|
||||
return hasActiveRunningChatRun(isThinking.value, activeRunId.value, runs.value);
|
||||
@@ -290,7 +286,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
return sanitizeShippingConversationText(stripReasoningPrelude(text), isShippingNoticeAgent.value);
|
||||
};
|
||||
|
||||
// ── 任务编号状态 ──────────────────────────────────────────
|
||||
// ── 任务编号状态(会话摘要同步,无抽屉/焦点条) ──────────────
|
||||
const shippingTaskIdFromQuery = computed(() => {
|
||||
const value = route.query.task_id;
|
||||
return typeof value === 'string' ? value.trim() : '';
|
||||
@@ -302,23 +298,14 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const resolvedShippingTaskId = ref('');
|
||||
const resolvedShippingBatchNo = ref('');
|
||||
const activeShippingBatchNo = ref('');
|
||||
const focusedShippingTaskNo = ref('');
|
||||
const shippingConversationWorkspace = ref<ShippingConversationWorkspace | null>(null);
|
||||
const shippingBatchSummary = ref<ShippingBatchSummary | null>(null);
|
||||
const shippingBatchTasks = ref<ShippingTaskSummary[]>([]);
|
||||
const shippingWorkspaceOpen = ref(false);
|
||||
const retryingShippingPendingTasks = ref(false);
|
||||
const activeShippingTaskDetail = ref<ShippingTaskDetail | null>(null);
|
||||
const shippingFocusReason = ref('');
|
||||
const autoResumedShippingTasks = ref<Record<string, boolean>>({});
|
||||
const lastConversationSyncKey = ref('');
|
||||
let shippingStatusPollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
// #region debug-point B:shipping-retry-chain
|
||||
const reportRetryRpaDebug = (hypothesisId: string, msg: string, data: Record<string, unknown>) =>
|
||||
reportShippingDebugEvent('useChatShipping.ts', hypothesisId, msg, data);
|
||||
// #endregion
|
||||
|
||||
const applyShippingBatchDetail = (
|
||||
detail: ShippingBatchUiState,
|
||||
fallbackBatchNo: string,
|
||||
@@ -469,10 +456,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
}
|
||||
if (taskNo) {
|
||||
resolvedShippingTaskId.value = taskNo;
|
||||
focusedShippingTaskNo.value = taskNo;
|
||||
if (!shippingFocusReason.value) {
|
||||
shippingFocusReason.value = t('chat.shippingNoticeUi.currentFocusDefaultReason');
|
||||
}
|
||||
}
|
||||
if (payload.shipping_ui_state && taskNo) {
|
||||
activeShippingTaskDetail.value = {
|
||||
@@ -520,56 +503,11 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
applyResolvedShippingMessageRecovery(resolveShippingMessageRecoveryPayload(message))
|
||||
);
|
||||
|
||||
const switchShippingFocusTask = async (taskNo: string) => {
|
||||
const batchNo = getActiveShippingBatchNo();
|
||||
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
|
||||
// #region debug-point C:switch-focus-entry
|
||||
void reportRetryRpaDebug('C', 'switchShippingFocusTask entry', {
|
||||
batchNo,
|
||||
normalizedTaskNo,
|
||||
activeBatchNo: activeShippingBatchNo.value,
|
||||
resolvedBatchNo: resolvedShippingBatchNo.value,
|
||||
routeBatchNo: shippingBatchNoFromQuery.value,
|
||||
});
|
||||
// #endregion
|
||||
if (!batchNo || !normalizedTaskNo) {
|
||||
// #region debug-point C:switch-focus-guard
|
||||
void reportRetryRpaDebug('C', 'switchShippingFocusTask guard returned false', {
|
||||
batchNo,
|
||||
normalizedTaskNo,
|
||||
});
|
||||
// #endregion
|
||||
return false;
|
||||
}
|
||||
await switchWorkspaceShippingBatchFocusTask(batchNo, normalizedTaskNo);
|
||||
resolvedShippingTaskId.value = normalizedTaskNo;
|
||||
focusedShippingTaskNo.value = normalizedTaskNo;
|
||||
shippingFocusReason.value = t('chat.shippingNoticeUi.currentFocusDefaultReason');
|
||||
if (shippingBatchSummary.value) {
|
||||
shippingBatchSummary.value = {
|
||||
...shippingBatchSummary.value,
|
||||
current_focus_task_no: normalizedTaskNo,
|
||||
};
|
||||
}
|
||||
await syncShippingBatchSummary(batchNo);
|
||||
await syncShippingConversationWorkspace();
|
||||
await syncActiveShippingTaskDetail(normalizedTaskNo);
|
||||
await refreshShippingActions();
|
||||
// #region debug-point C:switch-focus-success
|
||||
void reportRetryRpaDebug('C', 'switchShippingFocusTask success', {
|
||||
batchNo,
|
||||
normalizedTaskNo,
|
||||
resolvedTaskId: resolvedShippingTaskId.value,
|
||||
});
|
||||
// #endregion
|
||||
return true;
|
||||
};
|
||||
|
||||
const clearShippingFocus = () => {
|
||||
focusedShippingTaskNo.value = '';
|
||||
shippingFocusReason.value = '';
|
||||
};
|
||||
|
||||
/**
|
||||
* 切换会话上传摘要中的活动批次(只读同步,无焦点条/抽屉写操作)。
|
||||
* @param batchNo - 目标批次号
|
||||
* @returns 是否切换成功
|
||||
*/
|
||||
const switchShippingBatch = async (batchNo: string) => {
|
||||
const normalizedBatchNo = String(batchNo || '').trim();
|
||||
if (!normalizedBatchNo) return false;
|
||||
@@ -584,11 +522,9 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const nextFocusState = resolveShippingBatchFocusState(
|
||||
shippingBatchSummary.value,
|
||||
shippingBatchTasks.value,
|
||||
t('chat.shippingNoticeUi.currentFocusDefaultReason'),
|
||||
'',
|
||||
);
|
||||
const nextTaskNo = nextFocusState.taskNo;
|
||||
focusedShippingTaskNo.value = nextFocusState.taskNo;
|
||||
shippingFocusReason.value = nextFocusState.focusReason;
|
||||
if (nextTaskNo) {
|
||||
resolvedShippingTaskId.value = nextTaskNo;
|
||||
await syncActiveShippingTaskDetail(nextTaskNo);
|
||||
@@ -601,7 +537,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
* 清空当前聊天页绑定的发货任务上下文。
|
||||
*
|
||||
* 核心逻辑:在新建对话、切换 Agent 或离开发货任务场景时,主动清掉批次/任务/上传缓存,
|
||||
* 避免顶部 Stepper、列表展开态和待上传库存文件残留到下一次新会话。
|
||||
* 避免会话摘要和待上传库存文件残留到下一次新会话。
|
||||
*/
|
||||
const resetShippingConversationState = () => {
|
||||
shippingAutoFlowRequested.value = false;
|
||||
@@ -613,13 +549,9 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
resolvedShippingTaskId.value = '';
|
||||
resolvedShippingBatchNo.value = '';
|
||||
activeShippingBatchNo.value = '';
|
||||
focusedShippingTaskNo.value = '';
|
||||
shippingFocusReason.value = '';
|
||||
shippingConversationWorkspace.value = null;
|
||||
shippingBatchSummary.value = null;
|
||||
shippingBatchTasks.value = [];
|
||||
shippingWorkspaceOpen.value = false;
|
||||
retryingShippingPendingTasks.value = false;
|
||||
activeShippingTaskDetail.value = null;
|
||||
lastConversationSyncKey.value = '';
|
||||
};
|
||||
@@ -651,7 +583,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
shippingBatchSummary.value?.current_focus_task_no
|
||||
|| shippingBatchSummary.value?.process_summary?.current_task_no
|
||||
|| shippingBatchTasks.value[0]?.task_no
|
||||
|| focusedShippingTaskNo.value
|
||||
|| resolvedShippingTaskId.value
|
||||
|| '',
|
||||
).trim();
|
||||
@@ -770,7 +701,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const resolveShippingTaskForShortageQuery = async (taskNo?: string) => {
|
||||
const normalizedTaskNo = String(
|
||||
taskNo
|
||||
|| focusedShippingTaskNo.value
|
||||
|| getActiveBatchTaskId()
|
||||
|| getActiveShippingTaskId()
|
||||
|| '',
|
||||
@@ -1211,10 +1141,11 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
|
||||
onNoticeBatchConversationChanging(nextId, prevId);
|
||||
shippingIntakes.stopPolling();
|
||||
shippingOrderExtractionRuns.stopPolling();
|
||||
if (nextId && nextId !== prevId) {
|
||||
void shippingIntakes.restoreForConversation(nextId);
|
||||
void shippingOrderExtractionRuns.restoreForConversation(nextId);
|
||||
} else {
|
||||
shippingOrderExtractionRuns.clearActiveRun();
|
||||
}
|
||||
if (prevId !== nextId) {
|
||||
resolvedShippingTaskId.value = '';
|
||||
@@ -1226,38 +1157,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
}
|
||||
};
|
||||
|
||||
const WORKSPACE_DIRECT_PICKER_ACTION_IDS = new Set(['upload_inventory_file', 'replace_notice_file']);
|
||||
|
||||
/**
|
||||
* 从右侧批次工作台触发指定任务的后端状态机动作。
|
||||
*
|
||||
* 核心逻辑:普通动作先把 batch focus 切到目标 task,再复用聊天气泡的统一 action.id 分发器;
|
||||
* 文件选择类动作必须先同步打开 picker,再异步切焦点,避免浏览器丢失用户点击手势。
|
||||
* @param taskNo - 被点击按钮所属的任务编号
|
||||
* @param action - 后端 `ui_state.action_buttons` 返回的动作按钮
|
||||
* @returns 是否成功进入统一动作处理链
|
||||
*/
|
||||
const handleShippingWorkspaceAction = async (taskNo: string, action: ShippingActionButton) => {
|
||||
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
|
||||
if (!normalizedTaskNo || !action?.id || !isShippingNoticeAgent.value) return false;
|
||||
if (isShippingActionBusy.value) {
|
||||
msg.warning(t('chat.shippingNoticeUi.actionBusyHint'));
|
||||
return false;
|
||||
}
|
||||
if (WORKSPACE_DIRECT_PICKER_ACTION_IDS.has(String(action.id || ''))) {
|
||||
await handleShippingMenuAction(action, undefined, { taskId: normalizedTaskNo });
|
||||
void switchShippingFocusTask(normalizedTaskNo);
|
||||
return true;
|
||||
}
|
||||
const switched = await switchShippingFocusTask(normalizedTaskNo);
|
||||
if (!switched) return false;
|
||||
await handleShippingMenuAction(action, undefined, { taskId: normalizedTaskNo });
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 重试当前聚焦批次中可恢复的失败/排队任务。
|
||||
* 核心逻辑:调 workspace retry-pending → 刷新会话工作台/批次摘要/动作;成功反馈交给页面级非阻塞 toast,避免居中成功弹窗。
|
||||
* 重试当前聚焦批次中可恢复的失败/排队任务(供页面级确认弹窗调用;Chat 本身不再挂批次抽屉按钮)。
|
||||
* @returns 成功时返回 started/skipped;失败或跳过时返回 null
|
||||
*/
|
||||
const retryCurrentShippingBatchPendingTasks = async (): Promise<{
|
||||
@@ -1265,12 +1166,11 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
skipped: number;
|
||||
} | null> => {
|
||||
const batchNo = getActiveShippingBatchNo();
|
||||
if (!batchNo || retryingShippingPendingTasks.value) return null;
|
||||
if (!batchNo) return null;
|
||||
if (isShippingActionBusy.value) {
|
||||
msg.warning(t('chat.shippingNoticeUi.actionBusyHint'));
|
||||
return null;
|
||||
}
|
||||
retryingShippingPendingTasks.value = true;
|
||||
try {
|
||||
const { retryWorkspaceShippingBatchPending } = await import('@/features/chat/api/shipping.api');
|
||||
const result = await retryWorkspaceShippingBatchPending(batchNo);
|
||||
@@ -1284,8 +1184,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('chat.shippingNoticeUi.retryFailed'));
|
||||
return null;
|
||||
} finally {
|
||||
retryingShippingPendingTasks.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1342,10 +1240,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
};
|
||||
|
||||
/**
|
||||
* 启停发货批次状态短轮询。
|
||||
* 启停发货会话状态短轮询。
|
||||
*
|
||||
* 核心逻辑:聊天流当前没有 shipping 专属 SSE;因此在存在任务/批次上下文时每 3 秒补拉一次,
|
||||
* 让顶部 Stepper、批次统计和动作按钮能在后端异步状态变化后自动更新。
|
||||
* 让右侧会话摘要与通知态 ui_state 能在后端异步状态变化后自动更新。
|
||||
*/
|
||||
const restartShippingStatusPolling = () => {
|
||||
if (shippingStatusPollTimer) {
|
||||
@@ -1444,7 +1342,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
return {
|
||||
shippingBindSend,
|
||||
isShippingNoticeAgent,
|
||||
showShippingProgressWorkspace,
|
||||
prepareMarkdownDisplayText,
|
||||
shippingAutoFlowRequested,
|
||||
shippingInventoryPickerRef,
|
||||
@@ -1457,21 +1354,14 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
shippingBatchNoFromQuery,
|
||||
resolvedShippingBatchNo,
|
||||
activeShippingBatchNo,
|
||||
focusedShippingTaskNo,
|
||||
shippingFocusReason,
|
||||
shippingConversationWorkspace,
|
||||
shippingBatchSummary,
|
||||
shippingBatchTasks,
|
||||
shippingWorkspaceOpen,
|
||||
isShippingActionBusy,
|
||||
retryingShippingPendingTasks,
|
||||
activeShippingTaskDetail,
|
||||
getCurrentShippingChatContext,
|
||||
getActiveShippingBatchNo,
|
||||
switchShippingBatch,
|
||||
switchShippingFocusTask,
|
||||
clearShippingFocus,
|
||||
handleShippingWorkspaceAction,
|
||||
retryCurrentShippingBatchPendingTasks,
|
||||
queryShippingShortageDetails,
|
||||
resetShippingConversationState,
|
||||
@@ -1487,7 +1377,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
finalizeShippingAssistantMessage,
|
||||
selectShippingInventoryUploadTask,
|
||||
cancelShippingInventoryTaskSelection,
|
||||
shippingActionButtonClass,
|
||||
shippingSuggestedPrompt,
|
||||
useShippingSuggestedPrompt,
|
||||
enqueueShippingNoticeFiles: shippingIntakes.enqueueNoticeFiles,
|
||||
@@ -1496,6 +1385,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
retryShippingNoticeAttachment: shippingIntakes.retryNoticeAttachment,
|
||||
retryOrderExtractionRun: shippingOrderExtractionRuns.retryRun,
|
||||
reparseOrderExtractionRun: shippingOrderExtractionRuns.reparseRun,
|
||||
getActiveOrderExtractionRunNo: shippingOrderExtractionRuns.getActiveRunNo,
|
||||
shippingNoticeAllReadyForConfirmation: shippingIntakes.allReadyForConfirmation,
|
||||
setShippingCandidateSelected,
|
||||
resolveShippingCandidateDuplicate,
|
||||
|
||||
@@ -43,8 +43,6 @@ function createContext(
|
||||
canOpenQueryPreview: () => false,
|
||||
getQueryPreviewSummary: () => '',
|
||||
openQueryPreviewDialog: () => undefined,
|
||||
shippingActionButtonClass: () => '',
|
||||
onShippingActionClick: () => undefined,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -83,8 +83,6 @@ export interface ChatPageMarkdownContext {
|
||||
canOpenQueryPreview: ChatMessageBubbleHandlers['canOpenQueryPreview'];
|
||||
getQueryPreviewSummary: ChatMessageBubbleHandlers['getQueryPreviewSummary'];
|
||||
openQueryPreviewDialog: ChatMessageBubbleHandlers['openQueryPreviewDialog'];
|
||||
shippingActionButtonClass: ChatMessageBubbleHandlers['shippingActionButtonClass'];
|
||||
onShippingActionClick: ChatMessageBubbleHandlers['onShippingActionClick'];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -461,8 +459,6 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
canOpenQueryPreview: ctx.canOpenQueryPreview,
|
||||
getQueryPreviewSummary: ctx.getQueryPreviewSummary,
|
||||
openQueryPreviewDialog: ctx.openQueryPreviewDialog,
|
||||
shippingActionButtonClass: ctx.shippingActionButtonClass,
|
||||
onShippingActionClick: ctx.onShippingActionClick,
|
||||
getDisplayRetrieverResources: (msgItem) => ctx.getDisplayRetrieverResources(msgItem as unknown as Record<string, unknown>),
|
||||
getSourceLinks: (resources) => ctx.getSourceLinks(resources),
|
||||
shouldExpandSourceDetails: (msgItem) => ctx.shouldExpandSourceDetails(msgItem as unknown as Record<string, unknown>),
|
||||
|
||||
@@ -1,127 +0,0 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingWorkspaceActions.spec.ts
|
||||
* 用途:锁定聊天页右侧批次工作台的业务按钮解析契约。
|
||||
* 依赖:vitest、shippingWorkspaceActions、shipping.api.types。
|
||||
* 逻辑:验证终态任务不渲染业务按钮,且非终态任务只消费后端 `ui_state.action_buttons`。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { ShippingTaskSummary } from '../types/shipping.api.types';
|
||||
import {
|
||||
isShippingWorkspaceTerminalTask,
|
||||
resolveShippingWorkspaceActionButtons,
|
||||
} from './shippingWorkspaceActions';
|
||||
|
||||
const createTask = (overrides: Partial<ShippingTaskSummary> = {}): ShippingTaskSummary => ({
|
||||
id: 1,
|
||||
task_no: 'SN-UNIT-001',
|
||||
source_type: 'manual',
|
||||
process_status: 'matched',
|
||||
ui_state: {
|
||||
task_no: 'SN-UNIT-001',
|
||||
process_status: 'matched',
|
||||
steps: [],
|
||||
summary: {},
|
||||
action_buttons: [],
|
||||
},
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('shippingWorkspaceActions', () => {
|
||||
it('treats uploaded/completed/closed/rejected tasks as terminal workspace tasks', () => {
|
||||
expect(isShippingWorkspaceTerminalTask(createTask({ process_status: 'uploaded' }))).toBe(true);
|
||||
expect(isShippingWorkspaceTerminalTask(createTask({ process_status: 'completed' }))).toBe(true);
|
||||
expect(isShippingWorkspaceTerminalTask(createTask({ process_status: 'closed' }))).toBe(true);
|
||||
expect(isShippingWorkspaceTerminalTask(createTask({ process_status: 'rejected' }))).toBe(true);
|
||||
expect(isShippingWorkspaceTerminalTask(createTask({ process_status: 'matched' }))).toBe(false);
|
||||
});
|
||||
|
||||
it('hides business buttons for completed tasks even if ui_state.action_buttons exists', () => {
|
||||
const task = createTask({
|
||||
process_status: 'completed',
|
||||
ui_state: {
|
||||
task_no: 'SN-UNIT-001',
|
||||
process_status: 'completed',
|
||||
steps: [],
|
||||
summary: {},
|
||||
action_buttons: [
|
||||
{
|
||||
id: 'retry_rpa',
|
||||
label: '重新获取库存',
|
||||
message: '重新获取库存',
|
||||
variant: 'primary',
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(resolveShippingWorkspaceActionButtons(task)).toEqual([]);
|
||||
});
|
||||
|
||||
it('hides business buttons for rejected tasks even if ui_state.action_buttons exists', () => {
|
||||
const task = createTask({
|
||||
process_status: 'rejected',
|
||||
ui_state: {
|
||||
task_no: 'SN-UNIT-001',
|
||||
process_status: 'rejected',
|
||||
steps: [],
|
||||
summary: {},
|
||||
action_buttons: [
|
||||
{
|
||||
id: 'retry_upload',
|
||||
label: '重试上传',
|
||||
message: '重试上传',
|
||||
variant: 'danger',
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(resolveShippingWorkspaceActionButtons(task)).toEqual([]);
|
||||
});
|
||||
|
||||
it('uses backend ui_state.action_buttons as the only business button source for non-completed tasks', () => {
|
||||
const task = createTask({
|
||||
process_status: 'waiting_inventory',
|
||||
pending_human_reason: 'rpa_exhausted',
|
||||
ui_state: {
|
||||
task_no: 'SN-UNIT-001',
|
||||
process_status: 'waiting_inventory',
|
||||
steps: [],
|
||||
summary: {},
|
||||
action_buttons: [
|
||||
{
|
||||
id: 'upload_inventory_file',
|
||||
label: '上传库存文件',
|
||||
message: '请上传库存文件',
|
||||
variant: 'primary',
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(resolveShippingWorkspaceActionButtons(task)).toEqual([
|
||||
{
|
||||
id: 'upload_inventory_file',
|
||||
label: '上传库存文件',
|
||||
message: '请上传库存文件',
|
||||
variant: 'primary',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns empty array when non-completed task has no backend action_buttons', () => {
|
||||
const task = createTask({
|
||||
process_status: 'waiting_inventory',
|
||||
pending_human_reason: 'rpa_exhausted',
|
||||
ui_state: {
|
||||
task_no: 'SN-UNIT-001',
|
||||
process_status: 'waiting_inventory',
|
||||
steps: [],
|
||||
summary: {},
|
||||
action_buttons: [],
|
||||
},
|
||||
});
|
||||
|
||||
expect(resolveShippingWorkspaceActionButtons(task)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,32 +0,0 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingWorkspaceActions.ts
|
||||
* 用途:集中封装聊天页右侧批次工作台的业务按钮解析规则。
|
||||
* 依赖:shipping.api.types 任务 DTO 类型。
|
||||
* 逻辑:由 ShippingBatchWorkspaceDrawer 调用;统一约束终态任务不渲染业务按钮,且非终态任务只消费后端 `ui_state.action_buttons`。
|
||||
*/
|
||||
import type { ShippingChatAction, ShippingTaskDetail, ShippingTaskSummary } from '../api/shipping.api';
|
||||
|
||||
const TERMINAL_PROCESS_STATUSES = new Set(['uploaded', 'completed', 'closed', 'rejected']);
|
||||
|
||||
/**
|
||||
* 判断工作台任务是否已进入终态。
|
||||
* 核心逻辑:终态任务只允许查看/切换,不再暴露任何后端业务动作按钮。
|
||||
* @param task - 工作台任务摘要或详情
|
||||
* @returns 是否属于终态任务
|
||||
*/
|
||||
export const isShippingWorkspaceTerminalTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
TERMINAL_PROCESS_STATUSES.has(String(task.process_status || '').trim());
|
||||
|
||||
/**
|
||||
* 解析工作台应渲染的业务按钮列表。
|
||||
* 核心逻辑:终态任务直接返回空数组;其他任务只信任后端 `ui_state.action_buttons`,
|
||||
* 不再根据 `process_status / pending_human_reason` 在前端二次推导。
|
||||
* @param task - 工作台任务摘要或详情
|
||||
* @returns 可渲染的业务动作按钮列表
|
||||
*/
|
||||
export const resolveShippingWorkspaceActionButtons = (
|
||||
task: ShippingTaskSummary | ShippingTaskDetail,
|
||||
): ShippingChatAction[] => {
|
||||
if (isShippingWorkspaceTerminalTask(task)) return [];
|
||||
return Array.isArray(task.ui_state?.action_buttons) ? task.ui_state.action_buttons : [];
|
||||
};
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* useChatShippingRefresh.spec.ts
|
||||
* 用途:验证发货动作按钮刷新时的任务定位优先级与 focus 切换刷新保护。
|
||||
* 用途:验证发货 UI State 刷新只同步通知态,不再把 action_buttons 映射为消息按钮。
|
||||
* 依赖:vitest、vue refs、useChatShippingRefresh 纯函数导出。
|
||||
* 逻辑:覆盖任务编号解析优先级,以及批次 focus 变化后应先锁定新 task 再拉取按钮。
|
||||
* 逻辑:覆盖任务编号解析优先级,以及刷新后 shipping_actions 始终清空。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
@@ -39,7 +39,7 @@ describe('useChatShippingRefresh', () => {
|
||||
})).toBe('');
|
||||
});
|
||||
|
||||
it('locks onto the latest focus task before refreshing chat buttons', async () => {
|
||||
it('syncs ui_state for notifications without attaching chat action buttons', async () => {
|
||||
getWorkspaceShippingTaskUiState.mockResolvedValue({
|
||||
task_no: 'SN-FOCUS-B',
|
||||
batch_no: 'SB-FOCUS-001',
|
||||
@@ -54,6 +54,7 @@ describe('useChatShippingRefresh', () => {
|
||||
title: '可生成发货文件',
|
||||
message: '库存匹配已满足发货条件,可以生成发货文件。',
|
||||
error_message: null,
|
||||
entry_surface: 'task_workbench',
|
||||
},
|
||||
action_buttons: [
|
||||
{
|
||||
@@ -94,13 +95,12 @@ describe('useChatShippingRefresh', () => {
|
||||
await refreshShippingActions();
|
||||
|
||||
expect(resolvedShippingTaskId.value).toBe('SN-FOCUS-B');
|
||||
expect(getWorkspaceShippingTaskUiState).toHaveBeenCalledTimes(1);
|
||||
expect(getWorkspaceShippingTaskUiState).toHaveBeenCalledWith('SN-FOCUS-B');
|
||||
expect(messages.value[0].shipping_ui_state?.task_no).toBe('SN-FOCUS-B');
|
||||
expect(messages.value[0].shipping_actions?.map((item) => item.id)).toEqual(['generate_excel']);
|
||||
expect(messages.value[0].shipping_actions).toBeUndefined();
|
||||
});
|
||||
|
||||
it('treats backend ui_state.action_buttons as the only button source when api refresh succeeds', async () => {
|
||||
it('clears legacy shipping_actions even when api returns action_buttons', async () => {
|
||||
getWorkspaceShippingTaskUiState.mockResolvedValue({
|
||||
task_no: 'SN-SOURCE-001',
|
||||
batch_no: 'SB-SOURCE-001',
|
||||
@@ -163,8 +163,8 @@ describe('useChatShippingRefresh', () => {
|
||||
|
||||
await refreshShippingActions();
|
||||
|
||||
expect(messages.value[0].shipping_actions?.map((item) => item.id)).toEqual(['download_excel']);
|
||||
expect(messages.value[0].shipping_ui_state?.action_buttons?.map((item) => item.id)).toEqual(['download_excel']);
|
||||
expect(messages.value[0].shipping_actions).toBeUndefined();
|
||||
expect(messages.value[0].shipping_ui_state?.summary?.title).toBe('可生成发货文件');
|
||||
});
|
||||
|
||||
it('does not guess a task id from history metadata when no explicit anchor exists', async () => {
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingRefresh.ts
|
||||
* 用途:刷新聊天区发货通知 UI State,把后端状态机 action_buttons 同步到消息气泡。
|
||||
* 用途:刷新聊天区发货通知 UI State,同步后端 summary/checkpoint 到消息,供通知展示。
|
||||
* 依赖:shipping.api、shippingTaskId、shippingNoticeActions 常量、chat.types。
|
||||
* 逻辑:由 useChatShipping 调用本文件;本文件只读取后端 /ui-state,不再从会话标题猜任务号或从 Dify 正文解析按钮。
|
||||
* 逻辑:由 useChatShipping 调用本文件;只读取后端 /ui-state 并净化正文中的动作菜单文案,不再把 action_buttons 映射为消息按钮。
|
||||
*/
|
||||
import { getWorkspaceShippingTaskUiState } from '@/features/chat/api/shipping.api';
|
||||
import { SHIPPING_TERMINAL_CHECKPOINTS } from '@/constants/shippingNoticeActions';
|
||||
import { findLatestShippingTaskId } from './shippingTaskId';
|
||||
import { stripShippingActionListByButtons, stripShippingPlainActionMenu } from './shippingText';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ShippingActionButton } from '../types/shipping.types';
|
||||
import type { ShippingTaskUiState } from '../types/shipping.api.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
@@ -27,7 +26,7 @@ export interface ShippingRefreshContext {
|
||||
* 解析当前聊天页最可靠的发货任务编号。
|
||||
*
|
||||
* 核心逻辑:优先使用批次当前焦点任务,其次才回退到消息内嵌任务号、已解析状态和路由参数;
|
||||
* 禁止再按 conversation 标题“猜”一票,避免多票会话把动作按钮挂错任务。
|
||||
* 禁止再按 conversation 标题“猜”一票,避免多票会话把状态挂错任务。
|
||||
* @param params - 当前聊天页中可用的任务定位线索
|
||||
* @returns 可信的任务编号;无法明确定位时返回空字符串
|
||||
*/
|
||||
@@ -57,11 +56,12 @@ export function assistantMessageHasLaterUserReply(msgs: Array<{ role?: string }>
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建发货通知动作按钮刷新器。
|
||||
* 创建发货通知 UI State 刷新器。
|
||||
*
|
||||
* 核心逻辑:按 taskId 拉取后端 ui_state/action_buttons,并在终态 checkpoint 清空旧按钮。
|
||||
* 核心逻辑:按 taskId 拉取后端 ui_state,写回 `shipping_ui_state` 供摘要/通知展示,
|
||||
* 并清空消息上的 `shipping_actions`(Chat 不再渲染履约写按钮)。
|
||||
* @param ctx - 发货通知聊天上下文
|
||||
* @returns 动作刷新函数
|
||||
* @returns 状态刷新函数
|
||||
*/
|
||||
export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
let shippingActionsRequestSeq = 0;
|
||||
@@ -128,43 +128,33 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
return;
|
||||
}
|
||||
msgs.forEach((rawMsg, index) => {
|
||||
const chatMsg = rawMsg as ChatMessage & {
|
||||
shipping_actions_used?: boolean;
|
||||
shipping_actions?: ShippingActionButton[];
|
||||
};
|
||||
if (chatMsg.role !== 'assistant' || chatMsg.shipping_actions_used) {
|
||||
const chatMsg = rawMsg as ChatMessage;
|
||||
if (chatMsg.role !== 'assistant') {
|
||||
return;
|
||||
}
|
||||
if (chatMsg.type && !['text', undefined].includes(chatMsg.type)) {
|
||||
chatMsg.shipping_actions = undefined;
|
||||
// Chat 只保留通知态:始终清空履约按钮,仅同步最新 ui_state summary。
|
||||
chatMsg.shipping_actions = undefined;
|
||||
if (chatMsg.type && !['text', undefined, 'shipping-match-result'].includes(chatMsg.type)) {
|
||||
return;
|
||||
}
|
||||
if (assistantMessageHasLaterUserReply(msgs, index) && index !== targetAssistantIndex) {
|
||||
chatMsg.shipping_actions = undefined;
|
||||
return;
|
||||
}
|
||||
let buttons: ShippingActionButton[] = [];
|
||||
let cleanedText = stripShippingPlainActionMenu(String(chatMsg.content || ''));
|
||||
if (index === targetAssistantIndex) {
|
||||
if (apiState?.action_buttons?.length) {
|
||||
buttons = apiState.action_buttons;
|
||||
chatMsg.shipping_ui_state = apiState;
|
||||
} else if (!apiResolved && chatMsg.shipping_ui_state?.action_buttons?.length) {
|
||||
buttons = chatMsg.shipping_ui_state.action_buttons;
|
||||
if (index === targetAssistantIndex && apiState) {
|
||||
chatMsg.shipping_ui_state = apiState;
|
||||
if (apiState.action_buttons?.length) {
|
||||
cleanedText = stripShippingActionListByButtons(cleanedText, apiState.action_buttons);
|
||||
}
|
||||
if (buttons.length) {
|
||||
cleanedText = stripShippingActionListByButtons(cleanedText, buttons);
|
||||
}
|
||||
} else {
|
||||
cleanedText = stripShippingPlainActionMenu(String(chatMsg.content || ''));
|
||||
} else if (!apiResolved && chatMsg.shipping_ui_state?.action_buttons?.length) {
|
||||
cleanedText = stripShippingActionListByButtons(
|
||||
cleanedText,
|
||||
chatMsg.shipping_ui_state.action_buttons,
|
||||
);
|
||||
}
|
||||
if (cleanedText !== String(chatMsg.content || '').trim()) {
|
||||
chatMsg.content = cleanedText;
|
||||
}
|
||||
if (chatMsg.type === 'shipping-match-result' && chatMsg.payload && typeof chatMsg.payload === 'object') {
|
||||
(chatMsg.payload as { action_buttons?: ShippingActionButton[] }).action_buttons = buttons;
|
||||
(chatMsg.payload as { action_buttons?: unknown[] }).action_buttons = [];
|
||||
}
|
||||
chatMsg.shipping_actions = buttons.length ? buttons : undefined;
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/chat/shipping/useShippingOrderExtractionRuns.ts
|
||||
* 用途:把货代订单抽取作为独立 Run 启动、轮询并投影到聊天状态消息。
|
||||
* 依赖:shipping.api Run 接口、chat.types、Vue refs。
|
||||
* 逻辑:发送处理器调用 startRun;本模块持久化本地消息并轮询 Run,终态后刷新 Intake、批次工作台与动作。
|
||||
* 逻辑:发送处理器调用 startRun;本模块持久化本地消息并轮询 Run;终态后仍保留 run_no 供右侧「本次处理」面板。
|
||||
*/
|
||||
import { getCurrentInstance, onBeforeUnmount, type ComputedRef, type Ref } from 'vue';
|
||||
import {
|
||||
@@ -48,6 +48,11 @@ export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtraction
|
||||
reviewRequiredDocuments: Number(run.summary?.review_required_documents || 0),
|
||||
failedDocuments: Number(run.summary?.failed_documents || 0),
|
||||
candidateCount: Number(run.summary?.candidate_count || 0),
|
||||
openedExistingCount: Number(
|
||||
run.summary?.opened_existing_documents
|
||||
|| run.result?.opened_existing_count
|
||||
|| 0,
|
||||
),
|
||||
},
|
||||
currentActivity: run.current_activity
|
||||
? {
|
||||
@@ -119,15 +124,21 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
let pollGeneration = 0;
|
||||
const persistedSignatures = new Map<string, string>();
|
||||
|
||||
/** 停止当前 Run 短轮询;终态、切会话和组件卸载都会调用。 */
|
||||
/** 停止当前 Run 短轮询;切会话和组件卸载时再清空 activeRunNo。 */
|
||||
const stopPolling = () => {
|
||||
if (pollTimer) clearTimeout(pollTimer);
|
||||
requestController?.abort();
|
||||
requestController = null;
|
||||
pollTimer = null;
|
||||
activeRunNo = '';
|
||||
pollFailureCount = 0;
|
||||
pollGeneration += 1;
|
||||
// 注意:终态(含需复核)后仍保留 activeRunNo,供右侧「本次处理」面板继续展示。
|
||||
};
|
||||
|
||||
/** 切会话时清空活动 Run,避免串会话。 */
|
||||
const clearActiveRun = () => {
|
||||
stopPolling();
|
||||
activeRunNo = '';
|
||||
};
|
||||
|
||||
/** 网络轮询失败只更新本地提示,不得把后台业务 Run 误判为失败。 */
|
||||
@@ -421,9 +432,9 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
}));
|
||||
};
|
||||
|
||||
/** 刷新或进入既有会话时恢复最新 Run;活动 Run 继续轮询,终态只恢复状态卡。 */
|
||||
/** 刷新或进入既有会话时恢复最新 Run;活动 Run 继续轮询,终态只恢复状态卡并保留 run_no 供右侧面板。 */
|
||||
const restoreForConversation = async (conversationId: string): Promise<void> => {
|
||||
stopPolling();
|
||||
clearActiveRun();
|
||||
try {
|
||||
const generation = pollGeneration;
|
||||
const request = createRequestController(generation);
|
||||
@@ -431,6 +442,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
const latest = items[0];
|
||||
if (!latest) return;
|
||||
activeRunNo = latest.run_no;
|
||||
const reviewAttachments = ACTIVE_RUN_STATUSES.has(latest.status)
|
||||
? undefined
|
||||
: await refreshTerminalFacts(latest);
|
||||
@@ -446,6 +458,15 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
}
|
||||
};
|
||||
|
||||
if (getCurrentInstance()) onBeforeUnmount(stopPolling);
|
||||
return { startRun, retryRun, reparseRun, restoreForConversation, stopPolling, updateCandidateReviewSnapshot, getActiveRunNo: () => activeRunNo };
|
||||
if (getCurrentInstance()) onBeforeUnmount(clearActiveRun);
|
||||
return {
|
||||
startRun,
|
||||
retryRun,
|
||||
reparseRun,
|
||||
restoreForConversation,
|
||||
stopPolling,
|
||||
clearActiveRun,
|
||||
updateCandidateReviewSnapshot,
|
||||
getActiveRunNo: () => activeRunNo,
|
||||
};
|
||||
}
|
||||
@@ -38,6 +38,8 @@ export interface ShippingOrderExtractionStateSummary {
|
||||
reviewRequiredDocuments: number;
|
||||
failedDocuments: number;
|
||||
candidateCount: number;
|
||||
/** 解析阶段已关联已有任务的份数(open_existing) */
|
||||
openedExistingCount?: number;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionCurrentActivityState {
|
||||
|
||||
@@ -120,6 +120,18 @@ export interface ShippingTaskSummary {
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
ui_state?: ShippingTaskUiState;
|
||||
/** 待办分类:review | exception | manual_upload | in_progress | done */
|
||||
todo_category?: string | null;
|
||||
/** task | review_case;复核项无 task_no,用 review_run_no 深链 */
|
||||
item_kind?: 'task' | 'review_case' | string | null;
|
||||
todo_ref?: string | null;
|
||||
review_run_no?: string | null;
|
||||
review_case_no?: string | null;
|
||||
review_case_status?: string | null;
|
||||
owner_agent_id?: number | null;
|
||||
/** 当前用户是否可写;管理员查看他人任务时为 false */
|
||||
can_handle?: boolean;
|
||||
created_by?: number | null;
|
||||
/** 业务版本号;修订建单时递增 */
|
||||
document_version?: number;
|
||||
supersedes_task_no?: string | null;
|
||||
@@ -397,6 +409,7 @@ export interface ShippingTaskUiState {
|
||||
task_no: string;
|
||||
batch_no?: string | null;
|
||||
checkpoint?: string | null;
|
||||
checkpoint_kind?: 'auto_continue' | 'must_human' | 'wait_manual_upload' | 'complete' | string | null;
|
||||
process_status: string;
|
||||
review_status?: string | null;
|
||||
pending_human_reason?: string | null;
|
||||
@@ -409,6 +422,15 @@ export interface ShippingTaskUiState {
|
||||
error_message?: string | null;
|
||||
/** 文件解析阶段汇总的全部待处理问题(库存源 + 解析 warnings 等) */
|
||||
issues?: string[] | null;
|
||||
stage?: string | null;
|
||||
checkpoint_kind?: string | null;
|
||||
current_todo?: string | null;
|
||||
pause_reason?: string | null;
|
||||
pause_reason_code?: string | null;
|
||||
next_auto_step?: string | null;
|
||||
event_at?: string | null;
|
||||
entry_surface?: 'review_workbench' | 'task_workbench' | 'none' | string | null;
|
||||
allowed_actions?: string[] | null;
|
||||
};
|
||||
action_buttons: ShippingChatAction[];
|
||||
updated_at?: string | null;
|
||||
@@ -441,6 +463,7 @@ export interface ShippingBatchSummary {
|
||||
failed?: number;
|
||||
running?: number;
|
||||
pending?: number;
|
||||
needs_human?: number;
|
||||
current_index?: number;
|
||||
current_task_no?: string | null;
|
||||
} | null;
|
||||
@@ -449,6 +472,8 @@ export interface ShippingBatchSummary {
|
||||
}
|
||||
|
||||
export interface ShippingBatchUiState extends ShippingBatchSummary {
|
||||
/** 批次仅作为会话上传集合摘要,非履约写操作面 */
|
||||
role?: 'upload_session_summary' | string;
|
||||
focus_task?: ShippingTaskSummary | null;
|
||||
focus_task_ui_state?: ShippingTaskUiState | null;
|
||||
tasks: ShippingTaskSummary[];
|
||||
@@ -647,6 +672,7 @@ export interface ShippingOrderExtractionRunSummary {
|
||||
review_required_documents: number;
|
||||
failed_documents: number;
|
||||
candidate_count: number;
|
||||
opened_existing_documents?: number;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionCurrentActivity {
|
||||
@@ -691,6 +717,10 @@ export interface ShippingOrderExtractionDocumentResult {
|
||||
email_supplement: ShippingOrderExtractionEmailSupplementResult;
|
||||
reason_code?: string | null;
|
||||
review_details?: Array<{ line_number: number; field_code?: string | null; reason_code: string }>;
|
||||
/** 解析阶段重复决策;open_existing 时右侧应跳转已有任务 */
|
||||
duplicate_resolution?: string | null;
|
||||
existing_task_no?: string | null;
|
||||
duplicate_status?: string | null;
|
||||
available_actions: string[];
|
||||
activity_event_code?: string | null;
|
||||
started_at?: string | null;
|
||||
@@ -837,6 +867,13 @@ export interface ShippingOrderReviewConfirmResponse {
|
||||
task_no?: string | null;
|
||||
idempotent_replay: boolean;
|
||||
case: ShippingOrderReviewCase;
|
||||
/** 确认后已触发与 STP 相同的 auto_progress */
|
||||
auto_progress_started?: boolean;
|
||||
auto_progress?: {
|
||||
status?: string | null;
|
||||
message?: string | null;
|
||||
checkpoint?: string | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderReviewReparseResponse {
|
||||
|
||||
@@ -57,6 +57,7 @@ const editable = computed(() => activeCase.value?.available_actions.includes('ed
|
||||
const selectedEvidenceId = ref('');
|
||||
const contextOpen = ref(false);
|
||||
const confirmDialogOpen = ref(false);
|
||||
const confirmSuccess = ref<{ taskNo: string; autoProgress: boolean } | null>(null);
|
||||
const selectedEvidence = computed(() => evidence.value.find((item) => item.evidence_id === selectedEvidenceId.value) || null);
|
||||
// PDF.js uses evidence.page_no to select the page; retain the original Blob URL while switching evidence.
|
||||
const previewSrc = computed(() => previewUrl.value);
|
||||
@@ -82,7 +83,18 @@ const confirmCase = () => {
|
||||
confirmDialogOpen.value = true;
|
||||
};
|
||||
const confirmCaseSubmit = async () => {
|
||||
await reportDisposition(() => confirm());
|
||||
try {
|
||||
const response = await confirm();
|
||||
if (response?.task_no) {
|
||||
confirmSuccess.value = {
|
||||
taskNo: String(response.task_no),
|
||||
autoProgress: Boolean(response.auto_progress_started || response.auto_progress),
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof BusinessError ? error.message : t('errors.generic');
|
||||
msg.error(message);
|
||||
}
|
||||
};
|
||||
const selectReplacement = (event: Event) => {
|
||||
const file = (event.target as HTMLInputElement).files?.[0];
|
||||
@@ -116,6 +128,14 @@ watch(
|
||||
<button type="button" class="ml-auto rounded border border-slate-200 px-2.5 py-1.5 text-xs hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800" @click="contextOpen = !contextOpen">{{ contextOpen ? '收起对话上下文' : '对话上下文' }}</button>
|
||||
<span class="shrink-0 rounded-full bg-sky-100 px-2.5 py-1 text-xs text-sky-800 dark:bg-sky-950 dark:text-sky-100">{{ saving ? t('chat.shippingOrderReview.saving') : saveFailed ? t('chat.shippingOrderReview.saveFailed') : t('chat.shippingOrderReview.saved') }}</span>
|
||||
</header>
|
||||
<div
|
||||
v-if="confirmSuccess"
|
||||
class="mx-4 mt-3 rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-800 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-100"
|
||||
>
|
||||
{{ confirmSuccess.autoProgress
|
||||
? t('chat.shippingOrderReview.confirmAutoProgress', { taskNo: confirmSuccess.taskNo })
|
||||
: t('chat.shippingOrderReview.confirmSuccess', { taskNo: confirmSuccess.taskNo }) }}
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="p-8 text-sm text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.loading') }}</div>
|
||||
<div v-else-if="loadFailed" class="m-4 rounded-lg border border-rose-300 bg-rose-50 p-4 text-sm text-rose-900 dark:border-rose-800 dark:bg-rose-950/30 dark:text-rose-100">{{ t('chat.shippingOrderReview.unavailable') }}</div>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* features/shipping-notice/shippingI18nParity.spec.ts
|
||||
* 用途:验证货代发货通知业务域在四种语言中的文案键保持一致。
|
||||
* 依赖:admin/chat/workspace 四语言 JSON;只检查货代业务子树,不受其他历史业务域影响。
|
||||
* 逻辑:递归收集叶子键并比较集合,防止只在单一语言新增或删除货代文案。
|
||||
* 逻辑:递归收集叶子键并比较集合;覆盖 Schema/库存/聊天通知/会话摘要/工作台待办。
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
@@ -61,6 +62,15 @@ describe('shipping notice i18n parity', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps chat shipping session summary keys aligned', () => {
|
||||
expectSameKeys([
|
||||
chatZhCn.shippingSessionSummary as LocaleTree,
|
||||
chatZhTw.shippingSessionSummary as LocaleTree,
|
||||
chatEn.shippingSessionSummary as LocaleTree,
|
||||
chatTh.shippingSessionSummary as LocaleTree,
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps workspace shipping notice keys aligned', () => {
|
||||
expectSameKeys([
|
||||
workspaceZhCn.shippingNotice as LocaleTree,
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* features/workspace/api/shipping-tasks.api.ts
|
||||
* 用途:工作台发货任务 / 我的待办 API 客户端。
|
||||
* 依赖:shared/api/client、chat shipping.api(履约写操作暂复用)。
|
||||
* 逻辑:My Todos 与徽标走本文件;submit-decision / 下载 / 人工上传仍委托 shipping.api。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import type { ShippingTaskSummary } from '@/features/chat/types/shipping.api.types';
|
||||
import {
|
||||
markWorkspaceShippingManualUploaded,
|
||||
submitWorkspaceShippingDecision,
|
||||
workspaceShippingExportUrl,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { downloadWorkspaceShippingExcelFile } from '@/features/chat/shipping/shippingDownload';
|
||||
|
||||
export interface ShippingMyTodosPage {
|
||||
items: ShippingTaskSummary[];
|
||||
page: number;
|
||||
page_size: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface ShippingMyTodosCount {
|
||||
pending: number;
|
||||
processing: number;
|
||||
done: number;
|
||||
total_pending_badge: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页拉取「我的待办」。
|
||||
* @param params.bucket - pending | processing | done
|
||||
*/
|
||||
export function listWorkspaceShippingMyTodos(params?: {
|
||||
bucket?: 'pending' | 'processing' | 'done' | string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
todo_category?: string;
|
||||
customer?: string;
|
||||
task_no?: string;
|
||||
}) {
|
||||
const sp = new URLSearchParams();
|
||||
if (params?.bucket) sp.set('bucket', params.bucket);
|
||||
if (params?.page) sp.set('page', String(params.page));
|
||||
if (params?.page_size) sp.set('page_size', String(params.page_size));
|
||||
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);
|
||||
const q = sp.toString();
|
||||
return requestJson<ShippingMyTodosPage>(
|
||||
`/api/workspace/shipping-tasks/my-todos${q ? `?${q}` : ''}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取待办徽标计数。
|
||||
*/
|
||||
export function countWorkspaceShippingMyTodos() {
|
||||
return requestJson<ShippingMyTodosCount>('/api/workspace/shipping-tasks/my-todos/count');
|
||||
}
|
||||
|
||||
export {
|
||||
downloadWorkspaceShippingExcelFile,
|
||||
markWorkspaceShippingManualUploaded,
|
||||
submitWorkspaceShippingDecision,
|
||||
workspaceShippingExportUrl,
|
||||
};
|
||||
@@ -3,14 +3,15 @@
|
||||
* features/workspace/components/WorkspaceSidebar.vue
|
||||
* 工作台左侧导航:业务一级/二级目录、返回聊天与退出登录。
|
||||
*/
|
||||
import { computed, inject, ref, watch } from 'vue';
|
||||
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,
|
||||
ChevronDown, ChevronRight, ContactRound, ListChecks,
|
||||
ChevronDown, ChevronRight, ContactRound, ListChecks, Inbox,
|
||||
} from 'lucide-vue-next';
|
||||
import { WORKSPACE_PATHS } from '../constants/routes';
|
||||
import { WORKSPACE_KEY } from '../composables/workspace.context';
|
||||
import { useShippingTodoBadge } from '../composables/useShippingTodoBadge';
|
||||
|
||||
const props = defineProps<{
|
||||
collapsed?: boolean;
|
||||
@@ -18,9 +19,10 @@ const props = defineProps<{
|
||||
|
||||
const ws = inject(WORKSPACE_KEY)! as any;
|
||||
const route = useRoute();
|
||||
const shippingRouteNames = ['workspace-shipping-customers', 'workspace-shipping-tasks'] as const;
|
||||
const shippingRouteNames = ['workspace-shipping-customers', 'workspace-shipping-tasks', 'workspace-shipping-my-tasks'] as const;
|
||||
const shippingExpanded = ref(false);
|
||||
const isAdmin = computed(() => String(ws.currentUser?.role || '').trim().toLowerCase() === 'admin');
|
||||
const { pendingBadge, startShippingTodoBadgePolling, stopShippingTodoBadgePolling } = useShippingTodoBadge();
|
||||
|
||||
const primaryLinkItems = [
|
||||
{ path: WORKSPACE_PATHS.profile, labelKey: 'workspace.nav.profile', icon: User, match: ['workspace-profile'] },
|
||||
@@ -48,14 +50,22 @@ watch(
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/** 展开或收起货代发货目录;侧栏折叠时图标直接进入发货任务。 */
|
||||
/** 展开或收起货代发货目录;侧栏折叠时图标直接进入我的待办。 */
|
||||
const toggleShippingMenu = (): void => {
|
||||
if (props.collapsed) {
|
||||
void ws.router.push(WORKSPACE_PATHS.shippingNoticeTasks);
|
||||
void ws.router.push(WORKSPACE_PATHS.shippingNoticeMyTasks);
|
||||
return;
|
||||
}
|
||||
shippingExpanded.value = !shippingExpanded.value;
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
startShippingTodoBadgePolling();
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
stopShippingTodoBadgePolling();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -130,6 +140,20 @@ const toggleShippingMenu = (): void => {
|
||||
<component v-if="!collapsed" :is="shippingExpanded ? ChevronDown : ChevronRight" class="h-4 w-4" />
|
||||
</button>
|
||||
<div v-if="!collapsed && shippingExpanded" class="mt-1 space-y-1 pl-5">
|
||||
<RouterLink
|
||||
:to="WORKSPACE_PATHS.shippingNoticeMyTasks"
|
||||
class="ws-nav-btn py-2.5 text-[13px]"
|
||||
:class="{ 'ws-nav-btn--active': isActive(['workspace-shipping-my-tasks']) }"
|
||||
>
|
||||
<Inbox class="h-4 w-4" />
|
||||
<span class="flex-1">{{ $t('workspace.nav.shippingMyTasks') }}</span>
|
||||
<span
|
||||
v-if="pendingBadge > 0"
|
||||
class="inline-flex min-w-[1.25rem] items-center justify-center rounded-full bg-rose-500 px-1.5 text-[10px] font-semibold text-white"
|
||||
>
|
||||
{{ pendingBadge > 99 ? '99+' : pendingBadge }}
|
||||
</span>
|
||||
</RouterLink>
|
||||
<RouterLink
|
||||
v-if="isAdmin"
|
||||
:to="WORKSPACE_PATHS.shippingNoticeCustomers"
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
|
||||
* features/workspace/composables/useShippingTodoBadge.ts
|
||||
|
||||
* 用途:工作台导航「我的待办」徽标计数(TTL 缓存 + 可选轮询)。
|
||||
|
||||
* 依赖:shipping-tasks.api.countWorkspaceShippingMyTodos。
|
||||
|
||||
* 逻辑:WorkspaceSidebar 挂载时拉取并启动轮询;15s 内复用缓存,避免频繁请求。
|
||||
|
||||
*/
|
||||
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { countWorkspaceShippingMyTodos } from '@/features/workspace/api/shipping-tasks.api';
|
||||
|
||||
|
||||
|
||||
const BADGE_CACHE_TTL_MS = 15_000;
|
||||
|
||||
const DEFAULT_POLL_INTERVAL_MS = 15_000;
|
||||
|
||||
const pendingBadge = ref(0);
|
||||
|
||||
let lastFetchedAt = 0;
|
||||
|
||||
let inFlight: Promise<void> | null = null;
|
||||
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 刷新待办徽标;命中 TTL 时跳过网络请求。
|
||||
|
||||
* @param force - 为 true 时忽略 TTL 强制拉取
|
||||
|
||||
* @returns 当前徽标数字
|
||||
|
||||
*/
|
||||
|
||||
export async function refreshShippingTodoBadge(force = false): Promise<number> {
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
if (!force && now - lastFetchedAt < BADGE_CACHE_TTL_MS && lastFetchedAt > 0) {
|
||||
|
||||
return pendingBadge.value;
|
||||
|
||||
}
|
||||
|
||||
if (inFlight) {
|
||||
|
||||
await inFlight;
|
||||
|
||||
return pendingBadge.value;
|
||||
|
||||
}
|
||||
|
||||
inFlight = (async () => {
|
||||
|
||||
try {
|
||||
|
||||
const res = await countWorkspaceShippingMyTodos();
|
||||
|
||||
pendingBadge.value = Number(res.total_pending_badge || res.pending || 0);
|
||||
|
||||
lastFetchedAt = Date.now();
|
||||
|
||||
} catch {
|
||||
|
||||
/* 徽标失败不阻断导航 */
|
||||
|
||||
} finally {
|
||||
|
||||
inFlight = null;
|
||||
|
||||
}
|
||||
|
||||
})();
|
||||
|
||||
await inFlight;
|
||||
|
||||
return pendingBadge.value;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 启动徽标轮询;每次 tick 强制刷新,便于跨会话待办变化及时反映。
|
||||
|
||||
* @param intervalMs - 轮询间隔,默认 15s
|
||||
|
||||
*/
|
||||
|
||||
export function startShippingTodoBadgePolling(intervalMs = DEFAULT_POLL_INTERVAL_MS): void {
|
||||
|
||||
stopShippingTodoBadgePolling();
|
||||
|
||||
void refreshShippingTodoBadge(true);
|
||||
|
||||
pollTimer = setInterval(() => {
|
||||
|
||||
void refreshShippingTodoBadge(true);
|
||||
|
||||
}, intervalMs);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 停止徽标轮询;侧栏卸载时调用,避免泄漏定时器。
|
||||
|
||||
*/
|
||||
|
||||
export function stopShippingTodoBadgePolling(): void {
|
||||
|
||||
if (pollTimer !== null) {
|
||||
|
||||
clearInterval(pollTimer);
|
||||
|
||||
pollTimer = null;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 暴露响应式徽标数字与刷新/轮询控制。
|
||||
|
||||
*/
|
||||
|
||||
export function useShippingTodoBadge() {
|
||||
|
||||
return {
|
||||
|
||||
pendingBadge,
|
||||
|
||||
refreshShippingTodoBadge,
|
||||
|
||||
startShippingTodoBadgePolling,
|
||||
|
||||
stopShippingTodoBadgePolling,
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ const ROUTE_NAME_TO_SIDEBAR: Record<string, WorkspaceSidebarItem> = {
|
||||
'workspace-schedule-runs': 'schedule_runs',
|
||||
'workspace-shipping-customers': 'shipping_notice',
|
||||
'workspace-shipping-tasks': 'shipping_notice',
|
||||
'workspace-shipping-my-tasks': 'shipping_notice',
|
||||
'workspace-feedback': 'feedback',
|
||||
'workspace-history': 'history',
|
||||
};
|
||||
|
||||
@@ -9,9 +9,10 @@ export const WORKSPACE_PATHS = {
|
||||
updates: '/workspace/updates',
|
||||
knowledgeBase: '/workspace/knowledge-base',
|
||||
scheduleRuns: '/workspace/schedule-runs',
|
||||
shippingNotice: '/workspace/shipping-notice/tasks',
|
||||
shippingNotice: '/workspace/shipping-notice/my-tasks',
|
||||
shippingNoticeCustomers: '/workspace/shipping-notice/customers',
|
||||
shippingNoticeTasks: '/workspace/shipping-notice/tasks',
|
||||
shippingNoticeMyTasks: '/workspace/shipping-notice/my-tasks',
|
||||
feedback: '/workspace/feedback',
|
||||
history: '/workspace/history',
|
||||
} as const;
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* features/workspace/pages/ShippingMyTasksPage.vue
|
||||
* 「我的待办」嵌入页,挂载 ShippingTaskCenterPage。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import ShippingTaskCenterPage from '../shipping-task-center/ShippingTaskCenterPage.vue';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ShippingTaskCenterPage />
|
||||
</template>
|
||||
@@ -1,11 +1,11 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/workspace/pages/ShippingNoticePage.vue
|
||||
* 货代发货通知嵌入页,复用 ShippingNoticeView 的 embedded 模式。
|
||||
* 货代发货任务处理工作台嵌入页,复用 ShippingTaskCenterPage。
|
||||
*/
|
||||
import ShippingNoticeView from '../views/ShippingNoticeView.vue';
|
||||
<script setup lang="ts">
|
||||
import ShippingTaskCenterPage from '../shipping-task-center/ShippingTaskCenterPage.vue';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ShippingNoticeView :embedded="true" />
|
||||
<ShippingTaskCenterPage />
|
||||
</template>
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/InventorySourceSelectDialog.vue
|
||||
* 用途:确认库存查询来源——展示 resolution 候选列表或手动输入 source_code。
|
||||
* 依赖:ShippingInventorySourceCandidate、vue-i18n。
|
||||
* 逻辑:由 TaskTodoPanel 在 confirm_inventory_source 动作时打开;emit confirm(sourceCode)。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingInventorySourceCandidate } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
candidates?: ShippingInventorySourceCandidate[] | null;
|
||||
initialCode?: string;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [boolean];
|
||||
confirm: [sourceCode: string];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const selectedCode = ref('');
|
||||
const manualCode = ref('');
|
||||
const useManual = ref(false);
|
||||
|
||||
const candidateList = computed(() =>
|
||||
Array.isArray(props.candidates) ? props.candidates.filter((item) => item?.source_code) : [],
|
||||
);
|
||||
const hasCandidates = computed(() => candidateList.value.length > 0);
|
||||
|
||||
/**
|
||||
* 关闭对话框并重置本地选择状态。
|
||||
*/
|
||||
function close() {
|
||||
emit('update:open', false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交选中的库存源编码;候选模式取 radio,否则取手动输入。
|
||||
*/
|
||||
function submit() {
|
||||
const code = useManual.value || !hasCandidates.value
|
||||
? manualCode.value.trim().toUpperCase()
|
||||
: selectedCode.value.trim().toUpperCase();
|
||||
if (!code) return;
|
||||
emit('confirm', code);
|
||||
close();
|
||||
}
|
||||
|
||||
/** 每次打开时初始化选择与输入模式。 */
|
||||
watch(() => props.open, (open) => {
|
||||
if (!open) return;
|
||||
selectedCode.value = '';
|
||||
manualCode.value = String(props.initialCode || '').trim().toUpperCase();
|
||||
useManual.value = !hasCandidates.value;
|
||||
if (candidateList.value.length === 1) {
|
||||
selectedCode.value = candidateList.value[0]!.source_code;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open"
|
||||
class="admin-modal-overlay animate-fade-in items-center z-[170]"
|
||||
@click.self="close"
|
||||
>
|
||||
<div class="admin-modal-panel max-w-xl max-h-[90vh] scale-100">
|
||||
<div class="px-6 py-5 border-b border-subtle">
|
||||
<h3 class="section-title">{{ t('workspace.shippingNotice.inventorySourceDialog.title') }}</h3>
|
||||
<p class="section-desc mt-1">{{ t('workspace.shippingNotice.inventorySourceDialog.hint') }}</p>
|
||||
</div>
|
||||
<div class="px-6 py-5 space-y-4 overflow-y-auto">
|
||||
<div v-if="hasCandidates && !useManual" class="space-y-2 max-h-80 overflow-y-auto">
|
||||
<label
|
||||
v-for="candidate in candidateList"
|
||||
:key="candidate.source_code"
|
||||
class="flex items-start gap-3 rounded-xl border border-default p-3 cursor-pointer hover:border-brand-300"
|
||||
>
|
||||
<input v-model="selectedCode" type="radio" :value="candidate.source_code" class="mt-1" />
|
||||
<span class="flex-1 min-w-0">
|
||||
<span class="font-mono text-sm font-semibold text-primary">{{ candidate.source_code }}</span>
|
||||
<span v-if="candidate.display_name" class="ml-2 text-sm text-secondary">{{ candidate.display_name }}</span>
|
||||
<span
|
||||
v-if="candidate.warehouse_id"
|
||||
class="mt-0.5 block text-xs text-muted"
|
||||
>
|
||||
{{ t('workspace.shippingNotice.inventorySource.warehouseId') }}: {{ candidate.warehouse_id }}
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
<div v-if="hasCandidates" class="flex items-center gap-2">
|
||||
<input
|
||||
id="inventory-source-manual-toggle"
|
||||
v-model="useManual"
|
||||
type="checkbox"
|
||||
class="rounded border-default"
|
||||
/>
|
||||
<label for="inventory-source-manual-toggle" class="text-sm text-secondary cursor-pointer">
|
||||
{{ t('workspace.shippingNotice.inventorySourceDialog.manualEntry') }}
|
||||
</label>
|
||||
</div>
|
||||
<div v-if="useManual || !hasCandidates">
|
||||
<input
|
||||
v-model="manualCode"
|
||||
class="input-field text-sm w-full font-mono uppercase"
|
||||
:placeholder="t('workspace.shippingNotice.actions.inventorySourcePrompt')"
|
||||
@keyup.enter="submit"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-modal-footer">
|
||||
<button type="button" class="btn-ghost" @click="close">{{ t('common.cancel') }}</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-primary"
|
||||
:disabled="!(useManual || !hasCandidates ? manualCode.trim() : selectedCode.trim())"
|
||||
@click="submit"
|
||||
>
|
||||
{{ t('workspace.shippingNotice.inventorySourceDialog.confirm') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/ManualUploadEvidenceDialog.vue
|
||||
* 用途:人工上传凭据对话框;截图/PDF 证据必填,回执号可选。
|
||||
* 依赖:uploadFileAsset、workspace shipping-tasks.api。
|
||||
* 逻辑:由 TaskTodoPanel 在 mark_manual_uploaded 动作时打开;禁止触发 RPA 上传。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
import { markWorkspaceShippingManualUploaded } from '@/features/workspace/api/shipping-tasks.api';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
taskNo: string;
|
||||
artifactId?: number | null;
|
||||
disabled?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [boolean];
|
||||
success: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const busy = ref(false);
|
||||
const error = ref('');
|
||||
const evidenceFile = ref<File | null>(null);
|
||||
const freightRefNo = ref('');
|
||||
|
||||
/**
|
||||
* 关闭对话框并清空本地表单。
|
||||
*/
|
||||
function close() {
|
||||
if (busy.value) return;
|
||||
evidenceFile.value = null;
|
||||
freightRefNo.value = '';
|
||||
error.value = '';
|
||||
emit('update:open', false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 选择证据文件(截图或 PDF)。
|
||||
*/
|
||||
function onFileChange(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
evidenceFile.value = input.files?.[0] || null;
|
||||
error.value = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传证据资产并登记人工上传完成。
|
||||
*/
|
||||
async function submit() {
|
||||
if (props.disabled || busy.value) return;
|
||||
if (!evidenceFile.value) {
|
||||
error.value = t('workspace.shippingNotice.manualUpload.evidenceRequired');
|
||||
return;
|
||||
}
|
||||
busy.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const asset = await uploadFileAsset(evidenceFile.value);
|
||||
await markWorkspaceShippingManualUploaded(props.taskNo, {
|
||||
evidence_asset_no: asset.asset_no,
|
||||
...(props.artifactId ? { artifact_id: props.artifactId } : {}),
|
||||
...(freightRefNo.value.trim() ? { freight_ref_no: freightRefNo.value.trim() } : {}),
|
||||
});
|
||||
emit('success');
|
||||
close();
|
||||
} catch (e: unknown) {
|
||||
error.value = e instanceof Error ? e.message : t('workspace.shippingNotice.actions.failed');
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4"
|
||||
@click.self="close"
|
||||
>
|
||||
<div class="w-full max-w-md rounded-2xl border border-default bg-surface p-5 shadow-xl">
|
||||
<h3 class="text-base font-semibold text-primary">
|
||||
{{ $t('workspace.shippingNotice.manualUpload.title') }}
|
||||
</h3>
|
||||
<p class="mt-1 text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.manualUpload.hint') }}
|
||||
</p>
|
||||
|
||||
<label class="mt-4 block text-xs font-medium text-muted">
|
||||
{{ $t('workspace.shippingNotice.manualUpload.evidenceLabel') }}
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*,application/pdf"
|
||||
class="mt-1 block w-full text-sm"
|
||||
:disabled="busy || disabled"
|
||||
@change="onFileChange"
|
||||
>
|
||||
</label>
|
||||
|
||||
<label class="mt-3 block text-xs font-medium text-muted">
|
||||
{{ $t('workspace.shippingNotice.manualUpload.freightRefOptional') }}
|
||||
<input
|
||||
v-model="freightRefNo"
|
||||
type="text"
|
||||
class="mt-1 w-full rounded-xl border border-default bg-surface px-3 py-2 text-sm"
|
||||
:disabled="busy || disabled"
|
||||
>
|
||||
</label>
|
||||
|
||||
<p v-if="error" class="mt-3 text-sm text-rose-600">{{ error }}</p>
|
||||
|
||||
<div class="mt-5 flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl border border-default px-3 py-1.5 text-sm"
|
||||
:disabled="busy"
|
||||
@click="close"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.manualUpload.cancel') }}
|
||||
</button>
|
||||
<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="busy || disabled || !evidenceFile"
|
||||
@click="submit"
|
||||
>
|
||||
{{ busy ? $t('workspace.shippingNotice.manualUpload.submitting') : $t('workspace.shippingNotice.manualUpload.submit') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,484 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/ShippingTaskCenterPage.vue
|
||||
* 用途:发货「我的待办」壳——Pending|Processing|Done + 右侧任务工作台或复核深链。
|
||||
* 依赖:shipping-tasks.api(my-todos)、shipping.api 详情、ShippingTaskWorkbench、useShippingTodoBadge。
|
||||
* 逻辑:review_case 项用 review_run_no 打开人工复核;task 项打开任务处理工作台。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { ExternalLink, RefreshCw } from 'lucide-vue-next';
|
||||
import {
|
||||
getWorkspaceShippingTask,
|
||||
listShippingChatAgents,
|
||||
SHIPPING_NOTICE_AGENT_CODE,
|
||||
type ShippingTaskDetail,
|
||||
type ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import {
|
||||
countWorkspaceShippingMyTodos,
|
||||
listWorkspaceShippingMyTodos,
|
||||
type ShippingMyTodosCount,
|
||||
} from '@/features/workspace/api/shipping-tasks.api';
|
||||
import { useShippingTodoBadge } from '../composables/useShippingTodoBadge';
|
||||
import ShippingTaskWorkbench from './ShippingTaskWorkbench.vue';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const { refreshShippingTodoBadge } = useShippingTodoBadge();
|
||||
|
||||
const bucket = ref<'pending' | 'processing' | 'done'>('pending');
|
||||
const filterTodoCategory = ref<'all' | 'review' | 'exception' | 'manual_upload'>('all');
|
||||
const filterCustomer = ref('');
|
||||
const filterTaskNo = ref('');
|
||||
const appliedFilters = ref({
|
||||
todo_category: '',
|
||||
customer: '',
|
||||
task_no: '',
|
||||
});
|
||||
const loading = ref(false);
|
||||
const detailLoading = ref(false);
|
||||
const tasks = ref<ShippingTaskSummary[]>([]);
|
||||
const selectedRef = ref<string | null>(null);
|
||||
const detail = ref<ShippingTaskDetail | null>(null);
|
||||
const currentPage = ref(1);
|
||||
const pageSize = 20;
|
||||
const totalTasks = ref(0);
|
||||
const bucketCounts = ref<ShippingMyTodosCount>({
|
||||
pending: 0,
|
||||
processing: 0,
|
||||
done: 0,
|
||||
total_pending_badge: 0,
|
||||
});
|
||||
const chatAgentId = ref<number | null>(null);
|
||||
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(totalTasks.value / pageSize)));
|
||||
const canHandle = computed(() => detail.value?.can_handle !== false);
|
||||
const preferredTaskNo = computed(() =>
|
||||
String(route.params.taskNo || route.query.task_no || '').trim().toUpperCase(),
|
||||
);
|
||||
const preferredReviewRun = computed(() => String(route.query.run_no || '').trim());
|
||||
|
||||
const selectedItem = computed(() =>
|
||||
tasks.value.find((item) => todoItemKey(item) === selectedRef.value) || null,
|
||||
);
|
||||
const isReviewSelection = computed(() => selectedItem.value?.item_kind === 'review_case'
|
||||
|| Boolean(selectedItem.value?.review_run_no && !selectedItem.value?.task_no));
|
||||
|
||||
/**
|
||||
* 待办列表项稳定主键:复核用 case_no,任务用 task_no。
|
||||
*/
|
||||
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 || '');
|
||||
}
|
||||
return String(item.todo_ref || item.task_no || '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 列表展示编号:复核显示 case_no,任务显示 SN。
|
||||
*/
|
||||
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 || '—');
|
||||
}
|
||||
return String(item.task_no || item.todo_ref || '—');
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析货代 Chat Agent,供复核/会话深链。
|
||||
*/
|
||||
async function resolveChatAgent() {
|
||||
try {
|
||||
const agents = await listShippingChatAgents();
|
||||
const found = agents.find((a) => String(a.agent_code || '').trim() === SHIPPING_NOTICE_AGENT_CODE);
|
||||
if (found) chatAgentId.value = found.id;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新各 bucket 计数与导航徽标。
|
||||
*/
|
||||
async function loadCounts() {
|
||||
try {
|
||||
bucketCounts.value = await countWorkspaceShippingMyTodos();
|
||||
await refreshShippingTodoBadge(true);
|
||||
} catch {
|
||||
/* 计数失败不阻断列表 */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将筛选表单同步为已应用条件并重置到第 1 页。
|
||||
*/
|
||||
function applyFilters() {
|
||||
appliedFilters.value = {
|
||||
todo_category: bucket.value === 'pending' && filterTodoCategory.value !== 'all'
|
||||
? filterTodoCategory.value
|
||||
: '',
|
||||
customer: filterCustomer.value.trim(),
|
||||
task_no: filterTaskNo.value.trim().toUpperCase(),
|
||||
};
|
||||
void loadTodos(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空筛选条件并重新拉取列表。
|
||||
*/
|
||||
function resetFilters() {
|
||||
filterTodoCategory.value = 'all';
|
||||
filterCustomer.value = '';
|
||||
filterTaskNo.value = '';
|
||||
appliedFilters.value = { todo_category: '', customer: '', task_no: '' };
|
||||
void loadTodos(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按当前 bucket 分页拉取「我的待办」;优先选中路由 task_no / run_no。
|
||||
*/
|
||||
async function loadTodos(resetPage = false) {
|
||||
if (resetPage) currentPage.value = 1;
|
||||
loading.value = true;
|
||||
try {
|
||||
const res = await listWorkspaceShippingMyTodos({
|
||||
bucket: bucket.value,
|
||||
page: currentPage.value,
|
||||
page_size: pageSize,
|
||||
...(appliedFilters.value.todo_category ? { todo_category: appliedFilters.value.todo_category } : {}),
|
||||
...(appliedFilters.value.customer ? { customer: appliedFilters.value.customer } : {}),
|
||||
...(appliedFilters.value.task_no ? { task_no: appliedFilters.value.task_no } : {}),
|
||||
});
|
||||
tasks.value = res.items || [];
|
||||
totalTasks.value = Number(res.total || 0);
|
||||
const byTask = preferredTaskNo.value
|
||||
? tasks.value.find((item) => String(item.task_no || '').toUpperCase() === preferredTaskNo.value)
|
||||
: null;
|
||||
const byRun = preferredReviewRun.value
|
||||
? tasks.value.find((item) => String(item.review_run_no || '') === preferredReviewRun.value)
|
||||
: null;
|
||||
const preferred = byTask || byRun;
|
||||
if (preferred) {
|
||||
selectedRef.value = todoItemKey(preferred);
|
||||
} else if (selectedRef.value && !tasks.value.some((item) => todoItemKey(item) === selectedRef.value)) {
|
||||
selectedRef.value = tasks.value[0] ? todoItemKey(tasks.value[0]) : null;
|
||||
} else if (!selectedRef.value && tasks.value[0]) {
|
||||
selectedRef.value = todoItemKey(tasks.value[0]);
|
||||
}
|
||||
} catch {
|
||||
tasks.value = [];
|
||||
totalTasks.value = 0;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取任务详情;复核项不拉 Task API。
|
||||
*/
|
||||
async function loadDetail(taskNo: string) {
|
||||
detailLoading.value = true;
|
||||
try {
|
||||
detail.value = await getWorkspaceShippingTask(taskNo);
|
||||
} catch {
|
||||
detail.value = null;
|
||||
} finally {
|
||||
detailLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 列表与详情联动刷新。
|
||||
*/
|
||||
async function refreshAll() {
|
||||
await Promise.all([loadTodos(), loadCounts()]);
|
||||
const item = selectedItem.value;
|
||||
if (item?.task_no && item.item_kind !== 'review_case') {
|
||||
await loadDetail(item.task_no);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开人工复核工作台(Chat 主区替换为 order-review 模式)。
|
||||
*/
|
||||
function openReview(item: ShippingTaskSummary) {
|
||||
const runNo = String(item.review_run_no || '').trim();
|
||||
if (!runNo) return;
|
||||
const agentId = Number(item.owner_agent_id || chatAgentId.value || 0);
|
||||
if (!agentId) return;
|
||||
const query: Record<string, string> = {
|
||||
mode: 'order-review',
|
||||
run_no: runNo,
|
||||
};
|
||||
const cid = String(item.conversation_id || '').trim();
|
||||
if (cid) query.conversation_id = cid;
|
||||
const caseNo = String(item.review_case_no || '').trim();
|
||||
if (caseNo) query.case_no = caseNo;
|
||||
void router.push({ path: `/chat/${agentId}`, query });
|
||||
}
|
||||
|
||||
/**
|
||||
* 可选深链:打开 Chat 会话查看上下文(非履约写入口)。
|
||||
*/
|
||||
function openInChat() {
|
||||
if (!chatAgentId.value || !detail.value) return;
|
||||
const query: Record<string, string> = { task_id: detail.value.task_no };
|
||||
const batchNo = String(detail.value.batch_no || '').trim();
|
||||
if (batchNo) query.batch_no = batchNo;
|
||||
const cid = String(detail.value.conversation_id || '').trim();
|
||||
if (/^[0-9a-f]{32}$/i.test(cid)) query.conversation_id = cid;
|
||||
void router.push({ path: `/chat/${chatAgentId.value}`, query });
|
||||
}
|
||||
|
||||
/**
|
||||
* 选中列表项:复核显示入口卡;任务加载工作台详情。
|
||||
*/
|
||||
async function selectTodo(item: ShippingTaskSummary) {
|
||||
selectedRef.value = todoItemKey(item);
|
||||
const nextQuery: Record<string, string> = { ...route.query as Record<string, string> };
|
||||
if (item.item_kind === 'review_case' || item.review_run_no) {
|
||||
delete nextQuery.task_no;
|
||||
if (item.review_run_no) nextQuery.run_no = String(item.review_run_no);
|
||||
detail.value = null;
|
||||
} else if (item.task_no) {
|
||||
delete nextQuery.run_no;
|
||||
nextQuery.task_no = item.task_no;
|
||||
await loadDetail(item.task_no);
|
||||
}
|
||||
void router.replace({
|
||||
name: route.name || 'workspace-shipping-my-tasks',
|
||||
params: route.params,
|
||||
query: nextQuery,
|
||||
});
|
||||
}
|
||||
|
||||
watch(bucket, () => {
|
||||
selectedRef.value = null;
|
||||
detail.value = null;
|
||||
filterTodoCategory.value = 'all';
|
||||
appliedFilters.value = {
|
||||
...appliedFilters.value,
|
||||
todo_category: '',
|
||||
};
|
||||
void loadTodos(true);
|
||||
});
|
||||
|
||||
watch(selectedItem, (item) => {
|
||||
if (!item) {
|
||||
detail.value = null;
|
||||
return;
|
||||
}
|
||||
if (item.item_kind === 'review_case' || (item.review_run_no && !item.task_no)) {
|
||||
detail.value = null;
|
||||
return;
|
||||
}
|
||||
if (item.task_no && detail.value?.task_no !== item.task_no) {
|
||||
void loadDetail(item.task_no);
|
||||
}
|
||||
});
|
||||
|
||||
onMounted(async () => {
|
||||
await Promise.all([resolveChatAgent(), loadCounts(), loadTodos()]);
|
||||
if (preferredTaskNo.value) {
|
||||
const hit = tasks.value.find((item) => String(item.task_no || '').toUpperCase() === preferredTaskNo.value);
|
||||
if (!hit) {
|
||||
selectedRef.value = preferredTaskNo.value;
|
||||
await loadDetail(preferredTaskNo.value);
|
||||
}
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-5 animate-fade-in-up">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold text-primary">{{ $t('workspace.shippingNotice.myTodos.title') }}</h2>
|
||||
<p class="text-sm text-muted">{{ $t('workspace.shippingNotice.myTodos.subtitle') }}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1.5 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft"
|
||||
@click="refreshAll"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.refresh') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="key in (['pending', 'processing', 'done'] as const)"
|
||||
:key="key"
|
||||
type="button"
|
||||
class="rounded-xl px-3 py-1.5 text-sm font-medium"
|
||||
:class="bucket === key ? 'bg-brand-600 text-white' : 'border border-default text-secondary hover:bg-surface-soft'"
|
||||
@click="bucket = key"
|
||||
>
|
||||
{{ $t(`workspace.shippingNotice.myTodos.buckets.${key}`) }}
|
||||
<span class="ml-1 opacity-80">({{ bucketCounts[key] }})</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-end gap-3 rounded-2xl border border-default bg-surface px-4 py-3">
|
||||
<label v-if="bucket === 'pending'" class="space-y-1">
|
||||
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.filters.todoCategory') }}</span>
|
||||
<select v-model="filterTodoCategory" class="input-field text-sm min-w-[9rem]">
|
||||
<option value="all">{{ $t('workspace.shippingNotice.myTodos.filters.all') }}</option>
|
||||
<option value="review">{{ $t('workspace.shippingNotice.myTodos.filters.review') }}</option>
|
||||
<option value="exception">{{ $t('workspace.shippingNotice.myTodos.filters.exception') }}</option>
|
||||
<option value="manual_upload">{{ $t('workspace.shippingNotice.myTodos.filters.manualUpload') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1 flex-1 min-w-[10rem]">
|
||||
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.filters.customer') }}</span>
|
||||
<input
|
||||
v-model="filterCustomer"
|
||||
type="text"
|
||||
class="input-field text-sm w-full"
|
||||
:placeholder="$t('workspace.shippingNotice.myTodos.filters.customerPlaceholder')"
|
||||
@keyup.enter="applyFilters"
|
||||
/>
|
||||
</label>
|
||||
<label class="space-y-1 flex-1 min-w-[10rem]">
|
||||
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.filters.taskNo') }}</span>
|
||||
<input
|
||||
v-model="filterTaskNo"
|
||||
type="text"
|
||||
class="input-field text-sm w-full font-mono uppercase"
|
||||
:placeholder="$t('workspace.shippingNotice.myTodos.filters.taskNoPlaceholder')"
|
||||
@keyup.enter="applyFilters"
|
||||
/>
|
||||
</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="applyFilters"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.myTodos.filters.apply') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft disabled:opacity-50"
|
||||
:disabled="loading"
|
||||
@click="resetFilters"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.myTodos.filters.reset') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-5 lg:grid-cols-[minmax(18rem,0.85fr)_minmax(0,2.15fr)]">
|
||||
<div class="space-y-2">
|
||||
<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="!tasks.length" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.myTodos.empty') }}
|
||||
</div>
|
||||
<button
|
||||
v-for="item in tasks"
|
||||
:key="todoItemKey(item)"
|
||||
type="button"
|
||||
class="w-full rounded-2xl border px-4 py-3 text-left transition-colors"
|
||||
:class="selectedRef === todoItemKey(item) ? 'border-brand-400 bg-brand-50/60' : 'border-default hover:bg-surface-soft/70'"
|
||||
@click="selectTodo(item)"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="font-mono text-sm font-semibold text-primary">{{ todoDisplayNo(item) }}</span>
|
||||
<span
|
||||
v-if="item.todo_category === 'review' || item.item_kind === 'review_case'"
|
||||
class="rounded-full bg-amber-50 px-2 py-0.5 text-[10px] text-amber-700"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.myTodos.openReview') }}
|
||||
</span>
|
||||
<span
|
||||
v-else-if="item.can_handle === false"
|
||||
class="rounded-full bg-slate-100 px-2 py-0.5 text-[10px] text-slate-600"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.todo.adminViewOnlyShort') }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1 truncate text-sm text-secondary">
|
||||
{{ item.ui_state?.summary?.current_todo || item.ui_state?.summary?.title || item.process_status }}
|
||||
</div>
|
||||
<div class="mt-1 truncate text-xs text-muted">
|
||||
{{ item.customer_name || item.source_file_name || item.review_run_no || '—' }}
|
||||
</div>
|
||||
</button>
|
||||
<div v-if="totalPages > 1" class="flex items-center justify-between gap-2 pt-2 text-xs text-muted">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-2 py-1 disabled:opacity-50"
|
||||
:disabled="currentPage <= 1 || loading"
|
||||
@click="currentPage -= 1; loadTodos()"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.pagination.previous') }}
|
||||
</button>
|
||||
<span>{{ currentPage }}/{{ totalPages }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-2 py-1 disabled:opacity-50"
|
||||
:disabled="currentPage >= totalPages || loading"
|
||||
@click="currentPage += 1; loadTodos()"
|
||||
>
|
||||
{{ $t('workspace.shippingNotice.pagination.next') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div
|
||||
v-if="isReviewSelection && selectedItem"
|
||||
class="space-y-4 rounded-2xl border border-default bg-surface p-6"
|
||||
>
|
||||
<div class="font-mono text-lg font-bold text-primary">{{ todoDisplayNo(selectedItem) }}</div>
|
||||
<p class="text-sm text-secondary">
|
||||
{{ selectedItem.ui_state?.summary?.message || selectedItem.ui_state?.summary?.current_todo }}
|
||||
</p>
|
||||
<p v-if="selectedItem.source_file_name" class="text-xs text-muted">
|
||||
{{ selectedItem.source_file_name }}
|
||||
<span v-if="selectedItem.review_run_no"> · {{ selectedItem.review_run_no }}</span>
|
||||
</p>
|
||||
<button
|
||||
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="!selectedItem.review_run_no || !(selectedItem.owner_agent_id || chatAgentId)"
|
||||
@click="openReview(selectedItem)"
|
||||
>
|
||||
<ExternalLink class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.myTodos.openReview') }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-else-if="detailLoading" class="rounded-2xl border border-dashed border-default py-16 text-center text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.loading') }}
|
||||
</div>
|
||||
<div v-else-if="!detail" class="rounded-2xl border border-dashed border-default py-16 text-center text-sm text-muted">
|
||||
{{ $t('workspace.shippingNotice.selectCase') }}
|
||||
</div>
|
||||
<div v-else class="space-y-3">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<div class="font-mono text-lg font-bold text-primary">{{ detail.task_no }}</div>
|
||||
<button
|
||||
v-if="chatAgentId"
|
||||
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="openInChat"
|
||||
>
|
||||
<ExternalLink class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.openChat') }}
|
||||
</button>
|
||||
</div>
|
||||
<ShippingTaskWorkbench
|
||||
:detail="detail"
|
||||
:can-handle="canHandle"
|
||||
@refreshed="refreshAll"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/ShippingTaskWorkbench.vue
|
||||
* 用途:发货任务处理主区——当前待办栏、订单概览、时间线;履约写操作入口。
|
||||
* 依赖:TaskTodoPanel、TaskProgressTimeline、ShippingTaskParsedResultCard、ShippingWorkflowStepper。
|
||||
* 逻辑:由 ShippingTaskCenterPage 选中任务后挂载;只消费后端 ui_state,不发明进度百分比。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import ShippingWorkflowStepper from '@/features/chat/components/ShippingWorkflowStepper.vue';
|
||||
import ShippingMatchResultCard from '@/features/chat/components/messages/ShippingMatchResultCard.vue';
|
||||
import ShippingTaskParsedResultCard from '@/features/chat/components/ShippingTaskParsedResultCard.vue';
|
||||
import { resolveShippingWorkflowSteps } from '@/features/chat/shipping';
|
||||
import type { ShippingTaskDetail } from '@/features/chat/types/shipping.api.types';
|
||||
import TaskTodoPanel from './TaskTodoPanel.vue';
|
||||
import TaskProgressTimeline from './TaskProgressTimeline.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
detail: ShippingTaskDetail;
|
||||
canHandle: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
refreshed: [];
|
||||
}>();
|
||||
|
||||
const workflowSteps = computed(() => resolveShippingWorkflowSteps(props.detail));
|
||||
const shortageLines = computed(() => props.detail.shortage?.lines || []);
|
||||
const hasMatchCard = computed(() =>
|
||||
(Array.isArray(props.detail.line_results) && props.detail.line_results.length > 0)
|
||||
|| shortageLines.value.length > 0,
|
||||
);
|
||||
const events = computed(() => props.detail.events || []);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-4">
|
||||
<TaskTodoPanel
|
||||
:detail="detail"
|
||||
:can-handle="canHandle"
|
||||
@refreshed="emit('refreshed')"
|
||||
/>
|
||||
|
||||
<section class="rounded-2xl border border-default/80 bg-surface px-4 py-3">
|
||||
<div class="mb-3 text-xs font-semibold uppercase tracking-wide text-muted">
|
||||
{{ $t('workspace.shippingNotice.todo.workflow') }}
|
||||
</div>
|
||||
<ShippingWorkflowStepper :steps="workflowSteps" />
|
||||
</section>
|
||||
|
||||
<section class="rounded-2xl border border-default/80 bg-surface px-4 py-3">
|
||||
<h3 class="mb-3 text-sm font-semibold text-secondary">
|
||||
{{ $t('workspace.shippingNotice.todo.orderOverview') }}
|
||||
</h3>
|
||||
<dl class="grid gap-3 text-sm sm:grid-cols-2">
|
||||
<div>
|
||||
<dt class="text-muted">{{ $t('workspace.shippingNotice.fields.status') }}</dt>
|
||||
<dd>{{ detail.process_status || '—' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-muted">{{ $t('workspace.shippingNotice.fields.match') }}</dt>
|
||||
<dd>{{ detail.match_status || '—' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-muted">{{ $t('workspace.shippingNotice.fields.shipTo') }}</dt>
|
||||
<dd>{{ detail.ship_to || '—' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-muted">{{ $t('workspace.shippingNotice.fields.freightRef') }}</dt>
|
||||
<dd>{{ detail.freight_ref_no || '—' }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<ShippingTaskParsedResultCard
|
||||
:task-no="detail.task_no"
|
||||
:po-number="String(detail.po_number || '')"
|
||||
:lines="detail.lines || []"
|
||||
:order-header="detail.order_header"
|
||||
:order-header-fields="detail.order_header_fields"
|
||||
:order-line-fields="detail.order_line_fields"
|
||||
:parse-validation="detail.step_payload?.parse_validation || detail.parse_validation"
|
||||
:process-field-gate="detail.process_field_gate"
|
||||
:source-candidate="detail.source_candidate"
|
||||
:field-conflicts="detail.field_conflicts"
|
||||
:order-data-version="detail.order_data_version"
|
||||
:default-expanded="true"
|
||||
@refreshed="emit('refreshed')"
|
||||
/>
|
||||
|
||||
<ShippingMatchResultCard
|
||||
v-if="hasMatchCard"
|
||||
:task-id="detail.task_no"
|
||||
:match-status="detail.match_status"
|
||||
:line-results="detail.line_results"
|
||||
:shortage-lines="shortageLines"
|
||||
:action-buttons="[]"
|
||||
:action-busy="false"
|
||||
/>
|
||||
|
||||
<TaskProgressTimeline :events="events" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* features/workspace/shipping-task-center/TaskProgressTimeline.vue
|
||||
* 用途:展示任务事件时间线(只读),不发明进度百分比。
|
||||
* 依赖:ShippingTaskEvent、dateTime 工具。
|
||||
* 逻辑:由 ShippingTaskWorkbench 传入 detail.events。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||
import type { ShippingTaskEvent } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
defineProps<{
|
||||
events: ShippingTaskEvent[];
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="rounded-2xl border border-default/80 bg-surface px-4 py-3 text-sm">
|
||||
<h3 class="mb-2 text-sm font-semibold text-secondary">
|
||||
{{ $t('workspace.shippingNotice.events') }}
|
||||
</h3>
|
||||
<div v-if="!events.length" class="py-4 text-center text-xs text-muted">
|
||||
{{ $t('workspace.shippingNotice.timeline.empty') }}
|
||||
</div>
|
||||
<div
|
||||
v-for="(event, index) in events"
|
||||
:key="`${event.event_type}-${index}`"
|
||||
class="border-t border-default/70 py-2 first:border-t-0 first:pt-0"
|
||||
>
|
||||
<div class="flex flex-wrap gap-x-3 gap-y-1 text-xs">
|
||||
<span class="font-medium text-secondary">{{ event.event_type }}</span>
|
||||
<span class="text-muted">{{ formatLocalDateTime(event.created_at) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,753 @@
|
||||
/**
|
||||
|
||||
* features/workspace/shipping-task-center/TaskTodoPanel.vue
|
||||
|
||||
* 用途:仅渲染后端 ui_state.action_buttons / summary.allowed_actions 对应的当前待办动作。
|
||||
|
||||
* 依赖:shipping.api 履约写接口、shipping-tasks.api 下载/人工上传、各确认对话框。
|
||||
|
||||
* 逻辑:禁止按 process_status 二次推导按钮;管理员 can_handle=false 时只读。
|
||||
|
||||
*/
|
||||
|
||||
<script setup lang="ts">
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
|
||||
import ShippingCustomerConfirmDialog from '@/features/chat/components/ShippingCustomerConfirmDialog.vue';
|
||||
|
||||
import type {
|
||||
|
||||
ShippingChatAction,
|
||||
|
||||
ShippingCustomerOption,
|
||||
|
||||
ShippingInventorySourceCandidate,
|
||||
|
||||
ShippingTaskDetail,
|
||||
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
import {
|
||||
|
||||
confirmWorkspaceShippingCustomer,
|
||||
|
||||
confirmWorkspaceShippingInventorySource,
|
||||
|
||||
freezeWorkspaceShippingOrder,
|
||||
|
||||
generateWorkspaceShippingExcel,
|
||||
|
||||
listWorkspaceShippingCustomerOptions,
|
||||
|
||||
matchWorkspaceShippingInventory,
|
||||
|
||||
retryWorkspaceShippingUpload,
|
||||
|
||||
submitWorkspaceShippingDecision,
|
||||
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
|
||||
import { downloadWorkspaceShippingExcelFile } from '@/features/workspace/api/shipping-tasks.api';
|
||||
|
||||
import { refreshShippingTodoBadge } from '@/features/workspace/composables/useShippingTodoBadge';
|
||||
|
||||
import InventorySourceSelectDialog from './InventorySourceSelectDialog.vue';
|
||||
|
||||
import ManualUploadEvidenceDialog from './ManualUploadEvidenceDialog.vue';
|
||||
|
||||
|
||||
|
||||
const props = defineProps<{
|
||||
|
||||
detail: ShippingTaskDetail;
|
||||
|
||||
canHandle: boolean;
|
||||
|
||||
}>();
|
||||
|
||||
|
||||
|
||||
const emit = defineEmits<{
|
||||
|
||||
refreshed: [];
|
||||
|
||||
}>();
|
||||
|
||||
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const msg = useMessage();
|
||||
|
||||
const busyId = ref<string | null>(null);
|
||||
|
||||
const manualUploadOpen = ref(false);
|
||||
|
||||
|
||||
|
||||
const customerDialogOpen = ref(false);
|
||||
|
||||
const customerOptions = ref<ShippingCustomerOption[]>([]);
|
||||
|
||||
const customerLoading = ref(false);
|
||||
|
||||
|
||||
|
||||
const freezeDialogOpen = ref(false);
|
||||
|
||||
const pendingFreezeVersion = ref<number | null>(null);
|
||||
|
||||
|
||||
|
||||
const inventorySourceDialogOpen = ref(false);
|
||||
|
||||
const inventorySourceCandidates = ref<ShippingInventorySourceCandidate[]>([]);
|
||||
|
||||
const inventorySourceInitialCode = ref('');
|
||||
|
||||
|
||||
|
||||
const summary = computed(() => props.detail.ui_state?.summary || {});
|
||||
|
||||
const actionButtons = computed(() => props.detail.ui_state?.action_buttons || []);
|
||||
|
||||
const checkpointKind = computed(() => String(props.detail.ui_state?.checkpoint_kind || ''));
|
||||
|
||||
/** auto_continue 仅保留刷新;正常 STP 由后台自动推进。 */
|
||||
const AUTO_CONTINUE_ACTIONS = new Set(['refresh']);
|
||||
|
||||
/** wait_manual_upload 仅允许下载/导出/人工上传确认。 */
|
||||
const WAIT_MANUAL_UPLOAD_ACTIONS = new Set(['download_excel', 'export', 'mark_manual_uploaded', 'refresh']);
|
||||
|
||||
/** must_human 保留例外处理动作,禁止 Chat 侧履约写路径。 */
|
||||
const MUST_HUMAN_ACTIONS = new Set([
|
||||
'confirm',
|
||||
'reject',
|
||||
'reparse',
|
||||
'replace_notice_file',
|
||||
'rematch',
|
||||
'retry_rpa',
|
||||
'confirm_inventory_source',
|
||||
'retry_resolve_inventory_source',
|
||||
'confirm_customer',
|
||||
'freeze_order',
|
||||
'upload_inventory_file',
|
||||
'match_inventory',
|
||||
'refresh',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 按 STP checkpoint_kind 过滤工作台动作,避免 auto_continue 误点写操作。
|
||||
*/
|
||||
function isActionAllowedForCheckpoint(actionId: string, kind: string): boolean {
|
||||
if (!kind || kind === 'complete') return actionId === 'refresh';
|
||||
if (kind === 'auto_continue') return AUTO_CONTINUE_ACTIONS.has(actionId);
|
||||
if (kind === 'wait_manual_upload') return WAIT_MANUAL_UPLOAD_ACTIONS.has(actionId);
|
||||
if (kind === 'must_human') return MUST_HUMAN_ACTIONS.has(actionId);
|
||||
return true;
|
||||
}
|
||||
|
||||
const allowedIds = computed(() => {
|
||||
|
||||
const fromSummary = summary.value.allowed_actions;
|
||||
|
||||
if (Array.isArray(fromSummary) && fromSummary.length) return new Set(fromSummary.map(String));
|
||||
|
||||
return new Set(actionButtons.value.map((item) => item.id));
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
const visibleActions = computed(() =>
|
||||
|
||||
actionButtons.value.filter((action) => {
|
||||
const id = String(action.id || '');
|
||||
return allowedIds.value.has(id) && isActionAllowedForCheckpoint(id, checkpointKind.value);
|
||||
}),
|
||||
|
||||
);
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 动作成功后刷新详情并更新导航徽标。
|
||||
|
||||
*/
|
||||
|
||||
async function afterSuccess() {
|
||||
|
||||
await refreshShippingTodoBadge(true);
|
||||
|
||||
emit('refreshed');
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 从任务上下文解析唯一库存源编码;多候选或无候选时返回空字符串。
|
||||
|
||||
*/
|
||||
|
||||
function resolveSingleInventorySourceCode(action: ShippingChatAction): string {
|
||||
|
||||
const fromAction = String(action.source_code || '').trim().toUpperCase();
|
||||
|
||||
if (fromAction) return fromAction;
|
||||
|
||||
const resolution = props.detail.inventory_source_resolution;
|
||||
|
||||
const candidates = resolution && typeof resolution === 'object'
|
||||
|
||||
? (resolution as { candidates?: unknown }).candidates
|
||||
|
||||
: null;
|
||||
|
||||
if (Array.isArray(candidates) && candidates.length === 1) {
|
||||
|
||||
const only = candidates[0];
|
||||
|
||||
if (only && typeof only === 'object') {
|
||||
|
||||
return String((only as { source_code?: unknown }).source_code || '').trim().toUpperCase();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return '';
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 打开库存源选择对话框;若已能唯一解析则直接提交。
|
||||
|
||||
*/
|
||||
|
||||
async function runConfirmInventorySource(action: ShippingChatAction) {
|
||||
|
||||
const directCode = resolveSingleInventorySourceCode(action);
|
||||
|
||||
if (directCode) {
|
||||
|
||||
busyId.value = 'confirm_inventory_source';
|
||||
|
||||
try {
|
||||
|
||||
await confirmWorkspaceShippingInventorySource(props.detail.task_no, directCode);
|
||||
|
||||
await afterSuccess();
|
||||
|
||||
} catch (e: unknown) {
|
||||
|
||||
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.failed'));
|
||||
|
||||
} finally {
|
||||
|
||||
busyId.value = null;
|
||||
|
||||
}
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
const resolution = props.detail.inventory_source_resolution;
|
||||
|
||||
const raw = resolution && typeof resolution === 'object'
|
||||
|
||||
? (resolution as { candidates?: unknown }).candidates
|
||||
|
||||
: null;
|
||||
|
||||
inventorySourceCandidates.value = Array.isArray(raw)
|
||||
|
||||
? raw.filter((item): item is ShippingInventorySourceCandidate =>
|
||||
|
||||
Boolean(item && typeof item === 'object' && (item as ShippingInventorySourceCandidate).source_code))
|
||||
|
||||
: [];
|
||||
|
||||
inventorySourceInitialCode.value = String(action.source_code || '').trim().toUpperCase();
|
||||
|
||||
inventorySourceDialogOpen.value = true;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 对话框确认库存源后提交后端。
|
||||
|
||||
*/
|
||||
|
||||
async function onInventorySourceConfirm(sourceCode: string) {
|
||||
|
||||
if (!sourceCode.trim()) {
|
||||
|
||||
msg.warning(t('workspace.shippingNotice.actions.inventorySourcePrompt'));
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
busyId.value = 'confirm_inventory_source';
|
||||
|
||||
try {
|
||||
|
||||
await confirmWorkspaceShippingInventorySource(props.detail.task_no, sourceCode.trim().toUpperCase());
|
||||
|
||||
await afterSuccess();
|
||||
|
||||
} catch (e: unknown) {
|
||||
|
||||
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.failed'));
|
||||
|
||||
} finally {
|
||||
|
||||
busyId.value = null;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 打开客户确认对话框并加载启用标准客户。
|
||||
|
||||
*/
|
||||
|
||||
async function openCustomerDialog() {
|
||||
|
||||
customerDialogOpen.value = true;
|
||||
|
||||
customerLoading.value = true;
|
||||
|
||||
try {
|
||||
|
||||
customerOptions.value = await listWorkspaceShippingCustomerOptions();
|
||||
|
||||
} catch (e: unknown) {
|
||||
|
||||
customerOptions.value = [];
|
||||
|
||||
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.customerNotFound'));
|
||||
|
||||
} finally {
|
||||
|
||||
customerLoading.value = false;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 按关键词刷新客户选项。
|
||||
|
||||
*/
|
||||
|
||||
async function searchCustomers(query: string) {
|
||||
|
||||
customerLoading.value = true;
|
||||
|
||||
try {
|
||||
|
||||
customerOptions.value = await listWorkspaceShippingCustomerOptions(query.trim());
|
||||
|
||||
if (!customerOptions.value.length) {
|
||||
|
||||
msg.warning(t('workspace.shippingNotice.actions.customerNotFound'));
|
||||
|
||||
}
|
||||
|
||||
} catch (e: unknown) {
|
||||
|
||||
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.customerNotFound'));
|
||||
|
||||
} finally {
|
||||
|
||||
customerLoading.value = false;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 确认客户后刷新任务详情。
|
||||
|
||||
*/
|
||||
|
||||
async function onCustomerConfirm(customerId: number) {
|
||||
|
||||
busyId.value = 'confirm_customer';
|
||||
|
||||
try {
|
||||
|
||||
await confirmWorkspaceShippingCustomer(props.detail.task_no, customerId);
|
||||
|
||||
customerDialogOpen.value = false;
|
||||
|
||||
await afterSuccess();
|
||||
|
||||
} catch (e: unknown) {
|
||||
|
||||
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.failed'));
|
||||
|
||||
} finally {
|
||||
|
||||
busyId.value = null;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 校验版本并打开冻结确认对话框。
|
||||
|
||||
*/
|
||||
|
||||
function openFreezeDialog() {
|
||||
|
||||
const version = Number(props.detail.order_data_version);
|
||||
|
||||
if (!Number.isInteger(version) || version < 1) {
|
||||
|
||||
msg.warning(t('workspace.shippingNotice.actions.freezeFailed'));
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
pendingFreezeVersion.value = version;
|
||||
|
||||
freezeDialogOpen.value = true;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 确认冻结后提交后端。
|
||||
|
||||
*/
|
||||
|
||||
async function onFreezeConfirm() {
|
||||
|
||||
const version = pendingFreezeVersion.value;
|
||||
|
||||
if (version == null) return;
|
||||
|
||||
busyId.value = 'freeze_order';
|
||||
|
||||
try {
|
||||
|
||||
await freezeWorkspaceShippingOrder(props.detail.task_no, version);
|
||||
|
||||
await afterSuccess();
|
||||
|
||||
} catch (e: unknown) {
|
||||
|
||||
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.failed'));
|
||||
|
||||
} finally {
|
||||
|
||||
busyId.value = null;
|
||||
|
||||
pendingFreezeVersion.value = null;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 执行后端允许的动作;人工上传/客户/库存源/冻结走对话框,其余走对应工作台 API。
|
||||
|
||||
*/
|
||||
|
||||
async function runAction(action: ShippingChatAction) {
|
||||
|
||||
if (!props.canHandle || busyId.value) return;
|
||||
|
||||
const id = String(action.id || '');
|
||||
|
||||
|
||||
|
||||
if (id === 'mark_manual_uploaded') {
|
||||
|
||||
manualUploadOpen.value = true;
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (id === 'refresh') {
|
||||
|
||||
emit('refreshed');
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (id === 'confirm_customer') {
|
||||
|
||||
await openCustomerDialog();
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (id === 'confirm_inventory_source') {
|
||||
|
||||
await runConfirmInventorySource(action);
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (id === 'freeze_order') {
|
||||
|
||||
openFreezeDialog();
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
busyId.value = id;
|
||||
|
||||
try {
|
||||
|
||||
if (id === 'download_excel' || id === 'export') {
|
||||
|
||||
await downloadWorkspaceShippingExcelFile(props.detail.task_no);
|
||||
|
||||
await afterSuccess();
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (id === 'generate_excel') {
|
||||
|
||||
await generateWorkspaceShippingExcel(props.detail.task_no);
|
||||
|
||||
await afterSuccess();
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (id === 'match_inventory' || id === 'rematch') {
|
||||
|
||||
await matchWorkspaceShippingInventory(props.detail.task_no);
|
||||
|
||||
await afterSuccess();
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (id === 'retry_upload') {
|
||||
|
||||
await retryWorkspaceShippingUpload(props.detail.task_no);
|
||||
|
||||
await afterSuccess();
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
await submitWorkspaceShippingDecision(props.detail.task_no, id);
|
||||
|
||||
await afterSuccess();
|
||||
|
||||
} catch (e: unknown) {
|
||||
|
||||
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.failed'));
|
||||
|
||||
} finally {
|
||||
|
||||
busyId.value = null;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
<template>
|
||||
|
||||
<section class="rounded-2xl border border-brand-200/80 bg-brand-50/40 px-4 py-3">
|
||||
|
||||
<div class="mb-1 text-xs font-semibold uppercase tracking-wide text-brand-700">
|
||||
|
||||
{{ $t('workspace.shippingNotice.todo.currentTodo') }}
|
||||
|
||||
</div>
|
||||
|
||||
<h3 class="text-sm font-semibold text-primary">
|
||||
|
||||
{{ summary.current_todo || summary.title || $t('workspace.shippingNotice.todo.noActionTitle') }}
|
||||
|
||||
</h3>
|
||||
|
||||
<p class="mt-1 text-sm text-secondary">
|
||||
|
||||
{{ summary.message || $t('workspace.shippingNotice.todo.noActionMessage') }}
|
||||
|
||||
</p>
|
||||
|
||||
<p v-if="summary.pause_reason" class="mt-1 text-xs text-amber-700">
|
||||
|
||||
{{ summary.pause_reason }}
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
<div v-if="!canHandle" class="mt-3 text-xs text-muted">
|
||||
|
||||
{{ $t('workspace.shippingNotice.todo.adminViewOnly') }}
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div v-else-if="visibleActions.length" class="mt-3 flex flex-wrap gap-2">
|
||||
|
||||
<button
|
||||
|
||||
v-for="action in visibleActions"
|
||||
|
||||
:key="action.id"
|
||||
|
||||
type="button"
|
||||
|
||||
class="rounded-xl px-3 py-1.5 text-sm font-medium transition-colors disabled:opacity-50"
|
||||
|
||||
:class="action.variant === 'danger'
|
||||
|
||||
? 'bg-rose-600 text-white hover:bg-rose-700'
|
||||
|
||||
: action.variant === 'secondary'
|
||||
|
||||
? 'border border-default bg-surface text-secondary hover:bg-surface-soft'
|
||||
|
||||
: 'bg-brand-600 text-white hover:bg-brand-700'"
|
||||
|
||||
:disabled="busyId === action.id"
|
||||
|
||||
@click="runAction(action)"
|
||||
|
||||
>
|
||||
|
||||
{{ action.label }}
|
||||
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<ManualUploadEvidenceDialog
|
||||
|
||||
v-model:open="manualUploadOpen"
|
||||
|
||||
:task-no="detail.task_no"
|
||||
|
||||
:artifact-id="detail.export_artifacts?.[0]?.id"
|
||||
|
||||
:disabled="!canHandle"
|
||||
|
||||
@success="afterSuccess"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
|
||||
<ShippingCustomerConfirmDialog
|
||||
|
||||
:open="customerDialogOpen"
|
||||
|
||||
:options="customerOptions"
|
||||
|
||||
:loading="customerLoading"
|
||||
|
||||
@close="customerDialogOpen = false"
|
||||
|
||||
@search="searchCustomers"
|
||||
|
||||
@confirm="onCustomerConfirm"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
|
||||
<InventorySourceSelectDialog
|
||||
|
||||
v-model:open="inventorySourceDialogOpen"
|
||||
|
||||
:candidates="inventorySourceCandidates"
|
||||
|
||||
:initial-code="inventorySourceInitialCode"
|
||||
|
||||
@confirm="onInventorySourceConfirm"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
|
||||
<DeleteConfirmDialog
|
||||
|
||||
v-model="freezeDialogOpen"
|
||||
|
||||
confirm-tone="primary"
|
||||
|
||||
:title="$t('workspace.shippingNotice.actions.freezeOrder')"
|
||||
|
||||
:message="$t('workspace.shippingNotice.actions.freezeConfirm')"
|
||||
|
||||
:confirm-text="$t('workspace.shippingNotice.actions.freezeOrder')"
|
||||
|
||||
:confirm-loading="busyId === 'freeze_order'"
|
||||
|
||||
@confirm="onFreezeConfirm"
|
||||
|
||||
/>
|
||||
|
||||
</section>
|
||||
|
||||
</template>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/workspace/views/ShippingNoticeView.vue
|
||||
* 用途:货代发货任务工作台,提供任务筛选、履约审计与跳转对话入口。
|
||||
* 用途:遗留货代任务列表视图;主写入口已迁至 shipping-task-center 工作台。
|
||||
* 依赖:ShippingWorkflowStepper、ShippingMatchResultCard、ShippingTaskParsedResultCard、shipping.api。
|
||||
* 逻辑:先拉取任务列表与详情,再展示步骤、匹配结果、解析行和事件记录;所有用户写操作仅由对话界面执行。
|
||||
* 逻辑:保留只读审计浏览;履约写操作请使用 ShippingTaskCenterPage / ShippingTaskWorkbench。
|
||||
*/
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
@@ -125,9 +125,6 @@ const detailStepProgress = computed<ShippingCurrentStepProgress | null>(() => {
|
||||
const progress = (payload as Record<string, unknown>).current_step_progress;
|
||||
return progress && typeof progress === 'object' ? progress as ShippingCurrentStepProgress : null;
|
||||
});
|
||||
const detailStepHasPercent = computed(() =>
|
||||
typeof detailStepProgress.value?.progress_percent === 'number',
|
||||
);
|
||||
const detailStepMessage = computed(() =>
|
||||
sanitizeShippingRuntimeStatusText(String(detailStepProgress.value?.message || '').trim()),
|
||||
);
|
||||
@@ -153,10 +150,6 @@ const detailTodoMessage = computed(() => (
|
||||
|| detailIssues.value[0]
|
||||
|| t('workspace.shippingNotice.todo.noActionMessage')
|
||||
));
|
||||
const detailTodoActionLabel = computed(() => (
|
||||
String(detail.value?.ui_state?.action_buttons?.[0]?.label || '').trim()
|
||||
));
|
||||
const detailHasTodo = computed(() => !!detailTodoActionLabel.value);
|
||||
|
||||
const inventorySnapshotLabel = (triggerType?: string | null) => {
|
||||
const key = String(triggerType || 'on_demand');
|
||||
@@ -253,6 +246,9 @@ const resolveChatAgent = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 可选深链:打开 Chat 会话查看上下文(非履约写入口)。
|
||||
*/
|
||||
const openInChat = (taskNo: string, conversationId?: string | null, batchNo?: string | null) => {
|
||||
if (!chatAgentId.value) return;
|
||||
const query: Record<string, string> = { task_id: taskNo };
|
||||
@@ -434,23 +430,16 @@ onMounted(async () => {
|
||||
</div>
|
||||
|
||||
<section class="rounded-2xl border border-brand-200 bg-brand-50/50 p-4">
|
||||
<div class="flex flex-wrap items-start justify-between gap-4">
|
||||
<div class="min-w-0">
|
||||
<div class="text-xs font-semibold uppercase tracking-wide text-brand-700">
|
||||
{{ $t('workspace.shippingNotice.todo.label') }}
|
||||
</div>
|
||||
<h3 class="mt-1 text-base font-semibold text-primary">{{ detailTodoTitle }}</h3>
|
||||
<p class="mt-1 text-sm text-secondary">{{ detailTodoMessage }}</p>
|
||||
<div class="min-w-0">
|
||||
<div class="text-xs font-semibold uppercase tracking-wide text-brand-700">
|
||||
{{ $t('workspace.shippingNotice.todo.currentTodo') }}
|
||||
</div>
|
||||
<button
|
||||
v-if="chatAgentId && detailHasTodo"
|
||||
type="button"
|
||||
class="inline-flex shrink-0 items-center gap-1 rounded-xl bg-brand-600 px-3 py-2 text-sm font-medium text-white hover:bg-brand-700"
|
||||
@click="openInChat(detail.task_no, detail.conversation_id, detail.batch_no)"
|
||||
>
|
||||
<ExternalLink class="h-3.5 w-3.5" />
|
||||
{{ $t('workspace.shippingNotice.todo.handleInChat', { action: detailTodoActionLabel }) }}
|
||||
</button>
|
||||
<h3 class="mt-1 text-base font-semibold text-primary">{{ detailTodoTitle }}</h3>
|
||||
<p class="mt-1 text-sm text-secondary">{{ detailTodoMessage }}</p>
|
||||
<p class="mt-2 text-xs text-muted">
|
||||
{{ $t('workspace.shippingNotice.myTodos.openTask') }}:
|
||||
{{ $t('workspace.shippingNotice.subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -462,38 +451,18 @@ onMounted(async () => {
|
||||
</section>
|
||||
|
||||
<div
|
||||
v-if="detailStepProgress"
|
||||
v-if="detailStepProgress && (detailStepMessage || detailStepDetail)"
|
||||
class="rounded-2xl border border-default/80 bg-surface px-4 py-3"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-3 text-xs">
|
||||
<div class="font-medium text-primary">
|
||||
{{ detailStepProgress.step_title || t('chat.shippingNoticeUi.stepDetail.title') }}
|
||||
</div>
|
||||
<div v-if="detailStepHasPercent" class="text-muted">
|
||||
{{ detailStepProgress.progress_percent }}%
|
||||
</div>
|
||||
<div class="text-xs font-medium text-primary">
|
||||
{{ detailStepProgress.step_title || t('chat.shippingNoticeUi.stepDetail.title') }}
|
||||
</div>
|
||||
<div class="mt-1 text-sm text-secondary">
|
||||
{{ detailStepMessage || t('chat.shippingNoticeUi.processing') }}
|
||||
<div v-if="detailStepMessage" class="mt-1 text-sm text-secondary">
|
||||
{{ detailStepMessage }}
|
||||
</div>
|
||||
<div v-if="detailStepDetail" class="mt-1 text-xs text-muted">
|
||||
{{ detailStepDetail }}
|
||||
</div>
|
||||
<div
|
||||
v-if="detailStepProgress.current && detailStepProgress.total"
|
||||
class="mt-1 text-xs text-muted"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.stepDetail.counter', { current: detailStepProgress.current, total: detailStepProgress.total }) }}
|
||||
</div>
|
||||
<div
|
||||
v-if="detailStepHasPercent"
|
||||
class="mt-2 h-2 overflow-hidden rounded-full bg-slate-200"
|
||||
>
|
||||
<div
|
||||
class="h-full rounded-full bg-sky-500 transition-all"
|
||||
:style="{ width: `${detailStepProgress.progress_percent}%` }"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section class="rounded-2xl border border-default/80 bg-surface px-4 py-3">
|
||||
|
||||
Reference in new issue
Block a user