Skip to content

Commit 1dc3dd0

Browse files
committed
Include simplify debts in backend checks
1 parent f348b73 commit 1dc3dd0

File tree

1 file changed

+23
-16
lines changed

1 file changed

+23
-16
lines changed

src/server/api/routers/group.ts

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -239,22 +239,6 @@ export const groupRouter = createTRPCRouter({
239239
.input(z.object({ groupId: z.number(), userId: z.number().optional() }))
240240
.mutation(async ({ input, ctx }) => {
241241
const userId = input.userId ?? ctx.session.user.id;
242-
const nonZeroBalance = await ctx.db.groupBalance.findFirst({
243-
where: {
244-
groupId: input.groupId,
245-
userId,
246-
amount: {
247-
not: 0,
248-
},
249-
},
250-
});
251-
252-
if (nonZeroBalance) {
253-
throw new TRPCError({
254-
code: 'BAD_REQUEST',
255-
message: 'User has a non-zero balance in this group',
256-
});
257-
}
258242

259243
const group = await ctx.db.group.findUnique({
260244
where: {
@@ -272,6 +256,21 @@ export const groupRouter = createTRPCRouter({
272256
});
273257
}
274258

259+
const groupBalances = await ctx.db.groupBalance.findMany({
260+
where: {
261+
groupId: input.groupId,
262+
},
263+
});
264+
265+
const finalGroupBalances = group.simplifyDebts ? simplifyDebts(groupBalances) : groupBalances;
266+
267+
if (finalGroupBalances.some((b) => b.userId === userId && 0n !== b.amount)) {
268+
throw new TRPCError({
269+
code: 'BAD_REQUEST',
270+
message: 'User has a non-zero balance in this group',
271+
});
272+
}
273+
275274
const groupUser = await ctx.db.groupUser.delete({
276275
where: {
277276
groupId_userId: {
@@ -348,6 +347,10 @@ export const groupRouter = createTRPCRouter({
348347

349348
// Only check balances when archiving (not when unarchiving)
350349
if (isArchiving) {
350+
if (group?.simplifyDebts) {
351+
group.groupBalances = simplifyDebts(group.groupBalances);
352+
}
353+
351354
const balanceWithNonZero = group.groupBalances.find((b) => 0n !== b.amount);
352355

353356
if (balanceWithNonZero) {
@@ -387,6 +390,10 @@ export const groupRouter = createTRPCRouter({
387390
throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Only creator can delete the group' });
388391
}
389392

393+
if (group?.simplifyDebts) {
394+
group.groupBalances = simplifyDebts(group.groupBalances);
395+
}
396+
390397
const balanceWithNonZero = group?.groupBalances.find((b) => 0n !== b.amount);
391398

392399
if (balanceWithNonZero) {

0 commit comments

Comments
 (0)