Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Onboarding: Add a team setup step (#6822)

RobertJoonas61a43114a5d7
diff --git a/e2e/tests/dashboard/team-setup.spec.ts b/e2e/tests/dashboard/team-setup.spec.ts
index de1b0459ce..74b4cbab07 100644
--- a/e2e/tests/dashboard/team-setup.spec.ts
+++ b/e2e/tests/dashboard/team-setup.spec.ts
@@ -1,6 +1,12 @@
-import { test, expect } from '@playwright/test'
-import { setupSite, subscribeToPlan } from '../fixtures'
-import { expectLiveViewConnected } from '../test-utils'
+import { test, expect, Page } from '@playwright/test'
+import {
+ login,
+ logout,
+ register,
+ setupSite,
+ subscribeToPlan
+} from '../fixtures'
+import { expectLiveViewConnected, randomID } from '../test-utils'
test('submitting team name via Enter key does not crash', async ({
page,
@@ -115,3 +121,80 @@ test('removing and re-adding a row', async ({ page, request }) => {
await expect(row2.locator('input[type="email"]')).toHaveValue('')
await expect(row2.getByTestId('role')).toHaveText('Viewer')
})
+
+function newUser() {
+ const userID = randomID()
+
+ return {
+ name: `User ${userID}`,
+ email: `email-${userID}@example.com`,
+ password: 'VeryStrongVerySecret'
+ }
+}
+
+async function createTeamInOnboarding(page: Page, teamName: string) {
+ await expect(page).toHaveURL(/\/team\/setup\?flow=register/)
+ await expectLiveViewConnected(page)
+
+ const nameInput = page.locator('input[name="team[name]"]')
+ await nameInput.clear()
+ await nameInput.fill(teamName)
+
+ await page.getByRole('button', { name: 'Create team' }).click()
+}
+
+async function expectCurrentTeamOnSitesPage(page: Page, teamName: string) {
+ await page.goto('/sites', { waitUntil: 'commit' })
+ await expectLiveViewConnected(page)
+
+ await expect(page.getByRole('heading', { level: 2 })).toHaveText(teamName)
+}
+
+test('team created during onboarding after adding a site stays the current team', async ({
+ page,
+ request
+}) => {
+ const user = newUser()
+ const teamName = `Onboarded team ${randomID()}`
+
+ await register({ page, request, user })
+
+ await page.getByLabel('Domain').fill(`${randomID()}.example.com`)
+ await page.getByRole('button', { name: 'Add site' }).click()
+
+ await createTeamInOnboarding(page, teamName)
+
+ await expect(page).toHaveURL(/\/installation\?flow=register&__team=/)
+
+ // without the `__team` param
+ await expectCurrentTeamOnSitesPage(page, teamName)
+
+ // with a fresh session
+ await logout(page)
+ await login({ page, user })
+ await expectCurrentTeamOnSitesPage(page, teamName)
+})
+
+test('team created during onboarding after skipping adding a site stays the current team', async ({
+ page,
+ request
+}) => {
+ const user = newUser()
+ const teamName = `Onboarded team ${randomID()}`
+
+ await register({ page, request, user })
+
+ await page.getByRole('link', { name: 'Skip' }).click()
+
+ await createTeamInOnboarding(page, teamName)
+
+ await expect(page).toHaveURL(/\/sites\?__team=/)
+
+ // without the `__team` param
+ await expectCurrentTeamOnSitesPage(page, teamName)
+
+ // with a fresh session
+ await logout(page)
+ await login({ page, user })
+ await expectCurrentTeamOnSitesPage(page, teamName)
+})
diff --git a/e2e/tests/fixtures.ts b/e2e/tests/fixtures.ts
index c195501ae0..271402f87c 100644
--- a/e2e/tests/fixtures.ts
+++ b/e2e/tests/fixtures.ts
@@ -126,7 +126,7 @@ export async function login({ page, user }: { page: Page; user: User }) {
await expect(page.getByRole('button', { name: 'Sign in' })).toBeVisible()
await page.getByLabel('Email').fill(user.email)
- await page.getByLabel('Password').fill(user.password)
+ await page.getByLabel('Password', { exact: true }).fill(user.password)
await page.getByRole('button', { name: 'Sign in' }).click()
await expect(page.getByRole('button', { name: user.name })).toBeVisible()
@@ -155,6 +155,10 @@ export async function addSite({
await page.getByRole('button', { name: 'Add site' }).click()
+ await expect(page).toHaveURL(/\/team\/setup/)
+
+ await page.getByRole('link', { name: 'Skip' }).click()
+
await expect(page).toHaveURL(/\/installation/)
await expect(
diff --git a/lib/plausible/teams.ex b/lib/plausible/teams.ex
index 6bd731c9cc..8c92454859 100644
--- a/lib/plausible/teams.ex
+++ b/lib/plausible/teams.ex
@@ -231,6 +231,42 @@ defmodule Plausible.Teams do
end
end
+ @doc """
+ Creates a new team owned by the given user and invites the given members.
+
+ Unlike `get_or_create/1`, this always creates a new team, regardless of
+ any other teams the user is already a member or an owner of. Those teams
+ are left untouched.
+ """
+ @spec create(Auth.User.t(), String.t(), [InviteToTeam.invite_entry()]) ::
+ {:ok, Teams.Team.t()} | {:error, any()}
+ def create(%Auth.User{} = user, name, invite_entries)
+ when is_binary(name) and is_list(invite_entries) do
+ with :ok <- check_user_type(user),
+ {:ok, {team, invitations}} <- do_create(user, name, invite_entries) do
+ InviteToTeam.send_invitation_emails(invitations)
+ {:ok, team}
+ end
+ end
+
+ defp do_create(user, name, invite_entries) do
+ Repo.transact(fn ->
+ with {:ok, team} <- insert_setup_team(name),
+ {:ok, _} <- Repo.insert(Teams.Membership.changeset(team, user, :owner)),
+ {:ok, invitations} <- InviteToTeam.invite_all(team, user, invite_entries) do
+ {:ok, {team, invitations}}
+ end
+ end)
+ end
+
+ defp insert_setup_team(name) do
+ %Teams.Team{}
+ |> Teams.Team.changeset(%{name: name})
+ |> Teams.Team.validate_not_reserved_name()
+ |> Teams.Team.setup_changeset()
+ |> Repo.insert()
+ end
+
@spec delete(Teams.Team.t()) :: {:ok, :deleted} | {:error, :active_subscription}
def delete(team) do
team = Teams.with_subscription(team)
diff --git a/lib/plausible/teams/team.ex b/lib/plausible/teams/team.ex
index 829c16a4c9..fdf2aa8fca 100644
--- a/lib/plausible/teams/team.ex
+++ b/lib/plausible/teams/team.ex
@@ -119,6 +119,35 @@ defmodule Plausible.Teams.Team do
def suggested_name(_user_name), do: @suggested_name_fallback
+ @doc """
+ Builds the team name suggested from a site domain, using the label right
+ before the public suffix, e.g. "shop.wannabuy.co.uk/blog" -> "Wannabuy".
+
+ Falls back to `suggested_name/1` when the domain doesn't yield a name-like
+ label or is invalid according to the rules of `valid_suggestion?/1`.
+ """
+ def suggested_name_from_domain(domain, user_name) when is_binary(domain) do
+ with [host | _] <- String.split(domain, "/", parts: 2),
+ registrable_domain when is_binary(registrable_domain) <-
+ PublicSuffix.registrable_domain(host),
+ [label | _] <- String.split(registrable_domain, "."),
+ true <- String.match?(label, ~r/\p{L}/u),
+ suggested = humanize_domain_label(label),
+ true <- String.length(suggested) <= @max_name_length and valid_suggestion?(suggested) do
+ suggested
+ else
+ _ -> suggested_name(user_name)
+ end
+ end
+
+ def suggested_name_from_domain(_domain, user_name), do: suggested_name(user_name)
+
+ defp humanize_domain_label(label) do
+ label
+ |> String.split(["-", "_"], trim: true)
+ |> Enum.map_join(" ", &String.capitalize/1)
+ end
+
defp valid_suggestion?(name) do
byte_size(name) <= @max_name_bytes and not contains_scheme?(name)
end
@@ -147,12 +176,14 @@ defmodule Plausible.Teams.Team do
end
def name_changeset(team, attrs \\ %{}) do
- changeset =
- team
- |> cast(attrs, [:name])
- |> validate_name()
- |> validate_required(:name)
+ team
+ |> cast(attrs, [:name])
+ |> validate_name()
+ |> validate_required(:name)
+ |> validate_not_reserved_name()
+ end
+ def validate_not_reserved_name(changeset) do
# Do not allow an actual team keep Plausible.Teams.default_name()
# as its name. This is just to avoid confusion in the UI and keep
# the auto-created team distinguishable from a real one.
diff --git a/lib/plausible_web/components/generic.ex b/lib/plausible_web/components/generic.ex
index c5ad9037fa..5dbfa77c74 100644
--- a/lib/plausible_web/components/generic.ex
+++ b/lib/plausible_web/components/generic.ex
@@ -1157,6 +1157,20 @@ defmodule PlausibleWeb.Components.Generic do
"""
end
+ attr :heading, :string, required: true
+ attr :subtitle, :string, required: true
+
+ def onboarding_page_heading(assigns) do
+ ~H"""
+ <div class="w-full max-w-md mx-auto mt-10 sm:mt-16 px-4 flex flex-col gap-y-2 dark:text-gray-300">
+ <h1 class="text-lg sm:text-xl font-semibold">{@heading}</h1>
+ <p class="text-base text-gray-500 dark:text-gray-400 text-pretty">
+ {@subtitle}
+ </p>
+ </div>
+ """
+ end
+
alias Phoenix.LiveView.JS
slot :inner_block, required: true
diff --git a/lib/plausible_web/components/site/new_site_form.ex b/lib/plausible_web/components/site/new_site_form.ex
index e304271f4a..a9096ff1a5 100644
--- a/lib/plausible_web/components/site/new_site_form.ex
+++ b/lib/plausible_web/components/site/new_site_form.ex
@@ -9,12 +9,15 @@ defmodule PlausibleWeb.Components.Site.NewSiteForm do
attr :site_limit, :integer, required: true
attr :current_user, :any, required: true
attr :current_team, :any, required: true
- attr :back_button_text, :string, required: true
- attr :back_button_href, :string, required: true
+ attr :secondary_action_text, :string, required: true
+ attr :secondary_action_href, :string, required: true
def new_site_form(assigns) do
~H"""
- <.heading_and_subtitle heading="Add a website" subtitle="Start measuring traffic on a new site." />
+ <.onboarding_page_heading
+ heading="Add a website"
+ subtitle="Start measuring traffic on a new site."
+ />
<div class="w-full max-w-md mx-auto mt-10 pb-16 px-4 dark:text-gray-300">
<.form :let={f} class="flex flex-col gap-y-8" for={@changeset} action={@form_submit_url}>
<PlausibleWeb.Components.Billing.Notice.limit_exceeded
@@ -46,8 +49,8 @@ defmodule PlausibleWeb.Components.Site.NewSiteForm do
</script>
<div class="flex justify-end items-center gap-x-2">
- <.button_link theme="ghost" href={@back_button_href}>
- {@back_button_text}
+ <.button_link theme="ghost" href={@secondary_action_href}>
+ {@secondary_action_text}
</.button_link>
<.button
disabled={@site_limit_exceeded?}
@@ -61,15 +64,4 @@ defmodule PlausibleWeb.Components.Site.NewSiteForm do
</div>
"""
end
-
- def heading_and_subtitle(assigns) do
- ~H"""
- <div class="w-full max-w-md mx-auto mt-10 sm:mt-16 px-4 flex flex-col gap-y-2 dark:text-gray-300">
- <h1 class="text-lg sm:text-xl font-semibold">{@heading}</h1>
- <p class="text-base text-gray-500 dark:text-gray-400 text-pretty">
- {@subtitle}
- </p>
- </div>
- """
- end
end
diff --git a/lib/plausible_web/controllers/auth_controller.ex b/lib/plausible_web/controllers/auth_controller.ex
index 6e613c7f57..f5753c29e6 100644
--- a/lib/plausible_web/controllers/auth_controller.ex
+++ b/lib/plausible_web/controllers/auth_controller.ex
@@ -107,7 +107,10 @@ defmodule PlausibleWeb.AuthController do
end
defp do_activate(conn, user, code) do
- has_any_invitations? = Plausible.Teams.Users.has_sites?(user, include_pending?: true)
+ has_any_invitations? =
+ Plausible.Teams.Users.has_sites?(user, include_pending?: true) or
+ Teams.Invitations.pending_team_invitations_for(user) != []
+
has_any_memberships? = Plausible.Teams.Users.has_sites?(user, include_pending?: false)
flow = conn.params["flow"]
@@ -301,7 +304,7 @@ defmodule PlausibleWeb.AuthController do
accept_team_invitation(conn, params["team_identifier"], user)
params["register_action"] == "register_form" ->
- ~p"/sites/new"
+ ~p"/sites/new?#{[flow: PlausibleWeb.Flows.register()]}"
true ->
params["return_to"]
diff --git a/lib/plausible_web/controllers/site_controller.ex b/lib/plausible_web/controllers/site_controller.ex
index 8c1e6bf365..3a866bc6a5 100644
--- a/lib/plausible_web/controllers/site_controller.ex
+++ b/lib/plausible_web/controllers/site_controller.ex
@@ -45,9 +45,7 @@ defmodule PlausibleWeb.SiteController do
|> Plausible.Mailer.send()
end
- redirect(conn,
- to: ~p"/#{site.domain}/installation?#{[flow: flow]}"
- )
+ redirect(conn, to: site_created_redirect_path(site, flow))
{:error, _, :permission_denied, _} ->
conn
@@ -68,6 +66,14 @@ defmodule PlausibleWeb.SiteController do
end
end
+ defp site_created_redirect_path(site, flow) do
+ if flow == PlausibleWeb.Flows.register() do
+ ~p"/team/setup?#{[flow: flow, domain: site.domain]}"
+ else
+ ~p"/#{site.domain}/installation?#{[flow: flow]}"
+ end
+ end
+
defp render_new_site_form(conn, flow, opts \\ []) do
defaults = [
changeset: Plausible.Site.changeset(%Plausible.Site{}),
diff --git a/lib/plausible_web/flows.ex b/lib/plausible_web/flows.ex
index 81c427bbdf..632e024d81 100644
--- a/lib/plausible_web/flows.ex
+++ b/lib/plausible_web/flows.ex
@@ -55,8 +55,9 @@ defmodule PlausibleWeb.Flows do
@doc """
The steps shown in the onboarding flow's progress indicator.
"""
- def onboarding_steps, do: [add_site_step(), installation_step()]
+ def onboarding_steps, do: [add_site_step(), team_setup_step(), installation_step()]
def add_site_step, do: "Add site info"
+ def team_setup_step, do: "Set up team"
def installation_step, do: "Install Plausible"
end
diff --git a/lib/plausible_web/live/installation.ex b/lib/plausible_web/live/installation.ex
index 2574980c0c..299b5acfbe 100644
--- a/lib/plausible_web/live/installation.ex
+++ b/lib/plausible_web/live/installation.ex
@@ -117,7 +117,7 @@ defmodule PlausibleWeb.Live.Installation do
~H"""
<.onboarding_or_app_layout {assigns}>
- <PlausibleWeb.Components.Site.NewSiteForm.heading_and_subtitle
+ <.onboarding_page_heading
heading={@heading}
subtitle={@subtitle}
/>
diff --git a/lib/plausible_web/live/team_setup.ex b/lib/plausible_web/live/team_setup.ex
index 2b327c5ac7..8d319a023b 100644
--- a/lib/plausible_web/live/team_setup.ex
+++ b/lib/plausible_web/live/team_setup.ex
@@ -8,30 +8,38 @@ defmodule PlausibleWeb.Live.TeamSetup do
import PlausibleWeb.Live.Components.Team, only: [role_select_input: 1]
alias Plausible.Teams
+ alias PlausibleWeb.{Flows, Layouts}
+
+ def mount(params, _session, socket) do
+ team = socket.assigns.current_team
+ onboarding? = params["flow"] == Flows.register()
+ domain = accessible_domain(socket.assigns.current_user, params["domain"])
- def mount(_params, _session, socket) do
socket =
- case socket.assigns.current_team do
- %Teams.Team{setup_complete: true} ->
+ cond do
+ Teams.setup?(team) and onboarding? ->
+ redirect(socket, to: onboarding_next_step_path(domain))
+
+ Teams.setup?(team) ->
socket
|> put_flash(:success, "Your team has already been created")
|> redirect(to: ~p"/settings/team/general")
- %Teams.Team{} = team ->
- suggested_name = Teams.Team.suggested_name(socket.assigns.current_user.name)
- name_changeset = Teams.Team.name_changeset(team, %{name: suggested_name})
+ true ->
+ suggested_name =
+ Teams.Team.suggested_name_from_domain(domain, socket.assigns.current_user.name)
+
+ name_changeset =
+ Teams.Team.name_changeset(team || %Teams.Team{}, %{name: suggested_name})
assign(socket,
- current_team: team,
+ team: team,
+ onboarding?: onboarding?,
+ domain: domain,
team_name_form: to_form(name_changeset),
- locked?: Plausible.Teams.Billing.solo?(team),
+ locked?: not is_nil(team) and Plausible.Teams.Billing.solo?(team),
max_new_members: max_new_members(team)
)
-
- _ ->
- socket
- |> put_flash(:error, "You cannot create any team just yet")
- |> redirect(to: ~p"/sites")
end
{:ok, socket}
@@ -39,25 +47,47 @@ defmodule PlausibleWeb.Live.TeamSetup do
def render(assigns) do
~H"""
- <.focus_box padding?={false}>
- <:title>
- <div class="pt-8 px-8 flex justify-between">
- <div>Create a new team</div>
- <div class="ml-auto">
- <.docs_info slug="users-roles" />
- </div>
- </div>
- </:title>
- <:subtitle>
- <p class="px-8">
- Name your team and optionally invite members by email. When ready, click "Create team"
- </p>
- </:subtitle>
-
- <div class="relative -mt-8 pt-4 pb-8 px-8">
+ <.onboarding_or_app_layout {assigns}>
+ <.team_setup_form {assigns} />
+ </.onboarding_or_app_layout>
+ """
+ end
+
+ defp onboarding_or_app_layout(assigns) do
+ if assigns.onboarding? do
+ ~H"""
+ <Layouts.onboarding current_step={Flows.team_setup_step()} current_user={@current_user}>
+ {render_slot(@inner_block)}
+ </Layouts.onboarding>
+ """
+ else
+ ~H"""
+ <Layouts.app
+ footer?={false}
+ global_notices?={false}
+ current_user={@current_user}
+ current_team={@current_team}
+ current_team_role={@current_team_role}
+ teams={@teams}
+ my_team={@my_team}
+ >
+ {render_slot(@inner_block)}
+ </Layouts.app>
+ """
+ end
+ end
+
+ defp team_setup_form(assigns) do
+ ~H"""
+ <.onboarding_page_heading
+ heading="Create a team"
+ subtitle="Name your team and optionally invite members by email."
+ />
+ <div class="w-full max-w-md mx-auto mt-10 pb-16 px-4 dark:text-gray-300">
+ <div class="relative">
<PlausibleWeb.Components.Billing.feature_gate
current_user={@current_user}
- current_team={@current_team}
+ current_team={@team}
locked?={@locked?}
>
<.flash_messages flash={@flash} />
@@ -67,7 +97,6 @@ defmodule PlausibleWeb.Live.TeamSetup do
for={@team_name_form}
id="create-team-form"
phx-submit="create-team"
- class="mt-6"
>
<.input
type="text"
@@ -101,13 +130,28 @@ defmodule PlausibleWeb.Live.TeamSetup do
</button>
</div>
- <.button id="create-team-submit" type="submit" class="mt-8 w-full">
- Create team
- </.button>
+ <div class="mt-8 flex justify-end items-center gap-x-2">
+ <%= if @onboarding? do %>
+ <.button_link
+ id="create-team-skip"
+ theme="ghost"
+ href={onboarding_next_step_path(@domain)}
+ >
+ Skip
+ </.button_link>
+ <% else %>
+ <.button_link id="create-team-cancel" theme="ghost" href={~p"/sites"}>
+ Cancel
+ </.button_link>
+ <% end %>
+ <.button id="create-team-submit" type="submit">
+ Create team
+ </.button>
+ </div>
</.form>
</PlausibleWeb.Components.Billing.feature_gate>
</div>
- </.focus_box>
+ </div>
"""
end
@@ -171,19 +215,25 @@ defmodule PlausibleWeb.Live.TeamSetup do
end
defp setup_team(socket, name, entries) do
- case Teams.setup(
- socket.assigns.current_team,
- name,
- entries,
- socket.assigns.current_user
- ) do
- {:ok, _} ->
+ user = socket.assigns.current_user
+
+ result =
+ case socket.assigns.team do
+ nil -> Teams.create(user, name, entries)
+ team -> Teams.setup(team, name, entries, user)
+ end
+
+ case result do
+ {:ok, team} ->
+ redirect_path =
+ success_redirect_path(socket.assigns.onboarding?, socket.assigns.domain,
+ __team: team.identifier
+ )
+
{:noreply,
socket
|> put_flash(:success, "Your team is now created")
- |> redirect(
- to: ~p"/settings/team/general?#{[__team: socket.assigns.current_team.identifier]}"
- )}
+ |> redirect(to: redirect_path)}
{:error, %Ecto.Changeset{data: %Teams.Team{}} = changeset} ->
{:noreply, assign(socket, team_name_form: to_form(changeset))}
@@ -215,24 +265,37 @@ defmodule PlausibleWeb.Live.TeamSetup do
end
end
+ defp accessible_domain(user, domain) when is_binary(domain) do
+ case Plausible.Sites.get_for_user(user, domain) do
+ %Plausible.Site{} = site -> site.domain
+ nil -> nil
+ end
+ end
+
+ defp accessible_domain(_user, _domain), do: nil
+
+ defp success_redirect_path(onboarding?, domain, params) do
+ if onboarding? do
+ onboarding_next_step_path(domain, params)
+ else
+ ~p"/settings/team/general?#{params}"
+ end
+ end
+
+ defp onboarding_next_step_path(domain, params \\ []) do
+ if is_nil(domain) do
+ ~p"/sites?#{params}"
+ else
+ ~p"/#{domain}/installation?#{[flow: Flows.register()] ++ params}"
+ end
+ end
+
@max_rows_when_unlimited 20
- # Defines the upper bound for how many email+role input rows the UI
+ # The upper bound for how many email+role input rows the UI
# should render at most, in order to prevent the user getting a
# "team member limit exceeded" error upon submit without any prior
# indication about it.
-
- # Since team setup is the very first creation of a team, we can safely
- # assume that there are no existing memberships/invitations, and that
- # max rows is equivalent to the team member limit.
-
- # There's one exception though: guest memberships/invitations (accounts
- # invited to individual sites of a team with `setup_complete: false`)
- # *can* exist, but we're deliberately ignoring those here. While such
- # teams might hit the team member limit error upon submit, we still
- # shouldn't prevent them from adding as many rows as the team member
- # limit because inviting an email that's already a guest won't count
- # "double" towards the team member limit.
defp max_new_members(team) do
case Teams.Billing.team_member_limit(team) do
:unlimited -> @max_rows_when_unlimited
diff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.ex
index fcee0cc3d1..7ce3519af9 100644
--- a/lib/plausible_web/router.ex
+++ b/lib/plausible_web/router.ex
@@ -624,7 +624,12 @@ defmodule PlausibleWeb.Router do
pipe_through [:app_layout, PlausibleWeb.RequireAccountPlug]
live "/sites", Sites, :index, as: :site
- live "/team/setup", TeamSetup, :setup, as: :team_setup
+
+ scope assigns: %{legacy_layout?: false, bg_class: "bg-white dark:bg-gray-950"} do
+ live "/team/setup", TeamSetup, :setup,
+ as: :team_setup,
+ container: {:div, class: "h-full"}
+ end
end
get "/sites/new", SiteController, :new
diff --git a/lib/plausible_web/templates/email/create_site_email.html.heex b/lib/plausible_web/templates/email/create_site_email.html.heex
index b87b760f69..b196456a9f 100644
--- a/lib/plausible_web/templates/email/create_site_email.html.heex
+++ b/lib/plausible_web/templates/email/create_site_email.html.heex
@@ -1,6 +1,8 @@
You’ve created your Plausible account but haven’t added a site yet.<br /><br />
Adding your first site only takes a minute and gets you from signup to seeing real traffic.<br /><br />
-<a href={"#{plausible_url()}/sites/new"}>Add your first site</a>
+<a href={"#{plausible_url()}/sites/new?flow=#{PlausibleWeb.Flows.register()}"}>
+ Add your first site
+</a>
<br /><br />
If you need help getting started, our documentation walks you through the setup step by step:<br />
<a href="https://plausible.io/docs">https://plausible.io/docs</a>
diff --git a/lib/plausible_web/templates/site/onboarding_new_site.html.heex b/lib/plausible_web/templates/site/onboarding_new_site.html.heex
index c5a2bf95d6..d319dcd0f9 100644
--- a/lib/plausible_web/templates/site/onboarding_new_site.html.heex
+++ b/lib/plausible_web/templates/site/onboarding_new_site.html.heex
@@ -10,7 +10,7 @@
site_limit={@site_limit}
current_user={@current_user}
current_team={@current_team}
- back_button_text="Skip"
- back_button_href={~p"/sites"}
+ secondary_action_text="Skip"
+ secondary_action_href={~p"/team/setup?#{[flow: PlausibleWeb.Flows.register()]}"}
/>
</Layouts.onboarding>
diff --git a/lib/plausible_web/templates/site/provisioning_new_site.html.heex b/lib/plausible_web/templates/site/provisioning_new_site.html.heex
index 8721eaf3ce..742d1d3a21 100644
--- a/lib/plausible_web/templates/site/provisioning_new_site.html.heex
+++ b/lib/plausible_web/templates/site/provisioning_new_site.html.heex
@@ -15,7 +15,7 @@
site_limit={@site_limit}
current_user={@current_user}
current_team={@current_team}
- back_button_text="Back to sites"
- back_button_href={~p"/sites"}
+ secondary_action_text="Back to sites"
+ secondary_action_href={~p"/sites"}
/>
</Layouts.app>
diff --git a/test/plausible/teams/team_test.exs b/test/plausible/teams/team_test.exs
index 47f1b67188..d5869348b6 100644
--- a/test/plausible/teams/team_test.exs
+++ b/test/plausible/teams/team_test.exs
@@ -187,4 +187,44 @@ defmodule Plausible.Teams.TeamTest do
end
end
end
+
+ describe "suggested_name_from_domain/2" do
+ test "uses the label right before the public suffix" do
+ for {domain, expected} <- [
+ {"delfi.ee", "Delfi"},
+ {"subdomain.example.com", "Example"},
+ {"shop.bbc.co.uk", "Bbc"},
+ {"пример.рф", "Пример"}
+ ] do
+ assert Team.suggested_name_from_domain(domain, "Jane") == expected
+ end
+ end
+
+ test "ignores the path" do
+ assert Team.suggested_name_from_domain("mysite.com/mypage", "Jane") == "Mysite"
+ assert Team.suggested_name_from_domain("sub.mysite.com/mypage", "Jane") == "Mysite"
+ end
+
+ test "uses the subdomain of a hosting platform" do
+ assert Team.suggested_name_from_domain("foo.github.io", "Jane") == "Foo"
+ assert Team.suggested_name_from_domain("myapp.vercel.app", "Jane") == "Myapp"
+ end
+
+ test "turns dashes and underscores into capitalized words" do
+ assert Team.suggested_name_from_domain("my-cool_site.com", "Jane") == "My Cool Site"
+ end
+
+ test "falls back to the user name when the domain doesn't yield a name-like label" do
+ for domain <- ["lol", "localhost", "127.0.0.1", "0.1.1", "123.com", "_.com", "", nil] do
+ assert Team.suggested_name_from_domain(domain, "Jane") == "Jane's team",
+ "expected #{inspect(domain)} to fall back"
+ end
+ end
+
+ test "falls back to the user name when the label is too long for a team name" do
+ domain = String.duplicate("a", 51) <> ".com"
+
+ assert Team.suggested_name_from_domain(domain, "Jane") == "Jane's team"
+ end
+ end
end
diff --git a/test/plausible/teams_test.exs b/test/plausible/teams_test.exs
index eef38245fa..1f6966e825 100644
--- a/test/plausible/teams_test.exs
+++ b/test/plausible/teams_test.exs
@@ -136,6 +136,23 @@ defmodule Plausible.TeamsTest do
|> Map.fetch!(:team_memberships)
end
+ test "creates 'My personal sites' if user only owns a setup team" do
+ user = new_user()
+ _site = new_site(owner: user)
+ setup_team = user |> team_of() |> Teams.complete_setup()
+
+ assert {:ok, team} = Teams.get_or_create(user)
+
+ assert team.id != setup_team.id
+ assert team.name == "My personal sites"
+ refute team.setup_complete
+
+ assert [team_membership] = Repo.preload(team, :team_memberships).team_memberships
+ assert team_membership.user_id == user.id
+ assert team_membership.role == :owner
+ assert team_membership.is_autocreated == true
+ end
+
test "returns existing owned team if user is also a non-owner member on existing teams" do
user = new_user()
_site = new_site(owner: user)
@@ -471,6 +488,106 @@ defmodule Plausible.TeamsTest do
end
end
+ describe "create/3" do
+ @subject_prefix if ee?(), do: "[Plausible Analytics] ", else: "[Plausible CE] "
+
+ test "creates a set up team owned by the user and invites members" do
+ today = Date.utc_today()
+ user = new_user()
+
+ assert {:ok, team} =
+ Teams.create(user, "New Team", [%{email: "[email protected]", role: :editor}])
+
+ assert team.name == "New Team"
+ assert team.setup_complete
+ assert team.setup_at
+ assert team.identifier
+ assert Date.compare(team.trial_expiry_date, today) == :gt
+
+ assert [team_membership] = Repo.preload(team, :team_memberships).team_memberships
+ assert team_membership.user_id == user.id
+ assert team_membership.role == :owner
+ assert team_membership.is_autocreated == false
+
+ assert [invitation] = Teams.Invitations.pending_team_invitations_for(team)
+ assert invitation.email == "[email protected]"
+ assert invitation.role == :editor
+
+ assert_email_delivered_with(
+ to: [nil: "[email protected]"],
+ subject: @subject_prefix <> "You've been invited to \"New Team\" team"
+ )
+ end
+
+ test "creates a team without any invitations" do
+ user = new_user()
+
+ assert {:ok, team} = Teams.create(user, "New Team", [])
+
+ assert team.setup_complete
+ assert [] = Teams.Invitations.pending_team_invitations_for(team)
+ assert_no_emails_delivered()
+ end
+
+ test "leaves the user's existing personal team untouched" do
+ user = new_user()
+ _site = new_site(owner: user)
+ personal_team = team_of(user)
+
+ assert {:ok, team} = Teams.create(user, "New Team", [])
+ assert team.id != personal_team.id
+
+ personal_team = Repo.reload!(personal_team)
+ assert personal_team.name == Teams.default_name()
+ refute personal_team.setup_complete
+
+ assert [team_membership] = Repo.preload(personal_team, :team_memberships).team_memberships
+ assert team_membership.user_id == user.id
+ assert team_membership.role == :owner
+ assert team_membership.is_autocreated == true
+
+ assert {:ok, %{id: personal_team_id}} = Teams.get_or_create(user)
+ assert personal_team_id == personal_team.id
+ end
+
+ test "rolls back team creation when an invitation fails" do
+ user = new_user()
+
+ assert {:error, :already_a_member} =
+ Teams.create(user, "New Team", [
+ %{email: "[email protected]", role: :editor},
+ %{email: user.email, role: :viewer}
+ ])
+
+ assert {:error, :no_team} = Teams.get_by_owner(user)
+ assert_no_emails_delivered()
+ end
+
+ test "returns a name changeset error without creating a team" do
+ user = new_user()
+
+ assert {:error, %Ecto.Changeset{data: %Teams.Team{}} = changeset} =
+ Teams.create(user, Teams.default_name(), [
+ %{email: "[email protected]", role: :editor}
+ ])
+
+ assert [name: {"is reserved", _}] = changeset.errors
+
+ assert {:error, :no_team} = Teams.get_by_owner(user)
+ assert_no_emails_delivered()
+ end
+ end
+
+ on_ee do
+ describe "create/3 - SSO user" do
+ setup [:create_user, :create_team, :setup_sso, :provision_sso_user]
+
+ test "does not allow creating a team to SSO user", %{user: user} do
+ assert {:error, :permission_denied} = Teams.create(user, "New Team", [])
+ end
+ end
+ end
+
describe "delete/1" do
test "deletes a team" do
user = new_user()
diff --git a/test/plausible_web/controllers/auth_controller_test.exs b/test/plausible_web/controllers/auth_controller_test.exs
index 778f7235f8..cb917a0183 100644
--- a/test/plausible_web/controllers/auth_controller_test.exs
+++ b/test/plausible_web/controllers/auth_controller_test.exs
@@ -85,7 +85,7 @@ defmodule PlausibleWeb.AuthControllerTest do
assert redirected_to(conn, 302) == "/activate?flow=register&team_identifier="
end
- test "logs the user in", %{conn: conn} do
+ test "logs the user in and redirects to onboarding", %{conn: conn} do
user =
Repo.insert!(
User.new(%{
@@ -94,6 +94,7 @@ defmodule PlausibleWeb.AuthControllerTest do
password: "very-secret-and-very-long-123",
password_confirmation: "very-secret-and-very-long-123"
})
+ |> Ecto.Changeset.put_change(:email_verified, true)
)
conn =
@@ -107,6 +108,7 @@ defmodule PlausibleWeb.AuthControllerTest do
assert %{sessions: [%{token: token}]} = user |> Repo.reload!() |> Repo.preload(:sessions)
assert get_session(conn, :user_token) == token
+ assert redirected_to(conn, 302) == "/sites/new?flow=register"
end
end
@@ -418,7 +420,7 @@ defmodule PlausibleWeb.AuthControllerTest do
assert redirected_to(conn) == "/sites/new?flow="
end
- test "redirects to /sites if user has invitation", %{conn: conn, user: user} do
+ test "redirects to /sites if user has a guest invitation", %{conn: conn, user: user} do
owner = new_user()
site = new_site(owner: owner)
invite_guest(site, user, role: :viewer, inviter: owner)
@@ -434,6 +436,23 @@ defmodule PlausibleWeb.AuthControllerTest do
assert redirected_to(conn) == "/sites?flow="
end
+ test "redirects to /sites if user has team invitation to a team without sites", %{
+ conn: conn,
+ user: user
+ } do
+ owner = new_user()
+ {:ok, team} = Plausible.Teams.create(owner, "Team without sites", [])
+ invite_member(team, user, role: :viewer, inviter: owner)
+
+ Repo.update!(Auth.User.changeset(user, %{email_verified: false}))
+
+ {:ok, %{code: code}} = Auth.EmailVerification.issue_code(user)
+
+ conn = post(conn, "/activate", %{code: code, team_identifier: ""})
+
+ assert redirected_to(conn) == "/sites?flow="
+ end
+
test "accepts team invite and redirects to team sites, if team provided", %{
conn: conn,
user: user
diff --git a/test/plausible_web/controllers/site_controller_test.exs b/test/plausible_web/controllers/site_controller_test.exs
index d84796e824..5b3ee9bad9 100644
--- a/test/plausible_web/controllers/site_controller_test.exs
+++ b/test/plausible_web/controllers/site_controller_test.exs
@@ -45,6 +45,12 @@ defmodule PlausibleWeb.SiteControllerTest do
refute html_response(conn, 200) =~ ~s(id="flow-progress")
end
+ test "skip link continues to the team setup onboarding step", %{conn: conn} do
+ conn = get(conn, "/sites/new?flow=register")
+
+ assert html_response(conn, 200) =~ ~s(href="/team/setup?flow=register")
+ end
+
test "does not display limit notice when user is on an enterprise plan", %{
conn: conn,
user: user
@@ -360,6 +366,30 @@ defmodule PlausibleWeb.SiteControllerTest do
describe "POST /sites" do
setup [:create_user, :log_in]
+ test "continues to the team setup step in the onboarding flow", %{conn: conn} do
+ conn =
+ post(conn, "/sites?flow=register", %{
+ "site" => %{
+ "domain" => "example.com",
+ "timezone" => "Europe/London"
+ }
+ })
+
+ assert redirected_to(conn) == "/team/setup?flow=register&domain=example.com"
+ end
+
+ test "continues to the installation step in the provisioning flow", %{conn: conn} do
+ conn =
+ post(conn, "/sites?flow=provisioning", %{
+ "site" => %{
+ "domain" => "example.com",
+ "timezone" => "Europe/London"
+ }
+ })
+
+ assert redirected_to(conn) == "/example.com/installation?flow=provisioning"
+ end
+
test "creates the site with valid params", %{conn: conn} do
conn =
post(conn, "/sites", %{
diff --git a/test/plausible_web/email_test.exs b/test/plausible_web/email_test.exs
index 2719afa03f..6fa088b9f8 100644
--- a/test/plausible_web/email_test.exs
+++ b/test/plausible_web/email_test.exs
@@ -542,6 +542,8 @@ defmodule PlausibleWeb.EmailTest do
assert email.html_body =~
"You’ve created your Plausible account but haven’t added a site yet."
+
+ assert email.html_body =~ "/sites/new?flow=register"
end
test "site setup help email", %{user: user, site: site} do
diff --git a/test/plausible_web/live/team_setup_test.exs b/test/plausible_web/live/team_setup_test.exs
index b7eafbc87c..9898328997 100644
--- a/test/plausible_web/live/team_setup_test.exs
+++ b/test/plausible_web/live/team_setup_test.exs
@@ -10,19 +10,200 @@ defmodule PlausibleWeb.Live.TeamSetupTest do
@url "/team/setup"
@subject_prefix if ee?(), do: "[Plausible Analytics] ", else: "[Plausible CE] "
- describe "/team/setup - edge cases" do
+ describe "/team/setup" do
setup [:create_user, :log_in]
- test "redirects if there's no implicit team created", %{conn: conn} do
- assert {:error, {:redirect, %{to: "/sites"}}} = live(conn, @url)
- end
-
test "redirects to /team/general if team is already set up", %{conn: conn, user: user} do
{:ok, team} = Teams.get_or_create(user)
Teams.complete_setup(team)
conn = set_current_team(conn, team)
assert {:error, {:redirect, %{to: "/settings/team/general"}}} = live(conn, @url)
end
+
+ test "renders a cancel link back to /sites", %{conn: conn} do
+ {:ok, _lv, html} = live(conn, @url)
+
+ assert text_of_element(html, "#create-team-cancel") == "Cancel"
+ assert text_of_attr(html, "#create-team-cancel", "href") == "/sites"
+ end
+
+ test "does not render the onboarding progress", %{conn: conn} do
+ {:ok, _lv, html} = live(conn, @url)
+
+ refute element_exists?(html, "#flow-progress")
+ end
+ end
+
+ describe "/team/setup?flow=register - after adding a site" do
+ setup [:create_user, :log_in, :create_site]
+
+ test "renders the team setup step of the onboarding progress", %{conn: conn, site: site} do
+ {:ok, _lv, html} = live(conn, onboarding_url(site.domain))
+
+ assert text_of_attr(html, ~s|#flow-progress [aria-current="step"]|, "aria-label") ==
+ "Set up team"
+ end
+
+ test "suggests a team name based on the site domain", %{conn: conn, user: user} do
+ site = new_site(owner: user, domain: "shop.my-company.co.uk")
+
+ {:ok, _lv, html} = live(conn, onboarding_url(site.domain))
+
+ assert text_of_attr(html, ~s|input#create-team-form_name[name="team[name]"]|, "value") ==
+ "My Company"
+ end
+
+ test "renders a skip link to the installation step", %{conn: conn, site: site} do
+ {:ok, _lv, html} = live(conn, onboarding_url(site.domain))
+
+ assert text_of_element(html, "#create-team-skip") == "Skip"
+
+ assert text_of_attr(html, "#create-team-skip", "href") ==
+ ~p"/#{site.domain}/installation?flow=register"
+ end
+
+ test "turns the personal team into a real team and continues to installation", %{
+ conn: conn,
+ site: site
+ } do
+ {:ok, lv, _html} = live(conn, onboarding_url(site.domain))
+
+ finish_setup(lv, name: "Onboarded Team")
+
+ assert_redirect(
+ lv,
+ ~p"/#{site.domain}/installation?flow=register&__team=#{site.team.identifier}"
+ )
+
+ team = Repo.reload!(site.team)
+ assert team.setup_complete
+ assert team.name == "Onboarded Team"
+ end
+
+ test "skips ahead to installation if the team is already set up", %{
+ conn: conn,
+ site: site
+ } do
+ team = Teams.complete_setup(site.team)
+ conn = set_current_team(conn, team)
+ expected_path = ~p"/#{site.domain}/installation?flow=register"
+
+ assert {:error, {:redirect, %{to: ^expected_path}}} =
+ live(conn, onboarding_url(site.domain))
+ end
+
+ test "ignores the domain of a site the user can't access", %{conn: conn} do
+ other_site = new_site(domain: "other-company.com")
+
+ {:ok, _lv, html} = live(conn, onboarding_url(other_site.domain))
+
+ assert text_of_attr(html, "#create-team-skip", "href") == "/sites"
+
+ assert text_of_attr(html, ~s|input#create-team-form_name[name="team[name]"]|, "value") ==
+ "Jane Smith's team"
+ end
+
+ test "ignores the domain of a non-existent site when skipping ahead", %{
+ conn: conn,
+ site: site
+ } do
+ team = Teams.complete_setup(site.team)
+ conn = set_current_team(conn, team)
+
+ assert {:error, {:redirect, %{to: "/sites"}}} =
+ live(conn, onboarding_url("evil.example.com"))
+ end
+ end
+
+ describe "/team/setup?flow=register - after skipping adding a site" do
+ setup [:create_user, :log_in]
+
+ test "suggests a team name based on the user name", %{conn: conn} do
+ {:ok, _lv, html} = live(conn, onboarding_url())
+
+ assert text_of_attr(html, ~s|input#create-team-form_name[name="team[name]"]|, "value") ==
+ "Jane Smith's team"
+ end
+
+ test "renders a skip link to /sites", %{conn: conn} do
+ {:ok, _lv, html} = live(conn, onboarding_url())
+
+ assert text_of_element(html, "#create-team-skip") == "Skip"
+ assert text_of_attr(html, "#create-team-skip", "href") == "/sites"
+ end
+
+ test "creates a team from scratch and continues to /sites", %{conn: conn, user: user} do
+ {:ok, lv, _html} = live(conn, onboarding_url())
+
+ finish_setup(lv, name: "Onboarded Team")
+
+ assert {:ok, team} = Teams.get_by_owner(user)
+ assert team.setup_complete
+ assert team.name == "Onboarded Team"
+
+ assert_redirect(lv, "/sites?__team=" <> team.identifier)
+ end
+
+ test "skips ahead to /sites if the team is already set up", %{conn: conn, user: user} do
+ {:ok, team} = Teams.create(user, "Onboarded Team", [])
+ conn = set_current_team(conn, team)
+
+ assert {:error, {:redirect, %{to: "/sites"}}} = live(conn, onboarding_url())
+ end
+ end
+
+ describe "/team/setup - without any existing team" do
+ setup [:create_user, :log_in]
+
+ test "renders the form with a suggested name", %{conn: conn} do
+ {:ok, _lv, html} = live(conn, @url)
+
+ assert text_of_attr(html, ~s|input#create-team-form_name[name="team[name]"]|, "value") ==
+ "Jane Smith's team"
+
+ assert element_exists?(html, "#create-team-submit")
+ refute element_exists?(html, "#feature-gate-overlay")
+ end
+
+ test "creates a new team from scratch and invites members", %{conn: conn, user: user} do
+ {:ok, lv, _html} = live(conn, @url)
+
+ finish_setup(lv,
+ name: "Brand New Team",
+ rows: %{"1" => %{"email" => "[email protected]", "role" => "editor"}}
+ )
+
+ assert {:ok, team} = Teams.get_by_owner(user)
+ assert team.name == "Brand New Team"
+ assert team.setup_complete
+
+ assert_redirect(lv, "/settings/team/general?__team=" <> team.identifier)
+
+ assert_email_delivered_with(
+ to: [nil: "[email protected]"],
+ subject: @subject_prefix <> "You've been invited to \"Brand New Team\" team"
+ )
+
+ assert [invitation] = Teams.Invitations.pending_team_invitations_for(team)
+ assert invitation.email == "[email protected]"
+ assert invitation.role == :editor
+ end
+
+ test "does not create a team when an invitation is rejected", %{conn: conn, user: user} do
+ {:ok, lv, _html} = live(conn, @url)
+
+ assert finish_setup(lv, rows: %{"1" => %{"email" => user.email, "role" => "viewer"}}) =~
+ "You cannot invite yourself"
+
+ assert {:error, :no_team} = Teams.get_by_owner(user)
+ end
+
+ @tag :ee_only
+ test "defaults the member rows to the trial team member limit", %{conn: conn} do
+ {:ok, _lv, html} = live(conn, @url)
+
+ assert elem_count(html, row_el()) == 10
+ end
end
describe "/team/setup - suggested team name" do
@@ -326,6 +507,9 @@ defmodule PlausibleWeb.Live.TeamSetupTest do
end
end
+ defp onboarding_url(), do: @url <> "?flow=register"
+ defp onboarding_url(domain), do: @url <> "?flow=register&domain=" <> domain
+
defp row_el(), do: ~s|#member-rows > div|
defp visible_row_el(), do: ~s|#member-rows > div:not(.hidden)|