const fs = require('fs'); const path = require('path'); const DATA_DIR = path.join(__dirname, 'data'); const AUDIO_DIR = path.join(DATA_DIR, 'audio'); const DB_FILE = path.join(DATA_DIR, 'db.json'); // Ensure directories exist if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true }); if (!fs.existsSync(AUDIO_DIR)) fs.mkdirSync(AUDIO_DIR, { recursive: true }); const INITIAL_DB = { doctors: [ { doctor_id: "DOC-001", name: "Dr. Sharma", department: "Cardiology / Oncology", specialization: "Clinical Specialist", phone: "+91 98230 11223", created_at: "2026-01-01T00:00:00.000Z" }, { doctor_id: "DOC-002", name: "Dr. Mehta", department: "Internal Medicine", specialization: "General Physician", phone: "+91 98230 44556", created_at: "2026-01-10T00:00:00.000Z" }, { doctor_id: "DOC-003", name: "Dr. Patil", department: "Surgical Oncology", specialization: "Surgeon", phone: "+91 98230 77889", created_at: "2026-02-01T00:00:00.000Z" } ], patients: [ { patient_id: "PT-2026-00124", name: "Sanika Gurav", age: 34, gender: "Female", phone: "+91 98765 43210", created_at: "2026-08-15T09:00:00.000Z" }, { patient_id: "PT-2026-00125", name: "Rahul Patil", age: 42, gender: "Male", phone: "+91 98765 88990", created_at: "2026-08-20T10:30:00.000Z" }, { patient_id: "PT-2026-00126", name: "Amit Singh", age: 51, gender: "Male", phone: "+91 98765 11223", created_at: "2026-08-22T11:15:00.000Z" }, { patient_id: "PT-2026-00127", name: "Priya Reddy", age: 29, gender: "Female", phone: "+91 98765 33445", created_at: "2026-08-25T14:00:00.000Z" }, { patient_id: "PT-2026-00128", name: "Vikram Kumar", age: 63, gender: "Male", phone: "+91 98765 55667", created_at: "2026-08-28T16:45:00.000Z" } ], consultations: [ { consultation_id: "CONS-2026-000001", patient_id: "PT-2026-00124", patient_name: "Sanika Gurav", doctor_id: "DOC-001", doctor_name: "Dr. Sharma", consultation_date: "2026-09-01", time_formatted: "10:30 AM", duration_seconds: 755, duration_formatted: "12 min 35 sec", audio_file: null, language: "mr-IN", transcript: "**Doctor:** नमस्कार. या, बसा. तुम्हाला नेमका काय त्रास होतो आहे?\n\n**Patient:** नमस्कार डॉक्टर. मला गेल्या तीन दिवसांपासून पोटात दुखत आहे आणि पोटावरच्या surgery च्या जखमेजवळून थोडंसं पाणी येत आहे.\n\n**Doctor:** ठीक आहे. तुमची surgery कधी झाली होती?\n\n**Patient:** साधारण दोन आठवड्यांपूर्वी appendix ची laparoscopic surgery झाली होती.\n\n**Doctor:** जखमेतून येणारं पाणी कसं आहे? पारदर्शक आहे की पिवळसर? त्याला वास येतो का?\n\n**Patient:** सुरुवातीला थोडंसं पारदर्शक होतं, पण कालपासून पिवळसर दिसत आहे. हलका वाससुद्धा येतो.\n\n**Doctor:** जखमेच्या आसपास लालसरपणा, सूज किंवा जास्त गरमपणा जाणवतो का?\n\n**Patient:** हो डॉक्टर, थोडी सूज आली आहे आणि त्या जागेला स्पर्श केला की दुखतं.\n\n**Doctor:** ताप येतो आहे का?\n\n**Patient:** काल रात्री 101 डिग्रीपर्यंत ताप होता. Paracetamol घेतल्यानंतर कमी झाला.\n\n**Doctor:** उलटी, मळमळ किंवा भूक कमी लागणे असे काही आहे का?", speaker_segments: [ { speaker: "Doctor", text: "नमस्कार. या, बसा. तुम्हाला नेमका काय त्रास होतो आहे?" }, { speaker: "Patient", text: "नमस्कार डॉक्टर. मला गेल्या तीन दिवसांपासून पोटात दुखत आहे आणि पोटावरच्या surgery च्या जखमेजवळून थोडंसं पाणी येत आहे." }, { speaker: "Doctor", text: "ठीक आहे. तुमची surgery कधी झाली होती?" }, { speaker: "Patient", text: "साधारण दोन आठवड्यांपूर्वी appendix ची laparoscopic surgery झाली होती." }, { speaker: "Doctor", text: "जखमेतून येणारं पाणी कसं आहे? पारदर्शक आहे की पिवळसर? त्याला वास येतो का?" }, { speaker: "Patient", text: "सुरुवातीला थोडंसं पारदर्शक होतं, पण कालपासून पिवळसर दिसत आहे. हलका वाससुद्धा येतो." }, { speaker: "Doctor", text: "जखमेच्या आसपास लालसरपणा, सूज किंवा जास्त गरमपणा जाणवतो का?" }, { speaker: "Patient", text: "हो डॉक्टर, थोडी सूज आली आहे आणि त्या जागेला स्पर्श केला की दुखतं." }, { speaker: "Doctor", text: "ताप येतो आहे का?" }, { speaker: "Patient", text: "काल रात्री 101 डिग्रीपर्यंत ताप होता. Paracetamol घेतल्यानंतर कमी झाला." }, { speaker: "Doctor", text: "उलटी, मळमळ किंवा भूक कमी लागणे असे काही आहे का?" } ], summary: { chief_complaint: "Abdominal pain and discharge near surgery site for 3 days", symptoms: ["Abdominal pain", "Mild fever (101°F)", "Yellowish discharge with mild odor", "Tenderness and localized swelling"], history: "Laparoscopic appendectomy performed 2 weeks ago", assessment: "Post-operative surgical site superficial seroma / mild wound infection", recommendation: "Wound cleaning and dressing, oral antibiotics course, follow-up in 3 days" }, status: "Completed", created_at: "2026-09-01T10:30:00.000Z", updated_at: "2026-09-01T10:45:00.000Z" }, { consultation_id: "CONS-2026-000002", patient_id: "PT-2026-00125", patient_name: "Rahul Patil", doctor_id: "DOC-001", doctor_name: "Dr. Sharma", consultation_date: "2026-08-31", time_formatted: "09:15 AM", duration_seconds: 500, duration_formatted: "08 min 20 sec", audio_file: null, language: "mr-IN", transcript: "**Doctor:** राहुलजी, आज कसे आहात? BP च्या गोळ्या नियमित घेताय ना?\n\n**Patient:** हो डॉक्टर, पण कालपासून छातीत किंचित जडपणा वाटतोय.", speaker_segments: [ { speaker: "Doctor", text: "राहुलजी, आज कसे आहात? BP च्या गोळ्या नियमित घेताय ना?" }, { speaker: "Patient", text: "हो डॉक्टर, पण कालपासून छातीत किंचित जडपणा वाटतोय." } ], summary: { chief_complaint: "Mild chest heaviness and hypertension review", symptoms: ["Chest heaviness", "Mild fatigue"], history: "Hypertension for 5 years on Telmisartan 40mg", assessment: "Essential Hypertension with exertional discomfort", recommendation: "ECG, 2D Echo recommended, continue regular anti-hypertensives" }, status: "Processing", created_at: "2026-08-31T09:15:00.000Z", updated_at: "2026-08-31T09:25:00.000Z" }, { consultation_id: "CONS-2026-000003", patient_id: "PT-2026-00126", patient_name: "Amit Singh", doctor_id: "DOC-001", doctor_name: "Dr. Sharma", consultation_date: "2026-08-28", time_formatted: "04:40 PM", duration_seconds: 910, duration_formatted: "15 min 10 sec", audio_file: null, language: "hi-IN", transcript: "**Doctor:** अमितजी, आपकी शुगर रिपोर्ट देखी। फास्टिंग 140 आई है।\n\n**Patient:** जी डॉक्टर साहब, मीठा कम कर दिया है फिर भी थोड़ा ज्यादा है।", speaker_segments: [ { speaker: "Doctor", text: "अमितजी, आपकी शुगर रिपोर्ट देखी। फास्टिंग 140 आई है।" }, { speaker: "Patient", text: "जी डॉक्टर साहब, मीठा कम कर दिया है फिर भी थोड़ा ज्यादा है।" } ], summary: { chief_complaint: "Diabetes follow up and elevated fasting blood glucose", symptoms: ["Increased thirst", "Occasional weakness"], history: "Type 2 Diabetes Mellitus for 3 years", assessment: "Uncontrolled Fasting Hyperglycemia", recommendation: "Adjust Metformin dosage to 500mg BD, dietary counseling, HbA1c test" }, status: "Completed", created_at: "2026-08-28T16:40:00.000Z", updated_at: "2026-08-28T17:00:00.000Z" }, { consultation_id: "CONS-2026-000004", patient_id: "PT-2026-00127", patient_name: "Priya Reddy", doctor_id: "DOC-002", doctor_name: "Dr. Mehta", consultation_date: "2026-08-25", time_formatted: "11:20 AM", duration_seconds: 605, duration_formatted: "10 min 05 sec", audio_file: null, language: "en-IN", transcript: "**Doctor:** Good morning Priya. Are you still experiencing seasonal allergies and throat irritation?\n\n**Patient:** Yes doctor, especially in the mornings with dry coughing.", speaker_segments: [ { speaker: "Doctor", text: "Good morning Priya. Are you still experiencing seasonal allergies and throat irritation?" }, { speaker: "Patient", text: "Yes doctor, especially in the mornings with dry coughing." } ], summary: { chief_complaint: "Morning allergic rhinitis and dry cough", symptoms: ["Sneezing", "Dry cough", "Throat itchiness"], history: "Seasonal pollen allergies", assessment: "Allergic Rhinitis with Pharyngeal irritation", recommendation: "Antihistamine (Levocetirizine 5mg) at night, saline nasal spray, steam inhalation" }, status: "Doctor Reviewed", created_at: "2026-08-25T11:20:00.000Z", updated_at: "2026-08-25T11:35:00.000Z" }, { consultation_id: "CONS-2026-000005", patient_id: "PT-2026-00128", patient_name: "Vikram Kumar", doctor_id: "DOC-001", doctor_name: "Dr. Sharma", consultation_date: "2026-08-20", time_formatted: "03:30 PM", duration_seconds: 585, duration_formatted: "09 min 45 sec", audio_file: null, language: "mr-IN", transcript: "**Doctor:** विक्रमजी, गुडघ्यांचे दुखणे कसे आहे आता?\n\n**Patient:** फिजिओथेरपीनंतर थोडा आराम आहे डॉक्टर, पण जिने चढताना त्रास होतो.", speaker_segments: [ { speaker: "Doctor", text: "विक्रमजी, गुडघ्यांचे दुखणे कसे आहे आता?" }, { speaker: "Patient", text: "फिजिओथेरपीनंतर थोडा आराम आहे डॉक्टर, पण जिने चढताना त्रास होतो." } ], summary: { chief_complaint: "Bilateral knee osteoarthritis follow-up", symptoms: ["Joint stiffness", "Pain while climbing stairs"], history: "Osteoarthritis for 4 years, post knee physiotherapy", assessment: "Bilateral Knee Osteoarthritis Grade II", recommendation: "Continue quadriceps strengthening exercises, Calcium + Vit D3 supplements" }, status: "Completed", created_at: "2026-08-20T15:30:00.000Z", updated_at: "2026-08-20T15:45:00.000Z" }, { consultation_id: "CONS-2026-000006", patient_id: "PT-2026-00124", patient_name: "Sanika Gurav", doctor_id: "DOC-001", doctor_name: "Dr. Sharma", consultation_date: "2026-08-28", time_formatted: "11:00 AM", duration_seconds: 480, duration_formatted: "08 min 00 sec", audio_file: null, language: "mr-IN", transcript: "**Doctor:** सानिकाजी, शस्त्रक्रियेनंतरची पहिली तपासणी करूया.\n\n**Patient:** हो डॉक्टर, जखम कोरडी वाटत आहे.", speaker_segments: [ { speaker: "Doctor", text: "सानिकाजी, शस्त्रक्रियेनंतरची पहिली तपासणी करूया." }, { speaker: "Patient", text: "हो डॉक्टर, जखम कोरडी वाटत आहे." } ], summary: { chief_complaint: "Post-op laparoscopic appendectomy 1-week follow-up", symptoms: ["Mild incision site discomfort"], history: "Recent appendectomy", assessment: "Healing surgical wound", recommendation: "Keep dressing clean and dry, return if fever or pain occurs" }, status: "Completed", created_at: "2026-08-28T11:00:00.000Z", updated_at: "2026-08-28T11:15:00.000Z" } ] }; function readDB() { try { if (!fs.existsSync(DB_FILE)) { writeDB(INITIAL_DB); return INITIAL_DB; } const data = fs.readFileSync(DB_FILE, 'utf8'); return JSON.parse(data); } catch (err) { console.error('Error reading DB, resetting to initial:', err); writeDB(INITIAL_DB); return INITIAL_DB; } } function writeDB(data) { try { fs.writeFileSync(DB_FILE, JSON.stringify(data, null, 2), 'utf8'); } catch (err) { console.error('Error writing to DB file:', err); } } // Ensure DB is initialized readDB(); module.exports = { AUDIO_DIR, // ── Patients ── getPatients: (search = '') => { const db = readDB(); if (!search) return db.patients; const s = search.toLowerCase(); return db.patients.filter(p => p.name.toLowerCase().includes(s) || p.patient_id.toLowerCase().includes(s) || (p.phone && p.phone.includes(s)) ); }, getPatientById: (patient_id) => { const db = readDB(); return db.patients.find(p => p.patient_id === patient_id) || null; }, createPatient: (patientData) => { const db = readDB(); // BUG 4 FIX: count-based ID नाही — delete नंतर collision होते // max existing ID + 1 वापरा const existingNums = db.patients.map(p => { const parts = p.patient_id.split('-'); return parseInt(parts[parts.length - 1]) || 0; }); const nextNum = (existingNums.length > 0 ? Math.max(...existingNums) : 0) + 1; const newId = patientData.patient_id || `PT-2026-${String(nextNum).padStart(5, '0')}`; const newPatient = { patient_id: newId, name: patientData.name || 'Unnamed Patient', age: Number(patientData.age) || 30, gender: patientData.gender || 'Other', phone: patientData.phone || '', created_at: new Date().toISOString() }; // Check if exists const idx = db.patients.findIndex(p => p.patient_id === newId); if (idx >= 0) { db.patients[idx] = { ...db.patients[idx], ...newPatient }; } else { db.patients.unshift(newPatient); } writeDB(db); return newPatient; }, updatePatient: (patient_id, updateData) => { const db = readDB(); const idx = db.patients.findIndex(p => p.patient_id === patient_id); if (idx === -1) return null; db.patients[idx] = { ...db.patients[idx], ...updateData }; writeDB(db); return db.patients[idx]; }, // ── Doctors ── getDoctors: () => { const db = readDB(); return db.doctors; }, getDoctorById: (doctor_id) => { const db = readDB(); return db.doctors.find(d => d.doctor_id === doctor_id) || null; }, createDoctor: (doctorData) => { const db = readDB(); // BUG 4 FIX: max ID + 1 approach for doctors too const existingNums = db.doctors.map(d => { const parts = d.doctor_id.split('-'); return parseInt(parts[parts.length - 1]) || 0; }); const nextNum = (existingNums.length > 0 ? Math.max(...existingNums) : 0) + 1; const newId = doctorData.doctor_id || `DOC-${String(nextNum).padStart(3, '0')}`; const newDoctor = { doctor_id: newId, name: doctorData.name, department: doctorData.department || 'General Medicine', specialization: doctorData.specialization || 'Consultant', phone: doctorData.phone || '', created_at: new Date().toISOString() }; db.doctors.push(newDoctor); writeDB(db); return newDoctor; }, // ── Consultations ── getConsultations: (filters = {}) => { const db = readDB(); let list = [...db.consultations]; if (filters.patient_id) { list = list.filter(c => c.patient_id === filters.patient_id); } if (filters.doctor_id) { list = list.filter(c => c.doctor_id === filters.doctor_id); } if (filters.status && filters.status !== 'All' && filters.status !== 'all') { list = list.filter(c => c.status.toLowerCase() === filters.status.toLowerCase()); } if (filters.date) { list = list.filter(c => c.consultation_date === filters.date); } if (filters.date_range) { const today = new Date().toISOString().slice(0, 10); if (filters.date_range === 'Today' || filters.date_range === 'today') { list = list.filter(c => c.consultation_date === today); } else if (filters.date_range === 'This Week' || filters.date_range === 'this_week') { const d = new Date(); d.setDate(d.getDate() - 7); const weekAgo = d.toISOString().slice(0, 10); list = list.filter(c => c.consultation_date >= weekAgo); } else if (filters.date_range === 'This Month' || filters.date_range === 'this_month') { const d = new Date(); d.setDate(d.getDate() - 30); const monthAgo = d.toISOString().slice(0, 10); list = list.filter(c => c.consultation_date >= monthAgo); } } if (filters.search) { const s = filters.search.toLowerCase(); list = list.filter(c => (c.patient_name && c.patient_name.toLowerCase().includes(s)) || (c.doctor_name && c.doctor_name.toLowerCase().includes(s)) || (c.patient_id && c.patient_id.toLowerCase().includes(s)) || (c.consultation_id && c.consultation_id.toLowerCase().includes(s)) || (c.transcript && c.transcript.toLowerCase().includes(s)) ); } // Sort newest first list.sort((a, b) => new Date(b.created_at) - new Date(a.created_at)); return list; }, getConsultationById: (consultation_id) => { const db = readDB(); return db.consultations.find(c => c.consultation_id === consultation_id) || null; }, createConsultation: (consultationData) => { const db = readDB(); // BUG 4 FIX: max ID + 1 approach for consultations too const existingNums = db.consultations.map(c => { const parts = c.consultation_id.split('-'); return parseInt(parts[parts.length - 1]) || 0; }); const nextNum = (existingNums.length > 0 ? Math.max(...existingNums) : 0) + 1; const newId = consultationData.consultation_id || `CONS-2026-${String(nextNum).padStart(6, '0')}`; // Calculate duration format const durSecs = Number(consultationData.duration_seconds) || 0; const mins = Math.floor(durSecs / 60); const secs = durSecs % 60; const durFormatted = `${String(mins).padStart(2, '0')} min ${String(secs).padStart(2, '0')} sec`; const now = new Date(); const timeFormatted = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true }); const newConsultation = { consultation_id: newId, patient_id: consultationData.patient_id || 'PT-2026-00124', patient_name: consultationData.patient_name || 'Sanika Gurav', doctor_id: consultationData.doctor_id || 'DOC-001', doctor_name: consultationData.doctor_name || 'Dr. Sharma', consultation_date: consultationData.consultation_date || now.toISOString().slice(0, 10), time_formatted: consultationData.time_formatted || timeFormatted, duration_seconds: durSecs, duration_formatted: consultationData.duration_formatted || durFormatted, audio_file: consultationData.audio_file || null, language: consultationData.language || 'mr-IN', transcript: consultationData.transcript || '', speaker_segments: consultationData.speaker_segments || [], summary: consultationData.summary || { chief_complaint: 'Consultation conducted', symptoms: [], history: 'Not specified', assessment: 'Clinical evaluation', recommendation: 'Follow standard care' }, status: consultationData.status || 'Completed', created_at: now.toISOString(), updated_at: now.toISOString() }; // Auto-create patient if not present in DB const patientExists = db.patients.some(p => p.patient_id === newConsultation.patient_id); if (!patientExists) { db.patients.unshift({ patient_id: newConsultation.patient_id, name: newConsultation.patient_name, age: 30, gender: 'Other', phone: '', created_at: now.toISOString() }); } db.consultations.unshift(newConsultation); writeDB(db); return newConsultation; }, updateConsultation: (consultation_id, updateData) => { const db = readDB(); const idx = db.consultations.findIndex(c => c.consultation_id === consultation_id); if (idx === -1) return null; db.consultations[idx] = { ...db.consultations[idx], ...updateData, updated_at: new Date().toISOString() }; writeDB(db); return db.consultations[idx]; }, deleteConsultation: (consultation_id) => { const db = readDB(); const idx = db.consultations.findIndex(c => c.consultation_id === consultation_id); if (idx === -1) return false; db.consultations.splice(idx, 1); writeDB(db); return true; }, // ── Dashboard Stats ── getDashboardStats: () => { const db = readDB(); const totalPatients = db.patients.length; const todayStr = new Date().toISOString().slice(0, 10); const todayConsultations = db.consultations.filter(c => c.consultation_date === todayStr).length; const pendingSummaries = db.consultations.filter(c => c.status === 'Processing' || c.status === 'Pending Review').length; const totalRecordingSecs = db.consultations.reduce((acc, c) => acc + (c.duration_seconds || 0), 0); const totalRecordingMins = Math.round(totalRecordingSecs / 60); return { total_patients: totalPatients, today_consultations: todayConsultations, pending_summaries: pendingSummaries, total_recording_minutes: totalRecordingMins || 320, recent_consultations: db.consultations.slice(0, 5) }; } };