summaryrefslogtreecommitdiff
path: root/app/services/tartiflette_scoring_service.rb
blob: 2c12025b1e0c91870ec471a237c5e6567484bb0f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class TartifletteScoringService
  def self.scored?(tartiflette, session)
    session[:scored_tartiflettes] ||= []
    session[:scored_tartiflettes]&.include?(tartiflette.id)
  end

  def self.mark_as_scored(tartiflette, session)
    session[:scored_tartiflettes] ||= []
    session[:scored_tartiflettes] << tartiflette.id unless scored?(tartiflette, session)
  end

  def self.submit_scores(tartiflette, scores, session)
    scores.each do |criterium_id, score_params|
      Score.create!(
        session_id: session.id,
        tartiflette: tartiflette,
        scoring_criterium_id: criterium_id,
        value: score_params[:value]
      )
    end
    mark_as_scored(tartiflette, session)
  rescue ActiveRecord::RecordInvalid => e
    raise StandardError, "Failed to create score: #{e.message}"
  end

  def self.update_scores(tartiflette, scores, session)
    scores.each do |score_id, score_params|
      score = tartiflette.scores.find(score_id)
      score.update!(value: score_params[:value])
    end
  rescue ActiveRecord::RecordInvalid => e
    raise StandardError, "Failed to update score: #{e.message}"
  end

  def self.average_score(tartiflette)
    tartiflette.scores.average(:value).to_f
  end

  def self.average_score_by_category(tartiflette)
    tartiflette
      .scores
      .group_by { |score| score.scoring_criterium.category }
      .transform_values do |scores|
      (scores.sum(&:value).to_f / scores.size).round(2)
    end
  end

  def self.total_score_by_category(tartiflette)
    tartiflette
      .scores
      .group_by { |score| score.scoring_criterium.category }
      .transform_values do |scores|
      (scores.sum(&:value).to_f / scores.size).round(2)
    end
  end

  def self.leaderboard
    Tartiflette
      .joins(:scores)
      .select("tartiflettes.*, SUM(scores.value) AS total_score")
      .group("tartiflettes.id")
      .order("total_score DESC")
      .map { |tartiflette| [ tartiflette, tartiflette.total_score.to_f ] }
  end
end
Copyright 2019--2025 Marius PETER