cal.pub0.org/pages/api/availability/_get.ts

71 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-06-14 21:17:09 +00:00
import type { NextApiRequest } from "next";
import { z } from "zod";
import { getUserAvailability } from "@calcom/core/getUserAvailability";
2022-07-05 18:58:26 +00:00
import { HttpError } from "@calcom/lib/http-error";
2022-06-14 21:17:09 +00:00
import { defaultResponder } from "@calcom/lib/server";
2022-07-05 18:58:26 +00:00
import { availabilityUserSelect } from "@calcom/prisma";
2022-06-14 21:17:09 +00:00
import { stringOrNumber } from "@calcom/prisma/zod-utils";
const availabilitySchema = z
.object({
2022-06-16 19:50:41 +00:00
userId: stringOrNumber.optional(),
2022-07-05 18:12:14 +00:00
teamId: stringOrNumber.optional(),
2022-06-14 21:17:09 +00:00
username: z.string().optional(),
dateFrom: z.string(),
dateTo: z.string(),
eventTypeId: stringOrNumber.optional(),
})
2022-07-05 18:12:14 +00:00
.refine(
(data) => !!data.username || !!data.userId || !!data.teamId,
"Either username or userId or teamId should be filled in."
);
2022-06-14 21:17:09 +00:00
async function handler(req: NextApiRequest) {
2022-07-05 18:12:14 +00:00
const { prisma, isAdmin } = req;
const { username, userId, eventTypeId, dateTo, dateFrom, teamId } = availabilitySchema.parse(req.query);
if (!teamId)
return getUserAvailability({
username,
dateFrom,
dateTo,
eventTypeId,
userId,
});
2022-07-05 18:58:26 +00:00
const team = await prisma.team.findUnique({
where: { id: teamId },
select: { members: true },
});
2022-07-05 18:12:14 +00:00
if (!team) throw new HttpError({ statusCode: 404, message: "teamId not found" });
if (!team.members) throw new HttpError({ statusCode: 404, message: "team has no members" });
2022-07-05 18:58:26 +00:00
const allMemberIds = team.members.map((membership) => membership.userId);
const members = await prisma.user.findMany({
where: { id: { in: allMemberIds } },
select: availabilityUserSelect,
});
2022-10-14 23:41:28 +00:00
if (!isAdmin) throw new HttpError({ statusCode: 403, message: "Forbidden" });
2022-07-05 21:05:29 +00:00
const availabilities = members.map(async (user) => {
return {
userId: user.id,
availability: await getUserAvailability(
2022-07-05 18:58:26 +00:00
{
2022-07-05 21:05:29 +00:00
userId: user.id,
2022-07-05 18:58:26 +00:00
dateFrom,
dateTo,
eventTypeId,
},
{ user }
2022-07-05 21:05:29 +00:00
),
};
});
const settled = await Promise.all(availabilities);
if (!settled)
throw new HttpError({
statusCode: 401,
message: "We had an issue retrieving all your members availabilities",
});
2022-07-12 18:01:51 +00:00
return settled;
2022-06-14 21:17:09 +00:00
}
export default defaultResponder(handler);