|
| 1 | +class Account::EntrySearch |
| 2 | + include ActiveModel::Model |
| 3 | + include ActiveModel::Attributes |
| 4 | + |
| 5 | + attribute :search, :string |
| 6 | + attribute :amount, :string |
| 7 | + attribute :amount_operator, :string |
| 8 | + attribute :types, :string |
| 9 | + attribute :accounts, :string |
| 10 | + attribute :account_ids, :string |
| 11 | + attribute :start_date, :string |
| 12 | + attribute :end_date, :string |
| 13 | + |
| 14 | + class << self |
| 15 | + def from_entryable_search(entryable_search) |
| 16 | + new(entryable_search.attributes.slice(*attribute_names)) |
| 17 | + end |
| 18 | + end |
| 19 | + |
| 20 | + def build_query(scope) |
| 21 | + query = scope |
| 22 | + |
| 23 | + query = query.where("account_entries.name ILIKE :search OR account_entries.enriched_name ILIKE :search", |
| 24 | + search: "%#{ActiveRecord::Base.sanitize_sql_like(search)}%" |
| 25 | + ) if search.present? |
| 26 | + query = query.where("account_entries.date >= ?", start_date) if start_date.present? |
| 27 | + query = query.where("account_entries.date <= ?", end_date) if end_date.present? |
| 28 | + |
| 29 | + if types.present? |
| 30 | + query = query.where(marked_as_transfer: false) unless types.include?("transfer") |
| 31 | + |
| 32 | + if types.include?("income") && !types.include?("expense") |
| 33 | + query = query.where("account_entries.amount < 0") |
| 34 | + elsif types.include?("expense") && !types.include?("income") |
| 35 | + query = query.where("account_entries.amount >= 0") |
| 36 | + end |
| 37 | + end |
| 38 | + |
| 39 | + if amount.present? && amount_operator.present? |
| 40 | + case amount_operator |
| 41 | + when "equal" |
| 42 | + query = query.where("ABS(ABS(account_entries.amount) - ?) <= 0.01", amount.to_f.abs) |
| 43 | + when "less" |
| 44 | + query = query.where("ABS(account_entries.amount) < ?", amount.to_f.abs) |
| 45 | + when "greater" |
| 46 | + query = query.where("ABS(account_entries.amount) > ?", amount.to_f.abs) |
| 47 | + end |
| 48 | + end |
| 49 | + |
| 50 | + if accounts.present? || account_ids.present? |
| 51 | + query = query.joins(:account) |
| 52 | + end |
| 53 | + |
| 54 | + query = query.where(accounts: { name: accounts }) if accounts.present? |
| 55 | + query = query.where(accounts: { id: account_ids }) if account_ids.present? |
| 56 | + |
| 57 | + query |
| 58 | + end |
| 59 | +end |
0 commit comments