-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathusers.controller.ts
More file actions
190 lines (174 loc) · 6.56 KB
/
Copy pathusers.controller.ts
File metadata and controls
190 lines (174 loc) · 6.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
UseGuards,
HttpCode,
HttpStatus,
NotFoundException,
Logger,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth } from '@nestjs/swagger';
import { UsersService, UpdateUserDto } from './users.service';
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
import { CurrentUser, JwtPayload } from '../../common/decorators/current-user.decorator';
import { UserResponseDto, UserStatsDto, UpdateProfileDto } from './dto';
import { SubscriptionService } from '../subscription/subscription.service';
@ApiTags('Users')
@Controller('users')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
export class UsersController {
private readonly logger = new Logger(UsersController.name);
constructor(
private readonly usersService: UsersService,
private readonly subscriptionService: SubscriptionService,
) {}
@Get('me')
@ApiOperation({ summary: 'Get current user profile' })
@ApiResponse({ status: 200, description: 'User profile', type: UserResponseDto })
async getProfile(@CurrentUser() user: JwtPayload) {
const profile = await this.usersService.findById(user.sub);
if (!profile) {
throw new NotFoundException('User not found');
}
// Fetch full subscription details
let plan = 'free';
let subscriptionData = null;
try {
const subscription = await this.subscriptionService.getOrCreateSubscription(
user.sub,
profile.email,
);
plan = subscription?.plan || 'free';
// Include full subscription object in response
subscriptionData = {
plan: subscription.plan,
status: subscription.status,
currentPeriodStart: subscription.currentPeriodStart,
currentPeriodEnd: subscription.currentPeriodEnd,
cancelAtPeriodEnd: subscription.cancelAtPeriodEnd,
};
} catch (err) {
this.logger.warn(
`Failed to fetch subscription for user ${user.sub}: ${(err as Error).message}`,
);
}
// Normalize: monthly/yearly → 'pro' for frontend, keep raw for billing
const planDisplay = plan === 'monthly' || plan === 'yearly' ? 'pro' : 'free';
return {
id: profile.id,
email: profile.email,
name: profile.name,
avatarUrl: profile.avatarUrl,
role: profile.role,
emailVerified: profile.emailVerified,
educationLevel: profile.educationLevel,
subjects: profile.subjects,
profileCompleted: profile.profileCompleted,
preferences: profile.preferences,
plan: planDisplay,
billingCycle: plan === 'free' ? null : plan,
subscription: subscriptionData,
createdAt: profile.createdAt,
};
}
@Put('me')
@ApiOperation({ summary: 'Update current user profile' })
@ApiResponse({ status: 200, description: 'Profile updated', type: UserResponseDto })
async updateProfile(@CurrentUser() user: JwtPayload, @Body() dto: UpdateProfileDto) {
const updateDto: UpdateUserDto = {};
if (dto.name !== undefined) updateDto.name = dto.name;
if (dto.avatarUrl !== undefined) updateDto.avatarUrl = dto.avatarUrl;
if (dto.educationLevel !== undefined) updateDto.educationLevel = dto.educationLevel;
if (dto.subjects !== undefined) updateDto.subjects = dto.subjects;
if (dto.profileCompleted !== undefined) updateDto.profileCompleted = dto.profileCompleted;
if (dto.preferences !== undefined) updateDto.preferences = dto.preferences;
const profile = await this.usersService.update(user.sub, updateDto);
// Fetch full subscription details
let plan = 'free';
let subscriptionData = null;
try {
const subscription = await this.subscriptionService.getOrCreateSubscription(
user.sub,
profile.email,
);
plan = subscription?.plan || 'free';
// Include full subscription object in response
subscriptionData = {
plan: subscription.plan,
status: subscription.status,
currentPeriodStart: subscription.currentPeriodStart,
currentPeriodEnd: subscription.currentPeriodEnd,
cancelAtPeriodEnd: subscription.cancelAtPeriodEnd,
};
} catch (err) {
this.logger.warn(
`Failed to fetch subscription for user ${user.sub}: ${(err as Error).message}`,
);
}
const planDisplay = plan === 'monthly' || plan === 'yearly' ? 'pro' : 'free';
return {
id: profile.id,
email: profile.email,
name: profile.name,
avatarUrl: profile.avatarUrl,
role: profile.role,
emailVerified: profile.emailVerified,
educationLevel: profile.educationLevel,
subjects: profile.subjects,
profileCompleted: profile.profileCompleted,
preferences: profile.preferences,
plan: planDisplay,
billingCycle: plan === 'free' ? null : plan,
subscription: subscriptionData,
createdAt: profile.createdAt,
};
}
@Delete('me')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Delete current user account' })
@ApiResponse({ status: 204, description: 'Account deleted' })
async deleteAccount(@CurrentUser() user: JwtPayload): Promise<void> {
await this.usersService.delete(user.sub);
}
@Get('me/stats')
@ApiOperation({ summary: 'Get current user statistics' })
@ApiResponse({ status: 200, description: 'User stats', type: UserStatsDto })
async getStats(@CurrentUser() user: JwtPayload): Promise<UserStatsDto> {
return this.usersService.getStats(user.sub);
}
@Get('me/gamification')
@ApiOperation({ summary: 'Get current user gamification stats (XP, level, streak)' })
@ApiResponse({ status: 200, description: 'Gamification stats' })
async getGamification(@CurrentUser() user: JwtPayload) {
return this.usersService.getGamification(user.sub);
}
@Post('me/xp')
@ApiOperation({ summary: 'Add XP event for current user' })
@ApiResponse({ status: 201, description: 'XP added' })
async addXp(@CurrentUser() user: JwtPayload, @Body() body: { type: string; xp: number }) {
await this.usersService.addXp(user.sub, body.type, body.xp);
return { success: true };
}
@Get(':id')
@ApiOperation({ summary: 'Get user by ID (public profile)' })
@ApiResponse({ status: 200, description: 'User profile', type: UserResponseDto })
@ApiResponse({ status: 404, description: 'User not found' })
async getUserById(@Param('id') id: string): Promise<Partial<UserResponseDto>> {
const user = await this.usersService.findById(id);
if (!user) {
throw new Error('User not found');
}
return {
id: user.id,
name: user.name,
avatarUrl: user.avatarUrl,
createdAt: user.createdAt,
};
}
}