All files / apps/web/src/handlers/receipt-item-payers add.ts

100% Statements 61/61
100% Branches 24/24
100% Functions 24/24
100% Lines 61/61

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 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                                    7x           7x         9x           14x     9x                 14x     9x     9x     9x     9x                                           9x   14x                           9x     7x                 9x 14x 24x   14x 14x 1x         13x 13x 3x 3x   3x 3x 1x         2x 2x 1x           11x   1x   11x 1x         10x 16x   10x 1x         9x             7x       9x 5x   4x                     7x         10x 10x   16x   10x 1x         1x         9x 9x 9x       14x     9x 14x 5x   9x   16x                     9x       7x                
import { TRPCError } from "@trpc/server";
import { unique } from "remeda";
import { z } from "zod";
 
import { partSchema } from "~app/utils/validation";
import type { BatchLoadContextFn } from "~web/handlers/batch";
import { queueCallFactory } from "~web/handlers/batch";
import type { AuthorizedContext } from "~web/handlers/context";
import { authProcedure } from "~web/handlers/trpc";
import {
	peerIdSchema,
	receiptItemIdSchema,
	roleSchema,
} from "~web/handlers/validation";
import { getDuplicates } from "~web/utils/batch";
 
export type PayerOutput = { createdAt: Temporal.ZonedDateTime };
 
export const addItemPayerSchema = z.strictObject({
	itemId: receiptItemIdSchema,
	peerId: peerIdSchema,
	part: partSchema,
});
 
const getData = async (
	ctx: AuthorizedContext,
	inputs: readonly z.infer<typeof addItemPayerSchema>[],
) => {
	const [receiptParticipants, receiptItems, receiptItemPayers] =
		await Promise.all([
			ctx.database
				.selectFrom("receiptParticipants")
				.where(
					"receiptParticipants.peerId",
					"in",
					unique(inputs.map((input) => input.peerId)),
				)
				.innerJoin("receipts", (qb) =>
					qb.onRef("receipts.id", "=", "receiptParticipants.receiptId"),
				)
				.select(["receiptParticipants.peerId"])
				.execute(),
			ctx.database
				.selectFrom("receiptItems")
				.where(
					"receiptItems.id",
					"in",
					unique(inputs.map((input) => input.itemId)),
				)
				.innerJoin("receipts", (qb) =>
					qb.onRef("receipts.id", "=", "receiptItems.receiptId"),
				)
				.leftJoin("receiptParticipants", (jb) =>
					jb.onRef("receipts.id", "=", "receiptParticipants.receiptId"),
				)
				.leftJoin("peers", (jb) =>
					jb.onRef("peers.id", "=", "receiptParticipants.peerId"),
				)
				.leftJoin("users", (jb) =>
					jb
						.onRef("users.id", "=", "peers.connectedUserId")
						.on("users.id", "=", ctx.auth.userId),
				)
				.groupBy([
					"users.id",
					"receipts.ownerUserId",
					"receipts.id",
					"receiptParticipants.role",
					"receiptItems.id",
				])
				.select([
					"users.id as selfUserId",
					"receipts.ownerUserId",
					"receipts.id as receiptId",
					"receiptParticipants.role",
					"receiptItems.id as itemId",
				])
				.execute(),
			ctx.database
				.selectFrom("receiptItemPayers")
				.where((eb) =>
					eb.or(
						inputs.map(({ itemId, peerId }) =>
							eb.and({
								"receiptItemPayers.itemId": itemId,
								"receiptItemPayers.peerId": peerId,
							}),
						),
					),
				)
				.select([
					"receiptItemPayers.part",
					"receiptItemPayers.peerId",
					"receiptItemPayers.itemId",
				])
				.execute(),
		]);
	return { receiptParticipants, receiptItems, receiptItemPayers };
};
 
