All files / packages/app/features/receipt receipt-sync-button.tsx

100% Statements 49/49
92.59% Branches 25/27
100% Functions 18/18
100% Lines 48/48

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                                              78x   1062x 1062x   1062x 1062x   347x 724x 724x 103x   687x                 1062x   347x           724x         1062x   347x   724x             1062x   347x   621x         1062x 1344x       1062x 1344x 374x   1344x                     1062x 1x 2x 11x   2x 2x 2x                   1x 2x 6x   2x 2x 2x                                             1342x 1332x   1062x 1116x   1062x 1062x   1062x                                                                       1062x 310x   566x                                
import React from "react";
 
import { skipToken, useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
 
import { suspendedFallback } from "~app/components/suspense-wrapper";
import { useParticipantsWithDebts } from "~app/hooks/use-participants";
import { useTrpcMutationOptions } from "~app/hooks/use-trpc-mutation-options";
import type { Receipt } from "~app/trpc-types";
import { isDebtInSyncWithReceipt } from "~app/utils/debts";
import { getReceiptDebtName } from "~app/utils/receipt";
import { useTRPC } from "~app/utils/trpc";
import { Button } from "~components/button";
import { Icon } from "~components/icons";
import { Tooltip } from "~components/tooltip";
import { options as debtsAddOptions } from "~mutations/debts/add";
import { options as debtsUpdateOptions } from "~mutations/debts/update";
 
type Props = {
	receipt: Receipt;
	isLoading: boolean;
};
 
export const ReceiptSyncButton = suspendedFallback<Props>(
	({ receipt, isLoading }) => {
		const { t } = useTranslation(["receipts", "debts"]);
		const trpc = useTRPC();
		const { participantsWithDebts, syncableParticipants } =
			useParticipantsWithDebts(receipt);
		const ourDebtsParticipants = React.useMemo(
			() =>
				syncableParticipants.map(({ balance, currentDebt, peerId }) => {
					const ourDebt = currentDebt?.our;
					if (!ourDebt) {
						return { sum: balance, peerId };
					}
					return {
						sum: balance,
						debt: { ...ourDebt, id: currentDebt.id },
						peerId,
					};
				}),
			[syncableParticipants],
		);
		// Debts that are already created
		const createdParticipants = React.useMemo(
			() =>
				ourDebtsParticipants.filter(
					(
						participant,
					): participant is Extract<
						typeof participant,
						{ debt: NonNullable<object> }
					> => Boolean(participant.debt),
				),
			[ourDebtsParticipants],
		);
		// Debts not created yet
		const nonCreatedParticipants = React.useMemo(
			() =>
				ourDebtsParticipants.filter(
					(participant) =>
						!createdParticipants.includes(
							participant as (typeof createdParticipants)[number],
						),
				),
			[ourDebtsParticipants, createdParticipants],
		);
		// Debts being de-synced from the receipt
		const desyncedParticipants = React.useMemo(
			() =>
				createdParticipants.filter(
					({ sum, debt }) =>
						!isDebtInSyncWithReceipt({ ...receipt, participantSum: sum }, debt),
				),
			[createdParticipants, receipt],
		);
 
		const addMutations = participantsWithDebts.map(() =>
			useMutation(
				trpc.debts.add.mutationOptions(useTrpcMutationOptions(debtsAddOptions)),
			),
		);
		const updateMutations = participantsWithDebts.map(({ peerId }) => {
			const matchedDesyncedParticipant = desyncedParticipants.find(
				(participant) => participant.peerId === peerId,
			);
			return useMutation(
				trpc.debts.update.mutationOptions(
					useTrpcMutationOptions(debtsUpdateOptions, {
						context: matchedDesyncedParticipant?.debt
							? { currDebt: { ...matchedDesyncedParticipant.debt, peerId } }
							: skipToken,
					}),
				),
			);
		});
 
		const propagateDebts = React.useCallback(() => {
			for (const participant of nonCreatedParticipants) {
				const participantIndex = participantsWithDebts.findIndex(
					({ peerId }) => peerId === participant.peerId,
				);
				const matchedMutation = addMutations[participantIndex];
				Eif (matchedMutation) {
					matchedMutation.mutate({
						note: getReceiptDebtName(receipt.name),
						currencyCode: receipt.currencyCode,
						peerId: participant.peerId,
						amount: participant.sum,
						timestamp: receipt.issued,
						receiptId: receipt.id,
					});
				}
			}
			for (const participant of desyncedParticipants) {
				const participantIndex = participantsWithDebts.findIndex(
					({ peerId }) => peerId === participant.peerId,
				);
				const matchedMutation = updateMutations[participantIndex];
				Eif (matchedMutation) {
					matchedMutation.mutate({
						id: participant.debt.id,
						update: {
							amount: participant.sum,
							currencyCode: receipt.currencyCode,
							timestamp: receipt.issued,
							receiptId: receipt.id,
						},
					});
				}
			}
		}, [
			nonCreatedParticipants,
			desyncedParticipants,
			participantsWithDebts,
			addMutations,
			receipt.name,
			receipt.currencyCode,
			receipt.issued,
			receipt.id,
			updateMutations,
		]);
		const isPropagating =
			addMutations.some((mutation) => mutation.isPending) ||
			updateMutations.some((mutation) => mutation.isPending);
 
		const emptyItemsAmount = receipt.items.filter(
			(item) => item.consumers.length === 0,
		).length;
		const hasDesyncedParticipants = desyncedParticipants.length !== 0;
		const hasNonCreatedParticipants = nonCreatedParticipants.length !== 0;
		const button =
			hasDesyncedParticipants || hasNonCreatedParticipants ? (
				<Button
					variant="ghost"
					title={
						hasDesyncedParticipants
							? t("receipt.syncButton.update")
							: t("receipt.syncButton.propagate")
					}
					isLoading={isPropagating}
					isDisabled={isPropagating || emptyItemsAmount !== 0 || isLoading}
					onPress={propagateDebts}
					color="primary"
					isIconOnly
				>
					{hasDesyncedParticipants ? (
						<Icon name="sync" className="size-6" />
					) : (
						<Icon name="send" className="size-6" />
					)}
				</Button>
			) : (
				<Button
					variant="flat"
					title={t("receipt.syncButton.synced")}
					isDisabled
					color={emptyItemsAmount === 0 ? "success" : "warning"}
					isIconOnly
				>
					{emptyItemsAmount === 0 ? (
						<Icon name="sync" className="size-6" />
					) : (
						<Icon name="unsync" className="size-6" />
					)}
				</Button>
			);
 
		if (emptyItemsAmount === 0) {
			return button;
		}
		return (
			<Tooltip
				content={t("receipt.syncButton.emptyItemsWarning", {
					count: emptyItemsAmount,
				})}
				placement="bottom-end"
				skipMobile
			>
				{button}
			</Tooltip>
		);
	},
	<Button variant="flat" isDisabled color="success" isIconOnly>
		<Icon name="sync" className="size-6" />
	</Button>,
);