2025-02-25 11:34:37 -05:00
|
|
|
class Rule < ApplicationRecord
|
2025-04-02 12:47:07 -04:00
|
|
|
UnsupportedResourceTypeError = Class.new(StandardError)
|
2025-04-02 11:36:38 -04:00
|
|
|
|
2025-02-25 11:34:37 -05:00
|
|
|
belongs_to :family
|
2025-04-01 20:17:57 -04:00
|
|
|
has_many :conditions, dependent: :destroy
|
2025-02-25 11:34:37 -05:00
|
|
|
has_many :actions, dependent: :destroy
|
|
|
|
|
2025-04-02 12:47:07 -04:00
|
|
|
validates :resource_type, presence: true
|
2025-04-01 20:17:57 -04:00
|
|
|
|
|
|
|
def apply
|
2025-04-02 11:36:38 -04:00
|
|
|
scope = resource_scope
|
2025-04-01 20:17:57 -04:00
|
|
|
|
2025-04-02 11:36:38 -04:00
|
|
|
conditions.each do |condition|
|
|
|
|
scope = condition.apply(scope)
|
|
|
|
end
|
2025-04-01 20:17:57 -04:00
|
|
|
|
2025-04-02 11:36:38 -04:00
|
|
|
actions.each do |action|
|
|
|
|
action.apply(scope)
|
|
|
|
end
|
|
|
|
end
|
2025-04-01 20:17:57 -04:00
|
|
|
|
2025-04-02 12:47:07 -04:00
|
|
|
def resource_scope
|
|
|
|
case resource_type
|
|
|
|
when "transaction"
|
|
|
|
family.transactions
|
|
|
|
.active
|
|
|
|
.with_entry
|
|
|
|
.where(account_entries: { date: effective_date..nil })
|
|
|
|
else
|
|
|
|
raise UnsupportedResourceTypeError, "Unsupported resource type: #{resource_type}"
|
2025-04-01 20:17:57 -04:00
|
|
|
end
|
2025-04-02 12:47:07 -04:00
|
|
|
end
|
2025-02-25 11:34:37 -05:00
|
|
|
end
|