fit notify route

This commit is contained in:
chris 2025-10-09 12:31:52 -04:00
parent 74ad2750b0
commit 37f02ae29b

View File

@ -341,30 +341,11 @@ app.post('/subscribe', authenticateToken, async (req, res) => {
}
});
app.get('/api/user/notes', authenticateToken, async (req, res) => {
try {
const notes = await db.all("SELECT admin_username, note_text, created_at FROM notes WHERE employee_user_id = ? ORDER BY created_at DESC", [req.user.id]);
try {
const userSubs = await db.all('SELECT subscription_object FROM subscriptions WHERE user_id = ?', [userId]);
const payload = JSON.stringify({
title: 'You Have a New Note',
body: `A new note has been added by ${adminUsername}.`
});
const promises = userSubs.map(s => {
const subscription = JSON.parse(s.subscription_object);
return webpush.sendNotification(subscription, payload).catch(err => {
if (err.statusCode === 410) db.run('DELETE FROM subscriptions WHERE subscription_object = ?', [s.subscription_object]);
else console.error('Error sending employee notification:', err);
});
});
await Promise.all(promises);
} catch (notifyError) {
console.error('Failed to send employee notification:', notifyError);
}
// The notification block has been removed from here.
res.json(notes);
} catch (err) {
res.status(500).json({ message: 'Failed to fetch notes.' });
@ -622,7 +603,30 @@ app.post('/api/admin/notify', authenticateToken, requireRole('admin'), async (re
const { userId, noteText } = req.body;
const adminUsername = req.user.username;
if (!userId || !noteText) return res.status(400).json({ message: "Employee and note text are required." });
await db.run('INSERT INTO notes (admin_username, employee_user_id, note_text) VALUES (?, ?, ?)', [adminUsername, userId, noteText]);
// --- START: NOTIFICATION CODE (Correct Placement) ---
try {
const userSubs = await db.all('SELECT subscription_object FROM subscriptions WHERE user_id = ?', [userId]);
const payload = JSON.stringify({
title: 'You Have a New Note',
body: `A new note has been added by ${adminUsername}.`
});
const promises = userSubs.map(s => {
const subscription = JSON.parse(s.subscription_object);
return webpush.sendNotification(subscription, payload).catch(err => {
if (err.statusCode === 410) db.run('DELETE FROM subscriptions WHERE subscription_object = ?', [s.subscription_object]);
else console.error('Error sending employee notification:', err);
});
});
await Promise.all(promises);
} catch (notifyError) {
console.error('Failed to send employee notification:', notifyError);
}
// --- END: NOTIFICATION CODE ---
res.status(201).json({ message: "Note successfully posted." });
} catch (err) {
res.status(500).json({ message: 'Failed to post note.' });