-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotifications.py
More file actions
204 lines (165 loc) · 5.95 KB
/
Copy pathnotifications.py
File metadata and controls
204 lines (165 loc) · 5.95 KB
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
"""
Notifications blueprint for ISUFST CareHub.
Handles notification creation, retrieval, and management.
"""
from flask import Blueprint, jsonify, request
from flask_login import login_required, current_user
from datetime import datetime, timezone
from models import db, Notification
from models_extended import PushSubscription
notifications = Blueprint('notifications', __name__, url_prefix='/notifications')
# ═══════════ HELPER FUNCTIONS ═══════════
def create_notification(user_id, notif_type, title, message, link=None):
"""Create a new notification for a user.
Args:
user_id: Target user ID
notif_type: 'appointment_update', 'reservation_update', 'reminder'
title: Short notification title
message: Notification message
link: Optional URL to navigate to
"""
notification = Notification(
user_id=user_id,
type=notif_type,
title=title,
message=message,
link=link,
is_read=False
)
db.session.add(notification)
db.session.commit()
return notification
# ═══════════ API ROUTES ═══════════
@notifications.route('/unread-count')
@login_required
def unread_count():
"""API: Get count of unread notifications for current user."""
count = Notification.query.filter_by(
user_id=current_user.id,
is_read=False
).count()
return jsonify({'count': count})
@notifications.route('/list')
@login_required
def notification_list():
"""API: Get recent notifications for current user."""
page = request.args.get('page', 1, type=int)
per_page = request.args.get('per_page', 20, type=int)
notifs = Notification.query.filter_by(
user_id=current_user.id
).order_by(
Notification.created_at.desc()
).limit(per_page).offset((page - 1) * per_page).all()
return jsonify({
'notifications': [{
'id': n.id,
'type': n.type,
'title': n.title,
'message': n.message,
'link': n.link,
'is_read': n.is_read,
'created_at': n.created_at.isoformat() if n.created_at else None,
'time_ago': _time_ago(n.created_at)
} for n in notifs]
})
@notifications.route('/mark-read', methods=['POST'])
@login_required
def mark_read():
"""API: Mark notification(s) as read."""
data = request.get_json() or {}
notif_id = data.get('id')
mark_all = data.get('all', False)
if mark_all:
Notification.query.filter_by(
user_id=current_user.id,
is_read=False
).update({'is_read': True})
db.session.commit()
return jsonify({'success': True, 'message': 'All notifications marked as read'})
if notif_id:
notif = Notification.query.filter_by(
id=notif_id,
user_id=current_user.id
).first()
if notif:
notif.is_read = True
db.session.commit()
return jsonify({'success': True})
return jsonify({'error': 'Invalid request'}), 400
# ═══════════ PUSH NOTIFICATION ROUTES ═══════════
@notifications.route('/push-subscribe', methods=['POST'])
@login_required
def push_subscribe():
"""Subscribe to push notifications."""
data = request.get_json() or {}
endpoint = data.get('endpoint')
p256dh = data.get('keys', {}).get('p256dh')
auth = data.get('keys', {}).get('auth')
if not endpoint or not p256dh or not auth:
return jsonify({'error': 'Missing subscription data'}), 400
# Check if subscription already exists
existing = PushSubscription.query.filter_by(endpoint=endpoint).first()
if existing:
# Update existing subscription
existing.last_used = datetime.now(timezone.utc)
existing.user_agent = request.headers.get('User-Agent', '')
db.session.commit()
else:
# Create new subscription
subscription = PushSubscription(
user_id=current_user.id,
endpoint=endpoint,
p256dh=p256dh,
auth=auth,
user_agent=request.headers.get('User-Agent', '')
)
db.session.add(subscription)
db.session.commit()
return jsonify({'success': True, 'message': 'Subscribed to push notifications'})
@notifications.route('/push-unsubscribe', methods=['POST'])
@login_required
def push_unsubscribe():
"""Unsubscribe from push notifications."""
data = request.get_json() or {}
endpoint = data.get('endpoint')
if not endpoint:
return jsonify({'error': 'Endpoint required'}), 400
subscription = PushSubscription.query.filter_by(
endpoint=endpoint,
user_id=current_user.id
).first()
if subscription:
db.session.delete(subscription)
db.session.commit()
return jsonify({'success': True, 'message': 'Unsubscribed from push notifications'})
return jsonify({'error': 'Subscription not found'}), 404
@notifications.route('/push-status')
@login_required
def push_status():
"""Check if user has push subscription."""
subscription = PushSubscription.query.filter_by(
user_id=current_user.id
).first()
return jsonify({'subscribed': subscription is not None})
def _time_ago(dt):
"""Convert datetime to human-readable 'time ago' string."""
if not dt:
return ''
now = datetime.now(timezone.utc)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
diff = now - dt
seconds = int(diff.total_seconds())
if seconds < 60:
return 'Just now'
elif seconds < 3600:
mins = seconds // 60
return f'{mins}m ago'
elif seconds < 86400:
hours = seconds // 3600
return f'{hours}h ago'
elif seconds < 604800:
days = seconds // 86400
return f'{days}d ago'
else:
return dt.strftime('%b %d')