All files / pages/settings NotificationsPage.tsx

91.66% Statements 44/48
96.66% Branches 29/30
78.57% Functions 11/14
95.45% Lines 42/44

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274                                                                              1x                                                                 38x       27x 27x         27x 27x           27x 34x 34x     27x   33x 4x 4x 4x 8x     4x     4x 1x 1x   3x       27x 1x     1x 1x                             27x               27x 14x             13x 1x                         12x 12x 34x       34x   33x 34x 34x     12x   12x                                           11x           33x 33x   33x                                                                                                                              
import {type ReactElement, useState} from 'react';
import {
	Alert,
	Box,
	Button,
	CircularProgress,
	Container,
	Divider,
	Paper,
	Snackbar,
	Switch,
	Typography
} from '@mui/material';
import {Save as SaveIcon} from '@mui/icons-material';
 
import {
	type NotificationPreference,
	useGetMyNotificationPreferencesQuery,
	useUpdateMyNotificationPreferencesMutation
} from '../../services/notificationPreferencesApi';
 
// ============================================================================
// Display catalog
// ============================================================================
 
/**
 * Frontend labels for backend notification type identifiers. The backend
 * is the source of truth for which types are *applicable* to the current
 * user (filtered by role); the page renders only those it gets back, but
 * uses this catalog to look up human-readable text.
 *
 * Adding a new notification type means: backend migration + this catalog.
 */
interface TypeDisplay {
	group: string;
	label: string;
	description: string;
}
 
const TYPE_CATALOG: Record<string, TypeDisplay> = {
	'admin.cron.daily_accrual': {
		group: 'System monitoring',
		label: 'Daily interest accrual',
		description: 'Email me only when nightly interest accrual fails or accrues to zero accounts (an anomaly).'
	},
	'admin.cron.monthly_post': {
		group: 'System monitoring',
		label: 'Monthly interest post',
		description: 'Email me on every monthly post, with the account count and total amount.'
	},
	'admin.cron.balance_snapshot': {
		group: 'System monitoring',
		label: 'Daily balance snapshot',
		description: 'Email me only when the nightly balance snapshot fails or covers zero accounts.'
	}
};
 
// ============================================================================
// Types
// ============================================================================
 
interface SnackbarState {
	open: boolean;
	message: string;
	severity: 'success' | 'error';
}
 
// ============================================================================
// Component
// ============================================================================
 
function prefKey(pref: NotificationPreference): string {
	return `${pref.notificationType}|${pref.channel}`;
}
 
