All files / apps/web/src/handlers/debts remove.ts

100% Statements 12/12
100% Branches 2/2
100% Functions 5/5
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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            6x                       5x 5x     5x           5x         5x         5x 2x         3x 3x       1x     3x    
import { TRPCError } from "@trpc/server";
import { z } from "zod";
 
import { authProcedure } from "~web/handlers/trpc";
import { debtIdSchema } from "~web/handlers/validation";
 
export const procedure = authProcedure
	.meta({
		title: "Remove debt",
		description:
			"Removes a debt owned by the current  user, and the counterparty's mirrored debt unless they require manual acceptance.",
	})
	.input(
		z.strictObject({
			id: debtIdSchema,
		}),
	)
	.mutation(async ({ input, ctx }) => {
		const { database } = ctx;
		const debt = await database
			.selectFrom("debts")
			.where((eb) =>
				eb.and({
					"debts.id": input.id,
					"debts.ownerUserId": ctx.auth.userId,
				}),
			)
			.innerJoin("peers", (qb) =>
				qb
					.onRef("peers.id", "=", "debts.peerId")
					.onRef("peers.ownerUserId", "=", "debts.ownerUserId"),
			)
			.leftJoin("userSettings", (qb) =>
				qb.onRef("peers.connectedUserId", "=", "userSettings.userId"),
			)
			.select(["userSettings.manualAcceptDebts"])
			.limit(1)
			.executeTakeFirst();
		if (!debt) {
			throw new TRPCError({
				code: "NOT_FOUND",
				message: `No debt found by id "${input.id}" on  user "${ctx.auth.email}"`,
			});
		}
		const reverseRemoved = !debt.manualAcceptDebts;
		const deleteResult = await database
			.deleteFrom("debts")
			.where("id", "=", input.id)
			.$if(!reverseRemoved, (qb) =>
				qb.where("ownerUserId", "=", ctx.auth.userId),
			)
			.executeTakeFirst();
		return { reverseRemoved: Number(deleteResult.numDeletedRows) > 1 };
	});