0
0
mirror of https://github.com/naturalcrit/homebrewery.git synced 2026-01-04 16:52:38 +00:00

"Updated admin notification management: added error handling and styling, modified notification add and lookup functionality, and refactored server-side API routes and error handling."

This commit is contained in:
Víctor Losada Hernández
2024-09-14 23:58:47 +02:00
parent 9bf28f1433
commit ebc3b4ee66
7 changed files with 121 additions and 112 deletions

View File

@@ -89,4 +89,12 @@ body {
justify-content : space-between; justify-content : space-between;
} }
} }
.error {
background: rgb(178, 54, 54);
color:white;
font-weight: 900;
margin-block:10px;
padding:10px;
}
} }

View File

@@ -24,10 +24,17 @@ const NotificationAdd = ()=>{
const stopAt = new Date(stopAtRef.current.value); const stopAt = new Date(stopAtRef.current.value);
// Basic validation // Basic validation
if(!dismissKey || !title || !text || !startAt || !stopAt) { if (!dismissKey || !title || !text || isNaN(startAt.getTime()) || isNaN(stopAt.getTime())) {
setState((prevState) => ({ setState((prevState) => ({
...prevState, ...prevState,
error : 'All fields are required!', error: 'All fields are required',
}));
return;
}
if (startAt >= stopAt) {
setState((prevState) => ({
...prevState,
error: 'End date must be after the start date!',
})); }));
return; return;
} }
@@ -37,7 +44,7 @@ const NotificationAdd = ()=>{
title, title,
text, text,
startAt : startAt?.toISOString() ?? '', startAt : startAt?.toISOString() ?? '',
stopAt : stopAt?.stopAt.toISOString() ?? '', stopAt : stopAt?.toISOString() ?? '',
}; };
try { try {
@@ -56,10 +63,11 @@ const NotificationAdd = ()=>{
...update, ...update,
searching : false, searching : false,
})); }));
} catch (err) { } catch (error) {
console.log(error.response.body.message);
setState((prevState)=>({ setState((prevState)=>({
...prevState, ...prevState,
error : `Error saving notification: ${err.message}`, error : `Error saving notification: ${error.response.body.message}`,
searching : false, searching : false,
})); }));
} }
@@ -110,7 +118,6 @@ const NotificationAdd = ()=>{
<i className={`fas ${state.searching ? 'fa-spin fa-spinner' : 'fa-save'}`} /> <i className={`fas ${state.searching ? 'fa-spin fa-spinner' : 'fa-save'}`} />
Save Notification Save Notification
</button> </button>
{state.error && <div className='error'>{state.error}</div>} {state.error && <div className='error'>{state.error}</div>}
</div> </div>
); );

View File

@@ -25,6 +25,7 @@
min-height : 7em; min-height : 7em;
max-height : 20em; max-height : 20em;
resize : vertical; resize : vertical;
padding : 10px;
} }
} }

View File

