All files / packages/mutations/src/receipt-items add.ts

100% Statements 13/13
100% Branches 0/0
100% Functions 10/10
100% Lines 11/11

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                          78x   2x 2x 2x   2x                     2x             1x 1x   1x                     1x       1x          
import type { ReceiptItemId } from "~db/ids";
import { getRandomUUID } from "~utils/crypto";
 
import {
	update as updateReceipts,
	updateRevert as updateRevertReceipts,
} from "../cache/receipts";
import type { UseContextedMutationOptions } from "../context";
 
export const options: UseContextedMutationOptions<
	"receiptItems.add",
	undefined,
	ReceiptItemId
> = {
	mutationKey: "receiptItems.add",
	onMutate: (controllerContext) => async (variables) => {
		const temporaryId = await getRandomUUID();
		const revertResult = await updateRevertReceipts(controllerContext, {
			get: (controller) =>
				controller.addItem(variables.receiptId, {
					id: temporaryId,
					name: variables.name,
					price: variables.price,
					quantity: variables.quantity,
					createdAt: Temporal.Now.zonedDateTimeISO(),
					consumers: [],
					payers: [],
				}),
			getPaged: undefined,
		});
		return {
			...revertResult,
			context: temporaryId,
		};
	},
	onSuccess:
		(controllerContext) =>
		({ id, createdAt }, variables, temporaryId) => {
			updateReceipts(controllerContext, {
				get: (controller) => {
					controller.updateItem(variables.receiptId, temporaryId, (item) => ({
						...item,
						id,
						createdAt,
					}));
				},
				getPaged: undefined,
			});
		},
	errorToastOptions:
		({ t }) =>
		(errors, variablesSet) => ({
			text: t("toasts.addItem.error", {
				ns: "receipts",
				itemsCount: variablesSet.length,
				items: variablesSet.map((variables) => `"${variables.name}"`),
				errors,
			}),
		}),
};