File size: 13,507 Bytes
34daf91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/**
 * Issue #39: Virtual Waiting Room Service
 * Enables patients to check-in remotely and join the virtual queue
 */

const db = require('../config/db');
const durationPrediction = require('./durationPrediction');

class VirtualCheckinService {
    constructor() {
        // Ensure methods are bound to this instance
        this.virtualCheckIn = this.virtualCheckIn.bind(this);
        this.updateStatus = this.updateStatus.bind(this);
        this.getWaitingRoomStatus = this.getWaitingRoomStatus.bind(this);
        this.getVirtualQueueForDoctor = this.getVirtualQueueForDoctor.bind(this);
        this.pingSession = this.pingSession.bind(this);
        this.cancelCheckin = this.cancelCheckin.bind(this);
        this.getPendingNotifications = this.getPendingNotifications.bind(this);
        this.acknowledgeNotification = this.acknowledgeNotification.bind(this);
    }

    /**
     * Virtual check-in for an appointment (patient joins queue from home)
     */
    async virtualCheckIn(appointmentId, patientId, options = {}) {
        const { etaMinutes, latitude, longitude, device, vitals } = options;
        
        // Verify appointment belongs to patient and is for today
        const [appointments] = await db.query(
            `SELECT a.*, u.first_name, u.last_name, d.first_name as doc_first, d.last_name as doc_last
             FROM appointments a
             JOIN users u ON a.patient_id = u.id
             JOIN users d ON a.doctor_id = d.id
             WHERE a.id = ? AND a.patient_id = ?`,
            [appointmentId, patientId]
        );

        if (!appointments.length) {
            throw new Error('Appointment not found or unauthorized');
        }

        const appointment = appointments[0];
        const today = new Date().toISOString().split('T')[0];
        const aptDate = new Date(appointment.appointment_date).toISOString().split('T')[0];

        if (aptDate !== today) {
            throw new Error('Virtual check-in is only available on the appointment day');
        }

        if (['COMPLETED', 'CANCELLED', 'NO_SHOW'].includes(appointment.status)) {
            throw new Error(`Cannot check-in for ${appointment.status.toLowerCase()} appointment`);
        }

        // Update appointment with virtual check-in
        await db.query(
            `UPDATE appointments SET 
                virtual_checkin_time = NOW(),
                virtual_checkin_status = 'CHECKED_IN',
                patient_eta_minutes = ?,
                patient_location_lat = ?,
                patient_location_lng = ?,
                checkin_device = ?
             WHERE id = ?`,
            [etaMinutes || null, latitude || null, longitude || null, device || 'web', appointmentId]
        );

        if (vitals && Object.keys(vitals).length > 0) {
            const vitalsService = require('./vitalsService');
            try {
                await vitalsService.logVitals(patientId, {
                    weight_kg: vitals.weight_kg || null,
                    height_cm: vitals.height_cm || null,
                    blood_pressure_sys: vitals.blood_pressure_sys || null,
                    blood_pressure_dia: vitals.blood_pressure_dia || null,
                    heart_rate: vitals.heart_rate || null,
                    temperature_c: vitals.temperature_c || null,
                    spo2: vitals.spo2 || null
                }, patientId);
            } catch (vErr) {
                logger.error('Failed to log vitals during virtual checkin:', vErr);
            }
        }

        // Create virtual waiting session
        const [sessionResult] = await db.query(
            `INSERT INTO virtual_waiting_sessions 
                (appointment_id, patient_id, estimated_call_time) 
             VALUES (?, ?, DATE_ADD(NOW(), INTERVAL ? MINUTE))`,
            [appointmentId, patientId, etaMinutes || 30]
        );

        // Create notification for clinic staff
        await db.query(
            `INSERT INTO checkin_notifications 
                (appointment_id, notification_type, message)
             VALUES (?, 'VIRTUAL_CHECKIN', ?)`,
            [appointmentId, `${appointment.first_name} ${appointment.last_name} has checked in virtually. ETA: ${etaMinutes || 'Not specified'} minutes`]
        );

        return {
            success: true,
            message: 'Virtual check-in successful! You are now in the virtual waiting room.',
            sessionId: sessionResult.insertId,
            checkinTime: new Date().toISOString(),
            estimatedCallTime: etaMinutes ? new Date(Date.now() + etaMinutes * 60000).toISOString() : null
        };
    }

