2024-06-24 11:58:39 -04:00
|
|
|
class Account::Transaction < ApplicationRecord
|
2024-07-01 10:49:43 -04:00
|
|
|
include Account::Entryable
|
2024-03-18 11:21:00 -04:00
|
|
|
|
2024-03-07 19:15:50 +01:00
|
|
|
belongs_to :category, optional: true
|
2024-04-29 21:17:28 +02:00
|
|
|
belongs_to :merchant, optional: true
|
2024-05-23 08:09:33 -04:00
|
|
|
has_many :taggings, as: :taggable, dependent: :destroy
|
|
|
|
has_many :tags, through: :taggings
|
|
|
|
|
2024-07-01 10:49:43 -04:00
|
|
|
accepts_nested_attributes_for :taggings, allow_destroy: true
|
2024-03-15 12:21:59 -07:00
|
|
|
|
2024-05-30 20:55:18 -04:00
|
|
|
scope :active, -> { where(excluded: false) }
|
2024-03-11 14:51:16 +02:00
|
|
|
|
2024-05-30 20:55:18 -04:00
|
|
|
class << self
|
2024-07-01 10:49:43 -04:00
|
|
|
def search(params)
|
|
|
|
query = all
|
2024-10-25 15:37:05 +02:00
|
|
|
if params[:categories].present?
|
|
|
|
if params[:categories].exclude?("Uncategorized")
|
|
|
|
query = query
|
|
|
|
.joins(:category)
|
|
|
|
.where(categories: { name: params[:categories] })
|
|
|
|
else
|
|
|
|
query = query
|
|
|
|
.left_joins(:category)
|
|
|
|
.where(categories: { name: params[:categories] })
|
|
|
|
.or(query.where(category_id: nil))
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2024-10-04 09:17:48 -04:00
|
|
|
query = query.joins(:merchant).where(merchants: { name: params[:merchants] }) if params[:merchants].present?
|
|
|
|
|
|
|
|
if params[:tags].present?
|
|
|
|
query = query.joins(:tags)
|
|
|
|
.where(tags: { name: params[:tags] })
|
|
|
|
.distinct
|
|
|
|
end
|
|
|
|
|
2024-07-01 10:49:43 -04:00
|
|
|
query
|
2024-06-19 06:52:08 -04:00
|
|
|
end
|
|
|
|
|
2024-07-01 10:49:43 -04:00
|
|
|
def requires_search?(params)
|
|
|
|
searchable_keys.any? { |key| params.key?(key) }
|
2024-05-30 20:55:18 -04:00
|
|
|
end
|
2024-03-28 13:23:54 -04:00
|
|
|
|
2024-07-01 10:49:43 -04:00
|
|
|
private
|
2024-05-30 20:55:18 -04:00
|
|
|
|
2024-07-01 10:49:43 -04:00
|
|
|
def searchable_keys
|
2024-10-04 09:17:48 -04:00
|
|
|
%i[categories merchants tags]
|
2024-07-01 10:49:43 -04:00
|
|
|
end
|
2024-05-30 20:55:18 -04:00
|
|
|
end
|
2024-03-28 13:23:54 -04:00
|
|
|
|
2024-05-30 20:55:18 -04:00
|
|
|
private
|
|
|
|
def previous_transaction_date
|
|
|
|
self.account
|
|
|
|
.transactions
|
|
|
|
.where("date < ?", date)
|
|
|
|
.order(date: :desc)
|
|
|
|
.first&.date
|
2024-03-28 13:23:54 -04:00
|
|
|
end
|
2024-02-23 21:34:33 -05:00
|
|
|
end
|