17.5 KiB · text History 573fef1
defmodule VigilWeb.ProjectLive.Alerts do
  @moduledoc """
  A project's alerts (`Vigil.Alerts`): its rules and where each sends,
  a test message to any recipient, your own email subscription, and the
  latest deliveries with how they went (GlitchTip keeps no such record).
  Managing rules needs `project:write`; anyone who can see the project can
  turn its email alerts off for themselves.
  """
  use VigilWeb, :live_view

  alias Vigil.Accounts.Scope
  alias Vigil.Alerts
  alias Vigil.Alerts.{Recipient, Rule}

  @kinds [
    {"Events in a window (N events in M minutes)", :frequency},
    {"A new issue", :new_issue},
    {"A resolved issue comes back", :regression},
    {"A cron monitor fails or recovers", :monitor},
    {"An uptime monitor goes down or comes back", :uptime}
  ]

  @recipient_types [
    {"Email (subscribed members)", :email},
    {"Webhook (Slack-compatible)", :webhook},
    {"Discord", :discord},
    {"Google Chat", :googlechat},
    {"ntfy", :ntfy},
    {"Microsoft Teams", :teams},
    {"Zulip", :zulip}
  ]

  @impl true
  def mount(_params, _session, socket) do
    %{current_scope: scope, project: project} = socket.assigns

    {:ok,
     socket
     |> assign(:page_title, "#{project.name} · Alerts")
     |> assign(:can_manage?, Scope.can?(scope, "project:write"))
     |> assign(:subscribed?, Alerts.subscribed?(scope.user, project))
     |> assign(:rule_form, new_rule_form())
     |> assign(:recipient_rule_id, nil)
     |> assign(:recipient_form, nil)
     |> load()}
  end

  defp load(socket) do
    project = socket.assigns.project

    socket
    |> assign(:rules, Alerts.list_rules(project))
    |> stream(:deliveries, Alerts.list_deliveries(project), reset: true)
  end

  defp new_rule_form,
    do:
      to_form(
        Alerts.change_rule(%Rule{}, %{kind: :frequency, quantity: 10, timespan_minutes: 60})
      )

  defp project_path(scope, project),
    do: ~p"/orgs/#{scope.organization.slug}/projects/#{project.slug}"

  @impl true
  def render(assigns) do
    assigns = assign(assigns, kinds: @kinds, recipient_types: @recipient_types)

    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope} active={:projects}>
      <div class="mx-auto max-w-4xl space-y-8">
        <.header>
          {@project.name} alerts
          <:subtitle>Who hears about this project's issues, and when.</:subtitle>
          <:actions>
            <.link navigate={project_path(@current_scope, @project)} class="btn btn-ghost btn-sm">
              <.icon name="hero-arrow-left-micro" class="size-4" /> Issues
            </.link>
          </:actions>
        </.header>

        <section
          id="my-subscription"
          class="flex flex-wrap items-center justify-between gap-3 rounded-box border border-base-300 bg-base-100 p-4"
        >
          <div>
            <p class="font-medium">Email alerts for you</p>
            <p class="text-sm text-base-content/60">
              {if @subscribed?,
                do: "On: email recipients include you.",
                else: "Off: you won't get this project's alert emails."}
            </p>
          </div>
          <button
            type="button"
            id="toggle-subscription"
            class={["btn btn-sm", if(@subscribed?, do: "btn-ghost", else: "btn-primary")]}
            phx-click="toggle_subscription"
          >
            {if @subscribed?, do: "Turn off", else: "Turn on"}
          </button>
        </section>

        <section class="space-y-4">
          <h2 class="font-semibold">Rules</h2>

          <p
            :if={@rules == []}
            id="rules-empty"
            class="rounded-box border border-dashed border-base-300 p-6 text-center text-sm text-base-content/60"
          >
            No rules yet: nobody is told about this project's issues.
          </p>

          <article
            :for={rule <- @rules}
            id={"rule-#{rule.id}"}
            class={[
              "space-y-3 rounded-box border bg-base-100 p-4 transition",
              if(rule.enabled,
                do: "border-base-300",
                else: "border-dashed border-base-300 opacity-70"
              )
            ]}
          >
            <div class="flex flex-wrap items-start justify-between gap-2">
              <div>
                <p class="font-semibold">{rule.name}</p>
                <p class="text-sm text-base-content/70">{describe(rule)}</p>
              </div>
              <div :if={@can_manage?} class="flex gap-1">
                <button
                  type="button"
                  id={"toggle-rule-#{rule.id}"}
                  class="btn btn-ghost btn-xs"
                  phx-click="toggle_rule"
                  phx-value-id={rule.id}
                >
                  {if rule.enabled, do: "Pause", else: "Resume"}
                </button>
                <button
                  type="button"
                  id={"delete-rule-#{rule.id}"}
                  class="btn btn-ghost btn-xs text-error"
                  phx-click="delete_rule"
                  phx-value-id={rule.id}
                  data-confirm={"Delete the rule #{rule.name}?"}
                >
                  Delete
                </button>
              </div>
            </div>

            <ul class="space-y-1" id={"recipients-#{rule.id}"}>
              <li :if={rule.recipients == []} class="text-xs text-base-content/60">
                No recipients: it emails the project's subscribed members.
              </li>
              <li
                :for={r <- rule.recipients}
                id={"recipient-#{r.id}"}
                class="flex flex-wrap items-center gap-2 text-sm"
              >
                <span class="badge badge-ghost badge-sm">{type_label(r.type)}</span>
                <span class="min-w-0 flex-1 truncate font-mono text-xs text-base-content/70">{r.url ||
                  "subscribed members"}</span>
                <button
                  :if={@can_manage?}
                  type="button"
                  id={"test-#{r.id}"}
                  class="btn btn-ghost btn-xs"
                  phx-click="test"
                  phx-value-rule={rule.id}
                  phx-value-id={r.id}
                  phx-disable-with="Sending…"
                >
                  Send test
                </button>
                <button
                  :if={@can_manage?}
                  type="button"
                  id={"remove-#{r.id}"}
                  class="btn btn-ghost btn-xs text-error"
                  phx-click="remove_recipient"
                  phx-value-rule={rule.id}
                  phx-value-id={r.id}
                >
                  Remove
                </button>
              </li>
            </ul>

            <%= if @can_manage? do %>
              <%= if @recipient_rule_id == rule.id do %>
                <.form
                  for={@recipient_form}
                  id={"recipient-form-#{rule.id}"}
                  phx-change="validate_recipient"
                  phx-submit="add_recipient"
                  class="space-y-2 rounded-box bg-base-200/60 p-3"
                >
                  <input type="hidden" name="rule" value={rule.id} />
                  <div class="grid gap-x-3 sm:grid-cols-[12rem_1fr]">
                    <.input
                      field={@recipient_form[:type]}
                      type="select"
                      label="Send to"
                      options={@recipient_types}
                    />
                    <.input
                      :if={@recipient_form[:type].value not in [:email, "email"]}
                      field={@recipient_form[:url]}
                      label={
                        if @recipient_form[:type].value in [:zulip, "zulip"],
                          do: "Zulip server URL",
                          else: "Webhook URL"
                      }
                      placeholder="https://…"
                    />
                  </div>
                  <div
                    :if={@recipient_form[:type].value in [:zulip, "zulip"]}
                    class="grid gap-x-3 sm:grid-cols-2"
                  >
                    <.input
                      name="recipient[config][bot_email]"
                      label="Bot email"
                      value={config(@recipient_form, "bot_email")}
                    />
                    <.input
                      name="recipient[config][api_key]"
                      label="API key"
                      type="password"
                      value={config(@recipient_form, "api_key")}
                    />
                    <.input
                      name="recipient[config][channel]"
                      label="Channel"
                      value={config(@recipient_form, "channel")}
                    />
                    <.input
                      name="recipient[config][topic]"
                      label="Topic"
                      value={config(@recipient_form, "topic")}
                    />
                  </div>
                  <div :if={@recipient_form[:type].value in [:ntfy, "ntfy"]}>
                    <.input
                      name="recipient[config][token]"
                      label="Access token (optional)"
                      type="password"
                      value={config(@recipient_form, "token")}
                    />
                  </div>
                  <div class="flex gap-2">
                    <.button class="btn btn-primary btn-sm" phx-disable-with="Adding…">Add</.button>
                    <button type="button" class="btn btn-ghost btn-sm" phx-click="cancel_recipient">Cancel</button>
                  </div>
                </.form>
              <% else %>
                <button
                  type="button"
                  id={"add-recipient-#{rule.id}"}
                  class="btn btn-ghost btn-xs"
                  phx-click="new_recipient"
                  phx-value-rule={rule.id}
                >
                  <.icon name="hero-plus-micro" class="size-4" /> Add recipient
                </button>
              <% end %>
            <% end %>
          </article>

          <.form
            :if={@can_manage?}
            for={@rule_form}
            id="rule-form"
            phx-change="validate_rule"
            phx-submit="create_rule"
            class="space-y-2 rounded-box border border-base-300 bg-base-200/60 p-4"
          >
            <h3 class="text-sm font-semibold">New rule</h3>
            <div class="grid gap-x-3 sm:grid-cols-2">
              <.input field={@rule_form[:name]} label="Name" placeholder="Busy errors" required />
              <.input field={@rule_form[:kind]} type="select" label="When" options={@kinds} />
            </div>
            <div
              :if={@rule_form[:kind].value in [:frequency, "frequency"]}
              class="grid gap-x-3 sm:grid-cols-2"
            >
              <.input
                field={@rule_form[:quantity]}
                type="number"
                label="At least this many events"
                min="1"
              />
              <.input
                field={@rule_form[:timespan_minutes]}
                type="number"
                label="Within minutes"
                min="1"
              />
            </div>
            <.input
              :if={@rule_form[:kind].value not in [:monitor, "monitor", :uptime, "uptime"]}
              field={@rule_form[:renotify_minutes]}
              type="number"
              label="Tell again after minutes (empty: once, until it regresses)"
              min="1"
            />
            <.button class="btn btn-primary btn-sm" phx-disable-with="Creating…">Create rule</.button>
          </.form>
        </section>

        <section class="space-y-2">
          <h2 class="font-semibold">Recent deliveries</h2>
          <ul
            id="deliveries"
            phx-update="stream"
            class="divide-y divide-base-300 rounded-box border border-base-300 bg-base-100"
          >
            <li
              id="deliveries-empty"
              class="hidden p-4 text-center text-sm text-base-content/60 only:block"
            >
              Nothing sent yet.
            </li>
            <li
              :for={{dom_id, d} <- @streams.deliveries}
              id={dom_id}
              class="flex flex-wrap items-center gap-3 px-4 py-2 text-sm"
            >
              <span class={["badge badge-sm", state_class(d.state)]}>{d.state}</span>
              <span class="font-medium">{d.notification.alert_rule.name}</span>
              <span class="text-base-content/60">{d.type}</span>
              <span
                class="ml-auto text-xs text-base-content/60"
                title={DateTime.to_iso8601(d.inserted_at)}
              >
                {Calendar.strftime(d.inserted_at, "%b %-d %H:%M")} · {length(d.notification.issue_ids)} issue(s)
              </span>
              <p :if={d.error} class="w-full truncate font-mono text-xs text-error" title={d.error}>
                {d.error}
              </p>
            </li>
          </ul>
        </section>
      </div>
    </Layouts.app>
    """
  end

  defp describe(%Rule{kind: :frequency} = r),
    do: "#{r.quantity}+ events in #{r.timespan_minutes} min" <> renotify(r)

  defp describe(%Rule{kind: :new_issue} = r), do: "A new issue" <> renotify(r)
  defp describe(%Rule{kind: :regression} = r), do: "A resolved issue comes back" <> renotify(r)
  defp describe(%Rule{kind: :monitor}), do: "A cron monitor fails or recovers · once per incident"

  defp describe(%Rule{kind: :uptime}),
    do: "An uptime monitor goes down or comes back · once per change"

  defp renotify(%Rule{renotify_minutes: nil}), do: " · once per issue, until it regresses"
  defp renotify(%Rule{renotify_minutes: m}), do: " · again after #{m} min"

  defp type_label(type),
    do: Enum.find_value(@recipient_types, to_string(type), fn {l, t} -> t == type && l end)

  defp state_class(:sent), do: "badge-success"
  defp state_class(:failed), do: "badge-error"
  defp state_class(_), do: "badge-ghost"

  defp config(form, key), do: (form.params["config"] || %{})[key]

  @impl true
  def handle_event("toggle_subscription", _params, socket) do
    %{current_scope: scope, project: project, subscribed?: on?} = socket.assigns
    :ok = Alerts.set_subscription(scope.user, project, !on?)
    {:noreply, assign(socket, :subscribed?, !on?)}
  end

  def handle_event("validate_rule", %{"rule" => params}, socket) do
    {:noreply,
     assign(socket, :rule_form, to_form(Alerts.change_rule(%Rule{}, params), action: :validate))}
  end

  def handle_event("create_rule", %{"rule" => params}, socket) do
    case Alerts.create_rule(socket.assigns.current_scope, socket.assigns.project, params) do
      {:ok, _} ->
        {:noreply,
         socket
         |> assign(:rule_form, new_rule_form())
         |> load()
         |> put_flash(:info, "Rule created.")}

      {:error, %Ecto.Changeset{} = cs} ->
        {:noreply, assign(socket, :rule_form, to_form(cs))}

      {:error, _} ->
        {:noreply, put_flash(socket, :error, "You can't change this project's alerts.")}
    end
  end

  def handle_event("toggle_rule", %{"id" => id}, socket) do
    rule = Alerts.get_rule!(socket.assigns.project, id)

    socket
    |> result(Alerts.update_rule(socket.assigns.current_scope, rule, %{enabled: !rule.enabled}))
  end

  def handle_event("delete_rule", %{"id" => id}, socket) do
    rule = Alerts.get_rule!(socket.assigns.project, id)
    socket |> result(Alerts.delete_rule(socket.assigns.current_scope, rule))
  end

  def handle_event("new_recipient", %{"rule" => rule_id}, socket) do
    {:noreply,
     socket
     |> assign(:recipient_rule_id, rule_id)
     |> assign(
       :recipient_form,
       to_form(Alerts.change_recipient(%Recipient{type: :email}), as: "recipient")
     )}
  end

  def handle_event("cancel_recipient", _params, socket),
    do: {:noreply, assign(socket, recipient_rule_id: nil, recipient_form: nil)}

  def handle_event("validate_recipient", %{"recipient" => params}, socket) do
    cs = Alerts.change_recipient(%Recipient{}, params)
    {:noreply, assign(socket, :recipient_form, to_form(cs, as: "recipient", action: :validate))}
  end

  def handle_event("add_recipient", %{"rule" => rule_id, "recipient" => params}, socket) do
    rule = Alerts.get_rule!(socket.assigns.project, rule_id)

    case Alerts.add_recipient(socket.assigns.current_scope, rule, params) do
      {:ok, _} ->
        {:noreply, socket |> assign(recipient_rule_id: nil, recipient_form: nil) |> load()}

      {:error, %Ecto.Changeset{} = cs} ->
        {:noreply, assign(socket, :recipient_form, to_form(cs, as: "recipient"))}

      {:error, _} ->
        {:noreply, put_flash(socket, :error, "You can't change this project's alerts.")}
    end
  end

  def handle_event("remove_recipient", %{"rule" => rule_id, "id" => id}, socket) do
    rule = Alerts.get_rule!(socket.assigns.project, rule_id)
    socket |> result(Alerts.delete_recipient(socket.assigns.current_scope, rule, id))
  end

  def handle_event("test", %{"rule" => rule_id, "id" => id}, socket) do
    rule = Alerts.get_rule!(socket.assigns.project, rule_id)
    recipient = Enum.find(rule.recipients, &(&1.id == id))

    case recipient &&
           Alerts.send_test(socket.assigns.current_scope, recipient, socket.assigns.project) do
      :ok ->
        {:noreply, put_flash(socket, :info, "Test sent.")}

      nil ->
        {:noreply, socket}

      {:error, reason} ->
        {:noreply, put_flash(socket, :error, "The test didn't go through: #{inspect(reason)}")}
    end
  end

  defp result(socket, {:ok, _}), do: {:noreply, load(socket)}

  defp result(socket, {:error, _}),
    do: {:noreply, put_flash(socket, :error, "You can't change this project's alerts.")}
end