All files / packages/app/features/receipts receipts.tsx

97.56% Statements 40/41
91.66% Branches 11/12
94.73% Functions 18/19
97.29% Lines 36/37

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                                                                  30x   435x     525x 525x                                         30x 469x 2141x                     469x 3x 9x 4x       3x 4x             469x       2128x                               30x   563x 563x 563x 563x   2x     563x       563x         563x     563x 335x       563x 51x 47x           4x                                                 550x                                                         2120x               4x 4x                             61x           625x              
import React from "react";
 
import { useDebouncedCallback } from "@tanstack/react-pacer";
import { useMutation } from "@tanstack/react-query";
import { Trans, useTranslation } from "react-i18next";
import { isNonNullish, values } from "remeda";
 
import { EmptyCard } from "~app/components/empty-card";
import {
	PaginationBlock,
	PaginationBlockSkeleton,
} from "~app/components/pagination-block";
import { SuspendedOverlay } from "~app/components/pagination-overlay";
import { RemoveButton } from "~app/components/remove-button";
import { suspendedFallback } from "~app/components/suspense-wrapper";
import { useCursorPaging } from "~app/hooks/use-cursor-paging";
import { useTrpcMutationOptions } from "~app/hooks/use-trpc-mutation-options";
import type {
	SearchParamState,
	SearchParamStateDefaulted,
} from "~app/utils/navigation";
import { useTRPC } from "~app/utils/trpc";
import { Divider } from "~components/divider";
import { Icon } from "~components/icons";
import { ButtonLink } from "~components/link";
import { Text } from "~components/text";
import type { ViewReactNode } from "~components/view";
import { View } from "~components/view";
import type { ReceiptId } from "~db/ids";
import { options as receiptsRemoveOptions } from "~mutations/receipts/remove";
 
import { ReceiptPreview, ReceiptPreviewSkeleton } from "./receipt-preview";
 
const SEARCH_UPDATE_DEBOUNCE = 1000;
 
const ReceiptsWrapper: React.FC<{ children: ViewReactNode }> = ({
	children,
}) => {
	const { t } = useTranslation("receipts");
	return (
		<>
			<View className="flex-row gap-2">
				<View className="flex-8 p-2">
					<Text>{t("list.table.receipt")}</Text>
				</View>
				<View className="flex-2 p-2">
					<Text className="self-end">{t("list.table.sum")}</Text>
				</View>
				<View className="hidden flex-1 p-2 sm:flex" />
			</View>
			<Divider />
			<View>{children}</View>
		</>
	);
};
 
const RemoveReceiptsButton: React.FC<{
	receiptIds: ReceiptId[];
	selectedReceiptIds: ReceiptId[];
	setSelectedReceiptIds: React.Dispatch<React.SetStateAction<ReceiptId[]>>;
}> = ({ selectedReceiptIds, setSelectedReceiptIds, receiptIds }) => {
	const trpc = useTRPC();
	const removeMutations = receiptIds.map((receiptId) => ({
		receiptId,
		// Mutations are stable due to `key` based on limit in the parent component
		// oxlint-disable-next-line react-hooks/rules-of-hooks
		mutation: useMutation(
			trpc.receipts.remove.mutationOptions(
				// oxlint-disable-next-line react-hooks/rules-of-hooks
				useTrpcMutationOptions(receiptsRemoveOptions),
			),
		),
	}));
	const onRemoveSelected = React.useCallback(() => {
		for (const { receiptId, mutation } of removeMutations) {
			if (selectedReceiptIds.includes(receiptId)) {
				mutation.mutate(
					{ id: receiptId },
					{
						onSuccess: () =>
							setSelectedReceiptIds((prevReceiptIds) =>
								prevReceiptIds.filter((lookupId) => lookupId !== receiptId),
							),
					},
				);
			}
		}
	}, [removeMutations, selectedReceiptIds, setSelectedReceiptIds]);
	return (
		<RemoveButton
			onRemove={onRemoveSelected}
			mutation={{
				isPending: removeMutations.some(({ mutation }) => mutation.isPending),
			}}
			isIconOnly
			isDisabled={selectedReceiptIds.length === 0}
			noConfirm={selectedReceiptIds.length < 2}
		/>
	);
};
 
