Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.
TypeScript analyticsanalytics-dashboardclickhouseelixirgoogle-analyticsmarketingopen-source-analyticsphoenixplausible-analyticspostgresqlprivacyprivacy-friendlyself-hostedsimple-analyticsstatisticstailwindcssweb-analyticswebsite-analyticswebsite-statswebsite-tracking
Implement Team setup CTA+view (#4960)
hq1558352c8ac1f
diff --git a/extra/lib/plausible_web/live/funnel_settings/form.ex b/extra/lib/plausible_web/live/funnel_settings/form.exindex e7d5b0867a..05bcdc90ac 100644--- a/extra/lib/plausible_web/live/funnel_settings/form.ex+++ b/extra/lib/plausible_web/live/funnel_settings/form.ex@@ -94,7 +94,7 @@ defmodule PlausibleWeb.Live.FunnelSettings.Form doend}id={"step-#{step_idx}"}- options={reject_already_selected("step-#{step_idx}", @goals, @selections_made)}+ options={reject_already_selected(@goals, @selections_made)}/></div>@@ -385,16 +385,13 @@ defmodule PlausibleWeb.Live.FunnelSettings.Form doMap.delete(selections_made, step_input_id)end- defp reject_already_selected(combo_box, goals, selections_made) do+ defp reject_already_selected(goals, selections_made) doselection_ids =Enum.map(selections_made, fn{_, %{id: goal_id}} -> goal_idend)- result = Enum.reject(goals, fn {goal_id, _} -> goal_id in selection_ids end)-- send_update(PlausibleWeb.Live.Components.ComboBox, id: combo_box, suggestions: result)- result+ Enum.reject(goals, fn {goal_id, _} -> goal_id in selection_ids end)enddefp find_preselected(%Funnel{} = funnel, false, idx) dodiff --git a/lib/plausible/teams.ex b/lib/plausible/teams.exindex 43ec2950af..7b0dee4bfb 100644--- a/lib/plausible/teams.ex+++ b/lib/plausible/teams.ex@@ -261,6 +261,39 @@ defmodule Plausible.Teams do)end+ def setup_team(team, candidates) do+ inviter = Repo.preload(team, :owner).owner++ setup_team_fn = fn {{email, _name}, role} ->+ case Teams.Invitations.InviteToTeam.invite(team, inviter, email, role, send_email?: false) do+ {:ok, invitation} -> invitation+ {:error, error} -> Repo.rollback(error)+ end+ end++ result =+ Repo.transaction(fn ->+ team+ |> Teams.Team.setup_changeset()+ |> Repo.update!()++ Enum.map(candidates, setup_team_fn)+ end)++ case result do+ {:ok, invitations} ->+ Enum.each(invitations, fn invitation ->+ invitee = Plausible.Auth.find_user_by(email: invitation.email)+ Teams.Invitations.InviteToTeam.send_invitation_email(invitation, invitee)+ end)++ {:ok, invitations}++ {:error, {:over_limit, _}} = error ->+ error+ end+ end+defp create_my_team(user) doteam ="My Team"diff --git a/lib/plausible/teams/invitations/candidates.ex b/lib/plausible/teams/invitations/candidates.exindex 57047013cd..1e12a361b3 100644--- a/lib/plausible/teams/invitations/candidates.ex+++ b/lib/plausible/teams/invitations/candidates.ex@@ -23,11 +23,25 @@ defmodule Plausible.Teams.Invitations.Candidates doinner_join: u in assoc(tm, :user),where: gm.site_id in ^all_site_ids,where: ilike(u.email, ^term) or ilike(u.name, ^term),- where: u.id not in ^for(u <- exclude, do: u.id),+ where: u.email not in ^exclude,order_by: [asc: u.id],select: u,distinct: true,limit: ^limit)end++ def get_site_guest(%Teams.Team{} = team, email) do+ all_site_ids = Teams.owned_sites_ids(team)++ Repo.one(+ from gm in GuestMembership,+ inner_join: tm in assoc(gm, :team_membership),+ inner_join: u in assoc(tm, :user),+ where: gm.site_id in ^all_site_ids,+ where: u.email == ^email,+ distinct: true,+ select: u+ )+ endenddiff --git a/lib/plausible/teams/invitations/invite_to_team.ex b/lib/plausible/teams/invitations/invite_to_team.exindex c20dddcab5..f8ce8eddb1 100644--- a/lib/plausible/teams/invitations/invite_to_team.ex+++ b/lib/plausible/teams/invitations/invite_to_team.ex@@ -35,7 +35,9 @@ defmodule Plausible.Teams.Invitations.InviteToTeam do),{:ok, invitation} <-Teams.Invitations.invite(team, invitee_email, role, inviter) do- send_invitation_email(invitation, invitee)+ if Keyword.get(opts, :send_email?, true) do+ send_invitation_email(invitation, invitee)+ end{:ok, invitation}end@@ -45,7 +47,7 @@ defmodule Plausible.Teams.Invitations.InviteToTeam doraise "Invalid role passed: #{inspect(role)}"end- defp send_invitation_email(invitation, invitee) do+ def send_invitation_email(invitation, invitee) doinvitation|> Repo.preload([:team, :inviter])|> Teams.Invitations.send_invitation_email(invitee)diff --git a/lib/plausible/teams/team.ex b/lib/plausible/teams/team.exindex 76a2c2a8c4..ba8116b0a0 100644--- a/lib/plausible/teams/team.ex+++ b/lib/plausible/teams/team.ex@@ -61,6 +61,16 @@ defmodule Plausible.Teams.Team do|> validate_required(:name)end+ def setup_changeset(team) do+ now = NaiveDateTime.utc_now(:second)++ team+ |> change(+ setup_complete: true,+ setup_at: now+ )+ end+def start_trial(team, today \\ Date.utc_today()) dotrial_expiry = trial_expiry(today)diff --git a/lib/plausible_web/live/components/combo_box.ex b/lib/plausible_web/live/components/combo_box.exindex 69fec5114f..cd777dec47 100644--- a/lib/plausible_web/live/components/combo_box.ex+++ b/lib/plausible_web/live/components/combo_box.ex@@ -50,10 +50,10 @@ defmodule PlausibleWeb.Live.Components.ComboBox doif connected?(socket) dosocket|> assign_options()- |> assign_suggestions()elsesocketend+ |> assign_suggestions(assigns[:suggestions]){:ok, socket}end@@ -68,18 +68,15 @@ defmodule PlausibleWeb.Live.Components.ComboBox doattr(:suggest_fun, :any, required: true)attr(:suggestions_limit, :integer)attr(:class, :string, default: "")+ attr(:clear_on_select, :boolean, default: false)attr(:required, :boolean, default: false)attr(:creatable, :boolean, default: false)+ attr(:creatable_prompt, :string, default: "Create")attr(:errors, :list, default: [])attr(:async, :boolean, default: Mix.env() != :test)attr(:on_selection_made, :any)def render(assigns) do- assigns =- assign_new(assigns, :suggestions, fn ->- Enum.take(assigns.options, suggestions_limit(assigns))- end)-~H"""<divid={"input-picker-main-#{@id}"}@@ -115,7 +112,12 @@ defmodule PlausibleWeb.Live.Components.ComboBox do/><.spinner class="spinner hidden absolute inset-y-3 right-8" />- <.spinner x-show="selectionInProgress" class="spinner absolute inset-y-3 right-8" />+ <.spinner+ id={"selection-in-progress-#{@id}"}+ phx-update="ignore"+ x-show="selectionInProgress"+ class="spinner absolute inset-y-3 right-8"+ /><.dropdown_anchor id={@id} />@@ -136,6 +138,7 @@ defmodule PlausibleWeb.Live.Components.ComboBox dotarget={@myself}creatable={@creatable}display_value={@display_value}+ creatable_prompt={@creatable_prompt}/></div></div>@@ -170,6 +173,7 @@ defmodule PlausibleWeb.Live.Components.ComboBox doattr(:suggest_fun, :any, required: true)attr(:target, :any)attr(:creatable, :boolean, required: true)+ attr(:creatable_prompt, :string, default: nil)attr(:display_value, :string, required: true)def combo_dropdown(assigns) do@@ -180,6 +184,7 @@ defmodule PlausibleWeb.Live.Components.ComboBox dox-show="isOpen"x-ref="suggestions"class="text-sm w-full dropdown z-50 absolute mt-1 max-h-60 overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none dark:bg-gray-900"+ style="display: none;"><.option:if={display_creatable_option?(assigns)}@@ -189,6 +194,7 @@ defmodule PlausibleWeb.Live.Components.ComboBox dotarget={@target}ref={@ref}creatable+ creatable_prompt={@creatable_prompt}/><.option@@ -229,6 +235,7 @@ defmodule PlausibleWeb.Live.Components.ComboBox doattr(:target, :any)attr(:idx, :integer, required: true)attr(:creatable, :boolean, default: false)+ attr(:creatable_prompt, :string, required: false)def option(assigns) doassigns = assign(assigns, :suggestions_limit, suggestions_limit(assigns))@@ -245,7 +252,7 @@ defmodule PlausibleWeb.Live.Components.ComboBox do><ax-ref={"dropdown-#{@ref}-option-#{@idx}"}- x-on:click={not @creatable && "selectionInProgress = false"}+ x-on:click={not @creatable && "selectionInProgress = true"}phx-click={select_option(@ref, @submit_value, @display_value)}phx-value-submit-value={@submit_value}phx-value-display-value={@display_value}@@ -253,7 +260,7 @@ defmodule PlausibleWeb.Live.Components.ComboBox doclass="block truncate py-2 px-3"><%= if @creatable do %>- Create "{@display_value}"+ {@creatable_prompt} "{@display_value}"<% else %>{@display_value}<% end %>@@ -317,6 +324,13 @@ defmodule PlausibleWeb.Live.Components.ComboBox dodefp do_select(socket, submit_value, display_value) doid = socket.assigns.id+ display_value =+ if socket.assigns[:clear_on_select] do+ ""+ else+ display_value+ end+socket =socket|> push_event("update-value", %{id: id, value: display_value, fire: false})@@ -350,15 +364,17 @@ defmodule PlausibleWeb.Live.Components.ComboBox doend)end- defp assign_suggestions(socket) do- if socket.assigns[:suggestions] do- assign(- socket,- suggestions: Enum.take(socket.assigns.suggestions, suggestions_limit(socket.assigns))- )- else- socket- end+ defp assign_suggestions(socket, nil = _suggestions_from_update) do+ suggestions =+ socket.assigns+ |> Map.get(:options, [])+ |> Enum.take(suggestions_limit(socket.assigns))++ assign(socket, suggestions: suggestions)+ end++ defp assign_suggestions(socket, _suggestions_from_update) do+ socketenddefp select_default(socket) dodiff --git a/lib/plausible_web/live/components/form.ex b/lib/plausible_web/live/components/form.exindex e5fcf02bf3..53596fbd58 100644--- a/lib/plausible_web/live/components/form.ex+++ b/lib/plausible_web/live/components/form.ex@@ -18,7 +18,7 @@ defmodule PlausibleWeb.Live.Components.Form do<.input name="my-input" errors={["oh no!"]} />"""- @default_input_class "text-sm text-gray-900 dark:text-white dark:bg-gray-900 block pl-3.5 py-2.5 border-gray-300 dark:border-gray-500 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 rounded-md"+ @default_input_class "text-sm text-gray-900 dark:text-white dark:bg-gray-900 block pl-3.5 py-2 border-gray-300 dark:border-gray-500 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 rounded-md"attr(:id, :any, default: nil)attr(:name, :any)diff --git a/lib/plausible_web/live/team_setup.ex b/lib/plausible_web/live/team_setup.exnew file mode 100644index 0000000000..a33a43ea3c--- /dev/null+++ b/lib/plausible_web/live/team_setup.ex@@ -0,0 +1,312 @@+defmodule PlausibleWeb.Live.TeamSetup do+ @moduledoc """+ LiveView for Team setup+ """++ use PlausibleWeb, :live_view++ alias Plausible.Repo+ alias Plausible.Teams+ alias PlausibleWeb.Live.Components.ComboBox+ alias Plausible.Teams.Invitations.Candidates+ alias Plausible.Auth.User++ alias PlausibleWeb.Router.Helpers, as: Routes++ def mount(params, _session, socket) do+ my_team = socket.assigns.my_team+ enabled? = Teams.enabled?(my_team)++ # XXX: remove dev param, once manual testing is considered done+ socket =+ case {enabled?, my_team, params["dev"]} do+ {true, %Teams.Team{setup_complete: true}, nil} ->+ socket+ |> put_flash(:success, "Your team is now setup")+ |> redirect(to: Routes.settings_path(socket, :team_general))++ {true, %Teams.Team{}, _} ->+ all_candidates =+ my_team+ |> Candidates.search_site_guests("")+ |> Enum.map(fn user ->+ {user.email, "#{user.name} <#{user.email}>"}+ end)++ candidates_selected = %{}+ team_name_changeset = Teams.Team.name_changeset(my_team)++ assign(socket,+ all_candidates: all_candidates,+ team_name_changeset: team_name_changeset,+ candidates_selected: candidates_selected+ )++ {false, _, _} ->+ socket+ |> put_flash(:error, "You cannot set up any team just yet")+ |> redirect(to: Routes.site_path(socket, :index))+ end++ {:ok, socket}+ end++ def handle_params(_params, _uri, socket) do+ {:noreply, socket}+ end++ def render(assigns) do+ ~H"""+ <.flash_messages flash={@flash} />+ <.focus_box>+ <:title>Create a new team</:title>+ <:subtitle>+ Add members and assign roles to manage different sites access efficiently+ </:subtitle>++ <.form :let={f} for={@team_name_changeset} method="post" phx-change="update-team">+ <.input type="text" field={f[:name]} label="Name" width="w-full" phx-debounce="500" />++ <div class="mt-4">+ <.label>+ Add members+ </.label>++ <.live_component+ id="team-member-candidates"+ submit_name="team-member-candidate"+ class="py-2"+ module={ComboBox}+ clear_on_select+ creatable+ creatable_prompt="Send invitation to email:"+ placeholder="Select existing member or type email address to invite"+ options={reject_already_selected(@all_candidates, @candidates_selected)}+ on_selection_made={+ fn email, _by_id ->+ send(self(), {:candidate_selected, %{email: email, role: :viewer}})+ end+ }+ suggest_fun={+ fn input, _options ->+ exclude_emails =+ Enum.map(@candidates_selected, fn {{email, _}, _} -> email end)++ @my_team+ |> Candidates.search_site_guests(input, exclude: exclude_emails)+ |> Enum.map(fn user -> {user.email, "#{user.name} <#{user.email}>"} end)+ end+ }+ />+ </div>+ </.form>++ <.member user={@current_user} role={:owner} you?={true} />++ <%= for {{email, name}, role} <- @candidates_selected do %>+ <.member user={%User{email: email, name: name}} role={role} />+ <% end %>++ <:footer>+ <.button phx-click="setup-team" type="submit" mt?={false} class="w-full">+ Create team+ </.button>+ </:footer>+ </.focus_box>+ """+ end++ attr :user, User, required: true+ attr :you?, :boolean, default: false+ attr :role, :atom, default: nil++ def member(assigns) do+ ~H"""+ <div class="member mt-4">+ <div class="flex items-center gap-x-5">+ <img src={User.profile_img_url(@user)} class="w-7 rounded-full" />+ <span class="text-sm">+ {@user.name}+ <span+ :if={@you?}+ class="ml-1 dark:bg-indigo-600 dark:text-gray-200 bg-gray-100 text-gray-500 text-xs px-1 rounded"+ >+ You+ </span>++ <br /><span class="text-gray-500 text-xs">{@user.email}</span>+ </span>+ <div class="flex-1 text-right">+ <.dropdown class="relative">+ <:button class="role bg-transparent text-gray-800 dark:text-gray-100 hover:bg-gray-50 dark:hover:bg-gray-700 focus-visible:outline-gray-100 whitespace-nowrap truncate inline-flex items-center gap-x-2 font-medium rounded-md px-3.5 py-2.5 text-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 disabled:bg-gray-400 dark:disabled:text-white dark:disabled:text-gray-400 dark:disabled:bg-gray-700">+ {@role |> to_string() |> String.capitalize()}+ <Heroicons.chevron_down mini class="size-4 mt-0.5" />+ </:button>+ <:menu class="dropdown-items max-w-60">+ <.dropdown_item+ href="#"+ disabled={@you? or @role == :admin}+ phx-click="update-role"+ phx-value-role={:admin}+ phx-value-email={@user.email}+ phx-value-name={@user.name}+ >+ <div>Admin</div>+ <div class="text-gray-500 dark:text-gray-400 text-xs/5">+ Manage all team settings+ </div>+ </.dropdown_item>++ <.dropdown_item+ href="#"+ disabled={@you? or @role == :editor}+ phx-click="update-role"+ phx-value-role={:editor}+ phx-value-email={@user.email}+ phx-value-name={@user.name}+ >+ <div>Editor</div>+ <div class="text-gray-500 dark:text-gray-400 text-xs/5">+ Create and view new sites+ </div>+ </.dropdown_item>++ <.dropdown_item+ href="#"+ disabled={@you? or @role == :viewer}+ phx-click="update-role"+ phx-value-role={:viewer}+ phx-value-email={@user.email}+ phx-value-name={@user.name}+ >+ <div>Viewer</div>+ <div class="text-gray-500 dark:text-gray-400 text-xs/5">+ Can only view all sites under your team+ </div>+ </.dropdown_item>++ <.dropdown_divider />+ <.dropdown_item+ href="#"+ disabled={@you?}+ phx-click="remove-member"+ phx-value-email={@user.email}+ phx-value-name={@user.name}+ >+ <div class="text-red-600 hover:text-red-600 dark:text-red-500 hover:dark:text-red-400">+ Remove member+ </div>+ <div class="text-gray-500 dark:text-gray-400 text-xs/5">+ Remove member from your team+ </div>+ </.dropdown_item>+ </:menu>+ </.dropdown>+ </div>+ </div>+ </div>+ """+ end++ def handle_info(+ {:candidate_selected, %{email: email, role: role}},+ %{assigns: %{my_team: team, candidates_selected: candidates, current_user: current_user}} =+ socket+ ) do+ socket =+ case Candidates.get_site_guest(team, email) do+ %User{} = user ->+ assign(+ socket,+ :candidates_selected,+ Map.put(candidates, {user.email, user.name}, role)+ )++ nil ->+ if valid_email?(email) and email != current_user.email do+ assign(+ socket,+ :candidates_selected,+ Map.put(candidates, {email, "Invited User"}, role)+ )+ else+ put_live_flash(+ socket,+ :error,+ "Sorry, e-mail '#{email}' is invalid. Please type the address again."+ )+ end+ end++ {:noreply, socket}+ end++ def handle_event("update-team", %{"team" => params}, socket) do+ team_name_changeset =+ socket.assigns.my_team+ |> Teams.Team.name_changeset(params)++ if team_name_changeset.valid? do+ my_team = Repo.update!(team_name_changeset)++ {:noreply,+ assign(socket,+ team_name_changeset: team_name_changeset,+ my_team: my_team+ )}+ else+ {:noreply, socket}+ end+ end++ def handle_event("update-role", %{"name" => name, "email" => email, "role" => role}, socket) do+ updated_candidates =+ Map.put(socket.assigns.candidates_selected, {email, name}, String.to_existing_atom(role))++ {:noreply, assign(socket, candidates_selected: updated_candidates)}+ end++ def handle_event("remove-member", %{"name" => name, "email" => email}, socket) do+ updated_candidates = Map.delete(socket.assigns.candidates_selected, {email, name})+ {:noreply, assign(socket, candidates_selected: updated_candidates)}+ end++ def handle_event("setup-team", %{}, socket) do+ candidates = socket.assigns.candidates_selected+ team = socket.assigns.my_team++ case Teams.setup_team(team, candidates) do+ {:ok, _invitations} ->+ socket =+ socket+ |> put_flash(:success, "Your team is now setup")+ |> redirect(to: Routes.settings_path(socket, :team_general))++ {:noreply, socket}++ {:error, {:over_limit, limit}} ->+ socket =+ socket+ |> put_live_flash(+ :error,+ "Your account is limited to #{limit} team members. You can upgrade your plan to increase this limit."+ )++ {:noreply, socket}+ end+ end++ defp valid_email?(email) do+ String.contains?(email, "@") and String.contains?(email, ".")+ end++ defp reject_already_selected(candidates, candidates_selected) do+ candidates+ |> Enum.reject(fn {email, _} ->+ Enum.find(candidates_selected, fn+ {{^email, _}, _} -> true+ _ -> false+ end)+ end)+ end+enddiff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.exindex c457d42254..aaaad69f9c 100644--- a/lib/plausible_web/router.ex+++ b/lib/plausible_web/router.ex@@ -418,6 +418,7 @@ defmodule PlausibleWeb.Router dopipe_through [:app_layout, PlausibleWeb.RequireAccountPlug]live "/sites", Sites, :index, as: :site+ live "/team/setup", TeamSetup, :setup, as: :team_setupendget "/sites/new", SiteController, :newdiff --git a/lib/plausible_web/templates/layout/_header.html.heex b/lib/plausible_web/templates/layout/_header.html.heexindex 5b38e39f5f..f699cb1259 100644--- a/lib/plausible_web/templates/layout/_header.html.heex+++ b/lib/plausible_web/templates/layout/_header.html.heex@@ -76,6 +76,17 @@<.dropdown_item href={Routes.settings_path(@conn, :index)}>Account Settings</.dropdown_item>+ <div :if={Plausible.Teams.enabled?(@my_team) and @my_team.setup_complete}>+ <.dropdown_item+ class="flex"+ href={Routes.settings_path(@conn, :team_general)}+ >+ <span class="flex-1">+ Team Settings+ </span>+ </.dropdown_item>+ <.dropdown_divider />+ </div><.dropdown_itemclass="!flex justify-between gap-x-12"new_tab@@ -108,6 +119,17 @@Github Repo</.dropdown_item><.dropdown_divider />+ <div :if={Plausible.Teams.enabled?(@my_team) and not @my_team.setup_complete}>+ <.dropdown_item class="flex" href={Routes.team_setup_path(@conn, :setup)}>+ <span class="flex-1">+ Create a Team+ </span>+ <span class="ml-1 bg-indigo-700 text-gray-100 text-xs p-1 rounded">+ NEW+ </span>+ </.dropdown_item>+ <.dropdown_divider />+ </div><.dropdown_item href="/logout">Log Out</.dropdown_item></:menu></.dropdown>diff --git a/priv/repo/seeds.exs b/priv/repo/seeds.exsindex 06abd47dd8..3b72db7577 100644--- a/priv/repo/seeds.exs+++ b/priv/repo/seeds.exs@@ -11,6 +11,8 @@# and so on) as they will fail if something goes wrong.import Plausible.Teams.Test+FunWithFlags.enable(:teams)+words =for i <- 0..(:erlang.system_info(:atom_count) - 1),do: :erlang.binary_to_term(<<131, 75, i::24>>)@@ -58,6 +60,7 @@ site =)add_guest(site, user: new_user(name: "Arnold Wallaby", password: "plausible"), role: :viewer)+add_guest(site, user: new_user(name: "Lois Lane", password: "plausible"), role: :editor)Plausible.Factory.insert_list(29, :ip_rule, site: site)Plausible.Factory.insert(:country_rule, site: site, country_code: "PL")diff --git a/test/plausible/teams/invitations/candidates_test.exs b/test/plausible/teams/invitations/candidates_test.exsindex 9578532422..49ef537bc7 100644--- a/test/plausible/teams/invitations/candidates_test.exs+++ b/test/plausible/teams/invitations/candidates_test.exs@@ -61,7 +61,7 @@ defmodule Plausible.Teams.Invitations.CandidatesTest doassert [_, _] = Candidates.search_site_guests(team_of(owner), "", limit: 2)end- test "capable of exlucding users" do+ test "capable of excluding e-mails" doowner = new_user()site = new_site(owner: owner)@@ -73,6 +73,7 @@ defmodule Plausible.Teams.Invitations.CandidatesTest doassert [%{email: "[email protected]"}- ] = Candidates.search_site_guests(team_of(owner), "doe", exclude: [to_be_excluded])+ ] =+ Candidates.search_site_guests(team_of(owner), "doe", exclude: [to_be_excluded.email])endenddiff --git a/test/plausible_web/live/components/combo_box_test.exs b/test/plausible_web/live/components/combo_box_test.exsindex cb6f18423d..5babde7b85 100644--- a/test/plausible_web/live/components/combo_box_test.exs+++ b/test/plausible_web/live/components/combo_box_test.exs@@ -245,6 +245,24 @@ defmodule PlausibleWeb.Live.Components.ComboBoxTest doendend+ defmodule CreatableCustomView do+ use Phoenix.LiveView++ def render(assigns) do+ ~H"""+ <.live_component+ submit_name="some_submit_name"+ module={PlausibleWeb.Live.Components.ComboBox}+ suggest_fun={&ComboBox.StaticSearch.suggest/2}+ id="test-creatable-component"+ creatable+ creatable_prompt="Custom Text"+ clear_on_select+ />+ """+ end+ end+test "stores selected value from suggestion", %{conn: conn} do{:ok, lv, _html} = live_isolated(conn, CreatableView, session: %{})type_into_combo(lv, "test-creatable-component", "option 20")@@ -303,7 +321,7 @@ defmodule PlausibleWeb.Live.Components.ComboBoxTest do{:ok, lv, html} = live_isolated(conn, CreatableView, session: %{})regular_option = find(html, "li#dropdown-test-creatable-component-option-1 a")- assert Floki.attribute(regular_option, "x-on:click") == ["selectionInProgress = false"]+ assert Floki.attribute(regular_option, "x-on:click") == ["selectionInProgress = true"]creatable_option =lv@@ -312,6 +330,27 @@ defmodule PlausibleWeb.Live.Components.ComboBoxTest doassert Floki.attribute(creatable_option, "x-on:click") == []end++ test "allows for custom creatable prompt", %{conn: conn} do+ {:ok, lv, _html} = live_isolated(conn, CreatableCustomView, session: %{})++ assert lv+ |> type_into_combo("test-creatable-component", "my new option")+ |> text_of_element("li#dropdown-test-creatable-component-option-0 a") ==+ ~s(Custom Text "my new option")+ end++ test "clears on select", %{conn: conn} do+ {:ok, lv, _html} = live_isolated(conn, CreatableCustomView, session: %{})++ type_into_combo(lv, "test-creatable-component", "my new option")++ lv+ |> element("li#dropdown-test-creatable-component-option-0 a")+ |> render_click()++ assert lv |> render() |> text_of_attr("#test-creatable-component", "value") == ""+ endenddescribe "async suggestions" dodiff --git a/test/plausible_web/live/team_setup_sync_test.exs b/test/plausible_web/live/team_setup_sync_test.exsnew file mode 100644index 0000000000..de5f47da28--- /dev/null+++ b/test/plausible_web/live/team_setup_sync_test.exs@@ -0,0 +1,76 @@+defmodule PlausibleWeb.Live.TeamSetupSyncTest do+ use PlausibleWeb.ConnCase, async: false+ use Bamboo.Test, shared: true++ use Plausible.Teams.Test++ import Phoenix.LiveViewTest++ alias Plausible.Repo++ @url "/team/setup"++ describe "/team/setup - full integration" do+ setup [:create_user, :log_in, :create_team]++ @subject_prefix if ee?(), do: "[Plausible Analytics] ", else: "[Plausible CE] "++ test "setting up a team successfully creates invitations", %{+ conn: conn,+ user: user,+ team: team+ } do+ site = new_site(owner: user)+ guest = add_guest(site, role: :viewer)+ guest2 = build(:user)++ {:ok, lv, _html} = live(conn, @url)++ type_into_input(lv, "team[name]", "New Team Name")++ type_into_combo(lv, "team-member-candidates", guest.email)+ select_combo_option(lv, 1)++ type_into_combo(lv, "team-member-candidates", guest2.email)+ select_combo_option(lv, 0)++ lv |> element(~s|button[phx-click="setup-team"]|) |> render_click()++ [i1, i2] = team |> Ecto.assoc(:team_invitations) |> Repo.all() |> Enum.sort_by(& &1.id)++ assert i1.email == guest.email+ assert i2.email == guest2.email++ assert_email_delivered_with(+ to: [nil: guest.email],+ subject: @subject_prefix <> "You've been invited to \"New Team Name\" team"+ )++ assert_email_delivered_with(+ to: [nil: guest2.email],+ subject: @subject_prefix <> "You've been invited to \"New Team Name\" team"+ )+ end+ end++ defp type_into_input(lv, id, text) do+ lv+ |> element("form")+ |> render_change(%{id => text})+ end++ defp type_into_combo(lv, id, text) do+ lv+ |> element("input##{id}")+ |> render_change(%{+ "_target" => ["display-#{id}"],+ "display-#{id}" => "#{text}"+ })+ end++ defp select_combo_option(lv, index) do+ lv+ |> element(~s/li#dropdown-team-member-candidates-option-#{index} a/)+ |> render_click()+ end+enddiff --git a/test/plausible_web/live/team_setup_test.exs b/test/plausible_web/live/team_setup_test.exsnew file mode 100644index 0000000000..c230ad7625--- /dev/null+++ b/test/plausible_web/live/team_setup_test.exs@@ -0,0 +1,257 @@+defmodule PlausibleWeb.Live.TeamSetupTest do+ use PlausibleWeb.ConnCase, async: true++ alias Plausible.Teams+ use Plausible.Teams.Test++ import Phoenix.LiveViewTest+ import Plausible.Test.Support.HTML++ alias Plausible.Repo++ @url "/team/setup"++ describe "/team/setup - edge cases" 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)+ team |> Teams.Team.setup_changeset() |> Repo.update!()+ assert {:error, {:redirect, %{to: "/settings/team/general"}}} = live(conn, @url)+ end++ test "does not redirect to /team/general if dev mode", %{conn: conn, user: user} do+ {:ok, team} = Teams.get_or_create(user)+ team |> Teams.Team.setup_changeset() |> Repo.update!()+ assert {:ok, _, _} = live(conn, @url <> "?dev=1")+ end+ end++ describe "/team/setup - functional details" do+ setup [:create_user, :log_in, :create_team]++ test "renders form", %{conn: conn} do+ {:ok, _, html} = live(conn, @url)+ assert element_exists?(html, ~s|input#team_name[name="team[name]"]|)+ assert element_exists?(html, ~s|input[name="team-member-candidate"]|)+ assert element_exists?(html, ~s|button[phx-click="setup-team"]|)+ end++ test "changing team name, updates team name in db", %{conn: conn, team: team} do+ {:ok, lv, _html} = live(conn, @url)+ type_into_input(lv, "team[name]", "New Team Name")+ assert Repo.reload!(team).name == "New Team Name"+ end++ test "existing guest is suggested from combobox dropdown", %{conn: conn, user: user} do+ site = new_site(owner: user)+ guest = add_guest(site, role: :viewer)++ {:ok, lv, _html} = live(conn, @url)++ type_into_combo(lv, "team-member-candidates", guest.email)+ select_combo_option(lv, 1)++ [member1_row, member2_row] =+ lv+ |> render()+ |> find(".member")++ assert text(member1_row) =~ user.name+ assert text(member1_row) =~ "You"+ assert text(member1_row) =~ user.email++ assert text(member2_row) =~ guest.name+ assert text(member2_row) =~ guest.email++ assert member1_row |> find(".role") |> text() =~ "Owner"+ assert member2_row |> find(".role") |> text() =~ "Viewer"+ end++ test "team member is added from input", %{conn: conn, user: user} do+ new_member_email = build(:user).email++ {:ok, lv, _html} = live(conn, @url)++ type_into_combo(lv, "team-member-candidates", new_member_email)+ select_combo_option(lv, 0)++ [member1_row, member2_row] =+ lv+ |> render()+ |> find(".member")++ assert text(member1_row) =~ user.name+ assert text(member1_row) =~ "You"+ assert text(member1_row) =~ user.email++ assert text(member2_row) =~ "Invited User"+ assert text(member2_row) =~ new_member_email++ assert member1_row |> find(".role") |> text() =~ "Owner"+ assert member2_row |> find(".role") |> text() =~ "Viewer"+ end++ test "arbitrary invalid e-mail attempt", %{conn: conn} do+ {:ok, lv, _html} = live(conn, @url)+ type_into_combo(lv, "team-member-candidates", "invalid")++ refute lv |> render |> text() =~ "Sorry"++ select_combo_option(lv, 0)++ assert lv |> render() |> text() =~+ "Sorry, e-mail 'invalid' is invalid. Please type the address again."+ end++ test "owner's own e-mail attempt", %{conn: conn, user: user} do+ {:ok, lv, _html} = live(conn, @url)+ type_into_combo(lv, "team-member-candidates", user.email)++ refute lv |> render |> text() =~ "Sorry"++ select_combo_option(lv, 0)++ assert lv |> render() |> text() =~+ "Sorry, e-mail '#{user.email}' is invalid. Please type the address again."+ end++ test "owner's role dropdown consists of inactive options", %{conn: conn} do+ {:ok, _lv, html} = live(conn, @url)++ assert html+ |> find(".member")+ |> Enum.take(1)+ |> find(".dropdown-items > *:not([^role=separator])")+ |> Enum.all?(fn el ->+ text_of_attr(el, "data-ui-state") == "disabled"+ end)+ end++ test "candidate's role dropdown allows changing role", %{conn: conn} do+ new_member_email = build(:user).email+ {:ok, lv, _html} = live(conn, @url)++ type_into_combo(lv, "team-member-candidates", new_member_email)+ select_combo_option(lv, 0)++ lv+ |> element(~s|.member a[phx-click="update-role"][phx-value-role="admin"]|)+ |> render_click()++ member2_row = lv |> render() |> find(".member:nth-of-type(2) .role") |> text()+ assert member2_row =~ "Admin"++ lv+ |> element(~s|.member a[phx-click="update-role"][phx-value-role="viewer"]|)+ |> render_click()++ member2_row = lv |> render() |> find(".member:nth-of-type(2) .role") |> text()+ assert member2_row =~ "Viewer"+ end++ test "member candidate suggestion disappears when selected", %{conn: conn, user: user} do+ site = new_site(owner: user)+ guest = add_guest(site, role: :viewer)++ {:ok, lv, _html} = live(conn, @url)++ type_into_combo(lv, "team-member-candidates", guest.email)++ assert lv+ |> render()+ |> find("#dropdown-team-member-candidates")+ |> text() =~ guest.email++ select_combo_option(lv, 1)++ _ = render(lv)++ refute lv+ |> render()+ |> find("#dropdown-team-member-candidates")+ |> text() =~ guest.email+ end++ test "member candidate can be removed", %{conn: conn, user: user} do+ site = new_site(owner: user)++ guest = add_guest(site, role: :viewer)++ {:ok, lv, _html} = live(conn, @url)++ type_into_combo(lv, "team-member-candidates", guest.email)+ select_combo_option(lv, 1)++ assert lv+ |> render()+ |> find(".member:nth-of-type(2)")+ |> text() =~ guest.email++ lv+ |> element(~s|.member a[phx-click="remove-member"][phx-value-email="#{guest.email}"]|)+ |> render_click()++ refute lv+ |> render()+ |> find(".member")+ |> text() =~ guest.email+ end+ end++ describe "/team/setup - full integration" do+ setup [:create_user, :log_in, :create_team]++ test "setting up team above plan member limits", %{+ conn: conn,+ user: user,+ team: team+ } do+ site = new_site(owner: user)+ guest = add_guest(site, role: :viewer)++ extra_guests = build_list(3, :user)++ {:ok, lv, _html} = live(conn, @url)++ type_into_combo(lv, "team-member-candidates", guest.email)+ select_combo_option(lv, 1)++ for g <- extra_guests do+ type_into_combo(lv, "team-member-candidates", g.email)+ select_combo_option(lv, 0)+ end++ lv |> element(~s|button[phx-click="setup-team"]|) |> render_click()++ assert team |> Ecto.assoc(:team_invitations) |> Repo.aggregate(:count) == 0++ assert lv |> render() |> text() =~ "Your account is limited to 3 team members"+ end+ end++ defp type_into_input(lv, id, text) do+ lv+ |> element("form")+ |> render_change(%{id => text})+ end++ defp type_into_combo(lv, id, text) do+ lv+ |> element("input##{id}")+ |> render_change(%{+ "_target" => ["display-#{id}"],+ "display-#{id}" => "#{text}"+ })+ end++ defp select_combo_option(lv, index) do+ lv+ |> element(~s/li#dropdown-team-member-candidates-option-#{index} a/)+ |> render_click()+ end+enddiff --git a/test/support/html.ex b/test/support/html.exindex 041b450c21..313cb128d9 100644--- a/test/support/html.ex+++ b/test/support/html.ex@@ -12,12 +12,16 @@ defmodule Plausible.Test.Support.HTML do|> Kernel.not()end- def find(html, value) do+ def find(html, value) when is_binary(html) dohtml|> Floki.parse_document!()|> Floki.find(value)end+ def find(html, value) do+ Floki.find(html, value)+ end+def submit_button(html, form) dofind(html, "#{form} button[type=\"submit\"]")enddiff --git a/test/support/test_utils.ex b/test/support/test_utils.exindex 18c2fb97bb..362363a032 100644--- a/test/support/test_utils.ex+++ b/test/support/test_utils.ex@@ -42,6 +42,11 @@ defmodule Plausible.TestUtils do{:ok, site: Plausible.Teams.Test.new_site(owner: user)}end+ def create_team(%{user: user}) do+ {:ok, team} = Plausible.Teams.get_or_create(user)+ {:ok, team: team}+ end+def create_legacy_site_import(%{site: site}) docreate_site_import(%{site: site, create_legacy_import?: true})end