All files / packages/mutations/src/receipt-item-consumers add.ts

100% Statements 19/19
100% Branches 4/4
100% Functions 14/14
100% Lines 17/17

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                          78x       6x 6x 2x   2x               4x   4x                       4x 4x 1x   1x               3x   3x       3x               2x         2x 2x            
import type { ReceiptId } from "~db/ids";
 
import {
	update as updateReceipts,
	updateRevert as updateRevertReceipts,
} from "../cache/receipts";
import type { UseContextedMutationOptions } from "../context";
 
import { getConsumersItems } from "./utils";
 
export const options: UseContextedMutationOptions<
	"receiptItemConsumers.add",
	{ receiptId: ReceiptId }
> = {
	mutationKey: "receiptItemConsumers.add",
	onMutate:
		(controllerContext, { receiptId }) =>
		(variables) => {
			if (variables.itemId === receiptId) {
				return updateRevertReceipts(controllerContext, {
					get: (controller) =>
						controller.addPayer(receiptId, {
							peerId: variables.peerId,
							part: variables.part,
							createdAt: Temporal.Now.zonedDateTimeISO(),
						}),
					getPaged: undefined,
				});
			}
			return updateRevertReceipts(controllerContext, {
				get: (controller) =>
					controller.addItemConsumer(
						receiptId,
						variables.itemId,
						variables.peerId,
						variables.part,
						Temporal.Now.zonedDateTimeISO(),
					),
				getPaged: undefined,
			});
		},
	onSuccess:
		(controllerContext, { receiptId }) =>
		(result, variables) => {
			if (variables.itemId === receiptId) {
				return updateReceipts(controllerContext, {
					get: (controller) => {
						controller.updatePayer(receiptId, variables.peerId, (payer) => ({
							...payer,
							createdAt: result.createdAt,
						}));
					},
					getPaged: undefined,
				});
			}
			updateReceipts(controllerContext, {
				get: (controller) => {
					controller.updateItemConsumer(
						receiptId,
						variables.itemId,
						variables.peerId,
						(consumer) => ({ ...consumer, createdAt: result.createdAt }),
					);
				},
				getPaged: undefined,
			});
		},
	errorToastOptions:
		({ t }, contexts) =>
		(errors, variablesSet) => ({
			text: t("toasts.addConsumer.error", {
				ns: "receipts",
				items: getConsumersItems(
					t,
					variablesSet.map(({ itemId }) => itemId),
					contexts.map((context) => context.receiptId),
				),
				errors,
			}),
		}),
};