7.9 KiB · text History 573fef1
defmodule VigilWeb.OrgLive.Show do
  @moduledoc """
  An organization's front page: events per hour over the last day across
  the projects the caller may see, those projects with their own 24-hour
  counts, and the latest unresolved issues across them. It follows new
  events live (PubSub, per project), refreshing at most once a second.
  """
  use VigilWeb, :live_view

  import VigilWeb.ChartComponents, only: [bars: 1, hourly_points: 1, format_count: 1]

  alias Vigil.Accounts.Scope
  alias Vigil.{Issues, Projects}
  alias Vigil.Projects.Platforms

  @refresh_ms 1000

  @impl true
  def mount(_params, _session, socket) do
    scope = socket.assigns.current_scope
    projects = Projects.list_visible(scope)

    if connected?(socket) do
      Enum.each(projects, &Phoenix.PubSub.subscribe(Vigil.PubSub, "project:#{&1.id}:issues"))
    end

    {:ok,
     socket
     |> assign(:page_title, scope.organization.name)
     |> assign(:project_ids, Enum.map(projects, & &1.id))
     |> assign(:refresh_scheduled?, false)
     |> stream(:projects, projects)
     |> load()}
  end

  defp load(socket) do
    ids = socket.assigns.project_ids
    hourly = Issues.project_hourly(ids)

    socket
    |> assign(:hourly, hourly)
    |> assign(:total_24h, hourly |> Enum.map(&elem(&1, 1)) |> Enum.sum())
    |> assign(:project_counts, Issues.project_counts_24h(ids))
    |> stream(:recent, Issues.recent_across(ids), reset: true)
  end

  @impl true
  def handle_info({:issue_event, _}, socket), do: {:noreply, schedule_refresh(socket)}
  def handle_info({:issue_updated, _}, socket), do: {:noreply, schedule_refresh(socket)}
  def handle_info({:issue_comment, _}, socket), do: {:noreply, socket}

  def handle_info(:refresh, socket) do
    socket = socket |> assign(:refresh_scheduled?, false) |> load()

    # Project counts show inside streamed cards: re-insert them.
    projects = Projects.list_visible(socket.assigns.current_scope)
    {:noreply, stream(socket, :projects, projects, reset: true)}
  end

  defp schedule_refresh(%{assigns: %{refresh_scheduled?: true}} = socket), do: socket

  defp schedule_refresh(socket) do
    Process.send_after(self(), :refresh, @refresh_ms)
    assign(socket, :refresh_scheduled?, true)
  end

  @impl true
  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope} active={:projects}>
      <.header>
        {@current_scope.organization.name}
        <:subtitle>
          <%= if Scope.global?(@current_scope) or @current_scope.organization.open_membership do %>
            Every project in the organization.
          <% else %>
            The projects of your teams.
          <% end %>
        </:subtitle>
        <:actions>
          <.link
            :if={Scope.can?(@current_scope, "project:write")}
            navigate={~p"/orgs/#{@current_scope.organization.slug}/projects/new"}
            class="btn btn-primary btn-sm"
            id="new-project"
          >
            <.icon name="hero-plus-micro" class="size-4" /> New project
          </.link>
        </:actions>
      </.header>

      <section
        id="events-chart"
        class="rounded-box border border-base-300 bg-base-100 p-5"
        aria-labelledby="events-chart-title"
      >
        <div class="flex items-baseline justify-between gap-3">
          <h2 id="events-chart-title" class="text-sm font-semibold">
            Events per hour, last 24 hours
          </h2>
          <p class="text-sm text-base-content/70">
            <span id="events-total" class="text-2xl font-bold tabular-nums text-base-content">
              {format_count(@total_24h)}
            </span>
            events
          </p>
        </div>
        <.bars
          id="events"
          points={hourly_points(@hourly)}
          label="Events per hour over the last 24 hours"
          key_header="Hour (UTC)"
          value_header="Events"
        />
      </section>

      <div class="grid gap-6 lg:grid-cols-[1fr_22rem]">
        <section>
          <h2 class="mb-3 text-sm font-semibold">Latest unresolved issues</h2>
          <ul
            id="recent-issues"
            phx-update="stream"
            class="divide-y divide-base-300 rounded-box border border-base-300 bg-base-100"
          >
            <li
              id="recent-empty"
              class="hidden p-6 text-center text-sm text-base-content/60 only:block"
            >
              Nothing unresolved. Quiet day.
            </li>
            <li :for={{dom_id, issue} <- @streams.recent} id={dom_id}>
              <.link
                navigate={
                  ~p"/orgs/#{@current_scope.organization.slug}/projects/#{issue.project.slug}/issues/#{issue.short_id}"
                }
                class="group flex items-center gap-3 px-4 py-3 transition hover:bg-base-200/60"
              >
                <span
                  class={["h-8 w-1 shrink-0 rounded-full", level_class(issue.level)]}
                  aria-hidden="true"
                />
                <div class="min-w-0 flex-1">
                  <p class="truncate text-sm font-medium group-hover:text-primary">{issue.title}</p>
                  <p class="truncate text-xs text-base-content/60">
                    <span class="font-mono">{String.upcase(issue.project.slug)}-{issue.short_id}</span>
                    <span :if={issue.culprit}> · {issue.culprit}</span>
                  </p>
                </div>
                <div class="shrink-0 text-right text-xs text-base-content/60">
                  <p class="font-semibold tabular-nums text-base-content">
                    {format_count(issue.count)}
                  </p>
                  <p title={DateTime.to_iso8601(issue.last_seen)}>{relative(issue.last_seen)}</p>
                </div>
              </.link>
            </li>
          </ul>
        </section>

        <section>
          <h2 class="mb-3 text-sm font-semibold">Projects</h2>
          <ul id="project-list" phx-update="stream" class="space-y-2">
            <li
              id="project-list-empty"
              class="hidden rounded-box border border-dashed border-base-300 p-6 text-center text-sm text-base-content/60 only:block"
            >
              No projects to show yet. A project is where one app's errors land.
            </li>
            <li :for={{dom_id, p} <- @streams.projects} id={dom_id}>
              <.link
                navigate={~p"/orgs/#{@current_scope.organization.slug}/projects/#{p.slug}"}
                class="group flex items-center justify-between gap-3 rounded-box border border-base-300 bg-base-100 px-4 py-3 transition hover:-translate-y-0.5 hover:border-primary/50 hover:shadow-md"
              >
                <div class="min-w-0">
                  <p class="truncate font-semibold group-hover:text-primary">{p.name}</p>
                  <p class="text-xs text-base-content/60">
                    {Platforms.name(p.platform)}
                    <span :if={is_nil(p.first_event_at)}> · waiting for its first event</span>
                  </p>
                </div>
                <span class="text-right text-xs text-base-content/60">
                  <span class="block text-base font-semibold tabular-nums text-base-content">
                    {format_count(Map.get(@project_counts, p.id, 0))}
                  </span>
                  24h
                </span>
              </.link>
            </li>
          </ul>
        </section>
      </div>
    </Layouts.app>
    """
  end

  defp level_class("fatal"), do: "bg-error"
  defp level_class("error"), do: "bg-error/80"
  defp level_class("warning"), do: "bg-warning"
  defp level_class("info"), do: "bg-info"
  defp level_class(_), do: "bg-base-300"

  defp relative(%DateTime{} = at) do
    seconds = DateTime.diff(DateTime.utc_now(), at)

    cond do
      seconds < 60 -> "just now"
      seconds < 3600 -> "#{div(seconds, 60)}m ago"
      seconds < 86_400 -> "#{div(seconds, 3600)}h ago"
      true -> "#{div(seconds, 86_400)}d ago"
    end
  end
end