Improved notifications.
All checks were successful
farmcontrol/farmcontrol-ui/pipeline/head This commit looks good

This commit is contained in:
Tom Butcher 2026-03-01 19:21:10 +00:00
parent 96f7713f4d
commit 9470adbb8a
8 changed files with 336 additions and 162 deletions

View File

@ -22,13 +22,22 @@ import MissingPlaceholder from './MissingPlaceholder'
import NewNote from '../Management/Notes/NewNote' import NewNote from '../Management/Notes/NewNote'
import { ApiServerContext } from '../context/ApiServerContext' import { ApiServerContext } from '../context/ApiServerContext'
import ExclamationOctagonIcon from '../../Icons/ExclamationOctagonIcon' import ExclamationOctagonIcon from '../../Icons/ExclamationOctagonIcon'
import UserNotifierToggle from './UserNotifierToggle'
import { AuthContext } from '../context/AuthContext' import { AuthContext } from '../context/AuthContext'
import { getModelByName } from '../../../database/ObjectModels' import { getModelByName } from '../../../database/ObjectModels'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
const { Text } = Typography const { Text } = Typography
const NoteItem = ({ note }) => { const NoteItem = ({
note,
showCard = true,
showCreatedAt = true,
showChildNotes = true,
showActions = true,
showInfo = true,
largeSpacing = false
}) => {
const [childNotes, setChildNotes] = useState([]) const [childNotes, setChildNotes] = useState([])
const noteModel = getModelByName('note') const noteModel = getModelByName('note')
const infoAction = noteModel.actions.filter( const infoAction = noteModel.actions.filter(
@ -151,15 +160,8 @@ const NoteItem = ({ note }) => {
}) })
} }
return ( const noteItem = (
<Card <>
key={note._id}
size='small'
style={{
backgroundColor: note.noteType.color + '26',
textAlign: 'left'
}}
>
<Flex vertical gap={'small'}> <Flex vertical gap={'small'}>
<Flex gap={'middle'} align='start'> <Flex gap={'middle'} align='start'>
<Space> <Space>
@ -170,15 +172,25 @@ const NoteItem = ({ note }) => {
<MarkdownDisplay content={note.content} /> <MarkdownDisplay content={note.content} />
</div> </div>
</Flex> </Flex>
<Divider style={{ margin: 0 }} /> <Divider style={{ margin: largeSpacing ? '10px 0' : 0 }} />
<Flex wrap gap={'small'}> <Flex wrap gap={'small'}>
<Dropdown {showActions && (
menu={{ items: dropdownItems }} <>
trigger={['hover']} <Dropdown
placement='bottomLeft' menu={{ items: dropdownItems }}
> trigger={['hover']}
<Button size='small'>Actions</Button> placement='bottomLeft'
</Dropdown> >
<Button size='small'>Actions</Button>
</Dropdown>
<UserNotifierToggle
type='note'
size='small'
objectData={note}
disabled={false}
/>
</>
)}
<Space size={'small'} style={{ marginRight: 8 }}> <Space size={'small'} style={{ marginRight: 8 }}>
<Text type='secondary'>Type:</Text> <Text type='secondary'>Type:</Text>
<Tag color={note.noteType.color} style={{ margin: 0 }}> <Tag color={note.noteType.color} style={{ margin: 0 }}>
@ -194,34 +206,44 @@ const NoteItem = ({ note }) => {
showHyperlink={true} showHyperlink={true}
/> />
</Space> </Space>
<Space size={'small'} style={{ marginRight: 8 }}> {showCreatedAt && (
<Text type='secondary'>Created At:</Text> <Space size={'small'} style={{ marginRight: 8 }}>
<TimeDisplay dateTime={note.createdAt} showSince={true} /> <Text type='secondary'>Created At:</Text>
</Space> <TimeDisplay dateTime={note.createdAt} showSince={true} />
</Space>
)}
<Flex style={{ flexGrow: 1 }} justify='end'> <Flex style={{ flexGrow: 1 }} justify='end'>
<Space size={'small'}> <Space size={'small'}>
<Button {showInfo && (
icon={<InfoIcon />} <Button
type='text' icon={<InfoIcon />}
size='small' type='text'
onClick={() => { size='small'
navigate(infoAction.url(note._id)) onClick={() => {
}} navigate(infoAction.url(note._id))
/> }}
<Button />
icon={ )}
childNotesLoading ? <LoadingOutlined /> : <CaretLeftFilled /> {showChildNotes && (
} <Button
size='small' icon={
type='text' childNotesLoading ? (
loading={childNotesLoading} <LoadingOutlined />
disabled={childNotesLoading} ) : (
style={{ <CaretLeftFilled />
transform: transformValue, )
transition: 'transform 0.2s ease' }
}} size='small'
onClick={toggleExpand} type='text'
/> loading={childNotesLoading}
disabled={childNotesLoading}
style={{
transform: transformValue,
transition: 'transform 0.2s ease'
}}
onClick={toggleExpand}
/>
)}
</Space> </Space>
</Flex> </Flex>
</Flex> </Flex>
@ -296,12 +318,33 @@ const NoteItem = ({ note }) => {
> >
<Text>Are you sure you want to delete this note?</Text> <Text>Are you sure you want to delete this note?</Text>
</Modal> </Modal>
</>
)
return showCard ? (
<Card
key={note._id}
size='small'
style={{
backgroundColor: note.noteType.color + '26',
textAlign: 'left'
}}
>
{noteItem}
</Card> </Card>
) : (
noteItem
) )
} }
NoteItem.propTypes = { NoteItem.propTypes = {
note: PropTypes.object.isRequired note: PropTypes.object.isRequired,
showCard: PropTypes.bool,
showCreatedAt: PropTypes.bool,
showChildNotes: PropTypes.bool,
showActions: PropTypes.bool,
largeSpacing: PropTypes.bool,
showInfo: PropTypes.bool
} }
export default NoteItem export default NoteItem

View File

@ -13,6 +13,8 @@ import PropertyChanges from './PropertyChanges'
import XMarkIcon from '../../Icons/XMarkIcon' import XMarkIcon from '../../Icons/XMarkIcon'
import ObjectDisplay from './ObjectDisplay' import ObjectDisplay from './ObjectDisplay'
import BinIcon from '../../Icons/BinIcon' import BinIcon from '../../Icons/BinIcon'
import NoteItem from './NoteItem'
import PlusIcon from '../../Icons/PlusIcon'
const { Text, Paragraph } = Typography const { Text, Paragraph } = Typography
@ -35,6 +37,8 @@ const Notification = ({
return <InfoCircleOutlined /> return <InfoCircleOutlined />
case 'editObject': case 'editObject':
return <EditIcon /> return <EditIcon />
case 'newNote':
return <PlusIcon />
case 'deleteObject': case 'deleteObject':
return <BinIcon /> return <BinIcon />
case 'error': case 'error':
@ -67,6 +71,12 @@ const Notification = ({
Delete Delete
</Tag> </Tag>
) )
case 'newNote':
return (
<Tag color='green' icon={icon} style={{ margin: 0 }}>
Note
</Tag>
)
case 'error': case 'error':
return ( return (
<Tag color='red' icon={icon} style={{ margin: 0 }}> <Tag color='red' icon={icon} style={{ margin: 0 }}>
@ -110,7 +120,7 @@ const Notification = ({
expandable: true, expandable: true,
symbol: 'Show more' symbol: 'Show more'
}, },
style: { margin: 0 } style: { margin: largeSpacing ? '10px 0 0 0' : 0 }
} }
switch (type) { switch (type) {
case 'editObject': { case 'editObject': {
@ -118,7 +128,7 @@ const Notification = ({
<Paragraph {...paragraph}> <Paragraph {...paragraph}>
Object: Object:
<ObjectDisplay <ObjectDisplay
object={metadata.object} object={{ ...metadata?.object, _id: metadata?.object?._id }}
objectType={metadata.objectType} objectType={metadata.objectType}
showHyperlink={true} showHyperlink={true}
showSpotlight={true} showSpotlight={true}
@ -133,6 +143,21 @@ const Notification = ({
</Paragraph> </Paragraph>
) )
} }
case 'newNote': {
return (
<Paragraph {...paragraph}>
<NoteItem
note={metadata.note}
showCard={false}
showCreatedAt={false}
showChildNotes={false}
showActions={false}
showInfo={false}
largeSpacing={largeSpacing}
/>
</Paragraph>
)
}
default: default:
return <Paragraph {...paragraph}>{notification.message}</Paragraph> return <Paragraph {...paragraph}>{notification.message}</Paragraph>
} }

View File

@ -1,5 +1,6 @@
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
import { Typography, Flex, Badge, Tag, Popover } from 'antd' import { Typography, Flex, Badge, Tag, Popover } from 'antd'
import { LoadingOutlined } from '@ant-design/icons'
import { useState, useEffect, useContext, useCallback, useRef } from 'react' import { useState, useEffect, useContext, useCallback, useRef } from 'react'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import { getModelByName } from '../../../database/ObjectModels' import { getModelByName } from '../../../database/ObjectModels'
@ -18,6 +19,7 @@ const ObjectDisplay = ({
showSpotlight = true showSpotlight = true
}) => { }) => {
const [objectData, setObjectData] = useState(object) const [objectData, setObjectData] = useState(object)
const [isHydrating, setIsHydrating] = useState(false)
const { subscribeToObjectUpdates, connected, fetchSpotlightData } = const { subscribeToObjectUpdates, connected, fetchSpotlightData } =
useContext(ApiServerContext) useContext(ApiServerContext)
const { token } = useContext(AuthContext) const { token } = useContext(AuthContext)
@ -44,7 +46,12 @@ const ObjectDisplay = ({
const model = getModelByName(objectType) const model = getModelByName(objectType)
const spotlightQuery = `${model.prefix}:${obj._id}` const spotlightQuery = `${model.prefix}:${obj._id}`
const spotlightResult = await fetchSpotlightData(spotlightQuery) const spotlightResult = await fetchSpotlightData(spotlightQuery)
if (spotlightResult && typeof spotlightResult === 'object') { // Spotlight returns [] when not found; only use single-object results
if (
spotlightResult &&
typeof spotlightResult === 'object' &&
!Array.isArray(spotlightResult)
) {
return spotlightResult return spotlightResult
} }
} catch (err) { } catch (err) {
@ -57,7 +64,7 @@ const ObjectDisplay = ({
// Subscribe to object updates when component mounts // Subscribe to object updates when component mounts
useEffect(() => { useEffect(() => {
if (object?._id && objectType && connected && token) { if (object?._id && objectType && connected && token != null) {
const objectUpdatesUnsubscribe = subscribeToObjectUpdates( const objectUpdatesUnsubscribe = subscribeToObjectUpdates(
object._id, object._id,
objectType, objectType,
@ -79,22 +86,49 @@ const ObjectDisplay = ({
// Update local state when object prop changes // Update local state when object prop changes
useEffect(() => { useEffect(() => {
if (idRef.current == object?._id) return if (token == null) return
idRef.current = object?._id const isMinimal = isMinimalObject(object)
// Only skip re-fetch when we have a minimal object and already hydrated this id
if (isMinimal && idRef.current === object?._id) return
let cancelled = false let cancelled = false
if (isMinimal) setIsHydrating(true)
const hydrateObject = async () => { const hydrateObject = async () => {
const fullObject = await fetchFullObjectIfNeeded(object) const fullObject = await fetchFullObjectIfNeeded(object)
if (!cancelled) setObjectData(fullObject) if (!cancelled) {
setObjectData((prev) => merge({}, prev, fullObject))
if (isMinimal) idRef.current = object?._id
setIsHydrating(false)
}
} }
hydrateObject() hydrateObject()
return () => { return () => {
cancelled = true cancelled = true
setIsHydrating(false)
} }
}, [object, fetchFullObjectIfNeeded]) }, [object, fetchFullObjectIfNeeded, isMinimalObject, token])
if (!objectData) { if (!objectData) {
return <Text type='secondary'>n/a</Text> return <Text type='secondary'>n/a</Text>
} }
if (isHydrating) {
return (
<Tag
style={{
margin: 0,
border: 'none',
minWidth: 0,
maxWidth: '100%'
}}
className='object-display-tag'
>
<Flex gap='4px' align='center' style={{ minWidth: 0, height: '24px' }}>
<LoadingOutlined spin />
<Text type='secondary'>Loading...</Text>
</Flex>
</Tag>
)
}
const model = getModelByName(objectType) const model = getModelByName(objectType)
const Icon = model.icon const Icon = model.icon
const prefix = model.prefix const prefix = model.prefix

View File

@ -1,5 +1,5 @@
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
import { useState, useEffect, useContext } from 'react' import { useState, useEffect, useContext, useRef, useCallback, useMemo, memo } from 'react'
import { Button, message, Popover, Typography, Space, Flex } from 'antd' import { Button, message, Popover, Typography, Space, Flex } from 'antd'
import { UserOutlined } from '@ant-design/icons' import { UserOutlined } from '@ant-design/icons'
import BellIcon from '../../Icons/BellIcon' import BellIcon from '../../Icons/BellIcon'
@ -12,9 +12,10 @@ import InfoCircleIcon from '../../Icons/InfoCircleIcon'
const { Text } = Typography const { Text } = Typography
const UserNotifierToggle = ({ const UserNotifierToggle = memo(({
type, type,
objectData, objectData,
size = 'middle',
disabled = false, disabled = false,
...buttonProps ...buttonProps
}) => { }) => {
@ -24,7 +25,7 @@ const UserNotifierToggle = ({
fetchUserNotifiersForObject, fetchUserNotifiersForObject,
fetchAllUserNotifiersForObject fetchAllUserNotifiersForObject
} = useContext(ApiServerContext) } = useContext(ApiServerContext)
const { userProfile } = useContext(AuthContext) const { userProfile, token, authInitialized } = useContext(AuthContext)
const [isNotifying, setIsNotifying] = useState(false) const [isNotifying, setIsNotifying] = useState(false)
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const [initialLoad, setInitialLoad] = useState(true) const [initialLoad, setInitialLoad] = useState(true)
@ -34,14 +35,24 @@ const UserNotifierToggle = ({
const [emailTogglingId, setEmailTogglingId] = useState(null) const [emailTogglingId, setEmailTogglingId] = useState(null)
const objectId = objectData?._id const objectId = objectData?._id
const authReady = Boolean(token && authInitialized)
const apiRef = useRef({
fetchUserNotifiersForObject,
fetchAllUserNotifiersForObject
})
apiRef.current = {
fetchUserNotifiersForObject,
fetchAllUserNotifiersForObject
}
useEffect(() => { useEffect(() => {
const loadNotifierState = async () => { if (!authReady || !objectId || !type) return
if (!objectId || !type) return
const loadNotifierState = async () => {
setInitialLoad(true) setInitialLoad(true)
try { try {
const { data } = await fetchUserNotifiersForObject(objectId, type) const { data } = await apiRef.current.fetchUserNotifiersForObject(objectId, type)
setIsNotifying(data?.length > 0) setIsNotifying(data?.length > 0)
} catch (error) { } catch (error) {
console.error('Error fetching user notifier state:', error) console.error('Error fetching user notifier state:', error)
@ -51,15 +62,15 @@ const UserNotifierToggle = ({
} }
loadNotifierState() loadNotifierState()
}, [objectId, type, fetchUserNotifiersForObject]) }, [authReady, objectId, type])
useEffect(() => { useEffect(() => {
const loadAllNotifiers = async () => { if (!authReady || !objectId || !type || !popoverOpen) return
if (!objectId || !type || !popoverOpen) return
const loadAllNotifiers = async () => {
setPopoverLoading(true) setPopoverLoading(true)
try { try {
const { data } = await fetchAllUserNotifiersForObject(objectId, type) const { data } = await apiRef.current.fetchAllUserNotifiersForObject(objectId, type)
setAllNotifiers(data || []) setAllNotifiers(data || [])
} catch (error) { } catch (error) {
console.error('Error fetching all user notifiers:', error) console.error('Error fetching all user notifiers:', error)
@ -70,10 +81,10 @@ const UserNotifierToggle = ({
} }
loadAllNotifiers() loadAllNotifiers()
}, [objectId, type, popoverOpen, fetchAllUserNotifiersForObject]) }, [authReady, objectId, type, popoverOpen])
const handleClick = async () => { const handleClick = useCallback(async () => {
if (!objectId || !type || loading) return if (!authReady || !objectId || !type || loading) return
setLoading(true) setLoading(true)
try { try {
@ -94,9 +105,9 @@ const UserNotifierToggle = ({
} finally { } finally {
setLoading(false) setLoading(false)
} }
} }, [authReady, objectId, type, loading, popoverOpen, toggleUserNotifier, fetchAllUserNotifiersForObject])
const getUserDisplayName = (user) => { const getUserDisplayName = useCallback((user) => {
if (!user) return 'Unknown' if (!user) return 'Unknown'
return ( return (
user.name || user.name ||
@ -105,11 +116,11 @@ const UserNotifierToggle = ({
user.email || user.email ||
'Unknown' 'Unknown'
) )
} }, [])
const isCurrentUser = (user) => user?._id === userProfile?._id const isCurrentUser = useCallback((user) => user?._id === userProfile?._id, [userProfile?._id])
const handleEmailToggle = async (item) => { const handleEmailToggle = useCallback(async (item) => {
if (!isCurrentUser(item.user) || emailTogglingId) return if (!isCurrentUser(item.user) || emailTogglingId) return
setEmailTogglingId(item._id) setEmailTogglingId(item._id)
const newEmail = !item.email const newEmail = !item.email
@ -133,71 +144,74 @@ const UserNotifierToggle = ({
} finally { } finally {
setEmailTogglingId(null) setEmailTogglingId(null)
} }
} }, [isCurrentUser, emailTogglingId, editUserNotifier])
const popoverContent = ( const popoverContent = useMemo(
<Flex () => (
vertical <Flex
justify='center' vertical
style={{ minWidth: 240, minHeight: 25 }} justify='center'
gap={'4px'} style={{ minWidth: 240, minHeight: 25 }}
> gap={'4px'}
{popoverLoading ? ( >
<Space size={'small'}> {popoverLoading ? (
<LoadingOutlined /> <Space size={'small'}>
<Text style={{ margin: 0 }}>Loading, please wait...</Text> <LoadingOutlined />
</Space> <Text style={{ margin: 0 }}>Loading, please wait...</Text>
) : allNotifiers.length === 0 ? ( </Space>
<Space size={'small'}> ) : allNotifiers.length === 0 ? (
<Text style={{ margin: 0 }} type='secondary'> <Space size={'small'}>
<InfoCircleIcon /> <Text style={{ margin: 0 }} type='secondary'>
</Text> <InfoCircleIcon />
<Text style={{ margin: 0 }} type='secondary'> </Text>
No users subscribed. <Text style={{ margin: 0 }} type='secondary'>
</Text> No users subscribed.
</Space> </Text>
) : ( </Space>
<> ) : (
{[...allNotifiers] <>
.sort( {[...allNotifiers]
(a, b) => .sort(
(isCurrentUser(b.user) ? 1 : 0) - (a, b) =>
(isCurrentUser(a.user) ? 1 : 0) (isCurrentUser(b.user) ? 1 : 0) -
) (isCurrentUser(a.user) ? 1 : 0)
.map((item) => ( )
<Flex key={item._id} justify='space-between' align='center'> .map((item) => (
<Flex align='center' gap={'6px'}> <Flex key={item._id} justify='space-between' align='center'>
<UserOutlined /> <Flex align='center' gap={'6px'}>
<Text>{getUserDisplayName(item.user)}</Text> <UserOutlined />
{isCurrentUser(item.user) && ( <Text>{getUserDisplayName(item.user)}</Text>
<Text type='secondary'> (you)</Text> {isCurrentUser(item.user) && (
)} <Text type='secondary'> (you)</Text>
)}
</Flex>
<Space size={'small'}>
<Button
type='text'
icon={
item.email ? (
<MailCheckIcon
style={{
color: 'var(--color-primary)'
}}
/>
) : (
<MailIcon />
)
}
size='small'
disabled={!isCurrentUser(item.user)}
loading={emailTogglingId === item._id}
onClick={() => handleEmailToggle(item)}
/>
</Space>
</Flex> </Flex>
<Space size={'small'}> ))}
<Button </>
type='text' )}
icon={ </Flex>
item.email ? ( ),
<MailCheckIcon [popoverLoading, allNotifiers, emailTogglingId, isCurrentUser, getUserDisplayName, handleEmailToggle]
style={{
color: 'var(--color-primary)'
}}
/>
) : (
<MailIcon />
)
}
size='small'
disabled={!isCurrentUser(item.user)}
loading={emailTogglingId === item._id}
onClick={() => handleEmailToggle(item)}
/>
</Space>
</Flex>
))}
</>
)}
</Flex>
) )
return ( return (
@ -220,18 +234,23 @@ const UserNotifierToggle = ({
}} }}
/> />
} }
disabled={disabled || loading || initialLoad} disabled={disabled || loading || initialLoad || !authReady}
loading={loading || !objectId || !type} loading={loading || !authReady || !objectId || !type}
onClick={handleClick} onClick={handleClick}
size={size}
style={{ minWidth: size === 'small' ? 24 : undefined }}
/> />
</Popover> </Popover>
) )
} })
UserNotifierToggle.displayName = 'UserNotifierToggle'
UserNotifierToggle.propTypes = { UserNotifierToggle.propTypes = {
type: PropTypes.string.isRequired, type: PropTypes.string.isRequired,
objectData: PropTypes.object.isRequired, objectData: PropTypes.object.isRequired,
disabled: PropTypes.bool disabled: PropTypes.bool,
size: PropTypes.string
} }
export default UserNotifierToggle export default UserNotifierToggle

View File

@ -20,6 +20,11 @@ import loglevel from 'loglevel'
const logger = loglevel.getLogger('ApiServerContext') const logger = loglevel.getLogger('ApiServerContext')
logger.setLevel(config.logLevel) logger.setLevel(config.logLevel)
const SPOTLIGHT_CACHE_TTL_MS = 10_000
const spotlightCache = new Map()
const runningSpotlightFetches = new Map()
const ApiServerContext = createContext() const ApiServerContext = createContext()
const ApiServerProvider = ({ children }) => { const ApiServerProvider = ({ children }) => {
@ -974,24 +979,43 @@ const ApiServerProvider = ({ children }) => {
} }
const fetchSpotlightData = async (query) => { const fetchSpotlightData = async (query) => {
logger.debug('Fetching spotlight data with query:', query) const cached = spotlightCache.get(query)
try { if (cached && Date.now() - cached.timestamp < SPOTLIGHT_CACHE_TTL_MS) {
const response = await axios.get( logger.debug('Returning cached spotlight data for query:', query)
`${config.backendUrl}/spotlight/${query}`, return cached.data
{
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
}
}
)
return response.data
} catch (err) {
console.error(err)
showError(err, () => {
fetchSpotlightData(query)
})
} }
const existing = runningSpotlightFetches.get(query)
if (existing) {
return existing
}
const fetchPromise = (async () => {
try {
logger.debug('Fetching spotlight data with query:', query)
const response = await axios.get(
`${config.backendUrl}/spotlight/${query}`,
{
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
}
}
)
spotlightCache.set(query, { data: response.data, timestamp: Date.now() })
return response.data
} catch (err) {
console.error(err)
showError(err, () => {
fetchSpotlightData(query)
})
} finally {
runningSpotlightFetches.delete(query)
}
})()
runningSpotlightFetches.set(query, fetchPromise)
return fetchPromise
} }
const getModelStats = async (objectType) => { const getModelStats = async (objectType) => {

View File

@ -297,6 +297,7 @@ const AuthProvider = ({ children }) => {
setToken(nextToken) setToken(nextToken)
setExpiresAt(nextExpiresAt) setExpiresAt(nextExpiresAt)
setUserProfile(nextUser) setUserProfile(nextUser)
setAuthenticated(true)
// Persist session (cookies on web, keytar on electron) // Persist session (cookies on web, keytar on electron)
const persisted = await persistSession({ const persisted = await persistSession({
@ -619,6 +620,7 @@ const AuthProvider = ({ children }) => {
<AuthContext.Provider <AuthContext.Provider
value={{ value={{
authenticated, authenticated,
authInitialized: retreivedTokenFromCookies,
setUnauthenticated, setUnauthenticated,
loginWithSSO, loginWithSSO,
getLoginToken, getLoginToken,

View File

@ -5,6 +5,7 @@ import {
useCallback, useCallback,
useEffect useEffect
} from 'react' } from 'react'
import { useLocation } from 'react-router-dom'
import { notification, Drawer } from 'antd' import { notification, Drawer } from 'antd'
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
import { AuthContext } from './AuthContext' import { AuthContext } from './AuthContext'
@ -16,6 +17,7 @@ const NotificationContext = createContext()
const NotificationProvider = ({ children }) => { const NotificationProvider = ({ children }) => {
const [api, contextHolder] = notification.useNotification() const [api, contextHolder] = notification.useNotification()
const location = useLocation()
const { authenticated } = useContext(AuthContext) const { authenticated } = useContext(AuthContext)
const { const {
showError, showError,
@ -119,6 +121,10 @@ const NotificationProvider = ({ children }) => {
} }
}, [authenticated, fetchNotifications]) }, [authenticated, fetchNotifications])
useEffect(() => {
setNotificationCenterVisible(false)
}, [location.pathname])
useEffect(() => { useEffect(() => {
if (!authenticated || !registerNotificationListener) return if (!authenticated || !registerNotificationListener) return
const handleNotification = (notif) => { const handleNotification = (notif) => {

View File

@ -1,10 +1,10 @@
import { useSearchParams } from 'react-router-dom' import { useSearchParams } from 'react-router-dom'
import './EmailNotificationTemplate.css' import './EmailNotificationTemplate.css'
import { Button, Card, ConfigProvider, Flex, theme, Typography } from 'antd' import { Button, Card, ConfigProvider, Flex, theme, Typography } from 'antd'
import FarmControlLogo from '../Logos/FarmControlLogo' import FarmControlLogo from '../Logos/FarmControlLogo'
import Notification from '../Dashboard/common/Notification' import Notification from '../Dashboard/common/Notification'
import { useThemeContext } from '../Dashboard/context/ThemeContext' import { useThemeContext } from '../Dashboard/context/ThemeContext'
import { getModelByName } from '../../database/ObjectModels'
const { Text } = Typography const { Text } = Typography
@ -44,15 +44,32 @@ const EmailNotificationTemplate = () => {
const getNotifictionActions = () => { const getNotifictionActions = () => {
switch (type) { switch (type) {
case 'editObject': case 'editObject': {
const model = getModelByName(metadata?.objectType)
const infoAction = model.actions?.find(
(action) => action.name === 'info'
)
const url = infoAction ? infoAction.url(metadata?.object?._id) : '#'
return ( return (
<Button <Button href={`${origin}${url}`} type='primary'>
href={`${origin}/dashboard/${metadata.objectType}/${metadata.id}`}
type='primary'
>
View in Dashboard View in Dashboard
</Button> </Button>
) )
}
case 'newNote': {
console.log('newNote metadata', JSON.stringify(metadata, null, 2))
const model = getModelByName(metadata?.note?.parentType)
const infoAction =
model.actions?.find((action) => action.name === 'info') ?? null
const url = infoAction
? infoAction.url(metadata?.note?.parent?._id)
: null
return url ? (
<Button href={`${origin}${url}`} type='primary'>
View in Dashboard
</Button>
) : null
}
} }
return null return null
} }
@ -92,7 +109,11 @@ const EmailNotificationTemplate = () => {
{getNotifictionActions()} {getNotifictionActions()}
</Flex> </Flex>
{email && ( {email && (
<Flex justify='center' className='email-notification-card-footer'> <Flex
align='center'
className='email-notification-card-footer'
vertical
>
<Text <Text
type='secondary' type='secondary'
style={{ style={{