All files / packages/app/features/receipt-components receipt-participant.tsx

86.9% Statements 73/84
89.74% Branches 70/78
90% Functions 18/20
86.74% Lines 72/83

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                                                                          88x               343x       331x       343x 104x   239x   18x         221x 221x   24x               197x       12x   6x         6x   6x                     88x           343x 343x         343x 343x         343x 343x 343x               343x                   153x       365x 365x   365x   365x 365x     365x   365x   1212x     365x   1083x     365x   1169x   365x                     365x 365x       8x     8x 2x 6x 3x   3x             365x 365x         365x     992x   365x 365x 4x 4x   365x 3x 3x   365x                         365x 365x 365x 365x 82x     363x                                                   343x                                                                                             175x   50x                                   41x                                                                                                                                                           1320x 4835x   1320x     1320x                                            
import React from "react";
 
import { skipToken, useQuery, useSuspenseQuery } from "@tanstack/react-query";
import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
import { z } from "zod";
 
import { LoadablePeer } from "~app/components/app/loadable-peer";
import { PartButtons } from "~app/components/app/part-buttons";
import { RemoveButton } from "~app/components/remove-button";
import { suspendedFallback } from "~app/components/suspense-wrapper";
import { useAutofocus } from "~app/hooks/use-autofocus";
import { useAutosave, useAutosaveEffect } from "~app/hooks/use-autosave";
import { useRoundParts } from "~app/hooks/use-decimals";
import { useLocale } from "~app/hooks/use-locale";
import { useTrpcMutationState } from "~app/hooks/use-trpc-mutation-state";
import type { Debt } from "~app/trpc-types";
import { formatCurrency } from "~app/utils/currency";
import { useAppForm } from "~app/utils/forms";
import { useTRPC } from "~app/utils/trpc";
import { partSchema, partSchemaDecimal } from "~app/utils/validation";
import { Accordion, AccordionItem } from "~components/accordion";
import { Button } from "~components/button";
import { Divider } from "~components/divider";
import { Icon } from "~components/icons";
import { Text } from "~components/text";
import { Tooltip } from "~components/tooltip";
import { getMutationLoading } from "~components/utils";
import { View } from "~components/view";
import type { DebtId } from "~db/ids";
import { round } from "~utils/math";
 
import { useActionsHooksContext, useReceiptContext } from "./context";
import { useIsOwner } from "./hooks";
import { ReceiptParticipantRoleInput } from "./receipt-participant-role-input";
import type { Participant } from "./state";
 
const getParticipantError = (
	t: TFunction<"receipts">,
	participant: Participant,
	debt: Debt | undefined,
	hasConnectedUser: boolean,
	isOwner: boolean,
	isSelfParticipant: boolean,
) => {
	Iif (!isOwner && !isSelfParticipant) {
		// We don't have data on foreign debts with a foreign receipt
		return;
	}
	Iif (isOwner && isSelfParticipant) {
		// We don't have debt for ourselves
		return;
	}
	if (participant.balance === 0) {
		return;
	}
	if (!debt) {
		// No debt has been propagated
		return {
			className: "text-warning",
			content: t("participant.errors.noOurs"),
		};
	}
	const expectedSum = isOwner ? participant.balance : -participant.balance;
	if (debt.amount !== expectedSum) {
		// Our debt is desynced from the receipt
		return {
			className: "text-danger",
			content: t("participant.errors.desyncedOurs", {
				actual: debt.amount,
				expected: expectedSum,
			}),
		};
	}
	Iif (!hasConnectedUser) {
		// Debt is not syncable
		return;
	}
	if (!debt.their) {
		// Our debts exists, their does not
		return {
			className: "text-warning",
			content: t("participant.errors.noTheir"),
		};
	}
	Eif (debt.amount !== debt.their.amount) {
		// Our debt is desynced from their debt
		return {
			className: "text-warning",
			content: t("participant.errors.desyncedTheir", {
				actual: debt.their.amount,
				expected: debt.amount,
			}),
		};
	}
	// In sync
};
 
const RenderParticipantError = suspendedFallback<{
	participant: Participant;
	debtId: DebtId | undefined;
	children: (error: ReturnType<typeof getParticipantError>) => React.ReactNode;
}>(
	({ children, participant, debtId }) => {
		const trpc = useTRPC();
		const { data: debt } = useQuery(
			trpc.debts.get.queryOptions(debtId ? { id: debtId } : skipToken, {
				enabled: Boolean(debtId),
			}),
		);
		const isOwner = useIsOwner();
		const { data: peer } = isOwner
			? useSuspenseQuery(
					trpc.peers.get.queryOptions({ id: participant.peerId }),
				)
			: { data: null };
		const { t } = useTranslation("receipts");
		const { selfPeerId } = useReceiptContext();
		const error = getParticipantError(
			t,
			participant,
			debt,
			Boolean(peer?.connectedUser),
			isOwner,
			participant.peerId === selfPeerId,
		);
		return children(error);
	},
	({ children }) => <>{children(undefined)}</>,
);
 
