-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgroups.service.ts
More file actions
443 lines (384 loc) · 13.6 KB
/
Copy pathgroups.service.ts
File metadata and controls
443 lines (384 loc) · 13.6 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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
import { ConflictException, ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
import { GroupDefaultSplitDto, GroupDto, GroupMemberSummaryDto, GroupSummaryDto } from '@fairshare/shared-types';
import { PrismaService } from '../common/prisma.service';
import { RedisService } from '../redis/redis.service';
import { NotificationsService } from '../notifications/notifications.service';
import { RealtimeService } from '../realtime/realtime.service';
import { CreateGroupDto } from './dto/create-group.dto';
import { InviteMemberDto } from './dto/invite-member.dto';
import { UpdateGroupDefaultSplitDto } from './dto/update-group-default-split.dto';
@Injectable()
export class GroupsService {
constructor(
private readonly prisma: PrismaService,
private readonly redis: RedisService,
private readonly notificationsService: NotificationsService,
private readonly realtime: RealtimeService,
) {}
async create(userId: string, dto: CreateGroupDto): Promise<GroupDto> {
const group = await this.prisma.$transaction(async (tx) => {
const created = await tx.group.create({
data: {
name: dto.name,
currency: dto.currency,
createdBy: userId,
},
});
await tx.groupMember.create({
data: {
groupId: created.id,
userId,
role: 'OWNER',
},
});
await tx.activity.create({
data: {
groupId: created.id,
actorUserId: userId,
type: 'member_joined',
entityId: created.id,
metadata: { role: 'OWNER' },
},
});
return created;
});
return {
id: group.id,
name: group.name,
currency: group.currency as 'USD' | 'EUR' | 'INR',
createdBy: group.createdBy,
createdAt: group.createdAt.toISOString(),
defaultSplitPreference: null,
};
}
async list(userId: string): Promise<GroupDto[]> {
const groups = await this.prisma.group.findMany({
where: {
members: {
some: {
userId,
},
},
},
orderBy: { createdAt: 'desc' },
});
return groups.map((group) => ({
id: group.id,
name: group.name,
currency: group.currency as 'USD' | 'EUR' | 'INR',
createdBy: group.createdBy,
createdAt: group.createdAt.toISOString(),
defaultSplitPreference: this.parseDefaultSplitPreference(group.defaultSplitType, group.defaultSplitConfig),
}));
}
async getById(id: string, actorUserId: string): Promise<GroupDto> {
await this.assertMembership(id, actorUserId);
const cached = await this.redis.getGroupMembersCache(id);
if (cached) {
return JSON.parse(cached) as GroupDto;
}
const group = await this.prisma.group.findUnique({
where: { id },
include: { members: true },
});
if (!group) {
throw new NotFoundException('Group not found');
}
const response: GroupDto = {
id: group.id,
name: group.name,
currency: group.currency as 'USD' | 'EUR' | 'INR',
createdBy: group.createdBy,
createdAt: group.createdAt.toISOString(),
defaultSplitPreference: this.parseDefaultSplitPreference(group.defaultSplitType, group.defaultSplitConfig),
members: group.members.map((member) => ({
id: member.id,
userId: member.userId,
groupId: member.groupId,
role: member.role,
joinedAt: member.joinedAt.toISOString(),
})),
};
await this.redis.setGroupMembersCache(id, JSON.stringify(response));
return response;
}
async members(groupId: string, actorUserId: string): Promise<GroupMemberSummaryDto[]> {
await this.assertMembership(groupId, actorUserId);
const members = await this.prisma.groupMember.findMany({
where: { groupId },
include: { user: true },
orderBy: { joinedAt: 'asc' },
});
return members.map((member) => ({
memberId: member.id,
userId: member.userId,
name: member.user.name,
email: member.user.email,
avatarUrl: member.user.avatarUrl,
role: member.role,
}));
}
async summary(groupId: string, actorUserId: string): Promise<GroupSummaryDto> {
await this.assertMembership(groupId, actorUserId);
const cached = await this.redis.getGroupSummaryCache(groupId);
if (cached) {
return JSON.parse(cached) as GroupSummaryDto;
}
const [expenses, settlements, balances] = await Promise.all([
this.prisma.expense.findMany({
where: { groupId },
orderBy: { createdAt: 'desc' },
select: { totalAmountCents: true, payerId: true, createdAt: true },
}),
this.prisma.settlement.findMany({
where: { groupId },
select: { amountCents: true },
}),
this.prisma.balance.findMany({
where: { groupId },
select: { userId: true, amountCents: true },
}),
]);
const perUserSpent: Record<string, bigint> = {};
const perUserOwed: Record<string, bigint> = {};
let totalExpenses = 0n;
let largestExpense: bigint | null = null;
expenses.forEach((expense) => {
totalExpenses += expense.totalAmountCents;
perUserSpent[expense.payerId] = (perUserSpent[expense.payerId] ?? 0n) + expense.totalAmountCents;
if (largestExpense === null || expense.totalAmountCents > largestExpense) {
largestExpense = expense.totalAmountCents;
}
});
let totalSettled = 0n;
settlements.forEach((settlement) => {
totalSettled += settlement.amountCents;
});
balances.forEach((balance) => {
if (balance.amountCents < 0n) {
perUserOwed[balance.userId] = (perUserOwed[balance.userId] ?? 0n) + balance.amountCents * -1n;
}
});
const topSpenderEntry = Object.entries(perUserSpent).sort((a, b) => Number(b[1] - a[1]))[0];
const response: GroupSummaryDto = {
totalExpensesCents: totalExpenses.toString(),
totalSettledCents: totalSettled.toString(),
perUserSpentCents: Object.fromEntries(Object.entries(perUserSpent).map(([k, v]) => [k, v.toString()])),
perUserOwedCents: Object.fromEntries(Object.entries(perUserOwed).map(([k, v]) => [k, v.toString()])),
largestExpenseCents: largestExpense !== null ? String(largestExpense) : null,
lastExpenseCents: expenses.length > 0 ? expenses[0].totalAmountCents.toString() : null,
topSpenderUserId: topSpenderEntry?.[0] ?? null,
};
await this.redis.setGroupSummaryCache(groupId, JSON.stringify(response), 120);
return response;
}
async getUserSummary(userId: string): Promise<{ totalBalanceCents: string }> {
const balances = await this.prisma.balance.findMany({
where: { userId },
select: { amountCents: true },
});
const totalBalance = balances.reduce((acc, curr) => acc + curr.amountCents, 0n);
return {
totalBalanceCents: totalBalance.toString(),
};
}
async updateDefaultSplit(groupId: string, actorUserId: string, dto: UpdateGroupDefaultSplitDto): Promise<GroupDto> {
await this.assertMembership(groupId, actorUserId);
let normalizedPreference: GroupDefaultSplitDto | null = null;
if (dto.defaultSplitPreference) {
const members = await this.prisma.groupMember.findMany({
where: { groupId },
select: { userId: true },
});
const memberIds = new Set(members.map((member) => member.userId));
const participantUserIds = Array.from(new Set(dto.defaultSplitPreference.participantUserIds));
if (participantUserIds.length === 0) {
throw new ForbiddenException('Default split must include at least one participant');
}
const invalidParticipant = participantUserIds.find((userId) => !memberIds.has(userId));
if (invalidParticipant) {
throw new ForbiddenException('Default split participants must belong to the group');
}
normalizedPreference = {
splitType: dto.defaultSplitPreference.splitType,
participantUserIds,
exactAmountsCentsByUser: dto.defaultSplitPreference.exactAmountsCentsByUser,
percentagesByUser: dto.defaultSplitPreference.percentagesByUser,
};
}
await this.prisma.group.update({
where: { id: groupId },
data: {
defaultSplitType: normalizedPreference?.splitType ?? null,
defaultSplitConfig: normalizedPreference
? JSON.stringify({
participantUserIds: normalizedPreference.participantUserIds,
exactAmountsCentsByUser: normalizedPreference.exactAmountsCentsByUser ?? {},
percentagesByUser: normalizedPreference.percentagesByUser ?? {},
})
: null,
},
});
const group = await this.prisma.group.findUniqueOrThrow({
where: { id: groupId },
include: { members: true },
});
await this.redis.invalidateGroupCache(groupId);
return {
id: group.id,
name: group.name,
currency: group.currency as 'USD' | 'EUR' | 'INR',
createdBy: group.createdBy,
createdAt: group.createdAt.toISOString(),
defaultSplitPreference: this.parseDefaultSplitPreference(group.defaultSplitType, group.defaultSplitConfig),
members: group.members.map((member) => ({
id: member.id,
userId: member.userId,
groupId: member.groupId,
role: member.role,
joinedAt: member.joinedAt.toISOString(),
})),
};
}
async invite(groupId: string, actorUserId: string, dto: InviteMemberDto): Promise<{ success: true }> {
await this.assertMembership(groupId, actorUserId);
const email = dto.email.toLowerCase();
const user = await this.prisma.user.findUnique({ where: { email } });
if (!user) {
await this.prisma.groupInvite.upsert({
where: {
groupId_email: {
groupId,
email,
},
},
create: {
groupId,
email,
invitedBy: actorUserId,
role: 'MEMBER',
},
update: {},
});
return { success: true };
}
const existingMembership = await this.prisma.groupMember.findUnique({
where: {
groupId_userId: {
groupId,
userId: user.id,
},
},
});
if (existingMembership) {
throw new ConflictException('User is already a group member');
}
await this.prisma.$transaction(async (tx) => {
await tx.groupMember.create({
data: {
groupId,
userId: user.id,
role: 'MEMBER',
},
});
await tx.activity.create({
data: {
groupId,
actorUserId,
type: 'member_invited',
entityId: user.id,
metadata: {
invitedUserId: user.id,
invitedEmail: user.email,
},
},
});
});
await this.notificationsService.sendPushNotification([user.id], {
type: 'group_invite',
title: 'You were invited',
body: 'You have been added to a FairShare group.',
data: { groupId, notificationType: 'group_invite' },
});
await this.redis.invalidateGroupCache(groupId);
this.realtime.emitToGroup(groupId, 'group_member_joined', {
groupId,
userId: user.id,
email: user.email,
});
return { success: true };
}
async resolvePendingInvites(userId: string, email: string): Promise<void> {
const invites = await this.prisma.groupInvite.findMany({
where: { email: email.toLowerCase() },
});
if (invites.length === 0) {
return;
}
await this.prisma.$transaction(async (tx) => {
for (const invite of invites) {
await tx.groupMember.create({
data: {
groupId: invite.groupId,
userId,
role: invite.role,
},
});
await tx.activity.create({
data: {
groupId: invite.groupId,
actorUserId: invite.invitedBy,
type: 'member_joined',
entityId: userId,
metadata: { role: invite.role },
},
});
await tx.groupInvite.delete({
where: { id: invite.id },
});
await this.redis.invalidateGroupCache(invite.groupId);
}
});
}
private parseDefaultSplitPreference(splitType: string | null, splitConfig: string | null): GroupDefaultSplitDto | null {
if (!splitType || !splitConfig) {
return null;
}
try {
const config = JSON.parse(splitConfig) as {
participantUserIds?: unknown;
exactAmountsCentsByUser?: unknown;
percentagesByUser?: unknown;
};
return {
splitType: splitType as GroupDefaultSplitDto['splitType'],
participantUserIds: Array.isArray(config.participantUserIds)
? config.participantUserIds.filter((value): value is string => typeof value === 'string')
: [],
exactAmountsCentsByUser:
config.exactAmountsCentsByUser && typeof config.exactAmountsCentsByUser === 'object' && !Array.isArray(config.exactAmountsCentsByUser)
? (config.exactAmountsCentsByUser as Record<string, string>)
: undefined,
percentagesByUser:
config.percentagesByUser && typeof config.percentagesByUser === 'object' && !Array.isArray(config.percentagesByUser)
? (config.percentagesByUser as Record<string, string>)
: undefined,
};
} catch {
return null;
}
}
private async assertMembership(groupId: string, userId: string): Promise<void> {
const membership = await this.prisma.groupMember.findUnique({
where: {
groupId_userId: {
groupId,
userId,
},
},
});
if (!membership) {
throw new ForbiddenException('Actor is not a group member');
}
}
}