Skip to content

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

1.1 KB
Raw Blame
defmodule Plausible.Funnel.Step do
  @moduledoc """
  This module defines the database schema for a single Funnel step.
  See: `Plausible.Funnel` for more information.
  """

  use Ecto.Schema
  import Ecto.Changeset

  @type t() :: %__MODULE__{}
  schema "funnel_steps" do
    field :step_order, :integer
    belongs_to :funnel, Plausible.Funnel
    belongs_to :goal, Plausible.Goal
    timestamps()
  end

  @spec changeset(map() | Plausible.Goal.t() | t()) :: Ecto.Changeset.t()
  def changeset(goal_step_or_attrs \\ %{})

  def changeset(%__MODULE__{} = step), do: change(step)

  def changeset(%Plausible.Goal{id: goal_id}) do
    changeset(%{goal_id: goal_id})
  end

  def changeset(attrs) do
    %__MODULE__{}
    |> cast(attrs, [:goal_id])
    |> cast_assoc(:goal)
    |> validate_required([:goal_id])
    |> unique_constraint(:goal,
      name: :funnel_steps_goal_id_funnel_id_index
    )
  end

  @spec as_goal(t()) :: Plausible.Goal.t()
  def as_goal(step) do
    case step.goal do
      %Plausible.Goal{} = g ->
        g

      other ->
        raise "Expected goal, got: #{inspect(other)}"
    end
  end
end