All files / packages/app/features/add-receipt hooks.ts

80.26% Statements 122/152
39.39% Branches 13/33
76.25% Functions 61/80
80.95% Lines 119/147

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 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470                                                      18x 106x   8x 8x                                 18x 106x   2x 3x           18x 954x           8x 8x 8x       8x   8x     8x                   18x 106x 106x 1x         18x 106x 106x 1x         18x 106x 106x 1x         18x 106x 106x   4x   4x       2x                     18x 106x 106x                             18x 106x 106x   1x     1x 1x 2x   1x     1x                             18x 106x 106x                                     18x 106x 106x                             18x 106x 106x                                                     18x 106x   1x 1x                   18x 106x                 18x 106x           1x 1x 1x       1x   1x     1x                   18x 106x 106x 1x         18x 106x   11x 11x     8x                 18x       106x   1x   1x 1x       1x   1x                         18x 106x           1x 1x 1x   1x       1x   1x     1x                   18x 106x 106x 1x         18x         106x   19x 19x 19x 19x             106x   13x 13x 13x 13x             106x   2x 2x 2x 2x             106x                                         18x             106x                   25x 106x      
import React from "react";
 
import type {
	useActionHooks as useActionHooksRaw,
	useGetReceiptContext,
} from "~app/features/receipt/hooks";
import type { EmptyMutateOptions } from "~app/utils/queries";
import type { PeerId, ReceiptId, ReceiptItemId } from "~db/ids";
 
import type { Form, Item, Participant, Payer } from "./state";
 
type ActionsHooks = ReturnType<typeof useActionHooksRaw>;
type ReceiptContext = ReturnType<typeof useGetReceiptContext>;
 
type SetItems = (
	setStateAction: React.SetStateAction<Item[]>,
	options: EmptyMutateOptions | undefined,
) => void;
type SetParticipants = (
	setStateAction: React.SetStateAction<Participant[]>,
	options: EmptyMutateOptions | undefined,
) => void;
type SetPayers = (
	setStateAction: React.SetStateAction<Payer[]>,
	options: EmptyMutateOptions | undefined,
) => void;
 
const useAddItem = (setItems: SetItems) =>
	React.useCallback<ActionsHooks["addItem"]>(
		(name, price, quantity, options) =>
			setItems(
				(prevItems) => [
					...prevItems,
					{
						id: `new-item-${prevItems.length}`,
						name,
						price,
						quantity,
						consumers: [],
						payers: [],
						createdAt: Temporal.Now.zonedDateTimeISO(),
					},
				],
				options,
			),
		[setItems],
	);
 
const useRemoveItem = (setItems: SetItems) =>
	React.useCallback<ActionsHooks["removeItem"]>(
		(itemId, options) =>
			setItems(
				(prevItems) => prevItems.filter((item) => item.id !== itemId),
				options,
			),
		[setItems],
	);
 
const useUpdateItem = (setItems: SetItems) =>
	React.useCallback(
		(
			itemId: ReceiptItemId,
			setStateAction: React.SetStateAction<Partial<Item>>,
			options: EmptyMutateOptions | undefined,
		) => {
			setItems((prevItems) => {
				const index = prevItems.findIndex((item) => item.id === itemId);
				Iif (index === -1) {
					return prevItems;
				}
				// oxlint-disable-next-line typescript/no-non-null-assertion
				const prevItem = prevItems[index]!;
				const nextItemPartial =
					typeof setStateAction === "function"
						? setStateAction(prevItem)
						: setStateAction;
				return [
					...prevItems.slice(0, index),
					{ ...prevItem, ...nextItemPartial },
					...prevItems.slice(index + 1),
				];
			}, options);
		},
		[setItems],
	);
 
const useUpdateItemName = (setItems: SetItems) => {
	const updateItem = useUpdateItem(setItems);
	return React.useCallback<ActionsHooks["updateItemName"]>(
		(itemId, name, options) => updateItem(itemId, { name }, options),
		[updateItem],
	);
};
 
