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

100% Statements 75/75
100% Branches 29/29
100% Functions 32/32
100% Lines 74/74

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                                      6x                       58x     7x   51x 1x                     6x 45x               225x   45x                 111x   45x           6x       35x     35x     48x       35x         35x     35x                                               6x     6x   6x 35x 45x 12x   45x 42x   3x 3x                             6x       35x   42x 42x 27x                           15x     35x 14x   21x       21x   27x 23x   27x 25x   2x         6x       35x 2x   33x 33x   42x       42x             42x             33x     6x               35x 35x 35x 55x 48x 3x         45x   35x       48x   35x 35x       35x   42x 2x   35x 48x 3x   45x 54x                   45x                 6x                
import { TRPCError } from "@trpc/server";
import type { Updateable } from "kysely";
import { isNonNullish, keys, omitBy, unique } from "remeda";
import { z } from "zod";
 
import { debtAmountSchema, debtNoteSchema } from "~app/utils/validation";
import type { DB } from "~db/types.gen";
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,
	debtIdSchema,
	receiptIdSchema,
} from "~web/handlers/validation";
 
import { upsertAutoAcceptedDebts } from "./utils";
 
const updateDebtSchema = z.strictObject({
	id: debtIdSchema,
	update: z
		.strictObject({
			amount: debtAmountSchema,
			timestamp: temporalSchemas.plainDate,
			note: debtNoteSchema,
			currencyCode: currencyCodeSchema,
			receiptId: receiptIdSchema.optional(),
		})
		.partial()
		.check((ctx) => {
			if (ctx.issues.length !== 0) {
				// Short-circuit on continuable errors
				// It doesn't make sense to nag on object emptiness if some other error happened
				return;
			}
			if (keys(ctx.value).length === 0) {
				ctx.issues.push({
					code: "custom",
					message: "Update object has to have at least one key to update",
					input: ctx.value,
				});
			}
		}),
});
 
type DebtUpdateObject = Updateable<DB["debts"]>;
 
const buildSetObjects = (input: z.infer<typeof updateDebtSchema>) => {
	const setObject: DebtUpdateObject = omitBy(
		{
			amount: input.update.amount?.toString(),
			timestamp: input.update.timestamp,
			note: input.update.note,
			currencyCode: input.update.currencyCode,
			receiptId: input.update.receiptId,
		},
		(value) => value === undefined,
	);
	const reverseSetObject = omitBy(
		{
			...setObject,
			note: undefined,
			amount:
				input.update.amount === undefined
					? undefined
					: (-input.update.amount).toString(),
		},
		(value) => value === undefined,
	);
	return {
		setObject,
		reverseSetObject,
	};
};
 
const fetchDebts = async (
	ctx: AuthorizedContext,
	updates: readonly z.infer<typeof updateDebtSchema>[],
) =>
	ctx.database
		.selectFrom("debts")
		.where((eb) =>
			eb(
				"debts.id",
				"in",
				updates.map((update) => update.id),
			).and("debts.ownerUserId", "=", ctx.auth.userId),
		)
		.innerJoin("peers", (qb) =>
			qb
				.onRef("peers.id", "=", "debts.peerId")
				.onRef("peers.ownerUserId", "=", "debts.ownerUserId"),
		)
		.leftJoin("userSettings", (qb) =>
			qb.onRef("peers.connectedUserId", "=", "userSettings.userId"),
		)
		.leftJoin("peers as peersTheir", (qb) =>
			qb
				.onRef("peersTheir.connectedUserId", "=", "debts.ownerUserId")
				.onRef("peersTheir.ownerUserId", "=", "peers.connectedUserId"),
		)
		.select([
			"debts.id",
			"debts.peerId",
			"debts.updatedAt",
			"debts.note",
			"debts.currencyCode",
			"debts.amount",
			"debts.timestamp",
			"debts.receiptId",
			"peers.connectedUserId as foreignUserId",
			"userSettings.manualAcceptDebts",
			"peersTheir.id as theirPeerId",
		])
		.execute();
 
type Debt = Awaited<ReturnType<typeof fetchDebts>>[number];
type UpdateWithDebt = ReturnType<typeof buildSetObjects> & {
	debt: Debt;
};
 
const mergeSetObjects = <T extends DebtUpdateObject>(
	setObjectA: T,
	setObjectB: T,
): T => ({ ...setObjectA, ...setObjectB });
 
const mergeUpdates = (debtsToUpdate: UpdateWithDebt[]): UpdateWithDebt[] =>
	debtsToUpdate.reduce<UpdateWithDebt[]>((acc, debtToUpdate) => {
		const previousDebt = acc.find(
			({ debt }) => debt.id === debtToUpdate.debt.id,
		);
		if (!previousDebt) {
			return [...acc, debtToUpdate];
		}
		return [
			...acc.filter(({ debt }) => debt.id !== debtToUpdate.debt.id),
			{
				debt: debtToUpdate.debt,
				setObject: mergeSetObjects(
					debtToUpdate.setObject,
					previousDebt.setObject,
				),
				reverseSetObject: mergeSetObjects(
					debtToUpdate.reverseSetObject,
					previousDebt.reverseSetObject,
				),
			},
		];
	}, []);
 
