All files / apps/web/src/handlers/debts add.ts

100% Statements 82/82
100% Branches 41/41
100% Functions 32/32
100% Lines 78/78

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                                    6x                 6x       22x 14x     22x       14x       14x     14x                                   5x   5x                     14x     6x 50x   6x       21x                 20x     6x         14x       16x 16x         4x   12x                           14x 10x 2x   14x 7x 8x                   7x   14x   16x 12x   4x 4x   2x     4x 2x   2x                 6x             14x 4x   10x       16x                           10x 16x     25x 16x       6x                 14x 14x 14x 22x 22x 3x         19x 1x         18x 1x         17x   1x   17x 1x         16x   14x   22x   14x         14x   14x 5x   14x 14x 22x 6x     16x   22x 25x                   16x                   6x                
import { TRPCError } from "@trpc/server";
import { isNonNullish, unique } from "remeda";
import { z } from "zod";
 
import { debtAmountSchema, debtNoteSchema } from "~app/utils/validation";
import type { DebtId } from "~db/ids";
import { temporalSchemas } from "~utils/temporal";
import { queueCallFactory } from "~web/handlers/batch";
import type { AuthorizedContext } from "~web/handlers/context";
import { authProcedure } from "~web/handlers/trpc";
import {
	currencyCodeSchema,
	peerIdSchema,
	receiptIdSchema,
} from "~web/handlers/validation";
 
import { upsertAutoAcceptedDebts } from "./utils";
 
const addDebtSchema = z.strictObject({
	note: debtNoteSchema,
	currencyCode: currencyCodeSchema,
	peerId: peerIdSchema,
	amount: debtAmountSchema,
	timestamp: temporalSchemas.plainDate.optional(),
	receiptId: receiptIdSchema.optional(),
});
 
const getData = async (
	ctx: AuthorizedContext,
	debts: readonly z.infer<typeof addDebtSchema>[],
) => {
	const peerIds = unique(debts.map(({ peerId }) => peerId));
	const receiptPeerTuples = unique(
		debts
			.map(({ receiptId, peerId }) =>
				receiptId ? { receiptId, peerId } : undefined,
			)
			.filter(isNonNullish),
	);
	const [peers, debtReceiptTuples] = await Promise.all([
		ctx.database
			.selectFrom("peers")
			.leftJoin("userSettings", (qb) =>
				qb.onRef("peers.connectedUserId", "=", "userSettings.userId"),
			)
			.leftJoin("peers as peersTheir", (qb) =>
				qb
					.onRef("peersTheir.ownerUserId", "=", "peers.connectedUserId")
					.on("peersTheir.connectedUserId", "=", ctx.auth.userId),
			)
			.select([
				"peers.id as peerId",
				"peers.ownerUserId as selfUserId",
				"peers.connectedUserId as foreignUserId",
				"peersTheir.id as theirPeerId",
				"userSettings.manualAcceptDebts",
			])
			.where("peers.id", "in", peerIds)
			.execute(),
		receiptPeerTuples.length === 0
			? []
			: ctx.database
					.selectFrom("debts")
					.where((eb) =>
						eb.or(
							receiptPeerTuples.map(({ receiptId, peerId }) =>
								eb.and({
									"debts.receiptId": receiptId,
									"debts.peerId": peerId,
								}),
							),
						),
					)
					.where("debts.ownerUserId", "=", ctx.auth.userId)
					.select(["debts.peerId", "debts.receiptId"])
					.execute(),
	]);
	return { peers, debtReceiptTuples };
};
 
const getDebtPeerReceiptTupleId = (debt: z.infer<typeof addDebtSchema>) =>
	`${debt.peerId}/${debt.receiptId}`;
 
const getMatchedPeer = (
	debt: z.infer<typeof addDebtSchema>,
	peers: Awaited<ReturnType<typeof getData>>["peers"],
) => {
	const matchedPeer = peers.find((peer) => peer.peerId === debt.peerId);
	/* c8 ignore start */
	if (!matchedPeer) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: `Expected to have a matched peer id "${debt.peerId}".`,
		});
	}
	/* c8 ignore stop */
	return matchedPeer;
};
 
const addAutoAcceptingDebts = async (
	ctx: AuthorizedContext,
	peers: Awaited<ReturnType<typeof getData>>["peers"],
	debts: (z.infer<typeof addDebtSchema> & { generatedId: DebtId })[],
) => {
	const { updatedDebts, newDebts } = await upsertAutoAcceptedDebts(
		ctx.database,
		debts
			.map(({ generatedId, ...debt }) => {
				const peer = getMatchedPeer(debt, peers);
				if (
					!peer.foreignUserId ||
					!peer.theirPeerId ||
					peer.manualAcceptDebts
				) {
					return null;
				}
				return {
					id: generatedId,
					note: debt.note,
					currencyCode: debt.currencyCode,
					timestamp: debt.timestamp || Temporal.Now.plainDateISO(),
					receiptId: debt.receiptId,
					ownerUserId: peer.foreignUserId,
					peerId: peer.theirPeerId,
					amount: (-debt.amount).toString(),
					isNew: true,
				};
			})
			.filter(isNonNullish),
	);
	const acceptingReversePeerIds = unique([
		...newDebts.map((debt) => debt.peerId),
		...updatedDebts.map((debt) => debt.peerId),
	]);
	const acceptedPeerIds = acceptingReversePeerIds.map((reversePeerId) => {
		const matchedPeer = peers.find(
			(peer) => peer.theirPeerId === reversePeerId,
		);
		/* c8 ignore start */
		if (!matchedPeer) {
			throw new TRPCError({
				code: "INTERNAL_SERVER_ERROR",
				message: `Expected to have a peer for reverse peer id "${reversePeerId}".`,
			});
		}
		/* c8 ignore stop */
		return matchedPeer.peerId;
	});
	return {
		reverseIdMap: debts.reduce<Partial<Record<string, DebtId>>>((acc, debt) => {
			if (!debt.receiptId) {
				return acc;
			}
			const matchedPeer = getMatchedPeer(debt, peers);
			const matchedUpdatedDebt = updatedDebts.find(
				(lookupDebt) =>
					lookupDebt.receiptId === debt.receiptId &&
					lookupDebt.peerId === matchedPeer.theirPeerId,
			);
			if (!matchedUpdatedDebt) {
				return acc;
			}
			return {
				...acc,
				[getDebtPeerReceiptTupleId(debt)]: matchedUpdatedDebt.id,
			};
		}, {}),
		acceptedPeerIds,
	};
};
 
