feat: auto-accept team invitations for existing users (#24091)

* feat: auto-accept team invitations for existing users

- Change email button text from 'View Invitation' to 'Accept Invite'
- Implement auto-accept flow when clicking email CTA
- Update TeamService.inviteMemberByToken to support auto-acceptance
- Add new autoAcceptInvite tRPC endpoint for handling auto-acceptance
- Update invitation link generation to include autoAccept parameter
- Handle both team and organization invitation scenarios
- Maintain payment/billing flow integration with TeamBilling.updateQuantity
- Preserve backward compatibility with existing manual flow
- Update all locale files with new 'Accept Invite' button text

Co-Authored-By: [email protected] <[email protected]>

* revert: locale changes except English

- Keep only English 'Accept Invite' translation
- Revert all other locale files to original 'View Invitation' translations
- Maintain core auto-accept invitation functionality

Co-Authored-By: [email protected] <[email protected]>

* simplify: remove autoAccept parameter and make auto-acceptance default

- Remove autoAccept parameter from TeamService.inviteMemberByToken
- Always auto-accept invitations for existing users clicking email links
- Remove autoAccept logic from teams server-page.tsx
- Remove autoAccept=true from invitation URLs
- Delete autoAcceptInvite handler and schema files
- Remove autoAcceptInvite endpoint from tRPC router
- Simplify invitation flow to match new user pattern

Co-Authored-By: [email protected] <[email protected]>

* test: update teamService test to expect auto-accepted memberships

- Change expectation from accepted: false to accepted: true
- Update test description to reflect auto-accept behavior
- Fix TypeScript type casting to use Pick<TeamRepository, 'deleteById'>
- Aligns with new default auto-acceptance for team invitations

Co-Authored-By: [email protected] <[email protected]>

* update

* Update utils.ts

* fix type error

* delete token

* add prisma transaction

* update

* update param

* test: fix mock objects in teamService tests with realistic data

- Fix duplicate property assignments in mock user objects
- Use proper email format ([email protected]) for email fields
- Use proper username format (testuser) for username fields
- Fix logic error in acceptInvitationByToken (|| to &&)
- Add autoAccept parameter to resendInvitation.handler.ts
- All 16 tests passing with proper TypeScript types

Co-Authored-By: [email protected] <[email protected]>

* test: add e2e tests for team invitation auto-accept flow

- Add test for existing user auto-accepting team invitation via email link
- Add test for error handling when wrong user tries to use invitation link
- Verify proper user identity validation and database state changes
- Follow existing e2e test patterns with browser context isolation
- Fix ESLint warnings: replace conditional with assertion and remove unused browser parameter

Co-Authored-By: [email protected] <[email protected]>

* fix

* fix

* fix: update team owner creation in e2e tests to include proper names

- Fix email subject mismatch in auto-accept invitation tests
- Team owners now created with explicit names instead of undefined
- Matches pattern used in other working team invitation tests

Co-Authored-By: [email protected] <[email protected]>

* fix: update organization invitation test helper to match new auto-accept link format

- Change expectExistingUserToBeInvitedToOrganization to look for 'teams?token' instead of 'settings/team'
- Fixes 'Invite link not found' error in organization booking e2e test
- Aligns with auto-accept invitation URL changes that use /teams?token= format
- Fix eslint disable comment for playwright rule

Co-Authored-By: [email protected] <[email protected]>

* address coderrabit review

* fix failing test

* addressed review

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2025-09-30 13:07:21 +00:00
1 parent fea7e66996
commit 27820ce897
12 files changed
+630 -111

No files matched your search

@@ -23,7 +23,8 @@ const ServerPage = async ({ searchParams: _searchParams }: ServerPageProps) => {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
const searchParams = await _searchParams;
const token = Array.isArray(searchParams?.token) ? searchParams.token[0] : searchParams?.token;
const callbackUrl = token ? `/teams?token=${encodeURIComponent(token)}` : null;
const autoAccept = Array.isArray(searchParams?.autoAccept) ? searchParams.autoAccept[0] : searchParams?.autoAccept;
const callbackUrl = token ? `/teams?token=${encodeURIComponent(token)}${autoAccept ? `&autoAccept=${encodeURIComponent(autoAccept)}` : ''}` : null;
if (!session) {
redirect(callbackUrl ? `/auth/login?callbackUrl=${callbackUrl}` : "/auth/login");
@@ -33,14 +33,21 @@ export const ServerTeamsListing = async ({
session: Session;
}) => {
const token = Array.isArray(searchParams?.token) ? searchParams.token[0] : searchParams?.token;
const autoAccept = Array.isArray(searchParams?.autoAccept) ? searchParams.autoAccept[0] : searchParams?.autoAccept;
const userId = session.user.id;
let invitationAccepted = false;
let teamNameFromInvite,
errorMsgFromInvite = null;
if (token) {
try {
teamNameFromInvite = await TeamService.inviteMemberByToken(token, userId);
if (autoAccept === "true") {
await TeamService.acceptInvitationByToken(token, userId);
invitationAccepted = true;
} else {
teamNameFromInvite = await TeamService.inviteMemberByToken(token, userId);
}
} catch (e) {
errorMsgFromInvite = "Error while fetching teams";
if (e instanceof TRPCError) errorMsgFromInvite = e.message;
@@ -64,6 +71,7 @@ export const ServerTeamsListing = async ({
return {
Main: (
<TeamsListing
invitationAccepted={invitationAccepted}
teams={teams}
orgId={orgId ?? null}
permissions={{
+1 -2
View File
@@ -15,7 +15,6 @@ export async function expectInvitationEmailToBeReceived(
) {
if (!emails) return null;
// eslint-disable-next-line playwright/no-wait-for-timeout
await page.waitForTimeout(2000);
const receivedEmails = await getEmailsReceivedByUser({ emails, userEmail });
expect(receivedEmails?.total).toBe(1);
@@ -36,5 +35,5 @@ export async function expectExistingUserToBeInvitedToOrganization(
userEmail: string,
subject?: string | null
) {
return expectInvitationEmailToBeReceived(page, emails, userEmail, subject, "settings/team");
return expectInvitationEmailToBeReceived(page, emails, userEmail, subject, "teams?token");
}
+126 -3
View File
@@ -47,8 +47,7 @@ test.describe("Team", () => {
page.locator(`[data-testid="email-${invitedUserEmail.replace("@", "")}-pending"]`)
).toHaveCount(1);
// eslint-disable-next-line playwright/no-conditional-in-test
if (!inviteLink) return null;
expect(inviteLink).toBeTruthy();
// Follow invite link to new window
const context = await browser.newContext();
@@ -103,7 +102,7 @@ test.describe("Team", () => {
});
});
test("Invitation (verified)", async ({ browser, page, users, emails }) => {
test("Invitation (verified)", async ({ page, users, emails }) => {
const t = await localize("en");
const teamOwner = await users.create({ name: `team-owner-${Date.now()}` }, { hasTeam: true });
const { team } = await teamOwner.getFirstTeamMembership();
@@ -192,4 +191,128 @@ test.describe("Team", () => {
});
expect(parentEventType?.children.find((et) => et.userId === invitedMember.id)).toBeTruthy();
});
test("Auto-accept invitation for existing user", async ({ browser, page, users, emails }) => {
const t = await localize("en");
const teamOwner = await users.create({ name: "Invited User" }, { hasTeam: true });
const { team } = await teamOwner.getFirstTeamMembership();
const invitedUser = await users.create({
email: `invited-user-${Date.now()}@example.com`,
name: "Invited User",
});
await teamOwner.apiLogin();
await page.goto(`/settings/teams/${team.id}/members`);
let inviteLink: string;
await test.step("Send invitation to existing user", async () => {
await page.waitForLoadState("domcontentloaded");
await page.waitForTimeout(500);
await page.getByTestId("new-member-button").click();
await page.locator('input[name="inviteUser"]').fill(invitedUser.email);
await page.getByText(t("send_invite")).click();
inviteLink = await expectInvitationEmailToBeReceived(
page,
emails,
invitedUser.email,
`${teamOwner.name} invited you to join the team ${team.name} on Cal.com`,
"teams?token"
);
expect(inviteLink).toContain("autoAccept=true");
const membership = await prisma.membership.findFirst({
where: {
userId: invitedUser.id,
teamId: team.id,
},
});
expect(membership?.accepted).toBe(false);
});
await test.step("Auto-accept invitation by clicking link", async () => {
const [secondContext, secondPage] = await invitedUser.apiLoginOnNewBrowser(browser);
await secondPage.goto(inviteLink);
await expect(secondPage.getByText("Successfully joined")).toBeVisible();
const membership = await prisma.membership.findFirst({
where: {
userId: invitedUser.id,
teamId: team.id,
},
});
expect(membership?.accepted).toBe(true);
await secondPage.close();
await secondContext.close();
});
});
test("Error when wrong user tries to use invitation link", async ({ browser, page, users, emails }) => {
const t = await localize("en");
const teamOwner = await users.create({ name: "Wrong User" }, { hasTeam: true });
const { team } = await teamOwner.getFirstTeamMembership();
const invitedUser = await users.create({
email: `invited-user-${Date.now()}@example.com`,
name: "Invited User",
});
const wrongUser = await users.create({
email: `wrong-user-${Date.now()}@example.com`,
name: "Wrong User",
});
await teamOwner.apiLogin();
await page.goto(`/settings/teams/${team.id}/members`);
let inviteLink: string;
await test.step("Send invitation to specific user", async () => {
await page.waitForLoadState("domcontentloaded");
await page.waitForTimeout(500);
await page.getByTestId("new-member-button").click();
await page.locator('input[name="inviteUser"]').fill(invitedUser.email);
await page.getByText(t("send_invite")).click();
inviteLink = await expectInvitationEmailToBeReceived(
page,
emails,
invitedUser.email,
`${teamOwner.name} invited you to join the team ${team.name} on Cal.com`,
"teams?token"
);
expect(inviteLink).toContain("autoAccept=true");
});
await test.step("Wrong user tries to use invitation link", async () => {
const [secondContext, secondPage] = await wrongUser.apiLoginOnNewBrowser(browser);
await secondPage.goto(inviteLink);
await expect(secondPage.getByText("This invitation is not for your account")).toBeVisible();
const membership = await prisma.membership.findFirst({
where: {
userId: wrongUser.id,
teamId: team.id,
},
});
expect(membership).toBeNull();
const invitedMembership = await prisma.membership.findFirst({
where: {
userId: invitedUser.id,
teamId: team.id,
},
});
expect(invitedMembership?.accepted).toBe(false);
await secondPage.close();
await secondContext.close();
});
});
});
@@ -2152,6 +2152,9 @@
"delete_sso_configuration_confirmation_description": "Are you sure you want to delete the {{connectionType}} configuration? Your team members who use {{connectionType}} login will no longer be able to access Cal.com.",
"organizer_timezone": "Organizer timezone",
"email_user_cta": "View Invitation",
"accept_invite": "Accept Invite",
"join_now": "Join Now",
"successfully_joined": "Successfully joined",
"email_no_user_invite_heading_subteam": "You've been invited to join a team of {{parentTeamName}} organization",
"email_no_user_invite_heading_org": "You've been invited to join a {{appName}} organization",
"email_no_user_invite_subheading": "{{invitedBy}} has invited you to join their team on {{appName}}. {{appName}} is the event-juggling scheduler that enables you and your team to schedule meetings without the email tennis.",