diff --git a/src/API/src/auth/auth.controller.ts b/src/API/src/auth/auth.controller.ts index 73903a435..d42711bf1 100644 --- a/src/API/src/auth/auth.controller.ts +++ b/src/API/src/auth/auth.controller.ts @@ -24,6 +24,7 @@ export class AuthController { sub: userId, scope: createScope(userEntity), aud: process.env.AUTH0_AUDIENCE, + disable_notification: userEntity.disable_notification || false, }; const token = jwt.create(claims, process.env.TOKEN_KEY); token.setExpiration(new Date().getTime() + 60000 * 1000); diff --git a/src/API/src/db/email-registry/email-registry.controller.ts b/src/API/src/db/email-registry/email-registry.controller.ts index 4b1da8149..723a45711 100644 --- a/src/API/src/db/email-registry/email-registry.controller.ts +++ b/src/API/src/db/email-registry/email-registry.controller.ts @@ -11,6 +11,7 @@ import { Query, Res, UseGuards, + BadRequestException, } from '@nestjs/common'; import { Response } from 'express'; @@ -22,11 +23,19 @@ import { SubscriptionResponseDto } from './dto/subscription-response.dto'; import { EmailRegistryService } from './email-registry.service'; import { GqlAuthGuard } from 'src/auth/gqlAuthGuard'; import { RolesGuard } from 'src/auth/user_role/roles.guard'; +import { Queue } from 'bullmq'; +import { InjectQueue } from '@nestjs/bullmq'; +import { Role } from 'src/auth/user_role/role.enum'; +import { Roles } from 'src/auth/user_role/roles.decorator'; @Controller() @UseInterceptors(ClassSerializerInterceptor) export class EmailRegistryController { - constructor(private readonly emailRegistryService: EmailRegistryService) {} + constructor( + private readonly emailRegistryService: EmailRegistryService, + @InjectQueue('subscription-queue') + private readonly subscriptionQueue: Queue, + ) {} @Post('subscribe') @HttpCode(HttpStatus.CREATED) @@ -35,7 +44,11 @@ export class EmailRegistryController { ): Promise { return this.emailRegistryService.subscribe(subscribeEmailDto); } - + @Get('subscribers') + @UseGuards(GqlAuthGuard, RolesGuard) + async getSubscribers() { + return this.emailRegistryService.findAll({}); + } @Get('verify') @HttpCode(HttpStatus.OK) async verify( @@ -43,6 +56,25 @@ export class EmailRegistryController { ): Promise { return this.emailRegistryService.verify(query); } + @Post('cleanup-job') + @UseGuards(GqlAuthGuard, RolesGuard) + @Roles(Role.Admin) + async startCleanupJob() { + const job = await this.subscriptionQueue.add( + 'clean-expired-subscribers', + { timestamp: new Date() }, + { + repeat: { + pattern: '0 0 * * 0', + }, + }, + ); + + return { + message: 'Weekly cleanup job added to the background queue successfully.', + jobId: job.id, + }; + } @Delete('unsubscribe') @HttpCode(HttpStatus.NO_CONTENT) @@ -51,6 +83,26 @@ export class EmailRegistryController { ): Promise { return this.emailRegistryService.unsubscribe(unsubscribeEmailDto); } + @Post('manual-add') + @UseGuards(GqlAuthGuard, RolesGuard) + async manualAdd( + @Body() body: { email: string; first_name?: string; last_name?: string }, + ) { + if (!body.email) { + throw new BadRequestException('Email is required'); + } + return this.emailRegistryService.createManual(body); + } + @Post('request-unsubscribe') + @HttpCode(HttpStatus.OK) + async requestUnsubscribe( + @Body('email') email: string, + ): Promise<{ message: string; type: string }> { + if (!email) { + throw new BadRequestException('Email is required'); + } + return this.emailRegistryService.requestUnsubscribe(email); + } @Get('export') @UseGuards(GqlAuthGuard, RolesGuard) diff --git a/src/API/src/db/email-registry/email-registry.module.ts b/src/API/src/db/email-registry/email-registry.module.ts index c613c3d6d..740f4b1f8 100644 --- a/src/API/src/db/email-registry/email-registry.module.ts +++ b/src/API/src/db/email-registry/email-registry.module.ts @@ -5,10 +5,23 @@ import { EmailRegistry } from './entities/email-registry.entity'; import { TypeOrmModule } from '@nestjs/typeorm/dist/typeorm.module'; import { EmailModule } from 'src/email/email.module'; import { EmailRegistryController } from './email-registry.controller'; +import { BullModule } from '@nestjs/bullmq'; +import { UserRole } from 'src/auth/user_role/user_role.entity'; +import { SubscriptionProcessor } from './email-registry.processor'; +import { AuthModule } from 'src/auth/auth.module'; @Module({ - imports: [TypeOrmModule.forFeature([EmailRegistry]), EmailModule], - providers: [EmailRegistryService, EmailRegistryResolver], + imports: [ + TypeOrmModule.forFeature([EmailRegistry, UserRole]), + EmailModule, + BullModule.registerQueue({ name: 'subscription-queue' }), + AuthModule, + ], + providers: [ + EmailRegistryService, + EmailRegistryResolver, + SubscriptionProcessor, + ], controllers: [EmailRegistryController], }) export class EmailRegistryModule {} diff --git a/src/API/src/db/email-registry/email-registry.processor.ts b/src/API/src/db/email-registry/email-registry.processor.ts new file mode 100644 index 000000000..95870d77e --- /dev/null +++ b/src/API/src/db/email-registry/email-registry.processor.ts @@ -0,0 +1,36 @@ +import { Processor, WorkerHost } from '@nestjs/bullmq'; +import { Job } from 'bullmq'; +import { Injectable, Logger } from '@nestjs/common'; +import { EmailRegistryService } from './email-registry.service'; + +@Processor('subscription-queue') +@Injectable() +export class SubscriptionProcessor extends WorkerHost { + private readonly logger = new Logger(SubscriptionProcessor.name); + + constructor(private readonly emailRegistryService: EmailRegistryService) { + super(); + } + + async process(job: Job): Promise { + // this.logger.log(`Starting background job ${job.id}:${job.name}`); + + if (job.name === 'clean-expired-subscribers') { + try { + // Progress logging in frontend + await job.updateProgress(10); + + const deletedCount = + await this.emailRegistryService.hardDeleteInactiveSubscribers(); + + await job.updateProgress(100); + //this.logger.log(`Job ${job.id} completed successfully. Deleted ${deletedCount}`); + + return { success: true, recordsDeleted: deletedCount }; + } catch (error) { + this.logger.error(`Job ${job.id} failed`, error); + throw error; + } + } + } +} diff --git a/src/API/src/db/email-registry/email-registry.service.ts b/src/API/src/db/email-registry/email-registry.service.ts index b395ba25d..78d25994a 100644 --- a/src/API/src/db/email-registry/email-registry.service.ts +++ b/src/API/src/db/email-registry/email-registry.service.ts @@ -14,6 +14,11 @@ import { UnsubscribeEmailDto } from './dto/unsubscribe-email.dto'; import { AccountStatus } from './entities/email-registry.entity'; import { ILike } from 'typeorm'; import * as ExcelJS from 'exceljs'; +import { UserRole } from 'src/auth/user_role/user_role.entity'; +import { Queue } from 'bullmq'; +import { OnApplicationBootstrap } from '@nestjs/common'; +import { InjectQueue } from '@nestjs/bullmq'; +import { AuthService } from 'src/auth/auth.service'; /** * Evaluates token windows against a strict 48-hour Time-To-Live validation boundary. @@ -26,12 +31,32 @@ export class EmailRegistryService { @InjectRepository(EmailRegistry) private readonly emailRegistryRepository: Repository, private readonly emailService: EmailService, + @InjectRepository(UserRole) + private readonly userRoleRepository: Repository, + @InjectQueue('subscription-queue') + private readonly subscriptionQueue: Queue, + private readonly authService: AuthService, ) {} - + async hardDeleteInactiveSubscribers(): Promise { + const result = await this.emailRegistryRepository + .createQueryBuilder() + .delete() + .from(EmailRegistry) + .where('account_status = :unsubscribed', { + unsubscribed: AccountStatus.UNSUBSCRIBED, + }) + .orWhere('(account_status = :pending AND token_expires_at < :now)', { + pending: AccountStatus.PENDING_VERIFICATION, + now: new Date(), + }) + .execute(); + + return result.affected || 0; + } async subscribe(payload: SubscribeEmailDto): Promise { const email = payload.email.trim().toLowerCase(); const verificationToken = uuidv4(); - const unsubscriptionToken = uuidv4(); // Generate early so it is immediately ready + const unsubscriptionToken = uuidv4(); const codeExpiresAt = new Date(Date.now() + VERIFICATION_CODE_TTL_MS); let entry = await this.emailRegistryRepository.findOne({ @@ -82,6 +107,7 @@ export class EmailRegistryService { await this.emailService.sendEmail( [savedEntry.email], [], + 'Verify your email subscription', `

Thanks for subscribing to updates, ${savedEntry.first_name}.

@@ -101,6 +127,7 @@ export class EmailRegistryService { async verify(query: VerifyTokenDto): Promise { const trimmedToken = query.token?.trim(); + console.log(`Backend received token for verification: [${trimmedToken}]`); if (!trimmedToken) { throw new BadRequestException( 'Verification token parameter is missing from request.', @@ -142,6 +169,18 @@ export class EmailRegistryService { // NOTE: Keep the token or invalidate cleanly without breaking single-click checks return await this.emailRegistryRepository.save(entry); } + async deleteExpiredPendingAccounts(): Promise { + const result = await this.emailRegistryRepository + .createQueryBuilder() + .delete() + .from(EmailRegistry) + .where('account_status =: status', { + status: AccountStatus.PENDING_VERIFICATION, + }) + .andWhere('token_expires_at <: now', { now: new Date() }) + .execute(); + return result.affected || 0; + } async unsubscribe(payload: UnsubscribeEmailDto): Promise { const targetId = payload.id?.trim(); @@ -171,6 +210,19 @@ export class EmailRegistryService { await this.emailRegistryRepository.save(entry); } + async toggleNotificationsByEmail( + email: string, + enabled: boolean, + ): Promise { + const record = await this.emailRegistryRepository.findOne({ + where: { email: email.toLowerCase() }, + }); + if (record) { + record.notifications_enabled = enabled; + await this.emailRegistryRepository.save(record); + } + } + private async *streamVerified() { const chunkSize = 500; let lastId: string | null = null; @@ -420,7 +472,97 @@ export class EmailRegistryService { `; } + async createManualSubscrption(input: { + email: string; + first_name?: string; + last_name?: string; + }): Promise { + const email = input.email.trim().toLowerCase(); + + let entry = await this.emailRegistryRepository.findOne({ + where: { email }, + }); + if (entry) { + throw new BadRequestException('This email is already in the registry.'); + } + + entry = this.emailRegistryRepository.create({ + id: uuidv4(), + first_name: input.first_name || '', + last_name: input.last_name || '', + email: email, + notifications_enabled: true, + account_status: AccountStatus.VERIFIED, // Admin skips pending state + verification_token: uuidv4(), + token_expires_at: new Date(Date.now() + VERIFICATION_CODE_TTL_MS), + unsubscription_token: uuidv4(), + }); + + return await this.emailRegistryRepository.save(entry); + } + async requestUnsubscribe( + email: string, + ): Promise<{ message: string; type: string }> { + const normalizedEmail = email.trim().toLowerCase(); + + const entry = await this.emailRegistryRepository.findOne({ + where: { email: normalizedEmail }, + }); + + if (!entry || entry.account_status === AccountStatus.UNSUBSCRIBED) { + // 1. Initialize Auth0 client (required based on your AuthController pattern) + await this.authService.init(); + + // 2. Fetch all Auth0 users and find the match + const allUsers = await this.authService.getAllUsers(); + const appUser = allUsers?.find((u) => u.email === normalizedEmail); + + // 3. If found, turn off their notifications in UserRole + if (appUser && appUser.user_id) { + const userRole = await this.userRoleRepository.findOne({ + where: { auth0_id: appUser.user_id }, + }); + + if (userRole) { + userRole.disable_notification = true; + await this.userRoleRepository.save(userRole); + } + } + + return { + message: 'Account notifications disabled.', + type: 'direct_disable', + }; + } + + // 2. Existing Email Registry Logic + const frontendBaseUrl = + process.env.FRONTEND_BASE_URL?.trim() || 'http://localhost:3000'; + const unsubscribeLink = new URL('/unsubscribed-success', frontendBaseUrl); + + unsubscribeLink.searchParams.set('id', entry.id); + unsubscribeLink.searchParams.set('token', entry.unsubscription_token); + + await this.emailService.sendEmail( + [entry.email], + [], + 'Vector Atlas - Unsubscribe Request', + ` +

Hello ${entry.first_name || ''},

+

We received a request to unsubscribe you from Vector Atlas updates.

+

If you made this request, please click the link below to confirm:

+

Confirm Unsubscription

+
+

If you did not request this, please ignore this email.

+ `, + ); + + return { + message: 'Unsubscribe link sent.', + type: 'email_sent', + }; + } async queueDatasetCampaign( title: string, message: string, diff --git a/src/API/src/email/email.controller.ts b/src/API/src/email/email.controller.ts index dd1a968ba..7dce347e6 100644 --- a/src/API/src/email/email.controller.ts +++ b/src/API/src/email/email.controller.ts @@ -10,7 +10,6 @@ import { AttachmentLikeObject } from '@nestjs-modules/mailer/dist/interfaces/sen import { join } from 'path'; import { existsSync, mkdirSync, writeFileSync } from 'fs'; import { FilesInterceptor } from '@nestjs/platform-express'; -const stripHtml = (html: string): string => html.replace(/<\/?[^>]+(>|$)/g, ''); @Controller('mailService') export class EmailController { @@ -19,30 +18,48 @@ export class EmailController { @Post('sendNewEmail') @UseInterceptors(FilesInterceptor('files')) async sendNewEmail( - @Body('emails') emails: string[], - @Body('copyEmails') copyEmails: string[], - @Body('title') title: string, - @Body('emailBody') emailBody: string, - @UploadedFiles() files: Express.Multer.File[], // Handles file upload + @Body('recipients') recipients?: string | string[], + @Body('emails') emails?: string | string[], + @Body('subject') subject?: string, + @Body('title') title?: string, + @Body('copyEmails') copyEmails?: string | string[], + @Body('message') message?: string, + @Body('emailBody') emailBody?: string, + @UploadedFiles() files?: Express.Multer.File[], ) { try { const tempDir = join(__dirname, '..', 'temp'); if (!existsSync(tempDir)) { mkdirSync(tempDir, { recursive: true }); } - const attachedFiles: AttachmentLikeObject[] = files.map((file) => { + const rawRecipients = recipients || emails || []; + const finalRecipients = Array.isArray(rawRecipients) + ? rawRecipients + : [rawRecipients]; + + const rawCopy = copyEmails || []; + const finalCopyEmails = Array.isArray(rawCopy) ? rawCopy : [rawCopy]; + + const finalTitle = subject || title || 'No Subject'; + + const finalBody = message || emailBody || ''; + + const safeFiles = files || []; + const attachedFiles: AttachmentLikeObject[] = safeFiles.map((file) => { const tempFilePath = join(tempDir, file.originalname); writeFileSync(tempFilePath, file.buffer); return { path: tempFilePath }; }); + const result = await this.emailService.sendEmail( - emails, - copyEmails, - title, - emailBody, + finalRecipients, + finalCopyEmails, + finalTitle, + finalBody, attachedFiles, null, ); + return { success: result }; } catch (error) { return { success: false, message: error.message }; diff --git a/src/UI/api/api.ts b/src/UI/api/api.ts index 2b681e2da..f7b6b8679 100644 --- a/src/UI/api/api.ts +++ b/src/UI/api/api.ts @@ -15,6 +15,7 @@ import { debug, error } from 'console'; import { getUniqueObjectValues } from '../utils/utils'; import FormData from 'form-data'; import pako from 'pako'; +import { blob } from 'stream/consumers'; export const createBackgroundExport = async (payload: { filtersJson: string; @@ -214,6 +215,14 @@ export const approveUploadedDatasetAuthenticated = async ( ); return res; }; +export const exportSubscriber = async (token: string) => { + const config = { + headers: { Authorization: `Bearer ${token}` }, + responseType: 'blob' as const, + }; + const res = await axios.get(`${apiUrl}export`, config); + return download(res.data, 'email-registry.xlsx'); +}; /** * Function to initiate approval of datasets. If there are no issues found, the import process @@ -431,6 +440,13 @@ export const rejectUploadedDatasetAuthenticated = async ( ); return res; }; +export const cleanUpSubscription = async (token: string) => { + const config = { + headers: { Authorization: `Bearer ${token}` }, + }; + const res = await axios.post(`${apiUrl}subscribers/cleanup-job`, {}, config); + return res.data; +}; export const reviewUploadedDatasetAuthenticated = async ( token: String, @@ -1412,8 +1428,11 @@ export const fetchManyUsersDetails = async ( return res.data; }; -export const fetchAllUsers = async () => { - const res = await axios.get(`${apiUrl}auth/users`); +export const fetchAllUsers = async (token: String) => { + const config = { + headers: { Authorization: `Bearer ${token}` }, + }; + const res = await axios.get(`${apiUrl}auth/users`, config); return res.data; }; @@ -1469,3 +1488,142 @@ export const uploadSpeciesImageAuthenticated = async ( return res.data; }; + +export enum AccountStatus { + PENDING_VERIFICATION = 'pending_verification', + VERIFIED = 'verified', + DEACTIVATED = 'deactivated', + UNSUBSCRIBED = 'unsubscribed', +} + +export interface UnifiedRecipient { + id: string; + name: string; + email: string; + source: 'user' | 'subscriber'; + isDisabled: boolean; + statusLabel: string; + roles?: string[]; +} + +export const buildUnifiedRecipients = ( + platformUsers: any[], + subscribers: any[] +): UnifiedRecipient[] => { + const map = new Map(); + + for (const user of platformUsers || []) { + if (!user.email) continue; + + const roles: string[] = []; + if (user.is_admin) roles.push('Admin'); + if (user.is_uploader) roles.push('Uploader'); + if (user.is_reviewer) roles.push('Reviewer'); + if (user.is_editor) roles.push('Editor'); + if (user.is_reviewer_manager) roles.push('Reviewer Manager'); + if (user.is_model_manager) roles.push('Model Manager'); + + const isDisabled = Boolean(user.disable_notification); + + map.set(user.email.toLowerCase(), { + id: user.auth0_id || user.user_id || user.email, + name: user.name || user.nickname || user.email, + email: user.email, + source: 'user', + isDisabled, + statusLabel: isDisabled + ? 'Notifications Off' + : roles.length > 0 + ? `User (${roles.join(', ')})` + : 'User', + roles, + }); + } + + for (const sub of subscribers || []) { + if (!sub.email) continue; + const emailKey = sub.email.toLowerCase(); + + const isUnsubscribed = sub.account_status === AccountStatus.UNSUBSCRIBED; + const isDeactivated = sub.account_status === AccountStatus.DEACTIVATED; + const isPending = sub.account_status === AccountStatus.PENDING_VERIFICATION; + const isNotifOff = !sub.notifications_enabled; + + const isDisabled = + isUnsubscribed || isDeactivated || isPending || isNotifOff; + + let statusLabel = 'Subscriber'; + if (isUnsubscribed) statusLabel = 'Unsubscribed'; + else if (isDeactivated) statusLabel = 'Deactivated'; + else if (isPending) statusLabel = 'Pending Verification'; + else if (isNotifOff) statusLabel = 'Notifications Off'; + + if (map.has(emailKey)) { + const existing = map.get(emailKey)!; + const combinedDisabled = existing.isDisabled || isDisabled; + map.set(emailKey, { + ...existing, + isDisabled: combinedDisabled, + statusLabel: combinedDisabled + ? isDisabled + ? statusLabel + : existing.statusLabel + : `${existing.statusLabel} & Subscriber`, + }); + } else { + map.set(emailKey, { + id: sub.id, + name: + `${sub.first_name || ''} ${sub.last_name || ''}`.trim() || sub.email, + email: sub.email, + source: 'subscriber', + isDisabled, + statusLabel, + }); + } + } + + return Array.from(map.values()); +}; + +export const fetchUnifiedRecipients = async ( + token: String +): Promise => { + let platformUsers: any[] = []; + let subscribers: any[] = []; + + try { + const usersData = await fetchAllUsers(token); + platformUsers = Array.isArray(usersData) + ? usersData + : usersData?.users || []; + } catch (err) { + console.error('Failed to fetch platform users:', err); + } + + try { + const query = ` + query { + adminEmailRegistry { + data { + id + first_name + last_name + email + account_status + notifications_enabled + } + } + } + `; + const gqlRes = await fetchGraphQlDataAuthenticated(query, token); + + if (gqlRes?.data?.adminEmailRegistry?.data) { + subscribers = gqlRes.data.adminEmailRegistry.data; + } + } catch (err) { + console.error('Failed to fetch email subscribers:', err); + } + + return buildUnifiedRecipients(platformUsers, subscribers); +}; diff --git a/src/UI/api/queries.ts b/src/UI/api/queries.ts index fceafaa3f..72825aa1d 100644 --- a/src/UI/api/queries.ts +++ b/src/UI/api/queries.ts @@ -412,13 +412,11 @@ export const roleRequestMutation = ( export const disableNotificationsMutation = ( userId: string, disable: boolean -) => { - return ` +) => ` mutation { disableNotifications(userId: "${userId}", disable: ${disable}) } - `; -}; +`; export const triggerModelTransform = ( displayName: String, diff --git a/src/UI/components/communicationLog/communicationLogDetails.tsx b/src/UI/components/communicationLog/communicationLogDetails.tsx index e58682fab..9693792f2 100644 --- a/src/UI/components/communicationLog/communicationLogDetails.tsx +++ b/src/UI/components/communicationLog/communicationLogDetails.tsx @@ -103,7 +103,7 @@ const CommunicationLogDetails = () => { const loading = useAppSelector((state) => state.communicationLog.loading); const isAdmin = useAppSelector((state) => state.auth.roles.includes('admin')); const router = useRouter(); - const id = router.query.id as string | undefined; + const id = router.query.id as string; const [expanded, setExpanded] = useState(false); const [comments, setComments] = useState(''); const [actionDialogOpen, setActionDialogOpen] = useState(false); diff --git a/src/UI/components/communicationLog/communicationLogList.tsx b/src/UI/components/communicationLog/communicationLogList.tsx index c3ec05a84..d61ce6630 100644 --- a/src/UI/components/communicationLog/communicationLogList.tsx +++ b/src/UI/components/communicationLog/communicationLogList.tsx @@ -27,6 +27,7 @@ import { import { StatusRenderer } from '../shared/statusRenderer'; import DateRenderer from '../shared/dateRenderer'; import { useTranslations } from 'next-intl'; +import { ComposeMessageForm } from '../email/composeForm'; interface IDoiRequest { id: string; @@ -40,34 +41,25 @@ interface IDoiRequest { const APPROVE: string = 'Approve'; const REJECT: string = 'Reject'; -function AddToolbar() { +function CustomToolbar() { return ( - {/* +
+ +
*/} + Compose +
); } -function FilterToolbar() { - return ( -
- -
- ); -} - export const CommunicationLogList = () => { const t = useTranslations('CommunicationListPage'); @@ -81,32 +73,28 @@ export const CommunicationLogList = () => { // const columns: GridColDef[] = [ const columns: GridColDef[] = [ - //const columns = [ { field: 'subject', headerName: t('grid.subject'), width: 330, editable: false, - renderCell: (params: GridRenderCellParams) => ( + valueGetter: (params: any) => params.row.subject || '', + renderCell: (params: GridRenderCellParams) => ( { + component="button" + variant="body2" + onClick={(e) => { + e.preventDefault(); router.push({ pathname: '/communication-log/details', - query: { id: params.value }, + query: { id: params.row.id }, }); }} + style={{ cursor: 'pointer', textAlign: 'left' }} > - {params.value} + {params.row.subject} ), - valueGetter: (params: GridValueGetterParams) => { - return ( - - {params.row.subject} - - ); - }, }, { field: 'message_type', @@ -130,7 +118,7 @@ export const CommunicationLogList = () => { type: 'string', width: 150, editable: false, - renderCell: (params: GridRenderCellParams) => ( + renderCell: (params: GridRenderCellParams) => ( ), }, @@ -187,7 +175,7 @@ export const CommunicationLogList = () => { } }} slots={{ - toolbar: FilterToolbar, // AddToolbar, + toolbar: CustomToolbar, }} /> diff --git a/src/UI/components/dataset/uploadedDatasetList.tsx b/src/UI/components/dataset/uploadedDatasetList.tsx index c71fab312..3921170d0 100644 --- a/src/UI/components/dataset/uploadedDatasetList.tsx +++ b/src/UI/components/dataset/uploadedDatasetList.tsx @@ -227,7 +227,7 @@ export const UploadedDatasetList = () => { }; const loadUsers = async () => { - const res: any[] = await fetchAllUsers(); + const res: any[] = await fetchAllUsers(token); setUsers(res); }; diff --git a/src/UI/components/email/composeForm.tsx b/src/UI/components/email/composeForm.tsx new file mode 100644 index 000000000..eb5f6fb8a --- /dev/null +++ b/src/UI/components/email/composeForm.tsx @@ -0,0 +1,334 @@ +import React, { useState, useMemo } from 'react'; +import { + Autocomplete, + Box, + Button, + Card, + CardContent, + Checkbox, + Chip, + CircularProgress, + FormControl, + InputLabel, + MenuItem, + Select, + Stack, + TextField, + Typography, +} from '@mui/material'; +import CheckBoxOutlineBlankIcon from '@mui/icons-material/CheckBoxOutlineBlank'; +import CheckBoxIcon from '@mui/icons-material/CheckBox'; +import SendIcon from '@mui/icons-material/Send'; +import { TextEditor } from '../shared/textEditor/RichTextEditor'; +import { useUser } from '@auth0/nextjs-auth0/client'; + +export interface UnifiedRecipient { + id: string; + name: string; + email: string; + source: 'user' | 'subscriber'; + isDisabled: boolean; + statusLabel: string; + roles?: string[]; +} + +interface ComposeMessageFormProps { + loading?: boolean; + recipientsList?: UnifiedRecipient[]; + onSend?: (data: { + subject: string; + recipients: string[]; + message: string; + }) => void; + files?: File[]; +} + +const icon = ; +const checkedIcon = ; + +export const ComposeMessageForm: React.FC = ({ + loading = false, + recipientsList = [], + onSend, +}) => { + const { user } = useUser(); + const [subject, setSubject] = useState(''); + const [audienceMode, setAudienceMode] = useState< + 'all' | 'subscribers' | 'users' | 'custom' + >('custom'); + const [selectedRecipients, setSelectedRecipients] = useState< + UnifiedRecipient[] + >([]); + const [files, setFiles] = useState([]); + const senderName = user?.name || user?.nickname || 'Vector Altlas Team'; + const senderEmail = user?.email || ''; + const [message, setMessage] = useState(''); + const [touched, setTouched] = useState({ + subject: false, + recipients: false, + message: false, + }); + + const activeRecipientEmails = useMemo(() => { + const eligible = recipientsList.filter((r) => !r.isDisabled); + + if (audienceMode === 'all') { + return eligible.map((r) => r.email); + } + if (audienceMode === 'subscribers') { + return eligible + .filter((r) => r.source === 'subscriber') + .map((r) => r.email); + } + if (audienceMode === 'users') { + return eligible.filter((r) => r.source === 'user').map((r) => r.email); + } + return selectedRecipients.filter((r) => !r.isDisabled).map((r) => r.email); + }, [audienceMode, recipientsList, selectedRecipients]); + + const subjectError = touched.subject && !subject.trim(); + const recipientsError = + touched.recipients && activeRecipientEmails.length === 0; + const messageError = touched.message && !message.trim(); + + const isFormValid = + subject.trim() !== '' && + activeRecipientEmails.length > 0 && + message.trim() !== ''; + + const handleSubmit = (e: React.FormEvent) => { + e.preventDefault(); + setTouched({ subject: true, recipients: true, message: true }); + + if (!isFormValid || loading) return; + + if (onSend) { + onSend({ + subject, + recipients: Array.from(new Set(activeRecipientEmails)), + message, + }); + } + }; + + return ( + + {loading && ( + + + + )} + + + + Compose Message + + + + + + Recipient Group + + + + {audienceMode === 'custom' ? ( + option.isDisabled} + getOptionLabel={(option) => + option.name === option.email + ? option.email + : `${option.name} (${option.email})` + } + onChange={(_, newValue) => { + setSelectedRecipients(newValue); + setTouched((prev) => ({ ...prev, recipients: true })); + }} + onBlur={() => + setTouched((prev) => ({ ...prev, recipients: true })) + } + renderOption={(props, option, { selected }) => ( +
  • + + + + {option.name === option.email + ? option.email + : `${option.name} (${option.email})`} + + + +
  • + )} + renderInput={(params) => ( + + )} + /> + ) : ( + + )} + + setSubject(e.target.value)} + onBlur={() => setTouched((prev) => ({ ...prev, subject: true }))} + error={subjectError} + helperText={subjectError ? 'Subject cannot be empty' : ''} + /> + + + { + setMessage(val); + if (!touched.message) { + setTouched((prev) => ({ ...prev, message: true })); + } + }} + error={messageError} + helperText={messageError ? 'Message cannot be empty' : ''} + /> + + {/* + + {files.length > 0 && ( + + {files.map((file, idx) => ( + setFiles(files.filter((_, i) => i !== idx))} + /> + ))} + + )} + */} + + + + +
    +
    +
    +
    + ); +}; diff --git a/src/UI/components/model/uploadedModelList.tsx b/src/UI/components/model/uploadedModelList.tsx index 216bd79b7..973720a4f 100644 --- a/src/UI/components/model/uploadedModelList.tsx +++ b/src/UI/components/model/uploadedModelList.tsx @@ -163,7 +163,7 @@ export const UploadedModelList = () => { }; const loadUsers = async () => { - const res: any[] = await fetchAllUsers(); + const res: any[] = await fetchAllUsers(token); setUsers(res); }; diff --git a/src/UI/components/settings/UserSettingForm.tsx b/src/UI/components/settings/UserSettingForm.tsx index 177dd6dfc..8f88a80bc 100644 --- a/src/UI/components/settings/UserSettingForm.tsx +++ b/src/UI/components/settings/UserSettingForm.tsx @@ -6,7 +6,7 @@ import { FormControlLabel, Typography, } from '@mui/material'; -import React, { useState } from 'react'; +import React, { useState, useEffect } from 'react'; import { useUser } from '@auth0/nextjs-auth0/client'; import { useAppDispatch, useAppSelector } from '../../state/hooks'; import LockOpenIcon from '@mui/icons-material/LockOpen'; @@ -30,6 +30,9 @@ function UserSettingForm() { const isLoadingRequest = useAppSelector( (state) => state.auth.roleRequestLoading ); + const backendDisableNotifications = useAppSelector( + (state) => state.auth.disableNotification + ); const dispatch = useAppDispatch(); const roleList = [ @@ -43,7 +46,16 @@ function UserSettingForm() { const [roleRequestOpen, toggleRoleRequestOpen] = useState(false); const [rolesRequested, setRolesRequested] = useState([]); const [requestReason, setRequestReason] = useState(''); - const [disableNotification, setDisableNotification] = useState(); + + const [disableNotification, setDisableNotification] = + useState(false); + + useEffect(() => { + if (backendDisableNotifications !== undefined) { + setDisableNotification(backendDisableNotifications); + } + }, [backendDisableNotifications]); + const handleRoleCheck = (role: string) => { if (rolesRequested.length !== 0 && rolesRequested.includes(role)) { setRolesRequested(rolesRequested.filter((x) => x !== role)); @@ -54,18 +66,27 @@ function UserSettingForm() { }; const handleDisableNotification = async () => { - const disable = !disableNotification; - setDisableNotification(disable); - const userId = user!.sub || ''; - const success = await dispatch(disableNotifications({ userId, disable })); + const newDisableState = !disableNotification; + + setDisableNotification(newDisableState); + + const userId = user?.sub || ''; + const email = user?.email || ''; + + const success = await dispatch( + disableNotifications({ userId, disable: newDisableState }) + ); + if (success) { setRolesRequested([]); setRequestReason(''); + } else { + setDisableNotification(!newDisableState); } }; const requestRolesSubmit = async () => { - const email = user!.email || 'Empty'; + const email = user?.email || 'Empty'; const success = await dispatch( requestRoles({ requestReason, rolesRequested, email }) ); @@ -102,7 +123,7 @@ function UserSettingForm() { id="outlined-basic" label={t('name')} variant="outlined" - value={user?.name} + value={user?.name || ''} fullWidth={true} /> @@ -112,7 +133,7 @@ function UserSettingForm() { id="outlined-basic" label={t('email')} variant="outlined" - value={user?.email} + value={user?.email || ''} fullWidth={true} /> @@ -122,8 +143,8 @@ function UserSettingForm() { handleDisableNotification()} + checked={disableNotification} + onChange={handleDisableNotification} /> } label={t('disableNotifications')} diff --git a/src/UI/components/subscription/manage_subsriptions.tsx b/src/UI/components/subscription/manage_subsriptions.tsx new file mode 100644 index 000000000..030540829 --- /dev/null +++ b/src/UI/components/subscription/manage_subsriptions.tsx @@ -0,0 +1,317 @@ +import React, { useState, useEffect } from 'react'; +import { + Typography, + Box, + Chip, + IconButton, + Button, + Dialog, + DialogTitle, + DialogContent, + DialogActions, + TextField, + CircularProgress, +} from '@mui/material'; +import DeleteIcon from '@mui/icons-material/Delete'; +import AddIcon from '@mui/icons-material/Add'; +import { DataGrid, GridColDef, GridRenderCellParams } from '@mui/x-data-grid'; +import axios from 'axios'; +import { useTranslations } from 'next-intl'; +import { useAppSelector } from '../../state/hooks'; +import { apiUrl, AccountStatus } from '../../api/api'; +import DateRenderer from '../shared/dateRenderer'; +import { exportSubscriber } from '../../api/api'; +import finalPropsSelectorFactory from 'react-redux/es/connect/selectorFactory'; +import { string } from 'yup'; + +interface Subscriber { + id: string; + first_name: string; + last_name: string; + email: string; + account_status: AccountStatus; + notifications_enabled: boolean; + verification_token: string; + token_expires_at: Date; + unsubscription_token: string; +} + +export const SubscriptionList = () => { + const t = useTranslations('AdminPage'); + const [subscribers, setSubscribers] = useState([]); + const [loading, setLoading] = useState(false); + const token = useAppSelector((state) => state.auth.token); + const [exporting, setExporting] = useState(false); + + const handleExport = async () => { + if (!token) return; + setExporting(true); + try { + await exportSubscriber(token.toString()); + } catch (error) { + console.error('Failed to export subscribers', error); + alert('Failed to Download excel file. Please try again'); + } finally { + setExporting(false); + } + }; + + // Modal State + const [openModal, setOpenModal] = useState(false); + const [submitting, setSubmitting] = useState(false); + const [newSub, setNewSub] = useState({ + first_name: '', + last_name: '', + email: '', + }); + const [modalError, setModalError] = useState(''); + + const fetchSubscribers = async () => { + if (!token) return; + setLoading(true); + try { + const config = { headers: { Authorization: `Bearer ${token}` } }; + const response = await axios.get(`${apiUrl}subscribers`, config); + const data = response.data?.data || response.data || []; + setSubscribers(data); + } catch (error) { + console.error('Failed to fetch subscribers:', error); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + fetchSubscribers(); + }, [token]); + + const handleUnsubscribe = async (subscriberRow: Subscriber) => { + if ( + !window.confirm( + `Are you sure you want to unsubscribe ${subscriberRow.email}?` + ) + ) { + return; + } + + try { + const config = { + headers: { Authorization: `Bearer ${token}` }, + data: { + id: subscriberRow.id, + token: subscriberRow.unsubscription_token, + }, + }; + + await axios.delete(`${apiUrl}unsubscribe`, config); + fetchSubscribers(); + } catch (error) { + console.error('Failed to unsubscribe user:', error); + alert('Failed to process unsubscription.'); + } + }; + + const handleAddSubscriber = async () => { + if (!newSub.email.trim()) { + setModalError('Email is required'); + return; + } + + setSubmitting(true); + setModalError(''); + try { + const config = { headers: { Authorization: `Bearer ${token}` } }; + await axios.post(`${apiUrl}manual-add`, newSub, config); + + // Reset and close + setNewSub({ first_name: '', last_name: '', email: '' }); + setOpenModal(false); + fetchSubscribers(); // Refresh the grid + } catch (error: any) { + setModalError( + error.response?.data?.message || 'Failed to add subscriber' + ); + } finally { + setSubmitting(false); + } + }; + + const columns: GridColDef[] = [ + { + field: 'name', + headerName: 'Name', + width: 200, + valueGetter: (params: any) => + `${params.row.first_name || ''} ${params.row.last_name || ''}`.trim() || + 'N/A', + }, + { field: 'email', headerName: 'Email Address', width: 250 }, + { + field: 'account_status', + headerName: 'Status', + width: 180, + renderCell: (params: GridRenderCellParams) => { + let color: 'default' | 'success' | 'error' | 'warning' = 'default'; + const status = params.value; + + if (status === AccountStatus.VERIFIED) color = 'success'; + else if (status === AccountStatus.UNSUBSCRIBED) color = 'error'; + else if (status === AccountStatus.PENDING_VERIFICATION) + color = 'warning'; + else if (status === AccountStatus.DEACTIVATED) color = 'default'; + + return ( + + ); + }, + }, + { + field: 'notifications_enabled', + headerName: 'Notifications', + width: 150, + type: 'boolean', + }, + { + field: 'token_expires_at', + headerName: 'Token Expiry', + type: 'dateTime', + width: 180, + valueGetter: (params: any) => + params.row.token_expires_at + ? new Date(params.row.token_expires_at) + : null, + renderCell: ({ row }: { row: any }) => + row.token_expires_at ? ( + + ) : ( + - + ), + }, + { + field: 'actions', + headerName: 'Actions', + width: 100, + sortable: false, + filterable: false, + renderCell: (params: GridRenderCellParams) => { + const isUnsubscribed = + params.row.account_status === AccountStatus.UNSUBSCRIBED; + return ( + handleUnsubscribe(params.row as Subscriber)} + title={isUnsubscribed ? 'Already unsubscribed' : 'Unsubscribe user'} + > + + + ); + }, + }, + ]; + + return ( + + + + Subscriber List + + + + + + + + + {/* Manual Add Dialog */} + !submitting && setOpenModal(false)} + maxWidth="xs" + fullWidth + > + Add New Subscriber + + + setNewSub({ ...newSub, first_name: e.target.value }) + } + disabled={submitting} + /> + + setNewSub({ ...newSub, last_name: e.target.value }) + } + disabled={submitting} + /> + setNewSub({ ...newSub, email: e.target.value })} + disabled={submitting} + error={!!modalError} + helperText={modalError} + /> + + + + + + + + ); +}; diff --git a/src/UI/pages/admin.tsx b/src/UI/pages/admin.tsx index 1c2f607f9..e758689bb 100644 --- a/src/UI/pages/admin.tsx +++ b/src/UI/pages/admin.tsx @@ -8,6 +8,7 @@ import { getMessages } from '../utils/localization'; export default function SourcesPage(): JSX.Element { const t = useTranslations('AdminPage'); + return (
    @@ -26,19 +27,29 @@ export default function SourcesPage(): JSX.Element { {t('title')} - - - + + {/* Button Group Container */} + + + + + + + + + diff --git a/src/UI/pages/api/auth/verifyToken.ts b/src/UI/pages/api/auth/verifyToken.ts index 4abd7746f..ed4330656 100644 --- a/src/UI/pages/api/auth/verifyToken.ts +++ b/src/UI/pages/api/auth/verifyToken.ts @@ -35,6 +35,7 @@ export default async function handler( token: token, // Safely split the scope field into an array of roles roles: verifiedToken?.body.scope?.split(',') || [], + disable_notification: verifiedToken?.body.disable_notification || false, }; res.status(200).json(userInfo); diff --git a/src/UI/pages/communication-log/compose.tsx b/src/UI/pages/communication-log/compose.tsx new file mode 100644 index 000000000..37a96b566 --- /dev/null +++ b/src/UI/pages/communication-log/compose.tsx @@ -0,0 +1,98 @@ +import React, { useEffect, useState } from 'react'; +import { GetServerSidePropsContext } from 'next'; +import { useRouter } from 'next/router'; +import { toast } from 'react-toastify'; +import { marked } from 'marked'; +import { ComposeMessageForm } from '../../components/email/composeForm'; +import AuthWrapper from '../../components/shared/AuthWrapper'; +import SectionPanel from '../../components/layout/sectionPanel'; +import { + buildUnifiedRecipients, + sendNewEmail, + UnifiedRecipient, + apiUrl, +} from '../../api/api'; +import axios from 'axios'; +import { useAppSelector, useAppDispatch } from '../../state/hooks'; +import { getMessages } from '../../utils/localization'; +import { getUserRoles } from '../../state/admin/actions/admin.actions'; + +const ComposePage = () => { + const router = useRouter(); + const dispatch = useAppDispatch(); + const token = useAppSelector((state) => state.auth.token); + + const platformUsers = useAppSelector((state) => state.admin.users); + + const [recipientsList, setRecipientsList] = useState([]); + const [loading, setLoading] = useState(false); + + useEffect(() => { + if (token) { + dispatch(getUserRoles()); + } + }, [dispatch, token]); + + useEffect(() => { + const loadRecipients = async () => { + if (!token || typeof token !== 'string' || token.trim() === '') { + return; + } + + setLoading(true); + try { + const config = { headers: { Authorization: `Bearer ${token}` } }; + const restRes = await axios.get(`${apiUrl}subscribers`, config); + const subscribers = restRes.data?.data || restRes.data || []; + + const mergedList = buildUnifiedRecipients(platformUsers, subscribers); + setRecipientsList(mergedList); + } catch (err) { + console.error('Failed to load recipients:', err); + } finally { + setLoading(false); + } + }; + + loadRecipients(); + }, [token, platformUsers]); + + const handleSend = async (data: { + subject: string; + recipients: string[]; + message: string; + }) => { + setLoading(true); + try { + const htmlBody = await marked(data.message); + await sendNewEmail({ + subject: data.subject, + recipients: data.recipients, + message: htmlBody, + }); + toast.success('Message sent successfully!'); + router.push('/communication-log'); + } catch (error) { + console.error('Error sending email:', error); + toast.error('Failed to send message.'); + } finally { + setLoading(false); + } + }; + + return ( + + + + ); +}; + +export async function getServerSideProps(context: GetServerSidePropsContext) { + return await getMessages(context); +} + +export default ComposePage; diff --git a/src/UI/pages/subscribe/index.tsx b/src/UI/pages/subscribe/index.tsx index a8b310bd1..784e47221 100644 --- a/src/UI/pages/subscribe/index.tsx +++ b/src/UI/pages/subscribe/index.tsx @@ -4,8 +4,6 @@ import { Typography, TextField, Button, - FormControlLabel, - Checkbox, Paper, Alert, Box, @@ -14,6 +12,7 @@ import { import { useTranslations } from 'next-intl'; import { getMessages } from '../../utils/localization'; import { GetServerSidePropsContext } from 'next'; +import Link from 'next/link'; const SubscribePage = (): JSX.Element => { const t = useTranslations('EmailSubscription'); @@ -26,25 +25,34 @@ const SubscribePage = (): JSX.Element => { }); const [status, setStatus] = useState< - 'idle' | 'loading' | 'success' | 'error' + | 'idle' + | 'subscribing' + | 'unsubscribing' + | 'subscribe_success' + | 'unsubscribe_success' + | 'unsubscribe_direct' + | 'error' >('idle'); const [errorMsg, setErrorMsg] = useState(''); const isValidEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email); - const canSubmit = + const isProcessing = status === 'subscribing' || status === 'unsubscribing'; + + const canSubmitSubscribe = form.first_name.trim().length > 0 && form.last_name.trim().length > 0 && isValidEmail && - status !== 'loading'; + !isProcessing; + const canSubmitUnsubscribe = isValidEmail && !isProcessing; const handleChange = (field: string, value: string | boolean) => { setForm((prev) => ({ ...prev, [field]: value })); + if (status !== 'idle') setStatus('idle'); }; - const handleSubmit = async () => { - if (!canSubmit) return; - - setStatus('loading'); + const handleSubscribeSubmit = async () => { + if (!canSubmitSubscribe) return; + setStatus('subscribing'); setErrorMsg(''); try { @@ -58,7 +66,7 @@ const SubscribePage = (): JSX.Element => { }); if (res.ok) { - setStatus('success'); + setStatus('subscribe_success'); } else { const err = await res.json().catch(() => ({})); setErrorMsg(err.message || 'Failed to subscribe. Please try again.'); @@ -70,6 +78,37 @@ const SubscribePage = (): JSX.Element => { } }; + const handleUnsubscribeRequest = async () => { + if (!canSubmitUnsubscribe) return; + setStatus('unsubscribing'); + setErrorMsg(''); + + try { + const res = await fetch('/vector-api/request-unsubscribe', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ email: form.email.trim().toLowerCase() }), + }); + + if (res.ok) { + const data = await res.json().catch(() => ({})); + // Route success state based on backend action + if (data.type === 'direct_disable') { + setStatus('unsubscribe_direct'); + } else { + setStatus('unsubscribe_success'); + } + } else { + const err = await res.json().catch(() => ({})); + setErrorMsg(err.message || 'Request failed. Please try again.'); + setStatus('error'); + } + } catch { + setErrorMsg('Network error. Please check your connection and try again.'); + setStatus('error'); + } + }; + return ( @@ -77,93 +116,116 @@ const SubscribePage = (): JSX.Element => { {t('title') || 'Subscribe for Updates'} - {status === 'success' ? ( + {status === 'subscribe_success' && ( {t('successMessage') || "Almost done! We've sent a verification link to your email — please check your inbox to confirm."} - ) : ( - <> - - {t('description') || - 'Get notified about news and new datasets on VectorAtlas.'} - - - handleChange('first_name', e.target.value)} - margin="normal" - required - error={status === 'error' && !form.first_name.trim()} - /> - - handleChange('last_name', e.target.value)} - margin="normal" - required - error={status === 'error' && !form.last_name.trim()} - /> - - handleChange('email', e.target.value)} - margin="normal" - required - error={!!form.email && !isValidEmail} - helperText={ - !!form.email && !isValidEmail - ? 'Please enter a valid email' - : '' - } - /> - - - - handleChange('notifications_enabled', e.target.checked) - } - /> - } - label={ - t('notificationsLabel') || - 'Subscribe to news and dataset updates' + )} + + {status === 'unsubscribe_success' && ( + + We have sent you a secure unsubscription link. Please check your + inbox to confirm. + + )} + + {/* New Direct Success UI */} + {status === 'unsubscribe_direct' && ( + +

    + You are not a subscriber. However your account notifications have + been successfully disabled.{' '} +

    +

    Visit settings to re-enable.

    +
    + )} + + {status !== 'subscribe_success' && + status !== 'unsubscribe_success' && + status !== 'unsubscribe_direct' && ( + <> + + {t('description') || + 'Get notified about news and new datasets on VectorAtlas.'} + + + handleChange('first_name', e.target.value)} + disabled={isProcessing} + /> + + handleChange('last_name', e.target.value)} + disabled={isProcessing} + /> + + handleChange('email', e.target.value)} + disabled={isProcessing} + error={!!form.email && !isValidEmail} + helperText={ + !!form.email && !isValidEmail + ? 'Please enter a valid email' + : '' } /> -
    - - {status === 'error' && ( - - {errorMsg} - - )} - - - - )} + + {/* Subscribe Button */} + + + {/* Unsubscribe Button */} + + + )}
    ); diff --git a/src/UI/pages/subscriberList.tsx b/src/UI/pages/subscriberList.tsx new file mode 100644 index 000000000..4ef11f3fc --- /dev/null +++ b/src/UI/pages/subscriberList.tsx @@ -0,0 +1,31 @@ +import { Container } from '@mui/material'; +import React from 'react'; +import { GetServerSidePropsContext } from 'next'; +import { getMessages } from '../utils/localization'; +import AuthWrapper from '../components/shared/AuthWrapper'; +import { SubscriptionList } from '../components/subscription/manage_subsriptions'; + +const SubscriptionPage = (): JSX.Element => { + return ( +
    + + + + + +
    + ); +}; + +export async function getServerSideProps(context: GetServerSidePropsContext) { + return await getMessages(context); +} + +export default SubscriptionPage; diff --git a/src/UI/pages/unsubscribed-success/index.tsx b/src/UI/pages/unsubscribed-success/index.tsx index c991cc5d8..2beff099c 100644 --- a/src/UI/pages/unsubscribed-success/index.tsx +++ b/src/UI/pages/unsubscribed-success/index.tsx @@ -1,20 +1,65 @@ -import React from 'react'; -import { Container, Box, Typography, Button } from '@mui/material'; +import React, { useEffect, useRef, useState } from 'react'; +import { + Container, + Box, + Typography, + Button, + CircularProgress, +} from '@mui/material'; import Link from 'next/link'; import { useTranslations } from 'next-intl'; import { getMessages } from '../../utils/localization'; import { GetServerSidePropsContext } from 'next'; +import { useRouter } from 'next/router'; +import { apiUrl } from '../../api/api'; -type UnsubscribeStatus = 'success' | 'invalid'; +type UnsubscribeStatus = 'loading' | 'success' | 'invalid'; -interface Props { - status: UnsubscribeStatus; -} - -const UnsubscribePage = ({ status }: Props): JSX.Element => { +const UnsubscribePage = (): JSX.Element => { const t = useTranslations('EmailSubscription'); + const router = useRouter(); + const [status, setStatus] = useState('loading'); + const hasAttempted = useRef(false); + + useEffect(() => { + if (!router.isReady || hasAttempted.current) return; + + const { id, token } = router.query; + + if (typeof id === 'string' && typeof token === 'string' && id && token) { + hasAttempted.current = true; + + const processUnsubscribe = async () => { + try { + const res = await fetch(`${apiUrl}unsubscribe`, { + method: 'DELETE', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ id: id.trim(), token: token.trim() }), + }); + + if (res.ok || res.status === 204) { + setStatus('success'); + } else { + setStatus('invalid'); + } + } catch (err) { + console.error('Unsubscribe request failed:', err); + setStatus('invalid'); + } + }; + + processUnsubscribe(); + } else if (router.isReady) { + setStatus('invalid'); + } + }, [router.isReady, router.query]); const content = { + loading: { + title: 'Processing...', + body: 'Please wait while we process your request.', + color: 'text.primary', + }, success: { title: t('unsubscribeSuccessTitle') || 'Unsubscribed', body: @@ -41,46 +86,29 @@ const UnsubscribePage = ({ status }: Props): JSX.Element => { > {content.title} - - {content.body} - - - - + + {status === 'loading' ? ( + + ) : ( + + {content.body} + + )} + + {status !== 'loading' && ( + + + + )} ); }; export async function getServerSideProps(context: GetServerSidePropsContext) { - const messages = await getMessages(context); - const { id, token } = context.query; - - let status: UnsubscribeStatus = 'invalid'; - - if (typeof id === 'string' && typeof token === 'string' && id && token) { - try { - const res = await fetch(`${process.env.API_BASE_URL}/unsubscribe`, { - method: 'DELETE', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ id, token }), - }); - - status = res.ok ? 'success' : 'invalid'; - } catch (err) { - console.error('unsubscribe fetch failed:', err); - status = 'invalid'; - } - } - - return { - props: { - ...messages.props, - status, - }, - }; + return await getMessages(context); } export default UnsubscribePage; diff --git a/src/UI/pages/verify-success/index.tsx b/src/UI/pages/verify-success/index.tsx index a5af7d88d..5c9f476ea 100644 --- a/src/UI/pages/verify-success/index.tsx +++ b/src/UI/pages/verify-success/index.tsx @@ -76,8 +76,16 @@ export async function getServerSideProps(context: GetServerSidePropsContext) { if (typeof token === 'string' && token.length > 0) { try { + const backendUrl = + process.env.API_BASE_URL || 'http://127.0.0.1:3000/vector-api'; const res = await fetch( - `${process.env.API_BASE_URL}/verify?token=${encodeURIComponent(token)}` + `${backendUrl}/verify?token=${encodeURIComponent(token.trim())}`, + { + method: 'GET', + headers: { + Accept: 'application/json', + }, + } ); if (res.ok) { @@ -93,7 +101,8 @@ export async function getServerSideProps(context: GetServerSidePropsContext) { status = 'invalid'; } } - } catch { + } catch (error) { + console.error('Verification fetch failed:', error); status = 'invalid'; } } diff --git a/src/UI/public/messages/en.json b/src/UI/public/messages/en.json index 0b7943b4d..3bdd2b4b1 100644 --- a/src/UI/public/messages/en.json +++ b/src/UI/public/messages/en.json @@ -837,9 +837,9 @@ "apiVersion": "API Version", "description": "Mapping the future of research on vector-borne diseases", "contactTitle": "Contact Us", - "resourcesTitle": "Ressources", + "resourcesTitle": "Resources", "map": "Access the Map", - "subscribe": "Subscribe to Updates" + "subscribe": "Subscribe/Unsubscribe" }, "EmailSubscription": { "title": "Subscribe for Updates", diff --git a/src/UI/state/auth/actions/requestRoles.ts b/src/UI/state/auth/actions/requestRoles.ts index f1fa08765..fd38a4b72 100644 --- a/src/UI/state/auth/actions/requestRoles.ts +++ b/src/UI/state/auth/actions/requestRoles.ts @@ -55,6 +55,7 @@ export const disableNotifications = createAsyncThunk( try { dispatch(requestLoading(true)); const token = (getState() as AppState).auth.token; + const roleRequest = await fetchGraphQlDataAuthenticated( disableNotificationsMutation(userId, disable), token diff --git a/src/UI/state/auth/authSlice.ts b/src/UI/state/auth/authSlice.ts index dbb2e3e6d..22531ca69 100644 --- a/src/UI/state/auth/authSlice.ts +++ b/src/UI/state/auth/authSlice.ts @@ -6,6 +6,7 @@ export interface AuthState { roles: String[]; token: String; isLoading: Boolean; + disableNotification: boolean; roleRequestLoading: boolean; } @@ -15,6 +16,7 @@ export const initialState: () => AuthState = () => ({ token: '', isLoading: true, roleRequestLoading: false, + disableNotification: false, }); export const authSlice = createSlice({ @@ -37,6 +39,10 @@ export const authSlice = createSlice({ state.roles = action.payload.roles; state.token = action.payload.token; state.isLoading = false; + state.disableNotification = + action.payload.disable_notification || + action.payload.disableNotification || + false; }); }, });