All files / packages/app/features/debts-transfer debts-transfer-screen.tsx

97.72% Statements 86/88
92.85% Branches 52/56
100% Functions 35/35
97.64% Lines 83/85

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 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441                                                                                          27x       38x 86x               27x 954x     27x         340x 340x 340x       340x 340x     340x     340x     340x 340x 976x   340x       340x 278x   6x             340x     340x 340x     340x     940x 940x               2x     2x     2x     2x   10x 10x 8x   2x                 2x 2x                 2x 2x                 340x   40x   340x 1x 3x 3x                     340x 340x   3x 3x 3x       340x 946x     340x   2x 2x 2x 3x           340x 6x   340x 8x     340x                                           946x         997x       997x                                                                 1x 1x                                   2x               1x                                           500x     303x                                                     31x 31x               93x                                             27x 73x 73x 73x 73x 73x 2x     73x 2x       73x                                                                            
import React from "react";
 
import {
	hashKey,
	skipToken,
	useMutation,
	usePrefetchQuery,
	useQueryClient,
	useSuspenseQuery,
} from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { entries, isNonNullish, pullObject } from "remeda";
import { z } from "zod";
 
import { CurrenciesPicker } from "~app/components/app/currencies-picker";
import { PeersSuggest } from "~app/components/app/peers-suggest";
import { PageHeader } from "~app/components/page-header";
import { suspendedFallback } from "~app/components/suspense-wrapper";
import { ShowResolvedDebtsOption } from "~app/features/settings/show-resolved-debts-option";
import { useBooleanState } from "~app/hooks/use-boolean-state";
import { useLocale } from "~app/hooks/use-locale";
import { useShowResolvedDebts } from "~app/hooks/use-show-resolved-debts";
import { useTrpcMutationOptions } from "~app/hooks/use-trpc-mutation-options";
import { useTrpcMutationStates } from "~app/hooks/use-trpc-mutation-state";
import { getCurrencySymbol } from "~app/utils/currency";
import type { CurrencyCode } from "~app/utils/currency";
import { useAppForm } from "~app/utils/forms";
import { getPathHooks } from "~app/utils/navigation";
import { useTRPC } from "~app/utils/trpc";
import {
	currencyCodeSchema,
	debtAmountSchema,
	debtAmountSchemaDecimal,
} from "~app/utils/validation";
import { BackLink } from "~components/back-link";
import { Button } from "~components/button";
import { Icon } from "~components/icons";
import { Skeleton } from "~components/skeleton";
import { SkeletonNumberInput } from "~components/skeleton-number-input";
import { Text } from "~components/text";
import { cn } from "~components/utils";
import { View } from "~components/view";
import type { PeerId } from "~db/ids";
import { options as debtsAddOptions } from "~mutations/debts/add";
 
const formSchema = z
	.record(currencyCodeSchema, debtAmountSchema.or(z.literal(0)))
	.refine(
		(record) =>
			entries(record).some(
				([, sum]) => !Number.isNaN(sum) && Number.isFinite(sum) && sum !== 0,
			),
		{ message: "No non-zero transfers" },
	);
type Form = z.infer<typeof formSchema>;
 
/* oxlint-disable typescript/no-unnecessary-template-expression */
// Typescript is not as good with flavored types inside template literals
const transformCurrencyCode = (currencyCode: CurrencyCode): `${CurrencyCode}` =>
	currencyCode as `${CurrencyCode}`;
/* oxlint-enable typescript/no-unnecessary-template-expression */
 
