Files
cal.diy/packages/trpc/server/routers/viewer/teams/publish.handler.ts
T
583571247c feat: org invite billing (#9291)
* Initial commit

* Adding feature flag

* Desktop first banner, mobile pending

* Removing dead code and img

* AppInstallButtonBase

* WIP

* Adds Email verification template+translations for organizations (#9202)

* feat: Orgs Schema Changing `scopedMembers` to `orgUsers` (#9209)

* Change scopedMembers to orgMembers

* Change to orgUsers

* First step done

* Merge branch 'feat/organizations-onboarding' of github.com:calcom/cal.com into feat/organizations-onboarding

* Session logic to show org label

* Step 2 done, avatar not working

* List orgs and list teams specific if orgs exist

* Conditionally show org - fix settings layout - add labels for all pages

* Profile Page + update

* Org specific team creation

* appearance page

* Ensure members cant of org cant update settings in UI

* Fix update handler imports

* hide billing on sub teams

* Update profile slug page

* Letting duplicate slugs for teams to support orgs

* Add slug coliisions for org

* Covering null on unique clauses

* Covering null on unique clauses

* Extract to utils

* Update settings to use subdomain path in team url , team + org

* Supporting having the orgId in the session cookie

* Onboarding admins step

* Last step to create teams

* Update handler comments

* Upgrade ORG banner - disabled team banner for child teams

* Handle publishing ORGS

* Fix licenese issue

* Update packages/trpc/server/routers/viewer/teams/create.handler.ts

* Split into function calls to make this file more explisit

* Update parents stripe sub not teamID

* Moving change password handler, improving verifying code flow

* Clearing error before submitting

* Reverting email testing api changes

* Reverting having the banner for now

* Consistent exported components

* Remove unneeded files from banner

* Removing uneeded code

* Fixing avatar selector

* Using meta component for head/descr

* Missing i18n strings

* Create org membership also - billing portal page

* A11ly

* Hide create team if no valid permisisons

* Get Org members router

* Handle updating subscription if orgId

* Fix double upgrade banner

* Update constants

* Feedback

* Copy change

* Making an org avatar (temp)

* Add slug colission detection for user and team name

* Fix Import

* Remove update password func

* Fix module import over relative

* feat: organization event type filter (#9253)

Signed-off-by: Udit Takkar <[email protected]>

* Missing changes to support orgs schema changes

* Fix import again

* Throw no team found before auth error

* Check if invited found user is already in differnt org

* Move to for of loop to throw errors in usenamelist

* Remove app install button sa its in 9337

* Remove i18n key not being used

* feat: Onboarding process to create an organization (#9184)

* Desktop first banner, mobile pending

* Removing dead code and img

* WIP

* Adds Email verification template+translations for organizations (#9202)

* First step done

* Merge branch 'feat/organizations-onboarding' of github.com:calcom/cal.com into feat/organizations-onboarding

* Step 2 done, avatar not working

* Covering null on unique clauses

* Onboarding admins step

* Last step to create teams

* Moving change password handler, improving verifying code flow

* Clearing error before submitting

* Reverting email testing api changes

* Reverting having the banner for now

* Consistent exported components

* Remove unneeded files from banner

* Removing uneeded code

* Fixing avatar selector

* Using meta component for head/descr

* Missing i18n strings

* Feedback

* Making an org avatar (temp)

* Check for subteams slug clashes with usernames

* Fixing create teams onsuccess

* feedback

* Making sure we check requestedSlug now

---------

Co-authored-by: sean-brydon <[email protected]>

* feat: [CAL-1816] Organization subdomain support (#9345)

* Desktop first banner, mobile pending

* Removing dead code and img

* WIP

* Adds Email verification template+translations for organizations (#9202)

* First step done

* Merge branch 'feat/organizations-onboarding' of github.com:calcom/cal.com into feat/organizations-onboarding

* Step 2 done, avatar not working

* Covering null on unique clauses

* Onboarding admins step

* Last step to create teams

* Moving change password handler, improving verifying code flow

* Clearing error before submitting

* Reverting email testing api changes

* Reverting having the banner for now

* Consistent exported components

* Remove unneeded files from banner

* Removing uneeded code

* Fixing avatar selector

* Using meta component for head/descr

* Missing i18n strings

* Feedback

* Making an org avatar (temp)

* Check for subteams slug clashes with usernames

* Fixing create teams onsuccess

* Covering users and subteams, excluding non-org users

* Unpublished teams shows correctly

* Create subdomain in Vercel

* feedback

* Renaming Vercel env vars

* Vercel domain check before creation

* Supporting cal-staging.com

* Change to have vercel detect it

* vercel domain check data message error

* Remove check domain

* Making sure we check requestedSlug now

* Feedback and unneeded code

* Reverting unneeded changes

* Unneeded changes

---------

Co-authored-by: sean-brydon <[email protected]>

* Vercel subdomain creation in PROD only

* Fix router

* feat: organization settings general and members page (#9266)

* feat: organization settings general page

Signed-off-by: Udit Takkar <[email protected]>

* feat: add members page

Signed-off-by: Udit Takkar <[email protected]>

* chore: remove

Signed-off-by: Udit Takkar <[email protected]>

* fix: use invalidate

Signed-off-by: Udit Takkar <[email protected]>

* fix: delete mutation

Signed-off-by: Udit Takkar <[email protected]>

* fix: remove organization id

Signed-off-by: Udit Takkar <[email protected]>

* chore

Signed-off-by: Udit Takkar <[email protected]>

* fix: use zod schema

Signed-off-by: Udit Takkar <[email protected]>

---------

Signed-off-by: Udit Takkar <[email protected]>

* Type fixes

* Use org Stripe product when upgrading

* Removed unused code

* Reverting changes

* Update UsernameTextfield.tsx

* More reverts

* Update next-auth-options.ts

* Update common.json

* Type fixes

* Include invite token for orgs

* Update org schema

* Make token settings optional as it isnt used in orgs yet

* Reverts

* remove yarn.lock from commit

* Fix types

* feat: orgs unverified (#9415)

Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Keith Williams <[email protected]>

* Fix wrong banner being displayed

* Type fix

* Fix type issues

* Update packages/trpc/server/routers/viewer/teams/inviteMember.handler.ts

Co-authored-by: alannnc <[email protected]>

* fix missing input on trpc query

* Fix for parentId value for createProvisionalMembership

---------

Signed-off-by: Udit Takkar <[email protected]>
Co-authored-by: Leo Giovanetti <[email protected]>
Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: zomars <[email protected]>
Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Keith Williams <[email protected]>
Co-authored-by: alannnc <[email protected]>
2023-07-02 11:40:12 -07:00

160 lines
4.9 KiB
TypeScript

import type { Prisma } from "@prisma/client";
import { getRequestedSlugError } from "@calcom/app-store/stripepayment/lib/team-billing";
import {
purchaseTeamSubscription,
updateQuantitySubscriptionFromStripe,
} from "@calcom/features/ee/teams/lib/payments";
import { IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";
import { isOrganisationAdmin } from "@calcom/lib/server/queries/organisations";
import { isTeamAdmin } from "@calcom/lib/server/queries/teams";
import { closeComUpdateTeam } from "@calcom/lib/sync/SyncServiceManager";
import { prisma } from "@calcom/prisma";
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
import { TRPCError } from "@trpc/server";
import type { TrpcSessionUser } from "../../../trpc";
import type { TPublishInputSchema } from "./publish.schema";
type PublishOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: TPublishInputSchema;
};
const parseMetadataOrThrow = (metadata: Prisma.JsonValue) => {
const parsedMetadata = teamMetadataSchema.safeParse(metadata);
if (!parsedMetadata.success || !parsedMetadata.data)
throw new TRPCError({ code: "BAD_REQUEST", message: "Invalid team metadata" });
return parsedMetadata.data;
};
const generateCheckoutSession = async ({
teamId,
seats,
userId,
}: {
teamId: number;
seats: number;
userId: number;
}) => {
if (!IS_TEAM_BILLING_ENABLED) return;
const checkoutSession = await purchaseTeamSubscription({
teamId,
seats,
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" };
};
const publishOrganizationTeamHandler = async ({ ctx, input }: PublishOptions) => {
if (!ctx.user.organizationId) throw new TRPCError({ code: "UNAUTHORIZED" });
if (!isOrganisationAdmin(ctx.user.id, ctx.user?.organizationId))
throw new TRPCError({ code: "UNAUTHORIZED" });
const createdTeam = await prisma.team.findFirst({
where: { id: input.teamId, parentId: ctx.user.organizationId },
include: {
parent: {
include: {
members: true,
},
},
},
});
if (!createdTeam || !createdTeam.parentId)
throw new TRPCError({ code: "NOT_FOUND", message: "Team not found." });
const metadata = parseMetadataOrThrow(createdTeam.metadata);
// We update the quantity of the parent ID (organization) subscription
if (IS_TEAM_BILLING_ENABLED) {
await updateQuantitySubscriptionFromStripe(createdTeam.parentId);
}
if (!metadata?.requestedSlug) {
throw new TRPCError({ code: "BAD_REQUEST", message: "Can't publish team without `requestedSlug`" });
}
const { requestedSlug, ...newMetadata } = metadata;
let updatedTeam: Awaited<ReturnType<typeof prisma.team.update>>;
try {
updatedTeam = await prisma.team.update({
where: { id: createdTeam.id },
data: {
slug: requestedSlug,
metadata: { ...newMetadata },
},
});
} catch (error) {
const { message } = getRequestedSlugError(error, requestedSlug);
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message });
}
return {
url: `${WEBAPP_URL}/settings/teams/${updatedTeam.id}/profile`,
message: "Team published successfully",
};
};
export const publishHandler = async ({ ctx, input }: PublishOptions) => {
if (ctx.user.organizationId) return publishOrganizationTeamHandler({ ctx, input });
if (!(await isTeamAdmin(ctx.user.id, input.teamId))) throw new TRPCError({ code: "UNAUTHORIZED" });
const { teamId: id } = input;
const prevTeam = await prisma.team.findFirst({ where: { id }, include: { members: true } });
if (!prevTeam) throw new TRPCError({ code: "NOT_FOUND", message: "Team not found." });
const metadata = parseMetadataOrThrow(prevTeam.metadata);
// if payment needed, respond with checkout url
const checkoutSession = await generateCheckoutSession({
teamId: prevTeam.id,
seats: prevTeam.members.length,
userId: ctx.user.id,
});
if (checkoutSession) return checkoutSession;
if (!metadata?.requestedSlug) {
throw new TRPCError({ code: "BAD_REQUEST", message: "Can't publish team without `requestedSlug`" });
}
const { requestedSlug, ...newMetadata } = metadata;
let updatedTeam: Awaited<ReturnType<typeof prisma.team.update>>;
try {
updatedTeam = await prisma.team.update({
where: { id },
data: {
slug: requestedSlug,
metadata: { ...newMetadata },
},
});
} catch (error) {
const { message } = getRequestedSlugError(error, requestedSlug);
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message });
}
// Sync Services: Close.com
closeComUpdateTeam(prevTeam, updatedTeam);
return {
url: `${WEBAPP_URL}/settings/teams/${updatedTeam.id}/profile`,
message: "Team published successfully",
};
};