defmodule Jnb.Support.Team do use Ash.Resource, otp_app: :jnb, domain: Jnb.Support, data_layer: AshPostgres.DataLayer, notifiers: [Ash.Notifier.PubSub] postgres do table "teams" repo Jnb.Repo end actions do defaults [:read] destroy :destroy do primary? true require_atomic? false # Clear the many-to-many relationship before destroying change before_action(fn changeset, _context -> case Ash.load(changeset.data, :ticket_relationships) do {:ok, team} -> # Delete all join table records Enum.each(team.ticket_relationships, fn rel -> Ash.destroy!(rel) end) changeset _ -> changeset end end) end create :create do accept [:name] primary? true argument :ticket_ids, {:array, :uuid}, allow_nil?: true change manage_relationship(:ticket_ids, :tickets, type: :append_and_remove) end update :update do accept [:name] primary? true argument :ticket_ids, {:array, :uuid}, allow_nil?: true require_atomic? false change manage_relationship(:ticket_ids, :tickets, type: :append_and_remove) end end pub_sub do module JnbWeb.Endpoint prefix "teams" # This will publish all actions to a single topic "teams" # with the action name as the event (e.g., "create", "update", "destroy") publish_all :create, "" publish_all :update, "" publish_all :destroy, "" end attributes do uuid_primary_key :id attribute :name, :string do allow_nil? false public? true end timestamps() end relationships do has_many :ticket_relationships, Jnb.Support.TeamTicket do destination_attribute :team_id end many_to_many :tickets, Jnb.Support.Ticket do join_relationship :ticket_relationships source_attribute_on_join_resource :team_id destination_attribute_on_join_resource :ticket_id end end aggregates do list :ticket_ids, :tickets, :id end end