diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c23f77f5..9cc835572 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,9 @@ All notable changes to this project will be documented in this file. - Adds Gravatar profile image to navbar - Enforce email reverification on update - Add Plugins API Tokens provisioning UI +- Add searching sites by domain in /sites view +- Add last 24h plots to /sites view +- Add site pinning to /sites view ### Removed - Removed the nested custom event property breakdown UI when filtering by a goal in Goal Conversions diff --git a/assets/js/dashboard/site-switcher.js b/assets/js/dashboard/site-switcher.js index 2ea52a8c6..326be937b 100644 --- a/assets/js/dashboard/site-switcher.js +++ b/assets/js/dashboard/site-switcher.js @@ -131,7 +131,7 @@ export default class SiteSwitcher extends React.Component { domain === this.props.site.domain ? 'font-medium text-gray-900 dark:text-gray-100 cursor-default font-bold' : 'hover:bg-gray-100 dark:hover:bg-gray-900 hover:text-gray-900 dark:hover:text-gray-100 focus:outline-none focus:bg-gray-100 dark:focus:bg-gray-900 focus:text-gray-900 dark:focus:text-gray-100' - const showHotkey = !this.props.loggedIn + const showHotkey = this.props.loggedIn && this.state.sites.length > 1 return ( - {showHotkey ? index < 9 && {index + 1} : null} + {showHotkey && index < 9 ? {index + 1} : null} ) } diff --git a/assets/js/liveview/phx_events.js b/assets/js/liveview/phx_events.js index c36abf3fe..991f96f01 100644 --- a/assets/js/liveview/phx_events.js +++ b/assets/js/liveview/phx_events.js @@ -5,3 +5,9 @@ window.addEventListener(`phx:update-value`, (e) => { el.dispatchEvent(new Event("input", { bubbles: true })) } }) + +window.addEventListener(`phx:js-exec`, ({ detail }) => { + document.querySelectorAll(detail.to).forEach(el => { + window.liveSocket.execJS(el, el.getAttribute(detail.attr)) + }) +}) diff --git a/lib/plausible/site.ex b/lib/plausible/site.ex index fd650bb8d..f18fc5b03 100644 --- a/lib/plausible/site.ex +++ b/lib/plausible/site.ex @@ -50,9 +50,10 @@ defmodule Plausible.Site do field :from_cache?, :boolean, virtual: true, default: false # Used in the context of paginated sites list to order in relation to - # user's membership state. Currently it can be either "invitation" - # or "site", where invitations are first. - field :list_type, :string, virtual: true + # user's membership state. Currently it can be either "invitation", + # "pinned_site" or "site", where invitations are first. + field :entry_type, :string, virtual: true + field :pinned_at, :naive_datetime, virtual: true timestamps() end diff --git a/lib/plausible/site/user_preference.ex b/lib/plausible/site/user_preference.ex new file mode 100644 index 000000000..89e80e2f2 --- /dev/null +++ b/lib/plausible/site/user_preference.ex @@ -0,0 +1,30 @@ +defmodule Plausible.Site.UserPreference do + @moduledoc """ + User-specific site preferences schema + """ + + use Ecto.Schema + import Ecto.Changeset + + @type t() :: %__MODULE__{} + + @options [:pinned_at] + + schema "site_user_preferences" do + field :pinned_at, :naive_datetime + + belongs_to :user, Plausible.Auth.User + belongs_to :site, Plausible.Site + + timestamps() + end + + defmacro options, do: @options + + def changeset(user, site, attrs \\ %{}) do + %__MODULE__{} + |> cast(attrs, @options) + |> put_assoc(:user, user) + |> put_assoc(:site, site) + end +end diff --git a/lib/plausible/sites.ex b/lib/plausible/sites.ex index 4576450de..f448ae466 100644 --- a/lib/plausible/sites.ex +++ b/lib/plausible/sites.ex @@ -1,7 +1,18 @@ defmodule Plausible.Sites do - alias Plausible.{Repo, Site, Site.SharedLink, Billing.Quota} + @moduledoc """ + Sites context functions. + """ + import Ecto.Query + alias Plausible.Auth + alias Plausible.Billing.Quota + alias Plausible.Repo + alias Plausible.Site + alias Plausible.Site.SharedLink + + require Plausible.Site.UserPreference + @type list_opt() :: {:filter_by_domain, String.t()} def get_by_domain(domain) do @@ -12,51 +23,128 @@ defmodule Plausible.Sites do Repo.get_by!(Site, domain: domain) end - @spec list(Plausible.Auth.User.t(), map(), [list_opt()]) :: Scrivener.Page.t() + @spec toggle_pin(Auth.User.t(), Site.t()) :: + {:ok, Site.UserPreference.t()} | {:error, :too_many_pins} + def toggle_pin(user, site) do + pinned_at = + if site.pinned_at do + nil + else + NaiveDateTime.utc_now() + end + + with :ok <- check_user_pin_limit(user, pinned_at) do + {:ok, set_option(user, site, :pinned_at, pinned_at)} + end + end + + @pins_limit 9 + + defp check_user_pin_limit(_user, nil), do: :ok + + defp check_user_pin_limit(user, _) do + pins_count = + from(up in Site.UserPreference, + where: up.user_id == ^user.id and not is_nil(up.pinned_at) + ) + |> Repo.aggregate(:count) + + if pins_count + 1 > @pins_limit do + {:error, :too_many_pins} + else + :ok + end + end + + @spec set_option(Auth.User.t(), Site.t(), atom(), any()) :: Site.UserPreference.t() + def set_option(user, site, option, value) when option in Site.UserPreference.options() do + get_for_user!(user.id, site.domain) + + user + |> Site.UserPreference.changeset(site, %{option => value}) + |> Repo.insert!( + conflict_target: [:user_id, :site_id], + # This way of conflict handling enables doing upserts of options leaving + # existing, unrelated values intact. + on_conflict: from(p in Site.UserPreference, update: [set: [{^option, ^value}]]), + returning: true + ) + end + + @spec list(Auth.User.t(), map(), [list_opt()]) :: Scrivener.Page.t() def list(user, pagination_params, opts \\ []) do domain_filter = Keyword.get(opts, :filter_by_domain) - base_query = - from(s in Plausible.Site, - left_join: sm in assoc(s, :memberships), - on: sm.user_id == ^user.id, + from(s in Site, + left_join: up in Site.UserPreference, + on: up.site_id == s.id and up.user_id == ^user.id, + inner_join: sm in assoc(s, :memberships), + on: sm.user_id == ^user.id, + select: %{ + s + | pinned_at: selected_as(up.pinned_at, :pinned_at), + entry_type: + selected_as( + fragment( + """ + CASE + WHEN ? IS NOT NULL THEN 'pinned_site' + ELSE 'site' + END + """, + up.pinned_at + ), + :entry_type + ) + }, + order_by: [asc: selected_as(:entry_type), desc: selected_as(:pinned_at), asc: s.domain], + preload: [memberships: sm] + ) + |> maybe_filter_by_domain(domain_filter) + |> Repo.paginate(pagination_params) + end + + @spec list_with_invitations(Auth.User.t(), map(), [list_opt()]) :: Scrivener.Page.t() + def list_with_invitations(user, pagination_params, opts \\ []) do + domain_filter = Keyword.get(opts, :filter_by_domain) + + result = + from(s in Site, + left_join: up in Site.UserPreference, + on: up.site_id == s.id and up.user_id == ^user.id, left_join: i in assoc(s, :invitations), on: i.email == ^user.email, - where: not is_nil(i.id) or not is_nil(sm.id), + left_join: sm in assoc(s, :memberships), + on: sm.user_id == ^user.id, + where: not is_nil(sm.id) or not is_nil(i.id), select: %{ s - | list_type: - fragment( - """ - CASE WHEN ? IS NOT NULL THEN 'invitation' - ELSE 'site' + | pinned_at: selected_as(up.pinned_at, :pinned_at), + entry_type: + selected_as( + fragment( + """ + CASE + WHEN ? IS NOT NULL THEN 'invitation' + WHEN ? IS NOT NULL THEN 'pinned_site' + ELSE 'site' END - """, - i.id + """, + i.id, + up.pinned_at + ), + :entry_type ) - } - ) - - memberships_query = - from sm in Plausible.Site.Membership, - where: sm.user_id == ^user.id - - invitations_query = - from i in Plausible.Auth.Invitation, - where: i.email == ^user.email - - sites_query = - from(s in subquery(base_query), - order_by: [asc: s.list_type, asc: s.domain], - preload: [ - memberships: ^memberships_query, - invitations: ^invitations_query - ] + }, + order_by: [asc: selected_as(:entry_type), desc: selected_as(:pinned_at), asc: s.domain], + preload: [memberships: sm, invitations: i] ) |> maybe_filter_by_domain(domain_filter) + |> Repo.paginate(pagination_params) - result = Repo.paginate(sites_query, pagination_params) - + # Populating `site` preload on `invitation` + # without requesting it from database. + # Necessary for invitation modals logic. entries = Enum.map(result.entries, fn %{invitations: [invitation]} = site -> @@ -99,7 +187,7 @@ defmodule Plausible.Sites do defp maybe_start_trial(multi, user) do case user.trial_expiry_date do nil -> - changeset = Plausible.Auth.User.start_trial(user) + changeset = Auth.User.start_trial(user) Ecto.Multi.update(multi, :user, changeset) _ -> @@ -107,7 +195,7 @@ defmodule Plausible.Sites do end end - @spec stats_start_date(Plausible.Site.t()) :: Date.t() | nil + @spec stats_start_date(Site.t()) :: Date.t() | nil @doc """ Returns the date of the first event of the given site, or `nil` if the site does not have stats yet. @@ -156,7 +244,7 @@ defmodule Plausible.Sites do end def get_for_user!(user_id, domain, roles \\ [:owner, :admin, :viewer]) do - if :super_admin in roles and Plausible.Auth.is_super_admin?(user_id) do + if :super_admin in roles and Auth.is_super_admin?(user_id) do get_by_domain!(domain) else user_id @@ -166,7 +254,7 @@ defmodule Plausible.Sites do end def get_for_user(user_id, domain, roles \\ [:owner, :admin, :viewer]) do - if :super_admin in roles and Plausible.Auth.is_super_admin?(user_id) do + if :super_admin in roles and Auth.is_super_admin?(user_id) do get_by_domain(domain) else user_id diff --git a/lib/plausible_web/components/generic.ex b/lib/plausible_web/components/generic.ex index 7c72e0d22..5dcfa7886 100644 --- a/lib/plausible_web/components/generic.ex +++ b/lib/plausible_web/components/generic.ex @@ -182,6 +182,7 @@ defmodule PlausibleWeb.Components.Generic do attr :new_tab, :boolean, default: false attr :class, :string, default: "" attr :id, :any, default: nil + attr :rest, :global slot :inner_block def unstyled_link(assigns) do @@ -198,6 +199,7 @@ defmodule PlausibleWeb.Components.Generic do href={@href} target="_blank" rel="noopener noreferrer" + {@rest} > <%= render_slot(@inner_block) %> diff --git a/lib/plausible_web/controllers/api/internal_controller.ex b/lib/plausible_web/controllers/api/internal_controller.ex index e8e58e5a8..80fb8e4d9 100644 --- a/lib/plausible_web/controllers/api/internal_controller.ex +++ b/lib/plausible_web/controllers/api/internal_controller.ex @@ -66,17 +66,7 @@ defmodule PlausibleWeb.Api.InternalController do end defp sites_for(user) do - Repo.all( - from( - s in Site, - join: sm in Site.Membership, - on: sm.site_id == s.id, - where: sm.user_id == ^user.id, - order_by: s.domain, - select: %{domain: s.domain}, - # there are keyboard shortcuts for switching between sites, hence 9 - limit: 9 - ) - ) + pagination = Sites.list(user, %{page_size: 9}) + Enum.map(pagination.entries, &%{domain: &1.domain}) end end diff --git a/lib/plausible_web/live/flash.ex b/lib/plausible_web/live/flash.ex index ed1008f37..384399011 100644 --- a/lib/plausible_web/live/flash.ex +++ b/lib/plausible_web/live/flash.ex @@ -9,19 +9,29 @@ defmodule PlausibleWeb.Live.Flash do def render(assigns) do ~H"""
-
- <.flash> +
+ <.flash :if={Flash.get(@flash, :success)}> <:icon> - <.icon_success :if={Flash.get(@flash, :success)} /> - <.icon_error :if={Flash.get(@flash, :error)} /> + <.icon_success /> - <:title :if={Flash.get(@flash, :success)}> + <:title> <%= Flash.get(@flash, :success_title) || "Success!" %> <:message> <%= Flash.get(@flash, :success) %> + <.flash :if={Flash.get(@flash, :error)}> + <:icon> + <.icon_error /> + + <:title> + <%= Flash.get(@flash, :error_title) || "Error!" %> + + <:message> + <%= Flash.get(@flash, :error) %> + +
+
diff --git a/lib/plausible_web/live/sites.ex b/lib/plausible_web/live/sites.ex index 29d4dc6e1..cd1298951 100644 --- a/lib/plausible_web/live/sites.ex +++ b/lib/plausible_web/live/sites.ex @@ -4,6 +4,7 @@ defmodule PlausibleWeb.Live.Sites do """ use Phoenix.LiveView + alias Phoenix.LiveView.JS use Phoenix.HTML import PlausibleWeb.Components.Generic @@ -52,12 +53,13 @@ defmodule PlausibleWeb.Live.Sites do def render(assigns) do invitations = assigns.sites.entries - |> Enum.filter(&(&1.list_type == "invitation")) + |> Enum.filter(&(&1.entry_type == "invitation")) |> Enum.flat_map(& &1.invitations) assigns = assign(assigns, :invitations, invitations) ~H""" + <.live_component id="embedded_liveview_flash" module={PlausibleWeb.Live.Flash} flash={@flash} />
Enum.into(%{}) |> Jason.encode!}}"} x-on:keydown.escape.window="invitationOpen = false" @@ -95,12 +97,12 @@ defmodule PlausibleWeb.Live.Sites do
    <%= for site <- @sites.entries do %> <.site - :if={site.list_type == "site"} + :if={site.entry_type in ["pinned_site", "site"]} site={site} hourly_stats={@hourly_stats[site.domain]} /> <.invitation - :if={site.list_type == "invitation"} + :if={site.entry_type == "invitation"} site={site} invitation={hd(site.invitations)} hourly_stats={@hourly_stats[site.domain]} @@ -118,7 +120,7 @@ defmodule PlausibleWeb.Live.Sites do Total of <%= @sites.total_entries %> sites <.invitation_modal - :if={Enum.any?(@sites.entries, &(&1.list_type == "invitation"))} + :if={Enum.any?(@sites.entries, &(&1.entry_type == "invitation"))} user={@user} />
@@ -172,6 +174,7 @@ defmodule PlausibleWeb.Live.Sites do ~H"""
  • @@ -203,7 +206,24 @@ defmodule PlausibleWeb.Live.Sites do def site(assigns) do ~H""" -
  • +
  • """ end + def ellipsis_menu(assigns) do + ~H""" +
    + + + + +
    + """ + end + + attr :rest, :global + + def icon_pin(assigns) do + ~H""" + + + + """ + end + attr :hourly_stats, :map, required: true def site_stats(assigns) do ~H""" -
    +
    -
    -
    +
    +