-
Notifications
You must be signed in to change notification settings - Fork 12.6k
Expand file tree
/
Copy pathcreate.handler.ts
More file actions
170 lines (150 loc) · 4.74 KB
/
create.handler.ts
File metadata and controls
170 lines (150 loc) · 4.74 KB
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
import type { NextApiRequest } from "next";
import { generateTeamCheckoutSession } from "@calcom/features/ee/teams/lib/payments";
import { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository";
import { IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";
import { uploadLogo } from "@calcom/lib/server/avatar";
import { resizeBase64Image } from "@calcom/lib/server/resizeBase64Image";
import { getTrackingFromCookies } from "@calcom/lib/tracking";
import type { TrackingData } from "@calcom/lib/tracking";
import { prisma } from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
import type { BillingPeriod as BillingPeriodEnum } from "@calcom/prisma/zod-utils";
import { TRPCError } from "@trpc/server";
import type { TrpcSessionUser } from "../../../types";
import type { TCreateInputSchema } from "./create.schema";
type CreateOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
req?: NextApiRequest;
};
input: TCreateInputSchema;
};
const generateCheckoutSession = async ({
teamSlug,
teamName,
userId,
isOnboarding,
billingPeriod,
tracking,
}: {
teamSlug: string;
teamName: string;
userId: number;
isOnboarding?: boolean;
billingPeriod?: "MONTHLY" | "ANNUALLY";
tracking?: TrackingData;
}) => {
if (!IS_TEAM_BILLING_ENABLED) {
console.info("Team billing is disabled, not generating a checkout session.");
return;
}
const checkoutSession = await generateTeamCheckoutSession({
teamSlug,
teamName,
userId,
isOnboarding,
billingPeriod: billingPeriod as BillingPeriodEnum | undefined,
tracking,
});
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, bio, isOnboarding, billingPeriod } = 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 tracking = getTrackingFromCookies(ctx.req?.cookies);
const checkoutSession = await generateCheckoutSession({
teamSlug: slug,
teamName: name,
userId: user.id,
isOnboarding,
billingPeriod,
tracking,
});
// 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,
bio: bio || null,
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,") ||
input.logo.startsWith("data:image/jpeg;base64,") ||
input.logo.startsWith("data:image/jpg;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;