const useUpdateItemPrice = (setItems: SetItems) => {
	const updateItem = useUpdateItem(setItems);
	return React.useCallback<ActionsHooks["updateItemPrice"]>(
		(itemId, price, options) => updateItem(itemId, { price }, options),
		[updateItem],
	);
};
 
const useUpdateItemQuantity = (setItems: SetItems) => {
	const updateItem = useUpdateItem(setItems);
	return React.useCallback<ActionsHooks["updateItemQuantity"]>(
		(itemId, quantity, options) => updateItem(itemId, { quantity }, options),
		[updateItem],
	);
};
 
const useAddItemConsumer = (setItems: SetItems) => {
	const updateItem = useUpdateItem(setItems);
	return React.useCallback<ActionsHooks["addItemConsumer"]>(
		(itemId, peerId, part, options) =>
			updateItem(
				itemId,
				(prevItem) => ({
					// Remove accidentally added double participants
					consumers: [
						...(prevItem.consumers || []).filter(
							({ peerId: lookupPeerId }) => lookupPeerId !== peerId,
						),
						{ peerId, part, createdAt: Temporal.Now.zonedDateTimeISO() },
					],
				}),
				options,
			),
		[updateItem],
	);
};
 
const useRemoveItemConsumer = (setItems: SetItems) => {
	const updateItem = useUpdateItem(setItems);
	return React.useCallback<ActionsHooks["removeItemConsumer"]>(
		(itemId, peerId, options) =>
			updateItem(
				itemId,
				(prevItem) => ({
					consumers: (prevItem.consumers || []).filter(
						({ peerId: lookupPeerId }) => lookupPeerId !== peerId,
					),
				}),
				options,
			),
		[updateItem],
	);
};
 
const useUpdateItemConsumerPart = (setItems: SetItems) => {
	const updateItem = useUpdateItem(setItems);
	return React.useCallback<ActionsHooks["updateItemConsumerPart"]>(
		(itemId, peerId, part, options) =>
			updateItem(
				itemId,
				(prevItem) => {
					const prevConsumers = prevItem.consumers || [];
					const matchedPartIndex = prevConsumers.findIndex(
						({ peerId: lookupPeerId }) => peerId === lookupPeerId,
					);
					Iif (matchedPartIndex === -1) {
						return {};
					}
					return {
						consumers: [
							...prevConsumers.slice(0, matchedPartIndex),
							// oxlint-disable-next-line typescript/no-non-null-assertion
							{ ...prevConsumers[matchedPartIndex]!, part },
							...prevConsumers.slice(matchedPartIndex + 1),
						],
					};
				},
				options,
			),
		[updateItem],
	);
};
 
const useAddItemPayer = (setItems: SetItems) => {
	const updateItem = useUpdateItem(setItems);
	return React.useCallback<ActionsHooks["addItemPayer"]>(
		(itemId, peerId, part, options) =>
			updateItem(
				itemId,
				(prevItem) => ({
					// Remove accidentally added double participants
					payers: [
						...(prevItem.payers || []).filter(
							({ peerId: lookupPeerId }) => lookupPeerId !== peerId,
						),
						{ peerId, part, createdAt: Temporal.Now.zonedDateTimeISO() },
					],
				}),
				options,
			),
		[updateItem],
	);
};
 
const useRemoveItemPayer = (setItems: SetItems) => {
	const updateItem = useUpdateItem(setItems);
	return React.useCallback<ActionsHooks["removeItemPayer"]>(
		(itemId, peerId, options) =>
			updateItem(
				itemId,
				(prevItem) => ({
					payers: (prevItem.payers || []).filter(
						({ peerId: lookupPeerId }) => lookupPeerId !== peerId,
					),
				}),
				options,
			),
		[updateItem],
	);
};
 
