Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Recheck Monarch import destinations when the job runs (#4831)

jezmord74500f48d8d
diff --git a/app/controllers/imports_controller.rb b/app/controllers/imports_controller.rb
index d686ccea15..def2d9a836 100644
--- a/app/controllers/imports_controller.rb
+++ b/app/controllers/imports_controller.rb
@@ -37,6 +37,11 @@ class ImportsController < ApplicationController
end
def publish
+ # A failed import can stop being publishable, for example when a Monarch
+ # destination gained trades. The import page then sends it back to the
+ # step that needs a new choice.
+ return redirect_to import_path(@import) if @import.failed? && [email protected]?
+
@import.publish_later
redirect_to import_path(@import), notice: t(".started")
@@ -146,8 +151,8 @@ class ImportsController < ApplicationController
unless @import.requires_csv_workflow?
redirect_to import_upload_path(@import), alert: t("imports.show.finalize_upload")
- elsif @import.is_a?(MonarchImport) && @import.pending? && [email protected]?
- redirect_to import_configuration_path(@import), alert: t("imports.show.finalize_mappings")
+ elsif @import.is_a?(MonarchImport) && (@import.pending? || @import.failed?) && [email protected]?
+ redirect_to import_configuration_path(@import), alert: (@import.failed? && @import.error.presence) || t("imports.show.finalize_mappings")
end
return
end
diff --git a/app/models/monarch_import.rb b/app/models/monarch_import.rb
index 4a4ca92283..334610f3ef 100644
--- a/app/models/monarch_import.rb
+++ b/app/models/monarch_import.rb
@@ -167,10 +167,9 @@ class MonarchImport < Import
# Existing accounts the publisher must be able to write to: the ones it
# imports into, and the ones it has already changed.
def preexisting_target_account_ids
- included = account_mappings.includes(:mappable).select { |mapping| mapping.target && mapping.to_converter_choice.include }
changed = Array(summary["moved_opening_balances"]).map { |moved| moved["account_id"] } +
Array(summary["status_changes"]).map { |change| change["account_id"] }
- (included.map { |mapping| mapping.target.id } + changed.compact).uniq
+ (included_target_mappings.map { |mapping| mapping.target.id } + changed.compact).uniq
end
# Existing accounts whose status follows the Monarch account's: Closed
@@ -235,11 +234,11 @@ class MonarchImport < Import
result = conversion
transaction do
+ check_targets_still_supported!
move_opening_balances!(result.opening_balance_moves)
change_target_statuses!
- included_targets = account_mappings.includes(:mappable).select { |mapping| mapping.target && mapping.to_converter_choice.include }
- targets = included_targets.to_h { |mapping| [ MonarchImport::Converter.source_id(mapping.key), mapping.target ] }
+ targets = included_target_mappings.to_h { |mapping| [ MonarchImport::Converter.source_id(mapping.key), mapping.target ] }
imported = Family::DataImporter.new(family, ndjson(result.records), import: self, account_targets: targets).import!
Account.where(id: imported[:accounts].map(&:id)).update_all(import_id: id)
@@ -249,6 +248,28 @@ class MonarchImport < Import
end
private
+ def included_target_mappings
+ account_mappings.includes(:mappable).select { |mapping| mapping.target && mapping.to_converter_choice.include }
+ end
+
+ # The destinations were checked when the choices were saved, but one may
+ # have gained holdings or trades before the job ran. The lock holds off
+ # status changes; creating a trade doesn't lock the account, so one made
+ # in the same moment can still get past this check.
+ def check_targets_still_supported!
+ ids = included_target_mappings.map { |mapping| mapping.target.id }
+ return if ids.empty?
+
+ Account.where(id: ids).order(:id).lock.pluck(:id)
+ # Not family.accounts: an account moved to another family must fail too.
+ unsupported = Account.where(id: ids)
+ .where.not(id: Import::MonarchAccountMapping.target_accounts_for(self).select(:id))
+ return if unsupported.none?
+
+ raise I18n.t("activerecord.errors.models.monarch_import.target_not_supported",
+ accounts: unsupported.order(:name).pluck(:name).to_sentence)
+ end
+
def ndjson(records)
records.map { |record| record.to_json }.join("\n")
end
diff --git a/config/locales/models/monarch_import/en.yml b/config/locales/models/monarch_import/en.yml
index 696ea0a467..f4e9230aba 100644
--- a/config/locales/models/monarch_import/en.yml
+++ b/config/locales/models/monarch_import/en.yml
@@ -12,6 +12,7 @@ en:
blank_account: "A row has no account name. Check that the file is a Monarch export."
blank_transaction_id: "A transaction has no Id. Check that the file is a Monarch transactions export."
opening_balance_changed: "The opening balance of %{account} changed while importing. Review the import and publish it again."
+ target_not_supported: "Sure can't import into %{accounts} anymore. Destinations must be manual accounts without holdings or trades. Choose other destinations and publish again."
no_accounts: "The exports don't contain any accounts. Check that you exported the right files from Monarch."
files:
balances: balances
diff --git a/test/controllers/import/monarch_import_flow_test.rb b/test/controllers/import/monarch_import_flow_test.rb
index 9ddd96dad0..e0febc6252 100644
--- a/test/controllers/import/monarch_import_flow_test.rb
+++ b/test/controllers/import/monarch_import_flow_test.rb
@@ -123,6 +123,25 @@ class Import::MonarchImportFlowTest < ActionDispatch::IntegrationTest
end
end
+ test "trying again after a destination stopped qualifying goes back to the accounts step" do
+ upload_exports
+ target = accounts(:depository)
+ @import.account_mappings.find_by!(key: "Checking").update!(mappable: target)
+ security = Security.create!(ticker: "MONA", name: "Monarch Test")
+ target.entries.create!(date: Date.new(2024, 1, 4), amount: 10, currency: "USD", name: "Buy",
+ entryable: Trade.new(security: security, qty: 1, price: 10, currency: "USD"))
+ @import.publish
+ assert @import.reload.failed?
+
+ assert_no_enqueued_jobs(only: ImportJob) do
+ post publish_import_url(@import)
+ end
+ assert_redirected_to import_url(@import)
+ follow_redirect!
+ assert_redirected_to import_configuration_url(@import)
+ assert_match target.name, flash[:alert]
+ end
+
private
def csv_upload(name)
fixture_file_upload("imports/#{name}", "text/csv")
diff --git a/test/models/monarch_import_test.rb b/test/models/monarch_import_test.rb
index 95d8e09794..0d4de4cd64 100644
--- a/test/models/monarch_import_test.rb
+++ b/test/models/monarch_import_test.rb
@@ -112,6 +112,39 @@ class MonarchImportTest < ActiveSupport::TestCase
assert_equal 1, opening.reload.amount
end
+ test "a destination that gained a trade after the choices were saved stops the import" do
+ account = @family.accounts.create!(name: "My Brokerage", balance: 500, currency: "USD", accountable: Investment.new)
+ opening = account.entries.create!(date: Date.new(2024, 1, 3), amount: 500, currency: "USD", name: "Opening balance",
+ entryable: Valuation.new(kind: "opening_anchor"))
+ mapping("Old Savings").update!(mappable: account, choices: { "closed" => true })
+ security = Security.create!(ticker: "MONA", name: "Monarch Test")
+ account.entries.create!(date: Date.new(2024, 1, 4), amount: 10, currency: "USD", name: "Buy",
+ entryable: Trade.new(security: security, qty: 1, price: 10, currency: "USD"))
+
+ @import.reload.publish
+ assert @import.reload.failed?
+ assert_match "My Brokerage", @import.error
+ assert_empty @import.entries
+ assert_empty @import.accounts
+ assert_not @import.data_committed?
+ assert account.reload.active?
+ assert_equal [ Date.new(2024, 1, 3), 500 ], [ opening.reload.date, opening.amount ]
+ end
+
+ test "a destination moved to another family stops the import" do
+ account = @family.accounts.create!(name: "My Checking", balance: 500, currency: "USD", accountable: Depository.new)
+ opening = account.entries.create!(date: Date.new(2024, 1, 3), amount: 500, currency: "USD", name: "Opening balance",
+ entryable: Valuation.new(kind: "opening_anchor"))
+ mapping("Checking").update!(mappable: account)
+ account.update_column(:family_id, families(:dylan_family).id)
+
+ @import.reload.publish
+ assert @import.reload.failed?
+ assert_match "My Checking", @import.error
+ assert_empty @import.entries
+ assert_equal [ Date.new(2024, 1, 3), 500 ], [ opening.reload.date, opening.amount ]
+ end
+
test "a lost job that committed is completed, not failed" do
publish!
@import.update_columns(status: "importing", updated_at: 2.hours.ago)