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 | 7x 7x 25x 15x 25x 15x 15x 7x 15x 25x 24x 25x 1x 24x 1x 37x 23x 23x 7x 16x 16x 16x 1x 15x 7x 14x 6x 8x 7x 16x 16x 27x 16x 1x 1x 15x 15x 15x 24x 14x 24x 9x 15x 23x 15x 7x | import { TRPCError } from "@trpc/server";
import { z } from "zod";
import type { BatchLoadContextFn } from "~web/handlers/batch";
import { queueCallFactory } from "~web/handlers/batch";
import type { AuthorizedContext } from "~web/handlers/context";
import { authProcedure } from "~web/handlers/trpc";
import {
assignableRoleSchema,
peerIdSchema,
receiptIdSchema,
} from "~web/handlers/validation";
import { getDuplicates } from "~web/utils/batch";
export const addParticipantSchema = z.strictObject({
receiptId: receiptIdSchema,
peerId: peerIdSchema,
role: assignableRoleSchema,
});
export type ParticipantOutput = {
createdAt: Temporal.ZonedDateTime;
};
const getData = async (
ctx: AuthorizedContext,
inputs: readonly z.infer<typeof addParticipantSchema>[],
) => {
const receiptIds = inputs.map((input) => input.receiptId);
const [receipts, peers] = await Promise.all([
ctx.database
.selectFrom("receipts")
.where("id", "in", receiptIds)
.select(["receipts.id", "receipts.ownerUserId"])
.execute(),
ctx.database
.selectFrom("peers")
.where(
"id",
"in",
inputs.map((input) => input.peerId),
)
.leftJoin("receiptParticipants", (qb) =>
qb
.onRef("receiptParticipants.peerId", "=", "peers.id")
.on("receiptParticipants.receiptId", "in", receiptIds),
)
.select([
"peers.id",
"peers.ownerUserId",
"receiptParticipants.receiptId",
])
.execute(),
]);
return { receipts, peers };
};
const getParticipants = (
ctx: AuthorizedContext,
inputs: readonly z.infer<typeof addParticipantSchema>[],
{ receipts, peers }: Awaited<ReturnType<typeof getData>>,
) =>
inputs.map((input) => {
const matchedReceipt = receipts.find(
(receipt) => receipt.id === input.receiptId,
);
if (!matchedReceipt) {
return new TRPCError({
code: "NOT_FOUND",
message: `Receipt "${input.receiptId}" does not exist.`,
});
}
if (matchedReceipt.ownerUserId !== ctx.auth.userId) {
throw new TRPCError({
code: "FORBIDDEN",
message: `Not enough rights to add participant "${input.peerId}" to receipt "${input.receiptId}".`,
});
}
const matchedPeers = peers.filter((peer) => peer.id === input.peerId);
const [firstMatchedPeer] = matchedPeers;
if (!firstMatchedPeer || firstMatchedPeer.ownerUserId !== ctx.auth.userId) {
return new TRPCError({
code: "NOT_FOUND",
message: `Peer "${input.peerId}" does not exist or is not owned by you.`,
});
}
const matchedPeerReceipt = matchedPeers.find(
(peer) => peer.receiptId === input.receiptId,
);
if (matchedPeerReceipt) {
return new TRPCError({
code: "CONFLICT",
message: `Peer "${input.peerId}" already participates in receipt "${input.receiptId}".`,
});
}
return {
receiptId: input.receiptId,
peerId: input.peerId,
role:
matchedReceipt.ownerUserId === input.peerId
? ("owner" as const)
: input.role,
};
});
const insertParticipants = async (
ctx: AuthorizedContext,
participants: Exclude<
ReturnType<typeof getParticipants>[number],
TRPCError
>[],
) => {
if (participants.length === 0) {
return [];
}
return ctx.database
.insertInto("receiptParticipants")
.values(participants)
.returning([
"receiptParticipants.createdAt",
"receiptParticipants.peerId",
"receiptParticipants.receiptId",
])
.execute();
};
export const batchFn: BatchLoadContextFn<
AuthorizedContext,
z.infer<typeof addParticipantSchema>,
ParticipantOutput,
TRPCError
> = (ctx) => async (inputs) => {
const duplicatedTuples = getDuplicates(
inputs,
({ receiptId, peerId }) => [receiptId, peerId] as const,
);
if (duplicatedTuples.length !== 0) {
throw new TRPCError({
code: "CONFLICT",
message: `Expected to have unique pair of peer id and receipt id, got repeating pairs: ${duplicatedTuples
.map(
([[itemId, peerId], count]) =>
`receipt "${itemId}" / peer "${peerId}" (${count} times)`,
)
.join(", ")}.`,
});
}
const data = await getData(ctx, inputs);
const participantsOrErrors = getParticipants(ctx, inputs, data);
const results = await insertParticipants(
ctx,
participantsOrErrors.filter(
(
participantOrError,
): participantOrError is Exclude<typeof participantOrError, TRPCError> =>
!(participantOrError instanceof TRPCError),
),
);
return participantsOrErrors.map((participantOrError) => {
if (participantOrError instanceof TRPCError) {
return participantOrError;
}
const matchedResult = results.find(
(result) =>
result.receiptId === participantOrError.receiptId &&
result.peerId === participantOrError.peerId,
);
/* c8 ignore start */
if (!matchedResult) {
return new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: `Expected to have inserted peer "${participantOrError.peerId}" in receipt "${participantOrError.receiptId}".`,
});
}
/* c8 ignore stop */
return {
createdAt: matchedResult.createdAt,
};
});
};
export const procedure = authProcedure
.meta({
title: "Add receipt participant",
description:
"Adds a given peerId as a participant of a given receipt with an assigned role.",
})
.input(addParticipantSchema)
.mutation(queueCallFactory(batchFn));
|