File size: 4,008 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
const pool = require('../config/db');

/**
 * Handles user notification preferences
 */
class PreferenceService {
    constructor() {
        // Ensure methods are bound to this instance
        this.getUserPreferences = this.getUserPreferences.bind(this);
        this.isInQuietHours = this.isInQuietHours.bind(this);
        this.getPreferenceField = this.getPreferenceField.bind(this);
        this.updatePreferences = this.updatePreferences.bind(this);
        this.savePushSubscription = this.savePushSubscription.bind(this);
    }

    /**
     * Get user notification preferences
     */
    async getUserPreferences(userId) {
        const [prefsRows] = await pool.query(
            'SELECT * FROM notification_preferences WHERE user_id = ?',
            [userId]
        );
        const prefs = prefsRows[0];
        
        if (!prefs) {
            return {
                push_enabled: true,
                sms_enabled: false,
                email_enabled: true,
                whatsapp_enabled: true,
                queue_updates: true,
                appointment_reminders: true,
                delay_alerts: true,
                waitlist_offers: true,
                cancellation_confirm: true,
                quiet_hours_enabled: false
            };
        }
        
        return prefs;
    }

    /**
     * Check if user is in quiet hours
     */
    isInQuietHours(prefs) {
        if (!prefs.quiet_hours_enabled) return false;
        
        const now = new Date();
        const currentTime = now.toTimeString().slice(0, 8);
        const quietStart = prefs.quiet_start;
        const quietEnd = prefs.quiet_end;
        
        if (quietStart > quietEnd) {
            return currentTime >= quietStart || currentTime <= quietEnd;
        }
        return currentTime >= quietStart && currentTime <= quietEnd;
    }

    /**
     * Map notification type to preference field
     */
    getPreferenceField(type) {
        const mapping = {
            'QUEUE_UPDATE': 'queue_updates',
            'TURN_APPROACHING': 'queue_updates',
            'YOUR_TURN': 'queue_updates',
            'APPOINTMENT_REMINDER': 'appointment_reminders',
            'DELAY_ALERT': 'delay_alerts',
            'WAITLIST_OFFER': 'waitlist_offers',
            'CANCELLATION': 'cancellation_confirm',
            'MISSED': 'queue_updates',
            'EMERGENCY_ALERT': 'queue_updates'
        };
        return mapping[type] || null;
    }

    /**
     * Update notification preferences
     */
    async updatePreferences(userId, preferences) {
        const allowedFields = [
            'push_enabled', 'sms_enabled', 'email_enabled', 'whatsapp_enabled',
            'queue_updates', 'appointment_reminders', 'delay_alerts',
            'waitlist_offers', 'cancellation_confirm',
            'reminder_24h', 'reminder_1h', 'reminder_30m',
            'quiet_hours_enabled', 'quiet_start', 'quiet_end'
        ];
        
        const updates = [];
        const values = [];
        
        for (const [key, value] of Object.entries(preferences)) {
            if (allowedFields.includes(key)) {
                updates.push(`${key} = ?`);
                values.push(value);
            }
        }
        
        if (updates.length === 0) return { success: false };
        
        values.push(userId);
        
        await pool.query(
            `UPDATE notification_preferences SET ${updates.join(', ')} WHERE user_id = ?`,
            values
        );
        
        return { success: true };
    }

    /**
     * Save push subscription
     */
    async savePushSubscription(userId, subscription) {
        await pool.query(
            `INSERT INTO notification_preferences (user_id, push_subscription)
             VALUES (?, ?)
             ON DUPLICATE KEY UPDATE push_subscription = VALUES(push_subscription)`,
            [userId, JSON.stringify(subscription)]
        );
        return { success: true };
    }
}

module.exports = new PreferenceService();