The personal finance app for everyone (by everyone)
Ruby
Log DataEnrichment only after a successful save (#4390)
jaysbeekay85eeafbd0f9d
diff --git a/app/models/concerns/enrichable.rb b/app/models/concerns/enrichable.rbindex 8253c092de..00fbe6da61 100644--- a/app/models/concerns/enrichable.rb+++ b/app/models/concerns/enrichable.rb@@ -88,19 +88,33 @@ module Enrichablereturn false if enrichable_attrs.empty?+ # A new record's first save isn't technically an "enrichment", so it is+ # not logged. Captured before saving, which clears new_record?.+ was_new = new_record?+was_modified = false- ActiveRecord::Base.transaction do+ saved = false+ # requires_new: callers such as Account::ProviderImportAdapter already hold+ # a transaction, and without a savepoint the Rollback below would be+ # swallowed by the outer block and undo nothing.+ ActiveRecord::Base.transaction(requires_new: true) doenrichable_attrs.each do |attr, value|self.send("#{attr}=", value)+ end- # If it's a new record, this isn't technically an "enrichment". No logging necessary.- unless self.new_record?+ # A refused save leaves nothing behind: no provenance rows, and no join+ # rows a virtual setter (tag_ids=) wrote before save ran. The block+ # swallows Rollback, so the method returns false and errors stay set.+ raise ActiveRecord::Rollback unless save+ saved = true++ # Provenance is logged only once the save is known to have succeeded.+ unless was_new+ enrichable_attrs.each do |attr, value|log_enrichment(attribute_name: attr, attribute_value: value, source: source, metadata: metadata)endend- save-# For virtual attributes (like tag_ids), previous_changes won't track them# So we need to check if the value actually changed by comparing before/afterif previous_changes.any?@@ -126,6 +140,8 @@ module Enrichableendend+ reset_collection_caches(enrichable_attrs.map(&:first)) unless saved+# Return whether any attributes were actually savedwas_modifiedend@@ -188,6 +204,22 @@ module Enrichableendprivate+ # The rollback removes the join rows a collection setter such as tag_ids=+ # inserted, but not the records it loaded into the association. Resetting+ # makes the next read go to the database, so the instance stops reporting+ # the refused ids as current. Errors and plain attributes are untouched.+ def reset_collection_caches(attr_names)+ attr_names.each do |attr_name|+ reflection = self.class.reflect_on_all_associations.find do |r|+ r.collection? && "#{r.name.to_s.singularize}_ids" == attr_name.to_s+ end+ next unless reflection++ association(reflection.name).reset+ association(reflection.through_reflection.name).reset if reflection.through_reflection?+ end+ end+def log_enrichment(attribute_name:, attribute_value:, source:, metadata: {})de = DataEnrichment.find_or_create_by(enrichable: self,diff --git a/app/models/redbark_account/loan_details_processor.rb b/app/models/redbark_account/loan_details_processor.rbindex 68c884abfa..6ef72c5713 100644--- a/app/models/redbark_account/loan_details_processor.rb+++ b/app/models/redbark_account/loan_details_processor.rb@@ -244,9 +244,10 @@ class RedbarkAccount::LoanDetailsProcessordef write(attrs)return if attrs.blank?- # Enrichable logs the DataEnrichment before it saves, and a refused save- # does not roll that row back. The outer transaction does, so provenance- # never says Redbark supplied a value the loan rejected.+ # Enrichable rolls back its own savepoint when the save is refused, so no+ # DataEnrichment row says Redbark supplied a value the loan rejected.+ # That savepoint is the guarantee. This block can join a caller's+ # transaction, and a Rollback raised in a joined block undoes nothing.ActiveRecord::Base.transaction doloan.enrich_attributes(attrs, source: SOURCE)raise ActiveRecord::Rollback if loan.errors.any?diff --git a/test/models/concerns/enrichable_test.rb b/test/models/concerns/enrichable_test.rbindex 890b79c1b7..cc24c4d105 100644--- a/test/models/concerns/enrichable_test.rb+++ b/test/models/concerns/enrichable_test.rb@@ -76,4 +76,134 @@ class EnrichableTest < ActiveSupport::TestCaserefute_includes Account.enrichable(:name), @enrichableend++ # DataEnrichment rows record who set an attribute, so they are written only+ # after a save the record accepted, and only for records that already+ # existed when the call began.++ test "does not log enrichment when save is refused" do+ @enrichable.stubs(:save).returns(false)++ assert_no_difference "DataEnrichment.count" do+ @enrichable.enrich_attribute(:name, "Refused Save", source: "plaid")+ end+ end++ # No stub: the record's own validation refuses the write, so the savepoint+ # really rolls back and ActiveRecord restores the record's transaction+ # state. Callers such as RedbarkAccount::LoanDetailsProcessor#write read+ # errors afterwards, inside their own transaction, to decide whether to+ # roll back too, so the errors must survive that restore.+ test "a save refused by validation returns false and keeps its errors" do+ stored_name = @enrichable.name++ result = nil+ assert_no_difference "DataEnrichment.count" do+ Account.transaction do+ result = @enrichable.enrich_attribute(:name, "", source: "plaid")+ end+ end++ assert_equal false, result+ assert_includes @enrichable.errors.attribute_names, :name+ assert_equal stored_name, Account.find(@enrichable.id).name+ end++ test "does not log enrichment for a new record that a real save persists" do+ # The record crosses from new to persisted inside enrich_attributes, so+ # the log decision must use the state captured before the save.+ new_record = Account.new(+ family: families(:dylan_family),+ name: "Unsaved Account",+ balance: 0,+ currency: "USD",+ accountable: Depository.new+ )++ assert new_record.new_record?++ assert_no_difference "DataEnrichment.count" do+ assert new_record.enrich_attribute(:name, "Named On Create", source: "plaid")+ end++ assert new_record.persisted?+ assert_equal "Named On Create", Account.find(new_record.id).name+ assert_empty DataEnrichment.where(enrichable: new_record)+ end++ test "a refused save keeps the previously accepted provenance value" do+ # log_enrichment finds or creates the row for (record, attribute, source)+ # and overwrites its value, so a refused write that still logged would+ # replace the accepted value without changing the row count.+ @enrichable.enrich_attribute(:name, "Accepted Name", source: "plaid")+ row = DataEnrichment.find_by!(enrichable: @enrichable, attribute_name: "name", source: "plaid")+ assert_equal "Accepted Name", row.value++ @enrichable.stubs(:save).returns(false)+ @enrichable.enrich_attribute(:name, "Refused Name", source: "plaid")++ assert_equal "Accepted Name", row.reload.value+ assert_equal "Accepted Name", Account.find(@enrichable.id).name+ end++ test "a refused save rolls back association writes made by a virtual setter" do+ # On a persisted record, tag_ids= inserts the join rows before save runs.+ # The call runs inside a caller-held transaction, as the provider import+ # adapter's do, so the rollback must not depend on being the outermost.+ txn = transactions(:one)+ tag = tags(:three)+ tags_before = txn.tag_ids.sort+ refute_includes tags_before, tag.id++ txn.stubs(:save).returns(false)++ result = nil+ assert_no_difference -> { DataEnrichment.where(enrichable: txn).count } do+ Transaction.transaction do+ result = txn.enrich_attribute(:tag_ids, tags_before + [ tag.id ], source: "rule")+ end+ end++ assert_equal false, result+ assert_equal tags_before, Transaction.find(txn.id).tag_ids.sort+ end++ test "a refused virtual setter write leaves the instance reading the stored tags" do+ # The rollback removes the join rows, but tag_ids= also filled the+ # in-memory association. Left alone, the same instance would report the+ # refused tags as current, and a retry would be skipped as unchanged.+ txn = transactions(:one)+ tag = tags(:three)+ tags_before = txn.tag_ids.sort+ taggings_before = txn.taggings.map(&:tag_id).sort+ wanted = tags_before + [ tag.id ]++ txn.stubs(:save).returns(false)+ assert_equal false, txn.enrich_attribute(:tag_ids, wanted, source: "rule")++ assert_equal tags_before, txn.tag_ids.sort+ assert_equal taggings_before, txn.taggings.map(&:tag_id).sort++ txn.unstub(:save)+ assert txn.enrich_attribute(:tag_ids, wanted, source: "rule")+ assert_equal wanted.sort, Transaction.find(txn.id).tag_ids.sort+ end++ test "enriches a virtual attribute (tag_ids) and logs it after save" do+ # transactions(:one) already carries tags one and two; tag three is new.+ txn = transactions(:one)+ tag = tags(:three)++ refute_includes txn.tag_ids, tag.id++ assert_difference "DataEnrichment.count", 1 do+ assert txn.enrich_attribute(:tag_ids, [ tag.id ], source: "rule")+ end++ assert_includes txn.reload.tag_ids, tag.id++ de = DataEnrichment.where(enrichable: txn).order(:created_at).last+ assert_equal "tag_ids", de.attribute_name+ assert_equal "rule", de.source+ endend