type Props = {
	participant: Participant;
	debtId?: DebtId;
};
 
export const ReceiptParticipant: React.FC<Props> = ({
	participant,
	debtId,
}) => {
	const { t } = useTranslation("receipts");
	const trpc = useTRPC();
	const { receiptId, currencyCode, renderParticipantActions, items, payers } =
		useReceiptContext();
	const { removeParticipant, updatePayerPart, addPayer, removePayer } =
		useActionsHooksContext();
	const isOwner = useIsOwner();
 
	const currentPart =
		payers.find((payer) => payer.peerId === participant.peerId)?.part ?? 0;
	const addPayerMutationState =
		useTrpcMutationState<"receiptItemConsumers.add">(
			trpc.receiptItemConsumers.add.mutationKey(),
			(vars) => vars.itemId === receiptId && vars.peerId === participant.peerId,
		);
	const removePayerMutationState =
		useTrpcMutationState<"receiptItemConsumers.remove">(
			trpc.receiptItemConsumers.remove.mutationKey(),
			(vars) => vars.itemId === receiptId && vars.peerId === participant.peerId,
		);
	const updatePayerMutationState =
		useTrpcMutationState<"receiptItemConsumers.update">(
			trpc.receiptItemConsumers.update.mutationKey(),
			(vars) => vars.itemId === receiptId && vars.peerId === participant.peerId,
		);
	const isPayerPending = getMutationLoading([
		addPayerMutationState,
		removePayerMutationState,
		updatePayerMutationState,
	]);
	const {
		onSuccess,
		onSubmit,
		onSubmitImmediate,
		updateElement,
		eagerToSubmitState,
	} = useAutosave({ isUpdatePending: isPayerPending });
	const form = useAppForm({
		defaultValues: { value: currentPart },
		validators: { onChange: z.object({ value: partSchema.or(z.literal(0)) }) },
		onSubmit: ({ value }) => {
			Iif (value.value === currentPart) {
				return;
			}
			if (value.value === 0) {
				removePayer(participant.peerId, { onSuccess });
			} else if (currentPart === 0 && value.value === 1) {
				addPayer(participant.peerId, value.value, { onSuccess });
			} else {
				updatePayerPart(participant.peerId, value.value, { onSuccess });
			}
		},
		listeners: {
			onBlur: onSubmitImmediate,
		},
	});
	useAutosaveEffect(form, { state: eagerToSubmitState });
	const { ref: inputRef, onKeyDownBlur } = useAutofocus({
		shouldFocus: true,
	});
 
	const removeParticipantMutationState =
		useTrpcMutationState<"receiptParticipants.remove">(
			trpc.receiptParticipants.remove.mutationKey(),
			(vars) =>
				vars.receiptId === receiptId && vars.peerId === participant.peerId,
		);
	const isPending = removeParticipantMutationState?.status === "pending";
	const removeReceiptParticipant = React.useCallback(() => {
		removeParticipant(participant.peerId);
		form.setFieldValue("value", 0);
	}, [form, participant.peerId, removeParticipant]);
	const onAddPayer = React.useCallback(() => {
		form.setFieldValue("value", 1);
		onSubmitImmediate();
	}, [form, onSubmitImmediate]);
	const onPartUpdate = React.useCallback(
		(setStateAction: React.SetStateAction<number>) => {
			form.setFieldValue("value", setStateAction);
			const value = form.getFieldValue("value");
			if (value === 0) {
				onSubmitImmediate();
			} else {
				onSubmit();
			}
		},
		[form, onSubmit, onSubmitImmediate],
	);
 
	const locale = useLocale();
	const disabled = participant.debt.items.length === 0;
	const roundParts = useRoundParts();
	const totalPayParts = roundParts(
		payers.reduce((acc, { part }) => acc + part, 0),
	);
 
	return (
		<View testID="participant-row">
			<Accordion>
				<AccordionItem
					key="parts"
					textValue={t("participant.title", { peerId: participant.peerId })}
					title={
						<View className="flex-col items-start justify-between gap-2 min-[600px]:flex-row">
							<View className="flex flex-row items-center gap-1">
								{currentPart ? (
									<Icon name="money" className="text-secondary size-6" />
								) : null}
								<LoadablePeer
									className={
										disabled && !currentPart ? "opacity-disabled" : undefined
									}
									id={participant.peerId}
									foreign={!isOwner}
								/>
							</View>
							<View className="flex-row items-center justify-between gap-4 self-stretch">
								<RenderParticipantError
									participant={participant}
									debtId={debtId}
								>
									{(error) => (
										<Tooltip content={error?.content} isDisabled={!error}>
											<View className="flex flex-col items-end">
												<Text
													className={error?.className}
													testID={
														error ? "participant-debt-warning" : undefined
													}
												>
													{formatCurrency(
														locale,
														currencyCode,
														round(participant.debt.total),
													)}
												</Text>
												{participant.payment.total === 0 ? null : (
													<Text>
														{t("participant.payedShort", {
															amount: formatCurrency(
																locale,
																currencyCode,
																round(participant.payment.total),
															),
														})}
													</Text>
												)}
											</View>
										</Tooltip>
									)}
								</RenderParticipantError>
								<View className="flex-row items-center gap-2">
									{isOwner ? (
										<RemoveButton
											onRemove={removeReceiptParticipant}
											mutation={{ isPending }}
											subtitle={t("participants.remove.confirmSubtitle")}
											noConfirm={participant.balance === 0}
											isIconOnly
										/>
									) : null}
								</View>
							</View>
						</View>
					}
				>
					<View className="flex gap-3">
						<View className="flex flex-col justify-between gap-4 sm:flex-row sm:items-center">
							<View className="flex flex-row items-center gap-2">
								<form.Subscribe selector={(state) => state.values.value}>
									{(currentValue) =>
										currentValue === 0 ? (
											<>
												<Button onPress={onAddPayer}>
													{t("participant.form.addPayerButton")}
												</Button>
												<View className="absolute -top-0.5 -right-0.5">
													{updateElement}
												</View>
											</>
										) : (
											<>
												<Text>{t("participant.payedInfix")}</Text>
												<PartButtons
													updatePart={onPartUpdate}
													downDisabled={currentValue <= 0}
												>
													<form.AppField name="value">
														{(field) => (
															<field.NumberField
																ref={inputRef}
																value={field.state.value}
																onValueChange={field.setValue}
																name={field.name}
																onBlur={field.handleBlur}
																fieldError={
																	field.state.meta.isDirty
																		? field.state.meta.errors
																		: undefined
																}
																onKeyPress={onKeyDownBlur}
																className="w-28"
																aria-label={t(
																	"participant.form.payerPart.label",
																)}
																mutation={[
																	addPayerMutationState,
																	removePayerMutationState,
																	updatePayerMutationState,
																]}
																continuousMutations
																labelPlacement="outside-left"
																fractionDigits={partSchemaDecimal}
																hideStepper
																endContent={
																	<View className="flex flex-row items-center gap-1">
																		<Text className="shrink-0 self-center">
																			{t("participant.form.payerPart.postfix", {
																				parts: totalPayParts,
																			})}
																		</Text>
																		<View className="absolute -top-1 -right-2">
																			{updateElement}
																		</View>
																	</View>
																}
																variant="bordered"
															/>
														)}
													</form.AppField>
												</PartButtons>
											</>
										)
									}
								</form.Subscribe>
							</View>
							<View className="flex flex-row items-center gap-2 self-end">
								{renderParticipantActions(participant)}
								<ReceiptParticipantRoleInput participant={participant} />
							</View>
						</View>
						{currentPart && items.length !== 0 ? <Divider /> : null}
						<View className="flex flex-col gap-3">
							{currentPart && items.length !== 0 ? (
								<Text className="text-secondary">
									{t("participant.payerPart", {
										amount: formatCurrency(
											locale,
											currencyCode,
											participant.payment.total,
										),
									})}
								</Text>
							) : null}
							<View>
								{currentPart && participant.debt.items.length > 1 ? (
									<Text className="text-secondary">
										{t("participant.consumerPart", {
											amount: formatCurrency(
												locale,
												currencyCode,
												participant.debt.total,
											),
										})}
									</Text>
								) : null}
								{participant.debt.items.map((item) => {
									const matchedItem = items.find(
										({ id }) => id === item.itemId,
									);
									Iif (!matchedItem) {
										return null;
									}
									return (
										<Text key={matchedItem.id}>
											{t("participant.partDescription", {
												item: matchedItem.name,
												amount: formatCurrency(
													locale,
													currencyCode,
													round(item.sum),
												),
												extraSymbol: item.shortage === 0 ? "" : "+",
											})}
										</Text>
									);
								})}
							</View>
						</View>
					</View>
				</AccordionItem>
			</Accordion>
		</View>
	);
};