const useUpdateItemPayerPart = (setItems: SetItems) => {
	const updateItem = useUpdateItem(setItems);
	return React.useCallback<ActionsHooks["updateItemPayerPart"]>(
		(itemId, peerId, part, options) =>
			updateItem(
				itemId,
				(prevItem) => {
					const prevPayers = prevItem.payers || [];
					const matchedPartIndex = prevPayers.findIndex(
						({ peerId: lookupPeerId }) => peerId === lookupPeerId,
					);
					if (matchedPartIndex === -1) {
						return {};
					}
					return {
						payers: [
							...prevPayers.slice(0, matchedPartIndex),
							// oxlint-disable-next-line typescript/no-non-null-assertion
							{ ...prevPayers[matchedPartIndex]!, part },
							...prevPayers.slice(matchedPartIndex + 1),
						],
					};
				},
				options,
			),
		[updateItem],
	);
};
 
const useAddPayer = (setPayers: SetPayers) =>
	React.useCallback<ActionsHooks["addPayer"]>(
		(peerId, part, options) =>
			setPayers(
				(prevPayers) => [
					// Remove accidentally added double participants
					...prevPayers.filter((payer) => payer.peerId !== peerId),
					{ createdAt: Temporal.Now.zonedDateTimeISO(), peerId, part },
				],
				options,
			),
		[setPayers],
	);
 
const useRemovePayer = (setPayers: SetPayers) =>
	React.useCallback<ActionsHooks["removePayer"]>(
		(peerId, options) =>
			setPayers(
				(prevPayers) => prevPayers.filter((payer) => payer.peerId !== peerId),
				options,
			),
		[setPayers],
	);
 
const useUpdatePayers = (setPayers: SetPayers) =>
	React.useCallback(
		(
			options: EmptyMutateOptions | undefined,
			peerId: PeerId,
			setStateAction: React.SetStateAction<Partial<Payer>>,
		) => {
			setPayers((prevPayers) => {
				const index = prevPayers.findIndex((payer) => payer.peerId === peerId);
				Iif (index === -1) {
					return prevPayers;
				}
				// oxlint-disable-next-line typescript/no-non-null-assertion
				const prevPayer = prevPayers[index]!;
				const nextPayerPartial =
					typeof setStateAction === "function"
						? setStateAction(prevPayer)
						: setStateAction;
				return [
					...prevPayers.slice(0, index),
					{ ...prevPayer, ...nextPayerPartial },
					...prevPayers.slice(index + 1),
				];
			}, options);
		},
		[setPayers],
	);
 
const useUpdatePayerPart = (setPayers: SetPayers) => {
	const updatePayer = useUpdatePayers(setPayers);
	return React.useCallback<ActionsHooks["updatePayerPart"]>(
		(peerId, part, options) => updatePayer(options, peerId, { part }),
		[updatePayer],
	);
};
 
const useAddParticipant = (setParticipants: SetParticipants) =>
	React.useCallback<ActionsHooks["addParticipant"]>(
		(peerId, role, options) =>
			setParticipants(
				(prevParticipants) => [
					// Remove accidentally added double participants
					...prevParticipants.filter(
						(participant) => participant.peerId !== peerId,
					),
					{ createdAt: Temporal.Now.zonedDateTimeISO(), role, peerId },
				],
				options,
			),
		[setParticipants],
	);
 
const useRemoveParticipant = (
	setParticipants: SetParticipants,
	setItems: SetItems,
) =>
	React.useCallback<ActionsHooks["removeParticipant"]>(
		(peerId, options) => {
			setParticipants(
				(prevParticipants) =>
					prevParticipants.filter(
						(participant) => participant.peerId !== peerId,
					),
				options,
			);
			setItems(
				(items) =>
					items.map((item) => ({
						...item,
						consumers: item.consumers.filter(
							(consumer) => consumer.peerId !== peerId,
						),
						payers: item.payers.filter((payer) => payer.peerId !== peerId),
					})),
				undefined,
			);
		},
		[setParticipants, setItems],
	);
 
