feat: Send emails to potentially affected Organization Members on disabling delegation credential (#21276)

* mvp

* Improve UI

* wip

* self-review

* self-review

---------

Co-authored-by: Omar López <[email protected]>
This commit is contained in:
Hariom BalharaandOmar López authored and GitHub committed 2025-05-22 03:28:21 +00:00
1 parent d84d80eea6
commit 4fcf4081d0
15 files changed
+292 -9

No files matched your search

@@ -1599,6 +1599,7 @@
"team_url": "Team URL",
"team_members": "Team members",
"more": "More",
"and_count_more": "and {{count}} more",
"more_page_footer": "We view the mobile application as an extension of the web application. If you are performing any complicated actions, please refer back to the web application.",
"workflow_example_1": "Send SMS reminder 24 hours before event starts to attendee",
"workflow_example_2": "Send custom SMS when event is rescheduled to attendee",
@@ -3221,5 +3222,7 @@
"requires_credits": "Requires credits",
"requires_credits_tooltip": "You need enough credits in your account to use this feature",
"available_credits": "Available credits",
"members_affected_by_disabling_delegation_credential": "Affected members",
"no_members_affected_by_disabling_delegation_credential": "No members affected by disabling delegation credential",
"ADD_NEW_STRINGS_ABOVE_THIS_LINE_TO_PREVENT_MERGE_CONFLICTS": "↑↑↑↑↑↑↑↑↑↑↑↑↑ Add your new strings above here ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑"
}
+20
View File
@@ -50,6 +50,7 @@ import type { ChangeOfEmailVerifyLink } from "./templates/change-account-email-v
import ChangeOfEmailVerifyEmail from "./templates/change-account-email-verify";
import CreditBalanceLimitReachedEmail from "./templates/credit-balance-limit-reached-email";
import CreditBalanceLowWarningEmail from "./templates/credit-balance-low-warning-email";
import DelegationCredentialDisabledEmail from "./templates/delegation-credential-disabled-email";
import DisabledAppEmail from "./templates/disabled-app-email";
import type { Feedback } from "./templates/feedback-email";
import FeedbackEmail from "./templates/feedback-email";
@@ -835,3 +836,22 @@ export const sendCreditBalanceLimitReachedEmails = async ({
await sendEmail(() => new CreditBalanceLimitReachedEmail({ user }));
}
};
export const sendDelegationCredentialDisabledEmail = async ({
recipientEmail,
recipientName,
connectionName,
}: {
recipientEmail: string;
recipientName?: string;
connectionName: string;
}) => {
await sendEmail(
() =>
new DelegationCredentialDisabledEmail({
recipientEmail,
recipientName,
connectionName,
})
);
};
@@ -0,0 +1,64 @@
import { EMAIL_FROM_NAME } from "@calcom/lib/constants";
import BaseEmail from "./_base-email";
export default class DelegationCredentialDisabledEmail extends BaseEmail {
recipientEmail: string;
recipientName?: string;
connectionName: string;
constructor({
recipientEmail,
recipientName,
connectionName,
}: {
recipientEmail: string;
recipientName?: string;
connectionName: string;
}) {
super();
this.name = "DELEGATION_CREDENTIAL_DISABLED";
this.recipientEmail = recipientEmail;
this.recipientName = recipientName;
this.connectionName = connectionName;
}
protected async getNodeMailerPayload(): Promise<Record<string, unknown>> {
return {
from: `${EMAIL_FROM_NAME} <${this.getMailerOptions().from}>`,
to: this.recipientEmail,
subject: `You might need to connect your ${this.connectionName} Calendar`,
html: await this.getHtml(),
text: this.getTextBody(),
};
}
async getHtml() {
return `
<div style="font-family: Arial, sans-serif;">
<h2>Action Required: Connect your ${this.connectionName} Calendar</h2>
<p>
${this.recipientName ? `Hi ${this.recipientName},` : "Hello,"}
</p>
<p>
An admin has disabled Delegation Credential for your organization. You may need to connect your <b>${
this.connectionName
} Calendar</b> manually to continue receiving bookings and updates.
</p>
<p>
Please log in to your Cal.com account and connect your calendar from your settings page.
</p>
<p>
If you have already connected your calendar, you can ignore this message.
</p>
<p>
Thank you,<br />The Cal.com Team
</p>
</div>
`;
}
protected getTextBody(): string {
return `Action Required: Connect your ${this.connectionName} Calendar\n\nAn admin has disabled Delegation Credential for your organization. You may need to connect your ${this.connectionName} Calendar manually to continue receiving bookings and updates.\n\nPlease log in to your Cal.com account and connect your calendar from your settings page.\n\nIf you have already connected your calendar, you can ignore this message.\n\nThank you,\nThe Cal.com Team`;
}
}
@@ -113,7 +113,7 @@ Step 6: Enable Delegation Credential(To Be taken By Cal.com organization Owner/A
Cron jobs ensure that for each and every member of the organization that has Delegation Credential enabled, corresponding SelectedCalendar records are there. These crons currently run every 5 minutes and process a batch in one run to avoid overloading the DB and third party CalendarAPIs, look at vercel.json for the up-to-date schedule.
- `credentials` cron job creates Delegation User Credential records for all the members of the organization who don't have Delegation User Credentials yet. It also ensures that on disabling Delegation Credential, the Delegation User Credentials are deleted which automatically deletes the SelectedCalendars through DB cascade.
- `credentials` cron job creates Delegation User Credential records for all the members of the organization who don't have Delegation User Credentials yet. It also ensures that on disabling Delegation Credential, the Delegation User Credentials are deleted which automatically deletes the SelectedCalendar and CalendarCache records through DB cascade.
- `selected-calendars` cron job creates SelectedCalendar records for all the Delegation User Credentials of the organization who don't have Selected Calendars yet.
### Important Points
@@ -134,7 +134,8 @@ Cron jobs ensure that for each and every member of the organization that has Del
### Impact of disabling Delegation Credential
Disabling effectively stops generating in-memory delegation user credentials. So, any members who haven't manually connected their Calendar and thus their calendar connections were working only because of Delegation Credential, would have their calendar connections broken.
- It immediately stops generating in-memory delegation user credentials. So, any members who haven't manually connected their Calendar and thus their calendar connections were working only because of Delegation Credential, would have their calendar connections broken.
- Credentials cron job would delete the Delegation User Credentials which will then cascade to delete the SelectedCalendar and CalendarCache records.
### Impact of enabling Delegation Credential
- Existing calendar-cache records are re-used as we identify the relevant record by userId and key of CalendarCache record.
@@ -458,6 +458,41 @@ function DelegationCredentialList() {
);
}
function MembersThatWillBeAffectedOnDisablingDelegationCredential({
delegationCredentialId,
}: {
delegationCredentialId: string;
}) {
const { t } = useLocale();
const { data: affectedMembers, isLoading: isLoadingAffectedMembers } =
trpc.viewer.delegationCredential.getAffectedMembersForDisable.useQuery({ id: delegationCredentialId });
return (
<div className="mt-4">
<strong>{t("members_affected_by_disabling_delegation_credential")}</strong>
{isLoadingAffectedMembers ? (
<div>{t("loading")}</div>
) : affectedMembers?.length ? (
<>
<ul className="list-disc space-y-1 p-1 pl-5 sm:w-80">
{affectedMembers.slice(0, 5).map((m) => (
<li className="text-muted text-sm" key={m.email}>
{m.name ? `${m.name} (${m.email})` : m.email}
</li>
))}
</ul>
{affectedMembers.length > 5 && (
<p className="mt-2 text-sm text-gray-500">
{t("and_count_more", { count: affectedMembers.length - 5 })}
</p>
)}
</>
) : (
<div className="mt-2">{t("no_members_affected_by_disabling_delegation_credential")}</div>
)}
</div>
);
}
const ToggleDelegationDialog = ({
delegation,
onConfirm,
@@ -468,27 +503,34 @@ const ToggleDelegationDialog = ({
onClose: () => void;
}) => {
const { t } = useLocale();
if (!delegation) {
return null;
}
const isDisablingDelegation = delegation.enabled;
return (
<Dialog
name="toggle-delegation"
open={!!delegation}
onOpenChange={(open) => (!open ? onClose() : undefined)}>
<ConfirmationDialogContent
title={t(delegation.enabled ? "disable_delegation_credential" : "enable_delegation_credential")}
confirmBtnText={t(delegation.enabled ? "disable" : "enable")}
title={t(isDisablingDelegation ? "disable_delegation_credential" : "enable_delegation_credential")}
confirmBtnText={t(isDisablingDelegation ? "disable" : "enable")}
cancelBtnText={t("cancel")}
variety={delegation.enabled ? "danger" : "success"}
variety={isDisablingDelegation ? "danger" : "success"}
onConfirm={onConfirm}>
<p className="mt-5">
{t(
delegation.enabled
isDisablingDelegation
? "disable_delegation_credential_description"
: "enable_delegation_credential_description"
)}
</p>
{isDisablingDelegation && (
<MembersThatWillBeAffectedOnDisablingDelegationCredential delegationCredentialId={delegation.id} />
)}
</ConfirmationDialogContent>
</Dialog>
);
@@ -234,6 +234,8 @@ describe("DelegationCredentialRepository", () => {
domain: data.domain,
enabled: data.enabled,
createdAt: expect.any(Date),
lastEnabledAt: null,
lastDisabledAt: null,
updatedAt: null,
organizationId: data.organizationId,
workspacePlatform: {
@@ -267,6 +269,8 @@ describe("DelegationCredentialRepository", () => {
domain: created.domain,
enabled: created.enabled,
createdAt: expect.any(Date),
lastEnabledAt: created.lastEnabledAt,
lastDisabledAt: created.lastDisabledAt,
updatedAt: null,
organizationId: created.organizationId,
workspacePlatform: {
@@ -295,6 +299,8 @@ describe("DelegationCredentialRepository", () => {
expect(result).toEqual({
id: created.id,
lastEnabledAt: created.lastEnabledAt,
lastDisabledAt: created.lastDisabledAt,
domain: created.domain,
enabled: created.enabled,
createdAt: expect.any(Date),
@@ -21,6 +21,8 @@ const delegationCredentialSafeSelect = {
createdAt: true,
updatedAt: true,
organizationId: true,
lastEnabledAt: true,
lastDisabledAt: true,
workspacePlatform: {
select: {
name: true,
@@ -173,6 +175,8 @@ export class DelegationCredentialRepository {
domain: string;
enabled: boolean;
organizationId: number;
lastEnabledAt: Date;
lastDisabledAt: Date;
}>;
}) {
const { workspacePlatformId, organizationId, ...rest } = data;
@@ -337,4 +337,32 @@ export class MembershipRepository {
return memberships.map((membership) => membership.teamId);
}
/**
* Returns members who joined after the given time
*/
static async findMembershipsCreatedAfterTimeIncludeUser({
organizationId,
time,
}: {
organizationId: number;
time: Date;
}) {
return prisma.membership.findMany({
where: {
teamId: organizationId,
createdAt: { gt: time },
accepted: true,
},
include: {
user: {
select: {
email: true,
name: true,
id: true,
},
},
},
});
}
}
@@ -0,0 +1,3 @@
-- AlterTable
ALTER TABLE "DelegationCredential" ADD COLUMN "lastDisabledAt" TIMESTAMP(3),
ADD COLUMN "lastEnabledAt" TIMESTAMP(3);
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Membership" ALTER COLUMN "createdAt" SET DEFAULT CURRENT_TIMESTAMP;
+5 -1
View File
@@ -592,7 +592,7 @@ model Membership {
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
disableImpersonation Boolean @default(false)
AttributeToUser AttributeToUser[]
createdAt DateTime?
createdAt DateTime? @default(now())
updatedAt DateTime? @updatedAt
@@unique([userId, teamId])
@@ -2007,6 +2007,10 @@ model DelegationCredential {
/// @zod.custom(imports.serviceAccountKeySchema)
serviceAccountKey Json
enabled Boolean @default(false)
// lastEnabledAt is set when the delegation credential is enabled
lastEnabledAt DateTime?
// lastDisabledAt is set when the delegation credential is disabled. So, lastDisabledAt could be earlier then lastEnabledAt if the delegation credential was enabled -> then disabled -> then enabled again.
lastDisabledAt DateTime?
organizationId Int
organization Team @relation(fields: [organizationId], references: [id], onDelete: Cascade)
domain String
@@ -10,6 +10,7 @@ import {
DelegationCredentialUpdateSchema,
DelegationCredentialDeleteSchema,
DelegationCredentialToggleEnabledSchema,
DelegationCredentialGetAffectedMembersForDisableSchema,
} from "./schema";
const checkDelegationCredentialFeature = async ({
@@ -69,6 +70,13 @@ export const delegationCredentialRouter = router({
const handler = await import("./toggleEnabled.handler").then((mod) => mod.default);
return handler(opts);
}),
getAffectedMembersForDisable: authedOrgAdminProcedure
.use(checkDelegationCredentialFeature)
.input(DelegationCredentialGetAffectedMembersForDisableSchema)
.query(async (opts) => {
const handler = await import("./getAffectedMembersForDisable.handler").then((mod) => mod.default);
return handler(opts);
}),
delete: authedOrgAdminProcedure
.use(checkDelegationCredentialFeature)
.input(DelegationCredentialDeleteSchema)
@@ -0,0 +1,48 @@
import logger from "@calcom/lib/logger";
import { DelegationCredentialRepository } from "@calcom/lib/server/repository/delegationCredential";
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
import type { TDelegationCredentialGetAffectedMembersForDisableSchema } from "./schema";
const log = logger.getSubLogger({ prefix: ["[DelegationCredential]"] });
export async function getAffectedMembersForDisable({
delegationCredentialId,
}: {
delegationCredentialId: string;
}) {
const delegationCredential = await DelegationCredentialRepository.findById({ id: delegationCredentialId });
if (!delegationCredential) {
// If we cant find the delegation credential, we assume no members were affected
return [];
}
const lastEnabledAt = delegationCredential.lastEnabledAt;
if (!lastEnabledAt) {
log.info(
`Delegation credential ${delegationCredentialId} has no lastEnabledAt, so assuming no members were affected`
);
return [];
}
// Find members who joined after the delegation credential was last enabled
const membershipsThatCouldPotentiallyBeAffected =
await MembershipRepository.findMembershipsCreatedAfterTimeIncludeUser({
organizationId: delegationCredential.organizationId,
time: lastEnabledAt,
});
return membershipsThatCouldPotentiallyBeAffected.map((membership) => ({
email: membership.user.email,
name: membership.user.name,
id: membership.user.id,
}));
}
export default function getAffectedMembersForDisableHandler({
input,
}: {
input: TDelegationCredentialGetAffectedMembersForDisableSchema;
}) {
return getAffectedMembersForDisable({
delegationCredentialId: input.id,
});
}
@@ -22,3 +22,11 @@ export const DelegationCredentialToggleEnabledSchema = z.object({
export const DelegationCredentialDeleteSchema = z.object({
id: z.string(),
});
export const DelegationCredentialGetAffectedMembersForDisableSchema = z.object({
id: z.string(),
});
export type TDelegationCredentialGetAffectedMembersForDisableSchema = z.infer<
typeof DelegationCredentialGetAffectedMembersForDisableSchema
>;
@@ -1,13 +1,18 @@
import type { z } from "zod";
import { sendDelegationCredentialDisabledEmail } from "@calcom/emails/email-manager";
import { checkIfSuccessfullyConfiguredInWorkspace } from "@calcom/lib/delegationCredential/server";
import logger from "@calcom/lib/logger";
import { getTranslation } from "@calcom/lib/server/i18n";
import { DelegationCredentialRepository } from "@calcom/lib/server/repository/delegationCredential";
import type { ServiceAccountKey } from "@calcom/lib/server/repository/delegationCredential";
import { getAffectedMembersForDisable } from "./getAffectedMembersForDisable.handler";
import type { DelegationCredentialToggleEnabledSchema } from "./schema";
import { ensureNoServiceAccountKey } from "./utils";
const log = logger.getSubLogger({ prefix: ["viewer", "delegationCredential", "toggleEnabled"] });
type LoggedInUser = {
id: number;
email: string;
@@ -39,17 +44,54 @@ export async function toggleDelegationCredentialEnabled(
loggedInUser: Omit<LoggedInUser, "locale" | "emailVerified">,
input: z.infer<typeof DelegationCredentialToggleEnabledSchema>
) {
if (input.enabled) {
// Fetch the current credential to check the current enabled state
const currentDelegationCredential = await DelegationCredentialRepository.findById({
id: input.id,
});
if (!currentDelegationCredential) {
throw new Error("Delegation credential not found");
}
const shouldBeEnabled = input.enabled;
if (shouldBeEnabled === currentDelegationCredential.enabled) {
// Already enabled or disabled, so no need to do anything
return currentDelegationCredential;
}
if (shouldBeEnabled) {
await assertWorkspaceConfigured({
delegationCredentialId: input.id,
user: loggedInUser,
});
}
if (!shouldBeEnabled) {
const affectedMemberships = await getAffectedMembersForDisable({ delegationCredentialId: input.id });
const connectionName = currentDelegationCredential.workspacePlatform?.name;
if (!connectionName) {
log.error(`Delegation credential ${input.id} has no workspace platform name`);
}
for (const membership of affectedMemberships) {
if (membership.email) {
await sendDelegationCredentialDisabledEmail({
recipientEmail: membership.email,
recipientName: membership.name || undefined,
connectionName,
});
}
}
}
const updatedDelegationCredential = await DelegationCredentialRepository.updateById({
id: input.id,
data: {
enabled: input.enabled,
enabled: shouldBeEnabled,
// Don't touch lastEnabledAt if we are disabling
lastEnabledAt: shouldBeEnabled ? new Date() : undefined,
// Don't touch lastDisabledAt if we are enabling
lastDisabledAt: shouldBeEnabled ? undefined : new Date(),
},
});