8.8 KiB · text History 573fef1
defmodule VigilWeb.UserLive.Invites do
  @moduledoc """
  Your registration invites (`Vigil.Accounts.Invite`), as the sibling
  apps: the way to bring someone to Vigil while registration is closed.
  Make a link (optionally for one address, which then makes that account
  confirmed), copy it, replace it, see who used it, revoke it. Only a hash
  of each link's token is stored, so a link is shown once, in
  `#shared-link`, when it's made or replaced.
  """
  use VigilWeb, :live_view

  alias Vigil.Accounts

  @impl true
  def mount(_params, _session, socket) do
    {:ok,
     socket
     |> assign(:page_title, "Invites")
     |> assign(:invite_form, new_invite_form())
     |> assign(:shared_link, nil)
     |> stream(:sent, Accounts.list_invites(socket.assigns.current_scope.user))}
  end

  @impl true
  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope} active={:invites}>
      <section id="registration-invites" class="mx-auto max-w-2xl space-y-4">
        <.header>
          Invites
          <:subtitle>
            <%= if Accounts.registration_open?() do %>
              Anyone can sign up here right now, but an invite for an address makes that account
              confirmed, in one click.
            <% else %>
              Sign-up is by invite. Each link makes one account. Nothing is emailed: copy the
              link and hand it over.
            <% end %>
          </:subtitle>
        </.header>

        <.form
          for={@invite_form}
          id="invite-form"
          phx-submit="create_invite"
          class="flex flex-col gap-2 rounded-box border border-base-300 bg-base-200 p-3 sm:flex-row sm:items-start"
        >
          <div class="flex-1">
            <.input
              field={@invite_form[:email]}
              type="email"
              placeholder="Their email (optional)"
              autocomplete="off"
              spellcheck="false"
            />
          </div>
          <button
            type="submit"
            id="btn-create-invite"
            class="btn btn-primary sm:mt-1"
            phx-disable-with="Making…"
          >
            <.icon name="hero-plus-micro" class="size-4" /> New invite
          </button>
        </.form>
        <p class="text-xs text-base-content/60">
          With an email, the link is for that person only: one click makes their account, the address
          counted as confirmed. Without one, whoever holds the link signs up once, with any address.
        </p>

        <div
          :if={@shared_link}
          id="shared-link"
          class="space-y-2 rounded-box border border-primary/40 bg-base-100 p-3 motion-safe:animate-[fade-in_150ms_ease-out]"
        >
          <p class="text-sm">
            <%= if @shared_link.email do %>
              Invite link for <span class="font-mono">{@shared_link.email}</span>.
            <% else %>
              Invite link. Whoever holds it can sign up once.
            <% end %>
          </p>
          <div class="join w-full">
            <input
              id="shared-link-url"
              type="text"
              readonly
              value={@shared_link.url}
              class="input input-sm join-item min-w-0 flex-1 font-mono text-xs"
              phx-click={JS.dispatch("phx:copy")}
              aria-label="Invite link"
            />
            <button
              id="copy-shared-link"
              type="button"
              class="btn btn-sm btn-primary join-item"
              phx-click={JS.dispatch("phx:copy", to: "#shared-link-url")}
            >
              <.icon name="hero-clipboard-document-micro" class="size-4" /> Copy
            </button>
          </div>
          <p class="text-xs text-warning">
            Copy it now: it won't be shown again. Lost it? "New link" makes another and stops this one.
          </p>
          <button
            id="dismiss-shared-link"
            type="button"
            class="btn btn-ghost btn-xs"
            phx-click="dismiss_link"
          >
            Done
          </button>
        </div>

        <ul id="sent-invites" phx-update="stream" class="flex flex-col gap-2">
          <li id="sent-invites-empty" class="hidden py-6 text-center text-sm opacity-60 only:block">
            No invites made yet.
          </li>
          <li
            :for={{dom_id, invite} <- @streams.sent}
            id={dom_id}
            class={[
              "flex items-center gap-3 rounded-box border border-base-300 bg-base-100 p-3 transition",
              invite.consumed_at && "opacity-60"
            ]}
          >
            <div class="min-w-0 flex-1">
              <div class="flex items-center gap-2 text-xs">
                <span
                  :if={invite.consumed_at && invite.consumed_by_id}
                  class="badge badge-ghost badge-sm"
                >
                  used
                </span>
                <span
                  :if={invite.consumed_at && is_nil(invite.consumed_by_id)}
                  class="badge badge-error badge-sm"
                >
                  revoked
                </span>
                <span :if={is_nil(invite.consumed_at)} class="badge badge-success badge-sm">open</span>
                <span :if={invite.expires_at} class="opacity-60">
                  expires {Calendar.strftime(invite.expires_at, "%b %-d")}
                </span>
                <span :if={invite.note} class="truncate opacity-70">{invite.note}</span>
              </div>
              <p :if={invite.email} class="mt-1 truncate text-sm">
                For <span class="font-mono">{invite.email}</span>
              </p>
              <p :if={invite.consumed_by} class="mt-1 text-xs opacity-70">
                Used by <span class="font-mono">{invite.consumed_by.email}</span>
                on {Calendar.strftime(invite.consumed_at, "%b %-d")}
              </p>
            </div>
            <div :if={is_nil(invite.consumed_at)} class="flex items-center gap-1">
              <button
                type="button"
                id={"new-link-#{dom_id}"}
                phx-click="new_link"
                phx-value-id={invite.id}
                data-confirm="Make a new link? The current one will stop working."
                class="btn btn-ghost btn-xs"
                title="Replace the link; the old one stops working"
              >
                <.icon name="hero-arrow-path-micro" class="size-4" /> New link
              </button>
              <button
                type="button"
                id={"revoke-#{dom_id}"}
                phx-click="revoke_invite"
                phx-value-id={invite.id}
                class="btn btn-ghost btn-xs text-error"
                title="Revoke invite"
              >
                <.icon name="hero-x-mark-micro" class="size-4" />
              </button>
            </div>
          </li>
        </ul>
      </section>
    </Layouts.app>
    """
  end

  @impl true
  def handle_event("create_invite", params, socket) do
    attrs = %{email: get_in(params, ["invite", "email"])}

    case Accounts.create_invite(socket.assigns.current_scope.user, attrs) do
      {:ok, invite} ->
        {:noreply,
         socket
         |> put_flash(:info, "Invite made. Copy the link below and hand it over.")
         |> assign(:invite_form, new_invite_form())
         |> assign(:shared_link, shared_link(invite))
         |> stream_insert(:sent, Vigil.Repo.preload(invite, :consumed_by), at: 0)}

      {:error, %Ecto.Changeset{} = changeset} ->
        {:noreply, assign(socket, :invite_form, to_form(changeset, as: "invite"))}
    end
  end

  def handle_event("new_link", %{"id" => id}, socket) do
    case Accounts.rotate_invite(socket.assigns.current_scope.user, id) do
      {:ok, invite} ->
        {:noreply,
         socket
         |> put_flash(:info, "New link made. The old one no longer works.")
         |> assign(:shared_link, shared_link(invite))
         |> stream_insert(:sent, invite)}

      {:error, _} ->
        {:noreply, put_flash(socket, :error, "Couldn't make a new link.")}
    end
  end

  def handle_event("revoke_invite", %{"id" => id}, socket) do
    case Accounts.revoke_invite(socket.assigns.current_scope.user, id) do
      {:ok, invite} ->
        {:noreply,
         socket
         |> update(:shared_link, &if(&1 && &1.id == invite.id, do: nil, else: &1))
         |> stream_insert(:sent, invite)}

      {:error, _} ->
        {:noreply, put_flash(socket, :error, "Couldn't revoke the invite.")}
    end
  end

  def handle_event("dismiss_link", _params, socket),
    do: {:noreply, assign(socket, :shared_link, nil)}

  defp new_invite_form, do: to_form(%{"email" => ""}, as: "invite")

  # The raw token is on the invite only as it comes back from create or
  # rotate, so this is the one chance to show its link.
  defp shared_link(invite),
    do: %{id: invite.id, email: invite.email, url: VigilWeb.invite_url(invite)}
end