feat: add doctor dashboard and postgres prescription storage
Build Curio HMS / build-and-deploy (push) Successful in 1m12s Details

This commit is contained in:
Deep Koluguri 2026-06-02 23:16:56 -04:00
parent bb7038eb29
commit 1559e9f505
5 changed files with 396 additions and 38 deletions

View File

@ -84,11 +84,25 @@ CREATE TABLE IF NOT EXISTS agent_configs (
UNIQUE(tenant_id, agent_type)
);
CREATE TABLE IF NOT EXISTS prescriptions (
id TEXT PRIMARY KEY,
tenant_id TEXT REFERENCES tenants(id) ON DELETE CASCADE,
doctor_id INTEGER REFERENCES users(id),
patient_id TEXT NOT NULL,
patient_name TEXT NOT NULL,
diagnosis TEXT,
medicines JSONB DEFAULT '[]',
lab_tests JSONB DEFAULT '[]',
status TEXT DEFAULT 'pending' CHECK (status IN ('pending', 'ready', 'dispensed')),
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_users_tenant ON users(tenant_id);
CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
CREATE INDEX IF NOT EXISTS idx_pending_status ON pending_registrations(status);
CREATE INDEX IF NOT EXISTS idx_transactions_order ON transactions(order_id);
CREATE INDEX IF NOT EXISTS idx_agent_configs_tenant ON agent_configs(tenant_id);
CREATE INDEX IF NOT EXISTS idx_prescriptions_tenant_status ON prescriptions(tenant_id, status);
-- Migrations for existing DBs

View File

@ -1,35 +1,68 @@
/**
* PrescriptionManager: Handles digital prescription generation.
* PrescriptionManager: Handles digital prescription generation and storage in PostgreSQL.
*/
const db = require('./db');
class PrescriptionManager {
constructor() {
this.prescriptions = [];
}
generate(patientId, doctorId, medicines, diagnosis, labTests = []) {
/**
* Create a new prescription
*/
async generate(tenantId, doctorId, patientId, patientName, diagnosis, medicines = [], labTests = []) {
const id = `RX-${Date.now()}`;
const prescription = {
id,
patientId,
doctorId,
date: new Date().toISOString(),
diagnosis,
medicines, // Array of { name, dosage, frequency, duration, qty }
labTests // Array of { testName, instructions }
};
this.prescriptions.push(prescription);
const query = `
INSERT INTO prescriptions (id, tenant_id, doctor_id, patient_id, patient_name, diagnosis, medicines, lab_tests, status)
VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8::jsonb, 'pending')
RETURNING *;
`;
const values = [
id, tenantId, doctorId, patientId, patientName, diagnosis,
JSON.stringify(medicines), JSON.stringify(labTests)
];
const res = await db.query(query, values);
const prescription = res.rows[0];
// Ensure we format it properly for the whatsapp message
const whatsappMessage = `💊 *Digital Prescription from Curio*\n\n*Patient:* ${patientName}\n*Diagnosis:* ${diagnosis}\n\n*Medicines:*\n${medicines.map(m => `- ${m.name}: ${m.dosage} (${m.frequency}) for ${m.duration}`).join('\n')}\n\n` +
(labTests.length > 0 ? `🔬 *Lab Tests Recommended:*\n${labTests.map(t => `- ${t.testName}`).join('\n')}\n\n` : "") +
`_You can show this message at our pharmacy for a 10% discount._`;
return {
success: true,
prescriptionId: id,
data: prescription,
whatsappMessage: `💊 *Digital Prescription from Dr. Sharma*\n\n*Diagnosis:* ${diagnosis}\n\n*Medicines:*\n${medicines.map(m => `- ${m.name}: ${m.dosage} (${m.frequency}) for ${m.duration}`).join('\n')}\n\n` +
(labTests.length > 0 ? `🔬 *Lab Tests Recommended:*\n${labTests.map(t => `- ${t.testName}`).join('\n')}\n\n` : "") +
`_You can show this message at our pharmacy for a 10% discount._`
whatsappMessage
};
}
/**
* Get pending prescriptions for a tenant (used by Pharmacy)
*/
async getPending(tenantId) {
const query = `
SELECT p.*, u.name as doctor_name
FROM prescriptions p
LEFT JOIN users u ON p.doctor_id = u.id
WHERE p.tenant_id = $1 AND p.status = 'pending'
ORDER BY p.created_at ASC;
`;
const res = await db.query(query, [tenantId]);
return res.rows;
}
/**
* Update prescription status
*/
async updateStatus(tenantId, id, status) {
const query = `
UPDATE prescriptions
SET status = $1
WHERE id = $2 AND tenant_id = $3
RETURNING *;
`;
const res = await db.query(query, [status, id, tenantId]);
return res.rows.length > 0 ? res.rows[0] : null;
}
}
module.exports = new PrescriptionManager();

View File

@ -14,6 +14,7 @@ const { signToken, requireAuth } = require('./authMiddleware');
const Razorpay = require('razorpay');
const { upload, initStorage, uploadFile } = require('./storage');
const AgentManager = require('./agents/AgentManager');
const prescriptionManager = require('./prescriptionManager');
const razorpayInstance = new Razorpay({
key_id: process.env.RAZORPAY_KEY_ID || 'rzp_test_dummy_key_id',
@ -84,6 +85,7 @@ app.get('/admin', (req, res) => sendHtmlPage(res, 'admin.html'));
app.get('/dashboard', (req, res) => sendHtmlPage(res, 'dashboard.html'));
app.get('/register', (req, res) => sendHtmlPage(res, 'register.html'));
app.get('/super-admin', (req, res) => sendHtmlPage(res, 'super-admin.html'));
app.get('/doctor-dashboard', (req, res) => sendHtmlPage(res, 'doctor-dashboard.html'));
// ── Multi-tenant Config API (DB-first, fallback to in-memory) ─────────────────
@ -808,6 +810,54 @@ app.get('/api/ai/lab/alerts/:patientId', async (req, res) => {
}
});
// ── Prescriptions API ─────────────────────────────────────────────────────────
app.post('/api/prescriptions', requireAuth('DOCTOR'), async (req, res) => {
try {
const { patientId, patientName, diagnosis, medicines, labTests } = req.body;
const tenantId = req.user.tenantId;
const doctorId = req.user.id;
const result = await prescriptionManager.generate(tenantId, doctorId, patientId, patientName, diagnosis, medicines, labTests);
// Push notification via whatsappService (optional)
if (whatsappService && whatsappService.sendMessage && req.body.patientPhone) {
await whatsappService.sendMessage(req.body.patientPhone, result.whatsappMessage);
}
res.json(result);
} catch (error) {
console.error('[Prescription API] Error:', error);
res.status(500).json({ error: 'Failed to create prescription' });
}
});
app.get('/api/prescriptions/pending', requireAuth(), async (req, res) => {
try {
const tenantId = req.user.tenantId;
const pending = await prescriptionManager.getPending(tenantId);
res.json({ success: true, prescriptions: pending });
} catch (error) {
console.error('[Prescription API] Error:', error);
res.status(500).json({ error: 'Failed to fetch pending prescriptions' });
}
});
app.post('/api/prescriptions/:id/status', requireAuth(), async (req, res) => {
try {
const tenantId = req.user.tenantId;
const { status } = req.body;
const updated = await prescriptionManager.updateStatus(tenantId, req.params.id, status);
if (!updated) {
return res.status(404).json({ error: 'Prescription not found' });
}
res.json({ success: true, prescription: updated });
} catch (error) {
console.error('[Prescription API] Error:', error);
res.status(500).json({ error: 'Failed to update prescription status' });
}
});
// ── START ─────────────────────────────────────────────────────────────────────
initSchema().then(() => {

228
doctor-dashboard.html Normal file
View File

@ -0,0 +1,228 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Doctor Dashboard | Curio HMS</title>
<link rel="stylesheet" href="globals.css">
<link rel="stylesheet" href="index.css">
<link rel="stylesheet" href="dashboard.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Outfit:wght@500;600;700&display=swap" rel="stylesheet">
<script src="globals.js"></script>
<style>
.prescription-builder {
display: flex;
flex-direction: column;
gap: 1.5rem;
}
.form-group {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.form-group label {
font-weight: 600;
color: var(--text-dark);
}
.form-control {
padding: 0.75rem;
border: 1px solid var(--border-color);
border-radius: 6px;
font-family: inherit;
}
.medicines-list {
display: flex;
flex-direction: column;
gap: 1rem;
}
.medicine-row {
display: grid;
grid-template-columns: 2fr 1fr 1fr 1fr auto;
gap: 1rem;
align-items: center;
background: #f8fafc;
padding: 1rem;
border-radius: 6px;
border: 1px solid var(--border-color);
}
.print-only {
display: none;
}
/* Print Styles */
@media print {
body * {
visibility: hidden;
}
.sidebar, .dash-header, .header-actions, .actions-row {
display: none !important;
}
#prescription-print-area, #prescription-print-area * {
visibility: visible;
}
#prescription-print-area {
position: absolute;
left: 0;
top: 0;
width: 100%;
padding: 2rem;
}
.print-only {
display: block;
text-align: center;
margin-bottom: 2rem;
border-bottom: 2px solid #000;
padding-bottom: 1rem;
}
.medicine-row {
border: none;
background: none;
border-bottom: 1px dashed #ccc;
grid-template-columns: 2fr 1fr 1fr 1fr;
}
.medicine-row button {
display: none;
}
.form-control {
border: none;
padding: 0;
appearance: none;
background: transparent;
}
}
</style>
</head>
<body class="dashboard-body">
<aside class="sidebar">
<div class="logo">
<div class="logo-icon">C</div>
<span class="logo-text">Curio</span>
</div>
<nav class="side-nav">
<a href="doctor-dashboard.html" class="active"><span>🩺</span> Consultations</a>
<a href="dashboard.html"><span>📂</span> Patients</a>
<a href="login.html" class="logout-btn" style="margin-top:auto;"><span>🚪</span> Logout</a>
</nav>
</aside>
<main class="dashboard-main">
<header class="dash-header">
<div class="header-title">
<h1>Doctor Dashboard</h1>
<p>Record details, prescribe medicines, and send to pharmacy.</p>
</div>
<div class="header-actions">
<button class="btn btn-secondary" onclick="window.print()">🖨️ Print Prescription</button>
<button class="btn btn-primary" onclick="submitPrescription()">✅ Prescribe & Send</button>
</div>
</header>
<section class="section-card" id="prescription-print-area">
<div class="print-only">
<h2>Curio Clinic</h2>
<p>Dr. Sharma | MBBS, MD</p>
<p>Date: <span id="print-date"></span></p>
</div>
<div class="prescription-builder">
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
<div class="form-group">
<label>Patient ID / Phone</label>
<input type="text" id="patient-id" class="form-control" placeholder="e.g., 9876543210">
</div>
<div class="form-group">
<label>Patient Name</label>
<input type="text" id="patient-name" class="form-control" placeholder="Patient Full Name">
</div>
</div>
<div class="form-group">
<label>Symptoms & Diagnosis</label>
<textarea id="diagnosis" class="form-control" rows="3" placeholder="Enter diagnosis..."></textarea>
</div>
<div class="form-group">
<label>Medicines</label>
<div id="medicines-container" class="medicines-list">
<!-- Medicine rows injected here -->
</div>
<button class="btn btn-secondary actions-row" style="width:fit-content; margin-top: 1rem;" onclick="addMedicineRow()">+ Add Medicine</button>
</div>
</div>
</section>
</main>
<script>
document.getElementById('print-date').innerText = new Date().toLocaleDateString();
function addMedicineRow() {
const container = document.getElementById('medicines-container');
const row = document.createElement('div');
row.className = 'medicine-row';
row.innerHTML = `
<input type="text" class="form-control med-name" placeholder="Medicine Name">
<input type="text" class="form-control med-dosage" placeholder="Dosage (e.g. 500mg)">
<input type="text" class="form-control med-freq" placeholder="Frequency (e.g. 1-0-1)">
<input type="text" class="form-control med-dur" placeholder="Duration (e.g. 5 days)">
<button class="btn btn-sm btn-secondary actions-row" onclick="this.parentElement.remove()"></button>
`;
container.appendChild(row);
}
// Add initial row
addMedicineRow();
async function submitPrescription() {
const patientId = document.getElementById('patient-id').value;
const patientName = document.getElementById('patient-name').value;
const diagnosis = document.getElementById('diagnosis').value;
const medicines = [];
document.querySelectorAll('.medicine-row').forEach(row => {
const name = row.querySelector('.med-name').value;
if (name) {
medicines.push({
name: name,
dosage: row.querySelector('.med-dosage').value,
frequency: row.querySelector('.med-freq').value,
duration: row.querySelector('.med-dur').value
});
}
});
if (!patientName || medicines.length === 0) {
alert("Please fill in patient name and at least one medicine.");
return;
}
try {
const res = await apiCall('/api/prescriptions', 'POST', {
patientId,
patientName,
diagnosis,
medicines,
labTests: []
});
if (res.success) {
alert('Prescription created and sent to pharmacy! ID: ' + res.prescriptionId);
window.print();
// Clear form
document.getElementById('patient-id').value = '';
document.getElementById('patient-name').value = '';
document.getElementById('diagnosis').value = '';
document.getElementById('medicines-container').innerHTML = '';
addMedicineRow();
} else {
alert('Failed to create prescription.');
}
} catch (err) {
console.error(err);
alert('An error occurred.');
}
}
</script>
</body>
</html>

View File

@ -84,23 +84,8 @@
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr class="active-row">
<td>#RX-901</td>
<td><strong>Suresh Kumar</strong></td>
<td>Amoxicillin, Paracetamol</td>
<td>Dr. Sharma</td>
<td><span class="badge badge-warning">Waiting for Dispense</span></td>
<td><button class="btn btn-sm btn-primary" onclick="handleComingSoon('Dispense')">Dispense</button></td>
</tr>
<tr>
<td>#RX-902</td>
<td><strong>Anjali Singh</strong></td>
<td>Thyroxine 50mcg</td>
<td>Dr. Sharma</td>
<td><span class="badge badge-success">Ready</span></td>
<td><button class="btn btn-sm btn-secondary" onclick="handleComingSoon('Ready')">Ready</button></td>
</tr>
<tbody id="pending-queue">
<tr><td colspan="6" style="text-align: center;">Loading prescriptions...</td></tr>
</tbody>
</table>
</div>
@ -127,5 +112,53 @@
</div>
</section>
</main>
<script>
async function fetchPending() {
try {
const res = await apiCall('/api/prescriptions/pending');
if (res && res.success) {
const tbody = document.getElementById('pending-queue');
if (res.prescriptions.length === 0) {
tbody.innerHTML = '<tr><td colspan="6" style="text-align: center;">No pending prescriptions</td></tr>';
return;
}
tbody.innerHTML = '';
res.prescriptions.forEach(p => {
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${p.id}</td>
<td><strong>${p.patient_name}</strong></td>
<td>${(p.medicines || []).map(m => m.name).join(', ')}</td>
<td>${p.doctor_name || 'Dr. Sharma'}</td>
<td><span class="badge badge-warning">${p.status}</span></td>
<td>
<button class="btn btn-sm btn-primary" onclick="updateStatus('${p.id}', 'dispensed')">Dispense</button>
</td>
`;
tbody.appendChild(tr);
});
}
} catch (err) {
console.error("Failed to fetch pending prescriptions", err);
}
}
async function updateStatus(id, status) {
try {
const res = await apiCall(\`/api/prescriptions/\${id}/status\`, 'POST', { status });
if (res.success) {
fetchPending();
}
} catch (err) {
console.error("Failed to update status", err);
}
}
// Poll every 5 seconds
setInterval(fetchPending, 5000);
fetchPending();
</script>
</body>
</html>