Files
cal.diy/packages/lib/server/queries/teams/index.ts
T
12466fb064 feat: New Organization Schema along with the ability to invite existing users to an organization (#13002)
* Add profile table

Copy to profile table

Update schema

Migrations

* wip

* Get switcher working

* Add organization seeder

* wip

* Remove dead code

* Fix unit tests

* relevantProfile -> profile

* cache bust

* One more comment

* Squash migrations

* Copy to profile table

* Update schema

* Fix existing user invite flow

* Add profile table

* Copy to profile table

* Update schema

* Format

* Add profile table

Copy to profile table

Update schema

Migrations

* Format

* wip

Get switcher working

Add organization seeder

wip

Remove dead code

Fix unit tests

relevantProfile -> profile

cache bust

One more comment

Squash migrations

Copy to profile table

Update schema

Fix existing user invite flow

Add profile table

Copy to profile table

Update schema

chore: small improvements to signup (#13227)

* removed features on mobile, better background color

* nit

* dark mode nits

New Crowdin translations by Github Action

fix: event reschedule workflow trigger (#13122)

* fix event reschedule workflow trigger

* uncomment previously failed test

* review fix

---------

Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: CarinaWolli <[email protected]>

chore: added community support to help (#13213)

refactor: Abstract `handleSeats` from `handleNewBooking` (#12062)

* Refactor createBooking

* Type fix

* Abstract handleSeats

* Create Invitee type

* Create OrganizerUser type

* Abstract addVideoCallDataToEvt

* Abstract createLoggerWithEventDetails

* Abstract `handleAppStatus` from handler

* Create ReqAppsStatus type

* Move `deleteMeeting` and `getCalendar`

* Set parameters for `handleSeats`

* Typescript refactor

* Change function params from req

* Type fix

---------

Co-authored-by: Morgan <[email protected]>
Co-authored-by: Erik <[email protected]>

fix: Dynamic group booking  org-migration redirect (#13223)

* fix: Dynamic group booking redirect

* Fix flaky private team test

test: Check availability tab and all your functions (teste2e-availability) (#12434)

* add changes

* add changes

* add changes

* add changes

* Requested changes

* Change way to grab element

---------

Co-authored-by: gitstart-calcom <[email protected]>
Co-authored-by: gitstart-calcom <[email protected]>
Co-authored-by: Morgan <[email protected]>
Co-authored-by: Keith Williams <[email protected]>
Co-authored-by: Joe Au-Yeung <[email protected]>

fix: Reschedule a cancelled booking (#13170)

* fix: Reschedule a cancelled booking

* canceled instead of cancelled

---------

Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: Carina Wollendorfer <[email protected]>

v3.7.0

test: In Team Event type when location is Organizer Default App and U… (#12939)

* test: In Team Event type when location is Organizer Default App and User Metadata is emoty

* chore: use variable

* fix: type error

test: add test for invalid cal video (#13103)

* test: add test for invalid cal video

* chore: add confirm

* chore: fix type error

* chore: update code

* test: add unit test

* chore: type error

* chore

* chore: type

* chore: fix test

* chore

---------

Co-authored-by: Carina Wollendorfer <[email protected]>

chore: add error message for no availability (#13230)

* chore: add error message for no default user availability

* chore: check only availability

* chore: change message

* chore: add eventType

fix: Team revert with members (#13228)

refactor: Refactor seats logic (#12905)

* Refactor createBooking

* Type fix

* Abstract handleSeats

* Create Invitee type

* Create OrganizerUser type

* Abstract addVideoCallDataToEvt

* Abstract createLoggerWithEventDetails

* Abstract `handleAppStatus` from handler

* Create ReqAppsStatus type

* Move `deleteMeeting` and `getCalendar`

* Set parameters for `handleSeats`

* Typescript refactor

* Change function params from req

* Type fix

* Move handleSeats

* Abstract lastAttendeeDeleteBooking

* Create function for rescheduling seated events

* Fix imports on reschedule seats function

* Fix imports

* Import handleSeats function

* Fix rescheduleUid type

* Refactor owner reschedule to new time slot

* Refactor combine two booking times together

* Reschedule as an attendee

* Refactor createNewSeat

* Remove old handleSeats

* Remove lastAttendeeDeleteBooking from handleNewBooking

* Test for new attendee right params are passed

* Unit test params for reschedule

* Typo fix

* Clean up

* Create new seat test

* Test when attendee already signs up for booking

* Type fix

* Test reschedule move attendee to existing booking

* On reschedule create new booking

* Test on last attendee cancel booking

* Owner reschedule to new time slot

* Owner rescheduling, merge two bookings together

* Test: when merging more than available seats, then fail

* Test: fail when event is full

* Remove duplicate E2E tests

* Clean up

* Rename `addVideoCallDataToEvt` to `addVideoCallDataToEvent`

* Refactor `calcAppsStatus`

* Assign `evt` to resutl of `addVideoCallDataToEvent`

* Use prisma.transaction when moving attendees

* Clean create seat call

* Use ErrorCode enum

* Use attendeeRescheduledSeatedBooking function

* Await function

* Prevent double triggering of workflows

* Use inviteeToAdd in createNewSeat

* Remove unused error code

* Remove old handleSeats file

* Type fix

* Type fix

* Type fix

* Type fix

* Type fix

* Type fix

* Type fix

* Type fix

---------

Co-authored-by: Morgan <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Erik <[email protected]>

feat: Allow admins to filter bookings only by attendee emails (#13236)

* chore: Allow admins to filter bookings only by attendee emails

* Fix type error

Fixed [CAL-2930] Org branding isnt centered in shell #13225 (#13237)

Add profile table

Copy to profile table

Update schema

Migrations

Format

* wip

* Add profile relation everywhere

* Fix schema

* Fix invite handler

* Add profileId during eventTypec reation

* Get dashboard working with profile relatioon

* Add workflow create repository

* Add profileId to host

* Add profileId to credential table

* Add destinationCalendar repository

* Add profileId to membership

* Revert all profile related changes

* Add acme and dunder

* Fix membership profileId usgae

* Various fixes

* Some renaming

* Fix failing tests

* Debugging next-aut

* Consolidate migrations

* Testing fixes

* Fix unit tests

* Self review feedback

* PR feedback

* Fix orgMigration as well

* Add profile schema and copy users to it

* Remove migrations from here

* Fix type issues

* Fix type error after main merge

* Remove movedFromUserId

* Add missing migration file

* Self review addressed

* Joe's review addressed

* Fix profile switcher

---------

Co-authored-by: Joe Au-Yeung <[email protected]>
2024-02-02 21:34:13 +00:00

346 lines
9.7 KiB
TypeScript

import { Prisma } from "@prisma/client";
import { getAppFromSlug } from "@calcom/app-store/utils";
import prisma, { baseEventTypeSelect } from "@calcom/prisma";
import type { Team } from "@calcom/prisma/client";
import { SchedulingType } from "@calcom/prisma/enums";
import { _EventTypeModel } from "@calcom/prisma/zod";
import {
EventTypeMetaDataSchema,
allManagedEventTypeProps,
unlockedManagedEventTypeProps,
} from "@calcom/prisma/zod-utils";
import { WEBAPP_URL } from "../../../constants";
import { getBookerBaseUrlSync } from "../../../getBookerUrl/client";
import { getTeam, getOrg } from "../../repository/team";
import { UserRepository } from "../../repository/user";
export type TeamWithMembers = Awaited<ReturnType<typeof getTeamWithMembers>>;
export async function getTeamWithMembers(args: {
id?: number;
slug?: string;
userId?: number;
orgSlug?: string | null;
includeTeamLogo?: boolean;
isTeamView?: boolean;
currentOrg?: Team | null;
/**
* If true, means that you are fetching an organization and not a team
*/
isOrgView?: boolean;
}) {
const { id, slug, currentOrg, userId, orgSlug, isTeamView, isOrgView, includeTeamLogo } = args;
// This should improve performance saving already app data found.
const appDataMap = new Map();
const userSelect = Prisma.validator<Prisma.UserSelect>()({
username: true,
email: true,
name: true,
avatarUrl: true,
id: true,
bio: true,
teams: {
select: {
team: {
select: {
slug: true,
id: true,
},
},
},
},
credentials: {
select: {
app: {
select: {
slug: true,
categories: true,
},
},
destinationCalendars: {
select: {
externalId: true,
},
},
},
},
});
let lookupBy;
if (id) {
lookupBy = { id, havingMemberWithId: userId };
} else if (slug) {
lookupBy = { slug, havingMemberWithId: userId };
} else {
throw new Error("Must provide either id or slug");
}
const arg = {
lookupBy,
forOrgWithSlug: orgSlug ?? null,
isOrg: !!isOrgView,
teamSelect: {
id: true,
name: true,
slug: true,
...(!!includeTeamLogo ? { logo: true } : {}),
bio: true,
hideBranding: true,
hideBookATeamMember: true,
isPrivate: true,
metadata: true,
parent: {
select: {
id: true,
slug: true,
name: true,
},
},
children: {
select: {
name: true,
slug: true,
},
},
members: {
select: {
accepted: true,
role: true,
disableImpersonation: true,
user: {
select: userSelect,
},
},
},
theme: true,
brandColor: true,
darkBrandColor: true,
eventTypes: {
where: {
hidden: false,
schedulingType: {
not: SchedulingType.MANAGED,
},
},
select: {
users: {
select: userSelect,
},
metadata: true,
...baseEventTypeSelect,
},
},
inviteTokens: {
select: {
token: true,
expires: true,
expiresInDays: true,
identifier: true,
},
},
},
} as const;
const teamOrOrg = isOrgView ? await getOrg(arg) : await getTeam(arg);
if (!teamOrOrg) return null;
const teamOrOrgMemberships = [];
for (const membership of teamOrOrg.members) {
teamOrOrgMemberships.push({
...membership,
user: await UserRepository.enrichUserWithItsProfile({
user: membership.user,
}),
});
}
const members = teamOrOrgMemberships.map((m) => {
const { credentials, profile, ...restUser } = m.user;
return {
...restUser,
username: profile?.username ?? restUser.username,
role: m.role,
profile: profile,
organizationId: profile?.organizationId ?? null,
organization: profile?.organization,
accepted: m.accepted,
disableImpersonation: m.disableImpersonation,
subteams: orgSlug
? m.user.teams
.filter((membership) => membership.team.id !== teamOrOrg.id)
.map((membership) => membership.team.slug)
: null,
avatar: `${WEBAPP_URL}/${m.user.username}/avatar.png`,
bookerUrl: getBookerBaseUrlSync(profile?.organization?.slug || ""),
connectedApps: !isTeamView
? credentials?.map((cred) => {
const appSlug = cred.app?.slug;
let appData = appDataMap.get(appSlug);
if (!appData) {
appData = getAppFromSlug(appSlug);
appDataMap.set(appSlug, appData);
}
const isCalendar = cred?.app?.categories?.includes("calendar") ?? false;
const externalId = isCalendar ? cred.destinationCalendars?.[0]?.externalId : null;
return {
name: appData?.name ?? null,
logo: appData?.logo ?? null,
app: cred.app,
externalId: externalId ?? null,
};
})
: null,
};
});
const eventTypesWithUsersUserProfile = [];
for (const eventType of teamOrOrg.eventTypes) {
const usersWithUserProfile = [];
for (const user of eventType.users) {
usersWithUserProfile.push(
await UserRepository.enrichUserWithItsProfile({
user,
})
);
}
eventTypesWithUsersUserProfile.push({
...eventType,
users: usersWithUserProfile,
});
}
const eventTypes = eventTypesWithUsersUserProfile.map((eventType) => ({
...eventType,
metadata: EventTypeMetaDataSchema.parse(eventType.metadata),
}));
// Don't leak invite tokens to the frontend
const { inviteTokens, ...teamWithoutInviteTokens } = teamOrOrg;
// Don't leak stripe payment ids
const teamMetadata = teamOrOrg.metadata;
const {
paymentId: _,
subscriptionId: __,
subscriptionItemId: ___,
...restTeamMetadata
} = teamMetadata || {};
return {
...teamWithoutInviteTokens,
/** To prevent breaking we only return non-email attached token here, if we have one */
inviteToken: inviteTokens.find(
(token) =>
token.identifier === `invite-link-for-teamId-${teamOrOrg.id}` &&
token.expires > new Date(new Date().setHours(24))
),
metadata: restTeamMetadata,
eventTypes: !isOrgView ? eventTypes : null,
members,
};
}
// also returns team
export async function isTeamAdmin(userId: number, teamId: number) {
const team = await prisma.membership.findFirst({
where: {
userId,
teamId,
accepted: true,
OR: [{ role: "ADMIN" }, { role: "OWNER" }],
},
include: { team: true },
});
if (!team) return false;
return team;
}
export async function isTeamOwner(userId: number, teamId: number) {
return !!(await prisma.membership.findFirst({
where: {
userId,
teamId,
accepted: true,
role: "OWNER",
},
}));
}
export async function isTeamMember(userId: number, teamId: number) {
return !!(await prisma.membership.findFirst({
where: {
userId,
teamId,
accepted: true,
},
}));
}
export async function updateNewTeamMemberEventTypes(userId: number, teamId: number) {
const eventTypesToAdd = await prisma.eventType.findMany({
where: {
team: { id: teamId },
assignAllTeamMembers: true,
},
select: {
...allManagedEventTypeProps,
id: true,
schedulingType: true,
},
});
const allManagedEventTypePropsZod = _EventTypeModel.pick(allManagedEventTypeProps);
eventTypesToAdd.length > 0 &&
(await prisma.$transaction(
eventTypesToAdd.map((eventType) => {
if (eventType.schedulingType === "MANAGED") {
const managedEventTypeValues = allManagedEventTypePropsZod
.omit(unlockedManagedEventTypeProps)
.parse(eventType);
// Define the values for unlocked properties to use on creation, not updation
const unlockedEventTypeValues = allManagedEventTypePropsZod
.pick(unlockedManagedEventTypeProps)
.parse(eventType);
// Calculate if there are new workflows for which assigned members will get too
const currentWorkflowIds = eventType.workflows?.map((wf) => wf.workflowId);
return prisma.eventType.create({
data: {
...managedEventTypeValues,
...unlockedEventTypeValues,
bookingLimits:
(managedEventTypeValues.bookingLimits as unknown as Prisma.InputJsonObject) ?? undefined,
recurringEvent:
(managedEventTypeValues.recurringEvent as unknown as Prisma.InputJsonValue) ?? undefined,
metadata: (managedEventTypeValues.metadata as Prisma.InputJsonValue) ?? undefined,
bookingFields: (managedEventTypeValues.bookingFields as Prisma.InputJsonValue) ?? undefined,
durationLimits: (managedEventTypeValues.durationLimits as Prisma.InputJsonValue) ?? undefined,
onlyShowFirstAvailableSlot: managedEventTypeValues.onlyShowFirstAvailableSlot ?? false,
userId,
users: {
connect: [{ id: userId }],
},
parentId: eventType.parentId,
hidden: false,
workflows: currentWorkflowIds && {
create: currentWorkflowIds.map((wfId) => ({ workflowId: wfId })),
},
},
});
} else {
return prisma.eventType.update({
where: { id: eventType.id },
data: { hosts: { create: [{ userId, isFixed: eventType.schedulingType === "COLLECTIVE" }] } },
});
}
})
));
}