FFFF feat(notifications): huddl lifecycle and reminders (C1-C4, D1-D2) by mwoods79 · Pull Request #131 · huddlz-hq/huddlz · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 89 additions & 2 deletions lib/huddlz/communities/huddl.ex
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ defmodule Huddlz.Communities.Huddl do
domain: Huddlz.Communities,
data_layer: AshPostgres.DataLayer,
authorizers: [Ash.Policy.Authorizer],
extensions: [AshJsonApi.Resource, AshGraphql.Resource],
extensions: [AshOban, AshJsonApi.Resource, AshGraphql.Resource],
primary_read_warning?: false

graphql do
Expand Down Expand Up @@ -50,6 +50,28 @@ defmodule Huddlz.Communities.Huddl do
end
end

oban do
triggers do
trigger :send_24h_reminder do
action :send_24h_reminder
read_action :due_for_24h_reminder
scheduler_cron "*/2 * * * *"
queue :notifications
worker_module_name Huddlz.Notifications.Workers.HuddlReminder24h
scheduler_module_name Huddlz.Notifications.Workers.HuddlReminder24hScheduler
end

trigger :send_1h_reminder do
action :send_1h_reminder
read_action :due_for_1h_reminder
scheduler_cron "*/2 * * * *"
queue :notifications
worker_module_name Huddlz.Notifications.Workers.HuddlReminder1h
scheduler_module_name Huddlz.Notifications.Workers.HuddlReminder1hScheduler
end
end
end

postgres do
table "huddlz"
repo Huddlz.Repo
Expand All @@ -67,7 +89,11 @@ defmodule Huddlz.Communities.Huddl do
end

actions do
defaults [:destroy]
destroy :destroy do
primary? true
require_atomic? false
change Huddlz.Communities.Huddl.Changes.NotifyCancelled
end

read :read do
primary? true
Expand Down Expand Up @@ -116,6 +142,7 @@ defmodule Huddlz.Communities.Huddl do
change Huddlz.Geocoding.ApplyProvidedCoordinates
change {Huddlz.Geocoding.GeocodeChange, field: :physical_location}
change Huddlz.Communities.Huddl.Changes.DefaultLocationFromGroup
change Huddlz.Communities.Huddl.Changes.NotifyNewInGroup
end

update :update do
Expand Down Expand Up @@ -163,6 +190,8 @@ defmodule Huddlz.Communities.Huddl do
change {Huddlz.Geocoding.GeocodeChange, field: :physical_location}
change Huddlz.Communities.Huddl.Changes.DefaultLocationFromGroup
change Huddlz.Communities.Huddl.Changes.EnforceCapacityFloor
change Huddlz.Communities.Huddl.Changes.ResetReminderStamps
change Huddlz.Communities.Huddl.Changes.NotifyMeaningfulUpdate
end

read :by_status do
Expand Down Expand Up @@ -270,6 +299,44 @@ defmodule Huddlz.Communities.Huddl do

change Huddlz.Communities.Huddl.Changes.CancelRsvp
end

read :due_for_24h_reminder do
description "Huddlz starting in the next 24 hours that have not yet had a 24h reminder sent."

pagination keyset?: true, required?: false, default_limit: 100

filter expr(
starts_at > now() and
starts_at < from_now(24, :hour) and
is_nil(reminder_24h_sent_at)
)
end

read :due_for_1h_reminder do
description "Huddlz starting in the next hour that have not yet had a 1h reminder sent."

pagination keyset?: true, required?: false, default_limit: 100

filter expr(
starts_at > now() and
starts_at < from_now(1, :hour) and
is_nil(reminder_1h_sent_at)
)
end

update :send_24h_reminder do
description "Mark and fan out the 24-hour reminder for this huddl. Invoked by the AshOban scheduler."
require_atomic? false

change {Huddlz.Communities.Huddl.Changes.SendReminder, kind: :h24}
end

update :send_1h_reminder do
description "Mark and fan out the 1-hour reminder for this huddl. Invoked by the AshOban scheduler."
require_atomic? false

change {Huddlz.Communities.Huddl.Changes.SendReminder, kind: :h1}
end
end

policies do
Expand All @@ -293,6 +360,12 @@ defmodule Huddlz.Communities.Huddl do
authorize_if always()
end

# Reminder fan-out actions are invoked by the AshOban scheduler with no actor.
policy action([:send_24h_reminder, :send_1h_reminder]) do
description "Reminder dispatch runs from background scheduler"
authorize_if always()
end