    /**
     * Update patient status (en route, arrived, running late)
     */
    async updateStatus(appointmentId, patientId, status, options = {}) {
        const { etaMinutes, message } = options;
        const validStatuses = ['EN_ROUTE', 'ARRIVED', 'RUNNING_LATE'];
        
        if (!validStatuses.includes(status)) {
            throw new Error('Invalid status');
        }

        // Verify appointment
        const [appointments] = await db.query(
            `SELECT * FROM appointments WHERE id = ? AND patient_id = ?`,
            [appointmentId, patientId]
        );

        if (!appointments.length) {
            throw new Error('Appointment not found or unauthorized');
        }

        // Map RUNNING_LATE to EN_ROUTE for DB but create special notification
        const dbStatus = status === 'RUNNING_LATE' ? 'EN_ROUTE' : status;

        // Update appointment status
        await db.query(
            `UPDATE appointments SET 
                virtual_checkin_status = ?,
                patient_eta_minutes = COALESCE(?, patient_eta_minutes)
             WHERE id = ?`,
            [dbStatus, etaMinutes, appointmentId]
        );

        // Create notification
        const notificationMessages = {
            EN_ROUTE: 'Patient is on their way to the clinic',
            ARRIVED: 'Patient has arrived at the clinic',
            RUNNING_LATE: `Patient is running late. ${message || `ETA: ${etaMinutes || 'Unknown'} minutes`}`
        };

        await db.query(
            `INSERT INTO checkin_notifications 
                (appointment_id, notification_type, message)
             VALUES (?, ?, ?)`,
            [appointmentId, status, notificationMessages[status]]
        );

        // If arrived, update session
        if (status === 'ARRIVED') {
            await db.query(
                `UPDATE virtual_waiting_sessions 
                 SET status = 'COMPLETED', session_end = NOW()
                 WHERE appointment_id = ? AND status = 'ACTIVE'`,
                [appointmentId]
            );
        }

        return {
            success: true,
            status: dbStatus,
            message: `Status updated to ${status.toLowerCase().replace('_', ' ')}`
        };
    }

    /**
     * Get virtual waiting room status for a patient
     */
    async getWaitingRoomStatus(appointmentId, patientId) {
        const [appointments] = await db.query(
            `SELECT a.*, 
                    u.first_name, u.last_name,
                    d.first_name as doc_first, d.last_name as doc_last,
                    d.specialty
             FROM appointments a
             JOIN users u ON a.patient_id = u.id
             JOIN doctors d ON a.doctor_id = d.id
             WHERE a.id = ? AND a.patient_id = ?`,
            [appointmentId, patientId]
        );

        if (!appointments.length) {
            return null;
        }

        const appointment = appointments[0];

        // Get queue position based on active waiting patients
        const [queuePosition] = await db.query(
            `SELECT COUNT(*) + 1 as position
             FROM appointments a
             JOIN live_queue lq ON a.id = lq.appointment_id
             WHERE a.doctor_id = ? 
               AND a.appointment_date = ?
               AND lq.status = 'WAITING'
               AND (a.time_slot < ? OR (a.time_slot = ? AND a.id < ?))`,
            [appointment.doctor_id, appointment.appointment_date, 
             appointment.time_slot, appointment.time_slot, appointmentId]
        );

        // Get virtual session info
        const [sessions] = await db.query(
            `SELECT * FROM virtual_waiting_sessions 
             WHERE appointment_id = ? 
             ORDER BY created_at DESC LIMIT 1`,
            [appointmentId]
        );

        // Calculate estimated wait using the centralized duration prediction service
        const waitInfo = await durationPrediction.calculateQueueWaitTime(appointmentId);
        const estimatedWaitMins = waitInfo.estimatedWait || 0;

        return {
            appointment: {
                id: appointment.id,
                date: appointment.appointment_date,
                time: appointment.time_slot,
                doctor: `Dr. ${appointment.doc_first} ${appointment.doc_last}`,
                specialty: appointment.specialty,
                status: appointment.status,
                virtualCheckinStatus: appointment.virtual_checkin_status,
                checkinTime: appointment.virtual_checkin_time
            },
            queue: {
                position: queuePosition[0]?.position || 1,
                estimatedWaitMins,
                estimatedCallTime: new Date(Date.now() + estimatedWaitMins * 60000).toISOString()
            },
            session: sessions[0] || null,
            isCheckedIn: appointment.virtual_checkin_status !== 'NOT_CHECKED_IN'
        };
    }