@@ -1,13 +1,12 @@
require('./notificationLookup.less'); require('./notificationLookup.less');
const React = require('react'); const React = require('react');
const { useState, useRef } = require('react'); const { useState } = require('react');
const cx = require('classnames');
const request = require('superagent'); const request = require('superagent');
const Moment = require('moment'); const Moment = require('moment');
const NotificationDetail = ({ notification, onDelete })=>( const NotificationDetail = ({ notification, onDelete })=>(
<div> <>
<dl> <dl>
<dt>Key</dt> <dt>Key</dt>
<dd>{notification.dismissKey}</dd> <dd>{notification.dismissKey}</dd>
@@ -28,7 +27,7 @@ const NotificationDetail = ({ notification, onDelete }) => (
<dd>{Moment(notification.stopAt).format('LLLL') || 'No End Time'}</dd> <dd>{Moment(notification.stopAt).format('LLLL') || 'No End Time'}</dd>
</dl> </dl>
<button onClick={()=>onDelete(notification.dismissKey)}>DELETE</button> <button onClick={()=>onDelete(notification.dismissKey)}>DELETE</button>
</div> </>
); );
const NotificationLookup = ()=>{ const NotificationLookup = ()=>{
@@ -44,8 +43,9 @@ const NotificationLookup = () => {
try { try {
const res = await request.get('/admin/notification/all'); const res = await request.get('/admin/notification/all');
setNotifications(res.body || []); setNotifications(res.body || []);
} catch { } catch (error) {
setError('Error fetching all notifications.'); console.log(error);
setError(`Error looking up notifications: ${error.response.body.message}`)
} finally { } finally {
setSearching(false); setSearching(false);
} }
@@ -58,34 +58,34 @@ const NotificationLookup = () => {
`Really delete notification ${dismissKey}?` `Really delete notification ${dismissKey}?`
); );
if(!confirmed) { if(!confirmed) {
console.log('CANCELLED'); console.log('Delete notification cancelled');
return; return;
} }
console.log('CONFIRMED'); console.log('Delete notification confirm');
try { try {
await request.delete(`/admin/notification/delete/${dismissKey}`); await request.delete(`/admin/notification/delete/${dismissKey}`);
// Only reset the foundNotification if it matches the one being deleted // Only reset the foundNotification if it matches the one being deleted
if(foundNotification && foundNotification.dismissKey === dismissKey) { if(foundNotification && foundNotification.dismissKey === dismissKey) {
setFoundNotification(null); setFoundNotification(null);
} }
// Optionally refresh the list of all notifications
lookupAll(); lookupAll();
} catch { } catch (error) {
setError('Error deleting notification.'); console.log(error);
} setError(`Error deleting notification: ${error.response.body.message}`)
}; };
}
const renderNotificationsList = ()=>{ const renderNotificationsList = ()=>{
if(error) { if(error) {
return <div className="error">{error}</div>; return <div className='error'>{error}</div>;
} }
if(notifications.length === 0) { if(notifications.length === 0) {
return <div className="noNotification">No notifications available.</div>; return <div className='noNotification'>No notifications available.</div>;
} }
return ( return (
<ul className="notificationList"> <ul className='notificationList'>
{notifications.map((notification)=>( {notifications.map((notification)=>(
<li key={notification.dismissKey} > <li key={notification.dismissKey} >
<details> <details>
@@ -99,17 +99,10 @@ const NotificationLookup = () => {
}; };
return ( return (
<div className="notificationLookup"> <div className='notificationLookup'>
<h2>Check all Notifications</h2><button onClick={lookupAll}> <h2>Check all Notifications</h2><button onClick={lookupAll}>
<i <i className={`fas ${searching ? 'fa-spin fa-spinner' : 'fa-search'}`} />
className={cx('fas', {
'fa-search': !searching,
'fa-spin fa-spinner': searching,
})}
/>
</button> </button>
{renderNotificationsList()} {renderNotificationsList()}
</div> </div>
); );

View File

@@ -1,7 +1,7 @@
.notificationLookup { .notificationLookup {
width : max-content; width : 450px;
min-width : 450px; height : fit-content;
.notificationList { .notificationList {
display : flex; display : flex;

View File

@@ -145,20 +145,20 @@ router.get('/admin/notification/all', async (req, res, next) => {
try { try {
const notifications = await NotificationModel.getAll(); const notifications = await NotificationModel.getAll();
return res.json(notifications); return res.json(notifications);
} catch (err) { } catch (error) {
return next(err); console.log('Error getting all notifications: ', error.message);
return res.status(500).json({message: error.message});
} }
}); });
router.post('/admin/notification/add', mw.adminOnly, async (req, res, next) => { router.post('/admin/notification/add', mw.adminOnly, async (req, res, next) => {
console.table(req.body); console.table(req.body);
try { try {
// Assuming you have some validation logic here
const notification = await NotificationModel.addNotification(req.body); const notification = await NotificationModel.addNotification(req.body);
return res.json(notification); return res.status(201).json(notification);
} catch (error) { } catch (error) {
console.error('Error adding notification:', error); console.log('Error adding notification: ', error.message);
return res.status(500).json({ error: 'An error occurred while adding the notification' }); return res.status(500).json({message: error.message});
} }
}); });
@@ -167,8 +167,8 @@ router.delete('/admin/notification/delete/:id', mw.adminOnly, async (req, res, n
const notification = await NotificationModel.deleteNotification(req.params.id); const notification = await NotificationModel.deleteNotification(req.params.id);
return res.json(notification); return res.json(notification);
} catch (error) { } catch (error) {
console.error('Error deleting notification: { key: ', req.params.id , ' error: ', error ,' }'); console.error('Error deleting notification: { key: ', req.params.id , ' error: ', error.message ,' }');
return res.status(500).json({ error: 'An error occurred while deleting the notification' }); return res.status(500).json({message: error.message});
} }
}); });

View File

@@ -517,7 +517,7 @@ const getPureError = (error)=>{
app.use(async (err, req, res, next)=>{ app.use(async (err, req, res, next)=>{
err.originalUrl = req.originalUrl; err.originalUrl = req.originalUrl;
console.error(err); console.error('console.log in app.js: ', err);
if(err.originalUrl?.startsWith('/api/')) { if(err.originalUrl?.startsWith('/api/')) {
// console.log('API error'); // console.log('API error');