const DebtsListForm = suspendedFallback<{
	fromPeerId: PeerId;
	toPeerId?: PeerId;
}>(
	({ fromPeerId, toPeerId }) => {
		const { t } = useTranslation("debts");
		const trpc = useTRPC();
		const [extraCurrencyCodes, setExtraCurrencyCodes] = React.useState<
			CurrencyCode[]
		>([]);
 
		const queryClient = useQueryClient();
		const { data: fromPeerData } = useSuspenseQuery(
			trpc.debts.getAllPeer.queryOptions({ peerId: fromPeerId }),
		);
		const { data: fromPeer } = useSuspenseQuery(
			trpc.peers.get.queryOptions({ id: fromPeerId }),
		);
		usePrefetchQuery(
			trpc.peers.get.queryOptions(toPeerId ? { id: toPeerId } : skipToken),
		);
		const [showResolvedDebts] = useShowResolvedDebts();
		const nonResolvedDebts = fromPeerData.items.filter(
			(element) => element.sum !== 0,
		);
		const aggregatedDebts = showResolvedDebts
			? fromPeerData.items
			: nonResolvedDebts;
 
		const allCurrenciesWithSums = React.useMemo(
			() => [
				...aggregatedDebts,
				...extraCurrencyCodes.map((currencyCode) => ({
					currencyCode,
					sum: null,
				})),
			],
			[aggregatedDebts, extraCurrencyCodes],
		);
		const addMutation = useMutation(
			trpc.debts.add.mutationOptions(useTrpcMutationOptions(debtsAddOptions)),
		);
		const locale = useLocale();
		const [lastMutationTimestamps, setLastMutationTimestamps] = React.useState<
			string[]
		>([]);
		const form = useAppForm({
			defaultValues: pullObject(
				aggregatedDebts,
				(item) => item.currencyCode,
				() => 0,
			) satisfies Form,
			validators: {
				onMount: formSchema,
				onChange: formSchema,
				onSubmit: formSchema,
			},
			onSubmit: ({ value }) => {
				Iif (!toPeerId) {
					throw new Error(`Expected to have target peer id`);
				}
				const toPeer = queryClient.getQueryData(
					trpc.peers.get.queryOptions({ id: toPeerId }).queryKey,
				);
				Iif (!toPeer) {
					throw new Error(`Expected to have target peer`);
				}
				setLastMutationTimestamps(
					allCurrenciesWithSums.reduce<string[]>((acc, { currencyCode }) => {
						const amount = value[currencyCode] ?? 0;
						if (amount === 0) {
							return acc;
						}
						const fromMutationVars = {
							note: t("transfer.defaultNoteTo", {
								peer: toPeer.publicName || toPeer.name,
							}),
							currencyCode,
							peerId: fromPeerId,
							amount: -amount,
							timestamp: Temporal.Now.plainDateISO(),
						};
						addMutation.mutate(fromMutationVars);
						const toMutationVars = {
							note: t("transfer.defaultNoteFrom", {
								peer: fromPeer.publicName || fromPeer.name,
							}),
							currencyCode,
							peerId: toPeer.id,
							amount,
							timestamp: Temporal.Now.plainDateISO(),
						};
						addMutation.mutate(toMutationVars);
						return [
							...acc,
							hashKey([fromMutationVars]),
							hashKey([toMutationVars]),
						];
					}, []),
				);
			},
		});
		const lastMutationStates = useTrpcMutationStates<"debts.add">(
			trpc.debts.add.mutationKey(),
			(vars) => lastMutationTimestamps.includes(hashKey([vars])),
		);
		const setAllMax = React.useCallback(() => {
			for (const { currencyCode, sum } of allCurrenciesWithSums) {
				Eif (sum !== null) {
					form.setFieldValue(transformCurrencyCode(currencyCode), sum);
				}
			}
		}, [allCurrenciesWithSums, form]);
		const [
			currencyModalOpen,
			{
				setTrue: openCurrencyModal,
				switchValue: switchCurrencyModal,
				setFalse: closeCurrencyModal,
			},
		] = useBooleanState();
		const onCurrencyChange = React.useCallback(
			(currencyCode: CurrencyCode) => {
				setExtraCurrencyCodes((codes) => [...codes, currencyCode]);
				form.setFieldValue(transformCurrencyCode(currencyCode), 0);
				closeCurrencyModal();
			},
			[closeCurrencyModal, form],
		);
		const hiddenCurrencies = React.useMemo(
			() => allCurrenciesWithSums.map(({ currencyCode }) => currencyCode),
			[allCurrenciesWithSums],
		);
		const removeExtraCurrencyCode = React.useCallback(
			(currencyCode: CurrencyCode) => {
				form.deleteField(transformCurrencyCode(currencyCode));
				void form.validate("change");
				setExtraCurrencyCodes((codes) =>
					codes.filter((code) => code !== currencyCode),
				);
			},
			[form],
		);
 
		const mutationPending = lastMutationStates.some(
			(mutation) => mutation.status === "pending",
		);
		const mutationError = lastMutationStates
			.map((mutation) => mutation.error)
			.find(isNonNullish);
 
		return (
			<>
				<form.AppForm>
					<form.Form
						className="flex flex-col gap-4"
						testID="debts-transfer-form"
					>
						<View className="flex gap-2">
							{allCurrenciesWithSums.length === 0 ? (
								<Text>{t("transfer.form.noDebts")}</Text>
							) : (
								<>
									<View className="flex-row gap-4 self-end">
										{fromPeerData.items.length ===
										nonResolvedDebts.length ? null : (
											<ShowResolvedDebtsOption />
										)}
										<Button color="secondary" onPress={setAllMax}>
											{t("transfer.form.allMax")}
										</Button>
									</View>
									{allCurrenciesWithSums.map(({ currencyCode, sum }) => (
										<form.AppField
											key={currencyCode}
											name={transformCurrencyCode(currencyCode)}
										>
											{(field) => {
												const currencySymbol = getCurrencySymbol(
													locale,
													currencyCode,
												);
												return (
													<View
														testID={`debts-transfer-amount-${currencyCode}`}
														className="flex items-center gap-2 sm:flex-row"
													>
														<Text className="flex-2">{currencySymbol}</Text>
														<field.NumberField
															value={field.state.value}
															fractionDigits={debtAmountSchemaDecimal}
															formatOptions={{ signDisplay: "exceptZero" }}
															onValueChange={field.setValue}
															name={field.name}
															onBlur={field.handleBlur}
															fieldError={
																field.state.meta.isDirty
																	? field.state.meta.errors
																	: undefined
															}
															className="flex-6"
															aria-label={currencySymbol}
															color={
																field.state.value
																	? field.state.value > 0
																		? "success"
																		: "danger"
																	: "default"
															}
															startContent={
																<View
																	testID="debts-transfer-sign"
																	onPress={
																		field.state.value
																			? () =>
																					field.setValue(
																						(prevValue) => -prevValue,
																					)
																			: undefined
																	}
																	className={cn(
																		"size-4 rounded-sm",
																		field.state.value
																			? field.state.value > 0
																				? "bg-success"
																				: "bg-danger"
																			: "bg-default",
																	)}
																/>
															}
															endContent={
																sum === null ? (
																	<Button
																		onPress={() =>
																			removeExtraCurrencyCode(currencyCode)
																		}
																		color="danger"
																		isIconOnly
																	>
																		<Icon className="size-6" name="trash" />
																	</Button>
																) : (
																	<View onPress={() => field.setValue(sum)}>
																		<Text>{t("transfer.form.max")}</Text>
																	</View>
																)
															}
														/>
													</View>
												);
											}}
										</form.AppField>
									))}
								</>
							)}
							<Button
								className="self-start"
								color="secondary"
								onPress={openCurrencyModal}
							>
								{t("transfer.form.addCurrencyButton")}
							</Button>
						</View>
						<form.Subscribe
							selector={(state) => state.canSubmit && state.isValid}
						>
							{(canSubmit) => (
								<Button
									color={mutationError ? "danger" : "primary"}
									isDisabled={
										!canSubmit || mutationPending || fromPeerId === toPeerId
									}
									isLoading={mutationPending}
									type="submit"
								>
									{mutationError
										? mutationError.message
										: t("transfer.form.submit")}
								</Button>
							)}
						</form.Subscribe>
					</form.Form>
				</form.AppForm>
				<CurrenciesPicker
					onChange={onCurrencyChange}
					modalOpen={currencyModalOpen}
					switchModalOpen={switchCurrencyModal}
					topQueryOptions={{ type: "debts" }}
					hiddenCurrencies={hiddenCurrencies}
				/>
			</>
		);
	},
	() => {
		const { t } = useTranslation("debts");
		return (
			<View className="flex flex-col gap-4">
				<View className="flex gap-2">
					<Button color="secondary" className="self-end">
						{t("transfer.form.allMax")}
					</Button>
					{Array.from({ length: 3 }).map((_, index) => (
						// oxlint-disable-next-line react/no-array-index-key
						<View className="flex items-center gap-2 sm:flex-row" key={index}>
							<Skeleton className="h-6 w-8 flex-2 rounded-md" />
							<SkeletonNumberInput
								className="flex-6"
								startContent={<View className="bg-default size-4 rounded-sm" />}
								defaultValue={0}
								endContent={
									<View className="cursor-pointer">
										<Text>{t("transfer.form.max")}</Text>
									</View>
								}
							/>
						</View>
					))}
				</View>
				<Button color="primary" isDisabled>
					{t("transfer.form.submit")}
				</Button>
			</View>
		);
	},
);
 
