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

100% Statements 46/46
100% Branches 10/10
100% Functions 21/21
100% Lines 44/44

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 180 181 182 183 184 185 186 187                  7x           7x 6x     6x     9x       6x         6x                                       7x               7x 6x 3x   3x 3x   4x               4x             4x                 7x                             18x 18x 11x   7x     7x                             7x       6x 6x 6x 9x 11x   9x 2x         7x   6x       9x   6x       6x 9x 2x   7x 5x   7x 7x   7x                 7x       7x                
import { TRPCError } from "@trpc/server";
import { z } from "zod";
 
import type { UserId } from "~db/ids";
import { queueCallFactory } from "~web/handlers/batch";
import type { AuthorizedContext } from "~web/handlers/context";
import { authProcedure } from "~web/handlers/trpc";
import { debtIdSchema } from "~web/handlers/validation";
 
const acceptIntentionSchema = z.strictObject({
	id: debtIdSchema,
});
 
type Input = z.infer<typeof acceptIntentionSchema>;
 
const fetchIntentions = (ctx: AuthorizedContext, inputs: readonly Input[]) =>
	ctx.database
		.selectFrom("debts as theirDebts")
		.where((eb) =>
			eb(
				"theirDebts.id",
				"in",
				inputs.map((input) => input.id),
			).and("theirDebts.ownerUserId", "<>", ctx.auth.userId),
		)
		.innerJoin("peers", (qb) =>
			qb
				.onRef("peers.connectedUserId", "=", "theirDebts.ownerUserId")
				.on("peers.ownerUserId", "=", ctx.auth.userId),
		)
		.leftJoin("debts as selfDebts", (qb) =>
			qb
				.onRef("selfDebts.id", "=", "theirDebts.id")
				.on("selfDebts.ownerUserId", "=", ctx.auth.userId),
		)
		.select([
			"theirDebts.id",
			"theirDebts.ownerUserId",
			"theirDebts.updatedAt",
			"theirDebts.amount",
			"theirDebts.note",
			"theirDebts.timestamp",
			"theirDebts.currencyCode",
			"theirDebts.receiptId",
			"selfDebts.id as selfId",
			"peers.id as foreignPeerId",
		])
		.execute();
 
type FetchedIntention = Awaited<ReturnType<typeof fetchIntentions>>[number];
 
const acceptUpdatedIntentions = async (
	ctx: AuthorizedContext,
	ownerUserId: UserId,
	intentions: Pick<
		FetchedIntention,
		"id" | "amount" | "currencyCode" | "selfId" | "timestamp"
	>[],
) => {
	const updatedIntentions = intentions.filter((intention) => intention.selfId);
	if (updatedIntentions.length === 0) {
		return [];
	}
	return ctx.database.transaction().execute((tx) =>
		Promise.all(
			updatedIntentions.map(async (intentionToUpdate) => {
				const { id, updatedAt } = await tx
					.updateTable("debts")
					.set({
						amount: (Number(intentionToUpdate.amount) * -1).toString(),
						currencyCode: intentionToUpdate.currencyCode,
						timestamp: intentionToUpdate.timestamp,
					})
					.where((eb) =>
						eb.and({
							id: intentionToUpdate.id,
							ownerUserId,
						}),
					)
					.returning(["debts.id", "debts.updatedAt"])
					.executeTakeFirstOrThrow();
				return {
					id,
					updatedAt,
				};
			}),
		),
	);
};
 
export const acceptNewIntentions = async (
	ctx: AuthorizedContext,
	ownerUserId: UserId,
	intentions: Pick<
		FetchedIntention,
		| "id"
		| "selfId"
		| "foreignPeerId"
		| "currencyCode"
		| "amount"
		| "timestamp"
		| "note"
		| "receiptId"
	>[],
) => {
	const createdIntentions = intentions.filter((intention) => !intention.selfId);
	if (createdIntentions.length === 0) {
		return [];
	}
	return ctx.database
		.insertInto("debts")
		.values(
			createdIntentions.map((intention) => ({
				id: intention.id,
				ownerUserId,
				peerId: intention.foreignPeerId,
				currencyCode: intention.currencyCode,
				amount: (Number(intention.amount) * -1).toString(),
				timestamp: intention.timestamp,
				note: intention.note,
				receiptId: intention.receiptId,
			})),
		)
		.returning(["debts.id", "debts.updatedAt"])
		.execute();
};
 
const queueAcceptIntention = queueCallFactory<
	AuthorizedContext,
	Input,
	{ updatedAt: Temporal.ZonedDateTime }
>((ctx) => async (inputs) => {
	const intentions = await fetchIntentions(ctx, inputs);
	const intentionsOrErrors = inputs.map((input) => {
		const matchedIntention = intentions.find(
			(intention) => intention.id === input.id,
		);
		if (!matchedIntention) {
			return new TRPCError({
				code: "NOT_FOUND",
				message: `Intention for debt "${input.id}" is not found.`,
			});
		}
		return matchedIntention;
	});
	const intentionsToAccept = intentionsOrErrors.filter(
		(
			intentionOrError,
		): intentionOrError is Exclude<typeof intentionOrError, TRPCError> =>
			!(intentionOrError instanceof TRPCError),
	);
	const [updatedIntentions, newIntentions] = await Promise.all([
		acceptUpdatedIntentions(ctx, ctx.auth.userId, intentionsToAccept),
		acceptNewIntentions(ctx, ctx.auth.userId, intentionsToAccept),
	]);
	return intentionsOrErrors.map((intentionOrError) => {
		if (intentionOrError instanceof TRPCError) {
			return intentionOrError;
		}
		const matchedNewIntention = newIntentions.find(
			(intention) => intention.id === intentionOrError.id,
		);
		const matchedUpdatedIntention = updatedIntentions.find(
			(intention) => intention.id === intentionOrError.id,
		);
		const anyIntention = matchedNewIntention || matchedUpdatedIntention;
		/* c8 ignore start */
		if (!anyIntention) {
			return new TRPCError({
				code: "INTERNAL_SERVER_ERROR",
				message: `Expected to have an accepted intention id "${intentionOrError.id}".`,
			});
		}
		/* c8 ignore stop */
		return { updatedAt: anyIntention.updatedAt };
	});
});
 
export const procedure = authProcedure
	.meta({
		title: "Accept debt intention",
		description:
			"Accepts a counterparty's pending debt change for a given debt id by creating or updating the mirrored debt on the current  user.",
	})
	.input(acceptIntentionSchema)
	.mutation(queueAcceptIntention);