1# frozen_string_literal: true
2
3module Limitable
4  extend ActiveSupport::Concern
5  GLOBAL_SCOPE = :limitable_global_scope
6
7  included do
8    class_attribute :limit_scope
9    class_attribute :limit_relation
10    class_attribute :limit_name
11    class_attribute :limit_feature_flag
12    class_attribute :limit_feature_flag_for_override # Allows selectively disabling by actor (as per https://docs.gitlab.com/ee/development/feature_flags/#selectively-disable-by-actor)
13    self.limit_name = self.name.demodulize.tableize
14
15    validate :validate_plan_limit_not_exceeded, on: :create
16  end
17
18  private
19
20  def validate_plan_limit_not_exceeded
21    if GLOBAL_SCOPE == limit_scope
22      validate_global_plan_limit_not_exceeded
23    else
24      validate_scoped_plan_limit_not_exceeded
25    end
26  end
27
28  def validate_scoped_plan_limit_not_exceeded
29    scope_relation = self.public_send(limit_scope) # rubocop:disable GitlabSecurity/PublicSend
30    return unless scope_relation
31    return if limit_feature_flag && ::Feature.disabled?(limit_feature_flag, scope_relation, default_enabled: :yaml)
32    return if limit_feature_flag_for_override && ::Feature.enabled?(limit_feature_flag_for_override, scope_relation, default_enabled: :yaml)
33
34    relation = limit_relation ? self.public_send(limit_relation) : self.class.where(limit_scope => scope_relation) # rubocop:disable GitlabSecurity/PublicSend
35    limits = scope_relation.actual_limits
36
37    check_plan_limit_not_exceeded(limits, relation)
38  end
39
40  def validate_global_plan_limit_not_exceeded
41    relation = self.class.all
42    limits = Plan.default.actual_limits
43
44    check_plan_limit_not_exceeded(limits, relation)
45  end
46
47  def check_plan_limit_not_exceeded(limits, relation)
48    return unless limits.exceeded?(limit_name, relation)
49
50    errors.add(:base, _("Maximum number of %{name} (%{count}) exceeded") %
51        { name: limit_name.humanize(capitalize: false), count: limits.public_send(limit_name) }) # rubocop:disable GitlabSecurity/PublicSend
52  end
53end
54