# RSVP policies
policy action(:rsvp) do
description "Users can RSVP to huddlz they have access to"
Expand Down Expand Up @@ -414,6 +487,20 @@ defmodule Huddlz.Communities.Huddl do
constraints min: -180, max: 180
end

attribute :reminder_24h_sent_at, :utc_datetime_usec do
allow_nil? true
public? false

description "Stamped when the 24-hour reminder has been sent for this huddl. Reset to nil when starts_at changes."
end

attribute :reminder_1h_sent_at, :utc_datetime_usec do
allow_nil? true
public? false

description "Stamped when the 1-hour reminder has been sent for this huddl. Reset to nil when starts_at changes."
end

create_timestamp :inserted_at
update_timestamp :updated_at
end
Expand Down
57 changes: 57 additions & 0 deletions lib/huddlz/communities/huddl/changes/notify_cancelled.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
defmodule Huddlz.Communities.Huddl.Changes.NotifyCancelled do
@moduledoc """
Enqueues C3 (huddl_cancelled) notifications when a huddl is destroyed.

Captures attendee user_ids and the huddl's display fields in
`before_action` because the HuddlAttendee rows cascade-delete with
the huddl and the row itself disappears. The actor (the user
destroying the huddl, typically an organizer) is excluded from the
recipients. Fans out emails in `after_action` once the destroy
commits.
"""

use Ash.Resource.Change

alias Huddlz.Accounts.User
alias Huddlz.Communities.Huddl.Changes.RecipientHelpers
alias Huddlz.Notifications

@impl true
def change(changeset, _opts, _context) do
changeset
|> Ash.Changeset.before_action(&capture_recipients_and_payload/1)
|> Ash.Changeset.after_action(&notify/2)
end

defp capture_recipients_and_payload(cs) do
huddl = Ash.load!(cs.data, [:group], authorize?: false)

recipients =
RecipientHelpers.rsvp_user_ids(huddl.id, exclude: RecipientHelpers.actor_id(cs))

payload = %{
"huddl_title" => to_string(huddl.title),
"starts_at_iso" => DateTime.to_iso8601(huddl.starts_at),
"group_name" => to_string(huddl.group.name),
"group_slug" => to_string(huddl.group.slug)
}

cs
|> Ash.Changeset.put_context(:huddl_cancelled_recipients, recipients)
|> Ash.Changeset.put_context(:huddl_cancelled_payload, payload)
end

defp notify(cs, huddl) do
recipients = cs.context[:huddl_cancelled_recipients] || []
payload = cs.context[:huddl_cancelled_payload] || %{}

for user_id <- recipients do
case Ash.get(User, user_id, authorize?: false) do
{:ok, user} -> Notifications.deliver_async(user, :huddl_cancelled, payload)
_ -> :noop
end
end

{:ok, huddl}
end
end
117 changes: 117 additions & 0 deletions lib/huddlz/communities/huddl/changes/notify_meaningful_update.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
defmodule Huddlz.Communities.Huddl.Changes.NotifyMeaningfulUpdate do
@moduledoc """
Enqueues notifications when a huddl is edited in a way that affects
an attendee's plans — i.e. one of `:title`, `:starts_at`, `:ends_at`,
`:physical_location`, or `:virtual_link` is in the changeset.
Cosmetic edits (description, thumbnail, etc.) do not trigger an
email.

Branches on the `edit_type` action argument:

* `"instance"` (default) — C2: fan out `:huddl_updated` to the
current huddl's RSVPs, excluding the actor.
* `"all"` — C4: `EditRecurringHuddlz` has regenerated every
future instance in the series. Fan out
`:huddl_series_updated` to the RSVPs of the *next upcoming
instance only*, excluding the actor. Subsequent instances rely
on their own D1/D2 reminders.

Both branches use the same "meaningful field" gate.
"""

use Ash.Resource.Change

require Ash.Query

alias Huddlz.Accounts.User
alias Huddlz.Communities.Huddl
alias Huddlz.Communities.Huddl.Changes.RecipientHelpers
alias Huddlz.Notifications

@meaningful_attrs [:title, :starts_at, :ends_at, :physical_location, :virtual_link]

@impl true
def change(changeset, _opts, _context) do
changed_fields =
Enum.filter(@meaningful_attrs, &Ash.Changeset.changing_attribute?(changeset, &1))

if changed_fields == [] do
changeset
else
changeset
|> Ash.Changeset.put_context(:huddl_updated_changed_fields, changed_fields)
|> Ash.Changeset.after_action(&notify/2)
end
end

