-
Notifications
You must be signed in to change notification settings - Fork 0
fix(invites): consume invite tokens on signup #290
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
chiptus
wants to merge
6
commits into
main
Choose a base branch
from
claude/long-running-task-mman6l
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
848d48e
fix(invites): actually consume invite tokens so users join the group
claude 22f4a1e
fix(invites): address review findings on acceptance hook
claude 5704edb
refactor(invites): detect already-member by group_id, not message copy
claude 41f3ee5
refactor(invites): merge invite hooks into one useInviteFlow
claude c248e29
refactor(invites): keep invite query object instead of destructuring
claude 20c871a
refactor(invites): extract getError and merge validation toast effects
claude File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| import { useMutation, useQueryClient } from "@tanstack/react-query"; | ||
| import { supabase } from "@/integrations/supabase/client"; | ||
| import { groupsKeys } from "@/api/groups/types"; | ||
| import type { InviteUsageResult } from "@/types/invites"; | ||
|
|
||
| interface AcceptInviteParams { | ||
| token: string; | ||
| userId: string; | ||
| } | ||
|
|
||
| export interface AcceptInviteResult extends InviteUsageResult { | ||
| alreadyMember: boolean; | ||
| } | ||
|
|
||
| async function acceptInvite({ | ||
| token, | ||
| userId, | ||
| }: AcceptInviteParams): Promise<AcceptInviteResult> { | ||
| const { data, error } = await supabase.rpc("use_invite_token", { | ||
| token, | ||
| user_id: userId, | ||
| }); | ||
|
|
||
| if (error) { | ||
| console.error("Error using invite:", error); | ||
| throw new Error("Failed to join group"); | ||
| } | ||
|
|
||
| const result = data?.[0]; | ||
| if (!result) { | ||
| throw new Error("Failed to join group"); | ||
| } | ||
|
|
||
| if (result.success) { | ||
| return { ...result, alreadyMember: false }; | ||
| } | ||
|
|
||
| // Already-in-group is the only failure where the RPC returns a group_id | ||
| if (result.group_id) { | ||
| return { ...result, alreadyMember: true }; | ||
| } | ||
|
|
||
| throw new Error(result.message); | ||
| } | ||
|
|
||
| export function useAcceptInviteMutation() { | ||
| const queryClient = useQueryClient(); | ||
|
|
||
| return useMutation({ | ||
| mutationFn: acceptInvite, | ||
| onSuccess: (result) => { | ||
| if (!result.alreadyMember) { | ||
| queryClient.invalidateQueries({ queryKey: groupsKeys.all }); | ||
| } | ||
| }, | ||
| }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,240 @@ | ||
| import { describe, expect, it, vi, beforeEach } from "vitest"; | ||
| import { renderHook, waitFor } from "@testing-library/react"; | ||
| import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; | ||
| import type { ReactNode } from "react"; | ||
| import type { User } from "@supabase/supabase-js"; | ||
| import { useInviteFlow } from "./useInviteFlow"; | ||
| import { supabase } from "@/integrations/supabase/client"; | ||
| import type { InviteValidation } from "@/types/invites"; | ||
|
|
||
| const { navigateMock, toastMock } = vi.hoisted(() => ({ | ||
| navigateMock: vi.fn(), | ||
| toastMock: vi.fn(), | ||
| })); | ||
|
|
||
| vi.mock("@/integrations/supabase/client", () => ({ | ||
| supabase: { rpc: vi.fn() }, | ||
| })); | ||
|
|
||
| vi.mock("@tanstack/react-router", () => ({ | ||
| useNavigate: () => navigateMock, | ||
| })); | ||
|
|
||
| vi.mock("@/components/ui/use-toast", () => ({ | ||
| useToast: () => ({ toast: toastMock }), | ||
| })); | ||
|
|
||
| const rpcMock = vi.mocked(supabase.rpc); | ||
|
|
||
| const user = { id: "user-1" } as User; | ||
|
|
||
| const validInvite: InviteValidation = { | ||
| invite_id: "invite-row-id", | ||
| group_id: "group-1", | ||
| group_name: "Festival Crew", | ||
| is_valid: true, | ||
| reason: "valid", | ||
| }; | ||
|
|
||
| const joinedResult = { | ||
| success: true, | ||
| message: "Successfully joined group", | ||
| group_id: "group-1", | ||
| }; | ||
|
|
||
| function mockRpc( | ||
| validation: InviteValidation | null, | ||
| useResult: { success: boolean; message: string; group_id: string | null }, | ||
| ) { | ||
| rpcMock.mockImplementation((async (fn: string) => { | ||
| if (fn === "validate_invite_token") { | ||
| return { data: validation ? [validation] : [], error: null }; | ||
| } | ||
| return { data: [useResult], error: null }; | ||
| }) as never); | ||
| } | ||
|
|
||
| function useInviteTokenCalls() { | ||
| return rpcMock.mock.calls.filter(([fn]) => fn === "use_invite_token"); | ||
| } | ||
|
|
||
| function renderFlow(initialProps: { | ||
| token: string | undefined; | ||
| user: User | null; | ||
| }) { | ||
| const queryClient = new QueryClient({ | ||
| defaultOptions: { | ||
| queries: { retry: false }, | ||
| mutations: { retry: false }, | ||
| }, | ||
| }); | ||
| const invalidateSpy = vi.spyOn(queryClient, "invalidateQueries"); | ||
|
|
||
| const view = renderHook( | ||
| (props: { token: string | undefined; user: User | null }) => | ||
| useInviteFlow(props.token, props.user), | ||
| { | ||
| initialProps, | ||
| wrapper: function Wrapper({ children }: { children: ReactNode }) { | ||
| return ( | ||
| <QueryClientProvider client={queryClient}> | ||
| {children} | ||
| </QueryClientProvider> | ||
| ); | ||
| }, | ||
| }, | ||
| ); | ||
|
|
||
| return { ...view, invalidateSpy }; | ||
| } | ||
|
|
||
| describe("useInviteFlow", () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| it("validates the token then accepts the invite when a user is present", async () => { | ||
| mockRpc(validInvite, joinedResult); | ||
|
|
||
| const { result, invalidateSpy } = renderFlow({ token: "token-1", user }); | ||
|
|
||
| await waitFor(() => | ||
| expect(rpcMock).toHaveBeenCalledWith("validate_invite_token", { | ||
| token: "token-1", | ||
| }), | ||
| ); | ||
| await waitFor(() => | ||
| expect(rpcMock).toHaveBeenCalledWith("use_invite_token", { | ||
| token: "token-1", | ||
| user_id: "user-1", | ||
| }), | ||
| ); | ||
|
|
||
| await waitFor(() => | ||
| expect(toastMock).toHaveBeenCalledWith({ | ||
| title: "Success", | ||
| description: "Welcome to Festival Crew!", | ||
| }), | ||
| ); | ||
|
|
||
| expect(result.current.hasValidInvite).toBe(true); | ||
| expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ["groups"] }); | ||
| expect(navigateMock).toHaveBeenCalledWith({ | ||
| to: ".", | ||
| search: expect.any(Function), | ||
| replace: true, | ||
| }); | ||
|
|
||
| const searchUpdater = navigateMock.mock.calls[0][0].search; | ||
| expect(searchUpdater({ invite: "token-1", day: "friday" })).toEqual({ | ||
| invite: undefined, | ||
| day: "friday", | ||
| }); | ||
| }); | ||
|
|
||
| it("waits for the user to sign in before accepting", async () => { | ||
| mockRpc(validInvite, joinedResult); | ||
|
|
||
| const { result, rerender } = renderFlow({ token: "token-1", user: null }); | ||
|
|
||
| await waitFor(() => expect(result.current.hasValidInvite).toBe(true)); | ||
| expect(useInviteTokenCalls()).toHaveLength(0); | ||
|
|
||
| rerender({ token: "token-1", user }); | ||
|
|
||
| await waitFor(() => expect(useInviteTokenCalls()).toHaveLength(1)); | ||
| }); | ||
|
|
||
| it("shows the expired message and never consumes an invalid invite", async () => { | ||
| mockRpc( | ||
| { ...validInvite, is_valid: false, reason: "invite_expired" }, | ||
| joinedResult, | ||
| ); | ||
|
|
||
| const { result } = renderFlow({ token: "token-1", user }); | ||
|
|
||
| await waitFor(() => | ||
| expect(toastMock).toHaveBeenCalledWith({ | ||
| title: "Invalid Invite", | ||
| description: "This invite link has expired", | ||
| variant: "destructive", | ||
| }), | ||
| ); | ||
|
|
||
| expect(result.current.hasValidInvite).toBe(false); | ||
| expect(useInviteTokenCalls()).toHaveLength(0); | ||
| }); | ||
|
|
||
| it("surfaces an already-member reuse cleanly without an error", async () => { | ||
| mockRpc(validInvite, { | ||
| success: false, | ||
| message: "User already in group", | ||
| group_id: "group-1", | ||
| }); | ||
|
|
||
| const { invalidateSpy } = renderFlow({ token: "token-1", user }); | ||
|
|
||
| await waitFor(() => | ||
| expect(toastMock).toHaveBeenCalledWith({ | ||
| title: "Already a member", | ||
| description: "You're already a member of Festival Crew.", | ||
| }), | ||
| ); | ||
|
|
||
| expect(toastMock).not.toHaveBeenCalledWith( | ||
| expect.objectContaining({ variant: "destructive" }), | ||
| ); | ||
| expect(invalidateSpy).not.toHaveBeenCalledWith({ queryKey: ["groups"] }); | ||
| expect(navigateMock).toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("shows an error toast and keeps the invite param when acceptance fails", async () => { | ||
| mockRpc(validInvite, { | ||
| success: false, | ||
| message: "Invalid invite token", | ||
| group_id: null, | ||
| }); | ||
|
|
||
| renderFlow({ token: "token-1", user }); | ||
|
|
||
| await waitFor(() => | ||
| expect(toastMock).toHaveBeenCalledWith({ | ||
| title: "Couldn't join group", | ||
| description: "Invalid invite token", | ||
| variant: "destructive", | ||
| }), | ||
| ); | ||
|
|
||
| expect(navigateMock).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("allows a retry after a failed attempt", async () => { | ||
| mockRpc(validInvite, { | ||
| success: false, | ||
| message: "Invalid invite token", | ||
| group_id: null, | ||
| }); | ||
|
|
||
| const { rerender } = renderFlow({ token: "token-1", user }); | ||
|
|
||
| await waitFor(() => expect(useInviteTokenCalls()).toHaveLength(1)); | ||
|
|
||
| mockRpc(validInvite, joinedResult); | ||
| rerender({ token: "token-1", user: { ...user } }); | ||
|
|
||
| await waitFor(() => expect(useInviteTokenCalls()).toHaveLength(2)); | ||
| }); | ||
|
|
||
| it("only accepts once per token across re-renders", async () => { | ||
| mockRpc(validInvite, joinedResult); | ||
|
|
||
| const { rerender } = renderFlow({ token: "token-1", user }); | ||
|
|
||
| await waitFor(() => expect(useInviteTokenCalls()).toHaveLength(1)); | ||
|
|
||
| rerender({ token: "token-1", user }); | ||
|
|
||
| await Promise.resolve(); | ||
| expect(useInviteTokenCalls()).toHaveLength(1); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.