Skip to content

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

18.6 KB
Raw Blame
defmodule PlausibleWeb.Live.FunnelSettings.Form do
  @moduledoc """
  Phoenix LiveComponent that renders a form used for setting up dynamic funnels.
  """

  use PlausibleWeb, :live_view
  use Plausible.Funnel

  import PlausibleWeb.Live.Components.Form

  alias Plausible.Funnels
  alias Plausible.Stats.QueryBuilder

  def mount(_params, %{"domain" => domain} = session, socket) do
    site =
      Plausible.Sites.get_for_user!(socket.assigns.current_user, domain,
        roles: [
          :owner,
          :admin,
          :editor,
          :super_admin
        ]
      )

    goals =
      site
      |> Plausible.Goals.for_site()
      |> Enum.map(fn goal ->
        struct!(
          Plausible.Goal,
          Map.take(goal, [
            :id,
            :display_name,
            :event_name,
            :page_path,
            :scroll_threshold,
            :currency,
            :custom_props
          ])
        )
      end)

    socket =
      socket
      |> assign(site: site, goals: goals, evaluation_result: nil)
      |> prepare_socket(site, session["funnel_id"])

    {:ok, socket}
  end

  def render(assigns) do
    ~H"""
    <div class="fixed inset-0 flex items-center justify-center mt-16 z-50 overlofw-y-auto overflow-x-hidden">
      <div class="md:w-2/3 max-w-xl h-full">
        <div
          id="funnel-form"
          class="group relative"
          phx-click-away="cancel-add-funnel"
          phx-target="#funnel-form"
        >
          <div class="absolute inset-0 z-10 hidden items-center justify-center rounded-lg bg-white/50 dark:bg-gray-900/50 group-has-[.phx-click-loading]:flex">
            <.spinner class="h-8 w-8" />
          </div>

          <.form
            :let={f}
            for={@form}
            phx-change="validate"
            phx-submit="save"
            phx-target="#funnel-form"
            onkeydown="return event.key != 'Enter';"
            class="bg-white dark:bg-gray-900 shadow-2xl rounded-lg px-8 pt-6 pb-8 mb-4 mt-8"
          >
            <.title class="mb-6">
              {if @funnel, do: "Edit", else: "Add"} funnel
            </.title>

            <.input
              field={f[:name]}
              phx-debounce={200}
              autocomplete="off"
              placeholder="e.g. From Blog to Purchase"
              autofocus
              label="Funnel name"
            />

            <div class="flex flex-col gap-y-1 mt-8">
              <.label>
                Funnel type
              </.label>
              <div class="flex items-center justify-between gap-4 mt-2">
                <.input
                  type="radio"
                  id={f[:funnel_type].id <> "_sequential"}
                  name={f[:funnel_type].name}
                  value="sequential"
                  checked={@funnel_type == :sequential}
                  phx-click="switch-type"
                  phx-value-type="sequential"
                  label="Sequential"
                >
                  <:help_content>
                    All steps are required. Other activity is allowed between steps.
                  </:help_content>
                </.input>
              </div>

              <div class="flex items-center justify-between gap-4">
                <.input
                  type="radio"
                  id={f[:funnel_type].id <> "_flexible"}
                  name={f[:funnel_type].name}
                  value="flexible"
                  checked={@funnel_type == :flexible}
                  phx-click="switch-type"
                  phx-value-type="flexible"
                  label="Flexible"
                >
                  <:help_content>
                    Only the first and last steps are required. Middle steps can be skipped.
                  </:help_content>
                </.input>
              </div>

              <div class="flex items-center justify-between gap-4">
                <.input
                  type="radio"
                  id={f[:funnel_type].id <> "_strict"}
                  name={f[:funnel_type].name}
                  value="strict"
                  checked={@funnel_type == :strict}
                  phx-click="switch-type"
                  phx-value-type="strict"
                  label="Strict"
                >
                  <:help_content>
                    All steps are required. No other activity is allowed between steps.
                  </:help_content>
                </.input>
              </div>
            </div>

            <div id="steps-builder" class="mt-6">
              <.label>
                Funnel steps
              </.label>

              <div :for={step_idx <- @step_ids} class="flex items-center my-3">
                <div class="w-2/5 flex-1">
                  <.live_component
                    id={"step-#{step_idx}"}
                    module={PlausibleWeb.Live.Components.PrimaCombobox}
                    submit_name={"funnel[steps][#{step_idx}][step_data]"}
                    selected={selected_option(@steps, step_idx)}
                    suggest_trigger={@steps}
                    suggest_fun={
                      fn input, _suggestions -> suggest(input, @site, @goals, @steps, step_idx) end
                    }
                  />
                </div>

                <div class="w-min inline-flex items-center align-middle">
                  <.remove_step_button
                    :if={length(@step_ids) > Funnel.min_steps()}
                    step_idx={step_idx}
                  />
                </div>

                <div class="w-4/12 ml-4 text-gray-500 dark:text-gray-400">
                  <.evaluation
                    :if={@evaluation_result}
                    result={@evaluation_result}
                    at={Enum.find_index(@step_ids, &(&1 == step_idx))}
                  />
                </div>
              </div>

              <div class="flex flex-col gap-y-2 mt-2">
                <p>
                  <.add_step_button :if={length(@step_ids) < Funnel.max_steps()} />
                </p>
                <p id="funnel-eval" class="text-gray-800 dark:text-gray-200 text-sm">
                  <%= if @evaluation_result do %>
                    Last month conversion rate: <strong><%= List.last(@evaluation_result.steps).conversion_rate %></strong>%
                  <% end %>
                </p>
              </div>

              <.button
                id="save"
                type="submit"
                class="w-full mt-4"
                disabled={
                  has_steps_errors?(f) or map_size(@steps) < Funnel.min_steps() or
                    length(@step_ids) > map_size(@steps)
                }
              >
                <span>{if @funnel, do: "Update", else: "Add"} funnel</span>
              </.button>
            </div>
          </.form>
        </div>
      </div>
    </div>
    """
  end

  attr(:step_idx, :integer, required: true)

  def remove_step_button(assigns) do
    ~H"""
    <div class="inline-flex items-center ml-2 text-red-500">
      <svg
        id={"remove-step-#{@step_idx}"}
        class="feather feather-sm cursor-pointer"
        xmlns="http://www.w3.org/2000/svg"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        stroke-linecap="round"
        stroke-linejoin="round"
        phx-click="remove-step"
        phx-value-step-idx={@step_idx}
      >
        <polyline points="3 6 5 6 21 6"></polyline>
        <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2">
        </path>
        <line x1="10" y1="11" x2="10" y2="17"></line>
        <line x1="14" y1="11" x2="14" y2="17"></line>
      </svg>
    </div>
    """
  end

  def add_step_button(assigns) do
    ~H"""
    <a class="text-indigo-500 text-sm font-medium cursor-pointer" phx-click="add-step">
      + Add another step
    </a>
    """
  end

  attr(:at, :integer, required: true)
  attr(:result, :map, required: true)

  def evaluation(assigns) do
    ~H"""
    <span class="text-sm" id={"step-eval-#{@at}"}>
      <% step = Enum.at(@result.steps, @at) %>
      <span :if={step && @at == 0}>
        <span
          class="border-dotted border-b border-gray-400 "
          tooltip="Sample calculation for last month"
        >
          <span class="hidden md:inline">Visitors: </span><strong><%= PlausibleWeb.StatsView.large_number_format(@result.entering_visitors) %></strong>
        </span>
      </span>
      <span :if={step && @at > 0}>
        <span class="hidden md:inline">Dropoff: </span><strong><%= Map.get(step, :dropoff_percentage) %>%</strong>
      </span>
    </span>
    """
  end

  def handle_event("add-step", _value, socket) do
    step_ids = socket.assigns.step_ids

    if length(step_ids) < Funnel.max_steps() do
      first_free_idx = find_sequence_break(step_ids)
      new_ids = step_ids ++ [first_free_idx]
      {:noreply, assign(socket, step_ids: new_ids)}
    else
      {:noreply, socket}
    end
  end

  def handle_event("remove-step", %{"step-idx" => idx}, socket) do
    idx = String.to_integer(idx)
    step_ids = List.delete(socket.assigns.step_ids, idx)
    steps = drop_step(socket.assigns.steps, idx)

    send(self(), :evaluate_funnel)

    {:noreply, assign(socket, step_ids: step_ids, steps: steps)}
  end

  def handle_event("switch-type", %{"type" => funnel_type_str}, socket) do
    funnel_type = String.to_existing_atom(funnel_type_str)
    send(self(), :evaluate_funnel)

    {:noreply, assign(socket, funnel_type: funnel_type)}
  end

  def handle_event("validate", %{"funnel" => params}, socket) do
    funnel_type = socket.assigns.funnel_type
    allowed_goal_ids = Enum.map(socket.assigns.goals, & &1.id)

    steps_with_idx =
      params
      |> Map.get("steps", [])
      |> Enum.sort_by(&elem(&1, 0))
      |> Enum.map(fn {idx, payload} -> {idx, JSON.decode!(payload["step_data"])} end)

    changeset =
      socket.assigns.site
      |> Funnels.create_changeset(
        params["name"],
        Enum.map(steps_with_idx, &elem(&1, 1)),
        funnel_type: funnel_type,
        allowed_goal_ids: allowed_goal_ids
      )
      |> Map.put(:action, :validate)

    steps = store_steps(socket.assigns, steps_with_idx)

    send(self(), :evaluate_funnel)

    {:noreply, assign(socket, form: to_form(changeset), steps: steps)}
  end

  def handle_event(
        "save",
        %{"funnel" => params},
        %{
          assigns: %{
            site: site,
            funnel: funnel,
            funnel_type: funnel_type
          }
        } = socket
      ) do
    steps =
      Enum.map(params["steps"], fn {_idx, payload} -> JSON.decode!(payload["step_data"]) end)

    save_fn =
      case funnel do
        %Plausible.Funnel{} ->
          fn ->
            Funnels.update(funnel, params["name"], steps, funnel_type: funnel_type)
          end

        nil ->
          fn ->
            Funnels.create(site, params["name"], steps, funnel_type: funnel_type)
          end
      end

    case save_fn.() do
      {:ok, funnel} ->
        send(
          socket.parent_pid,
          {:funnel_saved, Map.put(funnel, :steps_count, length(steps))}
        )

        {:noreply, socket}

      {:error, changeset} ->
        {:noreply,
         assign(socket,
           form: to_form(Map.put(changeset, :action, :validate))
         )}
    end
  end

  def handle_event("cancel-add-funnel", _value, socket) do
    send(socket.parent_pid, :cancel_setup_funnel)
    {:noreply, socket}
  end

  def handle_info(:evaluate_funnel, socket) do
    {:noreply, evaluate_funnel(socket)}
  end

  defp suggest(input, site, goals, steps, step_idx) do
    steps =
      steps
      |> Enum.filter(fn {idx, _} -> idx != "step-#{step_idx}" end)
      |> Enum.map(&elem(&1, 1))

    query =
      QueryBuilder.build!(site,
        metrics: [:pageviews],
        input_date_range: query_date_range()
      )

    {goals_for_query, other_goals} =
      Enum.split_with(goals, fn g ->
        g.scroll_threshold == -1 and map_size(g.custom_props) == 0 and is_nil(g.currency)
      end)

    {suggestions, unmatched_query_goals} =
      Plausible.Stats.Funnel.suggest(site, query, goals: goals_for_query, input: input)

    unmatched_goal_entries =
      (unmatched_query_goals ++ other_goals)
      |> static_suggest(input)
      |> to_suggestion_entries(steps)

    suggestions
    |> to_suggestion_entries(steps)
    |> Enum.concat(unmatched_goal_entries)
    |> segment()
  end

  defp static_suggest(goals, input) do
    # NOTE: static search for goals logic should be in sync with
    # `Plausible.Stats.Exploration.maybe_search/2`.

    case String.trim(input) do
      term when byte_size(term) > 2 ->
        term = String.downcase(term)

        Enum.filter(goals, fn g ->
          display_name = String.downcase(g.display_name)
          event_name = String.downcase(g.event_name || "")
          page_path = String.downcase(g.page_path || "")

          String.contains?(display_name, term) or String.contains?(event_name, term) or
            String.contains?(page_path, term)
        end)

      _ ->
        goals
    end
  end

  defp to_suggestion_entries(suggestions, steps) do
    suggestions
    |> exclude_existing_steps(steps)
    |> Enum.map(
      &{to_step_data(&1), to_string(&1),
       [goal: &1, type: if(&1.event_name, do: :custom_event, else: :pageview)]}
    )
    |> set_icons()
  end

  defp set_icons(suggestions) do
    Enum.map(suggestions, fn {value, display_name, opts} ->
      icon =
        case opts[:type] do
          :custom_event -> :cursor
          :pageview -> :eye
        end

      {value, display_name, Keyword.put(opts, :icon, icon)}
    end)
  end

  defp segment(suggestions) do
    suggestions
    |> Enum.group_by(fn {_, _, opts} -> opts[:type] end)
    |> Enum.sort_by(fn {k, _} ->
      case k do
        :custom_event -> 0
        :pageview -> 1
      end
    end)
    |> Enum.reduce([], fn {_, segment}, acc ->
      [{value, display_name, opts} | rest] = segment

      separator? = acc != []

      title =
        case opts[:type] do
          :custom_event -> "Custom events"
          :pageview -> "Pageviews"
        end

      opts =
        opts
        |> Keyword.put(:title, title)
        |> Keyword.put(:separator?, separator?)

      acc ++ [{value, display_name, opts} | rest]
    end)
  end

  defp exclude_existing_steps(goals, steps) do
    existing_steps =
      MapSet.new(steps, &{&1.event_name, &1.page_path, &1.scroll_threshold, &1.custom_props})

    Enum.reject(
      goals,
      &MapSet.member?(
        existing_steps,
        {&1.event_name, &1.page_path, &1.scroll_threshold, &1.custom_props}
      )
    )
  end

  defp has_steps_errors?(f) do
    not f.source.valid?
  end

  defp store_steps(assigns, steps_with_idx) do
    Enum.reduce(steps_with_idx, assigns.steps, fn {idx, step_data}, steps ->
      Map.put(steps, "step-#{idx}", to_goal(step_data))
    end)
  end

  defp drop_step(steps, idx) do
    step_input_id = "step-#{idx}"
    Map.delete(steps, step_input_id)
  end

  defp selected_option(steps, idx) do
    if goal = steps["step-#{idx}"] do
      {to_step_data(goal), to_string(goal)}
    end
  end

  defp to_goal(%{"goal_id" => goal_id} = step_data) do
    step_data
    |> Map.delete("goal_id")
    |> then(&Plausible.Goal.changeset(%Plausible.Goal{}, &1))
    |> Ecto.Changeset.apply_changes()
    |> Map.put(:id, goal_id)
  end

  defp to_goal(step_data) do
    step_data
    |> Funnel.DynamicStep.changeset()
    |> Ecto.Changeset.apply_changes()
    |> Funnel.DynamicStep.as_goal()
  end

  defp to_step_data(%Plausible.Goal{} = goal) do
    data = %{
      event_name: goal.event_name,
      page_path: goal.page_path,
      display_name: goal.display_name,
      scroll_threshold: goal.scroll_threshold,
      currency: goal.currency
    }

    data =
      if is_integer(goal.id) and goal.id > 0 do
        Map.put(data, :goal_id, goal.id)
      else
        data
      end

    JSON.encode!(data)
  end

  defp find_sequence_break(input) do
    input
    |> Enum.sort()
    |> Enum.with_index(1)
    |> Enum.reduce_while(nil, fn {x, order}, _ ->
      if x != order do
        {:halt, order}
      else
        {:cont, order + 1}
      end
    end)
  end

  defp evaluate_funnel(%{assigns: %{steps: steps}} = socket)
       when map_size(steps) < Funnel.min_steps() do
    socket
  end

  defp evaluate_funnel(
         %{
           assigns: %{
             site: site,
             steps: steps,
             funnel_type: funnel_type,
             goals: goals
           }
         } = socket
       ) do
    with {:ok, {definition, query}} <-
           build_ephemeral_funnel(site, steps, funnel_type: funnel_type, goals: goals),
         {:ok, funnel} <- Plausible.Stats.funnel(site, query, definition) do
      assign(socket, evaluation_result: funnel)
    else
      _ ->
        socket
    end
  end

  defp build_ephemeral_funnel(site, steps, opts) do
    {goals, opts} = Keyword.pop(opts, :goals, [])
    opts = Keyword.put(opts, :allowed_goal_ids, Enum.map(goals, & &1.id))

    steps =
      steps
      |> Enum.sort_by(&elem(&1, 0))
      |> Enum.map(fn {_, goal} ->
        step_data = %{
          "event_name" => goal.event_name,
          "page_path" => goal.page_path,
          "currency" => goal.currency,
          "scroll_threshold" => goal.scroll_threshold,
          "custom_props" => goal.custom_props
        }

        if goal.id > 0 do
          %{
            "goal_id" => goal.id,
            "goal" => Map.put(step_data, "id", goal.id)
          }
        else
          step_data
        end
      end)

    definition =
      Funnels.ephemeral_definition(
        site,
        "Test funnel",
        steps,
        opts
      )

    query =
      QueryBuilder.build!(site,
        metrics: [:pageviews],
        input_date_range: query_date_range()
      )

    {:ok, {definition, query}}
  end

  defp query_date_range() do
    now = DateTime.utc_now()
    thirty_days_ago = DateTime.add(now, -30, :day)
    {:datetime_range, thirty_days_ago, now}
  end

  defp prepare_socket(socket, site, funnel_id) when is_integer(funnel_id) do
    funnel = Funnels.get(site.id, funnel_id)
    steps = Funnel.goals(funnel)

    form =
      funnel
      |> Funnels.edit_changeset(funnel.name, steps)
      |> to_form()

    steps =
      Enum.reduce(Enum.with_index(steps, 1), %{}, fn {step, idx}, acc ->
        Map.put(acc, "step-#{idx}", step)
      end)

    socket =
      assign(
        socket,
        form: form,
        funnel: funnel,
        funnel_type: funnel.funnel_type,
        steps: steps,
        step_ids: Enum.to_list(1..Enum.count(steps))
      )

    evaluate_funnel(socket)
  end

  defp prepare_socket(socket, site, nil) do
    form = to_form(Funnels.create_changeset(site, "", []))

    assign(
      socket,
      form: form,
      funnel: nil,
      funnel_type: :sequential,
      steps: Map.new(),
      step_ids: Enum.to_list(1..Funnel.min_steps())
    )
  end
end