Skip to content

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

Add ability to lookup by email and site domain in HelpScout integration (#4377)

Adrian Gruntkowski556c896936d2
diff --git a/extra/lib/plausible/help_scout.ex b/extra/lib/plausible/help_scout.ex
index cca1e5d1f6..15698a96b7 100644
--- a/extra/lib/plausible/help_scout.ex
+++ b/extra/lib/plausible/help_scout.ex
@@ -17,6 +17,12 @@ defmodule Plausible.HelpScout do
@base_api_url "https://api.helpscout.net"
@signature_field "X-HelpScout-Signature"
+ @signature_errors [:missing_signature, :bad_signature]
+
+ @type signature_error() :: unquote(Enum.reduce(@signature_errors, &{:|, [], [&1, &2]}))
+
+ def signature_errors(), do: @signature_errors
+
@doc """
Validates signature against secret key configured for the
HelpScout application.
@@ -30,7 +36,7 @@ defmodule Plausible.HelpScout do
params to JSON using wrapper struct, informing Jason to put the values
in the serialized object in this particular order matching query string.
"""
- @spec validate_signature(Plug.Conn.t()) :: :ok | {:error, :missing_signature | :bad_signature}
+ @spec validate_signature(Plug.Conn.t()) :: :ok | {:error, signature_error()}
def validate_signature(conn) do
params = conn.params
@@ -65,15 +71,23 @@ defmodule Plausible.HelpScout do
end
end
- @spec get_customer_details(String.t()) :: {:ok, map()} | {:error, any()}
- def get_customer_details(customer_id) do
- with {:ok, emails} <- get_customer_emails(customer_id),
- {:ok, user} <- get_user(emails) do
+ @spec get_details_for_customer(String.t()) :: {:ok, map()} | {:error, any()}
+ def get_details_for_customer(customer_id) do
+ with {:ok, emails} <- get_customer_emails(customer_id) do
+ get_details_for_emails(emails, customer_id)
+ end
+ end
+
+ @spec get_details_for_emails([String.t()], String.t()) :: {:ok, map()} | {:error, any()}
+ def get_details_for_emails(emails, customer_id) do
+ with {:ok, user} <- get_user(emails) do
+ set_mapping(customer_id, user.email)
user = Plausible.Users.with_subscription(user.id)
plan = Billing.Plans.get_subscription_plan(user.subscription)
{:ok,
%{
+ email: user.email,
status_label: status_label(user),
status_link:
Routes.kaffy_resource_url(PlausibleWeb.Endpoint, :show, :auth, :user, user.id),
@@ -88,6 +102,30 @@ defmodule Plausible.HelpScout do
end
end
+ @spec search_users(String.t(), String.t()) :: [map()]
+ def search_users(term, customer_id) do
+ clear_mapping(customer_id)
+
+ search_term = "%#{term}%"
+
+ domain_query =
+ from(s in Plausible.Site,
+ inner_join: sm in assoc(s, :memberships),
+ where: sm.user_id == parent_as(:user).id and sm.role == :owner,
+ where: ilike(s.domain, ^search_term) or ilike(s.domain_changed_from, ^search_term),
+ select: 1
+ )
+
+ users_query()
+ |> where(
+ [user: u],
+ like(u.email, ^search_term) or exists(domain_query)
+ )
+ |> limit(5)
+ |> select([user: u, site_membership: sm], %{email: u.email, sites_count: count(sm.id)})
+ |> Repo.all()
+ end
+
defp plan_link(nil), do: "#"
defp plan_link(%{paddle_subscription_id: paddle_id}) do
@@ -174,17 +212,42 @@ defmodule Plausible.HelpScout do
defp get_user(emails) do
user =
- from(u in Plausible.Auth.User, where: u.email in ^emails, limit: 1)
+ users_query()
+ |> where([user: u], u.email in ^emails)
+ |> limit(1)
|> Repo.one()
if user do
{:ok, user}
else
- {:error, :not_found}
+ {:error, {:user_not_found, emails}}
+ end
+ end
+
+ defp users_query() do
+ from(u in Plausible.Auth.User,
+ as: :user,
+ left_join: sm in assoc(u, :site_memberships),
+ on: sm.role == :owner,
+ as: :site_membership,
+ left_join: s in assoc(sm, :site),
+ as: :site,
+ group_by: u.id,
+ order_by: [desc: count(sm.id)]
+ )
+ end
+
+ defp get_customer_emails(customer_id) do
+ case lookup_mapping(customer_id) do
+ {:ok, email} ->
+ {:ok, [email]}
+
+ {:error, :mapping_not_found} ->
+ fetch_customer_emails(customer_id)
end
end
- defp get_customer_emails(customer_id, opts \\ []) do
+ defp fetch_customer_emails(customer_id, opts \\ []) do
refresh? = Keyword.get(opts, :refresh?, true)
token = get_token!()
@@ -206,7 +269,7 @@ defmodule Plausible.HelpScout do
{:ok, %{status: 401}} ->
if refresh? do
refresh_token!()
- get_customer_emails(customer_id, refresh?: false)
+ fetch_customer_emails(customer_id, refresh?: false)
else
{:error, :auth_failed}
end
@@ -220,6 +283,41 @@ defmodule Plausible.HelpScout do
end
end
+ # Exposed for testing
+ @doc false
+ def lookup_mapping(customer_id) do
+ email =
+ "SELECT email FROM help_scout_mappings WHERE customer_id = $1"
+ |> Repo.query!([customer_id])
+ |> Map.get(:rows)
+ |> List.first()
+
+ case email do
+ [email] ->
+ {:ok, email}
+
+ _ ->
+ {:error, :mapping_not_found}
+ end
+ end
+
+ # Exposed for testing
+ @doc false
+ def set_mapping(customer_id, email) do
+ now = NaiveDateTime.utc_now(:second)
+
+ Repo.insert_all(
+ "help_scout_mappings",
+ [[customer_id: customer_id, email: email, inserted_at: now, updated_at: now]],
+ conflict_target: :customer_id,
+ on_conflict: [set: [email: email, updated_at: now]]
+ )
+ end
+
+ defp clear_mapping(customer_id) do
+ Repo.query!("DELETE FROM help_scout_mappings WHERE customer_id = $1", [customer_id])
+ end
+
defp get_token!() do
token =
"SELECT access_token FROM help_scout_credentials ORDER BY id DESC LIMIT 1"
diff --git a/extra/lib/plausible_web/controllers/help_scout_controller.ex b/extra/lib/plausible_web/controllers/help_scout_controller.ex
index 1015a57121..16b457706d 100644
--- a/extra/lib/plausible_web/controllers/help_scout_controller.ex
+++ b/extra/lib/plausible_web/controllers/help_scout_controller.ex
@@ -3,18 +3,129 @@ defmodule PlausibleWeb.HelpScoutController do
alias Plausible.HelpScout
- def callback(conn, %{"customer-id" => customer_id}) do
- conn =
- conn
- |> delete_resp_header("x-frame-options")
- |> put_layout(false)
+ @conversation_cookie "helpscout_conversation"
+ @conversation_cookie_seconds 8 * 60 * 60
+ @signature_errors HelpScout.signature_errors()
+
+ plug :make_iframe_friendly
+
+ def callback(conn, %{"customer-id" => customer_id, "conversation-id" => conversation_id}) do
+ assigns = %{conversation_id: conversation_id, customer_id: customer_id}
with :ok <- HelpScout.validate_signature(conn),
- {:ok, details} <- HelpScout.get_customer_details(customer_id) do
- render(conn, "callback.html", details)
+ {:ok, details} <- HelpScout.get_details_for_customer(customer_id) do
+ conn
+ |> set_cookie(conversation_id)
+ |> render("callback.html", Map.merge(assigns, details))
else
+ {:error, {:user_not_found, [email | _]}} ->
+ conn
+ |> set_cookie(conversation_id)
+ |> render("callback.html", Map.merge(assigns, %{error: ":user_not_found", email: email}))
+
{:error, error} ->
- render(conn, "callback.html", error: inspect(error))
+ conn
+ |> maybe_set_cookie(error, conversation_id)
+ |> render("callback.html", Map.put(assigns, :error, inspect(error)))
+ end
+ end
+
+ def callback(conn, _) do
+ render(conn, "bad_request.html")
+ end
+
+ def show(
+ conn,
+ %{"email" => email, "conversation_id" => conversation_id, "customer_id" => customer_id} =
+ params
+ ) do
+ assigns = %{
+ xhr?: params["xhr"] == "true",
+ conversation_id: conversation_id,
+ customer_id: customer_id
+ }
+
+ with :ok <- match_conversation(conn, conversation_id),
+ {:ok, details} <- HelpScout.get_details_for_emails([email], customer_id) do
+ render(conn, "callback.html", Map.merge(assigns, details))
+ else
+ {:error, :invalid_conversation = error} ->
+ conn
+ |> clear_cookie()
+ |> render("callback.html", Map.put(assigns, :error, inspect(error)))
+
+ {:error, error} ->
+ render(conn, "callback.html", Map.put(assigns, :error, inspect(error)))
+ end
+ end
+
+ def search(conn, %{
+ "term" => term,
+ "conversation_id" => conversation_id,
+ "customer_id" => customer_id
+ }) do
+ assigns = %{
+ conversation_id: conversation_id,
+ customer_id: customer_id
+ }
+
+ case match_conversation(conn, conversation_id) do
+ :ok ->
+ users = HelpScout.search_users(term, customer_id)
+ render(conn, "search.html", Map.merge(assigns, %{users: users, term: term}))
+
+ {:error, :invalid_conversation = error} ->
+ conn
+ |> clear_cookie()
+ |> render("search.html", Map.put(assigns, :error, inspect(error)))
end
end
+
+ defp match_conversation(conn, conversation_id) do
+ conn = fetch_cookies(conn, encrypted: [@conversation_cookie])
+ cookie_conversation = conn.cookies[@conversation_cookie][:conversation_id]
+
+ if cookie_conversation && conversation_id == cookie_conversation do
+ :ok
+ else
+ {:error, :invalid_conversation}
+ end
+ end
+
+ defp maybe_set_cookie(conn, error, conversation_id)
+ when error not in @signature_errors do
+ set_cookie(conn, conversation_id)
+ end
+
+ defp maybe_set_cookie(conn, _error, _conversation_id) do
+ clear_cookie(conn)
+ end
+
+ # Exposed for testing
+ @doc false
+ def set_cookie(conn, conversation_id) do
+ put_resp_cookie(conn, @conversation_cookie, %{conversation_id: conversation_id},
+ domain: PlausibleWeb.Endpoint.host(),
+ secure: true,
+ encrypt: true,
+ max_age: @conversation_cookie_seconds,
+ same_site: "None"
+ )
+ end
+
+ defp clear_cookie(conn) do
+ delete_resp_cookie(conn, @conversation_cookie,
+ domain: PlausibleWeb.Endpoint.host(),
+ secure: true,
+ encrypt: true,
+ max_age: @conversation_cookie_seconds,
+ same_site: "None"
+ )
+ end
+
+ defp make_iframe_friendly(conn, _opts) do
+ conn
+ |> delete_resp_header("x-frame-options")
+ |> put_layout(false)
+ end
end
diff --git a/extra/lib/plausible_web/views/help_scout_view.ex b/extra/lib/plausible_web/views/help_scout_view.ex
index 94458877c9..fbbd6f19d8 100644
--- a/extra/lib/plausible_web/views/help_scout_view.ex
+++ b/extra/lib/plausible_web/views/help_scout_view.ex
@@ -3,66 +3,224 @@ defmodule PlausibleWeb.HelpScoutView do
def render("callback.html", assigns) do
~H"""
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>Helpscout Customer Details</title>
- <style type="text/css">
- * {
- margin: 0;
- padding: 0;
- }
-
- body {
- font-family: Helvetica, Arial, Sans-Serif;
- font-size: 14px;
- }
-
- p {
- margin-left: 1.25em;
- }
-
- .value {
- margin-bottom: 1.25em;
- font-weight: bold;
- }
- </style>
- </head>
-
- <body>
- <%= if @conn.assigns[:error] do %>
- <p>
- Failed to get details: <%= @error %>
+ <.layout xhr?={assigns[:xhr?]}>
+ <div class="search">
+ <form action="/helpscout/search">
+ <p class="entry">
+ <input type="text" name="term" value={assigns[:email]} />
+ <input type="submit" name="search" value="&nbsp;&#x1F50E;&nbsp;" />
</p>
- <% else %>
- <div class="status">
- <p class="label">
- Status
- </p>
- <p class="value">
- <a href={@status_link} target="_blank"><%= @status_label %></a>
- </p>
- </div>
+ <input type="hidden" name="conversation_id" value={@conversation_id} />
+ <input type="hidden" name="customer_id" value={@customer_id} />
+ </form>
+ </div>
- <div class="plan">
- <p class="label">
- Plan
- </p>
- <p class="value">
- <a href={@plan_link} target="_blank"><%= @plan_label %></a>
- </p>
- </div>
+ <%= if @conn.assigns[:error] do %>
+ <p>
+ Failed to get details: <%= @error %>
+ </p>
+ <% else %>
+ <div class="status">
+ <p class="label">
+ Status
+ </p>
+ <p class="value">
+ <a href={@status_link} target="_blank"><%= @status_label %></a>
+ </p>
+ </div>
+
+ <div class="plan">
+ <p class="label">
+ Plan
+ </p>
+ <p class="value">
+ <a href={@plan_link} target="_blank"><%= @plan_label %></a>
+ </p>
+ </div>
+
+ <div class="sites">
+ <p class="label">
+ Owner of <b><a href={@sites_link} target="_blank"><%= @sites_count %> sites</a></b>
+ </p>
+ </div>
+ <% end %>
+ </.layout>
+ """
+ end
- <div class="sites">
- <p class="label">
- Owner of <b><a href={@sites_link} target="_blank"><%= @sites_count %> sites</a></b>
+ def render("search.html", assigns) do
+ ~H"""
+ <.layout>
+ <%= if @conn.assigns[:error] do %>
+ <p>
+ Failed to run search: <%= @error %>
+ </p>
+ <% else %>
+ <div class="search">
+ <form action="/helpscout/search">
+ <p class="entry">
+ <input type="text" name="term" value={@term} />
+ <input type="submit" name="search" value="&nbsp;&#x1F50E;&nbsp;" />
</p>
+ <input type="hidden" name="conversation_id" value={@conversation_id} />
+ <input type="hidden" name="customer_id" value={@customer_id} />
+ </form>
+ <ul :if={length(@users) > 0}>
+ <li :for={user <- @users}>
+ <a
+ onclick={"loadContent('/helpscout/show?#{URI.encode_query(email: user.email, conversation_id: @conversation_id, customer_id: @customer_id)}')"}
+ href="#"
+ >
+ <%= user.email %> (<%= user.sites_count %> sites)
+ </a>
+ </li>
+ </ul>
+ <div :if={@users == []}>
+ No match found
</div>
- <% end %>
- </body>
- </html>
+ </div>
+ <% end %>
+ </.layout>
+ """
+ end
+
+ def render("bad_request.html", assigns) do
+ ~H"""
+ <.layout>
+ <p>Missing expected parameters</p>
+ </.layout>
"""
end
+
+ attr :xhr?, :boolean, default: false
+ slot :inner_block, required: true
+
+ defp layout(assigns) do
+ if assigns.xhr? do
+ ~H"""
+ render_slot(@inner_block)
+ """
+ else
+ ~H"""
+ <!DOCTYPE html>
+ <html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Helpscout Customer Details</title>
+ <style type="text/css">
+ * {
+ margin: 0;
+ padding: 0;
+ }
+
+ body {
+ font-family: Helvetica, Arial, Sans-Serif;
+ font-size: 14px;
+ }
+
+ ul {
+ list-style-type: none;
+ }
+
+ p, ul {
+ margin-left: 1.25em;
+ }
+
+ .entry {
+ width: 100%;
+ display: flex;
+ }
+
+ ul li, .entry {
+ margin-bottom: 1.25em;
+ }
+
+ .value {
+ margin-bottom: 1.25em;
+ font-weight: bold;
+ }
+ </style>
+ </head>
+
+ <body>
+ <div id="content">
+ <%= render_slot(@inner_block) %>
+ </div>
+
+ <script type="text/javascript">
+ /*
+ * HelpScout call adjusting iframe height.
+ *
+ * Extracted from their JavaScript SDK and adapted.
+ */
+ function setAppHeight(height) {
+ window.parent.postMessage(
+ {
+ value: height + 30,
+ type: 'SET_APP_HEIGHT',
+ appId: window.name && window.name.replace(/app-side-panel-|app-/, ''),
+ iframeId: window.name
+ },
+ 'https://secure.helpscout.net/'
+ )
+ }
+
+ const appContainer = document.getElementById("content")
+
+ const isSafari = !!(
+ navigator.vendor &&
+ navigator.vendor.indexOf('Apple') > -1 &&
+ navigator.userAgent &&
+ navigator.userAgent.indexOf('CriOS') == -1 &&
+ navigator.userAgent.indexOf('FxiOS') == -1
+ )
+
+ /*
+ * Using cookies within iframe requires requesting storage access
+ * in Safari. Unfortunately, the storage access check sometimes
+ * falsely returns true in FireFox and requesting storage access
+ * in FF seems to break the cookies. That's why there's an extra
+ * check for Safari.
+ */
+ window.addEventListener('load', async () => {
+ const hasStorageAccess = await document.hasStorageAccess()
+ if (isSafari && !hasStorageAccess) {
+ const paragraph = document.createElement('p')
+ paragraph.style = "text-align: center; margin-bottom: 0.4em;"
+ const button = document.createElement('button')
+ button.innerHTML = 'Grant cookie access'
+ button.onclick = async (e) => {
+ await document.requestStorageAccess()
+ paragraph.remove()
+ }
+ paragraph.append(button)
+ appContainer.prepend(paragraph)
+ }
+ })
+
+ async function loadContent(uri) {
+ const response = await fetch(uri)
+ const html = await response.text()
+ appContainer.innerHTML = html
+ setAppHeight(appContainer.clientHeight)
+ }
+
+ setAppHeight(appContainer.clientHeight)
+
+ /*
+ * Tracking any resize of integration content
+ * and adjusting iframe height accordingly.
+ */
+ const resizeObserver = new ResizeObserver(() => {
+ setAppHeight(appContainer.clientHeight)
+ })
+
+ resizeObserver.observe(appContainer)
+ </script>
+ </body>
+ </html>
+ """
+ end
+ end
end
diff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.ex
index 7944890db4..16db14e346 100644
--- a/lib/plausible_web/router.ex
+++ b/lib/plausible_web/router.ex
@@ -294,6 +294,8 @@ defmodule PlausibleWeb.Router do
on_ee do
get "/helpscout/callback", HelpScoutController, :callback
+ get "/helpscout/show", HelpScoutController, :show
+ get "/helpscout/search", HelpScoutController, :search
end
get "/", PageController, :index
diff --git a/test/plausible/help_scout_test.exs b/test/plausible/help_scout_test.exs
index af6792a7ee..6101e0ddea 100644
--- a/test/plausible/help_scout_test.exs
+++ b/test/plausible/help_scout_test.exs
@@ -52,7 +52,7 @@ defmodule Plausible.HelpScoutTest do
end
end
- describe "get_customer_details/1" do
+ describe "get_details_for_customer/2" do
test "returns details for user on trial" do
%{id: user_id, email: email} = insert(:user)
stub_help_scout_requests(email)
@@ -70,7 +70,7 @@ defmodule Plausible.HelpScoutTest do
plan_label: "None",
sites_count: 0,
sites_link: ^owned_sites_url
- }} = HelpScout.get_customer_details("500")
+ }} = HelpScout.get_details_for_customer("500")
end
test "returns for user without trial or subscription" do
@@ -83,7 +83,7 @@ defmodule Plausible.HelpScoutTest do
status_label: "None",
plan_link: "#",
plan_label: "None"
- }} = HelpScout.get_customer_details("500")
+ }} = HelpScout.get_details_for_customer("500")
end
test "returns for user with trial expired" do
@@ -96,7 +96,7 @@ defmodule Plausible.HelpScoutTest do
status_label: "Expired trial",
plan_link: "#",
plan_label: "None"
- }} = HelpScout.get_customer_details("500")
+ }} = HelpScout.get_details_for_customer("500")
end
test "returns for user with paid subscription on standard plan" do
@@ -116,7 +116,7 @@ defmodule Plausible.HelpScoutTest do
status_label: "Paid",
plan_link: ^plan_link,
plan_label: "10k Plan (€10 monthly)"
- }} = HelpScout.get_customer_details("500")
+ }} = HelpScout.get_details_for_customer("500")
end
test "returns for user with paid subscription on standard yearly plan" do
@@ -136,7 +136,7 @@ defmodule Plausible.HelpScoutTest do
status_label: "Paid",
plan_link: ^plan_link,
plan_label: "10k Plan (€100 yearly)"
- }} = HelpScout.get_customer_details("500")
+ }} = HelpScout.get_details_for_customer("500")
end
test "returns for user with paid subscription on free 10k plan" do
@@ -152,7 +152,7 @@ defmodule Plausible.HelpScoutTest do
status_label: "Paid",
plan_link: _,
plan_label: "Free 10k"
- }} = HelpScout.get_customer_details("500")
+ }} = HelpScout.get_details_for_customer("500")
end
test "returns for user with paid subscription on enterprise plan" do
@@ -174,7 +174,7 @@ defmodule Plausible.HelpScoutTest do
status_label: "Paid",
plan_link: _,
plan_label: "1M Enterprise Plan (€10 monthly)"
- }} = HelpScout.get_customer_details("500")
+ }} = HelpScout.get_details_for_customer("500")
end
test "returns for user with paid subscription on yearly enterprise plan" do
@@ -197,7 +197,7 @@ defmodule Plausible.HelpScoutTest do
status_label: "Paid",
plan_link: _,
plan_label: "1M Enterprise Plan (€10 yearly)"
- }} = HelpScout.get_customer_details("500")
+ }} = HelpScout.get_details_for_customer("500")
end
test "returns for user with subscription pending cancellation" do
@@ -217,7 +217,7 @@ defmodule Plausible.HelpScoutTest do
status_label: "Pending cancellation",
plan_link: _,
plan_label: "10k Plan (€10 monthly)"
- }} = HelpScout.get_customer_details("500")
+ }} = HelpScout.get_details_for_customer("500")
end
test "returns for user with canceled subscription" do
@@ -238,7 +238,7 @@ defmodule Plausible.HelpScoutTest do
status_label: "Canceled",
plan_link: _,
plan_label: "10k Plan (€10 monthly)"
- }} = HelpScout.get_customer_details("500")
+ }} = HelpScout.get_details_for_customer("500")
end
test "returns for user with paused subscription" do
@@ -258,7 +258,7 @@ defmodule Plausible.HelpScoutTest do
status_label: "Paused",
plan_link: _,
plan_label: "10k Plan (€10 monthly)"
- }} = HelpScout.get_customer_details("500")
+ }} = HelpScout.get_details_for_customer("500")
end
test "returns for user with locked site" do
@@ -277,7 +277,7 @@ defmodule Plausible.HelpScoutTest do
plan_link: _,
plan_label: "10k Plan (€10 monthly)",
sites_count: 1
- }} = HelpScout.get_customer_details("500")
+ }} = HelpScout.get_details_for_customer("500")
end
test "returns error when no matching user found in database" do
@@ -285,7 +285,8 @@ defmodule Plausible.HelpScoutTest do
stub_help_scout_requests("[email protected]")
- assert {:error, :not_found} = HelpScout.get_customer_details("500")
+ assert {:error, {:user_not_found, ["[email protected]"]}} =
+ HelpScout.get_details_for_customer("500")
end
test "returns error when no customer found in Help Scout" do
@@ -303,7 +304,7 @@ defmodule Plausible.HelpScoutTest do
|> Req.Test.text("Not found")
end)
- assert {:error, :not_found} = HelpScout.get_customer_details("500")
+ assert {:error, :not_found} = HelpScout.get_details_for_customer("500")
end
test "returns error when found customer has no emails" do
@@ -324,7 +325,7 @@ defmodule Plausible.HelpScoutTest do
})
end)
- assert {:error, :no_emails} = HelpScout.get_customer_details("500")
+ assert {:error, :no_emails} = HelpScout.get_details_for_customer("500")
end
test "uses existing access token when available" do
@@ -354,7 +355,7 @@ defmodule Plausible.HelpScoutTest do
})
end)
- assert {:ok, _} = HelpScout.get_customer_details("500")
+ assert {:ok, _} = HelpScout.get_details_for_customer("500")
end
test "refreshes token on expiry" do
@@ -400,7 +401,92 @@ defmodule Plausible.HelpScoutTest do
end
end)
- assert {:ok, _} = HelpScout.get_customer_details("500")
+ assert {:ok, _} = HelpScout.get_details_for_customer("500")
+ end
+ end
+
+ describe "get_details_for_emails/2" do
+ test "returns details for user and persists mapping" do
+ %{id: user_id, email: email} = insert(:user)
+
+ crm_url = "#{PlausibleWeb.Endpoint.url()}/crm/auth/user/#{user_id}"
+
+ owned_sites_url =
+ "#{PlausibleWeb.Endpoint.url()}/crm/sites/site?search=#{URI.encode_www_form(email)}"
+
+ assert {:ok,
+ %{
+ status_link: ^crm_url,
+ status_label: "Trial",
+ plan_link: "#",
+ plan_label: "None",
+ sites_count: 0,
+ sites_link: ^owned_sites_url
+ }} = HelpScout.get_details_for_emails([email], "123")
+
+ assert {:ok, ^email} = HelpScout.lookup_mapping("123")
+ end
+
+ test "updates mapping if one already exists" do
+ user = insert(:user)
+ %{email: new_email} = insert(:user)
+ HelpScout.set_mapping("123", user.email)
+
+ assert {:ok, _} = HelpScout.get_details_for_emails([new_email], "123")
+ assert {:ok, ^new_email} = HelpScout.lookup_mapping("123")
+ end
+
+ test "picks the match with largest number of owned sites" do
+ user1 = insert(:user)
+ insert(:site, members: [user1])
+ insert(:site_membership, site: build(:site), user: user1, role: :viewer)
+ insert(:site_membership, site: build(:site), user: user1, role: :admin)
+ user2 = insert(:user)
+ insert_list(2, :site, members: [user2])
+
+ crm_url = "#{PlausibleWeb.Endpoint.url()}/crm/auth/user/#{user2.id}"
+
+ owned_sites_url =
+ "#{PlausibleWeb.Endpoint.url()}/crm/sites/site?search=#{URI.encode_www_form(user2.email)}"
+
+ assert {:ok,
+ %{
+ status_link: ^crm_url,
+ status_label: "Trial",
+ plan_link: "#",
+ plan_label: "None",
+ sites_count: 2,
+ sites_link: ^owned_sites_url
+ }} = HelpScout.get_details_for_emails([user1.email, user2.email], "123")
+
+ user2_email = user2.email
+ assert {:ok, ^user2_email} = HelpScout.lookup_mapping("123")
+ end
+
+ test "does not persist the mapping when there's no match" do
+ assert {:error, {:user_not_found, ["[email protected]"]}} =
+ HelpScout.get_details_for_emails(["[email protected]"], "123")
+
+ assert {:error, :mapping_not_found} = HelpScout.lookup_mapping("123")
+ end
+ end
+
+ describe "search_users/2" do
+ test "lists matching users by email or site domain ordered by site counts" do
+ user1 = insert(:user, email: "[email protected]")
+
+ user2 = insert(:user, email: "[email protected]")
+ insert(:site, members: [user2])
+
+ user3 = insert(:user, email: "[email protected]")
+ insert(:site, members: [user3])
+ insert(:site, domain: "big.match.example.com/hit", members: [user3])
+
+ assert HelpScout.search_users("match.example.co", "123") == [
+ %{email: user3.email, sites_count: 2},
+ %{email: user2.email, sites_count: 1},
+ %{email: user1.email, sites_count: 0}
+ ]
end
end
diff --git a/test/plausible_web/controllers/help_scout_controller_test.exs b/test/plausible_web/controllers/help_scout_controller_test.exs
index 7824d3a3f5..51d16fb1d6 100644
--- a/test/plausible_web/controllers/help_scout_controller_test.exs
+++ b/test/plausible_web/controllers/help_scout_controller_test.exs
@@ -11,7 +11,7 @@ defmodule PlausibleWeb.HelpScoutControllerTest do
test "returns details on success", %{conn: conn} do
user = insert(:user)
signature_key = Application.fetch_env!(:plausible, HelpScout)[:signature_key]
- data = ~s|{"customer-id":"500"}|
+ data = ~s|{"conversation-id":"123","customer-id":"500"}|
signature =
:hmac
@@ -42,16 +42,116 @@ defmodule PlausibleWeb.HelpScoutControllerTest do
})
end)
- conn = get(conn, "/helpscout/callback?customer-id=500&X-HelpScout-Signature=#{signature}")
+ conn =
+ get(
+ conn,
+ "/helpscout/callback?conversation-id=123&customer-id=500&X-HelpScout-Signature=#{signature}"
+ )
assert html_response(conn, 200) =~ "/crm/auth/user/#{user.id}"
end
test "returns error on failure", %{conn: conn} do
- conn = get(conn, "/helpscout/callback?customer-id=500&X-HelpScout-Signature=invalid")
+ conn =
+ get(
+ conn,
+ "/helpscout/callback?conversation-id=123&customer-id=500&X-HelpScout-Signature=invalid"
+ )
assert html_response(conn, 200) =~ "bad_signature"
end
+
+ test "handles invalid parameters gracefully", %{conn: conn} do
+ conn =
+ get(
+ conn,
+ "/helpscout/callback?customer-id=500&X-HelpScout-Signature=whatever"
+ )
+
+ assert html_response(conn, 200) =~ "Missing expected parameters"
+ end
+ end
+
+ describe "search/2" do
+ test "returns results", %{conn: conn} do
+ insert(:user, email: "[email protected]")
+ insert(:user, email: "[email protected]")
+
+ conn =
+ conn
+ |> set_conversation_cookie("123")
+ |> get("/helpscout/search?conversation_id=123&customer_id=500&term=hs.match")
+
+ html = html_response(conn, 200)
+
+ assert html =~ "[email protected]"
+ refute html =~ "[email protected]"
+ end
+
+ test "returns error when cookie is missing", %{conn: conn} do
+ conn = get(conn, "/helpscout/search?conversation_id=123&customer_id=500&term=hs.match")
+
+ assert html_response(conn, 200) =~ "invalid_conversation"
+ end
+
+ test "returns error when cookie does not match", %{conn: conn} do
+ conn =
+ conn
+ |> set_conversation_cookie("456")
+ |> get("/helpscout/search?conversation_id=123&customer_id=500&term=hs.match")
+
+ assert html_response(conn, 200) =~ "invalid_conversation"
+ end
+ end
+
+ describe "shows/2" do
+ test "returns details on success", %{conn: conn} do
+ user = insert(:user, email: "[email protected]")
+
+ conn =
+ conn
+ |> set_conversation_cookie("123")
+ |> get(
+ "/helpscout/show?conversation_id=123&customer_id=500&[email protected]"
+ )
+
+ assert html_response(conn, 200) =~ "/crm/auth/user/#{user.id}"
+ end
+
+ test "returns error when cookie is missing", %{conn: conn} do
+ conn =
+ get(
+ conn,
+ "/helpscout/show?conversation_id=123&customer_id=500&[email protected]"
+ )
+
+ assert html_response(conn, 200) =~ "invalid_conversation"
+ end
+
+ test "returns error when cookie does not match", %{conn: conn} do
+ conn =
+ conn
+ |> set_conversation_cookie("456")
+ |> get(
+ "/helpscout/show?conversation_id=123&customer_id=500&[email protected]"
+ )
+
+ assert html_response(conn, 200) =~ "invalid_conversation"
+ end
+ end
+
+ defp set_conversation_cookie(conn, conversation_id) do
+ conn
+ |> PlausibleWeb.HelpScoutController.set_cookie(conversation_id)
+ |> recycle()
+ |> Map.put(:secret_key_base, secret_key_base())
+ |> Plug.Conn.put_req_header("x-forwarded-for", Plausible.TestUtils.random_ip())
+ end
+
+ defp secret_key_base() do
+ :plausible
+ |> Application.fetch_env!(PlausibleWeb.Endpoint)
+ |> Keyword.fetch!(:secret_key_base)
end
end
end