mirror of
https://github.com/naturalcrit/homebrewery.git
synced 2026-01-05 18:52:38 +00:00
"Refactored notification lookup and management functionality in admin API and model, added new endpoints for getting all notifications and deleting a notification by dismiss key."
This commit is contained in:
@@ -1,95 +1,183 @@
|
|||||||
require('./notificationLookup.less');
|
require('./notificationLookup.less');
|
||||||
|
|
||||||
const React = require('react');
|
const React = require('react');
|
||||||
const { useState } = require('react');
|
const { useState, useRef } = require('react');
|
||||||
const cx = require('classnames');
|
const cx = require('classnames');
|
||||||
|
|
||||||
const request = require('superagent');
|
const request = require('superagent');
|
||||||
const Moment = require('moment');
|
const Moment = require('moment');
|
||||||
|
|
||||||
|
const NotificationDetail = ({ notification, onDelete }) => (
|
||||||
|
<div>
|
||||||
|
<dl>
|
||||||
|
<dt>Key</dt>
|
||||||
|
<dd>{notification.dismissKey}</dd>
|
||||||
|
|
||||||
|
<dt>Title</dt>
|
||||||
|
<dd>{notification.title || 'No Title'}</dd>
|
||||||
|
|
||||||
|
<dt>Text</dt>
|
||||||
|
<dd>{notification.text || 'No Text'}</dd>
|
||||||
|
|
||||||
|
<dt>Created</dt>
|
||||||
|
<dd>{Moment(notification.createdAt).format('LLLL')}</dd>
|
||||||
|
|
||||||
|
<dt>Start</dt>
|
||||||
|
<dd>{Moment(notification.startAt).format('LLLL') || 'No Start Time'}</dd>
|
||||||
|
|
||||||
|
<dt>Stop</dt>
|
||||||
|
<dd>{Moment(notification.stopAt).format('LLLL') || 'No End Time'}</dd>
|
||||||
|
</dl>
|
||||||
|
<button onClick={() => onDelete(notification.dismissKey)}>DELETE</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
const NotificationLookup = () => {
|
const NotificationLookup = () => {
|
||||||
const [query, setQuery] = useState('');
|
|
||||||
const [foundNotification, setFoundNotification] = useState(null);
|
const [foundNotification, setFoundNotification] = useState(null);
|
||||||
const [searching, setSearching] = useState(false);
|
const [searching, setSearching] = useState(false);
|
||||||
const [error, setError] = useState(null);
|
const [error, setError] = useState(null);
|
||||||
|
const [notifications, setNotifications] = useState([]);
|
||||||
|
|
||||||
|
const lookupRef = useRef(null);
|
||||||
|
|
||||||
const handleChange = (e) => {
|
const lookup = async () => {
|
||||||
setQuery(e.target.value);
|
const query = lookupRef.current.value;
|
||||||
};
|
|
||||||
|
if (!query.trim()) {
|
||||||
|
setError('Please enter a valid dismiss key.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const lookup = () => {
|
|
||||||
setSearching(true);
|
setSearching(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
request.get(`/admin/notification/lookup/${query}`)
|
try {
|
||||||
.then((res) => setFoundNotification(res.body))
|
const res = await request.get(`/admin/notification/lookup/${query}`);
|
||||||
.catch((err) => setError(err))
|
if (res.body) {
|
||||||
.finally(() => setSearching(false));
|
setFoundNotification(res.body);
|
||||||
|
} else {
|
||||||
|
setFoundNotification(null);
|
||||||
|
setError('No notification found.');
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
setError('Error fetching notification.');
|
||||||
|
} finally {
|
||||||
|
setSearching(false);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteNotification = () => {
|
const lookupAll = async () => {
|
||||||
if (!foundNotification) return;
|
setSearching(true);
|
||||||
|
setError(null);
|
||||||
|
|
||||||
const confirmed = window.confirm(`Really delete notification ${foundNotification.dismissKey} : ${foundNotification.title}?`);
|
try {
|
||||||
|
const res = await request.get('/admin/notification/all');
|
||||||
|
setNotifications(res.body || []);
|
||||||
|
} catch {
|
||||||
|
setError('Error fetching all notifications.');
|
||||||
|
} finally {
|
||||||
|
setSearching(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteNotification = async (dismissKey) => {
|
||||||
|
if (!dismissKey) return;
|
||||||
|
|
||||||
|
const confirmed = window.confirm(
|
||||||
|
`Really delete notification ${dismissKey}?`
|
||||||
|
);
|
||||||
if (!confirmed) {
|
if (!confirmed) {
|
||||||
console.log('CANCELLED');
|
console.log('CANCELLED');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
console.log('CONFIRMED');
|
console.log('CONFIRMED');
|
||||||
// Perform delete operation here
|
try {
|
||||||
|
await request.delete(`/admin/notification/delete/${dismissKey}`);
|
||||||
|
// Only reset the foundNotification if it matches the one being deleted
|
||||||
|
if (foundNotification && foundNotification.dismissKey === dismissKey) {
|
||||||
|
setFoundNotification(null);
|
||||||
|
}
|
||||||
|
// Optionally refresh the list of all notifications
|
||||||
|
lookupAll();
|
||||||
|
} catch {
|
||||||
|
setError('Error deleting notification.');
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const renderFoundNotification = () => {
|
const renderFoundNotification = () => {
|
||||||
if (!foundNotification) return null;
|
if (error) {
|
||||||
|
return <div className="error">{error}</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!foundNotification) {
|
||||||
|
return <div className="noNotification">No notification found.</div>;
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='foundNotification'>
|
<div className="foundNotification">
|
||||||
<dl>
|
<NotificationDetail notification={foundNotification} onDelete={deleteNotification} />
|
||||||
<dt>Key</dt>
|
</div>
|
||||||
<dd>{foundNotification.dismissKey}</dd>
|
);
|
||||||
|
};
|
||||||
|
|
||||||
<dt>Title</dt>
|
const renderNotificationsList = () => {
|
||||||
<dd>{foundNotification.title || 'No Title'}</dd>
|
if (error) {
|
||||||
|
return <div className="error">{error}</div>;
|
||||||
|
}
|
||||||
|
|
||||||
<dt>Text</dt>
|
if (notifications.length === 0) {
|
||||||
<dd>{foundNotification.text || 'No Text'}</dd>
|
return <div className="noNotifications">No notifications available.</div>;
|
||||||
|
}
|
||||||
|
|
||||||
<dt>Created</dt>
|
return (
|
||||||
<dd>{Moment(foundNotification.createdAt).toLocaleString()}</dd>
|
<div className="notificationsList">
|
||||||
|
{notifications.map((notification) => (
|
||||||
<dt>Start</dt>
|
<details key={notification.dismissKey}>
|
||||||
<dd>{Moment(foundNotification.startAt).toLocaleString() || 'No Start Time'}</dd>
|
<summary>{notification.title || 'No Title'}</summary>
|
||||||
|
<NotificationDetail notification={notification} onDelete={deleteNotification} />
|
||||||
<dt>Stop</dt>
|
</details>
|
||||||
<dd>{Moment(foundNotification.stopAt).toLocaleString() || 'No End Time'}</dd>
|
))}
|
||||||
</dl>
|
|
||||||
<button onClick={deleteNotification}>DELETE</button>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='notificationLookup'>
|
<div className="notificationLookup">
|
||||||
<h2>Lookup</h2>
|
<div className="byId">
|
||||||
<input
|
<h2>Lookup</h2>
|
||||||
type='text'
|
<input
|
||||||
value={query}
|
type="text"
|
||||||
onChange={handleChange}
|
ref={lookupRef}
|
||||||
placeholder='notification key'
|
onKeyDown={(e) => {
|
||||||
/>
|
if (e.key === 'Enter') {
|
||||||
<button onClick={lookup}>
|
lookup();
|
||||||
<i className={cx('fas', {
|
}
|
||||||
'fa-search': !searching,
|
}}
|
||||||
'fa-spin fa-spinner': searching,
|
placeholder="dismiss key"
|
||||||
})} />
|
/>
|
||||||
</button>
|
<button onClick={lookup}>
|
||||||
|
<i
|
||||||
|
className={cx('fas', {
|
||||||
|
'fa-search': !searching,
|
||||||
|
'fa-spin fa-spinner': searching,
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
|
||||||
{error && <div className='error'>{error.toString()}</div>}
|
{renderFoundNotification()}
|
||||||
|
</div>
|
||||||
|
<div className="all">
|
||||||
|
<h2>All Notifications</h2>
|
||||||
|
<button onClick={lookupAll}>
|
||||||
|
<i
|
||||||
|
className={cx('fas', {
|
||||||
|
'fa-search': !searching,
|
||||||
|
'fa-spin fa-spinner': searching,
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
|
||||||
{foundNotification
|
{renderNotificationsList()}
|
||||||
? renderFoundNotification()
|
</div>
|
||||||
: <div className='noNotification'>No notification found.</div>
|
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -139,19 +139,51 @@ router.get('/admin/stats', mw.adminOnly, async (req, res)=>{
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ####################### NOTIFICATIONS
|
||||||
|
|
||||||
/* Searches for notification with matching key */
|
/* Searches for notification with matching key */
|
||||||
router.get('/admin/notification/lookup/:id', mw.adminOnly, (req, res, next)=>{
|
router.get('/admin/notification/lookup/:id', mw.adminOnly, async (req, res, next) => {
|
||||||
NotificationModel.findOne({ dismissKey: req.params.id })
|
try {
|
||||||
.exec((err, notification)=>{
|
const notification = await NotificationModel.findOne({ dismissKey: req.params.id }).exec();
|
||||||
return res.json(notification);
|
if (!notification) {
|
||||||
});
|
return res.status(404).json({ message: 'Notification not found' });
|
||||||
|
}
|
||||||
|
return res.json(notification);
|
||||||
|
} catch (err) {
|
||||||
|
return next(err);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
/* Add new notification */
|
// get all notifications
|
||||||
router.post('/admin/notification/add', mw.adminOnly, async (req, res, next)=>{
|
router.get('/admin/notification/all', mw.adminOnly, async (req, res, next) => {
|
||||||
console.log(req.body);
|
try {
|
||||||
const notification = await NotificationModel.addNotification(req.body);
|
const notifications = await NotificationModel.getAll();
|
||||||
return res.json(notification);
|
return res.json(notifications);
|
||||||
|
} catch (err) {
|
||||||
|
return next(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post('/admin/notification/add', mw.adminOnly, async (req, res, next) => {
|
||||||
|
console.table(req.body);
|
||||||
|
try {
|
||||||
|
// Assuming you have some validation logic here
|
||||||
|
const notification = await NotificationModel.addNotification(req.body);
|
||||||
|
return res.json(notification);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error adding notification:', error);
|
||||||
|
return res.status(500).json({ error: 'An error occurred while adding the notification' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.delete('/admin/notification/delete/:id', mw.adminOnly, async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const notification = await NotificationModel.deleteNotification(req.params.id);
|
||||||
|
return res.json(notification);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error deleting notification: { key: ', req.params.id , ' error: ', error ,' }');
|
||||||
|
return res.status(500).json({ error: 'An error occurred while deleting the notification' });
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/admin', mw.adminOnly, (req, res)=>{
|
router.get('/admin', mw.adminOnly, (req, res)=>{
|
||||||
|
|||||||
@@ -1,80 +1,104 @@
|
|||||||
const mongoose = require('mongoose');
|
const mongoose = require('mongoose');
|
||||||
const _ = require('lodash');
|
const _ = require('lodash');
|
||||||
|
|
||||||
const NotificationSchema = mongoose.Schema({
|
// Define the schema for the notification
|
||||||
dismissKey : { type: String, unique: true, required: true },
|
const NotificationSchema = new mongoose.Schema({
|
||||||
title : { type: String, default: '' },
|
dismissKey: { type: String, unique: true, required: true },
|
||||||
text : { type: String, default: '' },
|
title: { type: String, default: '' },
|
||||||
|
text: { type: String, default: '' },
|
||||||
createdAt : { type: Date, default: Date.now },
|
createdAt: { type: Date, default: Date.now },
|
||||||
startAt : { type: Date, default: Date.now },
|
startAt: { type: Date, default: Date.now },
|
||||||
stopAt : { type: Date, default: Date.now },
|
stopAt: { type: Date, default: Date.now },
|
||||||
}, { versionKey: false });
|
}, { versionKey: false });
|
||||||
|
|
||||||
NotificationSchema.statics.get = function(query, fields=null){
|
// Static method to get a notification based on a query
|
||||||
return new Promise((resolve, reject)=>{
|
NotificationSchema.statics.get = async function(query, fields = null) {
|
||||||
Notification.find(query, fields, null, (err, notifications)=>{
|
try {
|
||||||
if(err || !notifications.length) return reject('Can not find notification');
|
const notifications = await this.find(query, fields).exec();
|
||||||
return resolve(notifications[0]);
|
if (!notifications.length) throw new Error('Cannot find notification');
|
||||||
});
|
return notifications[0];
|
||||||
});
|
} catch (err) {
|
||||||
|
throw new Error(err.message || 'Error finding notification');
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
NotificationSchema.statics.getByKey = function(key, fields=null){
|
// Static method to get a notification by its dismiss key
|
||||||
return new Promise((resolve, reject)=>{
|
NotificationSchema.statics.getByKey = async function(key, fields = null) {
|
||||||
const query = { dissmissKey: key };
|
try {
|
||||||
Notification.findOne(query, fields).lean().exec((err, notifications)=>{ //lean() converts results to JSObjects
|
const notification = await this.findOne({ dismissKey: key }, fields).lean().exec();
|
||||||
if(err) return reject('Can not find notification');
|
if (!notification) throw new Error('Cannot find notification');
|
||||||
return resolve(notifications);
|
return notification;
|
||||||
});
|
} catch (err) {
|
||||||
});
|
throw new Error(err.message || 'Error finding notification');
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
NotificationSchema.statics.addNotification = async function(data){
|
// Static method to add a new notification
|
||||||
// console.log('add notification');
|
NotificationSchema.statics.addNotification = async function(data) {
|
||||||
if(!data.dismissKey) return 'Dismiss key is required!';
|
if (!data.dismissKey) return 'Dismiss key is required!';
|
||||||
const defaults = {
|
const defaults = {
|
||||||
title : '',
|
title: '',
|
||||||
text : '',
|
text: '',
|
||||||
startAt : new Date,
|
startAt: new Date(),
|
||||||
stopAt : new Date
|
stopAt: new Date()
|
||||||
};
|
};
|
||||||
_.defaults(data, defaults);
|
_.defaults(data, defaults);
|
||||||
const newNotification = new Notification(data);
|
const newNotification = new this(data);
|
||||||
const savedNotification = await newNotification.save()
|
try {
|
||||||
.catch((err)=>{
|
const savedNotification = await newNotification.save();
|
||||||
return { err };
|
return savedNotification;
|
||||||
});
|
} catch (err) {
|
||||||
|
throw new Error(err.message || 'Error saving notification');
|
||||||
return savedNotification;
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
NotificationSchema.statics.updateNotification = async function(dismissKey, title=null, text=null, startAt=null, stopAt=null){
|
// Static method to update a notification
|
||||||
if(!dismissKey) return 'No key!';
|
NotificationSchema.statics.updateNotification = async function(dismissKey, title = null, text = null, startAt = null, stopAt = null) {
|
||||||
if(!title && !text && !startAt && !stopAt) return 'No data!';
|
if (!dismissKey) return 'No key!';
|
||||||
const filter = {
|
if (!title && !text && !startAt && !stopAt) return 'No data!';
|
||||||
dismissKey : dismissKey
|
const filter = { dismissKey: dismissKey };
|
||||||
};
|
const data = { title, text, startAt, stopAt };
|
||||||
const data = {
|
|
||||||
title : title,
|
|
||||||
text : text,
|
|
||||||
startAt : startAt,
|
|
||||||
stopAt : stopAt
|
|
||||||
};
|
|
||||||
for (const [key, value] of Object.entries(data)){
|
|
||||||
if(value === null) delete data[key];
|
|
||||||
}
|
|
||||||
|
|
||||||
await Notification.findOneAndUpdate(filter, data, { new: true })
|
// Remove null values from the data object
|
||||||
.exec((err, notifications)=>{
|
for (const [key, value] of Object.entries(data)) {
|
||||||
if(err) return reject('Can not find notification');
|
if (value === null) delete data[key];
|
||||||
return resolve(notifications);
|
}
|
||||||
});
|
|
||||||
|
try {
|
||||||
|
const updatedNotification = await this.findOneAndUpdate(filter, data, { new: true }).exec();
|
||||||
|
if (!updatedNotification) throw new Error('Cannot find notification');
|
||||||
|
return updatedNotification;
|
||||||
|
} catch (err) {
|
||||||
|
throw new Error(err.message || 'Error updating notification');
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Static method to delete a notification
|
||||||
|
NotificationSchema.statics.deleteNotification = async function(dismissKey) {
|
||||||
|
if (!dismissKey) return 'No key provided!';
|
||||||
|
try {
|
||||||
|
const deletedNotification = await this.findOneAndDelete({ dismissKey }).exec();
|
||||||
|
if (!deletedNotification) throw new Error('Notification not found');
|
||||||
|
return deletedNotification;
|
||||||
|
} catch (err) {
|
||||||
|
throw new Error(err.message || 'Error deleting notification');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Static method to get all notifications
|
||||||
|
NotificationSchema.statics.getAll = async function() {
|
||||||
|
try {
|
||||||
|
const notifications = await this.find().exec();
|
||||||
|
return notifications;
|
||||||
|
} catch (err) {
|
||||||
|
throw new Error(err.message || 'Error retrieving notifications');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Create and export the model
|
||||||
const Notification = mongoose.model('Notification', NotificationSchema);
|
const Notification = mongoose.model('Notification', NotificationSchema);
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
schema : NotificationSchema,
|
schema: NotificationSchema,
|
||||||
model : Notification,
|
model: Notification,
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user