diff --git a/backend/src/HealthManager.Application/Services/ConsultationService.cs b/backend/src/HealthManager.Application/Services/ConsultationService.cs index 80d9666..370b5fd 100644 --- a/backend/src/HealthManager.Application/Services/ConsultationService.cs +++ b/backend/src/HealthManager.Application/Services/ConsultationService.cs @@ -41,7 +41,19 @@ public class ConsultationService(AppDbContext db) Subject = subject, }; db.Consultations.Add(consultation); - await db.SaveChangesAsync(); + try + { + await db.SaveChangesAsync(); + } + catch (DbUpdateException) + { + // Race condition: another request created one between our check and save + // The unique index on (PatientId, DoctorId) where Status='active' caught it + db.ChangeTracker.Clear(); + var retry = await db.Consultations + .FirstOrDefaultAsync(c => c.PatientId == patientId && c.DoctorId == doctorId && c.Status == "active"); + return retry!; + } return consultation; } diff --git a/frontend-patient/src/pages/services/ChatPage.tsx b/frontend-patient/src/pages/services/ChatPage.tsx index 5b78409..e8439d7 100644 --- a/frontend-patient/src/pages/services/ChatPage.tsx +++ b/frontend-patient/src/pages/services/ChatPage.tsx @@ -13,6 +13,7 @@ export function ChatPage() { const [text, setText] = useState(''); const [sending, setSending] = useState(false); const bottomRef = useRef(null); + const initRef = useRef(false); const loadMessages = useCallback((cid: string) => { api.get(`/api/consultations/${cid}/messages`) @@ -20,14 +21,30 @@ export function ChatPage() { .catch(() => {}); }, []); + // Init once - prevent Strict Mode double-fire useEffect(() => { + if (initRef.current) return; + initRef.current = true; + consultationService.getDoctors().then((docs) => { if (docs.length > 0) { const doc = docs[0]; setDoctor(doc); - consultationService.startConsultation(doc.id, '在线咨询').then((c) => { - setConsultation(c); - loadMessages(c.id); + // Find existing active consultation first + api.get('/api/consultations').then((res) => { + const existing = (res.data as Record[]).find( + (c) => c.doctorId === doc.id && c.status === 'active' + ); + if (existing) { + setConsultation(existing as unknown as Consultation); + loadMessages((existing as Record).id); + } else { + // Create new only if none exists + consultationService.startConsultation(doc.id, '在线咨询').then((c) => { + setConsultation(c); + loadMessages(c.id); + }); + } }); } });