     case invitation_res do
       %Invitation{} = invitation ->
         user = create_user(invitation)
-        if has_membership?(event, invitation, user) do
-          conn
-          |> put_flash(:error, "Already accepted the invitation.")
-          |> redirect(to: page_path(conn, :index))
+        if invitation_has_membership?(invitation, user) do
+          handle_error(conn, "Already accepted the invitation.")
         else
           membership = create_membership(invitation, user)
           invitation_changeset = Invitation.completion_changeset(invitation, %{

        conn
        |> put_flash(:info, "Invitation completed.")
        |> render("show.html", invitation: invitation)
      nil ->
        conn
        |> put_flash(:error, "Invalid invitation.")
        |> redirect(to: page_path(conn, :index))
    end
  end


    end
  end

  defp invitation_has_membership?(invitation, user) do
    membership_res =
      Membership
      |> Membership.for_event(invitation.event)
      |> Query.where(user_id: ^user.id)
      |> Query.where(role_id: ^invitation.role_id)
      |> Repo.one()
