All files / apps/web/src/handlers/user-connection-intentions accept.ts

100% Statements 32/32
100% Branches 18/18
100% Functions 11/11
100% Lines 30/30

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 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                6x                         11x 11x     11x         11x                     11x 1x         10x 1x         9x 1x         8x     8x                     15x 8x 1x         7x     7x           7x               7x 1x         6x     6x   6x 6x 6x                                                               6x       2x                           2x                       6x            
import { TRPCError } from "@trpc/server";
import assert from "node:assert";
import { z } from "zod";
 
import { acceptNewIntentions } from "~web/handlers/debt-intentions/accept";
import { authProcedure } from "~web/handlers/trpc";
import { peerIdSchema, userIdSchema } from "~web/handlers/validation";
 
export const procedure = authProcedure
	.meta({
		title: "Accept  user connection intention",
		description:
			"Accepts an inbound  user connection intention from a given userId, merging the matching peers and their debts.",
	})
	.input(
		z.strictObject({
			userId: userIdSchema,
			peerId: peerIdSchema,
		}),
	)
	.mutation(async ({ input, ctx }) => {
		const { database } = ctx;
		const peer = await ctx.database
			.selectFrom("peers")
			.leftJoin("peers as reciprocalPeers", (qb) =>
				qb
					.onRef("reciprocalPeers.ownerUserId", "=", "peers.connectedUserId")
					.onRef("reciprocalPeers.connectedUserId", "=", "peers.ownerUserId"),
			)
			.leftJoin("users", (qb) =>
				qb.onRef("peers.connectedUserId", "=", "users.id"),
			)
			.select([
				"peers.id",
				"users.email",
				"peers.ownerUserId",
				"reciprocalPeers.id as reciprocalPeerId",
			])
			.where("peers.id", "=", input.peerId)
			.limit(1)
			.executeTakeFirst();
		if (!peer) {
			throw new TRPCError({
				code: "NOT_FOUND",
				message: `Peer "${input.peerId}" does not exist.`,
			});
		}
		if (peer.ownerUserId !== ctx.auth.userId) {
			throw new TRPCError({
				code: "FORBIDDEN",
				message: `Peer "${input.peerId}" is not owned by "${ctx.auth.email}".`,
			});
		}
		if (peer.email && peer.reciprocalPeerId) {
			throw new TRPCError({
				code: "CONFLICT",
				message: `Peer "${input.peerId}" is already connected to an  user with email "${peer.email}".`,
			});
		}
		const users = await database
			.selectFrom("users")
			.leftJoin("userSettings", (jb) =>
				jb.onRef("userSettings.userId", "=", "users.id"),
			)
			.select([
				"users.id",
				"users.email",
				"users.avatarUrl",
				"userSettings.manualAcceptDebts",
			])
			.where("users.id", "in", [input.userId, ctx.auth.userId])
			.limit(2)
			.execute();
		const targetUser = users.find((user) => user.id === input.userId);
		if (!targetUser) {
			throw new TRPCError({
				code: "NOT_FOUND",
				message: `User with id "${input.userId}" does not exist.`,
			});
		}
		const intention = await database
			.selectFrom("peers")
			.leftJoin("peers as reciprocalPeers", (qb) =>
				qb
					.onRef("reciprocalPeers.ownerUserId", "=", "peers.connectedUserId")
					.onRef("reciprocalPeers.connectedUserId", "=", "peers.ownerUserId"),
			)
			.select("peers.id as peerId")
			.where((eb) =>
				eb.and({
					"peers.ownerUserId": targetUser.id,
					"peers.connectedUserId": ctx.auth.userId,
				}),
			)
			.where("reciprocalPeers.id", "is", null)
			.limit(1)
			.executeTakeFirst();
		if (!intention) {
			throw new TRPCError({
				code: "NOT_FOUND",
				message: `Intention from  user "${targetUser.email}" not found.`,
			});
		}
		await database
			.updateTable("peers")
			.set({ connectedUserId: targetUser.id })
			.where((eb) => eb.and({ ownerUserId: ctx.auth.userId, id: input.peerId }))
			.executeTakeFirst();
		const selfUser = users.find((user) => user.id === ctx.auth.userId);
		assert.ok(selfUser, "Expected to have self  user in  user list");
		const [outboundDebts, inboundDebts] = await Promise.all([
			targetUser.manualAcceptDebts
				? []
				: database
						.selectFrom("debts")
						.where("debts.ownerUserId", "=", ctx.auth.userId)
						.where("debts.peerId", "=", input.peerId)
						.select([
							"debts.id",
							"debts.amount",
							"debts.currencyCode",
							"debts.note",
							"debts.receiptId",
							"debts.timestamp",
						])
						.execute(),
			selfUser.manualAcceptDebts
				? []
				: database
						.selectFrom("debts")
						.where("debts.ownerUserId", "=", targetUser.id)
						.where("debts.peerId", "=", intention.peerId)
						.select([
							"debts.id",
							"debts.amount",
							"debts.currencyCode",
							"debts.note",
							"debts.receiptId",
							"debts.timestamp",
						])
						.execute(),
		]);
		await Promise.all([
			acceptNewIntentions(
				ctx,
				targetUser.id,
				outboundDebts.map((debt) => ({
					id: debt.id,
					currencyCode: debt.currencyCode,
					amount: debt.amount,
					timestamp: debt.timestamp,
					note: debt.note,
					receiptId: debt.receiptId,
					foreignPeerId: intention.peerId,
					selfId: null,
				})),
			),
			acceptNewIntentions(
				ctx,
				ctx.auth.userId,
				inboundDebts.map((debt) => ({
					id: debt.id,
					currencyCode: debt.currencyCode,
					amount: debt.amount,
					timestamp: debt.timestamp,
					note: debt.note,
					receiptId: debt.receiptId,
					foreignPeerId: input.peerId,
					selfId: null,
				})),
			),
		]);
		return {
			email: targetUser.email,
			id: targetUser.id,
			avatarUrl: targetUser.avatarUrl || undefined,
		};
	});