6.4 KiB · text History 573fef1
defmodule VigilWeb.OrgSettingsLive.Invites do
  @moduledoc """
  Inviting people by email, with a role and teams. Nothing is emailed yet:
  the link is shown once, to copy and hand over (`#shared-link`). For an
  address with no account the link makes one (confirmed) as it joins.
  """
  use VigilWeb, :live_view

  import VigilWeb.OrgSettingsLive.Components

  alias Vigil.Accounts.Scope
  alias Vigil.Organizations
  alias Vigil.Organizations.{Invite, Roles}

  @impl true
  def mount(_params, _session, socket) do
    org = socket.assigns.current_scope.organization

    {:ok,
     socket
     |> assign(:page_title, "#{org.name} · Invites")
     |> assign(:teams, Organizations.list_teams(org))
     |> assign(:form, to_form(Organizations.change_invite(%{role: :member})))
     |> assign(:shared_link, nil)
     |> stream(:invites, Organizations.list_invites(org))}
  end

  @impl true
  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope} active={:org_settings}>
      <.settings scope={@current_scope} tab={:invites}>
        <.form
          :if={Scope.can?(@current_scope, "member:write")}
          for={@form}
          id="invite-form"
          phx-submit="create"
          class="grid gap-x-3 rounded-box border border-base-300 bg-base-200/60 p-4 sm:grid-cols-[1fr_10rem_auto] sm:items-end"
        >
          <.input field={@form[:email]} type="email" label="Email" required />
          <.input
            field={@form[:role]}
            type="select"
            label="Role"
            options={Enum.map(Roles.all(), &{Roles.label(&1), &1})}
          />
          <.button class="btn btn-primary mb-2" phx-disable-with="Inviting…">Invite</.button>
          <div :if={@teams != []} class="sm:col-span-3">
            <.input
              field={@form[:team_ids]}
              type="select"
              multiple
              label="Teams"
              options={Enum.map(@teams, &{&1.name, &1.id})}
            />
          </div>
        </.form>

        <div
          :if={@shared_link}
          id="shared-link"
          class="space-y-2 rounded-box border border-primary/40 bg-base-100 p-3"
        >
          <p class="text-sm">Invite link for <span class="font-mono">{@shared_link.email}</span>.</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"
              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.
          </p>
        </div>

        <ul
          id="invites"
          phx-update="stream"
          class="divide-y divide-base-300 rounded-box border border-base-300"
        >
          <li
            id="invites-empty"
            class="hidden p-4 text-center text-sm text-base-content/60 only:block"
          >
            No invites yet.
          </li>
          <li
            :for={{dom_id, i} <- @streams.invites}
            id={dom_id}
            class="flex flex-wrap items-center gap-3 px-4 py-3"
          >
            <div class="min-w-0 flex-1">
              <p class="truncate font-mono text-sm">{i.email}</p>
              <p class="text-xs text-base-content/60">
                {Roles.label(i.role)} · {status(i)}
              </p>
            </div>
            <div
              :if={Invite.active?(i) and Scope.can?(@current_scope, "member:write")}
              class="flex gap-1"
            >
              <button
                type="button"
                id={"renew-#{dom_id}"}
                class="btn btn-ghost btn-xs"
                phx-click="renew"
                phx-value-id={i.id}
              >
                New link
              </button>
              <button
                type="button"
                id={"revoke-#{dom_id}"}
                class="btn btn-ghost btn-xs text-error"
                phx-click="revoke"
                phx-value-id={i.id}
              >
                Revoke
              </button>
            </div>
          </li>
        </ul>
      </.settings>
    </Layouts.app>
    """
  end

  defp status(%Invite{accepted_at: %DateTime{} = at}),
    do: "accepted #{Calendar.strftime(at, "%b %-d")}"

  defp status(%Invite{revoked_at: %DateTime{}}), do: "revoked"

  defp status(%Invite{} = i) do
    if Invite.active?(i),
      do: "open until #{Calendar.strftime(i.expires_at, "%b %-d")}",
      else: "expired"
  end

  @impl true
  def handle_event("create", %{"invite" => params}, socket) do
    case Organizations.create_invite(socket.assigns.current_scope, params) do
      {:ok, invite} ->
        {:noreply,
         socket
         |> assign(:form, to_form(Organizations.change_invite(%{role: :member})))
         |> assign(:shared_link, shared_link(invite))
         |> stream_insert(:invites, invite, at: 0)}

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

      {:error, reason} ->
        {:noreply, put_flash(socket, :error, forbidden_message(reason))}
    end
  end

  def handle_event("renew", %{"id" => id}, socket) do
    case Organizations.renew_invite(socket.assigns.current_scope, id) do
      {:ok, invite} ->
        {:noreply,
         socket |> assign(:shared_link, shared_link(invite)) |> stream_insert(:invites, invite)}

      {:error, reason} ->
        {:noreply, put_flash(socket, :error, forbidden_message(reason))}
    end
  end

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

      {:error, reason} ->
        {:noreply, put_flash(socket, :error, forbidden_message(reason))}
    end
  end

  defp shared_link(invite),
    do: %{
      id: invite.id,
      email: invite.email,
      url: VigilWeb.base_url() <> "/invites/" <> invite.token
    }
end