Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions apps/api/src/endpoints/cron/sendChoreReminders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,23 @@ export const sendChoreReminders = async (req: Request, res: Response): Promise<v
const notificationsSent: string[] = []
const errors: string[] = []

// Get current day of week (0 = Sunday, 1 = Monday, ..., 6 = Saturday)
const now = new Date()
const dayOfWeek = now.getDay()
const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
const currentDayName = dayNames[dayOfWeek] as 'Mon' | 'Tue' | 'Wed' | 'Thu' | 'Fri' | 'Sat' | 'Sun'

for (const user of users) {
try {
// Check if user has push notification days configured and if today is enabled
if (user.pushNotificationDays) {
const isTodayEnabled = user.pushNotificationDays[currentDayName]
if (!isTodayEnabled) {
// User doesn't want notifications on this day, skip
continue
}
}

/*
Vercel Hobby plan only allows one cron job run per day
so instead of running the job at 0 * * * * and checking if it's 8am in the user's timezone,
Expand Down
9 changes: 9 additions & 0 deletions apps/api/src/endpoints/trpc/auth/createAccount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@ export const createAccount = publicProcedure
password: hashedPassword,
timezone: input.timezone || 'America/New_York', // Default timezone if not provided
pushNotificationsEnabled: true, // Default to enabled
pushNotificationDays: { // Default to every day
Mon: true,
Tue: true,
Wed: true,
Thu: true,
Fri: true,
Sat: true,
Sun: true,
},
})

// Generate token
Expand Down
12 changes: 11 additions & 1 deletion apps/api/src/endpoints/trpc/auth/deleteMe.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { TRPCError } from '@trpc/server'
import mongoose from 'mongoose'

import { Chore, ChoreLog, Fertilizer, PasswordResetToken, Plant, PlantLifecycleEvent } from '../../../models'
Expand All @@ -6,6 +7,15 @@ import { authProcedure } from '../../../procedures/authProcedure'

export const deleteMe = authProcedure
.mutation(async ({ ctx }) => {
const user = ctx.user

if (!user) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: 'User not found',
})
}

const userId = ctx.userId

// Get all plants for this user
Expand Down Expand Up @@ -55,7 +65,7 @@ export const deleteMe = authProcedure
})

// Finally, delete the user
await ctx.user.deleteOne()
await user.deleteOne()

return { success: true }
})
10 changes: 10 additions & 0 deletions apps/api/src/endpoints/trpc/auth/me.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,26 @@
import { TRPCError } from '@trpc/server'

import { authProcedure } from '../../../procedures/authProcedure'

export const me = authProcedure
.query(async ({ ctx }) => {
const user = ctx.user

if (!user) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: 'User not found',
})
}

return {
_id: user._id.toString(),
name: user.name,
email: user.email,
phone: user.phone,
timezone: user.timezone,
pushNotificationsEnabled: user.pushNotificationsEnabled ?? true,
pushNotificationDays: user.pushNotificationDays,
}
})

7 changes: 7 additions & 0 deletions apps/api/src/endpoints/trpc/auth/updatePassword.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ export const updatePassword = authProcedure
.mutation(async ({ input, ctx }) => {
const user = ctx.user

if (!user) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: 'User not found',
})
}

// Verify current password
const isValidPassword = await bcrypt.compare(input.currentPassword, user.password)

Expand Down
7 changes: 7 additions & 0 deletions apps/api/src/endpoints/trpc/auth/updateProfile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ export const updateProfile = authProcedure
.mutation(async ({ input, ctx }) => {
const user = ctx.user

if (!user) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: 'User not found',
})
}

// Check if email is already taken by another user
if (input.email.toLowerCase().trim() !== user.email.toLowerCase().trim()) {
const existingUser = await User.findOne({ email: input.email.toLowerCase().trim() })
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { z } from 'zod'

import { User } from '../../../models'

import { authProcedure } from '../../../procedures/authProcedure'

const pushNotificationDaysSchema = z.object({
Mon: z.boolean(),
Tue: z.boolean(),
Wed: z.boolean(),
Thu: z.boolean(),
Fri: z.boolean(),
Sat: z.boolean(),
Sun: z.boolean(),
})

export const updatePushNotificationPreferences = authProcedure
.input(z.object({
days: pushNotificationDaysSchema.optional(),
enabled: z.boolean().optional(),
}))
.mutation(async ({ input, ctx }) => {
const userId = ctx.userId

const updateData: {
pushNotificationDays?: {
Mon: boolean,
Tue: boolean,
Wed: boolean,
Thu: boolean,
Fri: boolean,
Sat: boolean,
Sun: boolean,
},
pushNotificationsEnabled?: boolean,
} = {}

if (input.enabled !== undefined) {
updateData.pushNotificationsEnabled = input.enabled
}

if (input.days !== undefined) {
updateData.pushNotificationDays = input.days
}

await User.findByIdAndUpdate(userId, updateData)

return { success: true }
})

This file was deleted.

21 changes: 21 additions & 0 deletions apps/api/src/models/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@ export interface IUser {
timezone?: string,
pushNotificationToken?: string,
pushNotificationsEnabled?: boolean,
pushNotificationDays?: {
Mon: boolean,
Tue: boolean,
Wed: boolean,
Thu: boolean,
Fri: boolean,
Sat: boolean,
Sun: boolean,
},
createdAt: Date,
updatedAt: Date,
}
Expand Down Expand Up @@ -55,6 +64,18 @@ export const userSchema = new mongoose.Schema<IUser>({
type: Boolean,
default: true,
},
pushNotificationDays: {
type: {
Mon: Boolean,
Tue: Boolean,
Wed: Boolean,
Thu: Boolean,
Fri: Boolean,
Sat: Boolean,
Sun: Boolean,
},
required: false,
},
}, {
collation: { locale: 'en', strength: 2 },
timestamps: true,
Expand Down
4 changes: 2 additions & 2 deletions apps/api/src/routers/trpc/settings.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { router } from '../../trpc'

import { updatePushNotificationsEnabled } from '../../endpoints/trpc/settings/updatePushNotificationsEnabled'
import { updatePushNotificationPreferences } from '../../endpoints/trpc/settings/updatePushNotificationPreferences'
import { updatePushNotificationToken } from '../../endpoints/trpc/settings/updatePushNotificationToken'
import { updateTimezone } from '../../endpoints/trpc/settings/updateTimezone'

export const settingsRouter = router({
updatePushNotificationsEnabled,
updatePushNotificationPreferences,
updatePushNotificationToken,
updateTimezone,
})
Expand Down
15 changes: 11 additions & 4 deletions apps/api/src/trpc/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,18 @@ import { initTRPC } from '@trpc/server'
import superjson from 'superjson'
import type { IncomingMessage } from 'http'

import type { IUser } from '../models/User'
import type { Document } from 'mongoose'

export interface Context {
req?: IncomingMessage
userId?: string
user?: any
}
req?: IncomingMessage,
userId?: string,
user?: (Document<unknown, {}, IUser, {}, {}> & IUser & Required<{
_id: string;
}> & {
__v: number;
}) | null,
}

export const tRPCContext = initTRPC
.context<Context>()
Expand Down
76 changes: 66 additions & 10 deletions apps/mobile/src/app/(tabs)/settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@ export function SettingsScreen() {
const [isDeleteAccountExpanded, setIsDeleteAccountExpanded] = useState(false)

// Get user settings
const { data: userData } = trpc.auth.me.useQuery()
const {
data: userData,
isRefetching,
refetch,
} = trpc.auth.me.useQuery()

useEffect(() => {
if (!userData) {
Expand All @@ -45,7 +49,7 @@ export function SettingsScreen() {
return
}

setCurrentTimezone(userData.timezone)
setCurrentTimezone(userData.timezone || null)
}, [ userData?.timezone ])

const updateTimezoneMutation = trpc.settings.updateTimezone.useMutation({
Expand All @@ -58,7 +62,7 @@ export function SettingsScreen() {
},
})

const updatePushNotificationsMutation = trpc.settings.updatePushNotificationsEnabled.useMutation({
const updatePushNotificationPreferencesMutation = trpc.settings.updatePushNotificationPreferences.useMutation({
onSuccess: () => {
queryClient.invalidateQueries()
},
Expand All @@ -75,7 +79,45 @@ export function SettingsScreen() {

const handlePushNotificationsToggle = (enabled: boolean) => {
setPushNotificationsEnabled(enabled)
updatePushNotificationsMutation.mutate({ enabled })
updatePushNotificationPreferencesMutation.mutate({ enabled })
}

const getReminderDescription = (): string => {
const description = ' at 8am when chores are due.'

const days = userData?.pushNotificationDays || {
Mon: true,
Tue: true,
Wed: true,
Thu: true,
Fri: true,
Sat: true,
Sun: true,
}

const enabledDays = Object.entries(days)
.filter(([_, enabled]) => enabled)
.map(([day]) => day !== '_id' && day)
.filter(Boolean)

// Check if all days are selected
if (enabledDays.length === 7) {
return 'Receive reminders every day' + description
}

// Check if only weekends are selected
if (enabledDays.length === 2 && enabledDays.includes('Sat') && enabledDays.includes('Sun')) {
return 'Receive reminders on weekends' + description
}

// Check if only weekdays are selected
const weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
if (enabledDays.length === 5 && weekdays.every(day => enabledDays.includes(day))) {
return 'Receive reminders on weekdays' + description
}

// Otherwise, list the selected days
return `Receive reminders on ${enabledDays.join(', ').replace(/,([^,]*)$/g, ' and$1')}` + description
}

const deleteMeMutation = trpc.auth.deleteMe.useMutation({
Expand Down Expand Up @@ -137,8 +179,10 @@ export function SettingsScreen() {
}

return (
<ScreenWrapper>
<ScreenTitle isLoading={false}>Settings</ScreenTitle>
<ScreenWrapper onRefresh={refetch}>
<ScreenTitle isLoading={isRefetching}>
Settings
</ScreenTitle>

<ScrollView>
{user && (
Expand Down Expand Up @@ -174,12 +218,9 @@ export function SettingsScreen() {
<View style={localStyles.section}>
<Text style={localStyles.sectionTitle}>Notifications</Text>

<View style={localStyles.settingRow}>
<View style={[localStyles.settingRow, pushNotificationsEnabled && { borderBottomWidth: 0, paddingBottom: 0 }]}>
<View style={localStyles.settingContent}>
<Text style={localStyles.settingLabel}>Push Notifications</Text>
<Text style={localStyles.settingDescription}>
Receive daily reminders at 8am when chores are due
</Text>
</View>
<Switch
value={pushNotificationsEnabled}
Expand All @@ -188,6 +229,21 @@ export function SettingsScreen() {
thumbColor={pushNotificationsEnabled ? '#fff' : '#f4f3f4'}
/>
</View>
{pushNotificationsEnabled && (
<View style={localStyles.settingRow}>
<View style={localStyles.settingContent}>
<Text style={localStyles.settingDescription}>
{getReminderDescription()}
</Text>
</View>
<TouchableOpacity
style={localStyles.editButton}
onPress={() => router.push('/notification-preferences')}
>
<Text style={localStyles.editButtonText}>Edit</Text>
</TouchableOpacity>
</View>
)}
</View>

<View style={localStyles.section}>
Expand Down
Loading