All files / packages/app/features/receipt-components receipt-item-consumer-input.tsx

93.02% Statements 40/43
79.16% Branches 19/24
100% Functions 11/11
92.85% Lines 39/42

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                                                          15466x         16938x   16938x 16938x 16938x   16938x   16938x   16938x   7953x       16938x   6498x   16938x             16938x         16938x       4x     4x     4x             3x 3x       16938x 16938x       16938x   1x       1x 1x     1x           16938x   2540x         16938x 16938x 12755x       16938x   2545x                         16938x 31x     16907x 3x     6x                                                               16904x                        
import React from "react";
 
import { useTranslation } from "react-i18next";
import { z } from "zod";
 
import { PartButtons } from "~app/components/app/part-buttons";
import { useAutofocus } from "~app/hooks/use-autofocus";
import { useAutosave, useAutosaveEffect } from "~app/hooks/use-autosave";
import { useBooleanState } from "~app/hooks/use-boolean-state";
import { useRoundParts } from "~app/hooks/use-decimals";
import { useTrpcMutationState } from "~app/hooks/use-trpc-mutation-state";
import { useAppForm } from "~app/utils/forms";
import { useTRPC } from "~app/utils/trpc";
import { partSchema, partSchemaDecimal } from "~app/utils/validation";
import { Button } from "~components/button";
import { Text } from "~components/text";
import { View } from "~components/view";
import { updateSetStateAction } from "~utils/react";
 
import { useActionsHooksContext, useReceiptContext } from "./context";
import { useCanEdit } from "./hooks";
import type { Item } from "./state";
 
type Props = {
	consumer: Item["consumers"][number];
	item: Item;
	isDisabled: boolean;
};
 
export const ReceiptItemConsumerInput: React.FC<Props> = ({
	consumer,
	item,
	isDisabled: isExternalDisabled,
}) => {
	const { t } = useTranslation("receipts");
	const { updateItemConsumerPart, removeItemConsumer } =
		useActionsHooksContext();
	const { receiptDisabled } = useReceiptContext();
	const canEdit = useCanEdit();
	const [isEditing, { setTrue: setEditing, setFalse: unsetEditing }] =
		useBooleanState();
 
	const trpc = useTRPC();
	const updateMutationState =
		useTrpcMutationState<"receiptItemConsumers.update">(
			trpc.receiptItemConsumers.update.mutationKey(),
			(vars) => vars.peerId === consumer.peerId && vars.itemId === item.id,
		);
 
	const removeMutationState =
		useTrpcMutationState<"receiptItemConsumers.remove">(
			trpc.receiptItemConsumers.remove.mutationKey(),
			(vars) => vars.peerId === consumer.peerId && vars.itemId === item.id,
		);
	const isDisabled = isExternalDisabled || receiptDisabled;
	const {
		onSuccess,
		onSubmit,
		onSubmitImmediate,
		updateElement,
		eagerToSubmitState,
	} = useAutosave({
		isUpdatePending:
			updateMutationState?.status === "pending" ||
			removeMutationState?.status === "pending",
	});
	const form = useAppForm({
		defaultValues: { value: consumer.part },
		validators: { onChange: z.object({ value: partSchema.or(z.literal(0)) }) },
		onSubmit: ({ value }) => {
			Iif (isDisabled || value.value === consumer.part) {
				return;
			}
			Iif (value.value === 0) {
				removeItemConsumer(item.id, consumer.peerId, { onSuccess });
			} else {
				updateItemConsumerPart(item.id, consumer.peerId, value.value, {
					onSuccess,
				});
			}
		},
		listeners: {
			onBlur: () => {
				onSubmitImmediate();
				unsetEditing();
			},
		},
	});
	useAutosaveEffect(form, { state: eagerToSubmitState });
	const { ref: inputRef, onKeyDownBlur } = useAutofocus({
		shouldFocus: isEditing,
	});
 
	const updateConsumerPart = React.useCallback(
		(setStateAction: React.SetStateAction<number>) => {
			const nextValue = Math.max(
				0,
				updateSetStateAction(setStateAction, form.getFieldValue("value")),
			);
			form.setFieldValue("value", nextValue);
			Iif (nextValue === 0) {
				onSubmitImmediate();
			} else {
				onSubmit();
			}
		},
		[onSubmit, onSubmitImmediate, form],
	);
 
	const wrap = React.useCallback(
		(children: React.ReactElement) => (
			<PartButtons updatePart={updateConsumerPart}>{children}</PartButtons>
		),
		[updateConsumerPart],
	);
 
	const roundParts = useRoundParts();
	const totalParts = roundParts(
		item.consumers.reduce((acc, itemConsumer) => acc + itemConsumer.part, 0),
	);
 
	const readOnlyComponent = (
		<form.Subscribe selector={(state) => state.values.value}>
			{(currentValue) => (
				<>
					<Text>
						{t("item.form.consumer.value", {
							part: Number.isNaN(currentValue) ? "-" : currentValue,
							totalParts,
						})}
					</Text>
					<View className="absolute top-1 right-1">{updateElement}</View>
				</>
			)}
		</form.Subscribe>
	);
 
	if (!canEdit) {
		return readOnlyComponent;
	}
 
	if (isEditing) {
		return wrap(
			<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}
						fractionDigits={partSchemaDecimal}
						className="w-28"
						aria-label={t("item.form.consumer.label")}
						mutation={updateMutationState}
						continuousMutations
						isDisabled={isDisabled}
						labelPlacement="outside-left"
						endContent={
							<Text className="self-center">
								{t("item.form.consumer.value", {
									part: "",
									totalParts,
								})}
							</Text>
						}
						variant="bordered"
					/>
				)}
			</form.AppField>,
		);
	}
 
	return wrap(
		<Button
			variant="light"
			onPress={setEditing}
			isDisabled={isDisabled}
			isIconOnly
			className="w-auto min-w-16 px-2"
		>
			{readOnlyComponent}
		</Button>,
	);
};