Sha256: eb2ca501e65a094be97e49d64020d44bbbbadccfca79f496b8b32d98e768469b

Contents?: true

Size: 1.73 KB

Versions: 6

Compression:

Stored size: 1.73 KB

Contents

# frozen_string_literal: true

module Decidim
  module Debates
    # This command is executed when the user creates a Debate from the public
    # views.
    class CreateDebate < Rectify::Command
      def initialize(form)
        @form = form
      end

      # Creates the debate if valid.
      #
      # Broadcasts :ok if successful, :invalid otherwise.
      def call
        return broadcast(:invalid) if form.invalid?

        transaction do
          create_debate
          send_notifications
        end
        broadcast(:ok, debate)
      end

      private

      attr_reader :debate, :form

      def organization
        @organization = form.current_feature.organization
      end

      def i18n_field(field)
        organization.available_locales.inject({}) do |i18n, locale|
          i18n.update(locale => field)
        end
      end

      def create_debate
        @debate = Debate.create!(
          author: form.current_user,
          decidim_user_group_id: form.user_group_id,
          category: form.category,
          title: i18n_field(form.title),
          description: i18n_field(form.description),
          feature: form.current_feature
        )
      end

      def send_notifications
        send_notification(debate.author.followers.pluck(:id), :user)
        send_notification(debate.participatory_space.followers.pluck(:id), :participatory_space)
      end

      def send_notification(recipient_ids, type)
        Decidim::EventsManager.publish(
          event: "decidim.events.debates.debate_created",
          event_class: Decidim::Debates::CreateDebateEvent,
          resource: debate,
          recipient_ids: recipient_ids,
          extra: {
            type: type.to_s
          }
        )
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
decidim-debates-0.10.1 app/commands/decidim/debates/create_debate.rb
decidim-debates-0.10.0 app/commands/decidim/debates/create_debate.rb
decidim-debates-0.9.3 app/commands/decidim/debates/create_debate.rb
decidim-debates-0.9.2 app/commands/decidim/debates/create_debate.rb
decidim-debates-0.9.1 app/commands/decidim/debates/create_debate.rb
decidim-debates-0.9.0 app/commands/decidim/debates/create_debate.rb