From 8451e7df22a58af5c9063dad3c9919c3b899edf5 Mon Sep 17 00:00:00 2001
From: shimai <shimai@example.com>
Date: Tue, 21 Apr 2026 09:30:42 +0800
Subject: [PATCH] feat:增加节点推进倒计时弹窗
---
web-app/src/components/common/OutboundCallWidget.jsx | 502 +++++++++++++++++++++++++++++++++++++++++++++++--------
1 files changed, 430 insertions(+), 72 deletions(-)
diff --git a/web-app/src/components/common/OutboundCallWidget.jsx b/web-app/src/components/common/OutboundCallWidget.jsx
index 9bead7c..8342991 100644
--- a/web-app/src/components/common/OutboundCallWidget.jsx
+++ b/web-app/src/components/common/OutboundCallWidget.jsx
@@ -1,6 +1,7 @@
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useCaseData } from '../../contexts/CaseDataContext';
import OutboundBotAPIService from '../../services/OutboundBotAPIService';
+import ProcessAPIService from '../../services/ProcessAPIService';
import { message } from 'antd';
const OUTBOUND_JOBS_KEY = 'outbound_call_jobs';
@@ -27,20 +28,72 @@
* @param {Function} props.onRefreshData - 数据刷新回调
*/
const OutboundCallWidget = ({ onSwitchTab, onRefreshData }) => {
- const { caseData } = useCaseData();
+ const { caseData, refreshNodeData } = useCaseData();
const [isVisible, setIsVisible] = useState(false); // 默认隐藏
const [isMinimized, setIsMinimized] = useState(false); // 默认展开(非最小化)
const [calls, setCalls] = useState([]);
+ const [mediationRecords, setMediationRecords] = useState([]); // AI调解记录
+ const [aiProcessingTasks, setAiProcessingTasks] = useState([]); // AI处理中任务
+ const [countdownInfo, setCountdownInfo] = useState(null); // 下一节点外呼倒计时
const isMountedRef = useRef(true);
+ // 使用 ref 跟踪 isVisible,避免 useCallback 依赖 isVisible 导致轮询 useEffect 级联重建
+ const isVisibleRef = useRef(isVisible);
+ useEffect(() => { isVisibleRef.current = isVisible; }, [isVisible]);
+
// 轮询间隔(毫秒)
- const POLL_INTERVAL = 10000; // 10秒
+ const POLL_INTERVAL = 2000;
+
+ // 节点数据轻量刷新间隔(毫秒)—— 与主轮询对齐,避免节点进度延迟
+ const NODE_REFRESH_INTERVAL = 2000;
// 最大重试次数
const MAX_RETRY_COUNT = 10;
// 获取 caseId
const caseId = caseData?.caseId || caseData?.case_id;
+
+ // 获取 mediationId
+ const mediationId = caseData?.mediation?.id;
+
+ // 本地倒计时定时器:每秒递减 remaining_seconds,避免仅依赖轮询导致的跳动
+ useEffect(() => {
+ if (!countdownInfo || countdownInfo.remaining_seconds <= 0) return;
+ const timer = setInterval(() => {
+ setCountdownInfo(prev => {
+ if (!prev) return null;
+ const next = prev.remaining_seconds - 1;
+ if (next <= 0) return null; // 倒计时结束,清除
+ return { ...prev, remaining_seconds: next };
+ });
+ }, 1000);
+ return () => clearInterval(timer);
+ }, [countdownInfo?.remaining_seconds > 0]); // 仅在倒计时存在时启动
+
+ // 组件挂载/卸载生命周期(独立管理,不受轮询依赖变化影响)
+ useEffect(() => {
+ isMountedRef.current = true;
+ return () => { isMountedRef.current = false; };
+ }, []);
+
+ // 加载AI调解记录(无Loading效果)
+ const loadMediationRecords = useCallback(async () => {
+ if (!mediationId) return;
+
+ try {
+ const response = await ProcessAPIService.getProcessRecords({
+ mediation_id: mediationId
+ });
+
+ if (isMountedRef.current) {
+ setMediationRecords(response.data || []);
+ console.log('AI调解记录加载成功:', response.data?.length || 0, '条');
+ }
+ } catch (err) {
+ console.error('加载AI调解记录失败:', err);
+ // 不显示错误提示,不设置loading状态
+ }
+ }, [mediationId]);
// 格式化通话时长
const formatDuration = (seconds) => {
@@ -141,57 +194,26 @@
};
/**
- * 批量更新通话状态到后端
- * @param {Array} jobsToUpdate - 需要更新的任务列表
- * @returns {Promise<boolean>} 是否有成功的更新
+ * [已废弃] 批量更新通话状态到后端
+ * 改造后状态更新由后端回调驱动,前端不再调用 update-status API
*/
- const updateCallStatusToBackend = async (jobsToUpdate) => {
- if (!jobsToUpdate || jobsToUpdate.length === 0) return false;
-
- try {
- // 并行调用所有任务的更新API
- const results = await Promise.all(
- jobsToUpdate.map(async (job) => {
- try {
- const statusToUpdate = job.backendStatus || job.newStatus;
- if (!statusToUpdate) {
- return { success: false, job };
- }
- await OutboundBotAPIService.updateCallStatus({
- jobId: job.jobId,
- callStatus: statusToUpdate
- });
- console.log(`状态更新成功: ${job.jobId} -> ${statusToUpdate}`);
- return { success: true, job };
- } catch (err) {
- console.error(`状态更新失败: ${job.jobId}`, err);
- return { success: false, job };
- }
- })
- );
-
- // 检查是否有成功的更新
- const hasSuccess = results.some(r => r.success);
- return hasSuccess;
- } catch (err) {
- console.error('批量更新状态失败:', err);
- return false;
- }
- };
+ // const updateCallStatusToBackend = async (jobsToUpdate) => { ... 已移除 };
/**
- * 触发页面更新(刷新数据 + 切换Tab)
+ * 触发页面更新(轻量刷新节点数据 + 切换Tab)
+ * 不调用 onRefreshData(全量刷新会重复触发外呼/OCR),改用轻量级 refreshNodeData
*/
const triggerPageUpdate = useCallback(() => {
- // 刷新案件数据
- if (onRefreshData) {
- onRefreshData();
+ // 轻量刷新节点数据(仅 timeline + processNodes,不触发外呼等副作用)
+ if (refreshNodeData) {
+ console.log('[Widget] 终态检测 → 立即轻量刷新节点数据');
+ refreshNodeData();
}
// 切换到AI调解实时看板
if (onSwitchTab) {
onSwitchTab('mediation-board');
}
- }, [onRefreshData, onSwitchTab]);
+ }, [refreshNodeData, onSwitchTab]);
/**
* 移除终态或超时的任务
@@ -216,10 +238,72 @@
};
/**
+ * 查询下一节点外呼倒计时
+ */
+ const fetchCountdownInfo = useCallback(async () => {
+ if (!mediationId) return;
+ try {
+ const response = await OutboundBotAPIService.getNextNodeCountdown({ mediation_id: mediationId });
+ const data = response?.data;
+ if (data && data.countdown && data.remaining_seconds > 0) {
+ if (isMountedRef.current) {
+ setCountdownInfo({
+ remaining_seconds: data.remaining_seconds,
+ next_node_name: data.next_node_name || '',
+ delay_seconds: data.delay_seconds || 0,
+ });
+ // 倒计时存在时显示悬浮窗
+ if (!isVisibleRef.current) {
+ setIsVisible(true);
+ }
+ }
+ } else {
+ if (isMountedRef.current) {
+ setCountdownInfo(null);
+ }
+ }
+ } catch (e) {
+ console.warn('[Widget] 查询倒计时失败:', e);
+ }
+ }, [mediationId]);
+
+ /**
* 查询通话状态
*/
const fetchCallStatus = useCallback(async () => {
- // 从 localStorage 读取任务
+ // ── Step 1: 从后端补充活跃记录(解决后端创建任务前端不知情的问题)──
+ if (mediationId) {
+ try {
+ const backendResp = await OutboundBotAPIService.getActiveRecords({ mediation_id: mediationId });
+ const backendJobs = backendResp?.data || [];
+ if (backendJobs.length > 0) {
+ const storedRaw = localStorage.getItem(OUTBOUND_JOBS_KEY);
+ const storedJobs = storedRaw ? JSON.parse(storedRaw) : [];
+ const storedJobIds = new Set(storedJobs.map(j => j.jobId));
+ let changed = false;
+ backendJobs.forEach(bj => {
+ if (!storedJobIds.has(bj.jobId)) {
+ const createTs = bj.createTime ? new Date(bj.createTime).getTime() : Date.now();
+ storedJobs.push({
+ ...bj,
+ startTime: createTs,
+ pollStartTime: Date.now(),
+ retryCount: 0,
+ });
+ changed = true;
+ console.log('[Widget] 从后端补充活跃外呼任务:', bj.jobId, bj.perTypeName, bj.callStatus);
+ }
+ });
+ if (changed) {
+ localStorage.setItem(OUTBOUND_JOBS_KEY, JSON.stringify(storedJobs));
+ }
+ }
+ } catch (e) {
+ console.warn('[Widget] 从后端获取活跃记录失败:', e);
+ }
+ }
+
+ // ── Step 2: 从 localStorage 读取任务(与原逻辑一致)──
const storedJobs = loadJobsFromStorage();
// 分离成功任务和失败任务
@@ -230,7 +314,7 @@
// 没有活跃任务,更新状态并返回
if (isMountedRef.current) {
setCalls([...failedJobs]);
- if (failedJobs.length > 0 && !isVisible) {
+ if (failedJobs.length > 0 && !isVisibleRef.current) {
setIsVisible(true);
}
}
@@ -313,14 +397,13 @@
// 清理超时任务
const cleanedJobs = cleanupJobs(filteredJobs);
- // 如果有需要更新到后端的任务,批量调用更新API
- if (jobsNeedBackendUpdate.length > 0) {
- const hasUpdateSuccess = await updateCallStatusToBackend(jobsNeedBackendUpdate);
-
- // 如果有成功的更新,触发页面更新
- if (hasUpdateSuccess) {
- triggerPageUpdate();
- }
+ // 轮询仅用于 UI 展示,不再调用后端 update-status API
+ // 状态更新已由后端回调驱动,前端不再触发推进
+
+ // 如果有终态任务,触发页面更新
+ const hasTerminalJobs = jobsNeedBackendUpdate.length > 0;
+ if (hasTerminalJobs) {
+ triggerPageUpdate();
}
// 保存到 localStorage
@@ -333,27 +416,81 @@
if (isMountedRef.current) {
setCalls(allJobs);
// 如果有任务,显示气泡
- if (allJobs.length > 0 && !isVisible) {
+ if (allJobs.length > 0 && !isVisibleRef.current) {
setIsVisible(true);
}
}
- }, [isVisible, triggerPageUpdate]);
+ }, [triggerPageUpdate, mediationId]);
- // 定时轮询通话状态
+ // 记录上一次 AI 处理任务数,用于检测 "处理中→完成" 变化
+ const prevAiTaskCountRef = useRef(0);
+
+ // 轮询 AI 处理状态
+ const fetchAiProcessingStatus = useCallback(async () => {
+ if (!mediationId) return;
+ try {
+ const resp = await OutboundBotAPIService.getAiProcessingStatus({ mediation_id: mediationId });
+ const tasks = resp?.data || [];
+ if (isMountedRef.current) {
+ const prevCount = prevAiTaskCountRef.current;
+ prevAiTaskCountRef.current = tasks.length;
+ setAiProcessingTasks(tasks);
+
+ // AI 任务从 "有" → "无"(处理完成),立即刷新节点数据以感知新节点推进
+ if (prevCount > 0 && tasks.length === 0) {
+ console.log('[Widget] AI处理全部完成 → 立即刷新节点数据');
+ if (refreshNodeData) refreshNodeData();
+ }
+
+ // 如果有 AI 处理中任务,确保悬浮窗可见
+ if (tasks.length > 0 && !isVisibleRef.current) {
+ setIsVisible(true);
+ }
+ }
+ } catch (e) {
+ // 不影响主流程,静默失败
+ console.warn('[Widget] 查询AI处理状态失败:', e);
+ }
+ }, [mediationId, refreshNodeData]);
+
+ // 使用 ref 持有最新回调,供轮询定时器调用,避免 setInterval 闭包捕获过期函数
+ const fetchCallStatusRef = useRef(fetchCallStatus);
+ const loadMediationRecordsRef = useRef(loadMediationRecords);
+ const fetchAiProcessingStatusRef = useRef(fetchAiProcessingStatus);
+ const fetchCountdownInfoRef = useRef(fetchCountdownInfo);
+ useEffect(() => { fetchCallStatusRef.current = fetchCallStatus; }, [fetchCallStatus]);
+ useEffect(() => { loadMediationRecordsRef.current = loadMediationRecords; }, [loadMediationRecords]);
+ useEffect(() => { fetchAiProcessingStatusRef.current = fetchAiProcessingStatus; }, [fetchAiProcessingStatus]);
+ useEffect(() => { fetchCountdownInfoRef.current = fetchCountdownInfo; }, [fetchCountdownInfo]);
+
+ // 定时轮询通话状态(仅依赖 mediationId,避免回调引用变化导致定时器反复重建)
useEffect(() => {
- // 组件挂载时设置为 true
- isMountedRef.current = true;
+ // mediationId 尚未就绪时不启动轮询,等待 caseData 加载完毕
+ if (!mediationId) {
+ console.log('[Widget] mediationId 未就绪,延迟启动轮询');
+ return;
+ }
+
+ console.log('[Widget] 启动轮询, mediationId:', mediationId);
// 初始加载
- fetchCallStatus();
-
- // 设置轮询定时器(10秒间隔)
- const interval = setInterval(fetchCallStatus, POLL_INTERVAL);
+ fetchCallStatusRef.current();
+ loadMediationRecordsRef.current();
+ fetchAiProcessingStatusRef.current();
+ fetchCountdownInfoRef.current();
+
+ // 设置轮询定时器(通过 ref 调用最新回调,避免闭包过期)
+ const interval = setInterval(() => {
+ fetchCallStatusRef.current();
+ loadMediationRecordsRef.current();
+ fetchAiProcessingStatusRef.current();
+ fetchCountdownInfoRef.current();
+ }, POLL_INTERVAL);
// 监听外呼任务更新事件(立即刷新)
const handleOutboundJobsUpdated = () => {
console.log('收到外呼任务更新事件,立即刷新');
- fetchCallStatus();
+ fetchCallStatusRef.current();
};
window.addEventListener('outbound-jobs-updated', handleOutboundJobsUpdated);
@@ -370,12 +507,29 @@
// 清理函数
return () => {
+ console.log('[Widget] 清理轮询定时器');
clearInterval(interval);
window.removeEventListener('outbound-jobs-updated', handleOutboundJobsUpdated);
window.removeEventListener('mediation-terminated', handleMediationTerminated);
- isMountedRef.current = false;
};
- }, [fetchCallStatus]);
+ }, [mediationId]); // 仅在 mediationId 变化时重建轮询
+
+ // 独立定时器:周期性轻量刷新 timeline + processNodes(不依赖闭包变量,避免过期状态问题)
+ useEffect(() => {
+ const mediationState = caseData?.mediation?.state;
+ // 仅在调解进行中时启动周期性刷新
+ if (mediationState !== 1) return;
+
+ console.log('[Widget] 启动节点数据周期性轻量刷新,间隔:', NODE_REFRESH_INTERVAL, 'ms');
+ const nodeRefreshTimer = setInterval(() => {
+ if (isMountedRef.current && refreshNodeData) {
+ console.log('[Widget] 执行节点数据轻量刷新');
+ refreshNodeData();
+ }
+ }, NODE_REFRESH_INTERVAL);
+
+ return () => clearInterval(nodeRefreshTimer);
+ }, [caseData?.mediation?.state, refreshNodeData]);
// 关闭气泡
const handleClose = (e) => {
@@ -414,8 +568,8 @@
return true;
});
- // 如果没有活跃任务且不可见,不渲染任何内容
- if (activeCalls.length === 0 && !isVisible) {
+ // 如果没有活跃任务且没有AI处理中任务且没有倒计时且不可见,不渲染任何内容
+ if (activeCalls.length === 0 && aiProcessingTasks.length === 0 && !countdownInfo && !isVisible) {
return null;
}
@@ -454,8 +608,8 @@
color: 'white',
}}
/>
- {/* 红点提示有通话 */}
- {activeCalls.length > 0 && (
+ {/* 红点提示有通话、AI处理中或倒计时 */}
+ {(activeCalls.length + aiProcessingTasks.length + (countdownInfo ? 1 : 0)) > 0 && (
<div
style={{
position: 'absolute',
@@ -464,7 +618,7 @@
width: 16,
height: 16,
borderRadius: '50%',
- background: '#ff4d4f',
+ background: countdownInfo ? '#FA8C16' : aiProcessingTasks.length > 0 ? '#722ED1' : '#ff4d4f',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
@@ -473,7 +627,7 @@
fontWeight: 'bold',
}}
>
- {activeCalls.length}
+ {activeCalls.length + aiProcessingTasks.length + (countdownInfo ? 1 : 0)}
</div>
)}
</div>
@@ -620,8 +774,212 @@
</div>
))}
+ {/* 下一节点外呼倒计时卡片 */}
+ {countdownInfo && countdownInfo.remaining_seconds > 0 && (
+ <div
+ style={{
+ background: 'linear-gradient(135deg, #FA8C16 0%, #D46B08 100%)',
+ borderRadius: 12,
+ padding: '16px 20px',
+ color: 'white',
+ boxShadow: '0 4px 16px rgba(250, 140, 22, 0.3)',
+ position: 'relative',
+ minWidth: 280,
+ }}
+ >
+ {/* 关闭按钮 */}
+ <button
+ onClick={handleClose}
+ style={{
+ position: 'absolute',
+ top: 8,
+ right: 8,
+ width: 24,
+ height: 24,
+ borderRadius: '50%',
+ border: 'none',
+ background: 'rgba(255,255,255,0.2)',
+ color: 'white',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontSize: 14,
+ transition: 'all 0.2s ease',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.background = 'rgba(255,255,255,0.3)';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.background = 'rgba(255,255,255,0.2)';
+ }}
+ >
+ <i className="fas fa-times" />
+ </button>
+
+ {/* 头部 */}
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: 10,
+ marginBottom: 12,
+ }}
+ >
+ <div
+ style={{
+ width: 36,
+ height: 36,
+ borderRadius: '50%',
+ background: 'rgba(255,255,255,0.2)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ }}
+ >
+ <i className="fas fa-hourglass-half" style={{ fontSize: 18, animation: 'pulse 2s infinite' }} />
+ </div>
+ <div style={{ flex: 1 }}>
+ <div
+ style={{
+ fontSize: 16,
+ fontWeight: 600,
+ display: 'flex',
+ alignItems: 'center',
+ gap: 8,
+ }}
+ >
+ 下一节点外呼准备中
+ <span
+ style={{
+ width: 8,
+ height: 8,
+ borderRadius: '50%',
+ background: '#FFC069',
+ animation: 'pulse 2s infinite',
+ }}
+ />
+ </div>
+ </div>
+ </div>
+
+ {/* 倒计时信息 */}
+ <div style={{ marginBottom: 10 }}>
+ <div style={{ fontSize: 14, opacity: 0.95, lineHeight: 1.6 }}>
+ <span>即将进入:{countdownInfo.next_node_name || '下一节点'}</span>
+ </div>
+ </div>
+
+ {/* 倒计时显示 */}
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: 6,
+ fontSize: 13,
+ opacity: 0.9,
+ }}
+ >
+ <i className="far fa-clock" />
+ <span>
+ {Math.floor(countdownInfo.remaining_seconds / 60)}分
+ {String(countdownInfo.remaining_seconds % 60).padStart(2, '0')}秒后发起外呼
+ </span>
+ </div>
+ </div>
+ )}
+
+ {/* AI 处理中加载态卡片 */}
+ {aiProcessingTasks.map((task, index) => (
+ <div
+ key={`ai-${task.jobId || index}`}
+ style={{
+ background: 'linear-gradient(135deg, #722ED1 0%, #531DAB 100%)',
+ borderRadius: 12,
+ padding: '16px 20px',
+ color: 'white',
+ boxShadow: '0 4px 16px rgba(114, 46, 209, 0.3)',
+ position: 'relative',
+ minWidth: 280,
+ }}
+ >
+ {/* 头部 - AI 分析中 */}
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: 10,
+ marginBottom: 12,
+ }}
+ >
+ <div
+ style={{
+ width: 36,
+ height: 36,
+ borderRadius: '50%',
+ background: 'rgba(255,255,255,0.2)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ }}
+ >
+ <i className="fas fa-brain" style={{ fontSize: 18, animation: 'pulse 1.5s infinite' }} />
+ </div>
+ <div style={{ flex: 1 }}>
+ <div
+ style={{
+ fontSize: 16,
+ fontWeight: 600,
+ display: 'flex',
+ alignItems: 'center',
+ gap: 8,
+ }}
+ >
+ AI 分析中
+ <span
+ style={{
+ width: 8,
+ height: 8,
+ borderRadius: '50%',
+ background: '#B37FEB',
+ animation: 'pulse 1.5s infinite',
+ }}
+ />
+ </div>
+ </div>
+ </div>
+
+ {/* 分析信息 */}
+ <div style={{ marginBottom: 10 }}>
+ <div style={{ fontSize: 14, opacity: 0.95, lineHeight: 1.6 }}>
+ <span>{task.personName || '当事人'} 通话分析</span>
+ </div>
+ <div style={{ fontSize: 12, opacity: 0.75, marginTop: 6, display: 'flex', flexDirection: 'column', gap: 4 }}>
+ {(task.steps || []).includes('summary') && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
+ <i className="fas fa-file-alt" style={{ fontSize: 11 }} />
+ <span>对话总结生成中...</span>
+ </div>
+ )}
+ {(task.steps || []).includes('emotion') && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
+ <i className="fas fa-heart" style={{ fontSize: 11 }} />
+ <span>情绪识别中...</span>
+ </div>
+ )}
+ {(task.steps || []).includes('success_rate') && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
+ <i className="fas fa-chart-line" style={{ fontSize: 11 }} />
+ <span>成功率评估中...</span>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ ))}
+
{/* 无通话时的占位提示 */}
- {activeCalls.length === 0 && isVisible && (
+ {activeCalls.length === 0 && aiProcessingTasks.length === 0 && !countdownInfo && isVisible && (
<div
style={{
background: 'linear-gradient(135deg, #1A6FB8 0%, #0d4a8a 100%)',
--
Gitblit v1.8.0