export default function NotificationsPage(): ReactElement {
	const {data: serverPreferences, isLoading, error} = useGetMyNotificationPreferencesQuery();
	const [updatePreferences, {isLoading: isSaving}] = useUpdateMyNotificationPreferencesMutation();
 
	// Track only what the user has toggled away from the server's value. The
	// rendered switch state is derived from server data + this overrides map,
	// so we never have to sync local state with server state in an effect.
	const [overrides, setOverrides] = useState<Record<string, boolean>>({});
	const [snackbar, setSnackbar] = useState<SnackbarState>({
		open: false,
		message: '',
		severity: 'success'
	});
 
	const merged: NotificationPreference[] = (serverPreferences ?? []).map((pref) => {
		const override = overrides[prefKey(pref)];
		return override === undefined ? pref : {...pref, enabled: override};
	});
 
	const isDirty = Object.keys(overrides).length > 0;
 
	const handleToggle = (pref: NotificationPreference) => (): void => {
		const key = prefKey(pref);
		const next = !pref.enabled; // pref is merged, so this flips the displayed value
		const serverValue = serverPreferences?.find(
			(s) => s.notificationType === pref.notificationType && s.channel === pref.channel
		)?.enabled;
 
		setOverrides((prev) => {
			// If the new toggled value matches the server's stored value,
			// drop the override entirely so isDirty correctly reports clean.
			if (next === serverValue) {
				const {[key]: _removed, ...rest} = prev;
				return rest;
			}
			return {...prev, [key]: next};
		});
	};
 
	const handleSave = (): void => {
		updatePreferences(merged)
			.unwrap()
			.then((): void => {
				setOverrides({});
				setSnackbar({
					open: true,
					message: 'Notification preferences saved.',
					severity: 'success'
				});
			})
			.catch((): void => {
				setSnackbar({
					open: true,
					message: 'Failed to save preferences. Please try again.',
					severity: 'error'
				});
			});
	};
 
	const handleCloseSnackbar = (): void => {
		setSnackbar((prev) => ({...prev, open: false}));
	};
 
	// -------------------------------------------------------------------------
	// Loading / error
	// -------------------------------------------------------------------------
 
	if (isLoading) {
		return (
			<Box sx={{display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '60vh'}}>
				<CircularProgress/>
			</Box>
		);
	}
 
	if (error !== undefined) {
		return (
			<Container maxWidth="md" sx={{mt: 4}}>
				<Alert severity="error">
					Failed to load notification preferences. Please refresh and try again.
				</Alert>
			</Container>
		);
	}
 
	// -------------------------------------------------------------------------
	// Group preferences by display group
	// -------------------------------------------------------------------------
 
	const grouped = new Map<string, NotificationPreference[]>();
	for (const pref of merged) {
		const display = TYPE_CATALOG[pref.notificationType];
		// Hide unknown types defensively — the backend may add a type ahead
		// of the frontend catalog being updated. Without this guard the
		// page would render a row with no label.
		if (display === undefined) continue;
 
		const list = grouped.get(display.group) ?? [];
		list.push(pref);
		grouped.set(display.group, list);
	}
 
	const hasAnyPreferences = grouped.size > 0;
 
	return (
		<Box sx={{backgroundColor: 'background.default', minHeight: '100vh', py: 4}}>
			<Container maxWidth="md">
				<Box sx={{mb: 4}}>
					<Typography variant="h4" fontWeight="bold" gutterBottom>
						Notification Settings
					</Typography>
					<Typography variant="body1" color="text.secondary">
						Choose which emails you'd like to receive. All notifications are off by default.
					</Typography>
				</Box>
 
				{!hasAnyPreferences && (
					<Paper sx={{p: 3}}>
						<Alert severity="info">
							No notification preferences are available for your account yet. Investor-facing
							notifications will appear here once they ship.
						</Alert>
					</Paper>
				)}
 
				{Array.from(grouped.entries()).map(([groupName, prefs], groupIndex) => (
					<Paper key={groupName} sx={{p: 3, mb: 3}}>
						<Typography variant="h6" fontWeight="bold" gutterBottom>
							{groupName}
						</Typography>
 
						{prefs.map((pref, i) => {
							const display = TYPE_CATALOG[pref.notificationType];
							Iif (display === undefined) return null;
 
							return (
								<Box key={`${pref.notificationType}|${pref.channel}`}>
									{i > 0 && <Divider sx={{my: 2}}/>}
									<Box
										sx={{
											display: 'flex',
											justifyContent: 'space-between',
											alignItems: 'center',
											gap: 2
										}}
									>
										<Box sx={{flex: 1}}>
											<Typography variant="body1" fontWeight="medium">
												{display.label}
											</Typography>
											<Typography variant="body2" color="text.secondary">
												{display.description}
											</Typography>
										</Box>
										<Switch
											checked={pref.enabled}
											onChange={handleToggle(pref)}
											inputProps={{'aria-label': display.label}}
											data-testid={`pref-switch-${pref.notificationType}`}
										/>
									</Box>
								</Box>
							);
						})}
 
						{groupIndex === grouped.size - 1 && (
							<Box sx={{display: 'flex', justifyContent: 'flex-end', mt: 3}}>
								<Button
									variant="contained"
									startIcon={isSaving ? <CircularProgress size={20}/> : <SaveIcon/>}
									onClick={handleSave}
									disabled={!isDirty || isSaving}
								>
									{isSaving ? 'Saving...' : 'Save Changes'}
								</Button>
							</Box>
						)}
					</Paper>
				))}
 
				<Snackbar
					open={snackbar.open}
					autoHideDuration={4000}
					onClose={handleCloseSnackbar}
					anchorOrigin={{vertical: 'bottom', horizontal: 'center'}}
				>
					<Alert
						onClose={handleCloseSnackbar}
						severity={snackbar.severity}
						sx={{width: '100%'}}
					>
						{snackbar.message}
					</Alert>
				</Snackbar>
			</Container>
		</Box>
	);
}