All files / packages/app/features/receipt receipt-amount-input.tsx

71.42% Statements 10/14
71.42% Branches 5/7
66.66% Functions 2/3
71.42% Lines 10/14

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                                            1159x 1300x 1300x       1300x   1300x         1300x                           1300x     1300x 868x     1300x                                  
import React from "react";
 
import { useMutation } from "@tanstack/react-query";
 
import { CurrenciesPicker } from "~app/components/app/currencies-picker";
import { useBooleanState } from "~app/hooks/use-boolean-state";
import { useLocale } from "~app/hooks/use-locale";
import { useTrpcMutationOptions } from "~app/hooks/use-trpc-mutation-options";
import type { Receipt } from "~app/trpc-types";
import { getCurrencySymbol } from "~app/utils/currency";
import type { CurrencyCode } from "~app/utils/currency";
import { useTRPC } from "~app/utils/trpc";
import { Text } from "~components/text";
import { View } from "~components/view";
import { options as receiptsUpdateOptions } from "~mutations/receipts/update";
import { round } from "~utils/math";
 
type Props = {
	receipt: Receipt;
	isLoading: boolean;
};
 
export const ReceiptAmountInput: React.FC<Props> = ({ receipt, isLoading }) => {
	const trpc = useTRPC();
	const locale = useLocale();
	const [
		isModalOpen,
		{ switchValue: switchModalOpen, setTrue: openModal, setFalse: closeModal },
	] = useBooleanState();
 
	const updateReceiptMutation = useMutation(
		trpc.receipts.update.mutationOptions(
			useTrpcMutationOptions(receiptsUpdateOptions),
		),
	);
	const saveCurrency = React.useCallback(
		(nextCurrencyCode: CurrencyCode) => {
			closeModal();
			if (nextCurrencyCode === receipt.currencyCode) {
				return;
			}
			updateReceiptMutation.mutate({
				id: receipt.id,
				update: { type: "currencyCode", currencyCode: nextCurrencyCode },
			});
		},
		[updateReceiptMutation, receipt.id, receipt.currencyCode, closeModal],
	);
	const disabled =
		updateReceiptMutation.isPending ||
		isLoading ||
		receipt.ownerPeerId !== receipt.selfPeerId;
	const sum = round(
		receipt.items.reduce((acc, item) => acc + item.price * item.quantity, 0),
	);
 
	return (
		<View className="flex flex-row gap-2">
			<Text className="text-2xl/9">{sum}</Text>
			<View onPress={disabled ? undefined : openModal}>
				<Text className="text-2xl/9">
					{getCurrencySymbol(locale, receipt.currencyCode)}
				</Text>
			</View>
			<CurrenciesPicker
				onChange={saveCurrency}
				modalOpen={isModalOpen}
				switchModalOpen={switchModalOpen}
				topQueryOptions={{ type: "receipts" }}
			/>
		</View>
	);
};