Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ALTER TABLE "User" ADD COLUMN "weeklyDigestEnabled" BOOLEAN NOT NULL DEFAULT true;
ALTER TABLE "User" ADD COLUMN "followUpRemindersEnabled" BOOLEAN NOT NULL DEFAULT true;
16 changes: 9 additions & 7 deletions apps/api/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ datasource db {
}

model User {
id String @id
email String @unique
passwordHash String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
applications JobApplication[]
apiTokens ApiToken[]
id String @id
email String @unique
passwordHash String
weeklyDigestEnabled Boolean @default(true)
followUpRemindersEnabled Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
applications JobApplication[]
apiTokens ApiToken[]
}

model ApiToken {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,28 @@ describe('SendFollowUpRemindersUseCase', () => {
expect(applicationRepository.updateReminderSentAt).not.toHaveBeenCalled();
});

it('skips applications for users who have disabled follow-up reminders', async () => {
const app = makeApplication({ followUpAt: new Date() });
const user = makeUser({ followUpRemindersEnabled: false });
const applicationRepository = makeApplicationRepository({
findDueForReminder: vi.fn().mockResolvedValue([app]),
updateReminderSentAt: vi.fn(),
});
const userRepository = makeUserRepository({
findById: vi.fn().mockResolvedValue(user),
});
const emailService = makeEmailService();

await new SendFollowUpRemindersUseCase({
applicationRepository,
userRepository,
emailService,
}).execute();

expect(emailService.sendFollowUpReminder).not.toHaveBeenCalled();
expect(applicationRepository.updateReminderSentAt).not.toHaveBeenCalled();
});

it('continues past individual email failures without throwing', async () => {
const apps = [
makeApplication({ id: 'app-1', followUpAt: new Date() }),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { GetNotificationPreferencesUseCase } from '@/use-cases/user/GetNotificationPreferencesUseCase.js';
import { makeUserRepository, makeUser } from '@/__tests__/helpers/mocks.js';

describe('GetNotificationPreferencesUseCase', () => {
beforeEach(() => {
vi.clearAllMocks();
});

it('throws NOT_FOUND when the user does not exist', async () => {
const userRepository = makeUserRepository({ findById: vi.fn().mockResolvedValue(null) });

const err = await new GetNotificationPreferencesUseCase({ userRepository })
.execute('missing')
.catch((e) => e);

expect((err as { code: string }).code).toBe('NOT_FOUND');
});

it('returns the preferences from the user record', async () => {
const user = makeUser({ weeklyDigestEnabled: false, followUpRemindersEnabled: true });
const userRepository = makeUserRepository({ findById: vi.fn().mockResolvedValue(user) });

const result = await new GetNotificationPreferencesUseCase({ userRepository }).execute(
'user-1',
);

expect(result).toEqual({ weeklyDigestEnabled: false, followUpRemindersEnabled: true });
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { UpdateNotificationPreferencesUseCase } from '@/use-cases/user/UpdateNotificationPreferencesUseCase.js';
import { makeUserRepository, makeUser } from '@/__tests__/helpers/mocks.js';

describe('UpdateNotificationPreferencesUseCase', () => {
beforeEach(() => {
vi.clearAllMocks();
});

it('throws NOT_FOUND when the user does not exist', async () => {
const userRepository = makeUserRepository({ findById: vi.fn().mockResolvedValue(null) });

const err = await new UpdateNotificationPreferencesUseCase({ userRepository })
.execute({ userId: 'missing', weeklyDigestEnabled: false })
.catch((e) => e);

expect((err as { code: string }).code).toBe('NOT_FOUND');
expect(userRepository.update).not.toHaveBeenCalled();
});

it('updates the given preferences', async () => {
const user = makeUser({ id: 'user-1' });
const userRepository = makeUserRepository({ findById: vi.fn().mockResolvedValue(user) });

await new UpdateNotificationPreferencesUseCase({ userRepository }).execute({
userId: 'user-1',
weeklyDigestEnabled: false,
followUpRemindersEnabled: true,
});

expect(userRepository.update).toHaveBeenCalledWith('user-1', {
weeklyDigestEnabled: false,
followUpRemindersEnabled: true,
});
});

it('leaves fields untouched when undefined', async () => {
const user = makeUser({ id: 'user-1' });
const userRepository = makeUserRepository({ findById: vi.fn().mockResolvedValue(user) });

await new UpdateNotificationPreferencesUseCase({ userRepository }).execute({
userId: 'user-1',
weeklyDigestEnabled: false,
});

expect(userRepository.update).toHaveBeenCalledWith('user-1', {
weeklyDigestEnabled: false,
followUpRemindersEnabled: undefined,
});
});
});
17 changes: 17 additions & 0 deletions apps/api/src/__tests__/digest/SendWeeklyDigestUseCase.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,23 @@ describe('SendWeeklyDigestUseCase', () => {
expect(emailService.sendWeeklyDigest).not.toHaveBeenCalled();
});

it('skips users who have disabled the weekly digest', async () => {
const user = makeUser({ weeklyDigestEnabled: false });
const userRepository = makeUserRepository({ findAll: vi.fn().mockResolvedValue([user]) });
const applicationRepository = makeApplicationRepository();
const emailService = makeEmailService();

const result = await new SendWeeklyDigestUseCase({
userRepository,
applicationRepository,
emailService,
}).execute();

expect(result).toEqual({ totalUsers: 1, sent: 0, skipped: 1 });
expect(applicationRepository.findAllByUserId).not.toHaveBeenCalled();
expect(emailService.sendWeeklyDigest).not.toHaveBeenCalled();
});

it('sends a digest for each user with applications', async () => {
const userA = makeUser({ id: 'u1', email: 'a@test.com' });
const userB = makeUser({ id: 'u2', email: 'b@test.com' });
Expand Down
2 changes: 2 additions & 0 deletions apps/api/src/__tests__/helpers/createTestDb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ const SCHEMA_STATEMENTS = [
"id" TEXT PRIMARY KEY,
"email" TEXT NOT NULL UNIQUE,
"passwordHash" TEXT NOT NULL,
"weeklyDigestEnabled" INTEGER NOT NULL DEFAULT 1,
"followUpRemindersEnabled" INTEGER NOT NULL DEFAULT 1,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
)`,
Expand Down
2 changes: 2 additions & 0 deletions apps/api/src/__tests__/helpers/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,8 @@ export const makeUser = (overrides?: Partial<User>): User => ({
id: 'user-1',
email: 'test@example.com',
passwordHash: 'hashed-pw',
weeklyDigestEnabled: true,
followUpRemindersEnabled: true,
createdAt: new Date('2024-01-01'),
updatedAt: new Date('2024-01-01'),
...overrides,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ describe('PrismaUserRepository', () => {
expect(user.createdAt).toBeInstanceOf(Date);
expect(user.updatedAt).toBeInstanceOf(Date);
});

it('defaults notification preferences to enabled', async () => {
const user = await repo.create({ id: 'u1', email: 'a@b.com', passwordHash: 'hashed' });

expect(user.weeklyDigestEnabled).toBe(true);
expect(user.followUpRemindersEnabled).toBe(true);
});
});

describe('findById', () => {
Expand Down Expand Up @@ -100,6 +107,17 @@ describe('PrismaUserRepository', () => {
expect(updated.createdAt).toBeInstanceOf(Date);
expect(updated.updatedAt).toBeInstanceOf(Date);
});

it('updates notification preferences', async () => {
await repo.create({ id: 'u1', email: 'a@b.com', passwordHash: 'hashed' });
const updated = await repo.update('u1', {
weeklyDigestEnabled: false,
followUpRemindersEnabled: false,
});

expect(updated.weeklyDigestEnabled).toBe(false);
expect(updated.followUpRemindersEnabled).toBe(false);
});
});

describe('delete', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import type { IUpdateEmailUseCase } from '@/use-cases/user/IUpdateEmailUseCase.j
import type { IUpdatePasswordUseCase } from '@/use-cases/user/IUpdatePasswordUseCase.js';
import type { IDeleteAccountUseCase } from '@/use-cases/user/IDeleteAccountUseCase.js';
import type { IExportUserDataUseCase } from '@/use-cases/user/IExportUserDataUseCase.js';
import type { IGetNotificationPreferencesUseCase } from '@/use-cases/user/IGetNotificationPreferencesUseCase.js';
import type { IUpdateNotificationPreferencesUseCase } from '@/use-cases/user/IUpdateNotificationPreferencesUseCase.js';

const stub = <T>(methods: Partial<T>): T => methods as T;

Expand All @@ -16,6 +18,12 @@ const makeDeps = (overrides?: object) => ({
execute: vi.fn().mockResolvedValue(undefined),
}),
exportUserDataUseCase: stub<IExportUserDataUseCase>({ execute: vi.fn() }),
getNotificationPreferencesUseCase: stub<IGetNotificationPreferencesUseCase>({
execute: vi.fn(),
}),
updateNotificationPreferencesUseCase: stub<IUpdateNotificationPreferencesUseCase>({
execute: vi.fn().mockResolvedValue(undefined),
}),
...overrides,
});

Expand Down Expand Up @@ -100,4 +108,34 @@ describe('UserResolver', () => {
expect(result).toEqual(exportData);
});
});

describe('getNotificationPreferences', () => {
it('delegates to getNotificationPreferencesUseCase and returns the result', async () => {
const prefs = { weeklyDigestEnabled: true, followUpRemindersEnabled: false };
const deps = makeDeps({
getNotificationPreferencesUseCase: stub<IGetNotificationPreferencesUseCase>({
execute: vi.fn().mockResolvedValue(prefs),
}),
});

const result = await new UserResolver(deps).getNotificationPreferences('user-1');

expect(deps.getNotificationPreferencesUseCase.execute).toHaveBeenCalledWith('user-1');
expect(result).toEqual(prefs);
});
});

describe('updateNotificationPreferences', () => {
it('delegates to updateNotificationPreferencesUseCase with the correct arguments', async () => {
const deps = makeDeps();

await new UserResolver(deps).updateNotificationPreferences('user-1', false, true);

expect(deps.updateNotificationPreferencesUseCase.execute).toHaveBeenCalledWith({
userId: 'user-1',
weeklyDigestEnabled: false,
followUpRemindersEnabled: true,
});
});
});
});
2 changes: 2 additions & 0 deletions apps/api/src/domain/user/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ export interface User {
id: string;
email: string;
passwordHash: string;
weeklyDigestEnabled: boolean;
followUpRemindersEnabled: boolean;
createdAt: Date;
updatedAt: Date;
}
10 changes: 10 additions & 0 deletions apps/api/src/http/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ import { UpdateEmailUseCase } from '@/use-cases/user/UpdateEmailUseCase.js';
import { UpdatePasswordUseCase } from '@/use-cases/user/UpdatePasswordUseCase.js';
import { DeleteAccountUseCase } from '@/use-cases/user/DeleteAccountUseCase.js';
import { ExportUserDataUseCase } from '@/use-cases/user/ExportUserDataUseCase.js';
import { GetNotificationPreferencesUseCase } from '@/use-cases/user/GetNotificationPreferencesUseCase.js';
import { UpdateNotificationPreferencesUseCase } from '@/use-cases/user/UpdateNotificationPreferencesUseCase.js';
import { CreateInterviewRoundUseCase } from '@/use-cases/interviewRounds/CreateInterviewRoundUseCase.js';
import { GetInterviewRoundsUseCase } from '@/use-cases/interviewRounds/GetInterviewRoundsUseCase.js';
import { UpdateInterviewRoundUseCase } from '@/use-cases/interviewRounds/UpdateInterviewRoundUseCase.js';
Expand Down Expand Up @@ -149,6 +151,8 @@ declare module '@fastify/awilix' {
updatePasswordUseCase: UpdatePasswordUseCase;
deleteAccountUseCase: DeleteAccountUseCase;
exportUserDataUseCase: ExportUserDataUseCase;
getNotificationPreferencesUseCase: GetNotificationPreferencesUseCase;
updateNotificationPreferencesUseCase: UpdateNotificationPreferencesUseCase;
createInterviewRoundUseCase: CreateInterviewRoundUseCase;
getInterviewRoundsUseCase: GetInterviewRoundsUseCase;
updateInterviewRoundUseCase: UpdateInterviewRoundUseCase;
Expand Down Expand Up @@ -266,6 +270,12 @@ export function buildContainer(fastify: FastifyInstance): void {
updatePasswordUseCase: asClass(UpdatePasswordUseCase, { lifetime: Lifetime.TRANSIENT }),
deleteAccountUseCase: asClass(DeleteAccountUseCase, { lifetime: Lifetime.TRANSIENT }),
exportUserDataUseCase: asClass(ExportUserDataUseCase, { lifetime: Lifetime.TRANSIENT }),
getNotificationPreferencesUseCase: asClass(GetNotificationPreferencesUseCase, {
lifetime: Lifetime.TRANSIENT,
}),
updateNotificationPreferencesUseCase: asClass(UpdateNotificationPreferencesUseCase, {
lifetime: Lifetime.TRANSIENT,
}),
createInterviewRoundUseCase: asClass(CreateInterviewRoundUseCase, {
lifetime: Lifetime.TRANSIENT,
}),
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/http/schema/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import './types/inputs/DocumentInputs.js';
import './types/ContactType.js';
import './types/ParsedJobDescriptionType.js';
import './types/HealthScoreType.js';
import './types/NotificationPreferencesType.js';

// Queries
import './queries/applicationQueries.js';
Expand Down
24 changes: 24 additions & 0 deletions apps/api/src/http/schema/mutations/userMutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,27 @@ builder.mutationField('deleteAccount', (t) =>
},
}),
);

builder.mutationField('updateNotificationPreferences', (t) =>
t.boolean({
args: {
weeklyDigestEnabled: t.arg.boolean({ required: false }),
followUpRemindersEnabled: t.arg.boolean({ required: false }),
},
resolve: async (_root, args, ctx) => {
if (!ctx.user)
throw new GraphQLError('Unauthorized', { extensions: { code: ERROR_CODES.UNAUTHORIZED } });
const { userResolver } = ctx.diScope.cradle;
try {
await userResolver.updateNotificationPreferences(
ctx.user.sub,
args.weeklyDigestEnabled ?? undefined,
args.followUpRemindersEnabled ?? undefined,
);
return true;
} catch (err) {
throw fromCodedError(err);
}
},
}),
);
13 changes: 13 additions & 0 deletions apps/api/src/http/schema/queries/userQueries.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { GraphQLError } from 'graphql';
import { builder } from '@/http/schema/builder.js';
import { NotificationPreferencesRef } from '@/http/schema/types/NotificationPreferencesType.js';
import { ERROR_CODES } from '@/constants.js';

builder.queryField('exportUserData', (t) =>
Expand All @@ -13,3 +14,15 @@ builder.queryField('exportUserData', (t) =>
},
}),
);

builder.queryField('notificationPreferences', (t) =>
t.field({
type: NotificationPreferencesRef,
resolve: async (_root, _args, ctx) => {
if (!ctx.user)
throw new GraphQLError('Unauthorized', { extensions: { code: ERROR_CODES.UNAUTHORIZED } });
const { userResolver } = ctx.diScope.cradle;
return userResolver.getNotificationPreferences(ctx.user.sub);
},
}),
);
11 changes: 11 additions & 0 deletions apps/api/src/http/schema/types/NotificationPreferencesType.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { builder } from '@/http/schema/builder.js';
import type { NotificationPreferences } from '@/use-cases/user/IGetNotificationPreferencesUseCase.js';

export const NotificationPreferencesRef =
builder.objectRef<NotificationPreferences>('NotificationPreferences');
NotificationPreferencesRef.implement({
fields: (t) => ({
weeklyDigestEnabled: t.exposeBoolean('weeklyDigestEnabled'),
followUpRemindersEnabled: t.exposeBoolean('followUpRemindersEnabled'),
}),
});
Loading
Loading