feat: Custom host location (#25916)

* chore: save progress

* chore:

* feat: add input dialog

* fix: type error

* feat: mass apply dialog

* test: per host location

* test: fix test

* fix: address Cubic AI review feedback (confidence >= 9/10)

- Remove PII (address, phone number) from tracing logs in RegularBookingService.ts
- Constrain HostLocation.type to EventLocationType["type"] for compile-time validation

Co-Authored-By: unknown <>

* fix: translation

* refactor: improvements

* fix: correct grammar in custom host locations tooltip

Change 'custom host locations is enabled' to 'custom host locations are enabled' (plural subject requires plural verb).

Addresses Cubic AI review feedback (confidence 9/10).

Co-Authored-By: unknown <>

* refactor: improvements

* fix: auth

* fix: check

* refactor: improvements

* fix: address Cubic AI review feedback (confidence >= 9/10)

- Add scheduleId to newly created hosts in update.handler.ts to persist
  host-specific schedules during create operations
- Change host location deletion filter from !host.location to
  host.location === null to only delete when explicitly set to null
- Fix static-link per-host locations to use actual link instead of type
  in locationBodyString for bookingLocationService.ts

Co-Authored-By: unknown <>

* fix: preserve existing host scheduleId when not explicitly provided

Change scheduleId handling for existing hosts from 'host.scheduleId ?? null'
to 'host.scheduleId === undefined ? undefined : host.scheduleId' so that
when the client doesn't provide a scheduleId, the existing value is preserved
instead of being cleared to null.

Co-Authored-By: unknown <>

* fix; type erro

* fix; type erro

* fix; type erro

* refactor: move repository

* refactor: move repository

* fix: add singular/plural translations for location_applied_to_hosts

Addresses Cubic AI review feedback (confidence 9/10) to fix '1 hosts' rendering as '1 host' by using i18next plural format with _one and _other suffixes.

Co-Authored-By: unknown <>

* refactor: feedback

* fix: type err

* fix: use uuid in schema and remove attendee locaiton

* fix: type err

* fix: type err

* fix: validate eventTypeId as integer in massApplyHostLocation schema

Co-Authored-By: unknown <>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-01-23 11:18:43 -03:00
1 parent b9b7e50f5a
commit 0ad4367005
33 files changed
+2625 -68

No files matched your search

@@ -10,6 +10,8 @@ import { ZGetActiveOnOptionsSchema } from "./getActiveOnOptions.schema";
import { ZEventTypeInputSchema, ZGetEventTypesFromGroupSchema } from "./getByViewer.schema";
import { ZGetHashedLinkInputSchema } from "./getHashedLink.schema";
import { ZGetHashedLinksInputSchema } from "./getHashedLinks.schema";
import { ZGetHostsWithLocationOptionsInputSchema } from "./getHostsWithLocationOptions.schema";
import { ZMassApplyHostLocationInputSchema } from "./massApplyHostLocation.schema";
import { get } from "./procedures/get";
import { createEventPbacProcedure } from "./util";
@@ -145,4 +147,32 @@ export const eventTypesRouter = router({
input,
});
}),
getHostsWithLocationOptions: createEventPbacProcedure("eventType.update", [
MembershipRole.ADMIN,
MembershipRole.OWNER,
])
.input(ZGetHostsWithLocationOptionsInputSchema)
.query(async ({ ctx, input }) => {
const { getHostsWithLocationOptionsHandler } = await import("./getHostsWithLocationOptions.handler");
return getHostsWithLocationOptionsHandler({
ctx,
input,
});
}),
massApplyHostLocation: createEventPbacProcedure("eventType.update", [
MembershipRole.ADMIN,
MembershipRole.OWNER,
])
.input(ZMassApplyHostLocationInputSchema)
.mutation(async ({ ctx, input }) => {
const { massApplyHostLocationHandler } = await import("./massApplyHostLocation.handler");
return massApplyHostLocationHandler({
ctx,
input,
});
}),
});
@@ -0,0 +1,143 @@
import { appStoreMetadata } from "@calcom/app-store/appStoreMetaData";
import { enrichUsersWithDelegationCredentials } from "@calcom/app-store/delegationCredential";
import { EventTypeRepository } from "@calcom/features/eventtypes/repositories/eventTypeRepository";
import { HostRepository } from "@calcom/features/host/repositories/HostRepository";
import type { PrismaClient, Prisma } from "@calcom/prisma/client";
import { userMetadata } from "@calcom/prisma/zod-utils";
import { TRPCError } from "@trpc/server";
import type { TrpcSessionUser } from "../../../types";
import type { TGetHostsWithLocationOptionsInputSchema } from "./getHostsWithLocationOptions.schema";
type GetHostsWithLocationOptionsInput = {
ctx: {
user: NonNullable<TrpcSessionUser>;
prisma: PrismaClient;
};
input: TGetHostsWithLocationOptionsInputSchema;
};
type HostFromRepository = Awaited<
ReturnType<HostRepository["findHostsWithLocationOptionsPaginated"]>
>["items"][number];
type EnrichedCredential = {
id: number;
appId: string | null;
type: string;
};
export type HostWithLocationOptions = {
userId: number;
name: string | null;
email: string;
avatarUrl: string | null;
defaultConferencingApp: {
appSlug?: string;
appLink?: string;
} | null;
location: {
id: string;
type: string;
credentialId: number | null;
link: string | null;
address: string | null;
phoneNumber: string | null;
} | null;
installedApps: {
appId: string | null;
credentialId: number;
type: string;
locationOption?: {
value: string;
label: string;
icon?: string;
};
}[];
};
export type GetHostsWithLocationOptionsResponse = {
hosts: HostWithLocationOptions[];
nextCursor: number | undefined;
hasMore: boolean;
};
export function transformHostsToResponse(
hosts: HostFromRepository[],
enrichedUsers: { credentials: EnrichedCredential[] }[]
): HostWithLocationOptions[] {
const appMetadataBySlug = new Map(Object.values(appStoreMetadata).map((app) => [app.slug, app]));
return hosts.map((host, index) => ({
userId: host.userId,
name: host.user.name,
email: host.user.email,
avatarUrl: host.user.avatarUrl,
defaultConferencingApp: userMetadata.safeParse(host.user.metadata).data?.defaultConferencingApp ?? null,
location: host.location,
installedApps: enrichedUsers[index].credentials.map((cred) => {
const appMeta = cred.appId ? appMetadataBySlug.get(cred.appId) : null;
const locationData = appMeta?.appData?.location;
return {
appId: cred.appId,
credentialId: cred.id,
type: cred.type,
locationOption: locationData
? {
value: locationData.type,
label: locationData.label || appMeta?.name || cred.appId || "",
icon: appMeta?.logo,
}
: undefined,
};
}),
}));
}
export const getHostsWithLocationOptionsHandler = async ({
ctx,
input,
}: GetHostsWithLocationOptionsInput): Promise<GetHostsWithLocationOptionsResponse> => {
const { eventTypeId, cursor, limit } = input;
const eventTypeRepo = new EventTypeRepository(ctx.prisma);
const eventType = await eventTypeRepo.findByIdWithTeamId({ id: eventTypeId });
if (!eventType) {
throw new TRPCError({ code: "NOT_FOUND", message: "Event type not found" });
}
const organizationId = ctx.user.organizationId ?? null;
const hostRepository = new HostRepository(ctx.prisma);
const {
items: hosts,
nextCursor,
hasMore,
} = await hostRepository.findHostsWithLocationOptionsPaginated({
eventTypeId,
cursor,
limit,
});
const usersForEnrichment = hosts.map((host) => ({
id: host.user.id,
email: host.user.email,
credentials: host.user.credentials.map((cred) => ({
...cred,
key: {} as Prisma.JsonValue,
})),
}));
const enrichedUsers = await enrichUsersWithDelegationCredentials({
orgId: organizationId,
users: usersForEnrichment,
});
return {
hosts: transformHostsToResponse(hosts, enrichedUsers),
nextCursor,
hasMore,
};
};
@@ -0,0 +1,9 @@
import { z } from "zod";
export const ZGetHostsWithLocationOptionsInputSchema = z.object({
eventTypeId: z.number(),
cursor: z.number().optional(),
limit: z.number().min(1).max(100).default(10),
});
export type TGetHostsWithLocationOptionsInputSchema = z.infer<typeof ZGetHostsWithLocationOptionsInputSchema>;
@@ -102,6 +102,7 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
restrictionScheduleId,
calVideoSettings,
hostGroups,
enablePerHostLocations,
...rest
} = input;
@@ -256,6 +257,7 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
}),
seatsPerTimeSlot,
maxLeadThreshold: isLoadBalancingDisabled ? null : rest.maxLeadThreshold,
...(enablePerHostLocations !== undefined && { enablePerHostLocations }),
};
data.locations = locations ?? undefined;
@@ -473,6 +475,8 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
});
}
let hostLocationDeletions: { userId: number; eventTypeId: number }[] = [];
if (teamId && hosts) {
// check if all hosts can be assigned (memberships that have accepted invite)
const teamMemberIds = await membershipRepo.listAcceptedTeamMemberIds({ teamId });
@@ -489,6 +493,9 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
const newHostsSet = new Set(hosts.map((oldHost) => oldHost.userId));
const existingHosts = hosts.filter((newHost) => oldHostsSet.has(newHost.userId));
hostLocationDeletions = existingHosts
.filter((host) => host.location === null)
.map((host) => ({ userId: host.userId, eventTypeId: id }));
const newHosts = hosts.filter((newHost) => !oldHostsSet.has(newHost.userId));
const removedHosts = eventType.hosts.filter((oldHost) => !newHostsSet.has(oldHost.userId));
@@ -500,29 +507,105 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
})),
},
create: newHosts.map((host) => {
return {
...host,
const hostData: {
userId: number;
isFixed: boolean;
priority: number;
weight: number;
groupId: string | null | undefined;
scheduleId?: number | null | undefined;
location?: {
create: {
type: string;
credentialId: number | null | undefined;
link: string | null | undefined;
address: string | null | undefined;
phoneNumber: string | null | undefined;
};
};
} = {
userId: host.userId,
isFixed: data.schedulingType === SchedulingType.COLLECTIVE || host.isFixed || false,
priority: host.priority ?? 2,
weight: host.weight ?? 100,
groupId: host.groupId,
scheduleId: host.scheduleId ?? null,
};
if (host.location) {
hostData.location = {
create: {
type: host.location.type,
credentialId: host.location.credentialId,
link: host.location.link,
address: host.location.address,
phoneNumber: host.location.phoneNumber,
},
};
}
return hostData;
}),
update: existingHosts.map((host) => {
const updateData: {
isFixed: boolean | undefined;
priority: number;
weight: number;
scheduleId: number | null | undefined;
groupId: string | null | undefined;
location?: {
upsert: {
create: {
type: string;
credentialId: number | null | undefined;
link: string | null | undefined;
address: string | null | undefined;
phoneNumber: string | null | undefined;
};
update: {
type: string;
credentialId: number | null | undefined;
link: string | null | undefined;
address: string | null | undefined;
phoneNumber: string | null | undefined;
};
};
};
} = {
isFixed: data.schedulingType === SchedulingType.COLLECTIVE || host.isFixed,
priority: host.priority ?? 2,
weight: host.weight ?? 100,
scheduleId: host.scheduleId === undefined ? undefined : host.scheduleId,
groupId: host.groupId,
};
}),
update: existingHosts.map((host) => ({
where: {
userId_eventTypeId: {
userId: host.userId,
eventTypeId: id,
if (host.location) {
updateData.location = {
upsert: {
create: {
type: host.location.type,
credentialId: host.location.credentialId,
link: host.location.link,
address: host.location.address,
phoneNumber: host.location.phoneNumber,
},
update: {
type: host.location.type,
credentialId: host.location.credentialId,
link: host.location.link,
address: host.location.address,
phoneNumber: host.location.phoneNumber,
},
},
};
}
return {
where: {
userId_eventTypeId: {
userId: host.userId,
eventTypeId: id,
},
},
},
data: {
isFixed: data.schedulingType === SchedulingType.COLLECTIVE || host.isFixed,
priority: host.priority ?? 2,
weight: host.weight ?? 100,
scheduleId: host.scheduleId ?? null,
groupId: host.groupId,
},
})),
data: updateData,
};
}),
};
}
@@ -710,6 +793,15 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
}
throw e;
}
if (hostLocationDeletions.length > 0) {
await ctx.prisma.hostLocation.deleteMany({
where: {
OR: hostLocationDeletions,
},
});
}
const updatedValues = Object.entries(data).reduce((acc, [key, value]) => {
if (value !== undefined) {
// @ts-expect-error Element implicitly has any type
@@ -0,0 +1,73 @@
import { appStoreMetadata } from "@calcom/app-store/appStoreMetaData";
import { EventTypeRepository } from "@calcom/features/eventtypes/repositories/eventTypeRepository";
import { HostRepository } from "@calcom/features/host/repositories/HostRepository";
import { HostLocationRepository } from "@calcom/features/host/repositories/HostLocationRepository";
import type { PrismaClient } from "@calcom/prisma";
import { TRPCError } from "@trpc/server";
import type { TrpcSessionUser } from "../../../types";
import type { TMassApplyHostLocationInputSchema } from "./massApplyHostLocation.schema";
type MassApplyHostLocationInput = {
ctx: {
user: NonNullable<TrpcSessionUser>;
prisma: PrismaClient;
};
input: TMassApplyHostLocationInputSchema;
};
type MassApplyHostLocationResponse = {
success: boolean;
updatedCount: number;
};
const findCredentialIdForLocationType = (
locationType: string,
credentials: { id: number; type: string; appId: string | null }[]
): number | null => {
const appMeta = Object.values(appStoreMetadata).find(
(app) => app.appData?.location?.type === locationType
);
if (!appMeta) return null;
const matchingCredential = credentials.find(
(cred) => cred.type === appMeta.type || cred.appId === appMeta.slug
);
return matchingCredential?.id ?? null;
};
export const massApplyHostLocationHandler = async ({
ctx,
input,
}: MassApplyHostLocationInput): Promise<MassApplyHostLocationResponse> => {
const { eventTypeId, locationType, link, address, phoneNumber } = input;
const eventTypeRepo = new EventTypeRepository(ctx.prisma);
const eventType = await eventTypeRepo.findByIdWithTeamId({ id: eventTypeId });
if (!eventType) {
throw new TRPCError({ code: "NOT_FOUND", message: "Event type not found" });
}
const hostRepo = new HostRepository(ctx.prisma);
const hosts = await hostRepo.findHostsWithConferencingCredentials(eventTypeId);
if (hosts.length === 0) {
return { success: true, updatedCount: 0 };
}
const hostLocationRepo = new HostLocationRepository(ctx.prisma);
const locations = hosts.map((host) => ({
userId: host.userId,
eventTypeId,
type: locationType,
link: link || null,
address: address || null,
phoneNumber: phoneNumber || null,
credentialId: findCredentialIdForLocationType(locationType, host.user.credentials),
}));
await hostLocationRepo.upsertMany(locations);
return { success: true, updatedCount: hosts.length };
};
@@ -0,0 +1,11 @@
import { z } from "zod";
export const ZMassApplyHostLocationInputSchema = z.object({
eventTypeId: z.number().int(),
locationType: z.string(),
link: z.string().optional(),
address: z.string().optional(),
phoneNumber: z.string().optional(),
});
export type TMassApplyHostLocationInputSchema = z.infer<typeof ZMassApplyHostLocationInputSchema>;
@@ -59,6 +59,17 @@ type CalVideoSettings = {
requireEmailForGuests?: boolean | null;
} | null;
type HostLocationInput = {
id?: string;
userId: number;
eventTypeId: number;
type: string;
credentialId?: number | null;
link?: string | null;
address?: string | null;
phoneNumber?: string | null;
};
type HostInput = {
userId: number;
profileId?: number | null;
@@ -67,6 +78,7 @@ type HostInput = {
weight?: number | null;
scheduleId?: number | null;
groupId?: string | null;
location?: HostLocationInput | null;
};
type HostGroupInput = {
@@ -233,6 +245,7 @@ export type TUpdateInputSchema = {
instantMeetingSchedule?: number | null;
multiplePrivateLinks?: (string | HashedLinkInput)[];
hostGroups?: HostGroupInput[];
enablePerHostLocations?: boolean;
};
// ============================================================================
@@ -276,6 +289,17 @@ const calVideoSettingsSchema: z.ZodType<CalVideoSettings | undefined> = z
.optional()
.nullable();
const hostLocationSchema = z.object({
id: z.string().optional(),
userId: z.number(),
eventTypeId: z.number(),
type: z.string(),
credentialId: z.number().optional().nullable(),
link: z.string().optional().nullable(),
address: z.string().optional().nullable(),
phoneNumber: z.string().optional().nullable(),
});
const hostSchema: z.ZodType<HostInput> = z.object({
userId: z.number(),
profileId: z.number().or(z.null()).optional(),
@@ -284,6 +308,7 @@ const hostSchema: z.ZodType<HostInput> = z.object({
weight: z.number().min(0).optional().nullable(),
scheduleId: z.number().optional().nullable(),
groupId: z.string().optional().nullable(),
location: hostLocationSchema.optional().nullable(),
});
const hostGroupSchema: z.ZodType<HostGroupInput> = z.object({
@@ -417,6 +442,7 @@ const BaseEventTypeUpdateInput: z.ZodType<TUpdateInputSchema> = z
instantMeetingSchedule: z.number().nullable().optional(),
multiplePrivateLinks: z.array(z.union([z.string(), hashedLinkInputSchema])).optional(),
hostGroups: z.array(hostGroupSchema).optional(),
enablePerHostLocations: z.boolean().optional(),
})
.strict();