All files / packages/app/features/add-receipt add-receipt.tsx

97.5% Statements 39/40
75% Branches 6/8
93.33% Functions 14/15
97.5% Lines 39/40

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                                                                                      18x                                                   106x 106x 106x 106x 106x 106x                             106x 106x               106x                   29x 29x                 18x 84x 84x 84x 84x   84x 84x     84x             2x           84x 84x 84x       84x         84x         84x               4x         4x       2x       2x       1x               84x   84x         264x                               249x                   249x                                 383x   254x                              
import React from "react";
 
import type {
	FormApi,
	FormAsyncValidateOrFn,
	FormValidateOrFn,
} from "@tanstack/react-form";
import {
	skipToken,
	useMutation,
	useQueryClient,
	useSuspenseQuery,
} from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import type z from "zod";
 
import { CurrencyInput } from "~app/components/app/currency-input";
import { suspendedFallback } from "~app/components/suspense-wrapper";
import { NavigationContext } from "~app/contexts/navigation-context";
import {
	ActionsHooksContext,
	ReceiptContext,
} from "~app/features/receipt-components/context";
import {
	ReceiptItems,
	SkeletonAddReceiptItemController,
} from "~app/features/receipt-components/receipt-items";
import { ReceiptParticipants } from "~app/features/receipt-components/receipt-participants";
import type { Payer } from "~app/features/receipt-components/state";
import { useParticipants } from "~app/hooks/use-participants";
import { useTrpcMutationOptions } from "~app/hooks/use-trpc-mutation-options";
import { useAppForm, useTypedValues } from "~app/utils/forms";
import { useTRPC } from "~app/utils/trpc";
import { Button } from "~components/button";
import { DateInput } from "~components/date-input";
import type { PeerId } from "~db/ids";
import { options as receiptsAddOptions } from "~mutations/receipts/add";
import type { UseStateReturn } from "~utils/react";
 
import { useActionsHooks, useAddReceiptContext } from "./hooks";
import type { Form, Item, Participant } from "./state";
import { formSchema } from "./state";
 
const ContextedAddReceipt = suspendedFallback<{
	formStore: FormApi<
		Form,
		typeof formSchema,
		typeof formSchema,
		FormAsyncValidateOrFn<Form> | undefined,
		FormValidateOrFn<Form> | undefined,
		FormAsyncValidateOrFn<Form> | undefined,
		typeof formSchema,
		FormAsyncValidateOrFn<Form> | undefined,
		FormValidateOrFn<Form> | undefined,
		FormAsyncValidateOrFn<Form> | undefined,
		FormAsyncValidateOrFn<Form> | undefined
	>["store"];
	defaultFormValues: Pick<z.infer<typeof formSchema>, "name" | "issued">;
	itemsState: UseStateReturn<Item[]>;
	participantsState: UseStateReturn<Participant[]>;
	payersState: UseStateReturn<Payer[]>;
}>(
	({
		formStore,
		defaultFormValues,
		itemsState: [items, setItems],
		participantsState: [rawParticipants, setParticipants],
		payersState: [payers, setPayers],
	}) => {
		const trpc = useTRPC();
		const { data: user } = useSuspenseQuery(trpc.user.get.queryOptions());
		const selfPeerId = user.user.id as PeerId;
		const formValues = useTypedValues(formStore, defaultFormValues);
		const receiptId = React.useId();
		const participants = useParticipants({
			id: receiptId,
			createdAt: Temporal.Now.zonedDateTimeISO(),
			issued: formValues.issued,
			currencyCode: formValues.currencyCode ?? "???",
			participants: rawParticipants,
			items,
			ownerPeerId: selfPeerId,
			selfPeerId,
			payers,
			debts: {
				direction: "outcoming",
				debts: [],
			},
		});
		const actionsHooks = useActionsHooks(setItems, setParticipants, setPayers);
		const addReceiptContext = useAddReceiptContext(
			formValues,
			receiptId,
			selfPeerId,
			payers,
			items,
			participants,
		);
		return (
			<ReceiptContext value={addReceiptContext}>
				<ActionsHooksContext value={actionsHooks}>
					<ReceiptParticipants />
					<ReceiptItems />
				</ActionsHooksContext>
			</ReceiptContext>
		);
	},
	() => {
		const { t } = useTranslation("receipts");
		return (
			<>
				<Button isDisabled>{t("participants.addButton")}</Button>
				<SkeletonAddReceiptItemController />
			</>
		);
	},
);
 
