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
Consolidate and improve site transfer UX (#6413)
Sanne de Vries2efa355a9c71
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex eeac44d7af..9f10e57af8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -29,6 +29,7 @@ All notable changes to this project will be documented in this file.- Changed graph tooltip positioning logic: it now aligns to the top of the chart, to the right of the hovered data point- Use ResizeObserver instead of polling in tracker for scroll depth. Removes forced reflows caused by the tracker script.- Update custom range datepicker styles+- Improved site transfer UI### Fixeddiff --git a/lib/plausible_web/controllers/site/membership_controller.ex b/lib/plausible_web/controllers/site/membership_controller.exindex c10a7e41ff..8607be6a68 100644--- a/lib/plausible_web/controllers/site/membership_controller.ex+++ b/lib/plausible_web/controllers/site/membership_controller.ex@@ -93,125 +93,6 @@ defmodule PlausibleWeb.Site.MembershipController doendend- def transfer_ownership_form(conn, _params) do- site_domain = conn.assigns.site.domain-- site =- Plausible.Sites.get_for_user!(conn.assigns.current_user, site_domain)-- render(- conn,- "transfer_ownership_form.html",- site: site,- skip_plausible_tracking: true- )- end-- def transfer_ownership(conn, %{"email" => email}) do- site_domain = conn.assigns.site.domain-- site =- Plausible.Sites.get_for_user!(conn.assigns.current_user, site_domain)-- case Teams.Invitations.InviteToSite.invite(- site,- conn.assigns.current_user,- email,- :owner- ) do- {:ok, _invitation} ->- conn- |> put_flash(:success, "Site transfer request has been sent to #{email}")- |> redirect(to: Routes.site_path(conn, :settings_people, site.domain))-- {:error, changeset} ->- errors = Plausible.ChangesetHelpers.traverse_errors(changeset)-- message =- case errors do- %{invitation: ["already sent" | _]} -> "Invitation has already been sent"- _other -> "Site transfer request to #{email} has failed"- end-- conn- |> put_flash(:ttl, :timer.seconds(5))- |> put_flash(:error_title, "Transfer error")- |> put_flash(:error, message)- |> redirect(to: Routes.site_path(conn, :settings_people, site.domain))- end- end-- def change_team_form(conn, _params) do- site_domain = conn.assigns.site.domain- user = conn.assigns.current_user-- site =- Plausible.Sites.get_for_user!(user, site_domain)-- render_change_team_form(conn, user, site)- end-- defp render_change_team_form(conn, user, site, opts \\ []) do- transferable_teams =- user- |> Plausible.Teams.Users.teams(roles: [:owner, :admin])- |> Enum.reject(&(&1.id == site.team_id))- |> Enum.map(&{&1.name, &1.identifier})-- render(- conn,- "change_team_form.html",- site: site,- skip_plausible_tracking: true,- transferable_teams: transferable_teams,- error: opts[:error]- )- end-- def change_team(conn, %{"team_identifier" => identifier}) do- site_domain = conn.assigns.site.domain- user = conn.assigns.current_user-- site =- Plausible.Sites.get_for_user!(user, site_domain)-- destination_team =- Repo.one!(Teams.Users.teams_query(user, roles: [:admin, :owner], identifier: identifier))-- case Teams.Sites.Transfer.change_team(- site,- conn.assigns.current_user,- destination_team- ) do- :ok ->- conn- |> put_flash(:success, "Site team was changed")- |> redirect(to: Routes.site_path(conn, :index, __team: identifier))-- {:error, :no_plan} ->- conn- |> render_change_team_form(conn.assigns.current_user, site,- error:- "This team doesn't have a subscription. Please start a subscription for " <>- "the team first and then try moving the site again"- )-- {:error, {:over_plan_limits, _}} ->- conn- |> render_change_team_form(conn.assigns.current_user, site,- error:- "This site's usage is over the limits of the team's subscription. " <>- "Please upgrade the team to an appropriate subscription and then try moving the site again"- )-- {:error, _} ->- conn- |> render_change_team_form(conn.assigns.current_user, site,- error: "Sorry, this team cannot be used"- )- end- end-@doc """Updates the role of a user. The user being updated could be the same or different from the user takingthe action. When updating the role, it's important to enforce permissions:diff --git a/lib/plausible_web/controllers/site_controller.ex b/lib/plausible_web/controllers/site_controller.exindex a9a560bd4d..7413111898 100644--- a/lib/plausible_web/controllers/site_controller.ex+++ b/lib/plausible_web/controllers/site_controller.ex@@ -192,6 +192,7 @@ defmodule PlausibleWeb.SiteController doconn|> render("settings_danger_zone.html",site: site,+ connect_live_socket: true,dogfood_page_path: "/:dashboard/settings/danger-zone",layout: {PlausibleWeb.LayoutView, "site_settings.html"})diff --git a/lib/plausible_web/live/components/form.ex b/lib/plausible_web/live/components/form.exindex c49689be15..39b92bd185 100644--- a/lib/plausible_web/live/components/form.ex+++ b/lib/plausible_web/live/components/form.ex@@ -136,7 +136,7 @@ defmodule PlausibleWeb.Live.Components.Form doid={@id}name={@name}checked={assigns[:checked]}- class="block dark:bg-gray-900 size-4.5 mt-px cursor-pointer text-indigo-600 border-gray-400 dark:border-gray-600 checked:border-indigo-600 dark:checked:border-white"+ class="block dark:bg-gray-900 size-4.5 mt-px cursor-pointer text-indigo-600 border-gray-400 dark:border-gray-600 checked:border-indigo-600 dark:checked:border-white disabled:cursor-not-allowed"{@rest}/><.label :if={@label} class="flex flex-col flex-inline" for={@id}>@@ -416,7 +416,7 @@ defmodule PlausibleWeb.Live.Components.Form dodef error(assigns) do~H"""- <p class="flex gap-3 text-sm leading-6 text-red-500">+ <p class="mt-1 flex gap-3 text-sm text-red-500 leading-4.5 text-pretty">{render_slot(@inner_block)}</p>"""diff --git a/lib/plausible_web/live/site_transfer_settings.ex b/lib/plausible_web/live/site_transfer_settings.exnew file mode 100644index 0000000000..73fce9a773--- /dev/null+++ b/lib/plausible_web/live/site_transfer_settings.ex@@ -0,0 +1,318 @@+defmodule PlausibleWeb.Live.SiteTransferSettings do+ @moduledoc """+ LiveView for the "Transfer site" tile in the site Danger Zone.++ Lets the site owner pick a destination (another team they own/admin or+ another Plausible account), validates the form interactively, and+ dispatches to the appropriate transfer action.+ """++ use PlausibleWeb, :live_view++ alias Plausible.Teams+ alias PlausibleWeb.Live.SiteTransferSettings.Form+ alias PlausibleWeb.Router.Helpers, as: Routes++ def mount(_params, %{"domain" => domain}, socket) do+ user = socket.assigns.current_user++ site =+ Plausible.Sites.get_for_user!(user, domain, roles: [:owner, :admin, :super_admin])++ teams = Teams.Users.teams(user, roles: [:owner, :admin])++ team_options =+ user+ |> Teams.Users.teams(roles: [:owner, :admin])+ |> Enum.reject(&(&1.id == site.team_id || not &1.setup_complete))+ |> Enum.map(&{&1.name, &1.identifier})++ show_teams? = team_options != []++ show_my_team? =+ not is_nil(socket.assigns[:my_team]) and socket.assigns.my_team.id != site.team_id++ my_team_notice =+ cond do+ not is_nil(socket.assigns[:my_team]) and socket.assigns.my_team.id == site.team_id ->+ "The site is already in your personal sites."++ is_nil(socket.assigns[:my_team]) ->+ "You don't have an active subscription."++ true ->+ nil+ end++ initial_destination =+ cond do+ show_teams? -> :team+ show_my_team? -> :my_team+ true -> :account+ end++ socket =+ socket+ |> assign(+ site: site,+ teams: teams,+ team_options: team_options,+ show_teams?: show_teams?,+ show_my_team?: show_my_team?,+ my_team_notice: my_team_notice+ )+ |> assign_form(%{"destination" => initial_destination})++ {:ok, socket}+ end++ def render(assigns) do+ ~H"""+ <div>+ <.flash_messages flash={@flash} />++ <.tile docs="transfer-ownership">+ <:title>Transfer site</:title>+ <:subtitle>Move this site to another team or Plausible account.</:subtitle>++ <.form+ :let={f}+ for={@form}+ id="site-transfer-form"+ phx-change="validate"+ phx-submit="save"+ >+ <fieldset class="max-w-lg flex flex-col gap-y-4">+ <.label>Destination</.label>++ <div class="flex flex-col">+ <div class={not @show_teams? && "opacity-40 cursor-not-allowed"}>+ <.input+ type="radio"+ id="destination-team"+ name={f[:destination].name}+ value={:team}+ checked={f[:destination].value == :team and @show_teams?}+ disabled={not @show_teams?}+ label="Team"+ />+ </div>+ <div+ :if={f[:destination].value == :team and @show_teams?}+ class="ml-7 mt-1 flex flex-col gap-y-2"+ >+ <p class="text-sm text-gray-500 dark:text-gray-400 text-pretty">+ The site will immediately move to the selected team. Billing does not transfer.+ </p>+ <.input+ type="select"+ field={f[:team_identifier]}+ options={@team_options}+ prompt="Select a team"+ mt?={false}+ />+ </div>+ <p+ :if={not @show_teams?}+ class="ml-7 mt-1 text-sm text-gray-500/60 dark:text-gray-400/60 text-pretty"+ >+ You aren't a member of any other teams or you lack privileges for transfer.+ </p>+ </div>++ <div class="flex flex-col">+ <.input+ type="radio"+ id="destination-account"+ name={f[:destination].name}+ value={:account}+ checked={f[:destination].value == :account}+ label="Another Plausible account"+ />+ <div+ :if={f[:destination].value == :account}+ class="ml-7 mt-1 flex flex-col gap-y-2"+ >+ <p class="text-sm text-gray-500 dark:text-gray-400 text-pretty">+ The recipient will receive an email and have 48 hours to accept the transfer. You'll keep Guest Editor access by default.+ </p>+ <.input+ type="email"+ field={f[:email]}+ label="Email address"+ placeholder="[email protected]"+ mt?={false}+ />+ </div>+ </div>++ <div class="flex flex-col">+ <div class={not @show_my_team? && "opacity-40 cursor-not-allowed"}>+ <.input+ type="radio"+ id="destination-my_team"+ name={f[:destination].name}+ value={:my_team}+ checked={f[:destination].value == :my_team}+ disabled={not @show_my_team?}+ label="My personal sites"+ />+ <div class="ml-7">+ <.input+ :if={@show_my_team?}+ type="hidden"+ field={f[:my_team_available]}+ value={true}+ mt?={false}+ />+ </div>+ </div>+ <p+ :if={@my_team_notice}+ class="ml-7 mt-1 text-sm text-gray-500/60 dark:text-gray-400/60 text-pretty"+ >+ {@my_team_notice}+ </p>+ </div>+ </fieldset>++ <.button+ type="submit"+ theme="danger"+ phx-disable-with="Transferring..."+ >+ {submit_label(f[:destination].value)}+ </.button>+ </.form>+ </.tile>+ </div>+ """+ end++ def handle_event("validate", %{"form" => params}, socket) do+ {:noreply, assign_form(socket, params)}+ end++ def handle_event("save", %{"form" => params}, socket) do+ changeset = Form.changeset(params)++ case Ecto.Changeset.apply_action(changeset, :insert) do+ {:ok, %Form{destination: :team, team_identifier: identifier}} ->+ team = Enum.find(socket.assigns.teams, &(&1.identifier == identifier))+ do_change_team(socket, team, params)++ {:ok, %Form{destination: :my_team}} ->+ do_change_team(socket, socket.assigns[:my_team], params)++ {:ok, %Form{destination: :account, email: email}} ->+ do_transfer_ownership(socket, email, params)++ {:error, changeset} ->+ {:noreply, assign(socket, form: to_form(changeset, as: :form))}+ end+ end++ defp do_change_team(socket, destination_team, params) do+ if destination_team do+ my_team? =+ not is_nil(socket.assigns[:my_team]) and socket.assigns.my_team.id == destination_team.id++ user = socket.assigns.current_user+ site = socket.assigns.site++ error_field = if(my_team?, do: :my_team_available, else: :team_identifier)++ case Teams.Sites.Transfer.change_team(site, user, destination_team) do+ :ok ->+ {:noreply,+ socket+ |> put_flash(:success, "Site team was changed")+ |> redirect(to: Routes.site_path(socket, :index, __team: destination_team.identifier))}++ {:error, reason} ->+ {:noreply,+ assign_form(socket, params,+ action: :insert,+ field_errors: [{error_field, change_team_error_message(reason, my_team?)}]+ )}+ end+ else+ {:noreply,+ assign_form(socket, params,+ action: :insert,+ field_errors: [{:team_identifier, "Please select a team"}]+ )}+ end+ end++ defp do_transfer_ownership(socket, email, params) do+ user = socket.assigns.current_user+ site = socket.assigns.site++ case Teams.Invitations.InviteToSite.invite(site, user, email, :owner) do+ {:ok, _invitation} ->+ {:noreply,+ socket+ |> put_flash(:success, "Site transfer request has been sent to #{email}")+ |> redirect(to: Routes.site_path(socket, :settings_people, site.domain))}++ {:error, %Ecto.Changeset{} = changeset} ->+ message =+ case Plausible.ChangesetHelpers.traverse_errors(changeset) do+ %{invitation: ["already sent" | _]} -> "Invitation has already been sent"+ _ -> "Site transfer request to #{email} has failed"+ end++ {:noreply,+ assign_form(socket, params,+ action: :insert,+ field_errors: [{:email, message}]+ )}+ end+ end++ defp assign_form(socket, params, opts \\ []) do+ changeset = Form.changeset(params)++ changeset =+ Enum.reduce(Keyword.get(opts, :field_errors, []), changeset, fn {field, message}, cs ->+ Ecto.Changeset.add_error(cs, field, message)+ end)++ changeset =+ case opts[:action] do+ nil -> changeset+ action -> Map.put(changeset, :action, action)+ end++ assign(socket, form: to_form(changeset, as: :form))+ end++ defp submit_label(:team), do: "Move site"+ defp submit_label(:my_team), do: "Move site"+ defp submit_label(_), do: "Send transfer request"++ defp change_team_error_message(:no_plan, false = _my_team?) do+ "This team doesn't have a subscription. Please start a subscription for the team first and then try moving the site again."+ end++ defp change_team_error_message(:no_plan, true = _my_team?) do+ "You don't have a subscription. Please start a subscription first and then try moving the site again."+ end++ defp change_team_error_message({:over_plan_limits, _}, false = _my_team?) do+ "This site's usage exceeds the destination team's subscription limits. Upgrade the team's subscription to continue."+ end++ defp change_team_error_message({:over_plan_limits, _}, true = _my_team?) do+ "This site's usage exceeds your subscription limits. Upgrade your subscription to continue."+ end++ defp change_team_error_message(_, false = _my_team?) do+ "Sorry, this team cannot be used."+ end++ defp change_team_error_message(_, true = _my_team?) do+ "Sorry, My personal sites cannot be used."+ end+enddiff --git a/lib/plausible_web/live/site_transfer_settings/form.ex b/lib/plausible_web/live/site_transfer_settings/form.exnew file mode 100644index 0000000000..3988435309--- /dev/null+++ b/lib/plausible_web/live/site_transfer_settings/form.ex@@ -0,0 +1,36 @@+defmodule PlausibleWeb.Live.SiteTransferSettings.Form do+ @moduledoc """+ Form schema used by site transfer settings live view.+ """++ use Ecto.Schema+ import Ecto.Changeset++ @primary_key false+ embedded_schema do+ field :destination, Ecto.Enum, values: [:team, :my_team, :account]+ field :team_identifier, :string+ field :email, :string+ field :my_team_available, :boolean, default: false+ end++ def changeset(params) do+ %__MODULE__{}+ |> cast(params, [:destination, :team_identifier, :my_team_available, :email])+ |> validate_required(:destination)+ |> validate_destination_fields()+ end++ defp validate_destination_fields(changeset) do+ case get_field(changeset, :destination) do+ :team ->+ validate_required(changeset, :team_identifier, message: "Please select a team")++ :account ->+ validate_required(changeset, :email, message: "Please enter an email address")++ :my_team ->+ changeset+ end+ end+enddiff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.exindex aea99bae0c..572537e65f 100644--- a/lib/plausible_web/router.ex+++ b/lib/plausible_web/router.ex@@ -597,12 +597,6 @@ defmodule PlausibleWeb.Router dodelete "/sites/:domain/invitations/:invitation_id", InvitationController, :remove_invitation- get "/sites/:domain/transfer-ownership", Site.MembershipController, :transfer_ownership_form- post "/sites/:domain/transfer-ownership", Site.MembershipController, :transfer_ownership-- get "/sites/:domain/change-team", Site.MembershipController, :change_team_form- post "/sites/:domain/change-team", Site.MembershipController, :change_team-put "/sites/:domain/memberships/u/:id/role/:new_role",Site.MembershipController,:update_role_by_userdiff --git a/lib/plausible_web/templates/site/membership/change_team_form.html.heex b/lib/plausible_web/templates/site/membership/change_team_form.html.heexdeleted file mode 100644index f306820969..0000000000--- a/lib/plausible_web/templates/site/membership/change_team_form.html.heex+++ /dev/null@@ -1,24 +0,0 @@-<.focus_box>- <:title>- Change the team of {@site.domain}- </:title>- <:subtitle>- Choose the team you'd like to move the site to. The new team must have a sufficient subscription plan.- </:subtitle>- <.form :let={f} for={@conn} action={Routes.membership_path(@conn, :change_team, @site.domain)}>- <div class="my-6">- <.input- type="select"- options={@transferable_teams}- field={f[:team_identifier]}- label="Destination Team"- required="true"- />- <%= if @conn.assigns[:error] do %>- <div class="text-red-500 mt-4">{@conn.assigns[:error]}</div>- <% end %>- </div>-- <.button type="submit" class="w-full" mt?={false}>Change team</.button>- </.form>-</.focus_box>diff --git a/lib/plausible_web/templates/site/membership/transfer_ownership_form.html.heex b/lib/plausible_web/templates/site/membership/transfer_ownership_form.html.heexdeleted file mode 100644index 489777e641..0000000000--- a/lib/plausible_web/templates/site/membership/transfer_ownership_form.html.heex+++ /dev/null@@ -1,36 +0,0 @@-<.focus_box>- <:title>- Transfer ownership of {@site.domain}- </:title>- <:subtitle>- Enter the email address of the new owner. We will contact them over email to- offer them the ownership of {@site.domain}. If they don't respond in 48- hours, the request will expire automatically. <br /><br />- Do note that a subscription plan is not transferred alongside the site. If- they accept the transfer request, the new owner will need to have an active- subscription. Your access will be downgraded to <b>guest editor</b>- and any other- member roles will stay the same.- </:subtitle>- <.form- :let={f}- for={@conn}- action={Routes.membership_path(@conn, :transfer_ownership, @site.domain)}- >- <%= if @conn.assigns[:error] do %>- <div class="text-red-500 text-xs mt-1">{@conn.assigns[:error]}</div>- <% end %>-- <div class="my-6">- <.input- type="email"- field={f[:email]}- label="Email address"- placeholder="[email protected]"- required="true"- />- </div>-- <.button type="submit" class="w-full" mt?={false}>Request transfer</.button>- </.form>-</.focus_box>diff --git a/lib/plausible_web/templates/site/settings_danger_zone.html.heex b/lib/plausible_web/templates/site/settings_danger_zone.html.heexindex 3861992735..ed0bbd96c4 100644--- a/lib/plausible_web/templates/site/settings_danger_zone.html.heex+++ b/lib/plausible_web/templates/site/settings_danger_zone.html.heex@@ -3,30 +3,12 @@</.notice><.settings_tiles>- <.tile>- <:title>Transfer site ownership</:title>- <:subtitle>Transfer ownership of the site to a different account.</:subtitle>- <.button_link- href={Routes.membership_path(@conn, :transfer_ownership_form, @site.domain)}- theme="danger"- mt?={false}- >- Transfer {@site.domain} ownership- </.button_link>- </.tile>-- <.tile :if={Enum.count(Plausible.Teams.Users.teams(@current_user, roles: [:owner, :admin])) > 1}>- <:title>Change Teams</:title>- <:subtitle>Move the site to another team that you are a member of</:subtitle>- <.button_link- href={Routes.membership_path(@conn, :change_team_form, @site.domain)}- theme="danger"- >- Change {@site.domain} team- </.button_link>- </.tile>+ {live_render(@conn, PlausibleWeb.Live.SiteTransferSettings,+ id: "site-transfer-settings",+ session: %{"domain" => @site.domain}+ )}- <.tile>+ <.tile docs="reset-site-data"><:title>Reset stats</:title><:subtitle>Reset all stats but keep the site configuration intact.</:subtitle><.button_link@@ -40,7 +22,7 @@</.button_link></.tile>- <.tile>+ <.tile docs="delete-site-data"><:title>Delete site</:title><:subtitle>Permanently delete all stats and site settings.</:subtitle><.button_linkdiff --git a/test/plausible_web/controllers/site/membership_controller_test.exs b/test/plausible_web/controllers/site/membership_controller_test.exsindex a5c0138d27..cda8f96496 100644--- a/test/plausible_web/controllers/site/membership_controller_test.exs+++ b/test/plausible_web/controllers/site/membership_controller_test.exs@@ -90,7 +90,9 @@ defmodule PlausibleWeb.Site.MembershipControllerTest donew_owner = new_user()- post(conn, "/sites/#{site.domain}/transfer-ownership", %{email: new_owner.email})+ {:ok, _invitation} =+ Plausible.Teams.Invitations.InviteToSite.invite(site, user, new_owner.email, :owner)+assert_site_transfer(site, new_owner.email)conn =@@ -201,91 +203,6 @@ defmodule PlausibleWeb.Site.MembershipControllerTest doendend- describe "GET /sites/:domain/transfer-ownership" do- test "shows ownership transfer form", %{conn: conn, user: user} do- site = new_site(owner: user)-- conn = get(conn, "/sites/#{site.domain}/transfer-ownership")-- assert html_response(conn, 200) =~ "Transfer ownership of"- end- end-- describe "POST /sites/:domain/transfer-ownership" do- test "creates invitation with :owner role", %{conn: conn, user: user} do- site = new_site(owner: user)-- conn =- post(conn, "/sites/#{site.domain}/transfer-ownership", %{email: "[email protected]"})-- assert_site_transfer(site, "[email protected]")-- assert redirected_to(conn) == "/#{URI.encode_www_form(site.domain)}/settings/people"- end-- test "sends ownership transfer email for new user", %{conn: conn, user: user} do- site = new_site(owner: user)-- post(conn, "/sites/#{site.domain}/transfer-ownership", %{email: "[email protected]"})-- assert_email_delivered_with(- to: [nil: "[email protected]"],- subject: @subject_prefix <> "Request to transfer ownership of #{site.domain}"- )- end-- test "sends invitation email for existing user", %{conn: conn, user: user} do- existing_user = insert(:user)- site = new_site(owner: user)-- post(conn, "/sites/#{site.domain}/transfer-ownership", %{email: existing_user.email})-- assert_email_delivered_with(- to: [nil: existing_user.email],- subject: @subject_prefix <> "Request to transfer ownership of #{site.domain}"- )- end-- test "fails to transfer ownership to a foreign domain", %{conn: conn, user: user} do- new_site(owner: user)- foreign_site = new_site()-- conn =- post(conn, "/sites/#{foreign_site.domain}/transfer-ownership", %{- email: "[email protected]"- })-- assert conn.status == 404- end-- test "fails to transfer ownership to invited user with proper error message", ctx do- %{conn: conn, user: user} = ctx- site = new_site(owner: user)- invited = "[email protected]"-- # invite a user but don't join-- conn =- post(conn, "/sites/#{site.domain}/memberships/invite", %{- email: invited,- role: "editor"- })-- conn = get(recycle(conn), redirected_to(conn, 302))-- assert html_response(conn, 200) =~- "#{invited} has been invited to #{site.domain} as an editor"-- # transferring ownership to that domain now fails-- conn = post(conn, "/sites/#{site.domain}/transfer-ownership", %{email: invited})- conn = get(recycle(conn), redirected_to(conn, 302))- html = html_response(conn, 200)- assert html =~ "Transfer error"- assert html =~ "Invitation has already been sent"- end- end-describe "PUT /sites/memberships/:id/role/:new_role" dotest "updates a site member's role by user id", %{conn: conn, user: user} dosite = new_site(owner: user)diff --git a/test/plausible_web/controllers/site_controller_test.exs b/test/plausible_web/controllers/site_controller_test.exsindex e603dceb62..bb76d271a8 100644--- a/test/plausible_web/controllers/site_controller_test.exs+++ b/test/plausible_web/controllers/site_controller_test.exs@@ -1887,130 +1887,15 @@ defmodule PlausibleWeb.SiteControllerTest doendend- describe "change team" do+ describe "settings danger zone" dosetup [:create_user, :log_in, :create_site]- test "no change team section appears when <1 team", %{conn: conn, site: site} do+ test "renders the transfer tile", %{conn: conn, site: site} doconn = get(conn, Routes.site_path(conn, :settings_danger_zone, site.domain))html = html_response(conn, 200)assert html =~ "Danger zone"+ assert html =~ "Transfer site"assert html =~ "Delete #{site.domain}"- refute html =~ "Change #{site.domain} team"- end-- test "change team section appears when >1 team", %{user: user, conn: conn, site: site} do- join_2nd_team(user)-- conn = get(conn, Routes.site_path(conn, :settings_danger_zone, site.domain))- html = html_response(conn, 200)- assert html =~ "Danger zone"- assert html =~ "Delete #{site.domain}"- assert html =~ "Change #{site.domain} team"- end-- test "change team form renders", %{user: user, conn: conn, site: site} do- join_2nd_team(user)-- conn = get(conn, Routes.membership_path(conn, :change_team_form, site.domain))- html = html_response(conn, 200)- assert html =~ "Change the team of #{site.domain}"-- assert element_exists?(- html,- ~s|form[action="#{Routes.membership_path(conn, :change_team, site.domain)}"]|- )-- assert element_exists?(html, ~s|button[type=submit]|)- end-- @tag :ee_only- test "change team form error: destination team has no subscription", %{- user: user,- conn: conn,- site: site- } do- team2 = join_2nd_team(user)-- conn =- post(- conn,- Routes.membership_path(conn, :change_team, site.domain,- team_identifier: team2.identifier- )- )-- html = html_response(conn, 200)- assert text(html) =~ "This team doesn't have a subscription"- end-- @tag :ee_only- test "change team form error: subscription insufficient", %{- user: user,- conn: conn,- site: site- } do- team2 = join_2nd_team(user, subscribe?: true)-- generate_usage_for(site, 11_000, NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -5))- generate_usage_for(site, 11_000, NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -35))-- conn =- post(- conn,- Routes.membership_path(conn, :change_team, site.domain,- team_identifier: team2.identifier- )- )-- html = html_response(conn, 200)-- assert text(html) =~ "This site's usage is over the limits of the team's subscription"- end-- test "change team form error: unknown team identifier", %{- conn: conn,- site: site- } do- assert_raise Ecto.NoResultsError, fn ->- post(- conn,- Routes.membership_path(conn, :change_team, site.domain,- team_identifier: Ecto.UUID.generate()- )- )- end- end-- test "successfully changes team", %{- user: user,- conn: conn,- site: site- } do- team2 = join_2nd_team(user, subscribe?: true)-- conn =- post(- conn,- Routes.membership_path(conn, :change_team, site.domain,- team_identifier: team2.identifier- )- )-- assert redirected_to(conn) == "/sites?__team=#{team2.identifier}"- assert Phoenix.Flash.get(conn.assigns.flash, :success) =~ "Site team was changed"- end-- defp join_2nd_team(user, opts \\ []) do- another = new_user()- new_site(owner: another)- team2 = team_of(another)- add_member(team2, user: user, role: :admin)-- if opts[:subscribe?] do- subscribe_to_growth_plan(another)- end-- team2endendenddiff --git a/test/plausible_web/live/site_transfer_settings_test.exs b/test/plausible_web/live/site_transfer_settings_test.exsnew file mode 100644index 0000000000..36c60f63b9--- /dev/null+++ b/test/plausible_web/live/site_transfer_settings_test.exs@@ -0,0 +1,540 @@+defmodule PlausibleWeb.Live.SiteTransferSettingsTest do+ use PlausibleWeb.ConnCase, async: false+ use Plausible.Repo+ use Bamboo.Test, shared: true++ import Phoenix.LiveViewTest++ @subject_prefix if ee?(), do: "[Plausible Analytics] ", else: "[Plausible CE] "++ setup [:create_user, :log_in, :create_site]++ describe "mount" do+ test "renders the Team radio as disabled when user has no other team", %{+ conn: conn,+ site: site+ } do+ {:ok, _lv, html} = get_liveview(conn, site)++ assert html =~ "Transfer site"+ assert html =~ "Move this site to another team or Plausible account"+ assert html =~ "Another Plausible account"++ assert element_exists?(html, ~s|input[name="form[destination]"][value="account"]|)++ assert element_exists?(+ html,+ ~s|input[name="form[destination]"][value="team"][disabled]|+ )++ assert text_of_element(html, "#site-transfer-form") =~+ "You aren't a member of any other teams"++ assert element_exists?(+ html,+ ~s|input[name="form[destination]"][value="my_team"][disabled]|+ )++ assert text_of_element(html, "#site-transfer-form") =~+ "The site is already in your personal sites"+ end++ test "renders team destinations enabled when the user has another team", %{+ conn: conn,+ user: user,+ site: site+ } do+ _team2 = join_2nd_team(user)++ {:ok, _lv, html} = get_liveview(conn, site)++ assert element_exists?(html, ~s|input[name="form[destination]"][value="team"]|)+ assert element_exists?(html, ~s|input[name="form[destination]"][value="account"]|)++ refute element_exists?(+ html,+ ~s|input[name="form[destination]"][value="team"][disabled]|+ )++ assert element_exists?(+ html,+ ~s|input[name="form[destination]"][value="my_team"][disabled]|+ )++ assert html =~ "The site will immediately move to the selected team"+ refute html =~ "[email protected]"++ refute text_of_element(html, "#site-transfer-form") =~+ "You aren't a member of any other teams"+ end++ test "renders personal team destination enabled when the user transfers from another team", %{+ conn: conn,+ user: user+ } do+ _team2 = join_2nd_team(user)++ owner = new_user()+ site = new_site(owner: owner)+ add_member(site.team, user: user, role: :admin)++ {:ok, _lv, html} = get_liveview(conn, site)++ assert element_exists?(html, ~s|input[name="form[destination]"][value="team"]|)+ assert element_exists?(html, ~s|input[name="form[destination]"][value="account"]|)+ assert element_exists?(html, ~s|input[name="form[destination]"][value="my_team"]|)++ refute element_exists?(+ html,+ ~s|input[name="form[destination]"][value="team"][disabled]|+ )++ refute element_exists?(+ html,+ ~s|input[name="form[destination]"][value="my_team"][disabled]|+ )++ assert html =~ "The site will immediately move to the selected team"+ refute html =~ "[email protected]"++ refute text_of_element(html, "#site-transfer-form") =~+ "You aren't a member of any other teams"++ refute text_of_element(html, "#site-transfer-form") =~+ "The site is already in your personal sites"+ end++ test "renders personal team destination disabled if user does not have one", %{+ conn: conn,+ user: user,+ site: site+ } do+ _team2 = join_2nd_team(user)++ Repo.delete!(site.team)++ owner = new_user()+ site = new_site(owner: owner)+ add_member(site.team, user: user, role: :admin)++ {:ok, _lv, html} = get_liveview(conn, site)++ assert element_exists?(html, ~s|input[name="form[destination]"][value="team"]|)+ assert element_exists?(html, ~s|input[name="form[destination]"][value="account"]|)+ assert element_exists?(html, ~s|input[name="form[destination]"][value="my_team"]|)++ refute element_exists?(+ html,+ ~s|input[name="form[destination]"][value="team"][disabled]|+ )++ assert element_exists?(+ html,+ ~s|input[name="form[destination]"][value="my_team"][disabled]|+ )++ assert text_of_element(html, "#site-transfer-form") =~+ "You don't have an active subscription"+ end++ test "Team destination is preselected when available", %{+ conn: conn,+ user: user,+ site: site+ } do+ _team2 = join_2nd_team(user)++ {:ok, _lv, html} = get_liveview(conn, site)++ assert element_exists?(+ html,+ ~s|input[name="form[destination]"][value="team"][checked]|+ )++ refute element_exists?(+ html,+ ~s|input[name="form[destination]"][value="account"][checked]|+ )++ refute element_exists?(+ html,+ ~s|input[name="form[destination]"][value="my_team"][checked]|+ )+ end++ test "Personal team destination is preselected if available and team destination is unavailable",+ %{+ conn: conn,+ user: user+ } do+ owner = new_user()+ site = new_site(owner: owner)+ add_member(site.team, user: user, role: :admin)++ {:ok, _lv, html} = get_liveview(conn, site)++ refute element_exists?(+ html,+ ~s|input[name="form[destination]"][value="team"][checked]|+ )++ refute element_exists?(+ html,+ ~s|input[name="form[destination]"][value="account"][checked]|+ )++ assert element_exists?(+ html,+ ~s|input[name="form[destination]"][value="my_team"][checked]|+ )+ end+ end++ describe "switching destination" do+ test "changing to Account hides team picker and shows email input", %{+ conn: conn,+ user: user,+ site: site+ } do+ _team2 = join_2nd_team(user)++ {:ok, lv, _html} = get_liveview(conn, site)++ html =+ lv+ |> element("#site-transfer-form")+ |> render_change(%{"form" => %{"destination" => "account"}})++ assert html =~ "Email address"+ assert html =~ "[email protected]"+ refute html =~ "The site will immediately move to the selected team"++ assert text_of_attr(html, ~s|button[type=submit]|, "phx-disable-with") ==+ "Transferring..."++ assert text_of_element(html, ~s|button[type=submit]|) =~ "Send transfer request"+ end++ test "changing to Team hides email and shows team picker", %{+ conn: conn,+ user: user,+ site: site+ } do+ _team2 = join_2nd_team(user)++ {:ok, lv, _html} = get_liveview(conn, site)++ lv+ |> element("#site-transfer-form")+ |> render_change(%{"form" => %{"destination" => "account"}})++ html =+ lv+ |> element("#site-transfer-form")+ |> render_change(%{"form" => %{"destination" => "team"}})++ assert html =~ "Select a team"+ refute html =~ "Email address"+ assert text_of_element(html, ~s|button[type=submit]|) =~ "Move site"+ end++ test "changing to My personal sites hides everything else", %{+ conn: conn,+ user: user+ } do+ _team2 = join_2nd_team(user)++ site = new_site()+ add_member(site.team, user: user, role: :admin)++ {:ok, lv, _html} = get_liveview(conn, site)++ lv+ |> element("#site-transfer-form")+ |> render_change(%{"form" => %{"destination" => "account"}})++ html =+ lv+ |> element("#site-transfer-form")+ |> render_change(%{"form" => %{"destination" => "my_team"}})++ refute html =~ "Select a team"+ refute html =~ "Email address"++ assert text_of_element(html, ~s|button[type=submit]|) =~ "Move site"+ end+ end++ describe "submitting (account destination)" do+ test "creates a site transfer and redirects to settings/people", %{+ conn: conn,+ site: site+ } do+ {:ok, lv, _html} = get_liveview(conn, site)++ lv+ |> element("#site-transfer-form")+ |> render_submit(%{+ "form" => %{"destination" => "account", "email" => "[email protected]"}+ })++ assert_redirect(lv, "/#{URI.encode_www_form(site.domain)}/settings/people")++ assert_email_delivered_with(+ to: [nil: "[email protected]"],+ subject: @subject_prefix <> "Request to transfer ownership of #{site.domain}"+ )+ end++ test "renders an inline error when the user has already been invited", %{+ conn: conn,+ user: user,+ site: site+ } do+ invited = "[email protected]"++ {:ok, _invitation} =+ Plausible.Teams.Invitations.InviteToSite.invite(site, user, invited, :editor)++ {:ok, lv, _html} = get_liveview(conn, site)++ html =+ lv+ |> element("#site-transfer-form")+ |> render_submit(%{+ "form" => %{"destination" => "account", "email" => invited}+ })++ assert html =~ "Invitation has already been sent"+ end++ test "validates that an email is required", %{conn: conn, site: site} do+ {:ok, lv, _html} = get_liveview(conn, site)++ html =+ lv+ |> element("#site-transfer-form")+ |> render_submit(%{"form" => %{"destination" => "account", "email" => ""}})++ assert html =~ "Please enter an email address"+ end+ end++ describe "submitting (team destination)" do+ test "successfully changes the site's team and redirects to sites listing", %{+ conn: conn,+ user: user,+ site: site+ } do+ team2 = join_2nd_team(user, subscribe?: true)++ {:ok, lv, _html} = get_liveview(conn, site)++ lv+ |> element("#site-transfer-form")+ |> render_submit(%{+ "form" => %{"destination" => "team", "team_identifier" => team2.identifier}+ })++ assert_redirect(lv, "/sites?__team=#{team2.identifier}")++ assert Plausible.Repo.reload!(site).team_id == team2.id+ end++ @tag :ee_only+ test "renders an inline error when the destination team has no subscription", %{+ conn: conn,+ user: user,+ site: site+ } do+ team2 = join_2nd_team(user)++ {:ok, lv, _html} = get_liveview(conn, site)++ html =+ lv+ |> element("#site-transfer-form")+ |> render_submit(%{+ "form" => %{"destination" => "team", "team_identifier" => team2.identifier}+ })++ assert text_of_element(html, "#site-transfer-form") =~+ "This team doesn't have a subscription"+ end++ @tag :ee_only+ test "renders an inline error when usage exceeds destination team's limits", %{+ conn: conn,+ user: user,+ site: site+ } do+ team2 = join_2nd_team(user, subscribe?: true)++ generate_usage_for(site, 11_000, NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -5))+ generate_usage_for(site, 11_000, NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -35))++ {:ok, lv, _html} = get_liveview(conn, site)++ html =+ lv+ |> element("#site-transfer-form")+ |> render_submit(%{+ "form" => %{"destination" => "team", "team_identifier" => team2.identifier}+ })++ assert text_of_element(html, "#site-transfer-form") =~+ "This site's usage exceeds the destination team's subscription limits"+ end++ test "validates that a team must be selected", %{conn: conn, user: user, site: site} do+ _team2 = join_2nd_team(user)++ {:ok, lv, _html} = get_liveview(conn, site)++ html =+ lv+ |> element("#site-transfer-form")+ |> render_submit(%{+ "form" => %{"destination" => "team", "team_identifier" => ""}+ })++ assert html =~ "Please select a team"+ end++ test "rejects an unknown team identifier", %{conn: conn, user: user, site: site} do+ _team2 = join_2nd_team(user)++ {:ok, lv, _html} = get_liveview(conn, site)++ html =+ lv+ |> element("#site-transfer-form")+ |> render_submit(%{+ "form" => %{+ "destination" => "team",+ "team_identifier" => Ecto.UUID.generate()+ }+ })++ assert html =~ "Please select a team"+ end++ test "rejects a team identifier the user has no transfer permissions for", %{+ conn: conn,+ user: user,+ site: site+ } do+ _team2 = join_2nd_team(user)+ team3 = join_2nd_team(user, role: :viewer)++ {:ok, lv, _html} = get_liveview(conn, site)++ html =+ lv+ |> element("#site-transfer-form")+ |> render_submit(%{+ "form" => %{+ "destination" => "team",+ "team_identifier" => team3.identifier+ }+ })++ assert html =~ "Please select a team"+ end+ end++ describe "submitting (my_team destination)" do+ test "successfully changes the site's team to personal team and redirects to sites listing",+ %{+ conn: conn,+ user: user+ } do+ owner = new_user()+ site = new_site(owner: owner)+ add_member(site.team, user: user, role: :admin)++ subscribe_to_growth_plan(user)+ my_team = team_of(user)++ {:ok, lv, _html} = get_liveview(conn, site)++ lv+ |> element("#site-transfer-form")+ |> render_submit(%{+ "form" => %{"destination" => "my_team", "my_team_available" => "true"}+ })++ assert_redirect(lv, "/sites?__team=#{my_team.identifier}")++ assert Plausible.Repo.reload!(site).team_id == my_team.id+ end++ @tag :ee_only+ test "renders an inline error when personal team has no subscription", %{+ conn: conn,+ user: user+ } do+ owner = new_user()+ site = new_site(owner: owner)+ add_member(site.team, user: user, role: :admin)++ {:ok, lv, _html} = get_liveview(conn, site)++ html =+ lv+ |> element("#site-transfer-form")+ |> render_submit(%{+ "form" => %{"destination" => "my_team", "my_team_available" => "true"}+ })++ assert text_of_element(html, "#site-transfer-form") =~ "You don't have a subscription"+ end++ @tag :ee_only+ test "renders an inline error when usage exceeds destination personal team's limits", %{+ conn: conn,+ user: user+ } do+ owner = new_user()+ site = new_site(owner: owner)+ add_member(site.team, user: user, role: :admin)++ subscribe_to_growth_plan(user)++ generate_usage_for(site, 11_000, NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -5))+ generate_usage_for(site, 11_000, NaiveDateTime.utc_now() |> NaiveDateTime.shift(day: -35))++ {:ok, lv, _html} = get_liveview(conn, site)++ html =+ lv+ |> element("#site-transfer-form")+ |> render_submit(%{+ "form" => %{"destination" => "my_team", "my_team_available" => "true"}+ })++ assert text_of_element(html, "#site-transfer-form") =~+ "This site's usage exceeds your subscription limits"+ end+ end++ defp get_liveview(conn, site) do+ conn = assign(conn, :live_module, PlausibleWeb.Live.SiteTransferSettings)+ live(conn, "/#{URI.encode_www_form(site.domain)}/settings/danger-zone")+ end++ defp join_2nd_team(user, opts \\ []) do+ role = Keyword.get(opts, :role, :admin)+ another = new_user()++ if opts[:subscribe?] do+ subscribe_to_growth_plan(another)+ end++ new_site(owner: another)+ team2 = another |> team_of() |> Plausible.Teams.complete_setup()+ add_member(team2, user: user, role: role)++ team2+ end+end