Spaces:
Paused
Paused
Merge remote changes and resolve chat endpoint conflicts
Browse files- Resolved merge conflicts in static/js/app.js
- Kept improved chat endpoint logic (create session first, then post messages)
- Incorporated remote changes for other files
- Fixed /chat endpoint issue by using /session/{session_id}/messages
Files changed (8)
- API Endpoint Breakdown.mdAdded+230
- requirements-dev.txt+1-1
- src/models/common.py+3-2
- src/models/session.py+5-1
- static/index.html+303-303
- static/js/app.js+84-117
- static/js/patient.js+11-6
- static/patient.html+64-64
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230### **Definitive API Endpoint Breakdown (with Model Details)**
This document outlines all available API endpoints, their expected inputs, and their potential outputs, including the detailed structure of all data models.
#### **Account** (`/account`)---- **`GET /account`** - **Description:** Retrieves a list of accounts, optionally filtered by a search query. - **Inputs (Query):** `q` (optional, `string`), `limit` (optional, `integer`) - **Outputs (200 OK):** `list[Account]` - **Account Model:** ```json { "id": "string", "name": "string", "role": "string", "specialty": "string | null", "created_at": "datetime", "updated_at": "datetime", "last_seen": "datetime" } ```
- **`POST /account`** - **Description:** Creates a new account profile. - **Inputs (Body):** `AccountCreateRequest` ```json { "name": "string", "role": "string", "specialty": "string | null" } ``` - **Outputs (201 Created):** `Account` (see model above).
- **`GET /account/{account_id}`** - **Description:** Retrieves a single account by its unique ID. - **Inputs (Path):** `account_id` (required, `string`) - **Outputs (200 OK):** `Account` (see model above).
#### **Patient** (`/patient`)---- **`GET /patient`** - **Description:** Searches for patients by name. - **Inputs (Query):** `q` (required, `string`) - **Outputs (200 OK):** `list[Patient]` - **Patient Model:** ```json { "id": "string", "name": "string", "age": "integer", "sex": "string", "ethnicity": "string", "created_at": "datetime", "updated_at": "datetime", "address": "string | null", "phone": "string | null", "email": "string | null", "medications": "list[string] | null", "past_assessment_summary": "string | null", "assigned_doctor_id": "string | null" } ```
- **`POST /patient`** - **Description:** Creates a new patient profile. - **Inputs (Body):** `PatientCreateRequest` (matches the `Patient` model, but `id`, `created_at`, `updated_at` are not provided). - **Outputs (201 Created):** `Patient` (see model above).
- **`GET /patient/{patient_id}`** - **Description:** Retrieves a single patient by their unique ID. - **Inputs (Path):** `patient_id` (required, `string`) - **Outputs (200 OK):** `Patient` (see model above).
- **`PATCH /patient/{patient_id}`** - **Description:** Updates a patient's profile. - **Inputs (Path):** `patient_id` (required, `string`) - **Inputs (Body):** `PatientUpdateRequest` (all fields from the `Patient` model are optional). - **Outputs (200 OK):** `Patient` (the full, updated object).
- **`GET /patient/{patient_id}/session`** - **Description:** Lists all chat sessions for a specific patient. - **Inputs (Path):** `patient_id` (required, `string`) - **Outputs (200 OK):** `list[Session]` (see Session model below).
#### **Session & Chat** (`/session`)---- **`POST /session`** - **Description:** Creates a new, empty chat session. - **Inputs (Body):** `SessionCreateRequest` ```json { "account_id": "string", "patient_id": "string", "title": "string | null" } ``` - **Outputs (201 Created):** `Session` - **Session Model:** ```json { "id": "string", "account_id": "string", "patient_id": "string", "title": "string", "created_at": "datetime", "updated_at": "datetime", "messages": "list[Message]" } ``` - **Message Model (nested in Session):** ```json { "id": "integer", "sent_by_user": "boolean", "content": "string", "timestamp": "datetime" } ```
- **`GET /session/{session_id}`** - **Description:** Retrieves a session's metadata and all its messages. - **Inputs (Path):** `session_id` (required, `string`) - **Outputs (200 OK):** `Session` (see model above).
- **`DELETE /session/{session_id}`** - **Description:** Deletes a chat session. - **Inputs (Path):** `session_id` (required, `string`) - **Outputs (204 No Content):** Empty response.
- **`GET /session/{session_id}/messages`** - **Description:** Lists all messages for a session. - **Inputs (Path):** `session_id` (required, `string`) - **Outputs (200 OK):** `list[Message]` (see model above).
- **`POST /session/{session_id}/messages`** - **Description:** Posts a message to a session and gets a generated response. - **Inputs (Path):** `session_id` (required, `string`) - **Inputs (Body):** `ChatRequest` ```json { "account_id": "string", "patient_id": "string", "message": "string" } ``` - **Outputs (200 OK):** `ChatResponse` ```json { "response": "string", "session_id": "string", "timestamp": "datetime", "medical_context": "string | null" } ```
#### **EMR (Electronic Medical Records)** (`/emr`)---> **Note:** These endpoints represent an older architectural pattern and have not been integrated into the main `MemoryManager` service.
- **`GET /emr/patient/{patient_id}`**: Gets all EMR entries for a patient. - **Outputs (200 OK):** `list[EMRResponse]` - **EMRResponse Model:** ```json { "emr_id": "string", "patient_id": "string", "doctor_id": "string", "message_id": "string", "session_id": "string", "original_message": "string", "extracted_data": { "diagnosis": "list[string]", "symptoms": "list[string]", "medications": "list[Medication]", "vital_signs": "VitalSigns | null", "lab_results": "list[LabResult]", "procedures": "list[string]", "notes": "string | null" }, "confidence_score": "float", "created_at": "datetime", "updated_at": "datetime" } ```- **`POST /emr/extract`**: Extracts EMR data from a message. - **Inputs (Query):** `patient_id`, `doctor_id`, `message_id`, `session_id`, `message` (all `string`). - **Outputs (200 OK):** `{"emr_id": "string", "message": "string"}`.- *(Other EMR endpoints follow a similar pattern, using the models defined in `emr/models/emr.py`)*
#### **Utilities**---- **`POST /summarise`** - **Description:** Summarises text into a short title. - **Inputs (Body):** `SummariseRequest` ```json { "text": "string", "max_words": "integer" } ``` - **Outputs (200 OK):** `SummariseResponse` ```json { "title": "string" } ```
- **`POST /audio/transcribe`** - **Description:** Transcribes an audio file to text. - **Inputs (Form Data):** `file` (required, `UploadFile`), `language_code` (optional, `string`). - **Outputs (200 OK):** `JSON` ```json { "success": "boolean", "transcribed_text": "string", "language_code": "string", "file_name": "string" } ```- **`GET /audio/supported-formats`**: Returns `{"supported_formats": ["wav", "opus", ...], "description": "string"}`.
#### **System & Health**---- **`GET /`** & **`GET /system-status`**: Serves static HTML pages.- **`GET /system/health`**: Returns a `JSON` object detailing the status of core components (memory, embedding, API keys).- **`GET /system/database`**: Returns a detailed `JSON` object describing the state of each MongoDB collection (document counts, indexes, fields).- **`GET /audio/health`**: Returns a `JSON` object detailing the status of the audio transcription service.- **`GET /emr/health`**: Returns a `JSON` object with the status and document count of the EMR collection.9 unmodified lines101112139 unmodified linespymongopandaspython-multipartpytest9 unmodified lines101112139 unmodified linespymongopandaspython-multipartpytest
7 unmodified lines8910111213141516177 unmodified linesclass BaseMongoModel(BaseModel):"""A base Pydantic model for all MongoDB documents."""id: PyObjectId = Field(..., alias="_id")model_config = ConfigDict(frozen=True,from_attributes=True,arbitrary_types_allowed=True)7 unmodified lines891011121314151617187 unmodified linesclass BaseMongoModel(BaseModel):"""A base Pydantic model for all MongoDB documents."""id: PyObjectId = Field(..., validation_alias="_id")model_config = ConfigDict(frozen=True,from_attributes=True,arbitrary_types_allowed=True,populate_by_name=True)
15 unmodified lines1617181920212215 unmodified linestimestamp: datetime# Use a standard config for this sub-modelmodel_config = ConfigDict(frozen=True, from_attributes=True)class Session(BaseMongoModel):"""A Pydantic model for a chat session, including nested messages."""15 unmodified lines161718192021222324252615 unmodified linestimestamp: datetime# Use a standard config for this sub-modelmodel_config = ConfigDict(frozen=True,from_attributes=True,populate_by_name=True)class Session(BaseMongoModel):"""A Pydantic model for a chat session, including nested messages."""
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Medical AI Assistant</title><link rel="icon" type="image/svg+xml" href="/static/icon.svg"><link rel="stylesheet" href="/static/css/styles.css"><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"></head><body><div class="app-container"><div class="app-overlay" id="appOverlay"></div><!-- Sidebar --><div class="sidebar" id="sidebar"><div class="sidebar-header"><button class="new-chat-btn" id="newChatBtn"><i class="fas fa-plus"></i>New Chat</button></div><div class="user-section"><div class="user-profile" id="userProfile"><div class="user-avatar"><i class="fas fa-user-md"></i></div><div class="user-info"><div class="user-name" id="userName">Anonymous</div><div class="user-status" id="userStatus">Medical Professional</div></div><button class="user-menu-btn" id="userMenuBtn"><i class="fas fa-ellipsis-v"></i></button></div></div><!-- Patient Login Section --><div class="patient-section"><div class="patient-header">Patient</div><div class="patient-input-group patient-typeahead"><input type="text" id="patientIdInput" class="patient-input" placeholder="Search patient by name or ID"><div id="patientSuggestions" class="patient-suggestions" style="display:none;"></div><button class="patient-load-btn" id="loadPatientBtn" title="Load Patient"><i class="fas fa-arrow-right"></i></button><a class="patient-create-link" id="createPatientLink" href="/static/patient.html" title="Create new patient"><i class="fas fa-user-plus"></i></a></div><div class="patient-status" id="patientStatus">No patient selected</div><div class="patient-actions" id="patientActions" style="display: none;"><a href="/static/emr.html" id="emrLink" class="emr-link"><i class="fas fa-file-medical"></i> EMR</a></div></div><div class="chat-sessions" id="chatSessions"><!-- Chat sessions will be populated here --></div><div class="sidebar-footer"><button class="settings-btn" id="settingsBtn"><i class="fas fa-cog"></i>Settings</button></div></div><!-- Main Chat Area --><div class="main-content"><div class="chat-header"><button class="sidebar-toggle" id="sidebarToggle"><i class="fas fa-bars"></i></button><div class="chat-title" id="chatTitle">Medical AI Assistant</div><div class="chat-actions"><button class="action-btn" id="exportBtn" title="Export Chat"><i class="fas fa-download"></i></button><button class="action-btn" id="clearBtn" title="Clear Chat"><i class="fas fa-trash"></i></button></div></div><div class="chat-messages" id="chatMessages"><!-- Welcome message --><div class="message assistant-message"><div class="message-avatar"><i class="fas fa-robot"></i></div><div class="message-content"><div class="message-text">👋 Welcome to Medical AI Assistant<div class="tagged-title"><div class="tagged-title-bar"></div><div class="tagged-title-content"><h1>Who am I, and what can I do?</h1></div></div><p>I'm here to help you with medical questions, diagnosis assistance, and healthcare information. I can:</p><div class="tagged-title"><div class="tagged-title-bar"></div><div class="tagged-title-content"><h1>Key Features</h1></div></div><p><span class="blue-bubble">Medical Information:</span> I can provide evidence-based medical information and explanations.</p><p><span class="blue-bubble">Symptom Analysis:</span> I can help analyze symptoms and suggest possible conditions.</p><p><span class="blue-bubble">Treatment Guidance:</span> I can explain treatments, medications, and procedures.</p><p><span class="blue-bubble">Important:</span> This is for informational purposes only. Always consult with qualified healthcare professionals for medical advice.</p><p>How can I assist you today?</p></div><div class="message-time">Just now</div></div></div></div><div class="chat-input-container"><div class="input-wrapper"><textareaclass="chat-input"id="chatInput"placeholder="Ask me about any medical topic..."rows="1"></textarea><button class="send-btn" id="sendBtn"><i class="fas fa-paper-plane"></i></button></div><div class="input-footer"><div class="disclaimer"><i class="fas fa-info-circle"></i>AI-powered medical information. Not a substitute for professional medical advice.</div><div class="input-actions"><button class="microphone-btn" id="microphoneBtn" title="Voice Input"><i class="fas fa-microphone"></i></button><button class="attachment-btn" id="attachmentBtn" title="Attach Files"><i class="fas fa-paperclip"></i></button></div></div></div></div></div><!-- Modals --><div class="modal" id="userModal"><div class="modal-content"><div class="modal-header"><h3>Doctor Profile</h3><button class="modal-close" id="userModalClose">×</button></div><div class="modal-body"><div class="form-group"><label for="profileNameSelect">Name:</label><select id="profileNameSelect"></select></div><div class="form-group" id="newDoctorSection" style="display:none;"><label for="newDoctorName">Doctor name</label><input type="text" id="newDoctorName" placeholder="Enter doctor name"><div style="display:flex; gap:8px; margin-top:8px;"><button type="button" class="btn btn-secondary" id="cancelNewDoctor">Cancel</button><button type="button" class="btn btn-primary" id="confirmNewDoctor">Confirm</button></div></div><div class="form-group"><label for="profileRole">Medical Role:</label><select id="profileRole"><option value="Doctor">Doctor</option><option value="Healthcare Prof">Healthcare Prof</option><option value="Nurse">Nurse</option><option value="Caregiver">Caregiver</option><option value="Physician">Physician</option><option value="Medical Student">Medical Student</option><option value="Other">Other</option></select></div><div class="form-group"><label for="profileSpecialty">Specialty (Optional):</label><input type="text" id="profileSpecialty" placeholder="e.g., Cardiology, Pediatrics"></div></div><div class="modal-footer"><button class="btn btn-secondary" id="userModalCancel">Cancel</button><button class="btn btn-primary" id="userModalSave">Save</button></div></div></div><div class="modal" id="settingsModal"><div class="modal-content"><div class="modal-header"><h3>Settings</h3><button class="modal-close" id="settingsModalClose">×</button></div><div class="modal-body"><div class="form-group"><label for="themeSelect">Theme:</label><select id="themeSelect"><option value="light">Light</option><option value="dark">Dark</option><option value="auto">Auto</option></select></div><div class="form-group"><label for="fontSize">Font Size:</label><select id="fontSize"><option value="small">Small</option><option value="medium" selected>Medium</option><option value="large">Large</option></select></div><div class="form-group"><label><input type="checkbox" id="autoSave"> Auto-save conversations</label></div><div class="form-group"><label><input type="checkbox" id="notifications"> Enable notifications</label></div></div><div class="modal-footer"><button class="btn btn-secondary" id="settingsModalCancel">Cancel</button><button class="btn btn-primary" id="settingsModalSave">Save</button></div><div class="system-access"><button class="system-access-btn" id="systemAccessBtn">System status</button></div></div></div><!-- Edit Session Title Modal --><div class="modal" id="editTitleModal"><div class="modal-content"><div class="modal-header"><h3>Edit Chat Name</h3><button class="modal-close" id="editTitleModalClose">×</button></div><div class="modal-body"><div class="form-group"><label for="editSessionTitleInput">New name</label><input type="text" id="editSessionTitleInput" placeholder="Enter new chat name"></div></div><div class="modal-footer"><button class="btn btn-secondary" id="editTitleModalCancel">Cancel</button><button class="btn btn-primary" id="editTitleModalSave">Save</button></div></div></div><!-- Patient Modal --><div class="modal" id="patientModal"><div class="modal-content"><div class="modal-header"><h3>Patient Profile</h3><button class="modal-close" id="patientModalClose">×</button></div><div class="modal-body"><div class="patient-summary" id="patientSummary"></div><div class="patient-details"><div><strong>Medications:</strong> <span id="patientMedications">-</span></div><div><strong>Past Assessment:</strong> <span id="patientAssessment">-</span></div></div></div><div class="modal-footer"><button id="patientLogoutBtn" class="btn-danger">Log out patient</button><a id="patientCreateBtn" class="btn-primary" href="/static/patient.html">Create new patient</a></div></div></div><!-- Audio Recording Modal --><div class="modal" id="audioRecordingModal"><div class="modal-content audio-recording-modal"><div class="modal-header"><h3>Voice Recording</h3><button class="modal-close" id="audioRecordingModalClose">×</button></div><div class="modal-body"><div class="recording-container"><div class="microphone-icon"><i class="fas fa-microphone"></i></div><div class="wave-animation" id="waveAnimation"><div class="wave-bar"></div><div class="wave-bar"></div><div class="wave-bar"></div><div class="wave-bar"></div><div class="wave-bar"></div><div class="wave-bar"></div><div class="wave-bar"></div><div class="wave-bar"></div></div><div class="recording-status" id="recordingStatus">Listening...</div><div class="recording-timer" id="recordingTimer">00:00</div></div></div><div class="modal-footer"><button class="btn btn-secondary" id="stopRecordingBtn">Stop Recording</button></div></div></div><!-- Loading overlay --><div class="loading-overlay" id="loadingOverlay"><div class="loading-spinner"><i class="fas fa-heartbeat fa-spin"></i><div class="loading-text">Processing your medical query...</div></div></div><!-- Sidebar overlay for outside-click close --><div id="sidebarOverlay" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.35);z-index:900;"></div><script type="module" src="/static/js/app.js"></script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Medical AI Assistant</title><link rel="icon" type="image/svg+xml" href="/static/icon.svg"><link rel="stylesheet" href="/static/css/styles.css"><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"></head><body><div class="app-container"><div class="app-overlay" id="appOverlay"></div><!-- Sidebar --><div class="sidebar" id="sidebar"><div class="sidebar-header"><button class="new-chat-btn" id="newChatBtn"><i class="fas fa-plus"></i>New Chat</button></div><div class="user-section"><div class="user-profile" id="userProfile"><div class="user-avatar"><i class="fas fa-user-md"></i></div><div class="user-info"><div class="user-name" id="userName">Anonymous</div><div class="user-status" id="userStatus">Medical Professional</div></div><button class="user-menu-btn" id="userMenuBtn"><i class="fas fa-ellipsis-v"></i></button></div></div><!-- Patient Login Section --><div class="patient-section"><div class="patient-header">Patient</div><div class="patient-input-group patient-typeahead"><input type="text" id="patientIdInput" class="patient-input" placeholder="Search patient by name or ID"><div id="patientSuggestions" class="patient-suggestions" style="display:none;"></div><button class="patient-load-btn" id="loadPatientBtn" title="Load Patient"><i class="fas fa-arrow-right"></i></button><a class="patient-create-link" id="createPatientLink" href="/static/patient.html" title="Create new patient"><i class="fas fa-user-plus"></i></a></div><div class="patient-status" id="patientStatus">No patient selected</div><div class="patient-actions" id="patientActions" style="display: none;"><a href="/static/emr.html" id="emrLink" class="emr-link"><i class="fas fa-file-medical"></i> EMR</a></div></div><div class="chat-sessions" id="chatSessions"><!-- Chat sessions will be populated here --></div><div class="sidebar-footer"><button class="settings-btn" id="settingsBtn"><i class="fas fa-cog"></i>Settings</button></div></div><!-- Main Chat Area --><div class="main-content"><div class="chat-header"><button class="sidebar-toggle" id="sidebarToggle"><i class="fas fa-bars"></i></button><div class="chat-title" id="chatTitle">Medical AI Assistant</div><div class="chat-actions"><button class="action-btn" id="exportBtn" title="Export Chat"><i class="fas fa-download"></i></button><button class="action-btn" id="clearBtn" title="Clear Chat"><i class="fas fa-trash"></i></button></div></div><div class="chat-messages" id="chatMessages"><!-- Welcome message --><div class="message assistant-message"><div class="message-avatar"><i class="fas fa-robot"></i></div><div class="message-content"><div class="message-text">👋 Welcome to Medical AI Assistant<div class="tagged-title"><div class="tagged-title-bar"></div><div class="tagged-title-content"><h1>Who am I, and what can I do?</h1></div></div><p>I'm here to help you with medical questions, diagnosis assistance, and healthcare information. I can:</p><div class="tagged-title"><div class="tagged-title-bar"></div><div class="tagged-title-content"><h1>Key Features</h1></div></div><p><span class="blue-bubble">Medical Information:</span> I can provide evidence-based medical information and explanations.</p><p><span class="blue-bubble">Symptom Analysis:</span> I can help analyze symptoms and suggest possible conditions.</p><p><span class="blue-bubble">Treatment Guidance:</span> I can explain treatments, medications, and procedures.</p><p><span class="blue-bubble">Important:</span> This is for informational purposes only. Always consult with qualified healthcare professionals for medical advice.</p><p>How can I assist you today?</p></div><div class="message-time">Just now</div></div></div></div><div class="chat-input-container"><div class="input-wrapper"><textareaclass="chat-input"id="chatInput"placeholder="Ask me about any medical topic..."rows="1"></textarea><button class="send-btn" id="sendBtn"><i class="fas fa-paper-plane"></i></button></div><div class="input-footer"><div class="disclaimer"><i class="fas fa-info-circle"></i>AI-powered medical information. Not a substitute for professional medical advice.</div><div class="input-actions"><button class="microphone-btn" id="microphoneBtn" title="Voice Input"><i class="fas fa-microphone"></i></button><button class="attachment-btn" id="attachmentBtn" title="Attach Files"><i class="fas fa-paperclip"></i></button></div></div></div></div></div><!-- Modals --><div class="modal" id="userModal"><div class="modal-content"><div class="modal-header"><h3>Doctor Profile</h3><button class="modal-close" id="userModalClose">×</button></div><div class="modal-body"><div class="form-group"><label for="profileNameSelect">Name:</label><select id="profileNameSelect"></select></div><div class="form-group" id="newDoctorSection" style="display:none;"><label for="newDoctorName">Doctor name</label><input type="text" id="newDoctorName" placeholder="Enter doctor name"><div style="display:flex; gap:8px; margin-top:8px;"><button type="button" class="btn btn-secondary" id="cancelNewDoctor">Cancel</button><button type="button" class="btn btn-primary" id="confirmNewDoctor">Confirm</button></div></div><div class="form-group"><label for="profileRole">Medical Role:</label><select id="profileRole"><option value="Doctor">Doctor</option><option value="Healthcare Prof">Healthcare Prof</option><option value="Nurse">Nurse</option><option value="Caregiver">Caregiver</option><option value="Physician">Physician</option><option value="Medical Student">Medical Student</option><option value="Other">Other</option></select></div><div class="form-group"><label for="profileSpecialty">Specialty (Optional):</label><input type="text" id="profileSpecialty" placeholder="e.g., Cardiology, Pediatrics"></div></div><div class="modal-footer"><button class="btn btn-secondary" id="userModalCancel">Cancel</button><button class="btn btn-primary" id="userModalSave">Save</button></div></div></div><div class="modal" id="settingsModal"><div class="modal-content"><div class="modal-header"><h3>Settings</h3><button class="modal-close" id="settingsModalClose">×</button></div><div class="modal-body"><div class="form-group"><label for="themeSelect">Theme:</label><select id="themeSelect"><option value="light">Light</option><option value="dark">Dark</option><option value="auto">Auto</option></select></div><div class="form-group"><label for="fontSize">Font Size:</label><select id="fontSize"><option value="small">Small</option><option value="medium" selected>Medium</option><option value="large">Large</option></select></div><div class="form-group"><label><input type="checkbox" id="autoSave"> Auto-save conversations</label></div><div class="form-group"><label><input type="checkbox" id="notifications"> Enable notifications</label></div></div><div class="modal-footer"><button class="btn btn-secondary" id="settingsModalCancel">Cancel</button><button class="btn btn-primary" id="settingsModalSave">Save</button></div><div class="system-access"><button class="system-access-btn" id="systemAccessBtn">System status</button></div></div></div><!-- Edit Session Title Modal --><div class="modal" id="editTitleModal"><div class="modal-content"><div class="modal-header"><h3>Edit Chat Name</h3><button class="modal-close" id="editTitleModalClose">×</button></div><div class="modal-body"><div class="form-group"><label for="editSessionTitleInput">New name</label><input type="text" id="editSessionTitleInput" placeholder="Enter new chat name"></div></div><div class="modal-footer"><button class="btn btn-secondary" id="editTitleModalCancel">Cancel</button><button class="btn btn-primary" id="editTitleModalSave">Save</button></div></div></div><!-- Patient Modal --><div class="modal" id="patientModal"><div class="modal-content"><div class="modal-header"><h3>Patient Profile</h3><button class="modal-close" id="patientModalClose">×</button></div><div class="modal-body"><div class="patient-summary" id="patientSummary"></div><div class="patient-details"><div><strong>Medications:</strong> <span id="patientMedications">-</span></div><div><strong>Past Assessment:</strong> <span id="patientAssessment">-</span></div></div></div><div class="modal-footer"><button id="patientLogoutBtn" class="btn-danger">Log out patient</button><a id="patientCreateBtn" class="btn-primary" href="/static/patient.html">Create new patient</a></div></div></div><!-- Audio Recording Modal --><div class="modal" id="audioRecordingModal"><div class="modal-content audio-recording-modal"><div class="modal-header"><h3>Voice Recording</h3><button class="modal-close" id="audioRecordingModalClose">×</button></div><div class="modal-body"><div class="recording-container"><div class="microphone-icon"><i class="fas fa-microphone"></i></div><div class="wave-animation" id="waveAnimation"><div class="wave-bar"></div><div class="wave-bar"></div><div class="wave-bar"></div><div class="wave-bar"></div><div class="wave-bar"></div><div class="wave-bar"></div><div class="wave-bar"></div><div class="wave-bar"></div></div><div class="recording-status" id="recordingStatus">Listening...</div><div class="recording-timer" id="recordingTimer">00:00</div></div></div><div class="modal-footer"><button class="btn btn-secondary" id="stopRecordingBtn">Stop Recording</button></div></div></div><!-- Loading overlay --><div class="loading-overlay" id="loadingOverlay"><div class="loading-spinner"><i class="fas fa-heartbeat fa-spin"></i><div class="loading-text">Processing your medical query...</div></div></div><!-- Sidebar overlay for outside-click close --><div id="sidebarOverlay" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.35);z-index:900;"></div><script type="module" src="/static/js/app.js"></script></body></html>
612 unmodified lines613614615616617618619620621622121 unmodified lines744745746747748749750751752753754755111 unmodified lines867868869870871872873874875109 unmodified lines98598698798898999099199299399499599699720 unmodified lines101810191020102110221023102410251026102711 unmodified lines1039104010411042104310441045104656 unmodified lines1103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112819 unmodified lines11481149115011511152115311541155115611574 unmodified lines1162116311641165116611671168116911701171117211737 unmodified lines118111821183118411851186118711881189119011911192119311941195119611971 unmodified line11991200120112021203120412051206120714 unmodified lines122212231224122512261227122812296 unmodified lines1236123712381239124012411242124312441245124612471248124929 unmodified lines127912801281128212831284128558 unmodified lines13441345134613471348134913501351135213531354135513561357135813591360136136 unmodified lines139813991400140114021403140411 unmodified lines1416141714181419142014211422142314241425142614276 unmodified lines143414351436143714381439144021 unmodified lines146214631464146514661467146814691470147114721473147414751476147748 unmodified lines1526152715281529153015311532153315341535153615371538153915408 unmodified lines15491550155115521553155415551 unmodified line1557155815591560156115621563146 unmodified lines171017111712171317141715171627 unmodified lines17441745174617471748174917501751175217531754175517561757175817591760176117621763113 unmodified lines1877187818791880188118821883188418851886188718881889189018914 unmodified lines1896189718981899190019011902190319041905190660 unmodified lines19671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019914 unmodified lines19961997199819992000200120024 unmodified lines20072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220434 unmodified lines2048204920502051205220532054205520562057205820592060612 unmodified lines} else {// If doctor not found in local list, try to fetch from backendtry {const resp = await fetch(`/account/search?q=${encodeURIComponent(selectedName)}&limit=1`);if (resp.ok) {const data = await resp.json();const doctor = data.results && data.results[0];if (doctor) {if (doctor.role) {roleEl.value = doctor.role;121 unmodified linesconst sessionElement = document.createElement('div');sessionElement.className = `chat-session ${session.id === this.currentSession?.id ? 'active' : ''}`;sessionElement.addEventListener('click', async () => {if (session.source === 'backend') {this.currentSession = { ...session };await this.hydrateMessagesForSession(session.id);} else {this.loadChatSession(session.id);}});const time = this.formatTime(session.lastActivity);sessionElement.innerHTML = `111 unmodified linesthrow new Error(`HTTP ${resp.status}`);}const result = await resp.json();console.log('[DEBUG] Backend deletion result:', result);// Remove from backend sessionsthis.backendSessions = this.backendSessions.filter(s => s.id !== sessionId);109 unmodified linesconst resp = await fetch('/account');if (resp.ok) {const data = await resp.json();this.doctors = data.results || [];// Ensure each doctor has role and specialty informationthis.doctors = this.doctors.map(doctor => ({name: doctor.name,role: doctor.role || 'Medical Professional',specialty: doctor.specialty || '',_id: doctor._id // API returns _id, not doctor_id}));// Also save to localStorage for offline accesslocalStorage.setItem('medicalChatbotDoctors', JSON.stringify(this.doctors));20 unmodified linesasync searchDoctors(query) {try {const resp = await fetch(`/account/search?q=${encodeURIComponent(query)}&limit=10`);if (resp.ok) {const data = await resp.json();return data.results || [];}} catch (e) {console.warn('Doctor search failed:', e);11 unmodified linesif (resp.ok) {const data = await resp.json();// Add to local doctors list// FIX: Use account_id from the responsethis.doctors.push({ name: data.name, _id: data.account_id });this.saveDoctors();return data;}56 unmodified linesif (!this.doctors.find(d => d.name === name)) {// Get current role and specialty from the formconst role = document.getElementById('profileRole').value || 'Medical Professional';const specialty = document.getElementById('profileSpecialty').value.trim() || '';// Create doctor in MongoDBconst result = await this.createDoctor({name,role,specialty,medical_roles: [role]});if (result && result.account_id) {this.doctors.unshift({name,role,specialty,_id: result.account_id // FIX: Use account_id from response});this.saveDoctors();// Update current user profilethis.currentUser.id = result.account_id; // FIX: CRITICAL - Update the user IDthis.currentUser.name = name;this.currentUser.role = role;this.currentUser.specialty = specialty;19 unmodified lines}// Check if doctor exists in MongoDB firstlet doctorExists = false;try {const resp = await fetch(`/account/${encodeURIComponent(name)}`);doctorExists = resp.ok;} catch (e) {console.warn('Failed to check doctor existence:', e);}4 unmodified linesthis.currentUser.specialty = specialty;// Only create new doctor in MongoDB if it doesn't existif (!doctorExists) {const doctorPayload = {name: name,role: role,specialty: specialty || null,medical_roles: [role]};try {7 unmodified linesconst data = await resp.json();console.log('[Doctor] Created new doctor in backend:', data);// FIX: CRITICAL - Update the current user's ID with the one from the databaseif (data.account_id) {this.currentUser.id = data.account_id;}// Update local doctor list with the ID from backendconst existingDoctorIndex = this.doctors.findIndex(d => d.name === name);if (existingDoctorIndex === -1) {this.doctors.unshift({ name, role, specialty, _id: data.account_id });} else {this.doctors[existingDoctorIndex]._id = data.account_id;}} catch (err) {1 unmodified line}} else {// If doctor exists, find their ID and update currentUserconst existingDoctor = this.doctors.find(d => d.name === name);if (existingDoctor && existingDoctor._id) {this.currentUser.id = existingDoctor._id;}console.log('[Doctor] Doctor already exists in backend, no creation needed');}14 unmodified linesconst storedPatients = JSON.parse(localStorage.getItem('medicalChatbotPatients') || '[]');return storedPatients.filter(p => {const nameMatch = p.name.toLowerCase().includes(query.toLowerCase());// FIX: Check _id field which is what the API returnsconst idMatch = p._id && p._id.includes(query);return nameMatch || idMatch;});} catch (e) {6 unmodified linesconst resultMap = new Map();// Add MongoDB results first (they take priority)mongoResults.forEach(patient => {// FIX: Use _id as the unique keyif(patient._id) resultMap.set(patient._id, patient);});// Add localStorage results only if not already presentlocalResults.forEach(patient => {// FIX: Use _id as the unique keyif (patient._id && !resultMap.has(patient._id)) {resultMap.set(patient._id, patient);}});return Array.from(resultMap.values());29 unmodified linesconst resp = await fetch(`/patient/${pid}`);if (resp.ok) {const patient = await resp.json();status.textContent = `Patient: ${patient.name || 'Unknown'} (${patient._id})`;} else {status.textContent = `Patient: ${pid}`;}58 unmodified lines// Search for patient by name or IDconsole.log('[DEBUG] Searching for patient');try {const resp = await fetch(`/patient/search?q=${encodeURIComponent(value)}&limit=1`);console.log('[DEBUG] Search response status:', resp.status);if (resp.ok) {const data = await resp.json();console.log('[DEBUG] Search results:', data);const first = (data.results || [])[0];if (first && first._id) { // FIX: Check for _idconsole.log('[DEBUG] Found patient, setting as current:', first);this.currentPatientId = first._id; // FIX: Use _id from search resultthis.savePatientId();input.value = first._id;this.updatePatientDisplay(first._id, first.name || 'Unknown');await this.fetchAndRenderPatientSessions();return;}36 unmodified linesconst resp = await fetch(`/patient/${this.currentPatientId}/session`);if (resp.ok) {const data = await resp.json();sessions = Array.isArray(data.sessions) ? data.sessions : [];// Cache the sessionslocalStorage.setItem(cacheKey, JSON.stringify({11 unmodified lines// Process sessionsthis.backendSessions = sessions.map(s => ({// FIX: Add a fallback to _id to make the frontend more robustid: s.session_id || s._id,title: s.title || 'New Chat',messages: [],createdAt: s.created_at || new Date().toISOString(),lastActivity: s.last_activity || new Date().toISOString(),source: 'backend'}));6 unmodified lines}hydrateMessagesForSession = async function (sessionId) {// FIX: Add a guard clause to prevent calling the API with an invalid IDif (!sessionId || sessionId === 'undefined') {console.error('[DEBUG] hydrateMessagesForSession was called with an invalid session ID:', sessionId);return;21 unmodified lines// If no cache or cache is stale, fetch from backendif (messages.length === 0) {const resp = await fetch(`/session/${sessionId}/messages?limit=1000`);if (!resp.ok) {console.warn(`Failed to fetch messages for session ${sessionId}:`, resp.status);return;}const data = await resp.json();const msgs = Array.isArray(data.messages) ? data.messages : [];messages = msgs.map(m => ({id: m._id || this.generateId(),role: m.role,content: m.content,timestamp: m.timestamp}));48 unmodified linesitems.forEach(p => {const div = document.createElement('div');div.className = 'patient-suggestion';// FIX: Use _id for display as it's the consistent identifierdiv.textContent = `${p.name || 'Unknown'} (${p._id})`;div.addEventListener('click', async () => {// FIX: Use _id from the patient objectthis.currentPatientId = p._id;this.savePatientId();patientInput.value = p._id;hideSuggestions();this.updatePatientDisplay(p._id, p.name || 'Unknown');await this.fetchAndRenderPatientSessions();});suggestionsEl.appendChild(div);8 unmodified linesdebounceTimer = setTimeout(async () => {try {console.log('[DEBUG] Searching patients with query:', q);const url = `/patient/search?q=${encodeURIComponent(q)}&limit=8`;console.log('[DEBUG] Search URL:', url);const resp = await fetch(url);console.log('[DEBUG] Search response status:', resp.status);1 unmodified linelet mongoResults = [];if (resp.ok) {const data = await resp.json();mongoResults = data.results || [];console.log('[DEBUG] MongoDB search results:', mongoResults);} else {console.warn('MongoDB search request failed', resp.status);146 unmodified linesthis.showLoading(true);try {const responseData = await this.callMedicalAPI(message);this.addMessage('assistant', responseData.response || 'I apologize, but I received an empty response. Please try again.');this.updateCurrentSession();27 unmodified lines}}const payload = {account_id: this.currentUser.id,patient_id: this.currentPatientId,message: message};const response = await fetch(`/session/${sessionId}/messages`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(payload)});if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);const data = await response.json();return data;} catch (error) {console.error('API call failed:', error);console.error('Error details:', {113 unmodified linesmessageElement.id = `message-${message.id}`;const avatar = message.role === 'user' ? '<i class="fas fa-user"></i>' : '<i class="fas fa-robot"></i>';const time = this.formatTime(message.timestamp);// Add EMR icon for assistant messages (system-generated)const emrIcon = message.role === 'assistant' ?`<div class="message-actions"><button class="emr-extract-btn" onclick="app.extractEMR('${message.id}')" title="Extract to EMR" data-message-id="${message.id}"><i class="fas fa-file-medical"></i></button></div>` : '';messageElement.innerHTML = `<div class="message-avatar">${avatar}</div><div class="message-content">4 unmodified lineschatMessages.appendChild(messageElement);chatMessages.scrollTop = chatMessages.scrollHeight;if (this.currentSession) this.currentSession.lastActivity = new Date().toISOString();// Check EMR status for assistant messagesif (message.role === 'assistant' && this.currentPatientId) {this.checkEMRStatus(message.id);}}formatMessageContent(content) {60 unmodified linesbutton.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';}// Call EMR extraction APIconst response = await fetch('/emr/extract', {method: 'POST',headers: {'Content-Type': 'application/json',},body: JSON.stringify({patient_id: this.currentPatientId,doctor_id: this.currentUser.id || 'default-doctor',message_id: messageId,session_id: this.currentSession?.id || 'default-session',message: message.content})});if (response.ok) {const result = await response.json();console.log('EMR extraction successful:', result);// Show success messageif (button) {button.innerHTML = '<i class="fas fa-check"></i>';4 unmodified linesbutton.disabled = false;}, 2000);}// Show notificationthis.showNotification('EMR data extracted successfully!', 'success');} else {4 unmodified lines} catch (error) {console.error('Error extracting EMR:', error);// Reset button stateconst button = document.querySelector(`[onclick="app.extractEMR('${messageId}')"]`);if (button) {button.innerHTML = '<i class="fas fa-file-medical"></i>';button.disabled = false;}// Show error messagethis.showNotification('Failed to extract EMR data. Please try again.', 'error');}}async checkEMRStatus(messageId) {try {const response = await fetch(`/emr/check/${messageId}`);if (response.ok) {const result = await response.json();const button = document.querySelector(`[data-message-id="${messageId}"]`);if (button && result.emr_exists) {button.innerHTML = '<i class="fas fa-check"></i>';button.style.color = 'var(--success-color)';button.title = 'EMR data already extracted';button.disabled = true;}}} catch (error) {console.warn('Could not check EMR status:', error);}}showNotification(message, type = 'info') {// Create notification elementconst notification = document.createElement('div');4 unmodified lines<span>${message}</span></div>`;// Add to pagedocument.body.appendChild(notification);// Show notificationsetTimeout(() => notification.classList.add('show'), 100);// Remove after 3 secondssetTimeout(() => {notification.classList.remove('show');612 unmodified lines613614615616617618619620621622121 unmodified lines744745746747748749750751752753111 unmodified lines865866867868869870109 unmodified lines98098198298398498598698798898999099199220 unmodified lines101310141015101610171018101910201021102211 unmodified lines103410351036103710381039104056 unmodified lines109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112119 unmodified lines11411142114311441145114611471148114911501151115211534 unmodified lines115811591160116111621163116411651166116711687 unmodified lines11761177117811791180118111821183118411851186118711881189119011911 unmodified line1193119411951196119711981199120014 unmodified lines12151216121712181219122012216 unmodified lines12281229123012311232123312341235123612371238123929 unmodified lines126912701271127212731274127558 unmodified lines13341335133613371338133913401341134213431344134513461347134813491350135136 unmodified lines138813891390139113921393139411 unmodified lines140614071408140914101411141214131414141514166 unmodified lines14231424142514261427142821 unmodified lines145014511452145314541455145614571458145914601461146214631464146548 unmodified lines15141515151615171518151915201521152215231524152515268 unmodified lines15351536153715381539154015411 unmodified line1543154415451546154715481549146 unmodified lines16961697169816991700170127 unmodified lines1729173017311732173317341735173617371738173917401741174217431744174517461747174817491750113 unmodified lines1864186518661867186818691870187118721873187418751876187718784 unmodified lines18831884188518861887188860 unmodified lines19491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519764 unmodified lines19811982198319841985198619874 unmodified lines19921993199419951996199719981999200020012002200320042005200620072008200920104 unmodified lines2015201620172018201920202021202220232024202520262027612 unmodified lines} else {// If doctor not found in local list, try to fetch from backendtry {const resp = await fetch(`/account?q=${encodeURIComponent(selectedName)}&limit=1`);if (resp.ok) {const data = await resp.json();const doctor = data && data[0];if (doctor) {if (doctor.role) {roleEl.value = doctor.role;121 unmodified linesconst sessionElement = document.createElement('div');sessionElement.className = `chat-session ${session.id === this.currentSession?.id ? 'active' : ''}`;sessionElement.addEventListener('click', async () => {// Avoid re-loading if the session is already activeif (session.id === this.currentSession?.id) return;await this.switchToSession(session);});const time = this.formatTime(session.lastActivity);sessionElement.innerHTML = `111 unmodified linesthrow new Error(`HTTP ${resp.status}`);}// Remove from backend sessionsthis.backendSessions = this.backendSessions.filter(s => s.id !== sessionId);109 unmodified linesconst resp = await fetch('/account');if (resp.ok) {const data = await resp.json();this.doctors = data || [];// Ensure each doctor has role and specialty informationthis.doctors = this.doctors.map(doctor => ({name: doctor.name,role: doctor.role || 'Medical Professional',specialty: doctor.specialty || '',id: doctor.id}));// Also save to localStorage for offline accesslocalStorage.setItem('medicalChatbotDoctors', JSON.stringify(this.doctors));20 unmodified linesasync searchDoctors(query) {try {const resp = await fetch(`/account?q=${encodeURIComponent(query)}&limit=10`);if (resp.ok) {const data = await resp.json();return data || [];}} catch (e) {console.warn('Doctor search failed:', e);11 unmodified linesif (resp.ok) {const data = await resp.json();// Add to local doctors listthis.doctors.push({ name: data.name, id: data.id });this.saveDoctors();return data;}56 unmodified linesif (!this.doctors.find(d => d.name === name)) {// Get current role and specialty from the formconst role = document.getElementById('profileRole').value || 'Medical Professional';const specialty = document.getElementById('profileSpecialty').value.trim() || null;// Create doctor in MongoDBconst result = await this.createDoctor({name,role,specialty});if (result && result.id) {this.doctors.unshift({name,role,specialty,id: result.id});this.saveDoctors();// Update current user profilethis.currentUser.id = result.id;this.currentUser.name = name;this.currentUser.role = role;this.currentUser.specialty = specialty;19 unmodified lines}// Check if doctor exists in MongoDB firstlet existingDoctor = null;try {const resp = await fetch(`/account?q=${encodeURIComponent(name)}`);if(resp.ok) {const accounts = await resp.json();existingDoctor = accounts.find(acc => acc.name === name);}} catch (e) {console.warn('Failed to check doctor existence:', e);}4 unmodified linesthis.currentUser.specialty = specialty;// Only create new doctor in MongoDB if it doesn't existif (!existingDoctor) {const doctorPayload = {name: name,role: role,specialty: specialty || null};try {7 unmodified linesconst data = await resp.json();console.log('[Doctor] Created new doctor in backend:', data);if (data.id) {this.currentUser.id = data.id;}// Update local doctor list with the ID from backendconst existingDoctorIndex = this.doctors.findIndex(d => d.name === name);if (existingDoctorIndex === -1) {this.doctors.unshift({ name, role, specialty, id: data.id });} else {this.doctors[existingDoctorIndex].id = data.id;}} catch (err) {1 unmodified line}} else {// If doctor exists, find their ID and update currentUserif (existingDoctor && existingDoctor.id) {this.currentUser.id = existingDoctor.id;}console.log('[Doctor] Doctor already exists in backend, no creation needed');}14 unmodified linesconst storedPatients = JSON.parse(localStorage.getItem('medicalChatbotPatients') || '[]');return storedPatients.filter(p => {const nameMatch = p.name.toLowerCase().includes(query.toLowerCase());const idMatch = p.id && p.id.includes(query);return nameMatch || idMatch;});} catch (e) {6 unmodified linesconst resultMap = new Map();// Add MongoDB results first (they take priority)mongoResults.forEach(patient => {if(patient.id) resultMap.set(patient.id, patient);});// Add localStorage results only if not already presentlocalResults.forEach(patient => {if (patient.id && !resultMap.has(patient.id)) {resultMap.set(patient.id, patient);}});return Array.from(resultMap.values());29 unmodified linesconst resp = await fetch(`/patient/${pid}`);if (resp.ok) {const patient = await resp.json();status.textContent = `Patient: ${patient.name || 'Unknown'} (${patient.id})`;} else {status.textContent = `Patient: ${pid}`;}58 unmodified lines// Search for patient by name or IDconsole.log('[DEBUG] Searching for patient');try {const resp = await fetch(`/patient?q=${encodeURIComponent(value)}&limit=1`);console.log('[DEBUG] Search response status:', resp.status);if (resp.ok) {const data = await resp.json();console.log('[DEBUG] Search results:', data);const first = (data || [])[0];if (first && first.id) {console.log('[DEBUG] Found patient, setting as current:', first);this.currentPatientId = first.id;this.savePatientId();input.value = first.id;this.updatePatientDisplay(first.id, first.name || 'Unknown');await this.fetchAndRenderPatientSessions();return;}36 unmodified linesconst resp = await fetch(`/patient/${this.currentPatientId}/session`);if (resp.ok) {const data = await resp.json();sessions = Array.isArray(data) ? data : [];// Cache the sessionslocalStorage.setItem(cacheKey, JSON.stringify({11 unmodified lines// Process sessionsthis.backendSessions = sessions.map(s => ({id: s.id,title: s.title || 'New Chat',messages: [],createdAt: s.created_at || new Date().toISOString(),lastActivity: s.updated_at || new Date().toISOString(),source: 'backend'}));6 unmodified lines}hydrateMessagesForSession = async function (sessionId) {if (!sessionId || sessionId === 'undefined') {console.error('[DEBUG] hydrateMessagesForSession was called with an invalid session ID:', sessionId);return;21 unmodified lines// If no cache or cache is stale, fetch from backendif (messages.length === 0) {const resp = await fetch(`/session/${sessionId}/messages`);if (!resp.ok) {console.warn(`Failed to fetch messages for session ${sessionId}:`, resp.status);return;}const data = await resp.json();const msgs = Array.isArray(data) ? data : [];messages = msgs.map(m => ({id: m.id || this.generateId(),role: m.sent_by_user ? 'user' : 'assistant',content: m.content,timestamp: m.timestamp}));48 unmodified linesitems.forEach(p => {const div = document.createElement('div');div.className = 'patient-suggestion';div.textContent = `${p.name || 'Unknown'} (${p.id})`;div.addEventListener('click', async () => {this.currentPatientId = p.id;this.savePatientId();patientInput.value = p.id;hideSuggestions();this.updatePatientDisplay(p.id, p.name || 'Unknown');await this.fetchAndRenderPatientSessions();});suggestionsEl.appendChild(div);8 unmodified linesdebounceTimer = setTimeout(async () => {try {console.log('[DEBUG] Searching patients with query:', q);const url = `/patient?q=${encodeURIComponent(q)}&limit=8`;console.log('[DEBUG] Search URL:', url);const resp = await fetch(url);console.log('[DEBUG] Search response status:', resp.status);1 unmodified linelet mongoResults = [];if (resp.ok) {const data = await resp.json();mongoResults = data || [];console.log('[DEBUG] MongoDB search results:', mongoResults);} else {console.warn('MongoDB search request failed', resp.status);146 unmodified linesthis.showLoading(true);try {const responseData = await this.callMedicalAPI(message);this.addMessage('assistant', responseData.response || 'I apologize, but I received an empty response. Please try again.');this.updateCurrentSession();27 unmodified lines}}const messagePayload = {account_id: this.currentUser.id,patient_id: this.currentPatientId,message: message};const messageResponse = await fetch(`/session/${sessionId}/messages`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(messagePayload)});if (!messageResponse.ok) throw new Error(`HTTP error! status: ${messageResponse.status}`);const data = await messageResponse.json();return data;} catch (error) {console.error('API call failed:', error);console.error('Error details:', {113 unmodified linesmessageElement.id = `message-${message.id}`;const avatar = message.role === 'user' ? '<i class="fas fa-user"></i>' : '<i class="fas fa-robot"></i>';const time = this.formatTime(message.timestamp);// Add EMR icon for assistant messages (system-generated)const emrIcon = message.role === 'assistant' ?`<div class="message-actions"><button class="emr-extract-btn" onclick="app.extractEMR('${message.id}')" title="Extract to EMR" data-message-id="${message.id}"><i class="fas fa-file-medical"></i></button></div>` : '';messageElement.innerHTML = `<div class="message-avatar">${avatar}</div><div class="message-content">4 unmodified lineschatMessages.appendChild(messageElement);chatMessages.scrollTop = chatMessages.scrollHeight;if (this.currentSession) this.currentSession.lastActivity = new Date().toISOString();}formatMessageContent(content) {60 unmodified linesbutton.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';}// Build URL with query parametersconst params = new URLSearchParams({patient_id: this.currentPatientId,doctor_id: this.currentUser.id || 'default-doctor',message_id: messageId,session_id: this.currentSession?.id || 'default-session',message: message.content});const url = `/emr/extract?${params.toString()}`;// Call EMR extraction APIconst response = await fetch(url, {method: 'POST',headers: {'Content-Type': 'application/json', // Header might still be needed by middleware}});if (response.ok) {const result = await response.json();console.log('EMR extraction successful:', result);// Show success messageif (button) {button.innerHTML = '<i class="fas fa-check"></i>';4 unmodified linesbutton.disabled = false;}, 2000);}// Show notificationthis.showNotification('EMR data extracted successfully!', 'success');} else {4 unmodified lines} catch (error) {console.error('Error extracting EMR:', error);// Reset button stateconst button = document.querySelector(`[onclick="app.extractEMR('${messageId}')"]`);if (button) {button.innerHTML = '<i class="fas fa-file-medical"></i>';button.disabled = false;}// Show error messagethis.showNotification('Failed to extract EMR data. Please try again.', 'error');}}showNotification(message, type = 'info') {// Create notification elementconst notification = document.createElement('div');4 unmodified lines<span>${message}</span></div>`;// Add to pagedocument.body.appendChild(notification);// Show notificationsetTimeout(() => notification.classList.add('show'), 100);// Remove after 3 secondssetTimeout(() => {notification.classList.remove('show');
14 unmodified lines15161718192021222366 unmodified lines9091929394959697989910010110210310410510610710816 unmodified lines12512612712812913013114 unmodified linesfunction getPatientIdFromUrl() {const urlParams = new URLSearchParams(window.location.search);const pidFromUrl = urlParams.get('patient_id');if (pidFromUrl && /^\d{8}$/.test(pidFromUrl)) return pidFromUrl;return null;}async function loadPatientIntoForm(patientId) {66 unmodified lines});if (!resp.ok) throw new Error(`HTTP ${resp.status}`);const data = await resp.json();const pid = data.patient_id;localStorage.setItem('medicalChatbotPatientId', pid);// Add to localStorage for future suggestionsconst existingPatients = JSON.parse(localStorage.getItem('medicalChatbotPatients') || '[]');const newPatient = {patient_id: pid,name: payload.name,age: payload.age,sex: payload.sex};// Check if patient already exists to avoid duplicatesconst exists = existingPatients.some(p => p.patient_id === pid);if (!exists) {existingPatients.push(newPatient);localStorage.setItem('medicalChatbotPatients', JSON.stringify(existingPatients));16 unmodified linesif (successEdit) successEdit.addEventListener('click', () => {successModal.classList.remove('show');const pid = createdIdEl?.textContent?.trim() || localStorage.getItem('medicalChatbotPatientId');if (pid && /^\d{8}$/.test(pid)) {enableEditMode(pid);loadPatientIntoForm(pid);}14 unmodified lines15161718192021222366 unmodified lines9091929394959697989910010110210310410510610710816 unmodified lines12512612712812913013113213313413513614 unmodified linesfunction getPatientIdFromUrl() {const urlParams = new URLSearchParams(window.location.search);// The API uses a generic string 'id', but we'll keep the client-side validation for now.const pidFromUrl = urlParams.get('patient_id');return pidFromUrl;}async function loadPatientIntoForm(patientId) {66 unmodified lines});if (!resp.ok) throw new Error(`HTTP ${resp.status}`);const data = await resp.json();const pid = data.id;localStorage.setItem('medicalChatbotPatientId', pid);// Add to localStorage for future suggestionsconst existingPatients = JSON.parse(localStorage.getItem('medicalChatbotPatients') || '[]');const newPatient = {id: pid,name: payload.name,age: payload.age,sex: payload.sex};// Check if patient already exists to avoid duplicatesconst exists = existingPatients.some(p => p.id === pid);if (!exists) {existingPatients.push(newPatient);localStorage.setItem('medicalChatbotPatients', JSON.stringify(existingPatients));16 unmodified linesif (successEdit) successEdit.addEventListener('click', () => {successModal.classList.remove('show');const pid = createdIdEl?.textContent?.trim() || localStorage.getItem('medicalChatbotPatientId');if (pid) {// Update URL to reflect edit mode for clarity and reload safetyconst newUrl = new URL(window.location.href);newUrl.searchParams.set('patient_id', pid);window.history.pushState({ path: newUrl.href }, '', newUrl.href);enableEditMode(pid);loadPatientIntoForm(pid);}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Create Patient</title><link rel="stylesheet" href="/static/css/patient.css"><link rel="icon" type="image/svg+xml" href="/static/icon.svg"><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"></head><body><div class="container"><a href="/" class="back-link"><i class="fas fa-arrow-left"></i> Back to Assistant</a><h1>Create Patient</h1><form id="patientForm"><div class="grid"><!-- Row 1: Name and Age --><div class="row"><label>Name<input type="text" id="name" required></label><label>Age<input type="number" id="age" min="0" max="130" required></label></div><!-- Row 2: Sex and Ethnicity --><div class="row"><label>Sex<select id="sex" required><option value="Male">Male</option><option value="Female">Female</option><option value="Intersex">Intersex</option></select></label><label>Ethnicity<input type="text" id="ethnicity"></label></div><!-- Row 3: Contact Information --><div class="row contact-info"><label>Phone<input type="tel" id="phone"></label><label>Email<input type="email" id="email"></label><label>Address<input type="text" id="address"></label></div><!-- Row 4: Medical Information --><div class="row"><label>Active Medications<textarea id="medications" placeholder="One per line"></textarea></label><label>Past Assessment Summary<textarea id="summary"></textarea></label></div></div><div class="actions"><button type="button" id="cancelBtn" class="secondary">Cancel</button><button type="submit" class="primary">Create</button></div></form><div id="result" class="result"></div></div><!-- Success Modal --><div class="modal" id="patientSuccessModal"><div class="modal-content"><div class="modal-header"><h3>Patient Created</h3><button class="modal-close" id="patientSuccessClose">×</button></div><div class="modal-body"><p>Your new Patient ID is:</p><div id="createdPatientId" class="big-id"></div></div><div class="modal-footer"><button class="secondary" id="patientSuccessReturn">Return to main page</button><button class="primary" id="patientSuccessEdit">Edit patient profile</button></div></div></div><script src="/static/js/patient.js"></script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Create Patient</title><link rel="stylesheet" href="/static/css/patient.css"><link rel="icon" type="image/svg+xml" href="/static/icon.svg"><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"></head><body><div class="container"><a href="/" class="back-link"><i class="fas fa-arrow-left"></i> Back to Assistant</a><h1>Create Patient</h1><form id="patientForm"><div class="grid"><!-- Row 1: Name and Age --><div class="row"><label>Name<input type="text" id="name" required></label><label>Age<input type="number" id="age" min="0" max="130" required></label></div><!-- Row 2: Sex and Ethnicity --><div class="row"><label>Sex<select id="sex" required><option value="Male">Male</option><option value="Female">Female</option><option value="Intersex">Intersex</option></select></label><label>Ethnicity<input type="text" id="ethnicity"></label></div><!-- Row 3: Contact Information --><div class="row contact-info"><label>Phone<input type="tel" id="phone"></label><label>Email<input type="email" id="email"></label><label>Address<input type="text" id="address"></label></div><!-- Row 4: Medical Information --><div class="row"><label>Active Medications<textarea id="medications" placeholder="One per line"></textarea></label><label>Past Assessment Summary<textarea id="summary"></textarea></label></div></div><div class="actions"><button type="button" id="cancelBtn" class="secondary">Cancel</button><button type="submit" class="primary">Create</button></div></form><div id="result" class="result"></div></div><!-- Success Modal --><div class="modal" id="patientSuccessModal"><div class="modal-content"><div class="modal-header"><h3>Patient Created</h3><button class="modal-close" id="patientSuccessClose">×</button></div><div class="modal-body"><p>Your new Patient ID is:</p><div id="createdPatientId" class="big-id"></div></div><div class="modal-footer"><button class="secondary" id="patientSuccessReturn">Return to main page</button><button class="primary" id="patientSuccessEdit">Edit patient profile</button></div></div></div><script src="/static/js/patient.js"></script></body></html>
API Endpoint Breakdown.mdAdded+230
requirements-dev.txt+1-1
src/models/common.py+3-2
src/models/session.py+5-1
static/index.html+303-303
static/js/app.js+84-117
static/js/patient.js+11-6
static/patient.html+64-64