const getPayersOrErrors = (
	ctx: AuthorizedContext,
	inputs: readonly z.infer<typeof addItemPayerSchema>[],
	{
		receiptItems,
		receiptParticipants,
		receiptItemPayers,
	}: Awaited<ReturnType<typeof getData>>,
) =>
	inputs.map((input) => {
		const matchedReceiptItems = receiptItems.filter(
			(receiptItem) => receiptItem.itemId === input.itemId,
		);
		const [firstReceiptItem] = matchedReceiptItems;
		if (!firstReceiptItem) {
			return new TRPCError({
				code: "NOT_FOUND",
				message: `Receipt item "${input.itemId}" does not exist.`,
			});
		}
		const { receiptId, ownerUserId } = firstReceiptItem;
		if (ownerUserId !== ctx.auth.userId) {
			const selfReceiptItemRole = matchedReceiptItems.find(
				(receiptItem) => receiptItem.selfUserId === ctx.auth.userId,
			)?.role;
			const parsed = roleSchema.safeParse(selfReceiptItemRole);
			if (!parsed.success) {
				return new TRPCError({
					code: "PRECONDITION_FAILED",
					message: `Peer "${input.peerId}" doesn't participate in receipt "${receiptId}".`,
				});
			}
			const accessRole = parsed.data;
			if (accessRole !== "owner" && accessRole !== "editor") {
				return new TRPCError({
					code: "FORBIDDEN",
					message: `Not enough rights to add item to receipt "${receiptId}".`,
				});
			}
		}
		const matchedReceiptItemPayer = receiptItemPayers.find(
			({ peerId, itemId }) =>
				peerId === input.peerId && itemId === input.itemId,
		);
		if (matchedReceiptItemPayer) {
			return new TRPCError({
				code: "CONFLICT",
				message: `Peer "${input.peerId}" already pays for item "${input.itemId}".`,
			});
		}
		const matchedPeer = receiptParticipants.find(
			(receiptParticipant) => receiptParticipant.peerId === input.peerId,
		);
		if (!matchedPeer) {
			return new TRPCError({
				code: "PRECONDITION_FAILED",
				message: `Peer "${input.peerId}" doesn't participate in receipt "${receiptId}".`,
			});
		}
		return {
			peerId: input.peerId,
			itemId: input.itemId,
			part: input.part.toString(),
		};
	});
 
const insertPayers = async (
	ctx: AuthorizedContext,
	payers: Exclude<ReturnType<typeof getPayersOrErrors>[number], TRPCError>[],
) => {
	if (payers.length === 0) {
		return [];
	}
	return ctx.database
		.insertInto("receiptItemPayers")
		.values(payers)
		.returning([
			"receiptItemPayers.createdAt",
			"receiptItemPayers.itemId",
			"receiptItemPayers.peerId",
		])
		.execute();
};
 
export const batchFn: BatchLoadContextFn<
	AuthorizedContext,
	z.infer<typeof addItemPayerSchema>,
	PayerOutput,
	TRPCError
> = (ctx) => async (inputs) => {
	const duplicatedTuples = getDuplicates(
		inputs,
		({ itemId, peerId }) => [itemId, peerId] as const,
	);
	if (duplicatedTuples.length !== 0) {
		throw new TRPCError({
			code: "CONFLICT",
			message: `Expected to have unique pair of item id and peer id, got repeating pairs: ${duplicatedTuples
				.map(
					([[itemId, peerId], count]) =>
						`item "${itemId}" / peer "${peerId}" (${count} times)`,
				)
				.join(", ")}.`,
		});
	}
	const data = await getData(ctx, inputs);
	const payersOrErrors = getPayersOrErrors(ctx, inputs, data);
	const insertedPayer = await insertPayers(
		ctx,
		payersOrErrors.filter(
			(payerOrError): payerOrError is Exclude<typeof payerOrError, TRPCError> =>
				!(payerOrError instanceof TRPCError),
		),
	);
	return payersOrErrors.map((itemOrError) => {
		if (itemOrError instanceof TRPCError) {
			return itemOrError;
		}
		const matchedPayer = insertedPayer.find(
			(payer) =>
				payer.itemId === itemOrError.itemId &&
				payer.peerId === itemOrError.peerId,
		);
		/* c8 ignore start */
		if (!matchedPayer) {
			return new TRPCError({
				code: "INTERNAL_SERVER_ERROR",
				message: `Expected to have a matched item payer in list of inserted rows for item id "${itemOrError.itemId}" and peer id "${itemOrError.peerId}".`,
			});
		}
		/* c8 ignore stop */
		return { createdAt: matchedPayer.createdAt };
	});
};
 
export const procedure = authProcedure
	.meta({
		title: "Add receipt item payer",
		description:
			"Assigns a participating peerId as a payer of a given receipt item with a given part share.",
	})
	.input(addItemPayerSchema)
	.mutation(queueCallFactory(batchFn));