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

100% Statements 54/54
100% Branches 15/15
100% Functions 24/24
100% Lines 52/52

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                                                              6x                                   6x             12x             12x   12x         12x     2x   10x 61x 61x 31x           10x         31x                     6x 70x   6x       36x 22x         14x                 14x       14x 14x 14x           6x       18x 18x   18x   18x   18x         18x           18x   18x   18x     18x   18x   18x     18x 16x   2x 1x   1x       7x     18x                           18x                       18x     30x         5x                             6x 17x 17x 18x       6x                
import { TRPCError } from "@trpc/server";
import type { ExpressionBuilder } from "kysely";
import { sql } from "kysely";
import { jsonArrayFrom } from "kysely/helpers/postgres";
import { z } from "zod";
 
import {
	limitSchema,
	offsetSchema,
	receiptsFiltersSchema,
	receiptsOrderBySchema,
} from "~app/utils/validation";
import type { ReceiptId, ReceiptItemId } from "~db/ids";
import type { DB } from "~db/types.gen";
import type { Interval } from "~utils/array";
import { mergeIntervals } from "~utils/array";
import {
	SIMILARTY_THRESHOLD,
	trigramSimilarity,
	trigramsForString,
} from "~utils/server/trigram";
import { queueCallFactory } from "~web/handlers/batch";
import type { AuthorizedContext } from "~web/handlers/context";
import {
	getOwnReceipts,
	getParticipantsReceipts,
} from "~web/handlers/receipts/utils";
import { authProcedure } from "~web/handlers/trpc";
import type { GeneralOutput } from "~web/utils/batch";
import { queueList } from "~web/utils/batch";
 
const inputSchema = z.strictObject({
	cursor: offsetSchema,
	limit: limitSchema,
	orderBy: receiptsOrderBySchema,
	filters: receiptsFiltersSchema.optional(),
});
 
type Input = z.infer<typeof inputSchema>;
type OutputItem = {
	id: ReceiptId;
	highlights: Interval[];
	matchedItems: {
		id: ReceiptItemId;
		highlights: Interval[];
	}[];
};
type Output = GeneralOutput<OutputItem> & { count: number };
 
const getTrigramHighlight = ({
	query,
	target,
}: {
	query: string;
	target: string;
}) => {
	const words = target.split(" ").map((word, index, allWords) => ({
		word,
		startIndex:
			/* c8 ignore next */
			allWords.slice(0, index).join(" ").length + (index === 0 ? 0 : 1),
	}));
 
	return mergeIntervals(
		words.flatMap(({ word, startIndex }) => {
			if (
				query
					.split(" ")
					.every(
						(queryPart) =>
							trigramSimilarity(queryPart, word) < SIMILARTY_THRESHOLD,
					)
			) {
				return [];
			}
			const filterQueryTrigrams = Array.from(trigramsForString(query))
				.map((trigram) => trigram.trim())
				.filter((trigram) => trigram.length >= 3)
				.map((trigram) => RegExp.escape(trigram));
			/* c8 ignore start */
			if (filterQueryTrigrams.length === 0) {
				return [];
			}
			/* c8 ignore stop */
			const matches = [
				...word.matchAll(
					new RegExp(`(?=(${filterQueryTrigrams.join("|")}))`, "giu"),
				),
			];
			return matches.map<Interval>((match) => [
				startIndex + match.index,
				// This is non-consuming RegExp hence 2nd argument
				// oxlint-disable-next-line typescript/no-non-null-assertion
				startIndex + match.index + match[1]!.length,
			]);
		}),
		true,
	);
};
 
const itemSimilarity = (query: string, lookupColumn: string) =>
	sql<number>`similarity(${query}, ${sql.id(...lookupColumn.split("."))})`;
 