type Props = {
	sort: SearchParamState<"/_protected/receipts/", "sort">[0];
	filtersState: SearchParamState<"/_protected/receipts/", "filters">;
	limitState: SearchParamStateDefaulted<"/_protected/receipts/", "limit">;
	offsetState: SearchParamState<"/_protected/receipts/", "offset">;
};
 
export const Receipts = suspendedFallback<Props>(
	({ filtersState, sort, limitState: [limit, setLimit], offsetState }) => {
		const { t } = useTranslation("receipts");
		const trpc = useTRPC();
		const [filters, setFilters] = filtersState;
		const updateFiltersQuery = React.useCallback(
			(nextValue: string) =>
				setFilters((prev) => ({ ...prev, query: nextValue })),
			[setFilters],
		);
		const debounceUpdateFiltersQuery = useDebouncedCallback(
			updateFiltersQuery,
			{ wait: SEARCH_UPDATE_DEBOUNCE },
		);
		const { data, onPageChange, isPending } = useCursorPaging(
			trpc.receipts.getPaged,
			{ limit, orderBy: sort, filters },
			offsetState,
		);
		const [selectedReceiptIds, setSelectedReceiptIds] = React.useState<
			ReceiptId[]
		>([]);
		const receiptIds = React.useMemo(
			() => data.items.map(({ id }) => id),
			[data.items],
		);
 
		if (!data.count) {
			if (values(filters).filter(isNonNullish).length === 0) {
				return (
					<Text variant="h3" className="text-center">
						{t("list.noResults")}
					</Text>
				);
			}
			return (
				<EmptyCard title={t("list.empty.title")}>
					<Trans
						t={t}
						i18nKey="list.empty.message"
						components={{
							text: <Text variant="h3" />,
							icon: (
								<ButtonLink
									color="primary"
									to="/receipts/add"
									title={t("list.addButton")}
									variant="bordered"
									className="mx-2"
									isIconOnly
								>
									<Icon name="add" className="size-6" />
								</ButtonLink>
							),
						}}
					/>
				</EmptyCard>
			);
		}
 
		return (
			<>
				<PaginationBlock
					totalCount={data.count}
					limit={limit}
					setLimit={setLimit}
					offset={offsetState[0]}
					onPageChange={onPageChange}
					selection={{
						items: receiptIds,
						selectedItems: selectedReceiptIds,
						setSelectedItems: setSelectedReceiptIds,
					}}
					search={{
						onValueChange: debounceUpdateFiltersQuery,
						value: filters.query ?? "",
					}}
					endContent={
						<RemoveReceiptsButton
							key={data.items.length}
							selectedReceiptIds={selectedReceiptIds}
							setSelectedReceiptIds={setSelectedReceiptIds}
							receiptIds={receiptIds}
						/>
					}
				/>
				<SuspendedOverlay isPending={isPending}>
					<ReceiptsWrapper>
						{data.items.map(({ id, highlights, matchedItems }) => (
							<ReceiptPreview
								key={id}
								id={id}
								highlights={highlights}
								filterQuery={filters.query || ""}
								matchedItems={matchedItems}
								isSelected={selectedReceiptIds.includes(id)}
								onValueChange={(nextSelected) =>
									setSelectedReceiptIds((prevSelected) =>
										nextSelected
											? [...prevSelected, id]
											: prevSelected.filter(
													(lookupValue) => lookupValue !== id,
												),
									)
								}
							/>
						))}
					</ReceiptsWrapper>
				</SuspendedOverlay>
			</>
		);
	},
	({ limitState }) => (
		<>
			<PaginationBlockSkeleton limit={limitState[0]} />
			<SuspendedOverlay isPending>
				<ReceiptsWrapper>
					{Array.from({ length: limitState[0] }).map((_, index) => (
						// oxlint-disable-next-line react/no-array-index-key
						<ReceiptPreviewSkeleton key={index} />
					))}
				</ReceiptsWrapper>
			</SuspendedOverlay>
		</>
	),
);