Files
calendar/packages/trpc/server/routers/viewer/teams/create.handler.ts
T
devin-ai-integration[bot]GitHubbenny@cal.com <benny@cal.com>benny@cal.com <benny@cal.com>benny@cal.com <benny@cal.com>benny@cal.com <benny@cal.com>Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>benny@cal.com <benny@cal.com>Anik Dhabal Babu
4920abdaf7 feat: optimize Prisma queries by replacing findFirst with findUnique where applicable (#21826)
* feat: optimize Prisma queries by replacing findFirst with findUnique where applicable

- Replace findFirst/findFirstOrThrow with findUnique/findUniqueOrThrow for queries using unique constraints
- Maintain existing functionality and error handling behavior
- Focus on queries using primary keys and unique index fields from schema
- Revert problematic changes that caused test failures to maintain stability

Co-Authored-By: benny@cal.com <benny@cal.com>

* revert: exclude API files from Prisma query optimizations per user request

- Reverted all 55 API-related files to their original state
- Kept all non-API Prisma query optimizations intact
- API files include apps/api/v1, apps/api/v2, apps/web/app/api, and packages/app-store/*/api
- Non-API optimizations remain for packages/lib, packages/features, apps/web (non-api), etc.

Co-Authored-By: benny@cal.com <benny@cal.com>

* feat: optimize membership query in attributeUtils to use findUnique with userId_teamId constraint

Co-Authored-By: benny@cal.com <benny@cal.com>

* revert: exclude test files from Prisma query optimizations per user request

Co-Authored-By: benny@cal.com <benny@cal.com>

* revert: revert attributeUtils.ts to use findFirst for test compatibility

Co-Authored-By: benny@cal.com <benny@cal.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: benny@cal.com <benny@cal.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2025-06-17 09:52:02 +03:00

145 lines
3.9 KiB
TypeScript

import { generateTeamCheckoutSession } from "@calcom/features/ee/teams/lib/payments";
import { IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";
import { uploadLogo } from "@calcom/lib/server/avatar";
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
import { resizeBase64Image } from "@calcom/lib/server/resizeBase64Image";
import { prisma } from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
import { TRPCError } from "@trpc/server";
import type { TrpcSessionUser } from "../../../types";
import type { TCreateInputSchema } from "./create.schema";
type CreateOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: TCreateInputSchema;
};
const generateCheckoutSession = async ({
teamSlug,
teamName,
userId,
}: {
teamSlug: string;
teamName: string;
userId: number;
}) => {
if (!IS_TEAM_BILLING_ENABLED) {
console.info("Team billing is disabled, not generating a checkout session.");
return;
}
const checkoutSession = await generateTeamCheckoutSession({
teamSlug,
teamName,
userId,
});
if (!checkoutSession.url)
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Failed retrieving a checkout session URL.",
});
return { url: checkoutSession.url, message: "Payment required to publish team" };
};
export const createHandler = async ({ ctx, input }: CreateOptions) => {
const { user } = ctx;
const { slug, name } = input;
const isOrgChildTeam = !!user.profile?.organizationId;
// For orgs we want to create teams under the org
if (user.profile?.organizationId && !user.organization.isOrgAdmin) {
throw new TRPCError({ code: "FORBIDDEN", message: "org_admins_can_create_new_teams" });
}
const slugCollisions = await prisma.team.findFirst({
where: {
slug: slug,
parentId: isOrgChildTeam ? user.profile?.organizationId : null,
},
});
if (slugCollisions) throw new TRPCError({ code: "BAD_REQUEST", message: "team_url_taken" });
if (user.profile?.organizationId) {
const nameCollisions = await isSlugTakenBySomeUserInTheOrganization({
organizationId: user.profile?.organizationId,
slug: slug,
});
if (nameCollisions) throw new TRPCError({ code: "BAD_REQUEST", message: "team_slug_exists_as_user" });
}
// If the user is not a part of an org, then make them pay before creating the team
if (!isOrgChildTeam) {
const checkoutSession = await generateCheckoutSession({
teamSlug: slug,
teamName: name,
userId: user.id,
});
// If there is a checkout session, return it. Otherwise, it means it's disabled.
if (checkoutSession)
return {
url: checkoutSession.url,
message: checkoutSession.message,
team: null,
};
}
const createdTeam = await prisma.team.create({
data: {
slug,
name,
members: {
create: {
userId: ctx.user.id,
role: MembershipRole.OWNER,
accepted: true,
},
},
...(isOrgChildTeam && { parentId: user.profile?.organizationId }),
},
});
// Upload logo, create doesn't allow logo removal
if (input.logo && input.logo.startsWith("data:image/png;base64,")) {
const logoUrl = await uploadLogo({
logo: await resizeBase64Image(input.logo),
teamId: createdTeam.id,
});
await prisma.team.update({
where: {
id: createdTeam.id,
},
data: {
logoUrl,
},
});
}
return {
url: `${WEBAPP_URL}/settings/teams/${createdTeam.id}/onboard-members`,
message: "Team billing is disabled, not generating a checkout session.",
team: createdTeam,
};
};
async function isSlugTakenBySomeUserInTheOrganization({
organizationId,
slug,
}: {
organizationId: number;
slug: string;
}) {
return await ProfileRepository.findByOrgIdAndUsername({
organizationId: organizationId,
username: slug,
});
}
export default createHandler;