const addDebts = async (
	ctx: AuthorizedContext,
	debts: (z.infer<typeof addDebtSchema> & { generatedId: DebtId })[],
	reverseIdMap: Awaited<
		ReturnType<typeof addAutoAcceptingDebts>
	>["reverseIdMap"],
) => {
	if (debts.length === 0) {
		return [];
	}
	const values = await ctx.database
		.insertInto("debts")
		.values(
			debts
				.map(({ generatedId, ...debt }) => ({
					id: reverseIdMap[getDebtPeerReceiptTupleId(debt)] || generatedId,
					note: debt.note,
					currencyCode: debt.currencyCode,
					timestamp: debt.timestamp || Temporal.Now.plainDateISO(),
					receiptId: debt.receiptId,
					ownerUserId: ctx.auth.userId,
					peerId: debt.peerId,
					amount: debt.amount.toString(),
				}))
				.filter(isNonNullish),
		)
		.returning(["debts.id", "debts.updatedAt"])
		.execute();
	return debts.map(({ generatedId, ...debt }) => {
		const id = reverseIdMap[getDebtPeerReceiptTupleId(debt)] || generatedId;
		// We just added these value, should be returned in `values` variable
		// oxlint-disable-next-line typescript/no-non-null-assertion
		const { updatedAt } = values.find(({ id: lookupId }) => lookupId === id)!;
		return { id, updatedAt };
	});
};
 
const queueAddDebt = queueCallFactory<
	AuthorizedContext,
	z.infer<typeof addDebtSchema>,
	{
		id: DebtId;
		updatedAt: Temporal.ZonedDateTime;
		// `undefined` signifies that peer is local
		reverseAccepted: boolean | undefined;
	}
>((ctx) => async (inputs) => {
	const { peers, debtReceiptTuples } = await getData(ctx, inputs);
	const debtsOrErrors = inputs.map((debt) => {
		const matchedPeer = peers.find((result) => result.peerId === debt.peerId);
		if (!matchedPeer) {
			return new TRPCError({
				code: "NOT_FOUND",
				message: `Peer "${debt.peerId}" does not exist.`,
			});
		}
		if (matchedPeer.selfUserId !== ctx.auth.userId) {
			return new TRPCError({
				code: "FORBIDDEN",
				message: `Peer "${debt.peerId}" is not owned by "${ctx.auth.email}".`,
			});
		}
		if (debt.peerId === matchedPeer.selfUserId) {
			return new TRPCError({
				code: "FORBIDDEN",
				message: `Cannot add a debt for yourself.`,
			});
		}
		const matchedDebtReceipt = debtReceiptTuples.find(
			({ peerId, receiptId }) =>
				peerId === debt.peerId && receiptId === debt.receiptId,
		);
		if (matchedDebtReceipt) {
			return new TRPCError({
				code: "FORBIDDEN",
				message: `There is already a debt for peer "${matchedDebtReceipt.peerId}" in receipt "${matchedDebtReceipt.receiptId}".`,
			});
		}
		return { ...debt, generatedId: ctx.getUuid() };
	});
	const debts = debtsOrErrors.filter(
		(debtOrError): debtOrError is Exclude<typeof debtOrError, TRPCError> =>
			!(debtOrError instanceof TRPCError),
	);
	const { reverseIdMap, acceptedPeerIds } = await addAutoAcceptingDebts(
		ctx,
		peers,
		debts,
	);
	const localPeerIds = new Set(
		peers
			.filter((peer) => peer.foreignUserId === null)
			.map((peer) => peer.peerId),
	);
	const addedDebts = await addDebts(ctx, debts, reverseIdMap);
	return debtsOrErrors.map((debtOrError) => {
		if (debtOrError instanceof TRPCError) {
			return debtOrError;
		}
		const id =
			reverseIdMap[getDebtPeerReceiptTupleId(debtOrError)] ||
			debtOrError.generatedId;
		const matchedAddedDebt = addedDebts.find(
			(addedDebt) => addedDebt.id === id,
		);
		/* c8 ignore start */
		if (!matchedAddedDebt) {
			return new TRPCError({
				code: "INTERNAL_SERVER_ERROR",
				message: `Expected to have matched added debt for id "${id}".`,
			});
		}
		/* c8 ignore stop */
		return {
			id,
			updatedAt: matchedAddedDebt.updatedAt,
			reverseAccepted: localPeerIds.has(debtOrError.peerId)
				? undefined
				: acceptedPeerIds.includes(debtOrError.peerId),
		};
	});
});
 
export const procedure = authProcedure
	.meta({
		title: "Add debt",
		description:
			"Adds a debt for a given peerId, auto-accepting the mirrored debt on the counterparty's  user unless they require manual acceptance.",
	})
	.input(addDebtSchema)
	.mutation(queueAddDebt);