All files / apps/web/src/handlers/receipts get.ts

100% Statements 55/55
100% Branches 14/14
100% Functions 28/28
100% Lines 51/51

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 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281                    6x       11x       11x                 11x                       11x                       11x                                                                               11x     11x                                     6x       11x   11x                   6x                                 9x 4x 2x 1x 2x 4x         5x 4x   9x   3x   9x 2x             3x 1x             2x               6x         9x 12x 15x 9x   6x       6x       9x                                     6x       11x 11x 11x       11x 11x 11x 1x         10x     5x     1x         9x 9x     6x   9x                 6x                        
import { TRPCError } from "@trpc/server";
import { jsonArrayFrom } from "kysely/helpers/postgres";
import { z } from "zod";
 
import type { DebtId, PeerId, ReceiptId, UserId } from "~db/ids";
import { queueCallFactory } from "~web/handlers/batch";
import type { AuthorizedContext } from "~web/handlers/context";
import { authProcedure } from "~web/handlers/trpc";
import { receiptIdSchema } from "~web/handlers/validation";
 
const fetchReceipts = async (
	{ database, auth }: AuthorizedContext,
	ids: ReceiptId[],
) =>
	database
		.selectFrom("receipts")
		.where("receipts.id", "in", ids)
		.innerJoin("peers as meFromReceiptOwnerView", (jb) =>
			jb
				.on("meFromReceiptOwnerView.connectedUserId", "=", auth.userId)
				.onRef(
					"meFromReceiptOwnerView.ownerUserId",
					"=",
					"receipts.ownerUserId",
				),
		)
		.innerJoin("peers as receiptOwnerFromMyView", (jb) =>
			jb
				.onRef(
					"receiptOwnerFromMyView.ownerUserId",
					"=",
					"meFromReceiptOwnerView.connectedUserId",
				)
				.onRef(
					"receiptOwnerFromMyView.connectedUserId",
					"=",
					"receipts.ownerUserId",
				),
		)
		.select((eb) => [
			"receipts.id",
			"receipts.createdAt",
			"receipts.name",
			"receipts.currencyCode",
			"receipts.ownerUserId",
			"receipts.issued",
			"receiptOwnerFromMyView.id as ownerPeerId",
			"meFromReceiptOwnerView.id as selfPeerId",
			jsonArrayFrom(
				eb
					.selectFrom("receiptItems")
					.select((ebb) => [
						"receiptItems.id",
						"receiptItems.name",
						"receiptItems.price",
						"receiptItems.quantity",
						"receiptItems.createdAt",
						jsonArrayFrom(
							ebb
								.selectFrom("receiptItemConsumers")
								.select([
									"receiptItemConsumers.part",
									"receiptItemConsumers.peerId",
									"receiptItemConsumers.createdAt",
								])
								.whereRef("receiptItemConsumers.itemId", "=", "receiptItems.id")
								.orderBy("receiptItemConsumers.createdAt", "desc")
								.orderBy("receiptItemConsumers.peerId"),
						).as("consumers"),
						jsonArrayFrom(
							ebb
								.selectFrom("receiptItemPayers")
								.select([
									"receiptItemPayers.part",
									"receiptItemPayers.peerId",
									"receiptItemPayers.createdAt",
								])
								.whereRef("receiptItemPayers.itemId", "=", "receiptItems.id")
								.orderBy("receiptItemPayers.createdAt", "desc")
								.orderBy("receiptItemPayers.peerId"),
						).as("payers"),
					])
					.whereRef("receiptItems.receiptId", "=", "receipts.id")
					.orderBy("receiptItems.createdAt", "desc")
					.orderBy("receiptItems.id"),
			).as("items"),
			jsonArrayFrom(
				eb
					.selectFrom("receiptParticipants")
					.whereRef("receiptParticipants.receiptId", "=", "receipts.id")
					.innerJoin("peers as peersTheir", (jb) =>
						jb.onRef("peersTheir.id", "=", "receiptParticipants.peerId"),
					)
					.leftJoin("peers as peersMine", (jb) =>
						jb
							.onRef(
								"peersMine.connectedUserId",
								"=",
								"peersTheir.connectedUserId",
							)
							.on("peersMine.ownerUserId", "=", auth.userId),
					)
					.select([
						"receiptParticipants.peerId",
						"receiptParticipants.createdAt",
						"receiptParticipants.role",
					])
					.orderBy("receiptParticipants.createdAt", "desc")
					.orderBy("receiptParticipants.peerId"),
			).as("participants"),
		])
		.execute();
 
const fetchDebts = async (
	{ database }: AuthorizedContext,
	receiptIds: ReceiptId[],
) =>
	database
		.selectFrom("debts")
		.innerJoin("peers", (qb) => qb.onRef("peers.id", "=", "debts.peerId"))
		.where("debts.receiptId", "in", receiptIds)
		.select([
			"debts.id as debtId",
			"debts.receiptId",
			"debts.ownerUserId",
			"peers.id as peerId",
		])
		.execute();
 