const useUpdateParticipant = (setParticipants: SetParticipants) =>
	React.useCallback(
		(
			options: EmptyMutateOptions | undefined,
			peerId: PeerId,
			setStateAction: React.SetStateAction<Partial<Participant>>,
		) => {
			setParticipants((prevParticipants) => {
				const index = prevParticipants.findIndex(
					(participant) => participant.peerId === peerId,
				);
				Iif (index === -1) {
					return prevParticipants;
				}
				// oxlint-disable-next-line typescript/no-non-null-assertion
				const prevParticipant = prevParticipants[index]!;
				const nextParticipantPartial =
					typeof setStateAction === "function"
						? setStateAction(prevParticipant)
						: setStateAction;
				return [
					...prevParticipants.slice(0, index),
					{ ...prevParticipant, ...nextParticipantPartial },
					...prevParticipants.slice(index + 1),
				];
			}, options);
		},
		[setParticipants],
	);
 
const useUpdateParticipantRole = (setParticipants: SetParticipants) => {
	const updateParticipant = useUpdateParticipant(setParticipants);
	return React.useCallback<ActionsHooks["updateParticipantRole"]>(
		(peerId, role, options) => updateParticipant(options, peerId, { role }),
		[updateParticipant],
	);
};
 
export const useActionsHooks = (
	setRawItems: React.Dispatch<React.SetStateAction<Item[]>>,
	setRawParticipants: React.Dispatch<React.SetStateAction<Participant[]>>,
	setRawPayers: React.Dispatch<React.SetStateAction<Payer[]>>,
): ActionsHooks => {
	const setItems = React.useCallback<SetItems>(
		(setStateAction, options = {}) => {
			try {
				setRawItems(setStateAction);
				options.onSettled?.();
				options.onSuccess?.();
			} catch {
				options.onError?.();
			}
		},
		[setRawItems],
	);
	const setParticipants = React.useCallback<SetParticipants>(
		(setStateAction, options = {}) => {
			try {
				setRawParticipants(setStateAction);
				options.onSettled?.();
				options.onSuccess?.();
			} catch {
				options.onError?.();
			}
		},
		[setRawParticipants],
	);
	const setPayers = React.useCallback<SetPayers>(
		(setStateAction, options = {}) => {
			try {
				setRawPayers(setStateAction);
				options.onSettled?.();
				options.onSuccess?.();
			} catch {
				options.onError?.();
			}
		},
		[setRawPayers],
	);
	return {
		addItem: useAddItem(setItems),
		removeItem: useRemoveItem(setItems),
		updateItemName: useUpdateItemName(setItems),
		updateItemPrice: useUpdateItemPrice(setItems),
		updateItemQuantity: useUpdateItemQuantity(setItems),
		addItemConsumer: useAddItemConsumer(setItems),
		removeItemConsumer: useRemoveItemConsumer(setItems),
		updateItemConsumerPart: useUpdateItemConsumerPart(setItems),
		addItemPayer: useAddItemPayer(setItems),
		removeItemPayer: useRemoveItemPayer(setItems),
		updateItemPayerPart: useUpdateItemPayerPart(setItems),
		addParticipant: useAddParticipant(setParticipants),
		removeParticipant: useRemoveParticipant(setParticipants, setItems),
		updateParticipantRole: useUpdateParticipantRole(setParticipants),
		addPayer: useAddPayer(setPayers),
		removePayer: useRemovePayer(setPayers),
		updatePayerPart: useUpdatePayerPart(setPayers),
	};
};
 
export const useAddReceiptContext = (
	form: Partial<Form>,
	receiptId: ReceiptId,
	selfPeerId: PeerId,
	payers: ReceiptContext["payers"],
	items: ReceiptContext["items"],
	participants: ReceiptContext["participants"],
): ReceiptContext => ({
	receiptId,
	selfPeerId,
	ownerPeerId: selfPeerId,
	payers,
	currencyCode: form.currencyCode ?? "???",
	receiptDisabled: false,
	confirmItemRemoval: false,
	items,
	participants,
	renderParticipantActions: () => null,
	getPeersSuggestOptions: () => undefined,
	emptyReceiptElement: null,
});