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

100% Statements 39/39
100% Branches 16/16
100% Functions 14/14
100% Lines 39/39

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                                7x                       7x       8x   14x   8x     8x     8x             7x         8x 14x 15x   14x 2x         12x 3x 3x 1x         2x 2x 1x           10x 10x                 7x       8x 3x   5x             7x         8x 8x 8x 8x       14x     8x 14x 4x   10x 16x                   10x       7x                
import { TRPCError } from "@trpc/server";
import { unique } from "remeda";
import { z } from "zod";
 
import {
	priceSchema,
	quantitySchema,
	receiptItemNameSchema,
} from "~app/utils/validation";
import type { ReceiptItemId } from "~db/ids";
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 { receiptIdSchema, roleSchema } from "~web/handlers/validation";
 
export const addItemSchema = z.strictObject({
	receiptId: receiptIdSchema,
	name: receiptItemNameSchema,
	price: priceSchema,
	quantity: quantitySchema,
});
 
export type ItemOutput = {
	id: ReceiptItemId;
	createdAt: Temporal.ZonedDateTime;
};
 
const getData = async (
	ctx: AuthorizedContext,
	items: readonly z.infer<typeof addItemSchema>[],
) =>
	ctx.database
		.selectFrom("receipts")
		.where("receipts.id", "in", unique(items.map((item) => item.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),
		)
		.select(["receipts.ownerUserId", "receipts.id", "receiptParticipants.role"])
		.execute();
 
const getItemsOrErrors = (
	ctx: AuthorizedContext,
	items: readonly z.infer<typeof addItemSchema>[],
	receipts: Awaited<ReturnType<typeof getData>>,
) =>
	items.map((item) => {
		const matchedReceipt = receipts.find(
			(receipt) => receipt.id === item.receiptId,
		);
		if (!matchedReceipt) {
			return new TRPCError({
				code: "NOT_FOUND",
				message: `Receipt "${item.receiptId}" does not exist.`,
			});
		}
		if (matchedReceipt.ownerUserId !== ctx.auth.userId) {
			const parsed = roleSchema.safeParse(matchedReceipt.role);
			if (!matchedReceipt.role || !parsed.success) {
				return new TRPCError({
					code: "FORBIDDEN",
					message: `Receipt "${item.receiptId}" is not allowed to be modified by "${ctx.auth.email}"`,
				});
			}
			const accessRole = parsed.data;
			if (accessRole !== "owner" && accessRole !== "editor") {
				return new TRPCError({
					code: "FORBIDDEN",
					message: `Receipt "${item.receiptId}" is not allowed to be modified by "${ctx.auth.email}" with role "${accessRole}"`,
				});
			}
		}
		const id: ReceiptItemId = ctx.getUuid();
		return {
			id,
			name: item.name,
			price: item.price.toString(),
			quantity: item.quantity.toString(),
			receiptId: item.receiptId,
		};
	});
 
const insertItems = (
	ctx: AuthorizedContext,
	items: Exclude<ReturnType<typeof getItemsOrErrors>[number], TRPCError>[],
) => {
	if (items.length === 0) {
		return [];
	}
	return ctx.database
		.insertInto("receiptItems")
		.values(items)
		.returning(["receiptItems.createdAt", "receiptItems.id"])
		.execute();
};
 
export const batchFn: BatchLoadContextFn<
	AuthorizedContext,
	z.infer<typeof addItemSchema>,
	ItemOutput,
	TRPCError
> = (ctx) => async (inputs) => {
	const data = await getData(ctx, inputs);
	const itemsOrErrors = getItemsOrErrors(ctx, inputs, data);
	const insertedItems = await insertItems(
		ctx,
		itemsOrErrors.filter(
			(item): item is Exclude<typeof item, TRPCError> =>
				!(item instanceof TRPCError),
		),
	);
	return itemsOrErrors.map((itemOrError) => {
		if (itemOrError instanceof TRPCError) {
			return itemOrError;
		}
		const matchedItem = insertedItems.find(
			(insertedItem) => insertedItem.id === itemOrError.id,
		);
		/* c8 ignore start */
		if (!matchedItem) {
			return new TRPCError({
				code: "INTERNAL_SERVER_ERROR",
				message: `Expected to have matched inserted item for id "${itemOrError.id}".`,
			});
		}
		/* c8 ignore stop */
		return { id: itemOrError.id, createdAt: matchedItem.createdAt };
	});
};
 
export const procedure = authProcedure
	.meta({
		title: "Add receipt item",
		description:
			"Adds a new item with a name, price and quantity to a given receiptId.",
	})
	.input(addItemSchema)
	.mutation(queueCallFactory(batchFn));