Sha256: fd0af92e4ded80d3969fb68fe824b3c9aae8456388ff8b1d160f23955070f683

Contents?: true

Size: 1.5 KB

Versions: 12

Compression:

Stored size: 1.5 KB

Contents

# frozen_string_literal: true

module Decidim
  # A command with all the business logic to invite a user to a group.
  class InviteUserToGroup < Decidim::Command
    # Public: Initializes the command.
    #
    # form - A form object with the params.
    # user_group - The user group that invites the user
    def initialize(form, user_group)
      @form = form
      @user_group = user_group
    end

    # Executes the command. Broadcasts these events:
    #
    # - :ok when everything is valid.
    # - :invalid if the form wasn't valid and we couldn't proceed.
    #
    # Returns nothing.
    def call
      return broadcast(:invalid) if form.invalid?
      return broadcast(:ok) if user_belongs_to_group?

      transaction do
        invite_user
        send_notification
      end

      broadcast(:ok)
    end

    private

    attr_reader :form, :user_group

    def invite_user
      Decidim::UserGroupMembership.create!(
        user: form.user,
        user_group: user_group,
        role: :invited
      )
    end

    def send_notification
      Decidim::EventsManager.publish(
        event: "decidim.events.groups.invited_to_group",
        event_class: InvitedToGroupEvent,
        resource: user_group,
        affected_users: [form.user],
        extra: {
          user_group_name: user_group.name,
          user_group_nickname: user_group.nickname
        }
      )
    end

    def user_belongs_to_group?
      Decidim::UserGroupMembership.where(user: form.user, user_group: user_group).any?
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
decidim-core-0.27.9 app/commands/decidim/invite_user_to_group.rb
decidim-core-0.27.8 app/commands/decidim/invite_user_to_group.rb
decidim-core-0.27.7 app/commands/decidim/invite_user_to_group.rb
decidim-core-0.27.6 app/commands/decidim/invite_user_to_group.rb
decidim-core-0.27.5 app/commands/decidim/invite_user_to_group.rb
decidim-core-0.27.4 app/commands/decidim/invite_user_to_group.rb
decidim-core-0.27.3 app/commands/decidim/invite_user_to_group.rb
decidim-core-0.27.2 app/commands/decidim/invite_user_to_group.rb
decidim-core-0.27.1 app/commands/decidim/invite_user_to_group.rb
decidim-core-0.27.0 app/commands/decidim/invite_user_to_group.rb
decidim-core-0.27.0.rc2 app/commands/decidim/invite_user_to_group.rb
decidim-core-0.27.0.rc1 app/commands/decidim/invite_user_to_group.rb