const getReceiptDebts = (
	debts: Awaited<ReturnType<typeof fetchDebts>>,
	receiptOwnerUserId: UserId,
	selfUserId: UserId,
	receiptSelfPeerId: PeerId,
):
	| ({
			direction: "incoming";
	  } & (
			| { id: DebtId; hasMine: true; hasForeign: boolean }
			| { id: DebtId; hasMine: false; hasForeign: true }
			| { id: undefined; hasMine: false; hasForeign: false }
	  ))
	| {
			direction: "outcoming";
			debts: { id: DebtId; peerId: PeerId }[];
	  } => {
	if (receiptOwnerUserId === selfUserId) {
		const outcomingDebt = debts
			.filter((debt) => debt.ownerUserId === selfUserId)
			.toSorted((a, b) => a.debtId.localeCompare(b.debtId))
			.map((debt) => ({ id: debt.debtId, peerId: debt.peerId }));
		return {
			direction: "outcoming",
			debts: outcomingDebt,
		};
	}
	const mineDebtId = debts.find(
		(debt) => debt.ownerUserId === selfUserId,
	)?.debtId;
	const foreignDebtId = debts.find(
		(debt) =>
			debt.ownerUserId !== selfUserId && debt.peerId === receiptSelfPeerId,
	)?.debtId;
	if (mineDebtId) {
		return {
			direction: "incoming",
			id: mineDebtId,
			hasMine: true,
			hasForeign: Boolean(foreignDebtId),
		};
	}
	if (foreignDebtId) {
		return {
			direction: "incoming",
			id: foreignDebtId,
			hasMine: false,
			hasForeign: true,
		};
	}
	return {
		direction: "incoming",
		id: undefined,
		hasMine: false,
		hasForeign: false,
	};
};
 
const mapReceipt = (
	auth: AuthorizedContext["auth"],
	receipt: Awaited<ReturnType<typeof fetchReceipts>>[number],
	debts: Awaited<ReturnType<typeof fetchDebts>>,
) => {
	const { ownerUserId, items, participants, ...receiptRest } = receipt;
	const payersItem = items.find((item) => item.id === receipt.id);
	const regularItems = items.filter((item) => item !== payersItem);
	return {
		...receiptRest,
		items: regularItems.map((item) => ({
			...item,
			price: Number(item.price),
			quantity: Number(item.quantity),
			payers: item.payers.map(({ part, ...consumer }) => ({
				...consumer,
				part: Number(part),
			})),
			consumers: item.consumers.map(({ part, ...consumer }) => ({
				...consumer,
				part: Number(part),
			})),
		})),
		participants,
		debts: getReceiptDebts(debts, ownerUserId, auth.userId, receipt.selfPeerId),
		// This can't happen as payers item always exists
		payers:
			/* c8 ignore next */
			payersItem?.consumers.map((payer) => ({
				...payer,
				part: Number(payer.part),
			})) ?? [],
	};
};
 
type Receipt = ReturnType<typeof mapReceipt>;
 
const queueReceipt = queueCallFactory<
	AuthorizedContext,
	{ id: ReceiptId },
	Receipt
>((ctx) => async (inputs) => {
	const receiptIds = inputs.map(({ id }) => id);
	const [receipts, debts] = await Promise.all([
		fetchReceipts(ctx, receiptIds),
		fetchDebts(ctx, receiptIds),
	]);
	return inputs.map((input) => {
		const receipt = receipts.find(({ id }) => id === input.id);
		if (!receipt) {
			return new TRPCError({
				code: "NOT_FOUND",
				message: `Receipt "${input.id}" is not found.`,
			});
		}
		if (
			receipt.ownerPeerId !== ctx.auth.userId &&
			!receipt.participants.some(
				(participant) => participant.peerId === receipt.selfPeerId,
			)
		) {
			return new TRPCError({
				code: "FORBIDDEN",
				message: `User "${ctx.auth.email}" has no access to receipt "${receipt.id}"`,
			});
		}
		try {
			const mapped = mapReceipt(
				ctx.auth,
				receipt,
				debts.filter((debt) => debt.receiptId === receipt.id),
			);
			return mapped;
			/* c8 ignore start */
		} catch (error) {
			return error as Error;
		}
		/* c8 ignore stop */
	});
});
 
export const procedure = authProcedure
	.meta({
		title: "Get receipt",
		description:
			"Returns a receipt by id with its items, participants, payers and linked debts, if the  user owns or participates in it.",
	})
	.input(
		z.strictObject({
			id: receiptIdSchema,
		}),
	)
	.query(queueReceipt);