const selectFields = (
	eb: ExpressionBuilder<DB, "receipts" | "receiptItems">,
	query: string | undefined,
) => {
	if (!query) {
		return [
			sql<number>`0`.as("similarity"),
			sql`'[]'::jsonb`.$castTo<Item[]>().as("matchedItems"),
		] as const;
	}
	const itemsQueryBuilder = eb
		.selectFrom("receiptItems")
		.select([
			"receiptItems.id",
			"receiptItems.name",
			itemSimilarity(query, "receiptItems.name").as("similarity"),
		])
		.whereRef("receiptItems.receiptId", "=", "receipts.id")
		.where((qb) =>
			qb(itemSimilarity(query, "receiptItems.name"), ">=", SIMILARTY_THRESHOLD),
		)
		.orderBy(itemSimilarity(query, "receiptItems.name"), "desc");
	type Item = NonNullable<(typeof itemsQueryBuilder)["expressionType"]>;
	const nameSimilarity = itemSimilarity(query, "receipts.name");
	const maxItemSimilarity = sql<number>`coalesce(${eb.fn.max(itemSimilarity(query, "receiptItems.name"))}, 0::float8)`;
	return [
		sql<number>`(${nameSimilarity} + ${maxItemSimilarity})`.as("similarity"),
		jsonArrayFrom(itemsQueryBuilder).$castTo<Item[]>().as("matchedItems"),
	] as const;
};
 
const fetchPage = async (
	{ database, auth }: AuthorizedContext,
	input: Input,
) => {
	const foreignReceipts = getParticipantsReceipts(database, auth.userId);
	const ownReceipts = getOwnReceipts(database, auth.userId);
 
	const mergedReceipts = database
		.with("mergedReceipts", () => {
			const query = input.filters?.query;
 
			const baseGroupBy = [
				"receipts.id",
				"receipts.name",
				"receipts.issued",
			] as const;
			const baseSelect = [
				"receipts.id",
				"receipts.name",
				"receipts.issued",
			] as const;
 
			const ownBuilder = ownReceipts
				.leftJoin("receiptItems", (qb) =>
					qb.onRef("receiptItems.receiptId", "=", "receipts.id"),
				)
				.select((eb) => [...baseSelect, ...selectFields(eb, query)])
				.groupBy(baseGroupBy);
 
			const foreignBuilder = foreignReceipts
				.leftJoin("receiptItems", (qb) =>
					qb.onRef("receiptItems.receiptId", "=", "receipts.id"),
				)
				.select((eb) => [...baseSelect, ...selectFields(eb, query)])
				.groupBy(baseGroupBy);
 
			if (!input.filters || typeof input.filters.ownedByMe !== "boolean") {
				return ownBuilder.unionAll(foreignBuilder);
			}
			if (input.filters.ownedByMe) {
				return ownBuilder;
			}
			return foreignBuilder;
		})
		.selectFrom("mergedReceipts")
		.$if(Boolean(input.filters?.query), (sqb) =>
			sqb.where("mergedReceipts.similarity", ">=", SIMILARTY_THRESHOLD),
		);
 
	const [receipts, receiptsCount] = await Promise.all([
		mergedReceipts
			.select(["id", "name", "matchedItems", "similarity"])
			.orderBy("mergedReceipts.similarity", "desc")
			// Stable order for receipts with the same date
			.orderBy(
				"mergedReceipts.issued",
				input.orderBy === "date-asc" ? "asc" : "desc",
			)
			.orderBy("mergedReceipts.id")
			.offset(input.cursor)
			.limit(input.limit)
			.execute(),
		mergedReceipts
			.select((eb) => eb.fn.count<number>("mergedReceipts.id").as("amount"))
			.executeTakeFirstOrThrow(
				/* c8 ignore start */
				() =>
					new TRPCError({
						code: "INTERNAL_SERVER_ERROR",
						message: `Unexpected having empty "amount" in "receipts.getPaged" handler`,
					}),
				/* c8 ignore stop */
			),
	]);
 
	return {
		count: receiptsCount.amount,
		cursor: input.cursor,
		items: receipts.map(({ id, name, matchedItems }) => ({
			id,
			highlights: input.filters?.query
				? getTrigramHighlight({ query: input.filters.query, target: name })
				: [],
			matchedItems: matchedItems.map((item) => ({
				id: item.id,
				highlights: input.filters?.query
					? getTrigramHighlight({
							query: input.filters.query,
							target: item.name,
							/* c8 ignore start */
						})
					: [],
				/* c8 ignore stop */
			})),
		})),
	};
};
 
const queueReceiptList = queueCallFactory<AuthorizedContext, Input, Output>(
	(ctx) => async (inputs) =>
		queueList<Input, OutputItem, Output>(inputs, (values) =>
			fetchPage(ctx, values),
		),
);
 
export const procedure = authProcedure
	.meta({
		title: "Get receipts, paged",
		description:
			"Returns a page of the  user's own and participated-in receipts, optionally filtered by a fuzzy name/item search query.",
	})
	.input(inputSchema)
	.query(queueReceiptList);