Skip to content

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

Reimplement user search in enterprise plans CRM and fix plan prefill (#4913)

Adrian Gruntkowski3e4d59d2d0d1
diff --git a/lib/plausible/billing/enterprise_plan.ex b/lib/plausible/billing/enterprise_plan.ex
index afc166cc88..36ccd0a1d6 100644
--- a/lib/plausible/billing/enterprise_plan.ex
+++ b/lib/plausible/billing/enterprise_plan.ex
@@ -36,6 +36,5 @@ defmodule Plausible.Billing.EnterprisePlan do
model
|> cast(attrs, @required_fields)
|> validate_required(@required_fields)
- |> unique_constraint(:user_id)
end
end
diff --git a/lib/plausible/crm_extensions.ex b/lib/plausible/crm_extensions.ex
index 1ca27addf6..054b6106f0 100644
--- a/lib/plausible/crm_extensions.ex
+++ b/lib/plausible/crm_extensions.ex
@@ -48,38 +48,71 @@ defmodule Plausible.CrmExtensions do
]
end
- def javascripts(%{assigns: %{context: context}})
- when context in ["sites", "billing"] do
+ def javascripts(%{assigns: %{context: "billing", resource: "enterprise_plan", changeset: %{}}}) do
[
Phoenix.HTML.raw("""
<script type="text/javascript">
- (() => {
- const publicField = document.querySelector("#kaffy-search-field")
- const searchForm = document.querySelector("#kaffy-filters-form")
- const searchField = document.querySelector("#kaffy-filter-search")
+ (async () => {
+ const CHECK_INTERVAL = 300
+ const userIdField = document.querySelector("#enterprise_plan_user_id")
+ const userIdLabel = document.querySelector("label[for=enterprise_plan_user_id]")
+ const dataList = document.createElement("datalist")
+ dataList.id = "user-choices"
+ userIdField.after(dataList)
+ userIdField.setAttribute("list", "user-choices")
+ userIdField.setAttribute("type", "text")
+ const labelSpan = document.createElement("span")
+ userIdLabel.appendChild(labelSpan)
+
+ let updateAction;
+
+ const updateLabel = async (id) => {
+ id = Number(id)
+
+ if (!isNaN(id) && id > 0) {
+ const response = await fetch(`/crm/billing/search/user-by-id/${id}`)
+ labelSpan.innerHTML = ` <i>(${await response.text()})</i>`
+ }
+ }
- if (publicField && searchForm && searchField) {
- publicField.name = "#{@custom_search}"
- searchField.name = "#{@custom_search}"
+ const updateSearch = async () => {
+ const search = userIdField.value
- const params = new URLSearchParams(window.location.search)
- publicField.value = params.get("#{@custom_search}")
+ updateLabel(search)
- const searchInput = document.createElement("input")
- searchInput.name = "search"
- searchInput.type = "hidden"
- searchInput.value = ""
+ const response = await fetch("/crm/billing/search/user", {
+ headers: { "Content-Type": "application/json" },
+ method: "POST",
+ body: JSON.stringify({ search: search })
+ })
- searchForm.appendChild(searchInput)
+ const list = await response.json()
+
+ const options =
+ list.map(([label, value]) => {
+ const option = document.createElement("option")
+ option.setAttribute("label", label)
+ option.textContent = value
+
+ return option
+ })
+
+ dataList.replaceChildren(...options)
}
+
+ updateLabel(userIdField.value)
+
+ userIdField.addEventListener("input", async (e) => {
+ if (updateAction) {
+ clearTimeout(updateAction)
+ updateAction = null
+ }
+
+ updateAction = setTimeout(() => updateSearch(), CHECK_INTERVAL)
+ })
})()
</script>
- """)
- ]
- end
-
- def javascripts(%{assigns: %{context: "billing", resource: "enterprise_plan", changeset: %{}}}) do
- [
+ """),
Phoenix.HTML.raw("""
<script type="text/javascript">
(() => {
@@ -153,6 +186,36 @@ defmodule Plausible.CrmExtensions do
""")
]
end
+
+ def javascripts(%{assigns: %{context: context}})
+ when context in ["sites", "billing"] do
+ [
+ Phoenix.HTML.raw("""
+ <script type="text/javascript">
+ (() => {
+ const publicField = document.querySelector("#kaffy-search-field")
+ const searchForm = document.querySelector("#kaffy-filters-form")
+ const searchField = document.querySelector("#kaffy-filter-search")
+
+ if (publicField && searchForm && searchField) {
+ publicField.name = "#{@custom_search}"
+ searchField.name = "#{@custom_search}"
+
+ const params = new URLSearchParams(window.location.search)
+ publicField.value = params.get("#{@custom_search}")
+
+ const searchInput = document.createElement("input")
+ searchInput.name = "search"
+ searchInput.type = "hidden"
+ searchInput.value = ""
+
+ searchForm.appendChild(searchInput)
+ }
+ })()
+ </script>
+ """)
+ ]
+ end
end
def javascripts(_) do
diff --git a/lib/plausible_web/controllers/admin_controller.ex b/lib/plausible_web/controllers/admin_controller.ex
index e5a5c501b3..69c6ef5f1c 100644
--- a/lib/plausible_web/controllers/admin_controller.ex
+++ b/lib/plausible_web/controllers/admin_controller.ex
@@ -2,6 +2,9 @@ defmodule PlausibleWeb.AdminController do
use PlausibleWeb, :controller
use Plausible
+ import Ecto.Query
+
+ alias Plausible.Repo
alias Plausible.Teams
def usage(conn, params) do
@@ -71,6 +74,60 @@ defmodule PlausibleWeb.AdminController do
|> send_resp(200, json_response)
end
+ def user_by_id(conn, params) do
+ id = params["user_id"]
+
+ entry =
+ Repo.one(
+ from u in Plausible.Auth.User,
+ where: u.id == ^id,
+ select: fragment("concat(?, ?, ?, ?)", u.name, " (", u.email, ")")
+ ) || ""
+
+ conn
+ |> send_resp(200, entry)
+ end
+
+ def user_search(conn, params) do
+ search =
+ (params["search"] || "")
+ |> String.trim()
+
+ choices =
+ if search != "" do
+ term =
+ search
+ |> String.replace("%", "\%")
+ |> String.replace("_", "\_")
+
+ term = "%#{term}%"
+
+ user_id =
+ case Integer.parse(search) do
+ {id, ""} -> id
+ _ -> 0
+ end
+
+ if user_id != 0 do
+ []
+ else
+ Repo.all(
+ from u in Plausible.Auth.User,
+ where: u.id == ^user_id or ilike(u.name, ^term) or ilike(u.email, ^term),
+ order_by: [u.name, u.id],
+ select: [fragment("concat(?, ?, ?, ?)", u.name, " (", u.email, ")"), u.id],
+ limit: 20
+ )
+ end
+ else
+ []
+ end
+
+ conn
+ |> put_resp_content_type("application/json")
+ |> send_resp(200, Jason.encode!(choices))
+ end
+
defp usage_and_limits_html(team, usage, limits, embed?) do
content = """
<ul>
diff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.ex
index 2f9a882fc1..a03955599f 100644
--- a/lib/plausible_web/router.ex
+++ b/lib/plausible_web/router.ex
@@ -92,6 +92,8 @@ defmodule PlausibleWeb.Router do
pipe_through :flags
get "/auth/user/:user_id/usage", AdminController, :usage
get "/billing/user/:user_id/current_plan", AdminController, :current_plan
+ get "/billing/search/user-by-id/:user_id", AdminController, :user_by_id
+ post "/billing/search/user", AdminController, :user_search
end
end