export const AddReceipt = () => {
	const { t } = useTranslation("receipts");
	const trpc = useTRPC();
	const { useNavigate } = React.use(NavigationContext);
	const navigate = useNavigate();
 
	const queryClient = useQueryClient();
	const optimisticUser = queryClient.getQueryData(
		trpc.user.get.queryOptions().queryKey,
	);
	const addReceiptMutation = useMutation(
		trpc.receipts.add.mutationOptions(
			useTrpcMutationOptions(receiptsAddOptions, {
				context: optimisticUser
					? { selfUserId: optimisticUser.user.id }
					: skipToken,
				onSuccess: ({ id }) =>
					navigate({ to: "/receipts/$id", params: { id }, replace: true }),
			}),
		),
	);
 
	/* oxlint-disable react/hook-use-state */
	const itemsState = React.useState<Item[]>([]);
	const participantsState = React.useState<Participant[]>([]);
	const payersState = React.useState<Payer[]>([]);
	/* oxlint-enable react/hook-use-state */
 
	// If we preloaded top currency codes for receipts - we can initialize our form with it
	const optimisticCurrencyCode = queryClient.getQueryData(
		trpc.currency.top.queryOptions({
			options: { type: "receipts" },
		}).queryKey,
	)?.items[0]?.currencyCode;
	const defaultValues = {
		name: "",
		issued: Temporal.Now.plainDateISO(),
		currencyCode: optimisticCurrencyCode,
	} satisfies Partial<Form>;
	const form = useAppForm({
		defaultValues: defaultValues as Form,
		validators: {
			onMount: formSchema,
			onChange: formSchema,
			onSubmit: formSchema,
		},
		onSubmit: ({ value }) => {
			addReceiptMutation.mutate({
				name: value.name,
				currencyCode: value.currencyCode,
				issued: value.issued,
				items: itemsState[0].map(
					({ name, price, quantity, consumers, payers }) => ({
						name,
						price,
						quantity,
						consumers: consumers.map(({ peerId, part }) => ({ peerId, part })),
						payers: payers.map(({ peerId, part }) => ({ peerId, part })),
					}),
				),
				participants: participantsState[0].map(({ peerId, role }) => ({
					peerId,
					role,
				})),
				payers: payersState[0].map(({ peerId, part }) => ({
					peerId,
					part,
				})),
			});
		},
	});
 
	const formId = React.useId();
 
	return (
		<form.AppForm>
			<form.Form id={formId} className="flex flex-col gap-4">
				<form.AppField name="name">
					{(field) => (
						<field.TextField
							label={t("receipt.form.name.label")}
							value={field.state.value}
							onValueChange={field.setValue}
							name={field.name}
							onBlur={field.handleBlur}
							isRequired
							mutation={addReceiptMutation}
							fieldError={
								field.state.meta.isDirty ? field.state.meta.errors : undefined
							}
						/>
					)}
				</form.AppField>
				<form.AppField name="currencyCode">
					{(field) => (
						<CurrencyInput
							mutation={addReceiptMutation}
							topQueryOptions={{ type: "receipts" }}
							value={field.state.value}
							onValueChange={field.setValue}
						/>
					)}
				</form.AppField>
				<form.AppField name="issued">
					{(field) => (
						<DateInput
							label={t("receipt.form.issued.label")}
							name="issued-date"
							value={field.state.value}
							onValueChange={field.setValue}
							mutation={addReceiptMutation}
						/>
					)}
				</form.AppField>
			</form.Form>
			<ContextedAddReceipt
				formStore={form.store}
				defaultFormValues={defaultValues}
				itemsState={itemsState}
				participantsState={participantsState}
				payersState={payersState}
			/>
			<form.Subscribe selector={(state) => state.canSubmit}>
				{(canSubmit) => (
					<Button
						className="mt-4"
						color="primary"
						isDisabled={!canSubmit || addReceiptMutation.isPending}
						isLoading={addReceiptMutation.isPending}
						type="submit"
						form={formId}
					>
						{t("add.saveButton")}
					</Button>
				)}
			</form.Subscribe>
		</form.AppForm>
	);
};