You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
analytics/lib/plausible/site/admin.ex

180 lines
4.7 KiB
Elixir

defmodule Plausible.SiteAdmin do
use Plausible.Repo
import Ecto.Query
def ordering(_schema) do
[desc: :inserted_at]
end
def search_fields(_schema) do
[
:domain,
members: [:name, :email]
]
end
def custom_index_query(_conn, _schema, query) do
from(r in query,
inner_join: o in assoc(r, :owner),
inner_join: m in assoc(r, :memberships),
preload: [owner: o, memberships: {m, :user}]
)
end
def form_fields(_) do
[
domain: %{update: :readonly},
timezone: %{choices: Plausible.Timezones.options()},
public: nil,
stats_start_date: nil,
ingest_rate_limit_scale_seconds: %{
help_text: "Time scale for which events rate-limiting is calculated. Default: 60"
},
ingest_rate_limit_threshold: %{
help_text:
"Keep empty to disable rate limiting, set to 0 to bar all events. Any positive number sets the limit."
}
]
end
def index(_) do
[
domain: nil,
inserted_at: %{name: "Created at", value: &format_date(&1.inserted_at)},
timezone: nil,
public: nil,
owner: %{value: &get_owner/1},
other_members: %{value: &get_other_members/1},
limits: %{
value: fn site ->
rate_limiting_status =
case site.ingest_rate_limit_threshold do
nil -> ""
0 -> "🛑 BLOCKED"
n -> "⏱ #{n}/#{site.ingest_rate_limit_scale_seconds}s (per server)"
end
owner = site.owner
owner_limits =
if owner.accept_traffic_until &&
Date.after?(Date.utc_today(), owner.accept_traffic_until) do
"💸 Rejecting traffic"
end
{:safe, Enum.join([rate_limiting_status, owner_limits], "<br/><br/>")}
end
}
]
end
def list_actions(_conn) do
[
transfer_ownership: %{
name: "Transfer ownership",
inputs: [
%{name: "email", title: "New Owner Email", default: nil}
],
action: fn conn, sites, params -> transfer_ownership(conn, sites, params) end
},
transfer_ownership_direct: %{
name: "Transfer ownership without invite",
inputs: [
%{name: "email", title: "New Owner Email", default: nil}
],
action: fn conn, sites, params -> transfer_ownership_direct(conn, sites, params) end
}
]
end
defp transfer_ownership(_conn, [], _params) do
{:error, "Please select at least one site from the list"}
end
defp transfer_ownership(conn, sites, %{"email" => email}) do
new_owner = Plausible.Auth.find_user_by(email: email)
inviter = conn.assigns[:current_user]
if new_owner do
Move limit enforcement to accepting site ownership transfer (#3612) * Move limit enforcement to accepting site ownerhsip transfer * enforce pageview limit on ownership transfer accept * Refactor plan limit check logic * Extract `ensure_can_take_ownership` to `Invitations` context and refactor * Improve styling of exceeded limits notice in invitation dialog and disable button * styling improvements to notice * make transfer_ownership return transfer to self error * do not allow transferring to user without active subscription WIP * Add missing typespec and improve existing ones * Fix formatting * Explicitly label direct match on function argument for clarity * Slightly refactor `CreateInvitation.bulk_transfer_ownership_direct` * Exclude quota enforcement tests from small build test suite * Remove unused return type from `invite_error()` union type * Do not block plan upgrade when there's pending ownership transfer * Don't block and only warn about missing features on transfer * Remove `x-init` attribute used for debugging * Add tests for `Quota.monthly_pageview_usage/2` * Test and improve site admin ownership transfer actions * Extend tests for `AcceptInvitation.transfer_ownership` * Test transfer ownership controller level accept action error cases * Test choosing plan by user without sites but with a pending ownership transfer * Test invitation x-data in sites LV * Remove sitelocker trigger in invitation acceptance code and simplify logic * Add Quota test for `user.allow_next_upgrade_override` being set * ignore pageview limit only when subscribing to plan * Use sandbox Paddle instance for staging * Use sandbox paddle key for staging and dev --------- Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>
3 years ago
result =
Plausible.Site.Memberships.bulk_create_invitation(
sites,
inviter,
new_owner.email,
:owner,
check_permissions: false
)
Move limit enforcement to accepting site ownership transfer (#3612) * Move limit enforcement to accepting site ownerhsip transfer * enforce pageview limit on ownership transfer accept * Refactor plan limit check logic * Extract `ensure_can_take_ownership` to `Invitations` context and refactor * Improve styling of exceeded limits notice in invitation dialog and disable button * styling improvements to notice * make transfer_ownership return transfer to self error * do not allow transferring to user without active subscription WIP * Add missing typespec and improve existing ones * Fix formatting * Explicitly label direct match on function argument for clarity * Slightly refactor `CreateInvitation.bulk_transfer_ownership_direct` * Exclude quota enforcement tests from small build test suite * Remove unused return type from `invite_error()` union type * Do not block plan upgrade when there's pending ownership transfer * Don't block and only warn about missing features on transfer * Remove `x-init` attribute used for debugging * Add tests for `Quota.monthly_pageview_usage/2` * Test and improve site admin ownership transfer actions * Extend tests for `AcceptInvitation.transfer_ownership` * Test transfer ownership controller level accept action error cases * Test choosing plan by user without sites but with a pending ownership transfer * Test invitation x-data in sites LV * Remove sitelocker trigger in invitation acceptance code and simplify logic * Add Quota test for `user.allow_next_upgrade_override` being set * ignore pageview limit only when subscribing to plan * Use sandbox Paddle instance for staging * Use sandbox paddle key for staging and dev --------- Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>
3 years ago
case result do
{:ok, _} ->
:ok
{:error, :transfer_to_self} ->
{:error, "User is already an owner of one of the sites"}
end
else
{:error, "User could not be found"}
end
end
defp transfer_ownership_direct(_conn, [], _params) do
{:error, "Please select at least one site from the list"}
end
defp transfer_ownership_direct(_conn, sites, %{"email" => email}) do
new_owner = Plausible.Auth.find_user_by(email: email)
if new_owner do
case Plausible.Site.Memberships.bulk_transfer_ownership_direct(sites, new_owner) do
Move limit enforcement to accepting site ownership transfer (#3612) * Move limit enforcement to accepting site ownerhsip transfer * enforce pageview limit on ownership transfer accept * Refactor plan limit check logic * Extract `ensure_can_take_ownership` to `Invitations` context and refactor * Improve styling of exceeded limits notice in invitation dialog and disable button * styling improvements to notice * make transfer_ownership return transfer to self error * do not allow transferring to user without active subscription WIP * Add missing typespec and improve existing ones * Fix formatting * Explicitly label direct match on function argument for clarity * Slightly refactor `CreateInvitation.bulk_transfer_ownership_direct` * Exclude quota enforcement tests from small build test suite * Remove unused return type from `invite_error()` union type * Do not block plan upgrade when there's pending ownership transfer * Don't block and only warn about missing features on transfer * Remove `x-init` attribute used for debugging * Add tests for `Quota.monthly_pageview_usage/2` * Test and improve site admin ownership transfer actions * Extend tests for `AcceptInvitation.transfer_ownership` * Test transfer ownership controller level accept action error cases * Test choosing plan by user without sites but with a pending ownership transfer * Test invitation x-data in sites LV * Remove sitelocker trigger in invitation acceptance code and simplify logic * Add Quota test for `user.allow_next_upgrade_override` being set * ignore pageview limit only when subscribing to plan * Use sandbox Paddle instance for staging * Use sandbox paddle key for staging and dev --------- Co-authored-by: Robert Joonas <robertjoonas16@gmail.com>
3 years ago
{:ok, _} ->
:ok
{:error, :transfer_to_self} ->
{:error, "User is already an owner of one of the sites"}
{:error, :no_plan} ->
{:error, "The new owner does not have a subscription"}
{:error, {:over_plan_limits, limits}} ->
{:error, "Plan limits exceeded for one of the sites: #{Enum.join(limits, ", ")}"}
end
else
{:error, "User could not be found"}
end
end
defp format_date(date) do
Timex.format!(date, "{Mshort} {D}, {YYYY}")
end
defp get_owner(site) do
owner = site.owner
if owner do
{:safe,
"""
<a href="/crm/auth/user/#{owner.id}">#{owner.name}</a>
<br/><br/>
#{owner.email}
"""}
end
end
defp get_other_members(site) do
Enum.filter(site.memberships, &(&1.role != :owner))
|> Enum.map(fn m -> m.user.email <> "(#{to_string(m.role)})" end)
|> Enum.join(", ")
end
def get_struct_fields(module) do
module.__struct__()
|> Map.drop([:__meta__, :__struct__])
|> Map.keys()
|> Enum.map(&Atom.to_string/1)
|> Enum.sort()
end
def create_changeset(schema, attrs), do: Plausible.Site.crm_changeset(schema, attrs)
def update_changeset(schema, attrs), do: Plausible.Site.crm_changeset(schema, attrs)
end