Sha256: d08dd4fa0905bc6ca9c6aba212ab1d3c323dd5d53935313dc9f422fb000ea9ca

Contents?: true

Size: 1.27 KB

Versions: 2

Compression:

Stored size: 1.27 KB

Contents

# frozen_string_literal: true

module Decidim
  module DecidimAwesome
    class VoteWeight < ApplicationRecord
      self.table_name = "decidim_awesome_vote_weights"
      belongs_to :vote, foreign_key: "proposal_vote_id", class_name: "Decidim::Proposals::ProposalVote"

      delegate :proposal, to: :vote

      after_destroy :update_vote_weight_totals!
      after_save :update_vote_weight_totals!

      def update_vote_weight_totals!
        extra = Decidim::DecidimAwesome::ProposalExtraField.find_or_initialize_by(proposal:)
        extra.vote_weight_totals = extra.vote_weight_totals || {}

        prev = weight_previous_change&.first
        if prev.present?
          extra.vote_weight_totals[prev.to_s] = Decidim::DecidimAwesome::VoteWeight.where(vote: proposal.votes, weight: prev).count
          extra.vote_weight_totals.delete(prev.to_s) if extra.vote_weight_totals[prev.to_s].zero?
        end
        extra.vote_weight_totals[weight.to_s] = Decidim::DecidimAwesome::VoteWeight.where(vote: proposal.votes, weight:).count
        extra.vote_weight_totals.delete(weight.to_s) if extra.vote_weight_totals[weight.to_s].zero?
        extra.weight_total = extra.vote_weight_totals.inject(0) { |sum, (weight, count)| sum + (weight.to_i * count) }
        extra.save!
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
decidim-decidim_awesome-0.11.2 app/models/decidim/decidim_awesome/vote_weight.rb
decidim-decidim_awesome-0.11.1 app/models/decidim/decidim_awesome/vote_weight.rb