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

100% Statements 19/19
100% Branches 6/6
100% Functions 10/10
100% Lines 18/18

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                  78x     6x 6x   2x   2x   2x         78x     6x 3x 3x   1x   1x   1x             78x       6x 6x   6x                   3x                
import type { TRPCMutationInput } from "~app/trpc";
import type { ReceiptItem } from "~app/trpc-types";
import type { ReceiptId } from "~db/ids";
 
import { updateRevert as updateRevertReceipts } from "../cache/receipts";
import type { UseContextedMutationOptions } from "../context";
import type { SnapshotFn, UpdateFn } from "../types";
 
const applyUpdate =
	(
		update: TRPCMutationInput<"receiptItems.update">["update"],
	): UpdateFn<ReceiptItem> =>
	(item) => {
		switch (update.type) {
			case "name":
				return { ...item, name: update.name };
			case "price":
				return { ...item, price: update.price };
			case "quantity":
				return { ...item, quantity: update.quantity };
		}
	};
 
const getRevert =
	(
		update: TRPCMutationInput<"receiptItems.update">["update"],
	): SnapshotFn<ReceiptItem> =>
	(snapshot) =>
	(item) => {
		switch (update.type) {
			case "name":
				return { ...item, name: snapshot.name };
			case "price":
				return { ...item, price: snapshot.price };
			case "quantity":
				return { ...item, quantity: snapshot.quantity };
		}
	};
 
export const options: UseContextedMutationOptions<
	"receiptItems.update",
	{ receiptId: ReceiptId }
> = {
	mutationKey: "receiptItems.update",
	onMutate:
		(controllerContext, { receiptId }) =>
		(updateObject) =>
			updateRevertReceipts(controllerContext, {
				get: (controller) =>
					controller.updateItem(
						receiptId,
						updateObject.id,
						applyUpdate(updateObject.update),
						getRevert(updateObject.update),
					),
				getPaged: undefined,
			}),
	errorToastOptions:
		({ t }) =>
		(errors) => ({
			text: t("toasts.updateItem.error", {
				ns: "receipts",
				itemsCount: errors.length,
				errors,
			}),
		}),
};