1# frozen_string_literal: true
2
3module Ci
4  class UnitTestFailure < Ci::ApplicationRecord
5    REPORT_WINDOW = 14.days
6
7    validates :unit_test, :build, :failed_at, presence: true
8
9    belongs_to :unit_test, class_name: "Ci::UnitTest", foreign_key: :unit_test_id
10    belongs_to :build, class_name: "Ci::Build", foreign_key: :build_id
11
12    scope :deletable, -> { where('failed_at < ?', REPORT_WINDOW.ago) }
13
14    def self.recent_failures_count(project:, unit_test_keys:, date_range: REPORT_WINDOW.ago..Time.current)
15      joins(:unit_test)
16        .where(
17          ci_unit_tests: {
18            project_id: project.id,
19            key_hash: unit_test_keys
20          },
21          ci_unit_test_failures: {
22            failed_at: date_range
23          }
24        )
25        .group(:key_hash)
26        .count('ci_unit_test_failures.id')
27    end
28  end
29end
30