1
0
Fork 0
mirror of https://github.com/maybe-finance/maybe.git synced 2025-07-19 13:19:39 +02:00

Add account data enrichment (#1532)
Some checks failed
Publish Docker image / ci (push) Has been cancelled
Publish Docker image / Build docker image (push) Has been cancelled

* Add data enrichment

* Make data enrichment optional for self-hosters

* Add categories to data enrichment

* Only update category and merchant if nil

* Fix name overrides

* Lint fixes
This commit is contained in:
Zach Gollwitzer 2024-12-13 17:22:27 -05:00 committed by GitHub
parent bac2e64c19
commit fe199f2357
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 182 additions and 10 deletions

View file

@ -0,0 +1,61 @@
class Account::DataEnricher
include Providable
attr_reader :account
def initialize(account)
@account = account
end
def run
enrich_transactions
end
private
def enrich_transactions
candidates = account.entries.account_transactions.includes(entryable: [ :merchant, :category ])
Rails.logger.info("Enriching #{candidates.count} transactions for account #{account.id}")
merchants = {}
categories = {}
candidates.each do |entry|
if entry.enriched_at.nil? || entry.entryable.merchant_id.nil? || entry.entryable.category_id.nil?
begin
info = self.class.synth_provider.enrich_transaction(entry.name).info
next unless info.present?
if info.name.present?
merchant = merchants[info.name] ||= account.family.merchants.find_or_create_by(name: info.name)
if info.icon_url.present?
merchant.icon_url = info.icon_url
end
end
if info.category.present?
category = categories[info.category] ||= account.family.categories.find_or_create_by(name: info.category)
end
entryable_attributes = { id: entry.entryable_id }
entryable_attributes[:merchant_id] = merchant.id if merchant.present? && entry.entryable.merchant_id.nil?
entryable_attributes[:category_id] = category.id if category.present? && entry.entryable.category_id.nil?
Account.transaction do
merchant.save! if merchant.present?
category.save! if category.present?
entry.update!(
enriched_at: Time.current,
name: entry.enriched_at.nil? ? info.name : entry.name,
entryable_attributes: entryable_attributes
)
end
rescue => e
Rails.logger.warn("Error enriching transaction #{entry.id}: #{e.message}")
end
end
end
end
end