export const DebtsTransferScreen = () => {
	const { useQueryState } = getPathHooks("/_protected/debts/transfer");
	const [fromId, setFromId] = useQueryState("from");
	const [toId, setToId] = useQueryState("to");
	const { t } = useTranslation("debts");
	const onFromClick = React.useCallback(
		(peerId: PeerId) => setFromId(fromId === peerId ? undefined : peerId),
		[fromId, setFromId],
	);
	const onToClick = React.useCallback(
		(peerId: PeerId) => setToId(toId === peerId ? undefined : peerId),
		[setToId, toId],
	);
 
	return (
		<>
			<PageHeader
				startContent={
					fromId ? (
						<BackLink to="/debts/peer/$id" params={{ id: fromId }} />
					) : (
						<BackLink to="/debts" />
					)
				}
			>
				{t("transfer.title")}
			</PageHeader>
			<View className="flex-row gap-2 self-center">
				<PeersSuggest
					label={t("transfer.form.from.label")}
					selected={fromId}
					onPeerClick={onFromClick}
					closeOnSelect
					setPeerNameToInput
					selectedProps={{ className: "flex flex-row gap-2 items-center" }}
				/>
				<Icon className="size-10" name="arrow-right" />
				<PeersSuggest
					label={t("transfer.form.to.label")}
					selected={toId}
					onPeerClick={onToClick}
					closeOnSelect
					setPeerNameToInput
					selectedProps={{ className: "flex flex-row gap-2 items-center" }}
				/>
			</View>
			{fromId ? (
				<DebtsListForm key={fromId} fromPeerId={fromId} toPeerId={toId} />
			) : null}
		</>
	);
};