Sha256: 8f9b57fdf7e98fbcac547a37d0cc84b3904060c056eeea4523eb94a695960172

Contents?: true

Size: 1.81 KB

Versions: 13

Compression:

Stored size: 1.81 KB

Contents

# frozen_string_literal: true

require "digest/sha1"

module Decidim
  # Initiatives can be voted by users and supported by organizations.
  class InitiativesVote < ApplicationRecord
    include Decidim::TranslatableAttributes

    belongs_to :author,
               foreign_key: "decidim_author_id",
               class_name: "Decidim::User"

    belongs_to :initiative,
               foreign_key: "decidim_initiative_id",
               class_name: "Decidim::Initiative",
               inverse_of: :votes

    belongs_to :scope,
               foreign_key: "decidim_scope_id",
               class_name: "Decidim::Scope",
               optional: true

    validates :initiative, uniqueness: { scope: [:author, :scope] }
    validates :initiative, uniqueness: { scope: [:hash_id, :scope] }

    after_commit :update_counter_cache, on: [:create, :destroy]

    scope :for_scope, ->(scope) { where(scope:) }

    # Public: Generates a hashed representation of the initiative support.
    #
    # Used when exporting the votes as CSV.
    def sha1
      title = translated_attribute(initiative.title)
      description = translated_attribute(initiative.description)

      Digest::SHA1.hexdigest "#{authorization_unique_id}#{title}#{description}"
    end

    def decrypted_metadata
      @decrypted_metadata ||= encrypted_metadata ? encryptor.decrypt(encrypted_metadata) : {}
    end

    private

    def encryptor
      @encryptor ||= Decidim::Initiatives::DataEncryptor.new(secret: "personal user metadata")
    end

    def authorization_unique_id
      first_authorization = Decidim::Initiatives::UserAuthorizations
                            .for(author)
                            .first

      first_authorization&.unique_id || author.email
    end

    def update_counter_cache
      initiative.update_online_votes_counters
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
decidim-initiatives-0.29.1 app/models/decidim/initiatives_vote.rb
decidim-initiatives-0.28.4 app/models/decidim/initiatives_vote.rb
decidim-initiatives-0.29.0 app/models/decidim/initiatives_vote.rb
decidim-initiatives-0.28.3 app/models/decidim/initiatives_vote.rb
decidim-initiatives-0.29.0.rc4 app/models/decidim/initiatives_vote.rb
decidim-initiatives-0.29.0.rc3 app/models/decidim/initiatives_vote.rb
decidim-initiatives-0.29.0.rc2 app/models/decidim/initiatives_vote.rb
decidim-initiatives-0.29.0.rc1 app/models/decidim/initiatives_vote.rb
decidim-initiatives-0.28.2 app/models/decidim/initiatives_vote.rb
decidim-initiatives-0.28.1 app/models/decidim/initiatives_vote.rb
decidim-initiatives-0.28.0 app/models/decidim/initiatives_vote.rb
decidim-initiatives-0.28.0.rc5 app/models/decidim/initiatives_vote.rb
decidim-initiatives-0.28.0.rc4 app/models/decidim/initiatives_vote.rb