Files
syops/frontend/src/features/workspace/shipping-task-center/TaskTodoPanel.vue
T

406 lines
16 KiB
Vue

/**
* features/workspace/shipping-task-center/TaskTodoPanel.vue
* 用途:渲染统一 Gate 恢复卡片与 STP 履约待办说明(表单/弹窗入口)。
* 依赖:ProcessGateRecoveryCard、shipping.api、shipping-tasks.api、element-plus、ManualUploadEvidenceDialog。
* 逻辑:gateCanHandle 控制 Gate 卡写按钮;actionsExecutable 控制统一 action.code 写操作;
* hidePrimaryActions=true 时隐藏本卡按钮(订单处理工作台写入口仅 Footer);
* 系统 Worker / technical_auto_only 不计入人工阻断,避免「待处理事项」冒充系统等待。
*/
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElButton } from 'element-plus';
import { useMessage } from '@/shared/composables/useMessage';
import ShippingCustomerConfirmDialog from '@/features/chat/components/ShippingCustomerConfirmDialog.vue';
import type {
ShippingCustomerOption,
ShippingTaskDetail,
ShippingUnifiedAction,
} from '@/features/chat/types/shipping.api.types';
import {
confirmWorkspaceShippingCustomer,
listWorkspaceShippingCustomerOptions,
} from '@/features/chat/api/shipping.api';
import { downloadWorkspaceShippingNoticeExcelFile } from '@/features/chat/shipping/shippingDownload';
import { refreshShippingTodoBadge } from '@/features/workspace/composables/useShippingTodoBadge';
import ManualUploadEvidenceDialog from './ManualUploadEvidenceDialog.vue';
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
import {
getWorkspaceProcessExecution,
postWorkspaceProcessGateAction,
} from '@/features/shipping-process-gates/api/process-gates.api';
import type {
ShippingProcessGateActionResponse,
ShippingProcessGateUserSummary,
} from '@/features/shipping-process-gates/types/process-gate.types';
const props = withDefaults(defineProps<{
detail: ShippingTaskDetail;
/** 兼容旧调用:未显式传 gate/actions 时两者跟随 canHandle。 */
canHandle?: boolean;
/** Gate 卡是否允许写(订单处理工作台恒为 false)。 */
gateCanHandle?: boolean;
/** 当前可见面板是否允许执行后端已授权动作。 */
actionsExecutable?: boolean;
/** 为 true 时隐藏本卡全部后端 actions(订单处理工作台写入口仅 Footer)。 */
hidePrimaryActions?: boolean;
/** 订单处理工作台将 Gate 卡提升到右侧展示时隐藏此处重复卡。 */
hideGateCard?: boolean;
/** 工作台权威正式 Notice 号;与 detail.task_no 不一致时禁止履约写。 */
expectedNoticeTaskNo?: string | null;
/** 工作台权威 OT 号,随履约 API 校验归属。 */
expectedOrderTaskNo?: string | null;
/** 当前 Review Case 号。 */
expectedReviewCaseNo?: string | null;
/** 当前 Extraction Run 号。 */
expectedRunNo?: string | null;
}>(), {
canHandle: undefined,
gateCanHandle: undefined,
actionsExecutable: undefined,
hidePrimaryActions: false,
hideGateCard: false,
expectedNoticeTaskNo: null,
expectedOrderTaskNo: null,
expectedReviewCaseNo: null,
expectedRunNo: null,
});
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 summary = computed(() => props.detail.ui_state?.summary || {});
const processGateSummary = computed((): ShippingProcessGateUserSummary | null =>
props.detail.ui_state?.process_gate
|| (summary.value.process_gate as ShippingProcessGateUserSummary | null | undefined)
|| null,
);
const unifiedActions = computed(() => props.detail.ui_state?.actions || { primary: null, secondary: [] });
const rawBackendPrimaryAction = computed(() => unifiedActions.value.primary || null);
const rawBackendSecondaryActions = computed(() => unifiedActions.value.secondary || []);
/**
* 任务中心只渲染后端已给出用户文案的受控动作。
*
* action.code 是协议/执行标识,不是展示文案;缺 label 的历史或异常投影必须 fail-closed。
*/
function hasUserFacingActionLabel(
action: ShippingUnifiedAction | null | undefined,
): action is ShippingUnifiedAction & { label: string } {
return Boolean(String(action?.label || '').trim());
}
const backendPrimaryAction = computed(() => (
hasUserFacingActionLabel(rawBackendPrimaryAction.value) ? rawBackendPrimaryAction.value : null
));
const backendSecondaryActions = computed(() => (
rawBackendSecondaryActions.value.filter(hasUserFacingActionLabel)
));
/** 有 Gate 阻断时优先展示统一投影文案。 */
const displayTodoTitle = computed(() =>
processGateSummary.value?.current_blocking_gate?.label
|| summary.value.current_todo
|| summary.value.title
|| t('workspace.shippingNotice.todo.noActionTitle'),
);
const displayTodoMessage = computed(() =>
processGateSummary.value?.blocking_message
|| summary.value.message
|| t('workspace.shippingNotice.todo.noActionMessage'),
);
/** 当前导出工件 id,供人工上传登记对话框绑定。 */
const currentExportArtifactId = computed(() => {
const artifacts = props.detail.export_artifacts;
if (!Array.isArray(artifacts) || !artifacts.length) return null;
const id = Number(artifacts[0]?.id);
return Number.isFinite(id) ? id : null;
});
const hasBlockingGate = computed(() => {
const gate = processGateSummary.value;
if (!gate?.current_blocking_gate) return false;
if (gate.technical_auto_only) return false;
const owner = String(gate.owner_type || '').trim().toLowerCase();
if (owner === 'system') return false;
if (!owner) {
const party = String(gate.responsible_party || '').trim().toLowerCase();
if (party === 'system' || party === 'worker') return false;
}
return true;
});
/** 系统自动等待:禁止用「待处理事项」或 STP 待办卡冒充人工动作。 */
const isSystemAutoWait = computed(() => {
const gate = processGateSummary.value;
if (!gate) return false;
if (gate.technical_auto_only) return true;
if (String(gate.owner_type || '').trim().toLowerCase() === 'system') return true;
if (!gate.current_blocking_gate) return false;
return !hasBlockingGate.value;
});
// 统一 actions 已是唯一按钮来源;旧 action_buttons 不再参与渲染。
/** Gate 卡写权限;订单处理工作台传入 false 保持只读。 */
const resolvedGateCanHandle = computed(() => (
props.gateCanHandle !== undefined ? Boolean(props.gateCanHandle) : Boolean(props.canHandle)
));
/** Footer 委托写权限。 */
const resolvedActionsExecutable = computed(() => (
props.actionsExecutable !== undefined ? Boolean(props.actionsExecutable) : Boolean(props.canHandle)
));
/**
* 动作成功后刷新详情并更新导航徽标。
*/
async function afterSuccess() {
await refreshShippingTodoBadge(true);
emit('refreshed');
}
/**
* 打开客户确认对话框并加载启用标准客户。
*/
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;
}
}
/**
* 履约写前校验正式任务号与工作台权威上下文一致。
*
* @returns 通过为 true;失败已提示并触发 refreshed
*/
async function assertFulfillmentOwnership(): Promise<boolean> {
const expectedNotice = String(props.expectedNoticeTaskNo || '').trim();
const actualNotice = String(props.detail.task_no || '').trim();
if (expectedNotice && actualNotice && expectedNotice !== actualNotice) {
msg.warning(t('errors.codes.SHIPPING_PROCESSING_TASK_OWNERSHIP_MISMATCH'));
emit('refreshed');
return false;
}
return true;
}
const ASYNC_ATTEMPT_POLL_INTERVAL_MS = 800;
const ASYNC_ATTEMPT_POLL_LIMIT = 25;
const ASYNC_ATTEMPT_TERMINAL_STATUSES = new Set(['succeeded', 'failed', 'cancelled', 'superseded']);
/**
* 等待后端已受理的异步 Gate Attempt 收口,避免仅刷新一次而仍读取到 Worker 执行前的投影。
*
* @param response - Gate Action API 的原始响应;仅由 dispatch/attempt 判定是否轮询。
*/
async function waitForAsyncGateAttempt(response: ShippingProcessGateActionResponse): Promise<void> {
if (response.dispatch !== 'async_job' || !Number.isInteger(Number(response.attempt?.id))) return;
const executionNo = String(response.execution_no || '').trim();
const submittedGateCode = String(response.gate_code || '').trim();
const attemptId = Number(response.attempt.id);
if (!executionNo || !submittedGateCode || attemptId < 1) return;
for (let index = 0; index < ASYNC_ATTEMPT_POLL_LIMIT; index += 1) {
const latest = await getWorkspaceProcessExecution(executionNo);
const latestAttempt = latest.current_blocking_gate?.latest_attempt;
const latestAttemptId = Number(latestAttempt?.id || 0);
const latestAttemptStatus = String(latestAttempt?.status || '').trim().toLowerCase();
if (
(latestAttemptId === attemptId || latestAttemptId === 0)
&& ASYNC_ATTEMPT_TERMINAL_STATUSES.has(latestAttemptStatus)
) return;
const currentGateCode = String(latest.current_blocking_gate?.gate_code || '').trim();
const executionStatus = String(latest.status || '').trim().toLowerCase();
if (
currentGateCode
&& currentGateCode !== submittedGateCode
&& !['pending', 'queued', 'running'].includes(executionStatus)
) return;
if (!latest.current_blocking_gate && ['completed', 'cancelled'].includes(executionStatus)) return;
await new Promise((resolve) => window.setTimeout(resolve, ASYNC_ATTEMPT_POLL_INTERVAL_MS));
}
}
/** 将后端下发的 Gate Action 原样提交;缺少 Projection 身份时只刷新。 */
async function requestProjectedGateAction(actionCode: string): Promise<boolean> {
const executionNo = String(processGateSummary.value?.execution_no || '').trim();
const gate = processGateSummary.value?.current_blocking_gate;
const gateCode = String(gate?.gate_code || '').trim();
const version = Number(gate?.evaluation_version);
if (!executionNo || !gateCode || !Number.isInteger(version)) {
emit('refreshed');
return false;
}
const response = await postWorkspaceProcessGateAction(executionNo, gateCode, {
action_code: actionCode,
expected_gate_version: version,
idempotency_key: `task-todo:${executionNo}:${gateCode}:${version}:${actionCode}:${crypto.randomUUID()}`,
});
try {
await waitForAsyncGateAttempt(response);
} catch {
// 受理结果已由 POST 确认;轮询仅用于缩小异步投影窗口,读取短暂失败仍刷新父级事实。
}
return true;
}
/** 将后端统一动作适配到既有宿主能力;业务判断、展示和授权仍完全由后端提供。 */
async function runUnifiedAction(action: ShippingUnifiedAction) {
if (!resolvedActionsExecutable.value || !action.enabled || busyId.value) return;
const dispatch = String(action.dispatch || 'mutation').trim();
const uiHandler = String(action.ui_handler || '').trim();
if (dispatch === 'dialog' && uiHandler === 'manual_upload_confirmation') {
if (!(await assertFulfillmentOwnership())) return;
manualUploadOpen.value = true;
return;
}
if (dispatch === 'view' && uiHandler === 'excel_download') {
busyId.value = action.code;
try {
const businessNo = String(props.detail.business_no || '').trim();
if (!businessNo) throw new Error(t('workspace.shippingNotice.actions.failed'));
await downloadWorkspaceShippingNoticeExcelFile(businessNo);
await afterSuccess();
} catch (e: unknown) {
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.failed'));
} finally {
busyId.value = null;
}
return;
}
if (dispatch === 'navigation' && uiHandler === 'customer_resolution') {
await openCustomerDialog();
return;
}
if (dispatch !== 'mutation' && dispatch !== 'refresh') return;
// 生命周期区域按后端 target_surface 展示后,再将同一份后端 action.code 原样
// 提交 Gate;前端不再维护库存、Excel 或 RPA 的动作别名与 API 分派。
busyId.value = action.code;
try {
if (!(await assertFulfillmentOwnership())) return;
await requestProjectedGateAction(action.code);
await afterSuccess();
} catch (e: unknown) {
msg.warning(e instanceof Error ? e.message : t('workspace.shippingNotice.actions.failed'));
} finally {
busyId.value = null;
}
}
</script>
<template>
<div class="space-y-3">
<ProcessGateRecoveryCard
v-if="!hideGateCard"
:summary="processGateSummary"
:can-handle="resolvedGateCanHandle"
:navigation-context="{
agentId: detail.owner_agent_id != null ? String(detail.owner_agent_id) : undefined,
conversationId: detail.conversation_id || undefined,
}"
@refreshed="afterSuccess"
@refresh-needed="afterSuccess"
@confirm-customer="() => void openCustomerDialog()"
@manual-upload="manualUploadOpen = true"
/>
<section
v-if="!hasBlockingGate && !isSystemAutoWait"
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">
{{ displayTodoTitle }}
</h3>
<p class="mt-1 text-sm text-secondary">
{{ displayTodoMessage }}
</p>
<p v-if="summary.pause_reason" class="mt-1 text-xs text-amber-700">
{{ summary.pause_reason }}
</p>
<div v-if="!resolvedActionsExecutable" class="mt-3 text-xs text-muted">
{{ $t('workspace.shippingNotice.todo.adminViewOnly') }}
</div>
<div v-else-if="backendPrimaryAction || backendSecondaryActions.length" class="mt-3 flex flex-wrap gap-2">
<ElButton
v-if="backendPrimaryAction"
:key="backendPrimaryAction.code"
:type="backendPrimaryAction.kind === 'terminate' ? 'danger' : backendPrimaryAction.kind === 'view' ? 'default' : 'primary'"
:disabled="!backendPrimaryAction.enabled"
:loading="busyId === backendPrimaryAction.code"
@click="runUnifiedAction(backendPrimaryAction)"
>
{{ backendPrimaryAction.label }}
</ElButton>
<ElButton
v-for="action in backendSecondaryActions"
:key="action.code"
:disabled="!action.enabled"
:loading="busyId === action.code"
@click="runUnifiedAction(action)"
>
{{ action.label }}
</ElButton>
</div>
<ManualUploadEvidenceDialog
v-model:open="manualUploadOpen"
:business-no="detail.business_no || ''"
:artifact-id="currentExportArtifactId"
:disabled="!resolvedActionsExecutable || !detail.business_no"
@success="afterSuccess"
/>
<ShippingCustomerConfirmDialog
:open="customerDialogOpen"
:options="customerOptions"
:loading="customerLoading"
@close="customerDialogOpen = false"
@search="searchCustomers"
@confirm="onCustomerConfirm"
/>
</section>
</div>
</template>