:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signup): nudge signups to existing org invites (#57480)
Yasenf88eba2f8d1e
diff --git a/frontend/src/scenes/authentication/signup/signupForm/SignupForm.tsx b/frontend/src/scenes/authentication/signup/signupForm/SignupForm.tsxindex 2728dc09bc16..e6759b5114d3 100644--- a/frontend/src/scenes/authentication/signup/signupForm/SignupForm.tsx+++ b/frontend/src/scenes/authentication/signup/signupForm/SignupForm.tsx@@ -47,7 +47,7 @@ export function SignupForm(): JSX.Element | null {if (passkeySignupEnabled) {return !user ? (<div className="deprecated-space-y-2">- <h2>{panelTitle}</h2>+ {panelTitle ? <h2>{panelTitle}</h2> : null}{!isSignupPanelOnboardingSubmitting && signupPanelOnboardingManualErrors?.generic && (<LemonBanner type="error">{signupPanelOnboardingManualErrors.generic?.detail ||@@ -95,7 +95,7 @@ export function SignupForm(): JSX.Element | null {// Legacy 2-panel flow (when passkey signup is disabled)return !user ? (<div className="deprecated-space-y-2">- <h2>{panelTitle}</h2>+ {panelTitle ? <h2>{panelTitle}</h2> : null}{!isSignupPanel2Submitting && signupPanel2ManualErrors?.generic && (<LemonBanner type="error">{signupPanel2ManualErrors.generic?.detail || 'Could not complete your signup. Please try again.'}diff --git a/frontend/src/scenes/authentication/signup/signupForm/panels/PendingInviteBanner.tsx b/frontend/src/scenes/authentication/signup/signupForm/panels/PendingInviteBanner.tsxnew file mode 100644index 000000000000..776fe6a5ea4d--- /dev/null+++ b/frontend/src/scenes/authentication/signup/signupForm/panels/PendingInviteBanner.tsx@@ -0,0 +1,49 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonButton } from '@posthog/lemon-ui'++import { PendingInvite, signupLogic } from '../signupLogic'++export function PendingInviteBanner({ invite, email }: { invite: PendingInvite; email: string }): JSX.Element {+ const { isPendingInviteResending, pendingInviteResent } = useValues(signupLogic)+ const { resendPendingInvite, dismissPendingInvite } = useActions(signupLogic)++ return (+ <div className="deprecated-space-y-4 Signup__panel__pending-invite">+ <h2 className="m-0">You've already been invited to PostHog</h2>+ <p className="text-secondary mb-0">+ <b>{invite.organization_name}</b> sent you an invite to join them on PostHog. Look for it in your inbox,+ or have us resend it.+ </p>+ {pendingInviteResent ? (+ <LemonBanner type="success">+ Sent. Check your inbox for the invite link from {invite.organization_name}.+ </LemonBanner>+ ) : (+ <>+ <LemonButton+ type="primary"+ status="alt"+ fullWidth+ center+ size="large"+ onClick={() => resendPendingInvite(email)}+ loading={isPendingInviteResending}+ data-attr="pending-invite-resend"+ >+ Resend invite email+ </LemonButton>+ <LemonButton+ type="secondary"+ fullWidth+ center+ onClick={dismissPendingInvite}+ data-attr="pending-invite-create-own-org"+ >+ I'd like to create my own organization+ </LemonButton>+ </>+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/authentication/signup/signupForm/panels/SignupPanel1.tsx b/frontend/src/scenes/authentication/signup/signupForm/panels/SignupPanel1.tsxindex 0456d93d814e..890d7f6bf851 100644--- a/frontend/src/scenes/authentication/signup/signupForm/panels/SignupPanel1.tsx+++ b/frontend/src/scenes/authentication/signup/signupForm/panels/SignupPanel1.tsx@@ -13,10 +13,12 @@ import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { JoinExistingOrgLink } from '../JoinExistingOrgLink'import { signupLogic } from '../signupLogic'+import { PendingInviteBanner } from './PendingInviteBanner'export function SignupPanel1(): JSX.Element | null {const { preflight, socialAuthAvailable } = useValues(preflightLogic)- const { isSignupPanel1Submitting, validatedPassword, loginUrl, emailCaseNotice } = useValues(signupLogic)+ const { isSignupPanel1Submitting, validatedPassword, loginUrl, emailCaseNotice, pendingInvite, signupPanel1 } =+ useValues(signupLogic)const emailInputRef = useRef<HTMLInputElement | null>(null)useEffect(() => {@@ -24,6 +26,10 @@ export function SignupPanel1(): JSX.Element | null {emailInputRef?.current?.focus()}, [preflight?.demo])+ if (pendingInvite) {+ return <PendingInviteBanner invite={pendingInvite} email={signupPanel1.email} />+ }+return (<div className="deprecated-space-y-4 Signup__panel__1"><RegionSelect />diff --git a/frontend/src/scenes/authentication/signup/signupForm/panels/SignupPanelEmail.tsx b/frontend/src/scenes/authentication/signup/signupForm/panels/SignupPanelEmail.tsxindex 1087ab79d1f1..cdc86c08eb38 100644--- a/frontend/src/scenes/authentication/signup/signupForm/panels/SignupPanelEmail.tsx+++ b/frontend/src/scenes/authentication/signup/signupForm/panels/SignupPanelEmail.tsx@@ -12,16 +12,29 @@ import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { JoinExistingOrgLink } from '../JoinExistingOrgLink'import { signupLogic } from '../signupLogic'+import { PendingInviteBanner } from './PendingInviteBanner'export function SignupPanelEmail(): JSX.Element | null {const { preflight, socialAuthAvailable } = useValues(preflightLogic)- const { isSignupPanelEmailSubmitting, loginUrl, emailCaseNotice, passkeyError, error } = useValues(signupLogic)+ const {+ isSignupPanelEmailSubmitting,+ loginUrl,+ emailCaseNotice,+ passkeyError,+ error,+ pendingInvite,+ signupPanelEmail,+ } = useValues(signupLogic)const emailInputRef = useRef<HTMLInputElement | null>(null)useEffect(() => {emailInputRef?.current?.focus()}, [])+ if (pendingInvite) {+ return <PendingInviteBanner invite={pendingInvite} email={signupPanelEmail.email} />+ }+return (<div className="deprecated-space-y-4 Signup__panel__email"><RegionSelect />diff --git a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.test.ts b/frontend/src/scenes/authentication/signup/signupForm/signupLogic.test.tsnew file mode 100644index 000000000000..f15a1caf9dec--- /dev/null+++ b/frontend/src/scenes/authentication/signup/signupForm/signupLogic.test.ts@@ -0,0 +1,91 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { signupLogic } from './signupLogic'++describe('signupLogic — pending invite banner', () => {+ let logic: ReturnType<typeof signupLogic.build>++ beforeEach(() => {+ useMocks({+ post: {+ '/api/signup/precheck': () => [+ 200,+ {+ email_exists: false,+ pending_invite: { organization_name: 'Acme Corp' },+ },+ ],+ '/api/signup/resend-invite': () => [200, { sent: true }],+ },+ })+ initKeaTests()+ router.actions.push('/signup')+ logic = signupLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it('shows the pending invite banner instead of advancing the panel', async () => {+ logic.actions.setSignupPanelEmailValue('email', '[email protected]')+ logic.actions.submitSignupPanelEmail()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.pendingInvite).toEqual({ organization_name: 'Acme Corp' })+ expect(logic.values.panel).toBe(0)+ })++ it('advances the panel and clears the banner when no invite is returned', async () => {+ useMocks({+ post: {+ '/api/signup/precheck': () => [200, { email_exists: false, pending_invite: null }],+ },+ })+ logic.actions.setSignupPanelEmailValue('email', '[email protected]')+ logic.actions.submitSignupPanelEmail()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.pendingInvite).toBeNull()+ expect(logic.values.panel).toBe(1)+ })++ it('advances the panel when the user dismisses the banner', async () => {+ logic.actions.setSignupPanelEmailValue('email', '[email protected]')+ logic.actions.submitSignupPanelEmail()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.pendingInvite).not.toBeNull()+ logic.actions.dismissPendingInvite()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.pendingInvite).toBeNull()+ expect(logic.values.panel).toBe(1)+ })++ it('skips the banner when skip_invite_check=1 is on the URL', async () => {+ router.actions.push('/signup', { skip_invite_check: '1' })+ logic.actions.setSignupPanelEmailValue('email', '[email protected]')+ logic.actions.submitSignupPanelEmail()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.pendingInvite).toBeNull()+ expect(logic.values.panel).toBe(1)+ })++ it('marks the invite as resent after resendPendingInvite succeeds', async () => {+ logic.actions.setPendingInvite({ organization_name: 'Acme Corp' })+ logic.actions.resendPendingInvite('[email protected]')+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.pendingInviteResent).toBe(true)+ expect(logic.values.isPendingInviteResending).toBe(false)+ })++ it('clears the resent state when a new invite banner is shown', async () => {+ logic.actions.setPendingInvite({ organization_name: 'Acme Corp' })+ logic.actions.setPendingInviteResent(true)+ logic.actions.setPendingInvite({ organization_name: 'Other Corp' })+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.pendingInviteResent).toBe(false)+ })+})diff --git a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts b/frontend/src/scenes/authentication/signup/signupForm/signupLogic.tsindex 239e03462465..72afd44dbf52 100644--- a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts+++ b/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts@@ -42,10 +42,15 @@ export interface SignupPanelOnboardingForm {referral_source_ai_prompt: string}+export interface PendingInvite {+ organization_name: string+}+interface SignupEmailPrecheckResponse {email_exists: booleancode?: stringdetail?: string+ pending_invite?: PendingInvite | null}// Keep SignupForm for backwards compatibility@@ -76,6 +81,12 @@ export const signupLogic = kea<signupLogicType>([setTurnstileSiteKey: (siteKey: string | null) => ({ siteKey }),setTurnstileToken: (token: string | null) => ({ token }),resetChallenge: true,+ // Pending-invite banner actions+ setPendingInvite: (invite: PendingInvite | null) => ({ invite }),+ dismissPendingInvite: true,+ resendPendingInvite: (email: string) => ({ email }),+ setPendingInviteResent: (resent: boolean) => ({ resent }),+ setPendingInviteResending: (resending: boolean) => ({ resending }),})),reducers(() => ({panel: [@@ -142,6 +153,27 @@ export const signupLogic = kea<signupLogicType>([resetChallenge: () => null,},],+ pendingInvite: [+ null as PendingInvite | null,+ {+ setPendingInvite: (_, { invite }) => invite,+ dismissPendingInvite: () => null,+ },+ ],+ pendingInviteResent: [+ false,+ {+ setPendingInviteResent: (_, { resent }) => resent,+ setPendingInvite: () => false,+ dismissPendingInvite: () => false,+ },+ ],+ isPendingInviteResending: [+ false,+ {+ setPendingInviteResending: (_, { resending }) => resending,+ },+ ],})),forms(({ actions, values }) => ({signupPanelEmail: {@@ -162,8 +194,9 @@ export const signupLogic = kea<signupLogicType>([actions.setSignupPanelEmailManualErrors({})actions.setPasskeyError(null)actions.setError(null)+ let precheckResponse: SignupEmailPrecheckResponsetry {- await api.create<SignupEmailPrecheckResponse>('api/signup/precheck', {+ precheckResponse = await api.create<SignupEmailPrecheckResponse>('api/signup/precheck', {email,})} catch (e: any) {@@ -181,6 +214,12 @@ export const signupLogic = kea<signupLogicType>([})return}+ const pendingInvite = precheckResponse.pending_invite ?? null+ if (pendingInvite && (router.values.searchParams as Record<string, string>).skip_invite_check !== '1') {+ actions.setPendingInvite(pendingInvite)+ return+ }+ actions.setPendingInvite(null)actions.setPanel(1)},},@@ -336,6 +375,12 @@ export const signupLogic = kea<signupLogicType>([actions.setPanel(0)return}+ const pendingInvite = precheckResponse.pending_invite ?? null+ if (pendingInvite && (router.values.searchParams as Record<string, string>).skip_invite_check !== '1') {+ actions.setPendingInvite(pendingInvite)+ return+ }+ actions.setPendingInvite(null)actions.setPanel(1)},},@@ -442,8 +487,11 @@ export const signupLogic = kea<signupLogicType>([},],panelTitle: [- (s) => [s.panel, s.passkeySignupEnabled, s.preflight],- (panel: number, passkeySignupEnabled: boolean, preflight): string => {+ (s) => [s.panel, s.passkeySignupEnabled, s.preflight, s.pendingInvite],+ (panel: number, passkeySignupEnabled: boolean, preflight, pendingInvite): string => {+ if (panel === 0 && pendingInvite) {+ return ''+ }if (preflight?.demo) {return 'Explore PostHog yourself'}@@ -466,6 +514,22 @@ export const signupLogic = kea<signupLogicType>([],}),listeners(({ actions, values }) => ({+ dismissPendingInvite: () => {+ // User chose to proceed with creating a new organization despite the pending invite.+ actions.setPanel(1)+ },+ resendPendingInvite: async ({ email }, breakpoint) => {+ actions.setPendingInviteResending(true)+ try {+ await api.create('api/signup/resend-invite', { email })+ breakpoint()+ actions.setPendingInviteResent(true)+ } catch {+ lemonToast.error('Could not resend the invite email. Please try again.')+ } finally {+ actions.setPendingInviteResending(false)+ }+ },normalizeEmailWithDelay: async ({ email }, breakpoint) => {await breakpoint(500)diff --git a/posthog/api/signup.py b/posthog/api/signup.pyindex bc635fa94951..79bc53369bda 100644--- a/posthog/api/signup.py+++ b/posthog/api/signup.py@@ -1,6 +1,7 @@import jsonimport uuid as uuid_module-from typing import Any, Optional, Union, cast+from datetime import timedelta+from typing import Any, Optional, TypedDict, Union, castfrom urllib.parse import quote, urlencodefrom django import forms@@ -11,6 +12,7 @@ from django.core.exceptions import ValidationErrorfrom django.db import IntegrityError, transactionfrom django.shortcuts import redirectfrom django.urls.base import reverse+from django.utils import timezoneimport structlogimport posthoganalytics@@ -34,6 +36,7 @@ from posthog.event_usage import alias_invite_id, report_user_joined_organizationfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.email_utils import EmailValidationHelper, validate_display_namefrom posthog.models import InviteExpiredException, Organization, OrganizationDomain, OrganizationInvite, Team, User+from posthog.models.organization_invite import INVITE_DAYS_VALIDITYfrom posthog.models.webauthn_credential import WebauthnCredentialfrom posthog.permissions import CanCreateOrgfrom posthog.rate_limit import SignupEmailPrecheckThrottle, SignupIPThrottle@@ -339,6 +342,25 @@ class SignupEmailPrecheckSerializer(serializers.Serializer):email: serializers.Field = serializers.EmailField()+class PendingInvitePayload(TypedDict):+ organization_name: str+++def _get_pending_invite_for_email(email: str) -> Optional[OrganizationInvite]:+ # Pre-filter in SQL to a generous validity window for efficiency, then defer to the+ # model's `is_expired` for the authoritative check so any future expansion of that+ # method (e.g. revocation flag) automatically applies here.+ invites = (+ OrganizationInvite.objects.filter(+ target_email__iexact=email,+ created_at__gt=timezone.now() - timedelta(days=INVITE_DAYS_VALIDITY),+ )+ .select_related("organization")+ .order_by("-created_at")+ )+ return next((i for i in invites if not i.is_expired()), None)++class SignupEmailPrecheckViewset(generics.GenericAPIView):serializer_class = SignupEmailPrecheckSerializerpermission_classes = (permissions.AllowAny,)@@ -358,7 +380,47 @@ class SignupEmailPrecheckViewset(generics.GenericAPIView):},status=status.HTTP_409_CONFLICT,)- return response.Response({"email_exists": False}, status=status.HTTP_200_OK)+ invite = _get_pending_invite_for_email(email)+ pending_invite: Optional[PendingInvitePayload] = None+ if invite is not None:+ # We deliberately do NOT return the invite UUID here. The signup form shows a+ # nudge banner, and the user has to round-trip through the invite email to+ # actually accept — preserving the pre-PR security property that only the+ # mailbox owner can consume the invite.+ pending_invite = {"organization_name": invite.organization.name}+ return response.Response(+ {"email_exists": False, "pending_invite": pending_invite},+ status=status.HTTP_200_OK,+ )+++class SignupResendInviteSerializer(serializers.Serializer):+ email: serializers.Field = serializers.EmailField()+++class SignupResendInviteViewset(generics.GenericAPIView):+ """Re-send the existing invite email for a given address, if one exists.++ Pairs with the precheck nudge banner: a user who landed on /signup with a pending invite+ can ask PostHog to re-deliver the original invite email. Returns the same shape whether+ or not an invite exists, but precheck has already disclosed the existence — this endpoint+ just makes the round-trip via email easier.+ """++ serializer_class = SignupResendInviteSerializer+ permission_classes = (permissions.AllowAny,)+ throttle_classes = [] if settings.E2E_TESTING else [SignupEmailPrecheckThrottle]++ def post(self, request: Request, *args: Any, **kwargs: Any) -> response.Response:+ serializer = self.get_serializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ email = serializer.validated_data["email"]+ invite = _get_pending_invite_for_email(email)+ if invite is not None and is_email_available():+ from posthog.tasks.email import send_invite++ send_invite.apply_async(kwargs={"invite_id": str(invite.id)})+ return response.Response({"sent": invite is not None}, status=status.HTTP_200_OK)class SignupViewset(generics.CreateAPIView):diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.pyindex 2ca65e865cc2..9313090dd16d 100644--- a/posthog/api/test/test_signup.py+++ b/posthog/api/test/test_signup.py@@ -16,6 +16,7 @@ from django.test import override_settingsfrom django.urls.base import reversefrom django.utils import timezone+from parameterized import parameterizedfrom rest_framework import statusfrom posthog.api.signup import _save_session_with_recovery, process_social_invite_signup@@ -25,7 +26,7 @@ from posthog.models import Organization, Team, Userfrom posthog.models.instance_setting import override_instance_configfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.organization_domain import OrganizationDomain-from posthog.models.organization_invite import OrganizationInvite+from posthog.models.organization_invite import INVITE_DAYS_VALIDITY, OrganizationInvitefrom posthog.models.webauthn_credential import WebauthnCredentialfrom posthog.utils import get_instance_realm@@ -2860,3 +2861,129 @@ class TestInviteSignupAPI(APIBaseTest):self.assertIsNone(session.get(WEBAUTHN_SIGNUP_CREDENTIAL_KEY))self.assertIsNone(session.get(WEBAUTHN_SIGNUP_EMAIL_KEY))self.assertIsNone(session.get(WEBAUTHN_SIGNUP_USER_UUID_KEY))+++class TestSignupPrecheckPendingInvite(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.client.logout()++ def _create_invite(self, email: str, *, days_old: int = 0) -> OrganizationInvite:+ invite = OrganizationInvite.objects.create(+ organization=self.organization,+ target_email=email,+ created_by=self.user,+ )+ if days_old:+ invite.created_at = timezone.now() - timedelta(days=days_old)+ invite.save(update_fields=["created_at"])+ return invite++ @parameterized.expand(+ [+ ("active_invite", "[email protected]", 0, "[email protected]", True),+ ("expired_invite", "[email protected]", INVITE_DAYS_VALIDITY + 5, "[email protected]", False),+ ("case_insensitive_match", "[email protected]", 0, "[email protected]", True),+ ("no_invite_for_email", "[email protected]", 0, "[email protected]", False),+ ]+ )+ def test_precheck_pending_invite_lookup(self, _name, invite_email, days_old, lookup_email, should_match):+ self._create_invite(invite_email, days_old=days_old)+ response = self.client.post("/api/signup/precheck", {"email": lookup_email})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ if should_match:+ self.assertEqual(+ response.json()["pending_invite"],+ {"organization_name": self.organization.name},+ )+ else:+ self.assertIsNone(response.json()["pending_invite"])++ def test_precheck_response_does_not_expose_invite_id_or_token(self):+ self._create_invite("[email protected]")+ response = self.client.post("/api/signup/precheck", {"email": "[email protected]"})+ payload = response.json()["pending_invite"]+ self.assertNotIn("id", payload)+ self.assertNotIn("token", payload)++ def test_precheck_skips_expired_invite_in_favor_of_older_valid_one(self):+ # `is_expired` is the authoritative check; if it returns True for the newest row, we+ # fall through to the next valid invite. With the current time-based implementation+ # the inversion is impossible to set up with real timestamps, so we mock `is_expired`+ # to simulate a future expiry signal (e.g. a revocation flag).+ self._create_invite("[email protected]", days_old=2)+ newer = self._create_invite("[email protected]")++ original_is_expired = OrganizationInvite.is_expired++ def fake_is_expired(self) -> bool:+ return self.id == newer.id++ with mock.patch.object(OrganizationInvite, "is_expired", fake_is_expired):+ response = self.client.post("/api/signup/precheck", {"email": "[email protected]"})++ # Sanity check: real method is restored.+ self.assertIs(OrganizationInvite.is_expired, original_is_expired)+ # Older valid invite is the one surfaced.+ self.assertEqual(+ response.json()["pending_invite"],+ {"organization_name": self.organization.name},+ )++ def test_precheck_does_not_return_pending_invite_when_account_exists(self):+ self._create_invite(self.user.email)+ response = self.client.post("/api/signup/precheck", {"email": self.user.email})+ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)+ self.assertNotIn("pending_invite", response.json())+++class TestSignupResendInvite(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.client.logout()++ def _create_invite(self, email: str, *, days_old: int = 0) -> OrganizationInvite:+ invite = OrganizationInvite.objects.create(+ organization=self.organization,+ target_email=email,+ created_by=self.user,+ )+ if days_old:+ invite.created_at = timezone.now() - timedelta(days=days_old)+ invite.save(update_fields=["created_at"])+ return invite++ @patch("posthog.api.signup.is_email_available", return_value=True)+ @patch("posthog.tasks.email.send_invite.apply_async")+ def test_resend_invite_dispatches_when_active_invite_exists(self, mock_send, _mock_email_available):+ invite = self._create_invite("[email protected]")+ response = self.client.post("/api/signup/resend-invite", {"email": "[email protected]"})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), {"sent": True})+ mock_send.assert_called_once_with(kwargs={"invite_id": str(invite.id)})++ @patch("posthog.api.signup.is_email_available", return_value=True)+ @patch("posthog.tasks.email.send_invite.apply_async")+ def test_resend_invite_no_op_when_no_active_invite(self, mock_send, _mock_email_available):+ response = self.client.post("/api/signup/resend-invite", {"email": "[email protected]"})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), {"sent": False})+ mock_send.assert_not_called()++ @patch("posthog.api.signup.is_email_available", return_value=True)+ @patch("posthog.tasks.email.send_invite.apply_async")+ def test_resend_invite_ignores_expired_invite(self, mock_send, _mock_email_available):+ self._create_invite("[email protected]", days_old=INVITE_DAYS_VALIDITY + 5)+ response = self.client.post("/api/signup/resend-invite", {"email": "[email protected]"})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), {"sent": False})+ mock_send.assert_not_called()++ @patch("posthog.api.signup.is_email_available", return_value=False)+ @patch("posthog.tasks.email.send_invite.apply_async")+ def test_resend_invite_skips_dispatch_when_email_disabled(self, mock_send, _mock_email_available):+ self._create_invite("[email protected]")+ response = self.client.post("/api/signup/resend-invite", {"email": "[email protected]"})+ # Status reflects that an invite exists, but no email goes out.+ self.assertEqual(response.json(), {"sent": True})+ mock_send.assert_not_called()diff --git a/posthog/urls.py b/posthog/urls.pyindex 4316a8ef52c5..7b258850c9ca 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -275,6 +275,7 @@ urlpatterns = [opt_slash_path("api/product_tours", product_tours),re_path(r"^external_surveys/(?P<survey_id>[^/]+)/?$", public_survey_page),opt_slash_path("api/signup/precheck", signup.SignupEmailPrecheckViewset.as_view()),+ opt_slash_path("api/signup/resend-invite", signup.SignupResendInviteViewset.as_view()),opt_slash_path("api/signup", signup.SignupViewset.as_view()),opt_slash_path("api/social_signup", signup.SocialSignupViewset.as_view()),path("api/signup/<str:invite_id>/", signup.InviteSignupViewset.as_view()),