From aabedcd477f600d1ababe54b78176a3dc65c3789 Mon Sep 17 00:00:00 2001 From: Micah Woods Date: Wed, 25 Nov 2026 10:28:59 -0600 Subject: [PATCH 1/2] refactor(organize): give Social its own LiveView Keep connection management and callback state on the Social route. Share the workspace access check so membership changes apply consistently, and close owner-only controls when ownership or group availability changes. --- lib/huddlz/communities/group.ex | 41 +- lib/huddlz_web/components/layouts.ex | 2 +- lib/huddlz_web/live/organize_live.ex | 729 +----------------- lib/huddlz_web/live/organize_live/social.ex | 706 +++++++++++++++++ .../live/organize_live/workspace.ex | 64 ++ lib/huddlz_web/router.ex | 2 +- test/browser/features/social_schedule.feature | 6 + test/browser/steps/social_schedule_steps.exs | 63 +- test/features/social_connections.feature | 22 + 9 files changed, 907 insertions(+), 728 deletions(-) create mode 100644 lib/huddlz_web/live/organize_live/social.ex create mode 100644 lib/huddlz_web/live/organize_live/workspace.ex diff --git a/lib/huddlz/communities/group.ex b/lib/huddlz/communities/group.ex index 04c354353..022f370a1 100644 --- a/lib/huddlz/communities/group.ex +++ b/lib/huddlz/communities/group.ex @@ -12,6 +12,7 @@ defmodule Huddlz.Communities.Group do domain: Huddlz.Communities, data_layer: AshPostgres.DataLayer, authorizers: [Ash.Policy.Authorizer], + notifiers: [Ash.Notifier.PubSub], extensions: [ AshPaperTrail.Resource, AshJsonApi.Resource, @@ -79,20 +80,6 @@ defmodule Huddlz.Communities.Group do end end - paper_trail do - change_tracking_mode :snapshot - store_action_name? true - reference_source? false - sensitive_attributes :ignore - ignore_attributes [:inserted_at, :updated_at] - belongs_to_actor :actor, Huddlz.Accounts.User, domain: Huddlz.Accounts, on_delete: :nilify - metadata :impersonation_id, :uuid - metadata :impersonator_id, :uuid - metadata :automatic?, :boolean - version_extensions authorizers: [Ash.Policy.Authorizer] - mixin {Huddlz.Audit.Version, :mixin, []} - end - postgres do table "groups" repo Huddlz.Repo @@ -107,6 +94,20 @@ defmodule Huddlz.Communities.Group do end end + paper_trail do + change_tracking_mode :snapshot + store_action_name? true + reference_source? false + sensitive_attributes :ignore + ignore_attributes [:inserted_at, :updated_at] + belongs_to_actor :actor, Huddlz.Accounts.User, domain: Huddlz.Accounts, on_delete: :nilify + metadata :impersonation_id, :uuid + metadata :impersonator_id, :uuid + metadata :automatic?, :boolean + version_extensions authorizers: [Ash.Policy.Authorizer] + mixin {Huddlz.Audit.Version, :mixin, []} + end + archive do exclude_destroy_actions([:destroy]) @@ -443,6 +444,18 @@ defmodule Huddlz.Communities.Group do end end + pub_sub do + module Phoenix.PubSub + name Huddlz.PubSub + prefix "group" + transform fn notification -> {:group_changed, notification.data.id} end + + publish :archive, [:id] + publish :unarchive, [:id] + publish :update_details, [:id] + publish :destroy, [:id] + end + validations do validate string_length(:name, min: @name_length.first, max: @name_length.last) do message "Must be between 3 and 100 characters" diff --git a/lib/huddlz_web/components/layouts.ex b/lib/huddlz_web/components/layouts.ex index 9f77d56b4..c3e184642 100644 --- a/lib/huddlz_web/components/layouts.ex +++ b/lib/huddlz_web/components/layouts.ex @@ -35,7 +35,7 @@ defmodule HuddlzWeb.Layouts do attr :active_organize_section, :atom, default: nil, - values: [nil, :overview, :huddlz, :members, :settings], + values: [nil, :overview, :huddlz, :members, :social, :settings], doc: "active sub-tab inside an organize-group section" attr :active_admin_section, :atom, diff --git a/lib/huddlz_web/live/organize_live.ex b/lib/huddlz_web/live/organize_live.ex index a625ed6b0..3e61806ee 100644 --- a/lib/huddlz_web/live/organize_live.ex +++ b/lib/huddlz_web/live/organize_live.ex @@ -10,7 +10,6 @@ defmodule HuddlzWeb.OrganizeLive do * `/organize/:group_slug` — overview (KPIs + next huddl) * `/organize/:group_slug/huddlz` — huddlz list, lifecycle filters * `/organize/:group_slug/members` — roster grouped by role, one menu per person - * `/organize/:group_slug/social` — social connections: the places huddlz posts to * `/organize/:group_slug/settings` — owner-only group administration """ use HuddlzWeb, :live_view @@ -24,22 +23,15 @@ defmodule HuddlzWeb.OrganizeLive do alias Huddlz.Accounts.User alias Huddlz.Communities alias Huddlz.Communities.GroupStats - alias Huddlz.Communities.MembershipEvents - alias Huddlz.Communities.SocialConnection - alias Huddlz.Communities.SocialConnection.Kind - alias Huddlz.Communities.SocialConnection.Moment - alias Huddlz.Communities.SocialPost.Occasion - alias Huddlz.Social - alias Huddlz.Social.Post alias HuddlzWeb.Components.TurnoutForm alias HuddlzWeb.FormFocus alias HuddlzWeb.HuddlStatus alias HuddlzWeb.Layouts alias HuddlzWeb.Live.Helpers.BrowserTimeZone alias HuddlzWeb.Live.Helpers.HuddlCardHelpers + alias HuddlzWeb.OrganizeLive.Workspace alias HuddlzWeb.ReportAccount - @group_loads [:current_image_url, :member_count] @huddl_loads [ :rsvp_count, :status, @@ -82,17 +74,8 @@ defmodule HuddlzWeb.OrganizeLive do |> assign(:invitation_count, 0) |> assign(:member_lookup, %{}) |> assign(:member_role_counts, %{owner: 0, organizer: 0, member: 0}) - |> assign(:subscribed_group_id, nil) |> assign(:pending_member_action, nil) |> assign(:member_action_form, member_action_form()) - |> assign(:social_connections, []) - |> assign(:upcoming_posts, []) - |> assign(:recent_posts, []) - |> assign(:connect_dialog?, false) - |> assign(:schedule_editor, nil) - |> assign(:schedule_form, nil) - |> assign(:moments_form, nil) - |> assign(:removing_connection, nil) |> assign(:transfer_target_form, transfer_target_form()) |> assign(:transfer_candidates, []) |> stream(:invitations, []) @@ -111,7 +94,6 @@ defmodule HuddlzWeb.OrganizeLive do |> assign(:pending_member_action, nil) |> assign(:huddlz_filter, parse_huddlz_filter(params["filter"])) |> assign(:period, GroupStats.parse_period(params["period"])) - |> assign(:connected_id, params["connected"]) |> load_action(action, params, user) {:noreply, socket} @@ -131,25 +113,27 @@ defmodule HuddlzWeb.OrganizeLive do end defp load_action(socket, action, %{"group_slug" => slug}, user) do - case load_group(slug, user) do - {:ok, group} -> + case Workspace.open(socket, slug) do + {:ok, socket} -> socket - |> subscribe_to_membership_changes(group) - |> assign(:group, group) - |> assign( - :can_edit_group, - is_nil(group.archived_at) && Ash.can?({group, :update_details}, user) - ) - |> assign(:page_title, "#{group.name} · Organizer") - |> load_section(action, group, user) - - :error -> + |> assign_group_edit_permission() + |> load_section(action, socket.assigns.group, user) + + {:error, socket} -> socket - |> put_flash(:error, "That group doesn't exist, or you don't organize it.") - |> push_navigate(to: ~p"/organize") end end + defp assign_group_edit_permission(socket) do + %{group: group, current_user: user} = socket.assigns + + assign( + socket, + :can_edit_group, + is_nil(group.archived_at) && Ash.can?({group, :update_details}, user) + ) + end + defp load_section(socket, :overview, group, user) do socket |> assign(:turnout_nudge, Communities.latest_uncounted_huddl!(group.id, actor: user)) @@ -184,21 +168,6 @@ defmodule HuddlzWeb.OrganizeLive do |> stream(:invitations, invitations, reset: true) end - defp load_section(socket, :social, group, user) do - socket = load_connections(socket, group, user) - - # Coming back from the platform opens the new connection's schedule. - editor = - case socket.assigns.connected_id do - nil -> nil - id -> Enum.find(socket.assigns.social_connections, &(&1.id == id)) - end - - socket - |> assign(:connect_dialog?, false) - |> assign_schedule(editor) - end - defp load_section(socket, :settings, group, user) when group.owner_id == user.id do assign_members(socket, list_group_members(group, user)) end @@ -209,13 +178,6 @@ defmodule HuddlzWeb.OrganizeLive do |> push_navigate(to: ~p"/organize/#{group.slug}") end - defp load_connections(socket, group, user) do - socket - |> assign(:social_connections, Communities.list_social_connections!(group.id, actor: user)) - |> assign(:upcoming_posts, Communities.list_upcoming_social_posts!(group.id, actor: user)) - |> assign(:recent_posts, Communities.list_recent_social_posts!(group.id, actor: user)) - end - # The huddl a turnout event names: the nudge's, or one of the listed rows. defp turnout_subject(%{assigns: %{group: %{archived_at: archived_at}}}, _id) when not is_nil(archived_at), @@ -246,13 +208,6 @@ defmodule HuddlzWeb.OrganizeLive do end end - defp load_group(slug, user) do - case Communities.get_group_for_organize(slug, actor: user, load: @group_loads) do - {:ok, %Huddlz.Communities.Group{} = group} -> {:ok, group} - _ -> :error - end - end - defp list_group_huddlz(group, state, user) do Communities.huddlz_for_organizer!(state, actor: user, @@ -359,15 +314,6 @@ defmodule HuddlzWeb.OrganizeLive do defp normalize_invitation_expiration(invitation, _user), do: invitation - defp subscribe_to_membership_changes(socket, group) do - if connected?(socket) and socket.assigns.subscribed_group_id != group.id do - :ok = MembershipEvents.subscribe(group.id) - assign(socket, :subscribed_group_id, group.id) - else - socket - end - end - defp parse_huddlz_filter("draft"), do: :draft defp parse_huddlz_filter("cancelled"), do: :cancelled defp parse_huddlz_filter("past"), do: :past @@ -387,20 +333,7 @@ defmodule HuddlzWeb.OrganizeLive do active_group_slug={@group && @group.slug} active_organize_section={active_section(@live_action)} > -
-

This group is archived

-

History is read-only. Ownership can transfer without reopening the group.

- <.link - :if={@group.owner_id == @current_user.id} - navigate={~p"/groups/#{@group.slug}/edit"} - class="btn-secondary" - >Manage archival -
+ <%= case @live_action do %> <% :index -> %> <.picker_view groups={@owned_groups} /> @@ -442,20 +375,6 @@ defmodule HuddlzWeb.OrganizeLive do invitations={@streams.invitations} invitation_count={@invitation_count} /> - <% :social -> %> - <.social_view - group={@group} - connections={@social_connections} - owner?={@group.owner_id == @current_user.id} - connect_dialog?={@connect_dialog?} - editor={@schedule_editor} - form={@schedule_form} - moments_form={@moments_form} - fresh?={not is_nil(@connected_id)} - removing={@removing_connection} - upcoming={@upcoming_posts} - recent={@recent_posts} - /> <% :settings -> %> <.settings_view :if={@group.owner_id == @current_user.id} @@ -479,7 +398,6 @@ defmodule HuddlzWeb.OrganizeLive do defp active_section(:overview), do: :overview defp active_section(:huddlz), do: :huddlz defp active_section(:members), do: :members - defp active_section(:social), do: :social defp active_section(:settings), do: :settings defp active_section(_), do: nil @@ -1854,81 +1772,6 @@ defmodule HuddlzWeb.OrganizeLive do {:noreply, put_flash(socket, :error, "Choose a member to receive ownership.")} end - def handle_event("open_connect_dialog", _params, socket) do - {:noreply, assign(socket, :connect_dialog?, true)} - end - - def handle_event("close_connect_dialog", _params, socket) do - {:noreply, assign(socket, :connect_dialog?, false)} - end - - def handle_event("edit_connection", %{"id" => id}, socket) do - editor = Enum.find(socket.assigns.social_connections, &(&1.id == id)) - {:noreply, assign_schedule(socket, editor)} - end - - def handle_event("close_schedule", _params, socket) do - {:noreply, close_schedule(socket)} - end - - def handle_event("ask_remove_connection", _params, socket) do - {:noreply, assign(socket, :removing_connection, socket.assigns.schedule_editor)} - end - - def handle_event("cancel_remove_connection", _params, socket) do - {:noreply, assign(socket, :removing_connection, nil)} - end - - def handle_event("remove_connection", _params, socket) do - %{removing_connection: connection, current_user: user, group: group} = socket.assigns - - case Communities.remove_social_connection(connection, actor: user) do - :ok -> - {:noreply, - socket - |> assign(:removing_connection, nil) - |> put_flash(:info, "#{SocialConnection.place(connection)} is no longer connected.") - |> close_schedule() - |> load_connections(group, user)} - - {:error, _error} -> - {:noreply, put_flash(socket, :error, "That connection didn't go.")} - end - end - - def handle_event("pause_connection", %{"id" => id}, socket) do - set_connection_state(socket, id, &Communities.pause_social_connection/2, "is paused.") - end - - def handle_event("resume_connection", %{"id" => id}, socket) do - set_connection_state(socket, id, &Communities.resume_social_connection/2, "is posting again.") - end - - def handle_event("send_test_post", _params, socket) do - %{schedule_editor: connection, current_user: user} = socket.assigns - - case Communities.send_social_test_post(connection.id, actor: user) do - :ok -> - {:noreply, - put_flash(socket, :info, "A test post went to #{SocialConnection.place(connection)}.")} - - {:error, error} -> - {:noreply, - socket - |> load_connections(socket.assigns.group, user) - |> put_flash(:error, test_post_error(error))} - end - end - - def handle_event("save_schedule", params, socket) do - {:noreply, save_schedule(socket, params)} - end - - def handle_event("finish_schedule", params, socket) do - socket = save_schedule(socket, params) - {:noreply, finish_schedule(socket, socket.assigns.schedule_form.source.valid?)} - end - def handle_event("cancel_member_action", _params, socket) do {:noreply, socket @@ -2036,24 +1879,15 @@ defmodule HuddlzWeb.OrganizeLive do end defp refresh_after_membership_change(socket) do - user = socket.assigns.current_user - group = socket.assigns.group - - case load_group(group.slug, user) do - {:ok, reloaded_group} -> + case Workspace.refresh(socket) do + {:ok, socket} -> socket - |> assign(:group, reloaded_group) - |> assign( - :can_edit_group, - is_nil(reloaded_group.archived_at) && Ash.can?({reloaded_group, :update_details}, user) - ) - |> refresh_members_if_visible(reloaded_group, user) + |> assign_group_edit_permission() + |> refresh_members_if_visible(socket.assigns.group, socket.assigns.current_user) |> refresh_pending_member_action() - :error -> + {:error, socket} -> socket - |> put_flash(:error, "Your organizer access to #{group.name} has changed.") - |> push_navigate(to: ~p"/organize") end end @@ -2262,521 +2096,4 @@ defmodule HuddlzWeb.OrganizeLive do defp rsvp_label(0), do: "0 RSVPs" defp rsvp_label(1), do: "1 RSVP" defp rsvp_label(n), do: "#{n} RSVPs" - - # --------------------------------------------------------------------------- - # Social - # --------------------------------------------------------------------------- - - defp save_schedule(socket, params) do - attrs = Map.put(params["schedule"] || %{}, "moments", chosen_moments(params["moments"])) - form = AshPhoenix.Form.validate(socket.assigns.schedule_form, attrs) - - socket - |> assign(:moments_form, to_form(params["moments"] || %{}, as: :moments)) - |> persist_schedule(form) - end - - defp persist_schedule(socket, %AshPhoenix.Form{valid?: true, changed?: false}), do: socket - - defp persist_schedule(socket, form) do - case AshPhoenix.Form.submit(form, params: form.params) do - {:ok, updated} -> - socket - |> assign_schedule(updated) - |> load_connections(socket.assigns.group, socket.assigns.current_user) - - {:error, form} -> - assign(socket, :schedule_form, to_form(form)) - end - end - - defp finish_schedule(socket, false), do: FormFocus.first_error(socket, "schedule-form") - - defp finish_schedule(socket, true) do - socket - |> put_flash( - :info, - "#{SocialConnection.place(socket.assigns.schedule_editor)} will post on that schedule." - ) - |> close_schedule() - end - - defp assign_schedule(socket, nil) do - assign(socket, schedule_editor: nil, schedule_form: nil, moments_form: nil) - end - - defp assign_schedule(socket, connection) do - form = - connection - |> AshPhoenix.Form.for_update(:edit, actor: socket.assigns.current_user, as: "schedule") - |> to_form() - - moments = Map.new(Moment.values(), &{Atom.to_string(&1), &1 in connection.moments}) - - assign(socket, - schedule_editor: connection, - schedule_form: form, - moments_form: to_form(moments, as: :moments) - ) - end - - defp close_schedule(socket) do - socket = assign_schedule(socket, nil) - - case socket.assigns.connected_id do - nil -> socket - _id -> push_patch(socket, to: ~p"/organize/#{socket.assigns.group.slug}/social") - end - end - - defp set_connection_state(socket, id, change, said) do - %{current_user: user, group: group} = socket.assigns - connection = Enum.find(socket.assigns.social_connections, &(&1.id == id)) - - case connection && change.(connection, actor: user) do - {:ok, _connection} -> - {:noreply, - socket - |> put_flash(:info, "#{SocialConnection.place(connection)} #{said}") - |> load_connections(group, user)} - - _ -> - {:noreply, put_flash(socket, :error, "That didn't change.")} - end - end - - defp test_post_error(%Ash.Error.Invalid{errors: [%{message: message} | _]}), do: message - defp test_post_error(_error), do: "The test post didn't go through." - - # The morning-of post for a made-up huddl this evening, worded by the same - # formatter scheduled posts use, so the preview cannot drift from a post. - defp preview_text(group, opening_line) do - today = group.time_zone |> DateTime.now!() |> DateTime.to_date() - - Post.text( - %{ - title: "Your next huddl with #{group.name}", - starts_at: DateTime.new!(today, ~T[18:00:00], group.time_zone), - time_zone: group.time_zone, - event_type: :virtual, - max_attendees: 20, - rsvp_count: 8, - waitlist_count: 0 - }, - moment: :morning_of, - opening_line: opening_line, - link: url(~p"/groups/#{group.slug}/huddlz/example") - ) - end - - # Checkbox params: %{"week_before" => "true"} for the ticked moments. - defp chosen_moments(nil), do: [] - - defp chosen_moments(params) when is_map(params) do - Enum.filter(Moment.values(), fn moment -> params[Atom.to_string(moment)] == "true" end) - end - - attr :group, :map, required: true - attr :connections, :list, required: true - attr :owner?, :boolean, required: true - attr :connect_dialog?, :boolean, required: true - attr :editor, :any, required: true - attr :form, :any, required: true - attr :moments_form, :any, required: true - attr :fresh?, :boolean, required: true - attr :removing, :any, required: true - attr :upcoming, :list, required: true - attr :recent, :list, required: true - - defp social_view(assigns) do - ~H""" -
-
-

Social

-

- Post each huddl to the places your people already talk. Only public huddlz in public groups are posted. -

-
- <.button - :if={@owner? && @group.is_public && is_nil(@group.archived_at)} - id="connect-place" - type="button" - variant={:primary} - phx-click="open_connect_dialog" - > - Connect a place - -
- -
-

- Only public groups post to outside places: a link to a private group's huddl dead-ends for anyone who isn't a member. -

-
- -
-

- The group owner sets up social connections. You can pause one, skip a huddl, or post a huddl now. -

-
- -
-
-
-

Social connections

-
Each one posts on its own social schedule.
-
-
-

- Nothing connected yet. Connect a Slack or Discord channel once and huddlz posts every public huddl there. -

-
- -
-
- -
-
-
-

Upcoming posts

-
- Times are in each huddl's time zone. A paused connection posts nothing, so its posts are not listed. -
-
-
-

- Nothing to post yet. Posts appear here as public huddlz are published. -

-
- -
-
- -
-
-
-

Recent posts

-
-
-
- -
-
- - <.connect_place_dialog :if={@connect_dialog?} group={@group} /> - <.schedule_sheet - :if={@editor} - connection={@editor} - form={@form} - moments_form={@moments_form} - group={@group} - fresh?={@fresh?} - /> - <.remove_connection_dialog :if={@removing} connection={@removing} /> - """ - end - - # When a post goes out, read in its huddl's time zone. - defp post_time(at, huddl) do - at |> DateTime.shift_zone!(huddl.time_zone) |> Calendar.strftime("%a, %b %-d, %-I:%M %p") - end - - # The huddl a post is about, with its date when the post goes out on - # another day. - defp post_huddl(%{huddl: huddl} = post) do - starts = DateTime.shift_zone!(huddl.starts_at, huddl.time_zone) - due = DateTime.shift_zone!(post.due_at, huddl.time_zone) - - if DateTime.to_date(starts) == DateTime.to_date(due), - do: huddl.title, - else: "#{huddl.title} · #{Calendar.strftime(starts, "%a, %b %-d")}" - end - - defp state_label(:posting), do: "Posting" - defp state_label(:paused), do: "Paused" - defp state_label(:needs_reconnecting), do: "Needs reconnecting" - - defp state_variant(:posting), do: :cyan - defp state_variant(:paused), do: :muted - defp state_variant(:needs_reconnecting), do: :warn - - @not_yet [ - {"Bluesky", "Free to post to, and links work. The next one to add."}, - {"Mastodon", "Free to post to, and links work."}, - {"X", "X charges huddlz for every post that carries a link."}, - {"Instagram", "Posts can't carry a link, and Meta has to review huddlz first."} - ] - - attr :group, :map, required: true - - defp connect_place_dialog(assigns) do - assigns = - assigns - |> assign(:not_yet, @not_yet) - |> assign(:tiles, [ - {:slack, "S", "Pick the workspace and channel on Slack's own screen."}, - {:discord, "D", "Pick the server and channel on Discord's own screen."} - ]) - - ~H""" - <.modal id="connect-place-dialog" show on_cancel={JS.push("close_connect_dialog")}> -
-

Connect a place

-

Where should huddlz post for {@group.name}?

-
-
- <%= for {kind, mark, line} <- @tiles do %> - <.link - :if={Social.configured?(kind)} - id={"connect-#{kind}"} - class="place-tile" - href={~p"/organize/#{@group.slug}/social/connect/#{kind}"} - > - - {Kind.label(kind)} - {line} - -
- - {Kind.label(kind)} - Not set up on this server yet. -
- <% end %> -
- -

- One social connection is one channel. Connect again to post to another. -

- - """ - end - - attr :connection, :map, required: true - - defp remove_connection_dialog(assigns) do - ~H""" - <.modal id="remove-connection-dialog" show on_cancel={JS.push("cancel_remove_connection")}> -
-

- Remove {SocialConnection.place(@connection)}? -

-

- huddlz stops posting there. Connecting it again goes through {Kind.label(@connection.kind)}'s own screen. -

-
-
- <.button id="remove-connection-cancel" type="button" phx-click="cancel_remove_connection"> - Cancel - - <.button - id="remove-connection-confirm" - type="button" - variant={:destructive} - phx-click="remove_connection" - > - Remove connection - -
- - """ - end - - attr :connection, :map, required: true - attr :group, :map, required: true - attr :fresh?, :boolean, default: false - - attr :form, :any, required: true - attr :moments_form, :any, required: true - - defp schedule_sheet(assigns) do - assigns = - assigns - |> assign(:moments, Moment.values()) - |> assign(:preview, preview_text(assigns.group, assigns.form[:opening_line].value)) - - ~H""" - <.modal id="schedule-sheet" show on_cancel={JS.push("close_schedule")}> -
-

Choose when it posts

-

- {SocialConnection.place(@connection)} · {@connection.workspace_name}. This applies to every public huddl from now on. -

-
- <.form - for={@form} - id="schedule-form" - phx-change="save_schedule" - phx-submit="finish_schedule" - class="mt-5" - > -
- What to call it -

- Discord shares only the server and channel ids, so name them the way your members would. -

-
- <.input - field={@form[:workspace_name]} - id="place-server-name" - label="Server name" - phx-debounce="300" - /> - <.input - field={@form[:channel_name]} - id="place-channel-name" - label="Channel name" - phx-debounce="300" - /> -
-
-
- Social schedule -
- <.toggle field={@moments_form[moment]} label={Moment.label(moment)} labelled_externally /> - - - {Moment.hint(moment)} - -
-

- If a posted huddl is cancelled or moved, huddlz always posts a short follow-up here. -

-
-
- <.input - field={@form[:opening_line]} - id="opening-line" - label="Opening line" - placeholder="Optional. For example: This week at Elixir Nashville:" - help="Up to 140 characters." - phx-debounce="300" - /> -
-

- Changes save as you make them and show in the group's activity. -

-
-

Morning-of post preview

-

- An example with your opening line. Each post uses the huddl's own details and local time. -

-

{@preview}

-
-
- <.button - id="remove-connection" - type="button" - variant={:destructive} - phx-click="ask_remove_connection" - > - Remove - - <.link - href={~p"/organize/#{@group.slug}/social/reconnect/#{@connection.id}"} - class="btn-secondary" - >Reconnect - <.button id="send-test-post" type="button" variant={:secondary} phx-click="send_test_post"> - Send a test post - - <.button id="finish-schedule" type="submit" variant={:primary}> - {if @fresh?, do: "Start posting", else: "Done"} - -
- - - """ - end end diff --git a/lib/huddlz_web/live/organize_live/social.ex b/lib/huddlz_web/live/organize_live/social.ex new file mode 100644 index 000000000..edc7347ef --- /dev/null +++ b/lib/huddlz_web/live/organize_live/social.ex @@ -0,0 +1,706 @@ +defmodule HuddlzWeb.OrganizeLive.Social do + @moduledoc "The organizer workspace for a group's social connections and scheduled posts." + use HuddlzWeb, :live_view + + alias Huddlz.Communities + alias Huddlz.Communities.SocialConnection + alias Huddlz.Communities.SocialConnection.Kind + alias Huddlz.Communities.SocialConnection.Moment + alias Huddlz.Communities.SocialPost.Occasion + alias Huddlz.Social + alias Huddlz.Social.Post + alias HuddlzWeb.FormFocus + alias HuddlzWeb.OrganizeLive.Workspace + + on_mount {HuddlzWeb.LiveUserAuth, :live_user_required} + on_mount {HuddlzWeb.LiveUserAuth, :app} + on_mount {HuddlzWeb.LiveUserAuth, :confirmed_user_required} + + @impl true + def handle_params(%{"group_slug" => slug} = params, _uri, socket) do + previous_group = socket.assigns[:group] + + case Workspace.open(socket, slug) do + {:ok, socket} -> + subscribe_to_group_changes(socket, previous_group) + socket = socket |> assign_access() |> load_connections() + connected_id = params["connected"] + + editor = + if socket.assigns.access == :manage, + do: Enum.find(socket.assigns.connections, &(&1.id == connected_id)) + + {:noreply, + socket + |> assign(:connected_id, connected_id) + |> reset_dialogs(editor)} + + {:error, socket} -> + {:noreply, socket} + end + end + + defp subscribe_to_group_changes(socket, previous_group) do + group = socket.assigns.group + + if connected?(socket) && (is_nil(previous_group) || previous_group.id != group.id) do + if previous_group, + do: Phoenix.PubSub.unsubscribe(Huddlz.PubSub, "group:#{previous_group.id}") + + Phoenix.PubSub.subscribe(Huddlz.PubSub, "group:#{group.id}") + end + end + + @impl true + def handle_info({change, id}, %{assigns: %{group: %{id: id}}} = socket) + when change in [:group_membership_changed, :group_changed] do + case Workspace.refresh(socket) do + {:ok, socket} -> + socket = socket |> assign_access() |> load_connections() + {:noreply, if(socket.assigns.access == :manage, do: socket, else: reset_dialogs(socket))} + + {:error, socket} -> + {:noreply, socket} + end + end + + def handle_info({change, _id}, socket) + when change in [:group_membership_changed, :group_changed], + do: {:noreply, socket} + + defp assign_access(socket) do + assign(socket, :access, access(socket.assigns.group, socket.assigns.current_user)) + end + + defp access(%{archived_at: at}, _user) when not is_nil(at), do: :read_only + defp access(%{is_public: false}, _user), do: :read_only + defp access(%{owner_id: id}, %{id: id}), do: :manage + defp access(_group, _user), do: :pause_resume + + defp reset_dialogs(socket, editor \\ nil) do + socket + |> assign(connect_dialog?: false, removing_connection?: false) + |> assign_schedule(editor) + end + + defp load_connections(socket) do + %{group: group, current_user: user} = socket.assigns + + socket + |> assign(:connections, Communities.list_social_connections!(group.id, actor: user)) + |> assign(:upcoming_posts, Communities.list_upcoming_social_posts!(group.id, actor: user)) + |> assign(:recent_posts, Communities.list_recent_social_posts!(group.id, actor: user)) + end + + @impl true + def handle_event(_event, _params, %{assigns: %{access: :read_only}} = socket), + do: {:noreply, socket} + + def handle_event("pause_connection", %{"id" => id}, socket) do + set_connection_state(socket, id, &Communities.pause_social_connection/2, "is paused.") + end + + def handle_event("resume_connection", %{"id" => id}, socket) do + set_connection_state(socket, id, &Communities.resume_social_connection/2, "is posting again.") + end + + def handle_event(_event, _params, %{assigns: %{access: :pause_resume}} = socket), + do: {:noreply, socket} + + def handle_event("open_connect_dialog", _params, socket) do + {:noreply, assign(socket, :connect_dialog?, true)} + end + + def handle_event("close_connect_dialog", _params, socket) do + {:noreply, assign(socket, :connect_dialog?, false)} + end + + def handle_event("edit_connection", %{"id" => id}, socket) do + editor = Enum.find(socket.assigns.connections, &(&1.id == id)) + {:noreply, assign_schedule(socket, editor)} + end + + def handle_event("close_schedule", _params, socket) do + {:noreply, close_schedule(socket)} + end + + # Dismiss queued form and dialog actions after the editor has closed. + def handle_event(_event, _params, %{assigns: %{schedule_editor: nil}} = socket), + do: {:noreply, socket} + + def handle_event("ask_remove_connection", _params, socket) do + {:noreply, assign(socket, :removing_connection?, true)} + end + + def handle_event("cancel_remove_connection", _params, socket) do + {:noreply, assign(socket, :removing_connection?, false)} + end + + def handle_event( + "remove_connection", + _params, + %{assigns: %{removing_connection?: false}} = socket + ), + do: {:noreply, socket} + + def handle_event("remove_connection", _params, socket) do + %{schedule_editor: connection, current_user: user} = socket.assigns + + case Communities.remove_social_connection(connection, actor: user) do + :ok -> + {:noreply, + socket + |> put_flash(:info, "#{SocialConnection.place(connection)} is no longer connected.") + |> close_schedule() + |> load_connections()} + + {:error, _error} -> + {:noreply, put_flash(socket, :error, "That connection didn't go.")} + end + end + + def handle_event("send_test_post", _params, socket) do + %{schedule_editor: connection, current_user: user} = socket.assigns + + case Communities.send_social_test_post(connection.id, actor: user) do + :ok -> + {:noreply, + put_flash(socket, :info, "A test post went to #{SocialConnection.place(connection)}.")} + + {:error, error} -> + {:noreply, + socket + |> load_connections() + |> put_flash(:error, test_post_error(error))} + end + end + + def handle_event("save_schedule", params, socket) do + {:noreply, save_schedule(socket, params)} + end + + def handle_event("finish_schedule", params, socket) do + socket = save_schedule(socket, params) + {:noreply, finish_schedule(socket, socket.assigns.schedule_form.source.valid?)} + end + + defp save_schedule(socket, params) do + attrs = Map.put(params["schedule"] || %{}, "moments", chosen_moments(params["moments"])) + form = AshPhoenix.Form.validate(socket.assigns.schedule_form, attrs) + + socket + |> assign(:moments_form, to_form(params["moments"] || %{}, as: :moments)) + |> persist_schedule(form) + end + + defp persist_schedule(socket, %AshPhoenix.Form{valid?: true, changed?: false}), do: socket + + defp persist_schedule(socket, form) do + case AshPhoenix.Form.submit(form, params: form.params) do + {:ok, updated} -> + socket + |> assign_schedule(updated) + |> load_connections() + + {:error, form} -> + assign(socket, :schedule_form, to_form(form)) + end + end + + defp finish_schedule(socket, false), do: FormFocus.first_error(socket, "schedule-form") + + defp finish_schedule(socket, true) do + socket + |> put_flash( + :info, + "#{SocialConnection.place(socket.assigns.schedule_editor)} will post on that schedule." + ) + |> close_schedule() + end + + defp assign_schedule(socket, nil) do + assign(socket, schedule_editor: nil, schedule_form: nil, moments_form: nil) + end + + defp assign_schedule(socket, connection) do + form = + connection + |> AshPhoenix.Form.for_update(:edit, actor: socket.assigns.current_user, as: "schedule") + |> to_form() + + moments = Map.new(Moment.values(), &{Atom.to_string(&1), &1 in connection.moments}) + + assign(socket, + schedule_editor: connection, + schedule_form: form, + moments_form: to_form(moments, as: :moments) + ) + end + + defp close_schedule(socket) do + socket = reset_dialogs(socket) + + case socket.assigns.connected_id do + nil -> socket + _id -> push_patch(socket, to: ~p"/organize/#{socket.assigns.group.slug}/social") + end + end + + defp set_connection_state(socket, id, change, said) do + %{current_user: user} = socket.assigns + connection = Enum.find(socket.assigns.connections, &(&1.id == id)) + + case connection && change.(connection, actor: user) do + {:ok, _connection} -> + {:noreply, + socket + |> put_flash(:info, "#{SocialConnection.place(connection)} #{said}") + |> load_connections()} + + _ -> + {:noreply, put_flash(socket, :error, "That didn't change.")} + end + end + + defp test_post_error(%Ash.Error.Invalid{errors: [%{message: message} | _]}), do: message + defp test_post_error(_error), do: "The test post didn't go through." + + # The morning-of post for a made-up huddl this evening, worded by the same + # formatter scheduled posts use, so the preview cannot drift from a post. + defp preview_text(group, opening_line) do + today = group.time_zone |> DateTime.now!() |> DateTime.to_date() + + Post.text( + %{ + title: "Your next huddl with #{group.name}", + starts_at: DateTime.new!(today, ~T[18:00:00], group.time_zone), + time_zone: group.time_zone, + event_type: :virtual, + max_attendees: 20, + rsvp_count: 8, + waitlist_count: 0 + }, + moment: :morning_of, + opening_line: opening_line, + link: url(~p"/groups/#{group.slug}/huddlz/example") + ) + end + + # Checkbox params: %{"week_before" => "true"} for the ticked moments. + defp chosen_moments(nil), do: [] + + defp chosen_moments(params) when is_map(params) do + Enum.filter(Moment.values(), fn moment -> params[Atom.to_string(moment)] == "true" end) + end + + @impl true + def render(assigns) do + ~H""" + + +
+
+

Social

+

+ Post each huddl to the places your people already talk. Only public huddlz in public groups are posted. +

+
+ <.button + :if={@access == :manage} + id="connect-place" + type="button" + variant={:primary} + phx-click="open_connect_dialog" + > + Connect a place + +
+ +
+

+ Only public groups post to outside places: a link to a private group's huddl dead-ends for anyone who isn't a member. +

+
+ +
+

+ The group owner sets up social connections. You can pause one, skip a huddl, or post a huddl now. +

+
+ +
+
+
+

Social connections

+
Each one posts on its own social schedule.
+
+
+

+ Nothing connected yet. Connect a Slack or Discord channel once and huddlz posts every public huddl there. +

+
+ +
+
+ +
+
+
+

Upcoming posts

+
+ Times are in each huddl's time zone. A paused connection posts nothing, so its posts are not listed. +
+
+
+

+ Nothing to post yet. Posts appear here as public huddlz are published. +

+
+ +
+
+ +
+
+
+

Recent posts

+
+
+
+ +
+
+ + <.connect_place_dialog :if={@connect_dialog?} group={@group} /> + <.schedule_sheet + :if={@schedule_editor} + connection={@schedule_editor} + form={@schedule_form} + moments_form={@moments_form} + group={@group} + fresh?={@connected_id == @schedule_editor.id} + /> + <.remove_connection_dialog :if={@removing_connection?} connection={@schedule_editor} /> +
+ """ + end + + # When a post goes out, read in its huddl's time zone. + defp post_time(at, huddl) do + at |> DateTime.shift_zone!(huddl.time_zone) |> Calendar.strftime("%a, %b %-d, %-I:%M %p") + end + + # The huddl a post is about, with its date when the post goes out on + # another day. + defp post_huddl(%{huddl: huddl} = post) do + starts = DateTime.shift_zone!(huddl.starts_at, huddl.time_zone) + due = DateTime.shift_zone!(post.due_at, huddl.time_zone) + + if DateTime.to_date(starts) == DateTime.to_date(due), + do: huddl.title, + else: "#{huddl.title} · #{Calendar.strftime(starts, "%a, %b %-d")}" + end + + defp state_label(:posting), do: "Posting" + defp state_label(:paused), do: "Paused" + defp state_label(:needs_reconnecting), do: "Needs reconnecting" + + defp state_variant(:posting), do: :cyan + defp state_variant(:paused), do: :muted + defp state_variant(:needs_reconnecting), do: :warn + + @not_yet [ + {"Bluesky", "Free to post to, and links work. The next one to add."}, + {"Mastodon", "Free to post to, and links work."}, + {"X", "X charges huddlz for every post that carries a link."}, + {"Instagram", "Posts can't carry a link, and Meta has to review huddlz first."} + ] + + attr :group, :map, required: true + + defp connect_place_dialog(assigns) do + assigns = + assigns + |> assign(:not_yet, @not_yet) + |> assign(:tiles, [ + {:slack, "S", "Pick the workspace and channel on Slack's own screen."}, + {:discord, "D", "Pick the server and channel on Discord's own screen."} + ]) + + ~H""" + <.modal id="connect-place-dialog" show on_cancel={JS.push("close_connect_dialog")}> +
+

Connect a place

+

Where should huddlz post for {@group.name}?

+
+
+ <%= for {kind, mark, line} <- @tiles do %> + <.link + :if={Social.configured?(kind)} + id={"connect-#{kind}"} + class="place-tile" + href={~p"/organize/#{@group.slug}/social/connect/#{kind}"} + > + + {Kind.label(kind)} + {line} + +
+ + {Kind.label(kind)} + Not set up on this server yet. +
+ <% end %> +
+ +

+ One social connection is one channel. Connect again to post to another. +

+ + """ + end + + attr :connection, :map, required: true + + defp remove_connection_dialog(assigns) do + ~H""" + <.modal id="remove-connection-dialog" show on_cancel={JS.push("cancel_remove_connection")}> +
+

+ Remove {SocialConnection.place(@connection)}? +

+

+ huddlz stops posting there. Connecting it again goes through {Kind.label(@connection.kind)}'s own screen. +

+
+
+ <.button id="remove-connection-cancel" type="button" phx-click="cancel_remove_connection"> + Cancel + + <.button + id="remove-connection-confirm" + type="button" + variant={:destructive} + phx-click="remove_connection" + > + Remove connection + +
+ + """ + end + + attr :connection, :map, required: true + attr :group, :map, required: true + attr :fresh?, :boolean, default: false + + attr :form, :any, required: true + attr :moments_form, :any, required: true + + defp schedule_sheet(assigns) do + assigns = + assigns + |> assign(:moments, Moment.values()) + |> assign(:preview, preview_text(assigns.group, assigns.form[:opening_line].value)) + + ~H""" + <.modal id="schedule-sheet" show on_cancel={JS.push("close_schedule")}> +
+

Choose when it posts

+

+ {SocialConnection.place(@connection)} · {@connection.workspace_name}. This applies to every public huddl from now on. +

+
+ <.form + for={@form} + id="schedule-form" + phx-change="save_schedule" + phx-submit="finish_schedule" + class="mt-5" + > +
+ What to call it +

+ Discord shares only the server and channel ids, so name them the way your members would. +

+
+ <.input + field={@form[:workspace_name]} + id="place-server-name" + label="Server name" + phx-debounce="300" + /> + <.input + field={@form[:channel_name]} + id="place-channel-name" + label="Channel name" + phx-debounce="300" + /> +
+
+
+ Social schedule +
+ <.toggle field={@moments_form[moment]} label={Moment.label(moment)} labelled_externally /> + + + {Moment.hint(moment)} + +
+

+ If a posted huddl is cancelled or moved, huddlz always posts a short follow-up here. +

+
+
+ <.input + field={@form[:opening_line]} + id="opening-line" + label="Opening line" + placeholder="Optional. For example: This week at Elixir Nashville:" + help="Up to 140 characters." + phx-debounce="300" + /> +
+

+ Changes save as you make them and show in the group's activity. +

+
+

Morning-of post preview

+

+ An example with your opening line. Each post uses the huddl's own details and local time. +

+

{@preview}

+
+
+ <.button + id="remove-connection" + type="button" + variant={:destructive} + phx-click="ask_remove_connection" + > + Remove + + <.link + href={~p"/organize/#{@group.slug}/social/reconnect/#{@connection.id}"} + class="btn-secondary" + >Reconnect + <.button id="send-test-post" type="button" variant={:secondary} phx-click="send_test_post"> + Send a test post + + <.button id="finish-schedule" type="submit" variant={:primary}> + {if @fresh?, do: "Start posting", else: "Done"} + +
+ + + """ + end +end diff --git a/lib/huddlz_web/live/organize_live/workspace.ex b/lib/huddlz_web/live/organize_live/workspace.ex new file mode 100644 index 000000000..68feaefbe --- /dev/null +++ b/lib/huddlz_web/live/organize_live/workspace.ex @@ -0,0 +1,64 @@ +defmodule HuddlzWeb.OrganizeLive.Workspace do + @moduledoc "Group access and archival status shared by organizer pages." + use HuddlzWeb, :html + + import Phoenix.LiveView, only: [connected?: 1, put_flash: 3, push_navigate: 2] + + alias Huddlz.Communities + alias Huddlz.Communities.MembershipEvents + + def open(socket, slug) do + load_group(socket, slug, "That group doesn't exist, or you don't organize it.") + end + + def refresh(socket) do + group = socket.assigns.group + load_group(socket, group.slug, "Your organizer access to #{group.name} has changed.") + end + + defp load_group(socket, slug, error_message) do + user = socket.assigns.current_user + + case Communities.get_group_for_organize(slug, + actor: user, + load: [:current_image_url, :member_count] + ) do + {:ok, %Communities.Group{} = group} -> + if connected?(socket) && socket.assigns[:subscribed_group_id] != group.id do + :ok = MembershipEvents.subscribe(group.id) + end + + {:ok, + assign(socket, + group: group, + subscribed_group_id: group.id, + page_title: "#{group.name} · Organizer" + )} + + _ -> + {:error, socket |> put_flash(:error, error_message) |> push_navigate(to: ~p"/organize")} + end + end + + attr :group, :map, required: true + attr :current_user, :map, required: true + + def archived_banner(assigns) do + ~H""" +
+

This group is archived

+

History is read-only. Ownership can transfer without reopening the group.

+ <.link + :if={@group.owner_id == @current_user.id} + navigate={~p"/groups/#{@group.slug}/edit"} + class="btn-secondary" + >Manage archival +
+ """ + end +end diff --git a/lib/huddlz_web/router.ex b/lib/huddlz_web/router.ex index 3616d8cfd..19cb1475b 100644 --- a/lib/huddlz_web/router.ex +++ b/lib/huddlz_web/router.ex @@ -196,7 +196,7 @@ defmodule HuddlzWeb.Router do live "/organize/:group_slug", OrganizeLive, :overview live "/organize/:group_slug/huddlz", OrganizeLive, :huddlz live "/organize/:group_slug/members", OrganizeLive, :members - live "/organize/:group_slug/social", OrganizeLive, :social + live "/organize/:group_slug/social", OrganizeLive.Social, :social live "/organize/:group_slug/settings", OrganizeLive, :settings # Group routes diff --git a/test/browser/features/social_schedule.feature b/test/browser/features/social_schedule.feature index ae8066246..8f0fe3fb4 100644 --- a/test/browser/features/social_schedule.feature +++ b/test/browser/features/social_schedule.feature @@ -13,3 +13,9 @@ Feature: Editing a social schedule in the browser When I choose morning-of posting with Space And I enter an opening line and finish immediately Then reopening the social schedule shows both changes + + Scenario: Browser history restores the schedule after returning from a provider + Given I have returned to Social after connecting a place + When I finish its schedule and open Members + Then Back returns to Social and back again reopens the connected place's schedule + And Forward returns to Social with the schedule closed diff --git a/test/browser/steps/social_schedule_steps.exs b/test/browser/steps/social_schedule_steps.exs index 89ac3983d..65250bda5 100644 --- a/test/browser/steps/social_schedule_steps.exs +++ b/test/browser/steps/social_schedule_steps.exs @@ -4,16 +4,13 @@ defmodule BrowserSocialScheduleSteps do import Huddlz.Generator import Huddlz.Test.BrowserHelpers import PhoenixTest - import PhoenixTest.Playwright, only: [press: 3] + import PhoenixTest.Playwright, only: [evaluate: 2, press: 3] step "I am editing a social connection as its owner", context do - owner = generate(user(role: :user)) - group = generate(group(owner_id: owner.id, is_public: true, actor: owner)) - generate(social_connection(group_id: group.id, actor: owner)) + {conn, group, _place} = connected_place(context.conn) conn = - context.conn - |> sign_in(owner) + conn |> visit("/organize/#{group.slug}/social") |> assert_has("body .phx-connected") |> click_button("Edit") @@ -67,4 +64,58 @@ defmodule BrowserSocialScheduleSteps do Map.put(context, :conn, conn) end + + step "I have returned to Social after connecting a place", context do + {conn, group, place} = connected_place(context.conn) + + conn = + conn + |> visit("/organize/#{group.slug}/social?connected=#{place.id}") + |> assert_has("#schedule-sheet", text: place.channel_name) + |> reload_page() + |> assert_has("body .phx-connected") + |> assert_has("#schedule-sheet", text: place.channel_name) + + Map.merge(context, %{conn: conn, place: place}) + end + + step "I finish its schedule and open Members", context do + conn = + context.conn + |> click_button("Start posting") + |> assert_browser("location.search === ''") + |> refute_has("#schedule-sheet") + |> click_link("Members") + |> assert_has("h1", text: "Members") + + Map.put(context, :conn, conn) + end + + step "Back returns to Social and back again reopens the connected place's schedule", context do + conn = + context.conn + |> evaluate("requestAnimationFrame(() => history.back())") + |> assert_has("a[aria-current='page']", text: "Social") + |> refute_has("#schedule-sheet") + |> evaluate("requestAnimationFrame(() => history.back())") + |> assert_has("#schedule-sheet", text: context.place.channel_name) + + Map.put(context, :conn, conn) + end + + step "Forward returns to Social with the schedule closed", context do + context.conn + |> evaluate("requestAnimationFrame(() => history.forward())") + |> refute_has("#schedule-sheet") + |> assert_has("h1", text: "Social") + + context + end + + defp connected_place(conn) do + owner = generate(user(role: :user)) + group = generate(group(owner_id: owner.id, is_public: true, actor: owner)) + place = generate(social_connection(group_id: group.id, actor: owner)) + {sign_in(conn, owner), group, place} + end end diff --git a/test/features/social_connections.feature b/test/features/social_connections.feature index a15991688..aa775ca92 100644 --- a/test/features/social_connections.feature +++ b/test/features/social_connections.feature @@ -204,3 +204,25 @@ Feature: A group connects a place for huddlz to post to And hand-offs come back through "https://dev.example" When I start connecting Slack from the Social tab of "Elixir Nashville" Then Slack is told to send me back to "https://dev.example/social/slack/callback" + + Scenario: Transferring ownership closes the former owner's open schedule + Given "Elixir Nashville" posts to the Slack channel "#general" + And "organizer@example.com" is an organizer of "Elixir Nashville" + And I am signed in as "owner@example.com" + When I open the Social tab of "Elixir Nashville" + And I click the "Edit" button + And the owner transfers "Elixir Nashville" to "organizer@example.com" in another session + Then I should not see "Choose when it posts" + And I can see the connection to "#general" but cannot change its schedule or remove it + And the "Pause" button should be visible + + Scenario: Archiving the group closes its open schedule + Given "Elixir Nashville" posts to the Slack channel "#general" + And I am signed in as "owner@example.com" + When I open the Social tab of "Elixir Nashville" + And I click the "Edit" button + And the owner archives "Elixir Nashville" in another session + Then I should see "This group is archived" + And I should not see "Choose when it posts" + And the "Connect a place" button should not be visible + And the "Pause" button should not be visible From de41dffab6f12dff3cb90c25c194e55aae9f1c6e Mon Sep 17 00:00:00 2001 From: Micah Woods Date: Wed, 25 Nov 2026 10:59:08 -0600 Subject: [PATCH 2/2] fix(organize): keep Social edits with their group Refresh organizer access by group ID when the slug changes and keep the open editor at the group's current address. Show removal confirmation inside that editor so a click reaches the intended action. Check group visibility when changing connections or sending test posts. Keep the existing private-group cleanup operations available outside the read-only Social page. --- lib/huddlz/communities.ex | 3 +- lib/huddlz/communities/group.ex | 15 +-- lib/huddlz/communities/social_connection.ex | 9 ++ .../checks/owns_connection_argument.ex | 9 +- lib/huddlz_web/components/modal.ex | 3 +- lib/huddlz_web/live/organize_live/social.ex | 110 +++++++++++------- .../live/organize_live/workspace.ex | 41 ++++--- lib/huddlz_web/live_user_auth.ex | 12 +- test/browser/features/social_schedule.feature | 8 ++ test/browser/steps/social_schedule_steps.exs | 29 +++++ test/features/social_connections.feature | 20 ++++ .../social_connections_steps.exs | 55 +++++++++ .../live/organize_live_social_test.exs | 104 +++++++++++++++++ 13 files changed, 331 insertions(+), 87 deletions(-) create mode 100644 test/huddlz_web/live/organize_live_social_test.exs diff --git a/lib/huddlz/communities.ex b/lib/huddlz/communities.ex index 22b8c40c2..1a653d7b7 100644 --- a/lib/huddlz/communities.ex +++ b/lib/huddlz/communities.ex @@ -86,7 +86,8 @@ defmodule Huddlz.Communities do define :drop_in?, action: :drop_in?, args: [:group_id] define :list_drop_ins, action: :drop_ins define :get_by_slug, action: :get_by_slug, args: [:slug] - define :get_group_for_organize, action: :get_for_organize, args: [:slug], get?: true + define :get_group_for_organize, action: :get_for_organize, get_by: [:slug] + define :get_group_for_organize_by_id, action: :get_for_organize, get_by: [:id] define :group_overview, action: :overview, args: [:group_id, {:optional, :period}] define :update_details, diff --git a/lib/huddlz/communities/group.ex b/lib/huddlz/communities/group.ex index 022f370a1..997a1659f 100644 --- a/lib/huddlz/communities/group.ex +++ b/lib/huddlz/communities/group.ex @@ -328,19 +328,10 @@ defmodule Huddlz.Communities.Group do read :get_for_organize do description """ - Get a group by slug, but only when the actor can manage it as an - organizer — they own the group or are an `:organizer` GroupMember. - Being an administrator does not count. Drives `OrganizeLive`'s - per-slug auth check; nil result means "not organizable by this actor." + Read a group the actor owns or helps organize, including archived + groups. Both opening a workspace by slug and refreshing it by id + use this action's organizer policies. """ - - get? true - - argument :slug, :string do - allow_nil? false - end - - filter expr(slug == ^arg(:slug)) end update :update_details do diff --git a/lib/huddlz/communities/social_connection.ex b/lib/huddlz/communities/social_connection.ex index 18e4515af..1f3dbdc71 100644 --- a/lib/huddlz/communities/social_connection.ex +++ b/lib/huddlz/communities/social_connection.ex @@ -187,6 +187,15 @@ defmodule Huddlz.Communities.SocialConnection do authorize_if Huddlz.Communities.GroupMember.Checks.GroupOwner end + # The Social page is read-only when the group closes or becomes private. + # Outside that workspace an owner can still disconnect a place, and an + # organizer can stop posting. Resuming or editing requires an open public group. + policy action([:edit, :pause, :resume, :remove]) do + authorize_if expr(group.is_public == true and is_nil(group.archived_at)) + forbid_if context_equals(:social_workspace?, true) + authorize_if action([:pause, :remove]) + end + policy action([:edit, :reconnect, :remove, :mark_needs_reconnecting]) do authorize_if expr(group.owner_id == ^actor(:id)) end diff --git a/lib/huddlz/communities/social_connection/checks/owns_connection_argument.ex b/lib/huddlz/communities/social_connection/checks/owns_connection_argument.ex index fa5bc8f90..a5703613c 100644 --- a/lib/huddlz/communities/social_connection/checks/owns_connection_argument.ex +++ b/lib/huddlz/communities/social_connection/checks/owns_connection_argument.ex @@ -1,7 +1,7 @@ defmodule Huddlz.Communities.SocialConnection.Checks.OwnsConnectionArgument do @moduledoc """ Authorizes a generic action whose `id` argument names a social connection - of a group the actor owns. Generic actions have no record to write an + of an open public group the actor owns. Generic actions have no record to write an expression policy against, so the lookup happens here. """ @@ -12,12 +12,15 @@ defmodule Huddlz.Communities.SocialConnection.Checks.OwnsConnectionArgument do alias Huddlz.Communities.SocialConnection @impl true - def describe(_opts), do: "actor owns the group of the connection named by id" + def describe(_opts), do: "actor owns the open public group of the connection named by id" @impl true def match?(%{id: actor_id}, %{subject: %{arguments: %{id: id}}}, _opts) when is_binary(id) do SocialConnection - |> Ash.Query.filter(id == ^id and group.owner_id == ^actor_id) + |> Ash.Query.filter( + id == ^id and group.owner_id == ^actor_id and + group.is_public == true and is_nil(group.archived_at) + ) |> Ash.exists?(authorize?: false) end diff --git a/lib/huddlz_web/components/modal.ex b/lib/huddlz_web/components/modal.ex index c2e5522bb..a2937112e 100644 --- a/lib/huddlz_web/components/modal.ex +++ b/lib/huddlz_web/components/modal.ex @@ -16,6 +16,7 @@ defmodule HuddlzWeb.Components.Modal do attr :id, :string, required: true attr :show, :boolean, default: false attr :on_cancel, JS, default: %JS{} + attr :dismiss_on_cancel, :boolean, default: true attr :class, :string, default: "w-full max-w-xl" attr :return_focus, :string, default: nil slot :inner_block, required: true @@ -29,7 +30,7 @@ defmodule HuddlzWeb.Components.Modal do phx-remove={ if @return_focus, do: hide_modal(@id) |> JS.focus(to: @return_focus), else: hide_modal(@id) } - data-cancel={JS.exec(@on_cancel, "phx-remove")} + data-cancel={if @dismiss_on_cancel, do: JS.exec(@on_cancel, "phx-remove"), else: @on_cancel} class="relative z-50 hidden" >
slug}, _uri, %{assigns: %{renamed_to: slug}} = socket) do + {:noreply, assign(socket, :renamed_to, nil)} + end + def handle_params(%{"group_slug" => slug} = params, _uri, socket) do previous_group = socket.assigns[:group] @@ -54,10 +59,13 @@ defmodule HuddlzWeb.OrganizeLive.Social do @impl true def handle_info({change, id}, %{assigns: %{group: %{id: id}}} = socket) when change in [:group_membership_changed, :group_changed] do + previous_slug = socket.assigns.group.slug + case Workspace.refresh(socket) do {:ok, socket} -> socket = socket |> assign_access() |> load_connections() - {:noreply, if(socket.assigns.access == :manage, do: socket, else: reset_dialogs(socket))} + socket = if socket.assigns.access == :manage, do: socket, else: reset_dialogs(socket) + {:noreply, update_address(socket, previous_slug)} {:error, socket} -> {:noreply, socket} @@ -68,6 +76,18 @@ defmodule HuddlzWeb.OrganizeLive.Social do when change in [:group_membership_changed, :group_changed], do: {:noreply, socket} + defp update_address(%{assigns: %{group: %{slug: slug}}} = socket, slug), do: socket + + defp update_address(socket, _old_slug) do + %{group: group, connected_id: connected_id} = socket.assigns + query = if connected_id, do: [connected: connected_id], else: [] + + socket + |> HuddlzWeb.LiveUserAuth.refresh_sidebar_groups() + |> assign(:renamed_to, group.slug) + |> push_patch(to: ~p"/organize/#{group.slug}/social?#{query}", replace: true) + end + defp assign_access(socket) do assign(socket, :access, access(socket.assigns.group, socket.assigns.current_user)) end @@ -79,7 +99,7 @@ defmodule HuddlzWeb.OrganizeLive.Social do defp reset_dialogs(socket, editor \\ nil) do socket - |> assign(connect_dialog?: false, removing_connection?: false) + |> assign(:dialog, if(editor, do: :schedule)) |> assign_schedule(editor) end @@ -108,45 +128,37 @@ defmodule HuddlzWeb.OrganizeLive.Social do do: {:noreply, socket} def handle_event("open_connect_dialog", _params, socket) do - {:noreply, assign(socket, :connect_dialog?, true)} + {:noreply, reset_dialogs(socket) |> assign(:dialog, :connect)} end - def handle_event("close_connect_dialog", _params, socket) do - {:noreply, assign(socket, :connect_dialog?, false)} + def handle_event("close_connect_dialog", _params, %{assigns: %{dialog: :connect}} = socket) do + {:noreply, assign(socket, :dialog, nil)} end def handle_event("edit_connection", %{"id" => id}, socket) do editor = Enum.find(socket.assigns.connections, &(&1.id == id)) - {:noreply, assign_schedule(socket, editor)} + {:noreply, reset_dialogs(socket, editor)} end - def handle_event("close_schedule", _params, socket) do + def handle_event("close_schedule", _params, %{assigns: %{dialog: :schedule}} = socket) do {:noreply, close_schedule(socket)} end - # Dismiss queued form and dialog actions after the editor has closed. - def handle_event(_event, _params, %{assigns: %{schedule_editor: nil}} = socket), - do: {:noreply, socket} - - def handle_event("ask_remove_connection", _params, socket) do - {:noreply, assign(socket, :removing_connection?, true)} + def handle_event("ask_remove_connection", _params, %{assigns: %{dialog: :schedule}} = socket) do + {:noreply, assign(socket, :dialog, :remove)} end - def handle_event("cancel_remove_connection", _params, socket) do - {:noreply, assign(socket, :removing_connection?, false)} + def handle_event("cancel_remove_connection", _params, %{assigns: %{dialog: :remove}} = socket) do + {:noreply, assign(socket, :dialog, :schedule)} end - def handle_event( - "remove_connection", - _params, - %{assigns: %{removing_connection?: false}} = socket - ), - do: {:noreply, socket} - - def handle_event("remove_connection", _params, socket) do + def handle_event("remove_connection", _params, %{assigns: %{dialog: :remove}} = socket) do %{schedule_editor: connection, current_user: user} = socket.assigns - case Communities.remove_social_connection(connection, actor: user) do + case Communities.remove_social_connection(connection, + actor: user, + context: %{social_workspace?: true} + ) do :ok -> {:noreply, socket @@ -159,7 +171,7 @@ defmodule HuddlzWeb.OrganizeLive.Social do end end - def handle_event("send_test_post", _params, socket) do + def handle_event("send_test_post", _params, %{assigns: %{dialog: :schedule}} = socket) do %{schedule_editor: connection, current_user: user} = socket.assigns case Communities.send_social_test_post(connection.id, actor: user) do @@ -175,15 +187,17 @@ defmodule HuddlzWeb.OrganizeLive.Social do end end - def handle_event("save_schedule", params, socket) do + def handle_event("save_schedule", params, %{assigns: %{dialog: :schedule}} = socket) do {:noreply, save_schedule(socket, params)} end - def handle_event("finish_schedule", params, socket) do + def handle_event("finish_schedule", params, %{assigns: %{dialog: :schedule}} = socket) do socket = save_schedule(socket, params) {:noreply, finish_schedule(socket, socket.assigns.schedule_form.source.valid?)} end + def handle_event(_event, _params, socket), do: {:noreply, socket} + defp save_schedule(socket, params) do attrs = Map.put(params["schedule"] || %{}, "moments", chosen_moments(params["moments"])) form = AshPhoenix.Form.validate(socket.assigns.schedule_form, attrs) @@ -250,7 +264,7 @@ defmodule HuddlzWeb.OrganizeLive.Social do %{current_user: user} = socket.assigns connection = Enum.find(socket.assigns.connections, &(&1.id == id)) - case connection && change.(connection, actor: user) do + case connection && change.(connection, actor: user, context: %{social_workspace?: true}) do {:ok, _connection} -> {:noreply, socket @@ -465,16 +479,26 @@ defmodule HuddlzWeb.OrganizeLive.Social do
- <.connect_place_dialog :if={@connect_dialog?} group={@group} /> - <.schedule_sheet + <.connect_place_dialog :if={@dialog == :connect} group={@group} /> + <.modal :if={@schedule_editor} - connection={@schedule_editor} - form={@schedule_form} - moments_form={@moments_form} - group={@group} - fresh?={@connected_id == @schedule_editor.id} - /> - <.remove_connection_dialog :if={@removing_connection?} connection={@schedule_editor} /> + id="schedule-sheet" + show + on_cancel={ + JS.push(if @dialog == :remove, do: "cancel_remove_connection", else: "close_schedule") + } + dismiss_on_cancel={@dialog != :remove} + > + <.remove_connection_confirmation :if={@dialog == :remove} connection={@schedule_editor} /> + <.schedule_sheet + :if={@dialog == :schedule} + connection={@schedule_editor} + form={@schedule_form} + moments_form={@moments_form} + group={@group} + fresh?={@connected_id == @schedule_editor.id} + /> + """ end @@ -566,11 +590,11 @@ defmodule HuddlzWeb.OrganizeLive.Social do attr :connection, :map, required: true - defp remove_connection_dialog(assigns) do + defp remove_connection_confirmation(assigns) do ~H""" - <.modal id="remove-connection-dialog" show on_cancel={JS.push("cancel_remove_connection")}> +
-

+

Remove {SocialConnection.place(@connection)}?

@@ -590,7 +614,7 @@ defmodule HuddlzWeb.OrganizeLive.Social do Remove connection

- +
""" end @@ -608,7 +632,7 @@ defmodule HuddlzWeb.OrganizeLive.Social do |> assign(:preview, preview_text(assigns.group, assigns.form[:opening_line].value)) ~H""" - <.modal id="schedule-sheet" show on_cancel={JS.push("close_schedule")}> +

Choose when it posts

@@ -700,7 +724,7 @@ defmodule HuddlzWeb.OrganizeLive.Social do

- +
""" end end diff --git a/lib/huddlz_web/live/organize_live/workspace.ex b/lib/huddlz_web/live/organize_live/workspace.ex index 68feaefbe..04cd8bee6 100644 --- a/lib/huddlz_web/live/organize_live/workspace.ex +++ b/lib/huddlz_web/live/organize_live/workspace.ex @@ -8,36 +8,35 @@ defmodule HuddlzWeb.OrganizeLive.Workspace do alias Huddlz.Communities.MembershipEvents def open(socket, slug) do - load_group(socket, slug, "That group doesn't exist, or you don't organize it.") + result = Communities.get_group_for_organize(slug, read_options(socket)) + assign_group(socket, result, "That group doesn't exist, or you don't organize it.") end def refresh(socket) do group = socket.assigns.group - load_group(socket, group.slug, "Your organizer access to #{group.name} has changed.") + result = Communities.get_group_for_organize_by_id(group.id, read_options(socket)) + assign_group(socket, result, "Your organizer access to #{group.name} has changed.") end - defp load_group(socket, slug, error_message) do - user = socket.assigns.current_user + defp read_options(socket) do + [actor: socket.assigns.current_user, load: [:current_image_url, :member_count]] + end - case Communities.get_group_for_organize(slug, - actor: user, - load: [:current_image_url, :member_count] - ) do - {:ok, %Communities.Group{} = group} -> - if connected?(socket) && socket.assigns[:subscribed_group_id] != group.id do - :ok = MembershipEvents.subscribe(group.id) - end + defp assign_group(socket, {:ok, %Communities.Group{} = group}, _error_message) do + if connected?(socket) && socket.assigns[:subscribed_group_id] != group.id do + :ok = MembershipEvents.subscribe(group.id) + end - {:ok, - assign(socket, - group: group, - subscribed_group_id: group.id, - page_title: "#{group.name} · Organizer" - )} + {:ok, + assign(socket, + group: group, + subscribed_group_id: group.id, + page_title: "#{group.name} · Organizer" + )} + end - _ -> - {:error, socket |> put_flash(:error, error_message) |> push_navigate(to: ~p"/organize")} - end + defp assign_group(socket, _result, error_message) do + {:error, socket |> put_flash(:error, error_message) |> push_navigate(to: ~p"/organize")} end attr :group, :map, required: true diff --git a/lib/huddlz_web/live_user_auth.ex b/lib/huddlz_web/live_user_auth.ex index dae60a51d..9c16af53b 100644 --- a/lib/huddlz_web/live_user_auth.ex +++ b/lib/huddlz_web/live_user_auth.ex @@ -317,6 +317,10 @@ defmodule HuddlzWeb.LiveUserAuth do end end + def refresh_sidebar_groups(socket) do + assign(socket, :sidebar_owned_groups, load_sidebar_owned_groups(socket)) + end + defp load_sidebar_owned_groups(%{assigns: %{current_user: user}}) when not is_nil(user) do Huddlz.Communities.get_organizable_groups!( actor: user, @@ -383,12 +387,8 @@ defmodule HuddlzWeb.LiveUserAuth do {:organizer_access_changed, user_id}, %{assigns: %{current_user: %{id: user_id}}} = socket ) do - groups = load_sidebar_owned_groups(socket) - - socket = - socket - |> assign(:sidebar_owned_groups, groups) - |> maybe_assign_picker_groups(groups) + socket = refresh_sidebar_groups(socket) + socket = maybe_assign_picker_groups(socket, socket.assigns.sidebar_owned_groups) organizer_access_result(socket) end diff --git a/test/browser/features/social_schedule.feature b/test/browser/features/social_schedule.feature index 8f0fe3fb4..f9d3d31d6 100644 --- a/test/browser/features/social_schedule.feature +++ b/test/browser/features/social_schedule.feature @@ -19,3 +19,11 @@ Feature: Editing a social schedule in the browser When I finish its schedule and open Members Then Back returns to Social and back again reopens the connected place's schedule And Forward returns to Social with the schedule closed + + @social_removal_browser + Scenario: The owner can reconsider removing a place before disconnecting it + Given I am editing a social connection as its owner + When I ask to remove the place and cancel + Then I can continue editing its schedule + When I ask to remove the place again and confirm + Then Social lists no connected places diff --git a/test/browser/steps/social_schedule_steps.exs b/test/browser/steps/social_schedule_steps.exs index 65250bda5..f97860392 100644 --- a/test/browser/steps/social_schedule_steps.exs +++ b/test/browser/steps/social_schedule_steps.exs @@ -24,6 +24,35 @@ defmodule BrowserSocialScheduleSteps do Map.put(context, :conn, conn) end + step "I ask to remove the place and cancel", context do + conn = context.conn |> click_button("Remove") |> click_button("Cancel") + Map.put(context, :conn, conn) + end + + step "I can continue editing its schedule", context do + conn = + context.conn + |> assert_has("#schedule-form") + |> fill_in("Opening line", with: "Still connected!") + |> assert_has("#social-post-preview", text: "Still connected!") + + Map.put(context, :conn, conn) + end + + step "I ask to remove the place again and confirm", context do + conn = context.conn |> click_button("Remove") |> click_button("Remove connection") + Map.put(context, :conn, conn) + end + + step "Social lists no connected places", context do + context.conn + |> assert_has("#social-connections", text: "Nothing connected yet") + |> reload_page() + |> assert_has("#social-connections", text: "Nothing connected yet") + + context + end + step "I choose morning-of posting with Space", context do conn = press(context.conn, "#moments_morning_of", "Space") Map.put(context, :conn, conn) diff --git a/test/features/social_connections.feature b/test/features/social_connections.feature index aa775ca92..18616edc9 100644 --- a/test/features/social_connections.feature +++ b/test/features/social_connections.feature @@ -226,3 +226,23 @@ Feature: A group connects a place for huddlz to post to And I should not see "Choose when it posts" And the "Connect a place" button should not be visible And the "Pause" button should not be visible + + @social_rename + Scenario: A group keeps its open schedule when its address changes + Given "Elixir Nashville" posts to the Slack channel "#general" + And I am signed in as "owner@example.com" + When I enter an opening line longer than 140 characters and finish + And the owner changes the group address to "music-city-elixir" in another session + Then I can correct the opening line and the saved connection is unchanged + And I can continue editing "#general" at the new Social address "music-city-elixir" + + @social_read_only + Scenario: Making a group private stops edits to its social schedule + Given "Elixir Nashville" posts to the Slack channel "#general" + And I am signed in as "owner@example.com" + When I open the Social tab of "Elixir Nashville" + And I click the "Edit" button + And the owner makes the group private in another session + Then the Social tab explains that only public groups post + And I should not see "Choose when it posts" + And my earlier connection cannot save a new opening line diff --git a/test/features/step_definitions/social_connections_steps.exs b/test/features/step_definitions/social_connections_steps.exs index 15cdf4710..996526b83 100644 --- a/test/features/step_definitions/social_connections_steps.exs +++ b/test/features/step_definitions/social_connections_steps.exs @@ -15,6 +15,7 @@ defmodule SocialConnectionsSteps do alias Huddlz.Accounts.User alias Huddlz.Communities.Group alias Huddlz.Communities.SocialConnection + alias Huddlz.Test.Helpers.Authentication # Connecting hands off to the platform's own consent screen and comes back # to huddlz with a code. The hand-off is followed by hand here: the redirect @@ -137,6 +138,60 @@ defmodule SocialConnectionsSteps do Map.merge(context, %{session: session, conn: session, group: group}) end + step "the owner makes the group private in another session", context do + build_conn() + |> Authentication.login(context.current_user) + |> visit("/groups/#{context.group.slug}/edit") + |> uncheck("Public group") + |> click_button("Save Changes") + |> assert_path("/groups/#{context.group.slug}") + + context + end + + step "my earlier connection cannot save a new opening line", context do + assert {:error, _} = + Huddlz.Communities.edit_social_connection( + context.connection, + %{opening_line: "A new opening line"}, + actor: context.current_user + ) + + saved = + Huddlz.Communities.get_social_connection!(context.connection.id, + actor: context.current_user + ) + + assert saved.opening_line == context.connection.opening_line + context + end + + step "the owner changes the group address to {string} in another session", + %{args: [slug]} = context do + build_conn() + |> Authentication.login(context.current_user) + |> visit("/groups/#{context.group.slug}/edit") + |> fill_in("URL Slug", with: slug) + |> click_button("Save Changes") + |> assert_path("/groups/#{slug}") + + context + end + + step "I can continue editing {string} at the new Social address {string}", + %{args: [channel, slug]} = context do + context.session + |> assert_has("#schedule-sheet", text: channel) + |> assert_path("/organize/#{slug}/social", timeout: 1000) + |> fill_in("Opening line", with: "See you tonight!") + |> click_button("Done") + |> assert_has("#social-connections", text: "See you tonight!") + |> click_link("Members") + |> assert_path("/organize/#{slug}/members") + + context + end + step "I can see the connection to {string} but cannot change its schedule or remove it", %{args: [channel]} = context do context.session diff --git a/test/huddlz_web/live/organize_live_social_test.exs b/test/huddlz_web/live/organize_live_social_test.exs new file mode 100644 index 000000000..98bb62bf3 --- /dev/null +++ b/test/huddlz_web/live/organize_live_social_test.exs @@ -0,0 +1,104 @@ +defmodule HuddlzWeb.OrganizeLiveSocialTest do + use HuddlzWeb.ConnCase, async: true + + import Phoenix.LiveViewTest + + alias Huddlz.Communities + alias Huddlz.Communities.SocialConnection + + setup %{conn: conn} do + owner = generate(user(role: :user)) + group = generate(group(actor: owner)) + place = generate(social_connection(group_id: group.id, actor: owner)) + + {:ok, view, _} = + live(login(conn, owner), ~p"/organize/#{group.slug}/social?connected=#{place.id}") + + %{owner: owner, group: group, place: place, view: view} + end + + test "a provider return stays with its original group after another group takes its slug", + %{owner: owner, group: group, place: place, view: view} do + # Hold the notification until the old address has a new owner. + {renamed, notifications} = + Ash.update!(group, %{slug: "new-address"}, + action: :update_details, + actor: owner, + return_notifications?: true + ) + + replacement = generate(group(name: "Another group", slug: group.slug, actor: owner)) + other_place = generate(social_connection(group_id: replacement.id, actor: owner)) + Ash.Notifier.notify(notifications) + + assert_patch(view, ~p"/organize/#{renamed.slug}/social?connected=#{place.id}") + assert has_element?(view, "#schedule-sheet", "Start posting") + assert has_element?(view, "#social-connection-#{place.id}") + refute has_element?(view, "#social-connection-#{other_place.id}") + end + + test "an obsolete edit selection dismisses removal confirmation", %{view: view, place: place} do + render_click(element(view, "#remove-connection")) + assert has_element?(view, "#remove-connection-confirm") + render_click(view, "edit_connection", %{"id" => Ash.UUID.generate()}) + refute has_element?(view, "#schedule-sheet") + assert has_element?(view, "#social-connection-#{place.id}") + end + + for visibility <- [:private, :archived] do + test "a queued Social interaction respects a group that became #{visibility}", %{ + owner: owner, + group: group, + place: place, + view: view + } do + # Hold the change notification so the owner still sees the preceding controls. + notifications = close_group(group, owner, unquote(visibility)) + render_click(element(view, "#pause-connection-#{place.id}")) + assert %{state: :posting} = Communities.get_social_connection!(place.id, authorize?: false) + + assert {:error, _} = Communities.resume_social_connection(place, actor: owner) + + assert {:error, _} = + Communities.edit_social_connection(place, %{opening_line: "Later"}, actor: owner) + + assert {:error, %Ash.Error.Forbidden{}} = + Communities.send_social_test_post(place.id, actor: owner) + + render_click(element(view, "#remove-connection")) + render_click(element(view, "#remove-connection-confirm")) + assert %SocialConnection{} = Communities.get_social_connection!(place.id, authorize?: false) + + Ash.Notifier.notify(notifications) + refute has_element?(view, "#schedule-sheet") + end + end + + test "the owner can still stop and disconnect a private group's old destination", %{ + owner: owner, + group: group, + place: place + } do + Ash.update!(group, %{is_public: false}, action: :update_details, actor: owner) + assert {:ok, %{state: :paused}} = Communities.pause_social_connection(place, actor: owner) + assert :ok = Communities.remove_social_connection(place, actor: owner) + end + + defp close_group(group, owner, :private) do + {_group, notifications} = + Ash.update!(group, %{is_public: false}, + action: :update_details, + actor: owner, + return_notifications?: true + ) + + notifications + end + + defp close_group(group, owner, :archived) do + {:ok, notifications} = + Communities.archive_group(group, actor: owner, return_notifications?: true) + + notifications + end +end