    /**
     * Get all virtually checked-in patients for a doctor (for clinic view)
     */
    async getVirtualQueueForDoctor(doctorId) {
        const today = new Date().toISOString().split('T')[0];

        const [patients] = await db.query(
            `SELECT a.id, a.time_slot, a.status, a.virtual_checkin_status,
                    a.virtual_checkin_time, a.patient_eta_minutes,
                    p.first_name, p.last_name, p.phone,
                    s.session_start, s.last_ping
             FROM appointments a
             JOIN patients p ON a.patient_id = p.id
             LEFT JOIN virtual_waiting_sessions s ON a.id = s.appointment_id AND s.status = 'ACTIVE'
             WHERE a.doctor_id = ?
               AND DATE(a.appointment_date) = ?
               AND a.virtual_checkin_status != 'NOT_CHECKED_IN'
             ORDER BY a.time_slot, a.virtual_checkin_time`,
            [doctorId, today]
        );

        return patients.map((p, index) => ({
            ...p,
            queuePosition: index + 1,
            patientName: `${p.first_name} ${p.last_name}`,
            waitingTime: p.virtual_checkin_time 
                ? Math.round((Date.now() - new Date(p.virtual_checkin_time).getTime()) / 60000)
                : 0
        }));
    }

    /**
     * Keep session alive (heartbeat from patient app)
     */
    async pingSession(appointmentId, patientId) {
        await db.query(
            `UPDATE virtual_waiting_sessions 
             SET last_ping = NOW()
             WHERE appointment_id = ? AND status = 'ACTIVE'`,
            [appointmentId]
        );

        return { success: true, timestamp: new Date().toISOString() };
    }

    /**
     * Cancel virtual check-in
     */
    async cancelCheckin(appointmentId, patientId) {
        await db.query(
            `UPDATE appointments SET 
                virtual_checkin_status = 'NOT_CHECKED_IN',
                virtual_checkin_time = NULL,
                patient_eta_minutes = NULL
             WHERE id = ? AND patient_id = ?`,
            [appointmentId, patientId]
        );

        await db.query(
            `UPDATE virtual_waiting_sessions 
             SET status = 'CANCELLED', session_end = NOW()
             WHERE appointment_id = ? AND status = 'ACTIVE'`,
            [appointmentId]
        );

        await db.query(
            `INSERT INTO checkin_notifications 
                (appointment_id, notification_type, message)
             VALUES (?, 'CANCELLED', 'Patient has cancelled their virtual check-in')`,
            [appointmentId]
        );

        return { success: true, message: 'Virtual check-in cancelled' };
    }

    /**
     * Get pending check-in notifications for staff
     */
    async getPendingNotifications(doctorId = null) {
        let query = `
            SELECT cn.*, a.time_slot, a.doctor_id,
                   u.first_name, u.last_name,
                   d.first_name as doc_first, d.last_name as doc_last
            FROM checkin_notifications cn
            JOIN appointments a ON cn.appointment_id = a.id
            JOIN users u ON a.patient_id = u.id
            JOIN users d ON a.doctor_id = d.id
            WHERE cn.acknowledged = FALSE
              AND DATE(a.appointment_date) = CURDATE()`;

        const params = [];
        if (doctorId) {
            query += ` AND a.doctor_id = ?`;
            params.push(doctorId);
        }

        query += ` ORDER BY cn.created_at DESC`;

        const [notifications] = await db.query(query, params);
        return notifications;
    }

    /**
     * Acknowledge a notification
     */
    async acknowledgeNotification(notificationId, userId) {
        await db.query(
            `UPDATE checkin_notifications 
             SET acknowledged = TRUE, acknowledged_by = ?, acknowledged_at = NOW()
             WHERE id = ?`,
            [userId, notificationId]
        );

        return { success: true };
    }
}

module.exports = new VirtualCheckinService();