Skip to content
Open
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
2 changes: 2 additions & 0 deletions apps/backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { ChainsModule } from './modules/chains/chains.module';
import { RiskAnalyzerModule } from './modules/soroban/risk/risk-analyzer.module';
import { NotesModule } from './modules/cases/notes/notes.module';
import { AlertsModule } from './modules/alerts/alerts.module';
import { ProfileModule } from './modules/profile/profile.module';

@Module({
imports: [
Expand All @@ -25,6 +26,7 @@ import { AlertsModule } from './modules/alerts/alerts.module';
RiskAnalyzerModule,
NotesModule,
AlertsModule,
ProfileModule,
],
controllers: [AppController],
})
Expand Down
3 changes: 3 additions & 0 deletions apps/backend/src/modules/profile/dto/update-profile.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export class UpdateProfileDto {
email?: string;
}
19 changes: 19 additions & 0 deletions apps/backend/src/modules/profile/interfaces/profile.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export interface NotificationPreferencesSummary {
discordEnabled: boolean;
telegramEnabled: boolean;
emailEnabled: boolean;
alertTypes: string[];
}

export interface AccountMetadata {
watchlistCount: number;
openAlertsCount: number;
notificationPreferences: NotificationPreferencesSummary | null;
}

export interface UserProfile {
id: string;
email: string;
createdAt: string;
metadata: AccountMetadata;
}
40 changes: 40 additions & 0 deletions apps/backend/src/modules/profile/profile.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Body, Controller, Get, Headers, Patch, UnauthorizedException } from '@nestjs/common';
import { ProfileService } from './profile.service';
import { UpdateProfileDto } from './dto/update-profile.dto';
import { UserProfile } from './interfaces/profile.interface';

/**
* User profile endpoints.
*
* GET /api/profile — read profile and account metadata
* PATCH /api/profile — update editable profile fields
*
* Auth: temporary `X-User-Id` header until login/JWT issues (#78, #80) land.
*/
@Controller('profile')
export class ProfileController {
constructor(private readonly profileService: ProfileService) {}

@Get()
getProfile(@Headers('x-user-id') userId?: string): Promise<UserProfile> {
const resolvedUserId = this.resolveUserId(userId);
return this.profileService.getProfile(resolvedUserId);
}

@Patch()
updateProfile(
@Headers('x-user-id') userId: string | undefined,
@Body() dto: UpdateProfileDto,
): Promise<UserProfile> {
const resolvedUserId = this.resolveUserId(userId);
return this.profileService.updateProfile(resolvedUserId, dto);
}

private resolveUserId(userId?: string): string {
const trimmed = userId?.trim();
if (!trimmed) {
throw new UnauthorizedException('X-User-Id header is required');
}
return trimmed;
}
}
10 changes: 10 additions & 0 deletions apps/backend/src/modules/profile/profile.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { ProfileController } from './profile.controller';
import { ProfileService } from './profile.service';

@Module({
controllers: [ProfileController],
providers: [ProfileService],
exports: [ProfileService],
})
export class ProfileModule {}
141 changes: 141 additions & 0 deletions apps/backend/src/modules/profile/profile.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import { Test, TestingModule } from '@nestjs/testing';
import { BadRequestException, ConflictException, NotFoundException } from '@nestjs/common';
import { ProfileService } from './profile.service';
import { PrismaClient } from '@prisma/client';

jest.mock('@prisma/client', () => {
const mPrismaClient = {
user: {
findUnique: jest.fn(),
update: jest.fn(),
},
watchlist: {
count: jest.fn(),
},
alert: {
count: jest.fn(),
},
};
return { PrismaClient: jest.fn(() => mPrismaClient) };
});

describe('ProfileService', () => {
let service: ProfileService;
let prisma: PrismaClient;

const mockUser = {
id: 'user-1',
email: 'user@example.com',
createdAt: new Date('2026-06-15T10:00:00.000Z'),
notificationPreferences: [
{
discordEnabled: true,
telegramEnabled: false,
emailEnabled: true,
alertTypes: ['critical'],
},
],
};

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ProfileService],
}).compile();

service = module.get<ProfileService>(ProfileService);
prisma = new PrismaClient();
});

afterEach(() => {
jest.clearAllMocks();
});

it('should be defined', () => {
expect(service).toBeDefined();
});

describe('getProfile', () => {
it('returns profile with metadata', async () => {
(prisma.user.findUnique as jest.Mock).mockResolvedValue(mockUser);
(prisma.watchlist.count as jest.Mock).mockResolvedValue(3);
(prisma.alert.count as jest.Mock).mockResolvedValue(2);

const result = await service.getProfile('user-1');

expect(result).toEqual({
id: 'user-1',
email: 'user@example.com',
createdAt: '2026-06-15T10:00:00.000Z',
metadata: {
watchlistCount: 3,
openAlertsCount: 2,
notificationPreferences: {
discordEnabled: true,
telegramEnabled: false,
emailEnabled: true,
alertTypes: ['critical'],
},
},
});
});

it('throws NotFoundException when user does not exist', async () => {
(prisma.user.findUnique as jest.Mock).mockResolvedValue(null);

await expect(service.getProfile('missing')).rejects.toThrow(NotFoundException);
});
});