defp notify(cs, huddl) do
case Ash.Changeset.get_argument(cs, :edit_type) do
"all" -> notify_series(cs, huddl)
_ -> notify_instance(cs, huddl)
end
end

defp notify_instance(cs, huddl) do
huddl = Ash.load!(huddl, [:group], authorize?: false)
changed_fields = cs.context[:huddl_updated_changed_fields] || []

recipients =
RecipientHelpers.rsvp_user_ids(huddl.id, exclude: RecipientHelpers.actor_id(cs))

payload = base_payload(huddl, changed_fields)

deliver_each(recipients, :huddl_updated, payload)

{:ok, huddl}
end

defp notify_series(cs, huddl) do
case fetch_next_upcoming_instance(huddl) do
nil ->
{:ok, huddl}

next ->
next = Ash.load!(next, [:group], authorize?: false)
changed_fields = cs.context[:huddl_updated_changed_fields] || []

recipients =
RecipientHelpers.rsvp_user_ids(next.id, exclude: RecipientHelpers.actor_id(cs))

payload = base_payload(next, changed_fields)

deliver_each(recipients, :huddl_series_updated, payload)

{:ok, huddl}
end
end

defp fetch_next_upcoming_instance(%Huddl{huddl_template_id: nil}), do: nil

defp fetch_next_upcoming_instance(%Huddl{huddl_template_id: template_id}) do
Huddl
|> Ash.Query.filter(huddl_template_id == ^template_id and starts_at > now())
|> Ash.Query.sort(starts_at: :asc)
|> Ash.Query.limit(1)
|> Ash.read_one!(authorize?: false)
end

defp base_payload(huddl, changed_fields) do
%{
"huddl_id" => huddl.id,
"huddl_title" => to_string(huddl.title),
"starts_at_iso" => DateTime.to_iso8601(huddl.starts_at),
"group_name" => to_string(huddl.group.name),
"group_slug" => to_string(huddl.group.slug),
"changed_fields" => Enum.map(changed_fields, &Atom.to_string/1)
}
end

defp deliver_each(user_ids, trigger, payload) do
for user_id <- user_ids do
case Ash.get(User, user_id, authorize?: false) do
{:ok, user} -> Notifications.deliver_async(user, trigger, payload)
_ -> :noop
end
end
end
end
68 changes: 68 additions & 0 deletions lib/huddlz/communities/huddl/changes/notify_new_in_group.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
defmodule Huddlz.Communities.Huddl.Changes.NotifyNewInGroup do
@moduledoc """
Enqueues C1 (huddl_new) notifications when a new huddl is created
in a group. Sent to every group member except the actor (the user
who created the huddl).

Skipped when the create runs without an actor — that path is
reserved for system-driven creations (e.g. `RecurrenceHelper`
generating subsequent instances of a recurring series). Group
members shouldn't get a "new huddl" email for every weekly
occurrence of the same series; the first instance covers it, and
D1/D2 reminders cover each occurrence individually.

Recipient resolution happens in `after_action` once the huddl row
exists, so the new huddl's group is reachable.
"""

use Ash.Resource.Change

require Ash.Query

alias Huddlz.Accounts.User
alias Huddlz.Communities.GroupMember
alias Huddlz.Communities.Huddl.Changes.RecipientHelpers
alias Huddlz.Notifications

@impl true
def change(changeset, _opts, _context) do
Ash.Changeset.after_action(changeset, &notify/2)
end

defp notify(cs, huddl) do
case RecipientHelpers.actor_id(cs) do
nil -> {:ok, huddl}
actor_id -> notify_with_actor(cs, huddl, actor_id)
end
end

defp notify_with_actor(_cs, huddl, actor_id) do
huddl = Ash.load!(huddl, [:group], authorize?: false)

user_ids =
GroupMember
|> Ash.Query.filter(group_id == ^huddl.group_id)
|> Ash.Query.select([:user_id])
|> Ash.read!(authorize?: false)
|> Enum.map(& &1.user_id)
|> Enum.uniq()
|> Enum.r 7865 eject(&(&1 == actor_id))

payload = %{
"huddl_id" => huddl.id,
"huddl_title" => to_string(huddl.title),
"starts_at_iso" => DateTime.to_iso8601(huddl.starts_at),
"group_name" => to_string(huddl.group.name),
"group_slug" => to_string(huddl.group.slug)
}

for user_id <- user_ids do
case Ash.get(User, user_id, authorize?: false) do
{:ok, user} -> Notifications.deliver_async(user, :huddl_new, payload)
_ -> :noop
end
end

{:ok, huddl}
end
end
Loading
Loading
0