const updateAutoAcceptingDebts = async (
	ctx: AuthorizedContext,
	debtsToUpdate: UpdateWithDebt[],
) => {
	const autoAcceptedData = debtsToUpdate
		.map((debtToUpdate) => {
			const { debt, setObject, reverseSetObject } = debtToUpdate;
			if (!debt.manualAcceptDebts && debt.foreignUserId && debt.theirPeerId) {
				return {
					id: debt.id,
					ownerUserId: debt.foreignUserId,
					peerId: debt.theirPeerId,
					currencyCode: debt.currencyCode,
					amount: (-Number(debt.amount)).toString(),
					timestamp: debt.timestamp,
					receiptId: debt.receiptId,
					...reverseSetObject,
					// In case debt doesn't exist - we need to set a new note, not the old one
					note: setObject.note || debt.note,
					isNew: false,
				};
			}
			return null;
		})
		.filter(isNonNullish);
	if (autoAcceptedData.length === 0) {
		return [];
	}
	const { newDebts } = await upsertAutoAcceptedDebts(
		ctx.database,
		autoAcceptedData,
	);
	return debtsToUpdate
		.map((debtToUpdate) => {
			const newDebtAdded = newDebts.some(
				(debt) => debtToUpdate.debt.id === debt.id,
			);
			if (keys(debtToUpdate.reverseSetObject).length !== 0 || newDebtAdded) {
				return debtToUpdate.debt.id;
			}
			return undefined;
		})
		.filter(isNonNullish);
};
 
const updateDebts = async (
	ctx: AuthorizedContext,
	debtsToUpdate: UpdateWithDebt[],
) => {
	if (debtsToUpdate.length === 0) {
		return [];
	}
	const results = await ctx.database.transaction().execute((tx) =>
		Promise.all(
			debtsToUpdate.map(async (debtToUpdate) => {
				const { id, updatedAt } = await tx
					.updateTable("debts")
					.set(debtToUpdate.setObject)
					.where((eb) =>
						eb.and({
							id: debtToUpdate.debt.id,
							ownerUserId: ctx.auth.userId,
						}),
					)
					.returning(["debts.id", "debts.updatedAt"])
					.executeTakeFirstOrThrow();
				return {
					id,
					updatedAt,
				};
			}),
		),
	);
	return results;
};
 
const queueUpdateDebt = queueCallFactory<
	AuthorizedContext,
	z.infer<typeof updateDebtSchema>,
	{
		updatedAt: Temporal.ZonedDateTime;
		// `undefined` signifies that peer is local
		reverseUpdated: boolean | undefined;
	}
>((ctx) => async (updates) => {
	const debts = await fetchDebts(ctx, updates);
	const updatesOrErrors = updates.map((update) => {
		const matchedDebt = debts.find((debt) => debt.id === update.id);
		if (!matchedDebt) {
			return new TRPCError({
				code: "NOT_FOUND",
				message: `Debt "${update.id}" does not exist on  user "${ctx.auth.email}".`,
			});
		}
		return { ...buildSetObjects(update), debt: matchedDebt };
	});
	const debtsToUpdate = updatesOrErrors.filter(
		(
			updateOrError,
		): updateOrError is Exclude<typeof updateOrError, TRPCError> =>
			!(updateOrError instanceof TRPCError),
	);
	const mergedDebts = mergeUpdates(debtsToUpdate);
	const [reverseUpdatedDebtsIds, updatedDebts] = await Promise.all([
		updateAutoAcceptingDebts(ctx, mergedDebts),
		updateDebts(ctx, mergedDebts),
	]);
	const localPeerIds = unique(
		debts
			.filter((debt) => debt.foreignUserId === null)
			.map((debt) => debt.peerId),
	);
	return updatesOrErrors.map((updateOrError) => {
		if (updateOrError instanceof TRPCError) {
			return updateOrError;
		}
		const matchedDebt = updatedDebts.find(
			(debt) => debt.id === updateOrError.debt.id,
		);
		/* c8 ignore start */
		if (!matchedDebt) {
			return new TRPCError({
				code: "INTERNAL_SERVER_ERROR",
				message: `Expected to have an updated debt id "${updateOrError.debt.id}".`,
			});
		}
		/* c8 ignore stop */
		return {
			updatedAt: matchedDebt.updatedAt,
			reverseUpdated: localPeerIds.includes(updateOrError.debt.peerId)
				? undefined
				: reverseUpdatedDebtsIds.includes(updateOrError.debt.id),
		};
	});
});
 
export const procedure = authProcedure
	.meta({
		title: "Update debt",
		description:
			"Updates a debt owned by the current  user, auto-updating the counterparty's mirrored debt unless they require manual acceptance.",
	})
	.input(updateDebtSchema)
	.mutation(queueUpdateDebt);