describe('updateProfile', () => {
it('updates email and returns profile', async () => {
(prisma.user.findUnique as jest.Mock).mockResolvedValue(mockUser);
(prisma.user.update as jest.Mock).mockResolvedValue({
...mockUser,
email: 'new@example.com',
});
(prisma.watchlist.count as jest.Mock).mockResolvedValue(1);
(prisma.alert.count as jest.Mock).mockResolvedValue(0);

const result = await service.updateProfile('user-1', { email: 'new@example.com' });

expect(prisma.user.update).toHaveBeenCalledWith({
where: { id: 'user-1' },
data: { email: 'new@example.com' },
include: {
notificationPreferences: {
take: 1,
orderBy: { createdAt: 'desc' },
},
},
});
expect(result.email).toBe('new@example.com');
});

it('throws BadRequestException for invalid email', async () => {
await expect(service.updateProfile('user-1', { email: 'not-an-email' })).rejects.toThrow(
BadRequestException,
);
});

it('throws BadRequestException when email is missing', async () => {
await expect(service.updateProfile('user-1', {})).rejects.toThrow(BadRequestException);
});

it('throws NotFoundException when user does not exist', async () => {
(prisma.user.findUnique as jest.Mock).mockResolvedValue(null);

await expect(service.updateProfile('missing', { email: 'a@b.com' })).rejects.toThrow(
NotFoundException,
);
});

it('throws ConflictException on duplicate email', async () => {
(prisma.user.findUnique as jest.Mock).mockResolvedValue(mockUser);
(prisma.user.update as jest.Mock).mockRejectedValue({ code: 'P2002' });

await expect(service.updateProfile('user-1', { email: 'taken@example.com' })).rejects.toThrow(
ConflictException,
);
});
});
});
131 changes: 131 additions & 0 deletions apps/backend/src/modules/profile/profile.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import {
BadRequestException,
ConflictException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
import { UpdateProfileDto } from './dto/update-profile.dto';
import { UserProfile } from './interfaces/profile.interface';

const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

@Injectable()
export class ProfileService {
private prisma: PrismaClient;

constructor() {
this.prisma = new PrismaClient();
}

async getProfile(userId: string): Promise<UserProfile> {
const user = await this.prisma.user.findUnique({
where: { id: userId },
include: {
notificationPreferences: {
take: 1,
orderBy: { createdAt: 'desc' },
},
},
});

if (!user) {
throw new NotFoundException(`User ${userId} not found`);
}

const [watchlistCount, openAlertsCount] = await Promise.all([
this.prisma.watchlist.count({ where: { userId } }),
this.prisma.alert.count({ where: { userId, status: 'open' } }),
]);

return this.toUserProfile(user, watchlistCount, openAlertsCount);
}

async updateProfile(userId: string, dto: UpdateProfileDto): Promise<UserProfile> {
const email = dto.email?.trim();

if (!email) {
throw new BadRequestException('email is required');
}

if (!EMAIL_REGEX.test(email)) {
throw new BadRequestException('email format is invalid');
}

const existing = await this.prisma.user.findUnique({ where: { id: userId } });

if (!existing) {
throw new NotFoundException(`User ${userId} not found`);
}

try {
const user = await this.prisma.user.update({
where: { id: userId },
data: { email },
include: {
notificationPreferences: {
take: 1,
orderBy: { createdAt: 'desc' },
},
},
});

const [watchlistCount, openAlertsCount] = await Promise.all([
this.prisma.watchlist.count({ where: { userId } }),
this.prisma.alert.count({ where: { userId, status: 'open' } }),
]);

return this.toUserProfile(user, watchlistCount, openAlertsCount);
} catch (error: unknown) {
if (this.isUniqueConstraintError(error)) {
throw new ConflictException('Email is already in use');
}
throw error;
}
}

private toUserProfile(
user: {
id: string;
email: string;
createdAt: Date;
notificationPreferences: Array<{
discordEnabled: boolean;
telegramEnabled: boolean;
emailEnabled: boolean;
alertTypes: string[];
}>;
},
watchlistCount: number,
openAlertsCount: number,
): UserProfile {
const prefs = user.notificationPreferences[0] ?? null;

return {
id: user.id,
email: user.email,
createdAt: user.createdAt.toISOString(),
metadata: {
watchlistCount,
openAlertsCount,
notificationPreferences: prefs
? {
discordEnabled: prefs.discordEnabled,
telegramEnabled: prefs.telegramEnabled,
emailEnabled: prefs.emailEnabled,
alertTypes: prefs.alertTypes,
}
: null,
},
};
}

private isUniqueConstraintError(error: unknown): boolean {
return (
typeof error === 'object' &&
error !== null &&
'code' in error &&
(error as { code: string }).code === 'P2002'
);
}
}
Loading