import * as admin from 'firebase-admin' import { EndpointDefinition } from './api' import { getPrivateUser } from './utils' import { PrivateUser } from '../../common/user' import { NOTIFICATION_DESCRIPTIONS } from '../../common/notification' import { notification_preference } from '../../common/user-notification-preferences' import { getFunctionUrl } from '../../common/api' export const unsubscribe: EndpointDefinition = { opts: { method: 'GET', minInstances: 1 }, handler: async (req, res) => { const id = req.query.id as string const type = req.query.type as string if (!id || !type) { res.status(400).send('Empty id or subscription type parameter.') return } console.log(`Unsubscribing ${id} from ${type}`) const notificationSubscriptionType = type as notification_preference if (notificationSubscriptionType === undefined) { res.status(400).send('Invalid subscription type parameter.') return } const optOutAllType: notification_preference = 'opt_out_all' const wantsToOptOutAll = notificationSubscriptionType === optOutAllType const user = await getPrivateUser(id) if (!user) { res.send('This user is not currently subscribed or does not exist.') return } const previousDestinations = user.notificationPreferences[notificationSubscriptionType] let newDestinations = previousDestinations if (wantsToOptOutAll) newDestinations.push('email') else newDestinations = previousDestinations.filter( (destination) => destination !== 'email' ) console.log(previousDestinations) const { email } = user const update: Partial = { notificationPreferences: { ...user.notificationPreferences, [notificationSubscriptionType]: newDestinations, }, } await firestore.collection('private-users').doc(id).update(update) const unsubscribeEndpoint = getFunctionUrl('unsubscribe') const optOutAllUrl = `${unsubscribeEndpoint}?id=${id}&type=${optOutAllType}` if (wantsToOptOutAll) { res.send( ` Unsubscribe from Manifold Markets emails
banner logo

${email} has opted out of receiving unnecessary email notifications

` ) } else { res.send( ` Unsubscribe from Manifold Markets emails
banner logo

Hello!

${email} has been unsubscribed from email notifications related to:

${NOTIFICATION_DESCRIPTIONS[notificationSubscriptionType].detailed}.




Click here to unsubscribe from all unnecessary emails.

Click here to manage the rest of your notification settings.

` ) } }, } const firestore = admin.firestore()