Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add a Monarch importer (#4811)

jezmor4ea82dadae23
diff --git a/app/assets/images/monarch-logo.png b/app/assets/images/monarch-logo.png
new file mode 100644
index 0000000000..a8100000a0
Binary files /dev/null and b/app/assets/images/monarch-logo.png differ
diff --git a/app/controllers/api/v1/imports_controller.rb b/app/controllers/api/v1/imports_controller.rb
index 84ea5c1149..9429802b7e 100644
--- a/app/controllers/api/v1/imports_controller.rb
+++ b/app/controllers/api/v1/imports_controller.rb
@@ -70,6 +70,15 @@ class Api::V1::ImportsController < Api::V1::BaseController
type = "TransactionImport" unless Import::TYPES.include?(type)
return create_sure_import(family) if type == "SureImport"
+ # A Monarch import combines two exports and per-account choices, which
+ # only the web import flow collects.
+ if type == "MonarchImport"
+ return render json: {
+ error: "unsupported_type",
+ message: "Monarch imports need per-account choices that only the web app collects. Use the import flow in the web app."
+ }, status: :unprocessable_entity
+ end
+
# 2. Build the import object with permitted config attributes
@import = family.imports.build(import_config_params.merge(type: type))
@import.account_id = params[:account_id] if params[:account_id].present?
diff --git a/app/controllers/import/configurations_controller.rb b/app/controllers/import/configurations_controller.rb
index 5f764d0e21..d71ae64bca 100644
--- a/app/controllers/import/configurations_controller.rb
+++ b/app/controllers/import/configurations_controller.rb
@@ -10,10 +10,19 @@ class Import::ConfigurationsController < ApplicationController
# PDF imports are auto-configured from AI extraction, skip to clean step
redirect_to import_clean_path(@import) and return if @import.is_a?(PdfImport)
redirect_to import_qif_category_selection_path(@import) and return if @import.is_a?(QifImport)
+ return unless @import.is_a?(MonarchImport)
+
+ redirect_to import_upload_path(@import) and return unless @import.uploaded?
+
+ @target_accounts = monarch_target_accounts
+ render :monarch
end
def update
- if params[:refresh_only]
+ if @import.is_a?(MonarchImport)
+ @import.apply_account_choices!(monarch_choices, target_accounts: monarch_target_accounts)
+ redirect_to import_path(@import), notice: t(".monarch_success")
+ elsif params[:refresh_only]
@import.update!(rows_to_skip: params.dig(:import, :rows_to_skip).to_i)
redirect_to import_configuration_path(@import)
else
@@ -33,6 +42,21 @@ class Import::ConfigurationsController < ApplicationController
@import = Current.family.imports.find(params[:import_id])
end
+ # Existing accounts a Monarch account can go into: the manual ones this
+ # user can write to.
+ def monarch_target_accounts
+ Import::MonarchAccountMapping.target_accounts_for(@import).where(id: Account.writable_by(Current.user).select(:id))
+ end
+
+ MONARCH_CHOICE_FIELDS = %i[name type target_id closed include transactions current_balance].freeze
+
+ def monarch_choices
+ accounts = params[:accounts]
+ return {} unless accounts.is_a?(ActionController::Parameters)
+
+ accounts.permit(accounts.keys.index_with { MONARCH_CHOICE_FIELDS }).to_h.transform_values(&:symbolize_keys)
+ end
+
def import_params
params.fetch(:import, {}).permit(
:date_col_label,
diff --git a/app/controllers/import/uploads_controller.rb b/app/controllers/import/uploads_controller.rb
index f290bf1a9a..ed746ab505 100644
--- a/app/controllers/import/uploads_controller.rb
+++ b/app/controllers/import/uploads_controller.rb
@@ -21,6 +21,8 @@ class Import::UploadsController < ApplicationController
handle_qif_upload
elsif @import.is_a?(SureImport)
update_sure_import_upload
+ elsif @import.is_a?(MonarchImport)
+ update_monarch_import_upload
elsif csv_valid?(csv_str)
@import.account = import_account_id.present? ? accessible_accounts.find(import_account_id) : nil
@import.assign_attributes(raw_file_str: csv_str, col_sep: upload_params[:col_sep])
@@ -66,6 +68,32 @@ class Import::UploadsController < ApplicationController
end
end
+ def update_monarch_import_upload
+ files = params.fetch(:import, {}).permit(:balances_file, :transactions_file)
+ balances, transactions = files[:balances_file], files[:transactions_file]
+
+ error = if balances.blank?
+ t("import.uploads.update.monarch_balances_required")
+ elsif [ balances, transactions ].compact.any? { |file| file.size > Import::MAX_CSV_SIZE }
+ t("imports.create.file_too_large", max_size: Import::MAX_CSV_SIZE / 1.megabyte)
+ elsif [ balances, transactions ].compact.any? { |file| !Import::ALLOWED_CSV_MIME_TYPES.include?(file.content_type) }
+ t("imports.create.invalid_file_type")
+ end
+
+ unless error
+ begin
+ @import.attach_exports!(balances_csv: balances.read, transactions_csv: transactions&.read)
+ redirect_to import_configuration_path(@import), notice: t("import.uploads.update.monarch_uploaded")
+ return
+ rescue MonarchImport::Exports::Error => e
+ error = e.message
+ end
+ end
+
+ flash.now[:alert] = error
+ render :show, status: :unprocessable_entity
+ end
+
def set_import
@import = Current.family.imports.find(params[:import_id])
end
diff --git a/app/controllers/imports_controller.rb b/app/controllers/imports_controller.rb
index eff2849d7a..d686ccea15 100644
--- a/app/controllers/imports_controller.rb
+++ b/app/controllers/imports_controller.rb
@@ -144,7 +144,11 @@ class ImportsController < ApplicationController
def show
unless @import.requires_csv_workflow?
- redirect_to import_upload_path(@import), alert: t("imports.show.finalize_upload") unless @import.uploaded?
+ 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")
+ end
return
end
diff --git a/app/javascript/controllers/checkbox_group_controller.js b/app/javascript/controllers/checkbox_group_controller.js
new file mode 100644
index 0000000000..1692c13b2f
--- /dev/null
+++ b/app/javascript/controllers/checkbox_group_controller.js
@@ -0,0 +1,35 @@
+import { Controller } from "@hotwired/stimulus";
+
+// A master toggle for a column of toggles. Mark each toggle in the column
+// with data-checkbox-group="name" and the master with
+// data-checkbox-group-master="name". Switching the master switches every
+// enabled member to match, and the master stays on only while every member
+// is on.
+export default class extends Controller {
+ connect() {
+ this.sync();
+ }
+
+ toggleAll({ target, params: { group } }) {
+ for (const checkbox of this.members(group)) {
+ checkbox.checked = target.checked;
+ }
+ }
+
+ sync() {
+ for (const master of this.element.querySelectorAll(
+ "[data-checkbox-group-master]",
+ )) {
+ const members = this.members(master.dataset.checkboxGroupMaster);
+ master.checked =
+ members.length > 0 && members.every((checkbox) => checkbox.checked);
+ }
+ }
+
+ members(group) {
+ const selector = `input[type=checkbox][data-checkbox-group="${group}"]`;
+ return [...this.element.querySelectorAll(selector)].filter(
+ (checkbox) => !checkbox.disabled,
+ );
+ }
+}
diff --git a/app/models/balance/sync_cache.rb b/app/models/balance/sync_cache.rb
index 9dfd1cabb9..0819f22b3b 100644
--- a/app/models/balance/sync_cache.rb
+++ b/app/models/balance/sync_cache.rb
@@ -23,6 +23,12 @@ class Balance::SyncCache
@unconvertible_holding_count
end
+ # Every entry the calculation uses: settled, without split parents or
+ # future-dated ones, and converted into the account's currency.
+ def entries
+ converted_entries
+ end
+
def get_valuation(date)
entries_by_date[date]&.find { |e| e.valuation? }
end
diff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rb
index 9ea1648e21..ac9c0c3c61 100644
--- a/app/models/family/data_importer.rb
+++ b/app/models/family/data_importer.rb
@@ -78,7 +78,9 @@ class Family::DataImporter
"Rule" => "rules"
}.freeze
- def initialize(family, ndjson_content, import_session: nil, import: nil)
+ # account_targets maps source account IDs to existing accounts that the
+ # import's records go into instead of accounts it creates.
+ def initialize(family, ndjson_content, import_session: nil, import: nil, account_targets: {})
@family = family
@ndjson_content = ndjson_content
@import_session = import_session
@@ -96,6 +98,7 @@ class Family::DataImporter
securities: {},
rules: {}
}
+ account_targets.each { |source_id, account| @id_mappings[:accounts][source_id] = account.id }
@security_cache = {}
@pending_replacements = {}
@created_accounts = []
@@ -934,6 +937,10 @@ class Family::DataImporter
merchant_id: new_merchant_id,
kind: data["kind"] || "standard"
)
+ # Source-system metadata, such as the ID that lets a later import from
+ # that system recognise the transaction, kept out of external_id so
+ # provider sync can still claim the entry.
+ transaction.extra = transaction.extra.merge(data["extra"]) if data["extra"].is_a?(Hash)
entry ||= Entry.new(entryable: transaction)
entry.assign_attributes(
@@ -949,6 +956,9 @@ class Family::DataImporter
entry.external_id = session_entry_external_id("Transaction", old_id)
entry.source = session_entry_source
end
+ # Records from another system may lock the entry against provider sync
+ # overwrites, as the CSV importer does.
+ entry.import_locked = true if truthy?(data["import_locked"])
entry.save!
diff --git a/app/models/import.rb b/app/models/import.rb
index f93e0a262c..c86af9a330 100644
--- a/app/models/import.rb
+++ b/app/models/import.rb
@@ -39,10 +39,10 @@ class Import < ApplicationRecord
DOCUMENT_TYPES = %w[bank_statement credit_card_statement investment_statement financial_document contract other].freeze
- TYPES = %w[TransactionImport TradeImport AccountImport MintImport ActualImport YnabImport CategoryImport RuleImport MerchantImport PdfImport QifImport SureImport].freeze
+ TYPES = %w[TransactionImport TradeImport AccountImport MintImport ActualImport YnabImport MonarchImport CategoryImport RuleImport MerchantImport PdfImport QifImport SureImport].freeze
# Imports that write family-wide configuration (categories, tags, rules,
# merchants), which guests may view but not change.
- FAMILY_CONFIG_TYPES = %w[CategoryImport MerchantImport RuleImport SureImport].freeze
+ FAMILY_CONFIG_TYPES = %w[CategoryImport MerchantImport RuleImport SureImport MonarchImport].freeze
SIGNAGE_CONVENTIONS = %w[inflows_positive inflows_negative]
SEPARATORS = [ [ "Comma (,)", "," ], [ "Semicolon (;)", ";" ] ].freeze
@@ -252,6 +252,12 @@ class Import < ApplicationRecord
ImportJob.perform_later(self)
end
+ # Whether publishing would change existing records even when the dry run
+ # counts nothing new. Subclasses that do this override it.
+ def changes_existing_records?
+ false
+ end
+
# Whether import! already committed rows for this import. Distinguishes a
# job that died mid-import (single transaction → rolled back, nothing
# attached) from one that died after the data landed but before the status
diff --git a/app/models/import/monarch_account_mapping.rb b/app/models/import/monarch_account_mapping.rb
new file mode 100644
index 0000000000..5d3ad7298c
--- /dev/null
+++ b/app/models/import/monarch_account_mapping.rb
@@ -0,0 +1,113 @@
+# One Monarch account in a MonarchImport, and what to do with it: create a
+# Sure account of the chosen type, import into an existing manual account
+# (mappable), or skip it. value holds the choices as JSON.
+class Import::MonarchAccountMapping < Import::Mapping
+ DEFAULTS = { "name" => nil, "type" => "Depository", "closed" => false, "include" => true, "transactions" => true, "current_balance" => nil }.freeze
+
+ serialize :value, coder: JSON
+
+ validates :key, presence: true
+ validate :choices_are_valid
+ validate :target_is_a_manual_family_account
+ validate :target_takes_one_monarch_account
+
+ # Manual accounts without holdings or trades: the import reproduces
+ # balances from transactions and valuations only, so it can't account for
+ # holdings.
+ def self.target_accounts_for(import)
+ import.family.accounts.listable_manual
+ .where.not(id: Holding.select(:account_id))
+ .where.not(id: Entry.where(entryable_type: "Trade").select(:account_id))
+ .alphabetically
+ end
+
+ def choices
+ DEFAULTS.merge(value.is_a?(Hash) ? value.slice(*DEFAULTS.keys) : {})
+ end
+
+ def choices=(attributes)
+ self.value = choices.merge(attributes.to_h.stringify_keys.slice(*DEFAULTS.keys))
+ end
+
+ %w[type closed include transactions current_balance].each do |name|
+ define_method(name) { choices[name] }
+ end
+
+ def target
+ mappable if mappable_type == "Account"
+ end
+
+ # The name a new account gets in Sure: the one chosen, or Monarch's.
+ def account_name
+ choices["name"].to_s.strip.presence || key
+ end
+
+ def to_converter_choice
+ MonarchImport::Converter::Choice.new(
+ name: key,
+ account_name: account_name,
+ type: target&.accountable_type || type,
+ closed: boolean(closed),
+ include: boolean(include),
+ transactions: boolean(transactions),
+ current_balance: parsed_current_balance,
+ target: target
+ )
+ end
+
+ def selectable_values
+ self.class.target_accounts_for(import).map { |account| [ account.name, account.id ] }
+ end
+
+ def values_count
+ 1
+ end
+
+ def mappable_class
+ Account
+ end
+
+ # Accounts are created by the import itself, not ahead of it.
+ def create_mappable!
+ end
+
+ private
+ def boolean(value)
+ ActiveModel::Type::Boolean.new.cast(value) || false
+ end
+
+ def parsed_current_balance
+ raw = current_balance.to_s.delete(",$").strip
+ return if raw.empty?
+
+ balance = BigDecimal(raw)
+ balance if balance.finite?
+ rescue ArgumentError
+ nil
+ end
+
+ def choices_are_valid
+ errors.add(:value, :inclusion) unless Accountable::TYPES.include?(type)
+ raw = current_balance.to_s.delete(",$").strip
+ errors.add(:value, :not_a_number) if raw.present? && parsed_current_balance.nil?
+ end
+
+ # Each source would reconcile its history against the account
+ # separately, so two of them would compete for its balance.
+ def target_takes_one_monarch_account
+ return if target.nil? || !boolean(include)
+
+ others = import.account_mappings.where(mappable_type: "Account", mappable_id: mappable_id).where.not(id: id)
+ if others.any? { |other| other.to_converter_choice.include }
+ errors.add(:base, :target_taken, account: target.name, monarch: key)
+ end
+ end
+
+ def target_is_a_manual_family_account
+ return if mappable.nil?
+
+ unless mappable.is_a?(Account) && self.class.target_accounts_for(import).exists?(id: mappable.id)
+ errors.add(:mappable, :invalid)
+ end
+ end
+end
diff --git a/app/models/import/preflight.rb b/app/models/import/preflight.rb
index 44be89ac77..0928f5943b 100644
--- a/app/models/import/preflight.rb
+++ b/app/models/import/preflight.rb
@@ -43,7 +43,7 @@ class Import::Preflight
:raw_file_content
] + CONFIG_PARAM_KEYS).freeze
- UNSUPPORTED_PREFLIGHT_IMPORT_TYPES = %w[PdfImport QifImport].freeze
+ UNSUPPORTED_PREFLIGHT_IMPORT_TYPES = %w[PdfImport QifImport MonarchImport].freeze
IMPORT_TYPES = (Import::TYPES - UNSUPPORTED_PREFLIGHT_IMPORT_TYPES).freeze
def initialize(family:, params:)
diff --git a/app/models/monarch_import.rb b/app/models/monarch_import.rb
new file mode 100644
index 0000000000..4a4ca92283
--- /dev/null
+++ b/app/models/monarch_import.rb
@@ -0,0 +1,335 @@
+# Imports Monarch's balance history and transactions exports.
+#
+# The balances export is attached; the optional transactions export is the
+# import's raw_file_str. Each Monarch account gets an
+# Import::MonarchAccountMapping holding the person's choice for it. Publishing
+# converts both exports with MonarchImport::Converter and imports the result
+# through Family::DataImporter, so the accounts and entries belong to this
+# import and reverting it removes them.
+class MonarchImport < Import
+ has_one_attached :balances_file, dependent: :purge_later
+
+ # Deleting a published import removes its entries, so it also has to put
+ # back what publishing changed in accounts it didn't create. That includes
+ # a failed import whose data committed before the failure.
+ before_destroy :restore_existing_accounts!, if: :changed_existing_accounts?
+ after_destroy_commit -> { family.sync_later }, unless: :pending?
+
+ def requires_csv_workflow?
+ false
+ end
+
+ def column_keys
+ []
+ end
+
+ def required_column_keys
+ []
+ end
+
+ def mapping_steps
+ []
+ end
+
+ def csv_template
+ nil
+ end
+
+ def account_mappings
+ mappings.where(type: "Import::MonarchAccountMapping")
+ end
+
+ # Replaces the exports and suggests a choice for every account in them.
+ # Raises MonarchImport::Exports::Error when a file isn't a Monarch export.
+ def attach_exports!(balances_csv:, transactions_csv: nil)
+ exports = MonarchImport::Exports.new(balances_csv: balances_csv, transactions_csv: transactions_csv)
+
+ transaction do
+ balances_file.attach(io: StringIO.new(balances_csv), filename: "balances.csv", content_type: "text/csv")
+ update!(raw_file_str: transactions_csv.presence)
+ account_mappings.destroy_all
+ exports.suggestions.each do |suggestion|
+ account_mappings.create!(
+ key: suggestion.name,
+ create_when_empty: true,
+ choices: { "type" => suggestion.type, "closed" => suggestion.closed }
+ )
+ end
+ end
+ @exports = exports
+ end
+
+ def exports
+ @exports ||= MonarchImport::Exports.new(balances_csv: balances_file.download, transactions_csv: raw_file_str)
+ end
+
+ # Mappings in the order the exports suggest: most recently active first.
+ def ordered_account_mappings
+ order = exports.suggestions.each_with_index.to_h { |suggestion, index| [ suggestion.name, index ] }
+ account_mappings.includes(:mappable).sort_by { |mapping| order.fetch(mapping.key, order.size) }
+ end
+
+ def suggestion_for(name)
+ @suggestions_by_name ||= exports.suggestions.index_by(&:name)
+ @suggestions_by_name[name]
+ end
+
+ # Monarch's latest balance for the account as Sure shows it, with amounts
+ # owed positive: what "Balance today" starts at.
+ def suggested_current_balance(mapping)
+ balance = suggestion_for(mapping.key)&.latest_balance
+ return if balance.nil?
+
+ balance = -balance if MonarchImport::Converter::LIABILITY_TYPES.include?(mapping.target&.accountable_type || mapping.type)
+ ActiveSupport::NumberHelper.number_to_rounded(balance, precision: 2)
+ end
+
+ # Saves the person's choices, keyed by mapping ID. target_id picks one of
+ # target_accounts to import into; a balance equal to the suggested one is
+ # stored as no change.
+ def apply_account_choices!(choices, target_accounts:)
+ transaction do
+ # The balances the form showed, before the destinations they depend on
+ # are cleared.
+ shown_balances = account_mappings.includes(:mappable).to_h { |mapping| [ mapping.id, suggested_current_balance(mapping) ] }
+ # Cleared first, so a destination can move between rows in one save.
+ account_mappings.where(id: choices.keys).update_all(mappable_id: nil, mappable_type: nil)
+ account_mappings.reload.each do |mapping|
+ choice = choices[mapping.id]
+ next if choice.nil?
+
+ balance = choice[:current_balance].to_s.strip
+ balance = nil if balance.empty? || balance == shown_balances[mapping.id]
+ name = choice[:name].to_s.strip
+ mapping.update!(
+ mappable: choice[:target_id].presence && target_accounts.find(choice[:target_id]),
+ choices: {
+ "name" => (name unless name.empty? || name == mapping.key),
+ "type" => choice[:type],
+ "closed" => choice[:closed] == "1",
+ "include" => choice[:include] == "1",
+ "transactions" => choice[:transactions] == "1",
+ "current_balance" => balance
+ }
+ )
+ end
+ end
+ @conversion = nil
+ end
+
+ def uploaded?
+ balances_file.attached?
+ end
+
+ def configured?
+ uploaded? && account_mappings.any? && account_mappings.all?(&:valid?)
+ end
+
+ def cleaned?
+ configured?
+ end
+
+ def publishable?
+ cleaned? && account_mappings.any? { |mapping| mapping.to_converter_choice.include }
+ end
+
+ def publishable_from_validation_stats?(invalid_rows_count:)
+ super && publishable?
+ end
+
+ # Moving an existing account's opening balance or changing its status is
+ # worth publishing even when no new records come with it.
+ def changes_existing_records?
+ configured? && (conversion.opening_balance_moves.any? || target_status_changes.any?)
+ end
+
+ # An import that only changes existing accounts commits no entries or
+ # accounts, but records its changes in the same transaction.
+ def data_committed?
+ super || changed_existing_accounts?
+ end
+
+ # A lost job may have died after its transaction committed. Then the import
+ # is done, as Import.clean decides, and failing it would let a retry import
+ # everything again.
+ def force_fail!(error_message = self.class.lost_error_message)
+ completed = with_lock do
+ next false unless importing? && presumed_lost? && data_committed?
+
+ update!(status: :complete, error: nil)
+ end
+ return super unless completed
+
+ family.sync_later
+ true
+ end
+
+ # 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
+ end
+
+ # Existing accounts whose status follows the Monarch account's: Closed
+ # disables an active account, and Open enables a disabled one.
+ def target_status_changes
+ account_mappings.includes(:mappable).filter_map do |mapping|
+ account = mapping.target
+ choice = mapping.to_converter_choice
+ next unless account && choice.include
+
+ if choice.closed && account.may_disable?
+ [ account, "disabled" ]
+ elsif !choice.closed && account.disabled?
+ [ account, "active" ]
+ end
+ end
+ end
+
+ def conversion
+ @conversion ||= MonarchImport::Converter.new(
+ exports: exports,
+ choices: account_mappings.includes(:mappable).map(&:to_converter_choice),
+ family: family
+ ).result
+ end
+
+ def dry_run
+ return {} unless configured?
+
+ stats = conversion.stats
+ {
+ accounts: stats["Account"],
+ transactions: stats["Transaction"],
+ valuations: stats["Valuation"],
+ categories: stats["Category"] - stats["categories_reusing_existing"],
+ merchants: stats["Merchant"] - stats.fetch("merchants_reusing_existing", 0),
+ tags: stats["Tag"]
+ }
+ end
+
+ # What the person should know before publishing, beyond the counts.
+ def review
+ result = conversion
+ new_names = account_mappings.reject(&:target).select { |mapping| mapping.to_converter_choice.include }.map(&:account_name)
+ {
+ existing_account_names: family.accounts.where(name: new_names).distinct.order(:name).pluck(:name),
+ conflicting_days: result.conflicts.values.sum(&:size),
+ overlapping_transactions: result.overlapping_transactions.values.sum,
+ moved_opening_balances: result.opening_balance_moves.size,
+ already_in_sure: result.stats.fetch("transactions_skipped_already_in_sure", 0),
+ opening_balances_kept: opening_balances_kept_after_revert
+ }
+ end
+
+ # Accounts whose opening balance was edited after the import, so undoing
+ # it left the edit in place.
+ def opening_balances_kept_after_revert
+ Array(summary["opening_balances_kept"])
+ end
+
+ def import!
+ result = conversion
+
+ transaction do
+ 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 ] }
+ 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)
+ Entry.where(id: imported[:entries].map(&:id)).update_all(import_id: id)
+ update!(summary: summary.merge("records" => imported[:summary]))
+ end
+ end
+
+ private
+ def ndjson(records)
+ records.map { |record| record.to_json }.join("\n")
+ end
+
+ def changed_existing_accounts?
+ summary["moved_opening_balances"].present? || summary["status_changes"].present?
+ end
+
+ # Opening balances moved for imported-into accounts, saved with their
+ # values before and after the import so reverting can put them back. The
+ # moved balance is in the account's currency, so the entry takes it too.
+ def move_opening_balances!(moves)
+ moved = moves.map do |move|
+ entry = move.entry
+ before = opening_values(entry)
+ # Locked, and checked against what the conversion read, so an edit
+ # made since then isn't overwritten.
+ entry.lock!
+ raise I18n.t("activerecord.errors.models.monarch_import.opening_balance_changed", account: move.account.name) if opening_values(entry) != before
+
+ entry.update!(date: move.date, amount: move.balance, currency: move.account.currency)
+ { "entry_id" => entry.id, "account_id" => move.account.id, "account" => move.account.name,
+ "before" => before, "after" => opening_values(entry) }
+ end
+ update!(summary: summary.except("opening_balances_kept").merge("moved_opening_balances" => moved))
+ end
+
+ def opening_values(entry)
+ { "date" => entry.date.iso8601, "amount" => entry.amount.to_s, "currency" => entry.currency }
+ end
+
+ # Saved so reverting can undo each change while it is still the latest.
+ def change_target_statuses!
+ changes = target_status_changes.map do |account, status|
+ previous_disabled_at = account.disabled_at
+ status == "disabled" ? account.disable! : account.enable!
+ { "account_id" => account.id, "status" => status, "disabled_at" => account.disabled_at&.iso8601(6),
+ "previous_disabled_at" => previous_disabled_at&.iso8601(6) }
+ end
+ update!(summary: summary.merge("status_changes" => changes))
+ end
+
+ def revert_derived_state!
+ kept = restore_existing_accounts!
+ update!(summary: summary.except("moved_opening_balances", "status_changes", "records").merge("opening_balances_kept" => kept))
+ end
+
+ # Undoes status changes and puts moved opening balances back, unless they
+ # were changed again after the import: then the later change is kept,
+ # since restoring would undo it. Returns the names of accounts whose
+ # opening balance edit was kept.
+ def restore_existing_accounts!
+ restore_target_statuses!
+
+ Array(summary["moved_opening_balances"]).filter_map do |moved|
+ # Locked, so an edit can't land between the comparison and the restore.
+ entry = family.entries.lock.find_by(id: moved["entry_id"])
+ next if entry.nil?
+
+ if opening_values(entry).slice(*moved["after"].keys) == moved["after"]
+ entry.update!(moved["before"])
+ nil
+ else
+ moved["account"]
+ end
+ end
+ end
+
+ # An enable clears disabled_at, so a disabled account that was reopened
+ # and closed again shows a different disabled_at and stays as it is.
+ def restore_target_statuses!
+ Array(summary["status_changes"]).each do |change|
+ account = family.accounts.lock.find_by(id: change["account_id"])
+ next if account.nil? || account.status != change["status"]
+
+ if change["status"] == "disabled"
+ account.enable! if account.disabled_at&.iso8601(6) == change["disabled_at"]
+ else
+ account.disable!
+ account.update!(disabled_at: change["previous_disabled_at"]) if change["previous_disabled_at"]
+ end
+ end
+ end
+end
diff --git a/app/models/monarch_import/balance_history.rb b/app/models/monarch_import/balance_history.rb
new file mode 100644
index 0000000000..d66247c875
--- /dev/null
+++ b/app/models/monarch_import/balance_history.rb
@@ -0,0 +1,125 @@
+# Works out the balance valuations Sure needs to reproduce an account's
+# Monarch balance history.
+#
+# Sure's forward calculator carries a balance from day to day by applying
+# transactions, and a valuation sets the balance outright on its date. So a
+# valuation is only needed where Monarch's balance differs from what the
+# transactions already give. Everything here uses Monarch's signs: balances
+# are negative for amounts owed, and flows are net transaction amounts with
+# inflows positive.
+#
+# An account that already exists in Sure brings its own entries. Its
+# valuations are fixed: where one disagrees with Monarch on the same day,
+# Sure's value is kept and the day is reported as a conflict. Its transactions
+# count toward the balance like imported ones.
+class MonarchImport::BalanceHistory
+ attr_reader :conflicts
+
+ def initialize(history:, flows: {}, closed: false, existing_valuations: {}, existing_flows: {})
+ @history = history
+ @flows = flows
+ @closed = closed
+ @existing_valuations = existing_valuations
+ @existing_flows = existing_flows
+ @conflicts = []
+ end
+
+ # [[date, balance]] in date order. The first is the opening balance.
+ def anchors
+ @anchors ||= compute_anchors
+ end
+
+ # The anchors, adjusted so the balance on as_of equals balance. Nothing is
+ # added when the history already ends at that balance.
+ def anchors_with_current_balance(as_of, balance)
+ return anchors if replay(through: as_of)[as_of] == balance
+
+ if @existing_valuations.key?(as_of)
+ @conflicts << as_of unless @existing_valuations[as_of] == balance || @conflicts.include?(as_of)
+ return anchors
+ end
+
+ (anchors.reject { |date, _| date == as_of } + [ [ as_of, balance ] ]).sort_by(&:first)
+ end
+
+ # { date => balance } the way Sure's forward calculator derives it, on every
+ # date with an entry and on through. Between those dates the balance holds.
+ def replay(anchors = self.anchors, through: nil)
+ valuations = @existing_valuations.merge(anchors.to_h)
+ flows = combined_flows
+ dates = valuations.keys | flows.keys
+ return {} if dates.empty?
+
+ dates |= [ through ] if through && through >= dates.min
+ running = BigDecimal("0")
+ dates.sort.each_with_object({}) do |date, balances|
+ running = valuations.fetch(date) { running + flows.fetch(date, 0) }
+ balances[date] = running
+ end
+ end
+
+ private
+ def combined_flows
+ @combined_flows ||= @flows.merge(@existing_flows) { |_, imported, existing| imported + existing }
+ end
+
+ def compute_anchors
+ flows = combined_flows
+ return [] if @history.empty? && @flows.empty?
+
+ anchors = []
+ running = nil
+
+ first_balance_date = @history.keys.min
+ # Existing transactions count too: an opening placed after one of them
+ # would override it.
+ first_flow_date = flows.keys.min
+
+ if first_flow_date && (first_balance_date.nil? || first_flow_date < first_balance_date) &&
+ no_existing_valuation_through?(first_balance_date)
+ # Transactions predate the balance history: work backwards from the
+ # first known balance so the earlier transactions land on the right
+ # total.
+ opening = if first_balance_date
+ @history[first_balance_date] - flows.sum { |date, amount| date <= first_balance_date ? amount : 0 }
+ else
+ BigDecimal("0")
+ end
+ anchors << [ first_flow_date - 1, opening ]
+ running = opening
+ end
+
+ (@history.keys | flows.keys | @existing_valuations.keys).sort.each do |date|
+ if @existing_valuations.key?(date)
+ running = @existing_valuations[date]
+ @conflicts << date if @history.key?(date) && @history[date] != running
+ next
+ end
+
+ expected = running && running + flows.fetch(date, 0)
+ actual = @history[date]
+ if actual && actual != expected
+ anchors << [ date, actual ]
+ running = actual
+ else
+ running = expected
+ end
+ end
+
+ if @closed && @history.any?
+ last_date = @history.keys.max
+ closing_date = last_date + 1
+ if @existing_valuations.key?(closing_date)
+ @conflicts << closing_date if @existing_valuations[closing_date].nonzero?
+ elsif @history[last_date].nonzero? && flows.keys.none? { |date| date > last_date }
+ anchors << [ closing_date, BigDecimal("0") ]
+ end
+ end
+
+ anchors
+ end
+
+ def no_existing_valuation_through?(date)
+ date.nil? || @existing_valuations.keys.none? { |existing| existing <= date }
+ end
+end
diff --git a/app/models/monarch_import/converter.rb b/app/models/monarch_import/converter.rb
new file mode 100644
index 0000000000..f3870151c4
--- /dev/null
+++ b/app/models/monarch_import/converter.rb
@@ -0,0 +1,339 @@
+# Converts Monarch's exports into the records Family::DataImporter imports,
+# following the person's choice for each account.
+#
+# A new account gets the Monarch history as an opening balance plus balance
+# valuations wherever its transactions don't explain Monarch's balance. An
+# existing Sure account gets the same, computed on top of the entries it
+# already has, and its opening balance moves to the start of the Monarch
+# history when it falls inside it.
+#
+# Existing categories and merchants with the same names are reused with their
+# current look: the records carry it, because DataImporter rewrites both from
+# the record.
+class MonarchImport::Converter
+ TRANSFER_CATEGORY_KINDS = {
+ "Transfer" => "funds_movement",
+ "Credit Card Payment" => "cc_payment"
+ }.freeze
+ RECORD_ORDER = %w[Account Category Tag Merchant Transaction Valuation].freeze
+ # Imported transactions keep their Monarch ID in extra under this key, so a
+ # later import into the same account can recognise them. It stays out of
+ # external_id: provider sync only claims entries without one, so a bank
+ # connection linked later matches these entries instead of duplicating them.
+ EXTRA_KEY = "monarch".freeze
+ # How the Monarch to Sure API tool's import sessions identify transactions.
+ SESSION_SOURCE_PREFIX = "sure_import_session:".freeze
+ SESSION_EXTERNAL_ID_PREFIX = "Transaction:monarch-transaction:".freeze
+ LIABILITY_TYPES = %w[CreditCard Loan OtherLiability].freeze
+ # Sure's balance calculator ignores transactions in these accounts (see
+ # Balance::BaseCalculator), so only valuations set their balance.
+ VALUATION_ONLY_TYPES = %w[Property Vehicle OtherAsset OtherLiability].freeze
+
+ # What the person picked for one Monarch account. name is Monarch's, and
+ # account_name what a new Sure account is called. target is an existing
+ # manual Account to import into, or nil to create one. current_balance is
+ # today's balance as Sure shows it, with amounts owed positive.
+ Choice = Data.define(:name, :type, :closed, :include, :transactions, :current_balance, :target, :account_name) do
+ def initialize(account_name: nil, **attributes)
+ super(account_name: account_name || attributes[:name], **attributes)
+ end
+
+ def liability?
+ LIABILITY_TYPES.include?(type)
+ end
+
+ def transactions_move_balance?
+ !VALUATION_ONLY_TYPES.include?(type)
+ end
+ end
+
+ # An existing account's opening balance, moved to the start of the history.
+ OpeningBalanceMove = Data.define(:account, :entry, :date, :balance)
+
+ Result = Data.define(:records, :stats, :opening_balance_moves, :conflicts, :overlapping_transactions)
+
+ def self.source_id(name)
+ "monarch-account:#{name}"
+ end
+
+ def initialize(exports:, choices:, family:, include_pending: false, today: nil)
+ @exports = exports
+ @choices = choices.index_by(&:name)
+ @family = family
+ @include_pending = include_pending
+ @today = today || default_today
+ end
+
+ def result
+ @result ||= convert
+ end
+
+ private
+ attr_reader :exports, :family, :today
+
+ def convert
+ unknown = exports.account_names - @choices.keys
+ raise ArgumentError, "No choice for #{unknown.join(', ')}" if unknown.any?
+
+ @records = RECORD_ORDER.index_with { [] }
+ @stats = Hash.new(0)
+ @categories = {}
+ @tags = {}
+ @merchants = {}
+ @opening_balance_moves = []
+ @conflicts = {}
+ @overlapping_transactions = {}
+
+ flows = convert_transactions
+ exports.account_names.each { |name| convert_account(@choices[name], flows.fetch(name, {})) }
+ convert_categories_tags_and_merchants
+
+ RECORD_ORDER.each { |type| @stats[type] = @records[type].size }
+ Result.new(
+ records: RECORD_ORDER.flat_map { |type| @records[type] },
+ stats: @stats.to_h,
+ opening_balance_moves: @opening_balance_moves,
+ conflicts: @conflicts,
+ overlapping_transactions: @overlapping_transactions
+ )
+ end
+
+ # Adds the transaction records and returns each account's daily flows.
+ def convert_transactions
+ flows = Hash.new { |hash, name| hash[name] = Hash.new(BigDecimal("0")) }
+
+ exports.transactions_for(include_pending: @include_pending).each do |row|
+ choice = @choices[row[:account]]
+ skipped = if !choice.include then "excluded_account"
+ elsif !choice.transactions then "balances_only"
+ elsif row[:amount].nil? then "no_amount"
+ end
+ next @stats["transactions_skipped_#{skipped}"] += 1 if skipped
+ next @stats["transactions_skipped_already_in_sure"] += 1 if already_in_sure?(choice.target, row)
+
+ flows[row[:account]][row[:date]] += row[:amount] if choice.transactions_move_balance?
+
+ kind = TRANSFER_CATEGORY_KINDS.fetch(row[:category], "standard")
+ data = {
+ "id" => "monarch-transaction:#{row[:id]}",
+ "account_id" => self.class.source_id(row[:account]),
+ "date" => row[:date].iso8601,
+ # Sure records outflows as positive amounts; Monarch as negative.
+ "amount" => money(-row[:amount]),
+ "name" => row[:merchant].presence || row[:original_statement].presence || "Imported transaction",
+ "notes" => row[:notes].presence,
+ "kind" => kind,
+ "extra" => { EXTRA_KEY => { "transaction_id" => row[:id] } },
+ # Like the CSV importer: a provider that later claims the entry links
+ # to it without overwriting what was imported.
+ "import_locked" => true
+ }
+ if row[:category].present? && kind == "standard"
+ data["category_id"] = @categories[row[:category]] ||= "monarch-category:#{row[:category]}"
+ end
+ if row[:merchant].present?
+ data["merchant_id"] = @merchants[row[:merchant]] ||= "monarch-merchant:#{row[:merchant]}"
+ end
+ tag_ids = row[:tags].map { |tag| @tags[tag] ||= "monarch-tag:#{tag}" }
+ data["tag_ids"] = tag_ids if tag_ids.any?
+
+ @records["Transaction"] << record("Transaction", data)
+ end
+
+ flows
+ end
+
+ # Whether an existing account already holds this Monarch transaction:
+ # first by its Monarch ID from an earlier import (natively or through the
+ # API tool), then by Sure's own duplicate matcher (same date, amount and
+ # currency). Entries with a Monarch ID only match by it, and each other
+ # entry matches at most one row, so two genuine identical purchases stay
+ # two. A skipped row is already in the account's balance, so it adds no
+ # flow.
+ def already_in_sure?(account, row)
+ return false if account.nil?
+
+ return true if imported_monarch_ids(account).key?(row[:id])
+
+ duplicate = Account::ProviderImportAdapter.new(account).find_duplicate_transaction(
+ date: row[:date], amount: -row[:amount], currency: account.currency,
+ exclude_entry_ids: claimed_entry_ids(account)
+ )
+ claimed_entry_ids(account) << duplicate.id if duplicate
+ duplicate.present?
+ end
+
+ def claimed_entry_ids(account)
+ @claimed_entry_ids ||= {}
+ @claimed_entry_ids[account.id] ||= imported_monarch_ids(account).values
+ end
+
+ # { Monarch transaction ID => entry ID } for the account's entries.
+ def imported_monarch_ids(account)
+ @imported_monarch_ids ||= {}
+ @imported_monarch_ids[account.id] ||= load_imported_monarch_ids(account)
+ end
+
+ def load_imported_monarch_ids(account)
+ native = Transaction.joins(:entry).where(entries: { account_id: account.id })
+ .where("transactions.extra -> ? ->> 'transaction_id' IS NOT NULL", EXTRA_KEY)
+ .pluck(Arel.sql(ActiveRecord::Base.sanitize_sql([ "transactions.extra -> ? ->> 'transaction_id'", EXTRA_KEY ])), "entries.id")
+ tool = session_entries(account.entries).pluck(:external_id, :id).map { |external_id, id| [ external_id.delete_prefix(SESSION_EXTERNAL_ID_PREFIX), id ] }
+ (native + tool).to_h
+ end
+
+ # Entries the API tool imported. Both the source and the ID prefix must
+ # match, since any API client can choose an external ID.
+ def session_entries(scope)
+ scope.where("entries.source LIKE ?", "#{ActiveRecord::Base.sanitize_sql_like(SESSION_SOURCE_PREFIX)}%")
+ .where("entries.external_id LIKE ?", "#{ActiveRecord::Base.sanitize_sql_like(SESSION_EXTERNAL_ID_PREFIX)}%")
+ end
+
+ def monarch_id_of(entry)
+ if entry.source.to_s.start_with?(SESSION_SOURCE_PREFIX) && entry.external_id.to_s.start_with?(SESSION_EXTERNAL_ID_PREFIX)
+ entry.external_id.delete_prefix(SESSION_EXTERNAL_ID_PREFIX)
+ else
+ entry.entryable.try(:extra).to_h.dig(EXTRA_KEY, "transaction_id")
+ end
+ end
+
+ def convert_account(choice, flows)
+ return unless choice.include
+
+ sign = choice.liability? ? -1 : 1 # Sure stores amounts owed as positive
+ history = exports.balances.fetch(choice.name, {})
+ current_balance = choice.current_balance && choice.current_balance * sign
+
+ if choice.target
+ convert_into_existing(choice, history, flows, sign, current_balance)
+ else
+ balance_history = MonarchImport::BalanceHistory.new(history: history, flows: flows, closed: choice.closed)
+ anchors = anchors_for(balance_history, choice, current_balance)
+ # Later valuations are imported, but the balance is today's.
+ balance = balance_history.replay(anchors, through: today).select { |date, _| date <= today }.values.last
+ @records["Account"] << record("Account", {
+ "id" => self.class.source_id(choice.name),
+ "name" => choice.account_name,
+ "accountable_type" => choice.type,
+ "accountable" => {},
+ "subtype" => nil,
+ "balance" => money((balance || 0) * sign),
+ "status" => choice.closed ? "disabled" : "active",
+ # The opening balance and history come from the valuations.
+ "skip_opening_balance_import" => true
+ })
+ add_valuations(choice, anchors, sign, first_kind: "opening_anchor")
+ end
+ end
+
+ def convert_into_existing(choice, history, flows, sign, current_balance)
+ account = choice.target
+ entries = account.entries.excluding_pending.excluding_split_parents.includes(:entryable).to_a
+ opening = entries.find { |entry| entry.valuation? && entry.entryable.opening_anchor? }
+ others = entries.reject(&:valuation?)
+
+ # Balances come from the entries Sure's calculator uses, in the
+ # account's currency.
+ calculated_valuations, calculated_others = Balance::SyncCache.new(account).entries.partition(&:valuation?)
+ # The calculator takes a day's first valuation.
+ existing_valuations = calculated_valuations.each_with_object({}) { |entry, values| values[entry.date] ||= entry.amount * sign }
+ existing_flows = Hash.new(BigDecimal("0"))
+ if choice.transactions_move_balance?
+ calculated_others.each { |entry| existing_flows[entry.date] -= entry.amount }
+ end
+
+ monarch_dates = history.keys + flows.keys
+ start_date, end_date = monarch_dates.minmax
+ if start_date
+ claimed = claimed_entry_ids(account)
+ @overlapping_transactions[choice.name] = others.count do |entry|
+ entry.date.between?(start_date, end_date) && !claimed.include?(entry.id) && monarch_id_of(entry).nil?
+ end
+ end
+
+ # The opening balance can move to the start of the history when it falls
+ # inside it and nothing else in the account comes earlier.
+ if opening && start_date && opening.date >= start_date
+ movable_valuations = existing_valuations.except(opening.date)
+ balance_history = MonarchImport::BalanceHistory.new(history: history, flows: flows, closed: choice.closed,
+ existing_valuations: movable_valuations, existing_flows: existing_flows)
+ anchors = anchors_for(balance_history, choice, current_balance)
+ opening_date, opening_balance = anchors.first
+ if opening_date && (entries - [ opening ]).none? { |entry| entry.date <= opening_date }
+ @opening_balance_moves << OpeningBalanceMove.new(account: account, entry: opening, date: opening_date, balance: opening_balance * sign)
+ @conflicts[choice.name] = balance_history.conflicts if balance_history.conflicts.any?
+ return add_valuations(choice, anchors.drop(1), sign, first_kind: "reconciliation")
+ end
+ end
+
+ balance_history = MonarchImport::BalanceHistory.new(history: history, flows: flows, closed: choice.closed,
+ existing_valuations: existing_valuations, existing_flows: existing_flows)
+ anchors = anchors_for(balance_history, choice, current_balance)
+ @conflicts[choice.name] = balance_history.conflicts if balance_history.conflicts.any?
+ add_valuations(choice, anchors, sign, first_kind: "reconciliation")
+ end
+
+ # The family's date, but never later than the server's: Sure leaves entries
+ # dated after Date.current out of the balance until that day arrives.
+ def default_today
+ [ Time.current.in_time_zone(family.resolved_time_zone).to_date, Date.current ].min
+ end
+
+ def anchors_for(balance_history, choice, current_balance)
+ return balance_history.anchors if current_balance.nil? || choice.closed
+
+ balance_history.anchors_with_current_balance(today, current_balance)
+ end
+
+ def add_valuations(choice, anchors, sign, first_kind:)
+ anchors.each_with_index do |(date, balance), index|
+ opening = index.zero? && first_kind == "opening_anchor"
+ @records["Valuation"] << record("Valuation", {
+ "id" => "monarch-valuation:#{choice.name}:#{date.iso8601}",
+ "account_id" => self.class.source_id(choice.name),
+ "date" => date.iso8601,
+ "amount" => money(balance * sign),
+ "kind" => opening ? "opening_anchor" : "reconciliation",
+ "name" => opening ? "Opening balance" : "Balance from Monarch"
+ })
+ end
+ end
+
+ def convert_categories_tags_and_merchants
+ existing_categories = family.categories.where(name: @categories.keys).index_by(&:name)
+ @stats["categories_reusing_existing"] = 0
+ @categories.sort.each do |name, id|
+ data = { "id" => id, "name" => name }
+ if (category = existing_categories[name])
+ data.merge!("color" => category.color, "lucide_icon" => category.lucide_icon,
+ "classification_unused" => category.classification_unused)
+ @stats["categories_reusing_existing"] += 1
+ end
+ @records["Category"] << record("Category", data)
+ end
+
+ @tags.sort.each { |name, id| @records["Tag"] << record("Tag", { "id" => id, "name" => name }) }
+
+ existing_merchants = family.merchants.where(name: @merchants.keys).index_by(&:name)
+ @merchants.sort.each do |name, id|
+ data = { "id" => id, "name" => name }
+ if (merchant = existing_merchants[name])
+ data.merge!("color" => merchant.color, "logo_url" => merchant.logo_url)
+ @stats["merchants_reusing_existing"] += 1
+ end
+ @records["Merchant"] << record("Merchant", data)
+ end
+ end
+
+ def record(type, data)
+ { "type" => type, "data" => data }
+ end
+
+ # Two decimals, rounding half to even like the Monarch to Sure tool, and
+ # never "-0.00".
+ def money(value)
+ rounded = value.to_d.round(2, BigDecimal::ROUND_HALF_EVEN)
+ whole, fraction = rounded.abs.to_s("F").split(".")
+ "#{'-' if rounded.negative?}#{whole}.#{fraction.to_s.ljust(2, '0')}"
+ end
+end
diff --git a/app/models/monarch_import/exports.rb b/app/models/monarch_import/exports.rb
new file mode 100644
index 0000000000..216b187459
--- /dev/null
+++ b/app/models/monarch_import/exports.rb
@@ -0,0 +1,154 @@
+# Monarch's two CSV exports, parsed: daily balances per account, and
+# transactions. Also suggests a Sure type and closure for each account, which
+# the person confirms before importing.
+class MonarchImport::Exports
+ BALANCE_COLUMNS = %w[Date Balance Account].freeze
+ TRANSACTION_COLUMNS = %w[Date Merchant Category Account Amount Id].freeze
+ STALE_AFTER_DAYS = 180
+
+ Error = Class.new(StandardError)
+
+ # Suggested settings for one Monarch account.
+ Suggestion = Data.define(:name, :type, :closed, :last_activity, :latest_balance, :transactions_count, :balance_days, :first_date, :last_date)
+
+ attr_reader :balances, :transactions
+
+ # balances: { account name => { date => balance } }, skipping blank balances.
+ # transactions: the transaction rows, pending ones included.
+ def initialize(balances_csv:, transactions_csv: nil)
+ @balances = parse_balances(balances_csv)
+ @transactions = transactions_csv.present? ? parse_transactions(transactions_csv) : []
+ raise Error, I18n.t("activerecord.errors.models.monarch_import.no_accounts") if account_names.empty?
+ end
+
+ def balances_only?
+ transactions.empty?
+ end
+
+ def account_names
+ (balances.keys | transactions.map { |row| row[:account] }).sort
+ end
+
+ def end_date
+ @end_date ||= (balances.values.flat_map(&:keys) + transactions.map { |row| row[:date] }).max
+ end
+
+ def transactions_for(include_pending:)
+ include_pending ? transactions : transactions.reject { |row| row[:pending] }
+ end
+
+ # Suggestions for every account, most recently active first.
+ def suggestions
+ @suggestions ||= begin
+ dates_by_account = transactions.group_by { |row| row[:account] }.transform_values { |rows| rows.map { |row| row[:date] } }
+
+ account_names.map do |name|
+ suggest(name, balances.fetch(name, {}), dates_by_account.fetch(name, []))
+ end.sort_by.with_index { |suggestion, index| [ -(suggestion.last_activity&.jd || 0), index ] }
+ end
+ end
+
+ private
+ def parse_balances(csv)
+ rows = parse_csv(csv, BALANCE_COLUMNS, :balances)
+ rows.each_with_object(Hash.new { |hash, key| hash[key] = {} }) do |row, balances|
+ amount = parse_amount(row["Balance"])
+ next if amount.nil?
+
+ balances[parse_account(row["Account"])][parse_date(row["Date"])] = amount
+ end.to_h { |name, history| [ name, history.sort.to_h ] }
+ end
+
+ def parse_transactions(csv)
+ parse_csv(csv, TRANSACTION_COLUMNS, :transactions).map do |row|
+ {
+ id: row["Id"].to_s.strip.presence || raise(Error, I18n.t("activerecord.errors.models.monarch_import.blank_transaction_id")),
+ date: parse_date(row["Date"]),
+ account: parse_account(row["Account"]),
+ amount: parse_amount(row["Amount"]),
+ merchant: row["Merchant"].to_s.strip,
+ original_statement: row["Original Statement"].to_s.strip,
+ category: row["Category"].to_s.strip,
+ notes: row["Notes"].to_s.strip,
+ tags: row["Tags"].to_s.split(",").map(&:strip).reject(&:blank?),
+ pending: row["Pending"].to_s.strip.casecmp?("true")
+ }
+ end
+ end
+
+ def parse_csv(csv, required, file)
+ label = I18n.t("activerecord.errors.models.monarch_import.files.#{file}")
+ text = csv.to_s.dup.force_encoding(Encoding::UTF_8).scrub.delete_prefix("\uFEFF")
+ table = CSV.parse(text, headers: true)
+ missing = required - table.headers.compact
+ raise Error, I18n.t("activerecord.errors.models.monarch_import.missing_columns", file: label, columns: missing.join(", ")) if missing.any?
+
+ table
+ rescue CSV::MalformedCSVError => e
+ raise Error, I18n.t("activerecord.errors.models.monarch_import.malformed_csv", file: label, error: e.message)
+ end
+
+ def parse_amount(value)
+ raw = value.to_s.delete(",$").strip
+ return if raw.empty?
+
+ amount = BigDecimal(raw)
+ raise ArgumentError unless amount.finite?
+
+ amount
+ rescue ArgumentError
+ raise Error, I18n.t("activerecord.errors.models.monarch_import.invalid_number", value: value)
+ end
+
+ # Limited to the dates other imports accept, which also bounds how many
+ # days a balance history can span.
+ def parse_date(value)
+ date = Date.iso8601(value.to_s)
+ range = Import.reasonable_date_range
+ unless range.cover?(date)
+ raise Error, I18n.t("activerecord.errors.models.monarch_import.date_out_of_range", value: value, from: range.begin.iso8601, to: range.end.iso8601)
+ end
+
+ date
+ rescue Date::Error
+ raise Error, I18n.t("activerecord.errors.models.monarch_import.invalid_date", value: value)
+ end
+
+ def parse_account(value)
+ value.to_s.strip.presence || raise(Error, I18n.t("activerecord.errors.models.monarch_import.blank_account"))
+ end
+
+ def suggest(name, history, transaction_dates)
+ nonzero = history.values.reject(&:zero?)
+ mostly_negative = nonzero.any? && nonzero.count(&:negative?) > nonzero.size / 2.0
+ type = if mostly_negative
+ transaction_dates.any? ? "CreditCard" : "Loan"
+ elsif transaction_dates.any?
+ "Depository"
+ else
+ "Investment"
+ end
+
+ last_activity = last_activity(history, transaction_dates)
+ Suggestion.new(
+ name: name,
+ type: type,
+ closed: last_activity.present? && (end_date - last_activity).to_i >= STALE_AFTER_DAYS,
+ last_activity: last_activity,
+ latest_balance: history.values.last,
+ transactions_count: transaction_dates.size,
+ balance_days: history.size,
+ first_date: history.keys.first,
+ last_date: history.keys.last
+ )
+ end
+
+ # The last day the account's money moved: its latest transaction, or the
+ # latest day its balance changed. Monarch keeps reporting a balance long
+ # after an account stops changing, so the last balance date says little.
+ def last_activity(history, transaction_dates)
+ dates = history.keys
+ last_change = dates.each_cons(2).select { |before, after| history[after] != history[before] }.map(&:last).last
+ [ last_change, dates.first, *transaction_dates ].compact.max
+ end
+end
diff --git a/app/views/import/configurations/monarch.html.erb b/app/views/import/configurations/monarch.html.erb
new file mode 100644
index 0000000000..5a6e40299c
--- /dev/null
+++ b/app/views/import/configurations/monarch.html.erb
@@ -0,0 +1,117 @@
+<%= content_for :header_nav do %>
+ <%= render "imports/nav", import: @import %>
+<% end %>
+
+<%= content_for :previous_path, import_upload_path(@import) %>
+
+<% type_options = Accountable::TYPES.map { |type| [ type.constantize.singular_display_name, type ] } %>
+<% target_options = [ [ t(".new_account"), "" ] ] + @target_accounts.map { |account| [ account.name, account.id ] } %>
+<% master_toggle = lambda do |group, label|
+ safe_join([
+ tag.span(label),
+ render(DS::Toggle.new(id: "monarch_all_#{group}", name: "all[#{group}]", checked: true,
+ aria: { label: t(".toggle_all_label", column: label) },
+ data: { checkbox_group_master: group, action: "checkbox-group#toggleAll", checkbox_group_group_param: group }))
+ ], " ")
+ end %>
+
+<div class="space-y-6">
+ <div class="text-center space-y-2 mx-auto max-w-2xl">
+ <h1 class="text-3xl text-primary font-medium"><%= t(".title") %></h1>
+ <p class="text-secondary text-sm"><%= t(".description") %></p>
+ </div>
+
+ <div class="mx-auto max-w-2xl">
+ <%= render DS::Alert.new(variant: :info, title: t(".help_title")) do %>
+ <ul class="list-disc pl-4 space-y-1 text-sm">
+ <li><%= t(".help_account") %></li>
+ <li><%= t(".help_closed", days: MonarchImport::Exports::STALE_AFTER_DAYS) %></li>
+ <li><%= t(".help_transactions") %></li>
+ <li><%= t(".help_balance") %></li>
+ </ul>
+ <% end %>
+ </div>
+
+ <%= styled_form_with url: import_configuration_path(@import), method: :patch, class: "space-y-4",
+ data: { turbo: false, controller: "checkbox-group", action: "change->checkbox-group#sync" } do |form| %>
+ <%= render DS::Table.new(rows: @import.ordered_account_mappings, label: t(".table_label")) do |table| %>
+ <% table.with_column(tag.span(master_toggle.call("include", t(".import_column")), class: "inline-flex items-center gap-2")) do |mapping| %>
+ <%= render DS::Toggle.new(id: dom_id(mapping, :include), name: "accounts[#{mapping.id}][include]",
+ checked: mapping.include, aria: { label: t(".import_label", name: mapping.key) }, data: { checkbox_group: "include" }) %>
+ <% end %>
+
+ <% table.with_column(t(".account_column"), row_header: true) do |mapping| %>
+ <% suggestion = @import.suggestion_for(mapping.key) %>
+ <div class="min-w-56 max-w-80 space-y-1">
+ <div class="form-field">
+ <%= form.text_field "accounts[#{mapping.id}][name]", value: mapping.account_name, label: false,
+ placeholder: mapping.key, id: dom_id(mapping, :name), aria: { label: t(".name_label", name: mapping.key) } %>
+ </div>
+ <% if mapping.account_name != mapping.key %>
+ <p class="text-xs text-secondary break-words"><%= t(".monarch_name", name: mapping.key) %></p>
+ <% end %>
+ <p class="text-xs text-secondary">
+ <%= suggestion&.last_activity ? t(".last_activity", date: l(suggestion.last_activity, format: :long)) : t(".no_activity") %>
+ </p>
+ </div>
+ <% end %>
+
+ <% table.with_column(t(".destination_column")) do |mapping| %>
+ <div class="form-field min-w-44">
+ <%= form.select "accounts[#{mapping.id}][target_id]", target_options,
+ { selected: mapping.mappable_id.to_s, label: false },
+ { id: dom_id(mapping, :target), aria: { label: t(".destination_label", name: mapping.key) } } %>
+ </div>
+ <% end %>
+
+ <% table.with_column(t(".type_column")) do |mapping| %>
+ <div class="form-field min-w-36">
+ <%= form.select "accounts[#{mapping.id}][type]", type_options,
+ { selected: mapping.type, label: false },
+ { id: dom_id(mapping, :type), aria: { label: t(".type_label", name: mapping.key) } } %>
+ </div>
+ <% end %>
+
+ <% table.with_column(t(".status_column")) do |mapping| %>
+ <%# On means open. The label follows the switch without script: the wrapper shows "Open" while it holds a checked box. %>
+ <div class="group/status flex items-center gap-2">
+ <%= render DS::Toggle.new(id: dom_id(mapping, :closed), name: "accounts[#{mapping.id}][closed]",
+ checked: !mapping.to_converter_choice.closed, checked_value: "0", unchecked_value: "1",
+ aria: { label: t(".status_label", name: mapping.key) }) %>
+ <span class="text-sm text-primary hidden group-has-[:checked]/status:inline"><%= t(".status_open") %></span>
+ <span class="text-sm text-secondary group-has-[:checked]/status:hidden"><%= t(".status_closed") %></span>
+ <% if @import.suggestion_for(mapping.key)&.closed %>
+ <%= render DS::Pill.new(label: t(".inactive"), tone: :warning, marker: false, size: :sm) %>
+ <% end %>
+ </div>
+ <% end %>
+
+ <% table.with_column(tag.span(master_toggle.call("transactions", t(".transactions_column")), class: "inline-flex items-center gap-2")) do |mapping| %>
+ <% count = @import.suggestion_for(mapping.key)&.transactions_count.to_i %>
+ <% if count.positive? %>
+ <div class="flex items-center gap-2">
+ <%= render DS::Toggle.new(id: dom_id(mapping, :transactions), name: "accounts[#{mapping.id}][transactions]",
+ checked: mapping.transactions, aria: { label: t(".transactions_label", name: mapping.key) },
+ data: { checkbox_group: "transactions" }) %>
+ <span class="text-sm text-secondary tabular-nums"><%= number_with_delimiter(count) %></span>
+ </div>
+ <% else %>
+ <span class="text-sm text-secondary"><%= t(".no_transactions") %></span>
+ <% end %>
+ <% end %>
+
+ <% table.with_column(t(".balance_column"), numeric: true) do |mapping| %>
+ <div class="form-field w-32 ml-auto">
+ <%= form.text_field "accounts[#{mapping.id}][current_balance]",
+ value: mapping.current_balance.presence || @import.suggested_current_balance(mapping),
+ label: false, inputmode: "decimal", class: "form-field__input text-right tabular-nums",
+ id: dom_id(mapping, :current_balance), aria: { label: t(".balance_label", name: mapping.key) } %>
+ </div>
+ <% end %>
+ <% end %>
+
+ <div class="flex justify-end">
+ <%= form.submit t(".submit"), disabled: @import.complete? %>
+ </div>
+ <% end %>
+</div>
diff --git a/app/views/import/uploads/show.html.erb b/app/views/import/uploads/show.html.erb
index 7bac7f02ca..34b41f7a3b 100644
--- a/app/views/import/uploads/show.html.erb
+++ b/app/views/import/uploads/show.html.erb
@@ -46,6 +46,36 @@
</span>
</div>
</div>
+<% elsif @import.is_a?(MonarchImport) %>
+ <div class="space-y-4 mx-auto max-w-md">
+ <div class="text-center space-y-2">
+ <h1 class="text-3xl text-primary font-medium"><%= t(".monarch_title") %></h1>
+ <p class="text-secondary text-sm"><%= t(".monarch_description") %></p>
+ </div>
+
+ <%= render DS::Alert.new(variant: :info, title: t(".monarch_export_title")) do %>
+ <ol class="list-decimal pl-4 space-y-1">
+ <li><%= t(".monarch_export_step_settings_html",
+ link: link_to(t(".monarch_export_settings_link"), "https://app.monarch.com/settings/data",
+ target: "_blank", rel: "noopener noreferrer", class: "text-link underline")) %></li>
+ <li><%= t(".monarch_export_step_download") %></li>
+ <li><%= t(".monarch_export_step_upload") %></li>
+ </ol>
+ <p class="text-secondary">
+ <%= t(".monarch_export_help_html",
+ link: link_to(t(".monarch_export_help_link"), "https://help.monarch.com/hc/en-us/articles/15526600975764-Downloading-Transaction-or-Account-History",
+ target: "_blank", rel: "noopener noreferrer", class: "text-link underline")) %>
+ </p>
+ <% end %>
+
+ <%= styled_form_with model: @import, scope: :import, url: import_upload_path(@import), multipart: true, class: "space-y-4" do |form| %>
+ <%= form.file_field :balances_file, label: t(".monarch_balances_label"), accept: ".csv,text/csv", required: true %>
+ <%= form.file_field :transactions_file, label: t(".monarch_transactions_label"), accept: ".csv,text/csv" %>
+ <p class="text-xs text-secondary"><%= t(".monarch_transactions_hint") %></p>
+
+ <%= form.submit t(".monarch_upload_button"), disabled: @import.complete? %>
+ <% end %>
+ </div>
<% elsif @import.is_a?(QifImport) %>
<%# ── QIF upload – fixed format, account required ── %>
<div class="space-y-4 mx-auto max-w-md">
diff --git a/app/views/imports/_nav.html.erb b/app/views/imports/_nav.html.erb
index 0c9ee5aaac..ba9cdc1ab9 100644
--- a/app/views/imports/_nav.html.erb
+++ b/app/views/imports/_nav.html.erb
@@ -5,6 +5,12 @@
{ name: t("imports.steps.upload", default: "Upload"), path: import_upload_path(import), is_complete: import.uploaded?, step_number: 1 },
{ name: t("imports.steps.confirm", default: "Confirm"), path: import_path(import), is_complete: import.complete?, step_number: 2 }
]
+elsif import.is_a?(MonarchImport)
+ [
+ { name: t("imports.steps.upload", default: "Upload"), path: import_upload_path(import), is_complete: import.uploaded?, step_number: 1 },
+ { name: t("imports.steps.accounts", default: "Accounts"), path: import.uploaded? ? import_configuration_path(import) : nil, is_complete: import.publishable?, step_number: 2 },
+ { name: t("imports.steps.confirm", default: "Confirm"), path: import_path(import), is_complete: import.complete?, step_number: 3 }
+ ]
elsif import.is_a?(PdfImport)
# PDF imports have a simplified flow: Upload -> Confirm
# Upload/Configure/Clean are always complete for processed PDF imports
diff --git a/app/views/imports/_ready.html.erb b/app/views/imports/_ready.html.erb
index 0d92d8084b..bfe6e80473 100644
--- a/app/views/imports/_ready.html.erb
+++ b/app/views/imports/_ready.html.erb
@@ -25,6 +25,34 @@
) %>
<% end %>
+ <% if import.is_a?(MonarchImport) %>
+ <% review = import.review %>
+ <% if review[:existing_account_names].any? %>
+ <%= render DS::Alert.new(variant: :warning, title: t(".monarch_existing_names_title"),
+ message: t(".monarch_existing_names_description", names: review[:existing_account_names].to_sentence)) %>
+ <% end %>
+ <% if review[:conflicting_days] > 0 %>
+ <%= render DS::Alert.new(variant: :warning, title: t(".monarch_conflicts_title"),
+ message: t(".monarch_conflicts_description", count: review[:conflicting_days])) %>
+ <% end %>
+ <% if review[:overlapping_transactions] > 0 %>
+ <%= render DS::Alert.new(variant: :warning, title: t(".monarch_overlap_title"),
+ message: t(".monarch_overlap_description", count: review[:overlapping_transactions])) %>
+ <% end %>
+ <% if review[:opening_balances_kept].any? %>
+ <%= render DS::Alert.new(variant: :warning, title: t(".monarch_kept_title"),
+ message: t(".monarch_kept_description", names: review[:opening_balances_kept].to_sentence)) %>
+ <% end %>
+ <% if review[:already_in_sure] > 0 %>
+ <%= render DS::Alert.new(variant: :info, title: t(".monarch_duplicates_title"),
+ message: t(".monarch_duplicates_description", count: review[:already_in_sure])) %>
+ <% end %>
+ <% if review[:moved_opening_balances] > 0 %>
+ <%= render DS::Alert.new(variant: :info, title: t(".monarch_opening_title"),
+ message: t(".monarch_opening_description", count: review[:moved_opening_balances])) %>
+ <% end %>
+ <% end %>
+
<% if reused_taxonomy_count > 0 %>
<%= render DS::Alert.new(
variant: :info,
@@ -99,7 +127,7 @@
</div>
</div>
- <% if import_summary_empty %>
+ <% if import_summary_empty && !import.changes_existing_records? %>
<%= render DS::Link.new(text: t(".back_to_imports"), href: imports_path, variant: :secondary, full_width: true) %>
<% else %>
<%= render DS::Button.new(text: t(".publish_import"), href: publish_import_path(import), method: :post, full_width: true) %>
diff --git a/app/views/imports/new.html.erb b/app/views/imports/new.html.erb
index 121760437a..687d6d6ba2 100644
--- a/app/views/imports/new.html.erb
+++ b/app/views/imports/new.html.erb
@@ -30,7 +30,7 @@
<% end %>
<%
- financial_tool_types = %w[MintImport ActualImport YnabImport QifImport SureImport DocumentImport PdfImport]
+ financial_tool_types = %w[MintImport ActualImport YnabImport MonarchImport QifImport SureImport DocumentImport PdfImport]
import_type = params[:type].presence || @pending_import&.type
active_tab = import_type.present? && !import_type.in?(financial_tool_types) ? "raw_data" : "financial_tools"
%>
@@ -128,6 +128,14 @@
enabled: true %>
<% end %>
+ <% if (params[:type].nil? || params[:type] == "MonarchImport") && !Current.user&.guest? %>
+ <%= render "imports/import_option",
+ type: "MonarchImport",
+ image: "monarch-logo.png",
+ label: t(".import_monarch"),
+ enabled: true %>
+ <% end %>
+
<% if (params[:type].nil? || params[:type].in?(%w[DocumentImport PdfImport])) && @document_upload_extensions.any? %>
<li>
<%= styled_form_with url: imports_path, scope: :import, multipart: true, class: "w-full", data: { turbo_frame: "_top" } do |form| %>
diff --git a/app/views/imports/show.html.erb b/app/views/imports/show.html.erb
index d4863585b5..34bc1ea214 100644
--- a/app/views/imports/show.html.erb
+++ b/app/views/imports/show.html.erb
@@ -2,7 +2,12 @@
<%= render "imports/nav", import: @import %>
<% end %>
-<%= content_for :previous_path, @import.is_a?(PdfImport) ? imports_path : import_confirm_path(@import) %>
+<% previous_path = case @import
+ when PdfImport then imports_path
+ when MonarchImport then import_configuration_path(@import)
+ else import_confirm_path(@import)
+end %>
+<%= content_for :previous_path, previous_path %>
<% if @import.is_a?(PdfImport) %>
<%= render "imports/pdf_import", import: @import %>
diff --git a/config/locales/models/monarch_import/en.yml b/config/locales/models/monarch_import/en.yml
new file mode 100644
index 0000000000..696ea0a467
--- /dev/null
+++ b/config/locales/models/monarch_import/en.yml
@@ -0,0 +1,20 @@
+---
+en:
+ activerecord:
+ errors:
+ models:
+ monarch_import:
+ missing_columns: "The %{file} file is missing the columns %{columns}. Is it the right Monarch export?"
+ malformed_csv: "The %{file} file isn't a readable CSV: %{error}"
+ invalid_number: "%{value} isn't a number"
+ invalid_date: "%{value} isn't a date in the form 2024-01-31"
+ date_out_of_range: "%{value} is outside the dates Sure imports (%{from} to %{to})"
+ 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."
+ no_accounts: "The exports don't contain any accounts. Check that you exported the right files from Monarch."
+ files:
+ balances: balances
+ transactions: transactions
+ import/monarch_account_mapping:
+ target_taken: "%{account} is already the destination of another Monarch account. Choose a different account for %{monarch}, or import it as a new account."
diff --git a/config/locales/views/imports/en.yml b/config/locales/views/imports/en.yml
index e160120c13..4c840761f1 100644
--- a/config/locales/views/imports/en.yml
+++ b/config/locales/views/imports/en.yml
@@ -43,6 +43,40 @@ en:
configurations:
update:
success: Import configured successfully.
+ monarch_success: Account choices saved.
+ monarch:
+ title: Check each Monarch account
+ description: Choose where each account goes, what type it is, and what to bring over.
+ help_title: How each choice works
+ help_account: "Import into a new account, named as you like, or into one of your manual accounts. An existing account keeps its name, type and own entries, and its opening balance moves to the start of the Monarch history if it falls inside it. Its status follows the Status you choose. Accounts with holdings or trades can't be imported into."
+ help_closed: "Switch Status to Closed for accounts you've closed. They drop to zero the day after their last Monarch balance and are hidden from current balances, but stay in your net worth history. Accounts marked inactive had no activity in the last %{days} days, which doesn't always mean they're closed."
+ help_transactions: Turn transactions off to import only an account's balance history.
+ help_balance: "Balance today starts at Monarch's latest balance. Change it if that's out of date, and it's recorded as today's balance. Enter amounts owed on cards and loans as positive numbers."
+ table_label: Monarch accounts
+ import_column: Import
+ account_column: Account name
+ destination_column: Import into
+ type_column: Type
+ status_column: Status
+ status_open: Open
+ status_closed: Closed
+ toggle_all_label: "%{column} for every account"
+ transactions_column: Transactions
+ balance_column: Balance today
+ import_label: "Import %{name}"
+ destination_label: "Where to import %{name}"
+ name_label: "Name in Sure for %{name}"
+ monarch_name: "In Monarch: %{name}"
+ type_label: "Type of %{name}"
+ status_label: "%{name} is open"
+ transactions_label: "Import the transactions of %{name}"
+ balance_label: "Balance today for %{name}"
+ new_account: New account
+ inactive: Inactive
+ last_activity: "Last activity %{date}"
+ no_activity: No activity
+ no_transactions: None
+ submit: Review import
account_import:
leave_empty: Leave empty
default: Default
@@ -208,7 +242,22 @@ en:
qif_account_required: Please select an account for the QIF import
update:
qif_uploaded: "QIF file uploaded successfully."
+ monarch_uploaded: Monarch exports uploaded.
+ monarch_balances_required: Choose the Monarch balances export.
show:
+ monarch_title: Upload your Monarch exports
+ monarch_description: Bring your accounts, transactions and balance history over from Monarch.
+ monarch_export_title: Download your data from Monarch
+ monarch_export_step_settings_html: "Log in to Monarch on the web and open %{link}."
+ monarch_export_settings_link: Settings → Data
+ monarch_export_step_download: Download your transactions and your account balance history, each as a CSV file.
+ monarch_export_step_upload: Choose the files below.
+ monarch_export_help_html: "Monarch explains each download in %{link}."
+ monarch_export_help_link: its help article
+ monarch_balances_label: Balances export
+ monarch_transactions_label: Transactions export
+ monarch_transactions_hint: Leave the transactions export out to import balance history only.
+ monarch_upload_button: Upload exports
csv_invalid: "Must be valid CSV with headers and at least one row of data"
drop_csv_title: Drop CSV to upload
drop_csv_subtitle: Your file will be uploaded automatically
@@ -361,6 +410,7 @@ en:
mint_import: "Mint import"
actual_import: "Actual import"
ynab_import: "YNAB import"
+ monarch_import: "Monarch import"
qif_import: "QIF import"
category_import: "Category import"
rule_import: "Rule import"
@@ -370,6 +420,7 @@ en:
sure_import: "Sure import"
steps:
upload: Upload
+ accounts: Accounts
configure: Configure
clean: Clean
map: Map
@@ -424,6 +475,7 @@ en:
tab_financial_tools: Financial Tools & Files
tab_raw_data: Raw Data
import_ynab: Import from YNAB
+ import_monarch: Import from Monarch
import_accounts: Import accounts
import_categories: Import categories
import_merchants: Import merchants
@@ -463,6 +515,26 @@ en:
ready:
description: Here's a summary of the new items that will be added to your account
once you publish this import.
+ monarch_existing_names_title: Accounts with these names already exist
+ monarch_existing_names_description: "You already have accounts named %{names}. Publishing creates new accounts beside them. To import into one of them instead, choose it on the Accounts step."
+ monarch_conflicts_title: Some existing balances differ from Monarch
+ monarch_conflicts_description:
+ one: "On 1 day, an account you're importing into already has a balance update that differs from Monarch's. Your existing value is kept."
+ other: "On %{count} days, accounts you're importing into already have balance updates that differ from Monarch's. Your existing values are kept."
+ monarch_overlap_title: Existing transactions in the same period
+ monarch_overlap_description:
+ one: "1 existing transaction falls within the Monarch history of an account you're importing into and doesn't match a Monarch transaction. It's kept and counts toward the balance."
+ other: "%{count} existing transactions fall within the Monarch history of accounts you're importing into and don't match a Monarch transaction. They're kept and count toward the balance."
+ monarch_duplicates_title: Transactions already in Sure are skipped
+ monarch_duplicates_description:
+ one: "1 Monarch transaction is already in the account it's going into, from an earlier import or with the same date and amount, so it's skipped."
+ other: "%{count} Monarch transactions are already in the accounts they're going into, from an earlier import or with the same date and amount, so they're skipped."
+ monarch_kept_title: Some opening balances were left as you edited them
+ monarch_kept_description: "Undoing the import didn't restore the opening balance of %{names}, because it was changed after the import. Check it before importing again."
+ monarch_opening_title: Opening balances will move
+ monarch_opening_description:
+ one: "1 existing account's opening balance moves to the start of its Monarch history. Undoing the import puts it back."
+ other: "%{count} existing accounts' opening balances move to the start of their Monarch history. Undoing the import puts them back."
title: Confirm your import data
summary_item_label: Item
summary_count_label: Count
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index d9537cf58d..42d8dbf229 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -2303,8 +2303,6 @@ components:
- CategoryImport
- RuleImport
- MerchantImport
- - PdfImport
- - QifImport
- SureImport
valid:
type: boolean
@@ -2392,6 +2390,7 @@ components:
- MintImport
- ActualImport
- YnabImport
+ - MonarchImport
- CategoryImport
- RuleImport
- MerchantImport
@@ -2449,6 +2448,7 @@ components:
- MintImport
- ActualImport
- YnabImport
+ - MonarchImport
- CategoryImport
- RuleImport
- MerchantImport
@@ -7801,6 +7801,7 @@ paths:
- MintImport
- ActualImport
- YnabImport
+ - MonarchImport
- CategoryImport
- RuleImport
- MerchantImport
@@ -7878,7 +7879,9 @@ paths:
- PdfImport
- QifImport
- SureImport
- description: Import type (defaults to TransactionImport)
+ description: Import type (defaults to TransactionImport). MonarchImport
+ imports are created in the web app; requesting one here returns
+ 422 unsupported_type.
account_id:
type: string
format: uuid
@@ -7989,7 +7992,9 @@ paths:
- PdfImport
- QifImport
- SureImport
- description: Import type (defaults to TransactionImport)
+ description: Import type (defaults to TransactionImport). MonarchImport
+ imports are created in the web app; requesting one here returns
+ 422 unsupported_type.
account_id:
type: string
format: uuid
@@ -8228,8 +8233,6 @@ paths:
- CategoryImport
- RuleImport
- MerchantImport
- - PdfImport
- - QifImport
- SureImport
description: Import type to validate (defaults to TransactionImport)
account_id:
@@ -8343,8 +8346,6 @@ paths:
- CategoryImport
- RuleImport
- MerchantImport
- - PdfImport
- - QifImport
- SureImport
description: Import type to validate (defaults to TransactionImport)
account_id:
diff --git a/spec/requests/api/v1/imports_spec.rb b/spec/requests/api/v1/imports_spec.rb
index abb4bab8d1..6c5cbbd64a 100644
--- a/spec/requests/api/v1/imports_spec.rb
+++ b/spec/requests/api/v1/imports_spec.rb
@@ -138,8 +138,8 @@ RSpec.describe 'API V1 Imports', type: :request do
},
type: {
type: :string,
- enum: Import::TYPES,
- description: 'Import type (defaults to TransactionImport)'
+ enum: Import::TYPES - %w[MonarchImport],
+ description: 'Import type (defaults to TransactionImport). MonarchImport imports are created in the web app; requesting one here returns 422 unsupported_type.'
},
account_id: {
type: :string,
@@ -420,7 +420,7 @@ RSpec.describe 'API V1 Imports', type: :request do
},
type: {
type: :string,
- enum: Import::TYPES,
+ enum: Import::Preflight::IMPORT_TYPES,
description: 'Import type to validate (defaults to TransactionImport)'
},
account_id: {
diff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rb
index 7699f61a91..83f5849921 100644
--- a/spec/swagger_helper.rb
+++ b/spec/swagger_helper.rb
@@ -1261,7 +1261,7 @@ RSpec.configure do |config|
type: :object,
required: %w[type valid content stats errors warnings],
properties: {
- type: { type: :string, enum: Import::TYPES },
+ type: { type: :string, enum: Import::Preflight::IMPORT_TYPES },
valid: { type: :boolean },
content: { '$ref' => '#/components/schemas/ImportPreflightContent' },
stats: { '$ref' => '#/components/schemas/ImportPreflightStats' },
diff --git a/test/controllers/api/v1/imports_controller_test.rb b/test/controllers/api/v1/imports_controller_test.rb
index 5f0aace517..3cb9f5c195 100644
--- a/test/controllers/api/v1/imports_controller_test.rb
+++ b/test/controllers/api/v1/imports_controller_test.rb
@@ -78,6 +78,17 @@ class Api::V1::ImportsControllerTest < ActionDispatch::IntegrationTest
)
end
+ test "refuses to create a Monarch import" do
+ assert_no_difference -> { @family.imports.count } do
+ post api_v1_imports_url,
+ params: { type: "MonarchImport", raw_file_content: "Date,Balance,Account\n2024-01-01,1.00,Checking\n" },
+ headers: api_headers(@api_key)
+ end
+
+ assert_response :unprocessable_entity
+ assert_equal "unsupported_type", JSON.parse(response.body)["error"]
+ end
+
test "should list imports" do
get api_v1_imports_url, headers: api_headers(@api_key)
assert_response :success
@@ -871,6 +882,15 @@ class Api::V1::ImportsControllerTest < ActionDispatch::IntegrationTest
assert_not response_data.key?("errors")
end
+ test "should reject Monarch imports in preflight" do
+ post preflight_api_v1_imports_url,
+ params: { type: "MonarchImport", raw_file_content: "date,amount,name\n2023-01-01,-10.00,Test Transaction" },
+ headers: api_headers(@read_only_api_key)
+
+ assert_response :unprocessable_entity
+ assert_equal "invalid_import_type", JSON.parse(response.body)["error"]
+ end
+
test "should reject import types excluded from preflight" do
assert_no_difference("Import.count") do
post preflight_api_v1_imports_url,
diff --git a/test/controllers/import/monarch_import_flow_test.rb b/test/controllers/import/monarch_import_flow_test.rb
new file mode 100644
index 0000000000..9ddd96dad0
--- /dev/null
+++ b/test/controllers/import/monarch_import_flow_test.rb
@@ -0,0 +1,137 @@
+require "test_helper"
+
+class Import::MonarchImportFlowTest < ActionDispatch::IntegrationTest
+ setup do
+ sign_in @user = users(:family_admin)
+ @import = @user.family.imports.create!(type: "MonarchImport")
+ end
+
+ test "upload shows both file fields" do
+ get import_upload_url(@import)
+
+ assert_response :success
+ assert_select "input[type=file][name='import[balances_file]']"
+ assert_select "input[type=file][name='import[transactions_file]']"
+ assert_select "a[href='https://app.monarch.com/settings/data'][target=_blank]"
+ end
+
+ test "uploading the exports goes to the accounts step" do
+ upload_exports
+
+ assert_redirected_to import_configuration_url(@import)
+ assert_equal %w[Card Checking Old\ Savings], @import.account_mappings.order(:key).pluck(:key)
+ end
+
+ test "uploading without the balances export is rejected" do
+ patch import_upload_url(@import), params: { import: { transactions_file: csv_upload("monarch_transactions.csv") } }
+
+ assert_response :unprocessable_entity
+ assert_not @import.reload.uploaded?
+ end
+
+ test "uploading the wrong file explains what's missing" do
+ patch import_upload_url(@import), params: { import: { balances_file: csv_upload("monarch_transactions.csv") } }
+
+ assert_response :unprocessable_entity
+ assert_match "missing the columns Balance", response.body
+ end
+
+ test "the accounts step lists each account and saves the choices" do
+ upload_exports
+ get import_configuration_url(@import)
+ assert_response :success
+ assert_select "table tbody tr", 3
+
+ checking = @import.account_mappings.find_by!(key: "Checking")
+ target = accounts(:depository)
+ patch import_configuration_url(@import), params: { accounts: {
+ checking.id => { name: "Everyday", type: "Depository", target_id: target.id, include: "1", closed: "0", transactions: "0", current_balance: "250" }
+ } }
+
+ assert_redirected_to import_url(@import)
+ checking.reload
+ assert_equal [ target, false, "250", "Everyday" ], [ checking.target, checking.to_converter_choice.transactions, checking.current_balance, checking.account_name ]
+ end
+
+ test "an account the user can't access can't be a target" do
+ upload_exports
+ checking = @import.account_mappings.find_by!(key: "Checking")
+ other_family_account = families(:empty).accounts.create!(name: "Elsewhere", balance: 0, currency: "USD", accountable: Depository.new)
+
+ patch import_configuration_url(@import), params: { accounts: { checking.id => { type: "Depository", target_id: other_family_account.id, include: "1" } } }
+
+ assert_response :not_found
+ assert_nil checking.reload.target
+ end
+
+ test "a read-only shared account can't be a target, or be published into" do
+ upload_exports
+ checking = @import.account_mappings.find_by!(key: "Checking")
+ read_only = accounts(:credit_card)
+ sign_in users(:family_member)
+
+ patch import_configuration_url(@import), params: { accounts: { checking.id => { type: "CreditCard", target_id: read_only.id, include: "1" } } }
+ assert_response :not_found
+
+ checking.update!(mappable: read_only)
+ assert_no_enqueued_jobs(only: ImportJob) do
+ post publish_import_url(@import)
+ end
+ assert_equal I18n.t("accounts.not_authorized"), flash[:alert]
+ end
+
+ test "saving with no accounts submitted changes nothing" do
+ upload_exports
+ checking = @import.account_mappings.find_by!(key: "Checking")
+ checking.update!(choices: { "name" => "Everyday", "transactions" => false })
+
+ patch import_configuration_url(@import), params: { other: "1" }
+
+ assert_redirected_to import_url(@import)
+ assert_equal [ "Everyday", false ], checking.reload.choices.values_at("name", "transactions")
+ end
+
+ test "the confirm step goes back to the accounts step" do
+ upload_exports
+ get import_url(@import)
+
+ assert_select "header > a[href='#{import_configuration_path(@import)}']"
+ end
+
+ test "two Monarch accounts can't go into the same account" do
+ upload_exports
+ checking, card = %w[Checking Card].map { |name| @import.account_mappings.find_by!(key: name) }
+ target = accounts(:depository)
+
+ patch import_configuration_url(@import), params: { accounts: {
+ checking.id => { type: "Depository", target_id: target.id, include: "1" },
+ card.id => { type: "CreditCard", target_id: target.id, include: "1" }
+ } }
+
+ assert_redirected_to import_configuration_url(@import)
+ assert_match "already the destination", flash[:alert]
+ assert_nil checking.reload.target
+ end
+
+ test "confirm shows the summary and publishes" do
+ upload_exports
+ get import_url(@import)
+ assert_response :success
+
+ assert_enqueued_with(job: ImportJob) do
+ post publish_import_url(@import)
+ end
+ end
+
+ private
+ def csv_upload(name)
+ fixture_file_upload("imports/#{name}", "text/csv")
+ end
+
+ def upload_exports
+ patch import_upload_url(@import), params: { import: {
+ balances_file: csv_upload("monarch_balances.csv"),
+ transactions_file: csv_upload("monarch_transactions.csv")
+ } }
+ end
+end
diff --git a/test/fixtures/files/imports/monarch_balances.csv b/test/fixtures/files/imports/monarch_balances.csv
new file mode 100644
index 0000000000..0c07a56c9c
--- /dev/null
+++ b/test/fixtures/files/imports/monarch_balances.csv
@@ -0,0 +1,10 @@
+Date,Balance,Account
+2024-01-01,100.00,Checking
+2024-01-02,90.00,Checking
+2024-01-03,95.00,Checking
+2024-01-04,95.00,Checking
+2024-01-01,-50.00,Card
+2024-01-02,-70.00,Card
+2024-01-03,-70.00,Card
+2024-01-04,-70.00,Card
+2024-01-01,10.00,Old Savings
diff --git a/test/fixtures/files/imports/monarch_transactions.csv b/test/fixtures/files/imports/monarch_transactions.csv
new file mode 100644
index 0000000000..9508ae95cb
--- /dev/null
+++ b/test/fixtures/files/imports/monarch_transactions.csv
@@ -0,0 +1,6 @@
+Date,Merchant,Category,Account,Original Statement,Notes,Amount,Tags,Owner,Reviewed,Reviewed At,Reviewed By,Pending,Id
+2024-01-02,Grocer,Groceries,Checking,GROCER #12,weekly shop,-10.00,Food,Me,true,,Me,false,1
+2024-01-04,Employer,Paychecks,Checking,PAYROLL,,7.00,,Me,false,,,false,2
+2024-01-02,Cafe,Restaurants,Card,CAFE,,-20.00,"Food, Treats",Me,false,,,false,3
+2024-01-04,Payment,Credit Card Payment,Checking,CC PMT,,-1.00,,Me,false,,,false,4
+2024-01-04,Later,Groceries,Checking,LATER,,-3.00,,Me,false,,,true,5
diff --git a/test/models/family/data_importer_test.rb b/test/models/family/data_importer_test.rb
index c3cc73fb11..3b12cf2219 100644
--- a/test/models/family/data_importer_test.rb
+++ b/test/models/family/data_importer_test.rb
@@ -31,6 +31,33 @@ class Family::DataImporterTest < ActiveSupport::TestCase
assert_equal "Depository", account.accountable_type
end
+ test "imports into existing accounts given as account targets" do
+ account = @family.accounts.create!(name: "Existing", balance: 0, currency: "USD", accountable: Depository.new)
+ ndjson = build_ndjson([
+ { type: "Transaction", data: { id: "old-txn", account_id: "old-account", date: "2024-01-02", amount: "10.00", name: "Grocer" } }
+ ])
+
+ result = Family::DataImporter.new(@family, ndjson, account_targets: { "old-account" => account }).import!
+
+ assert_empty result[:accounts]
+ assert_equal [ "Grocer" ], account.entries.pluck(:name)
+ end
+
+ test "keeps a transaction's own extra metadata and import lock" do
+ account = @family.accounts.create!(name: "Existing", balance: 0, currency: "USD", accountable: Depository.new)
+ ndjson = build_ndjson([
+ { type: "Transaction", data: { id: "old-txn", account_id: "old-account", date: "2024-01-02", amount: "10.00",
+ name: "Grocer", extra: { monarch: { transaction_id: "1" } }, import_locked: true } }
+ ])
+
+ Family::DataImporter.new(@family, ndjson, account_targets: { "old-account" => account }).import!
+
+ entry = account.entries.sole
+ assert_equal({ "monarch" => { "transaction_id" => "1" } }, entry.transaction.extra)
+ assert entry.import_locked?
+ assert_nil entry.external_id
+ end
+
test "restores the Brandfetch logo choice so no fetched icon replaces it" do
ndjson = build_ndjson([
{
diff --git a/test/models/monarch_import/balance_history_test.rb b/test/models/monarch_import/balance_history_test.rb
new file mode 100644
index 0000000000..61a54400e9
--- /dev/null
+++ b/test/models/monarch_import/balance_history_test.rb
@@ -0,0 +1,106 @@
+require "test_helper"
+
+class MonarchImport::BalanceHistoryTest < ActiveSupport::TestCase
+ test "adds no valuation where transactions explain the change" do
+ history = history_for("2024-01-01" => 100, "2024-01-02" => 90)
+
+ assert_equal [ [ day("2024-01-01"), 100 ] ], anchors(history: history, flows: amounts("2024-01-02" => -10))
+ end
+
+ test "adds a valuation where the balance drifts from the transactions" do
+ history = history_for("2024-01-01" => 100, "2024-01-02" => 95)
+
+ assert_equal [ [ day("2024-01-01"), 100 ], [ day("2024-01-02"), 95 ] ],
+ anchors(history: history, flows: amounts("2024-01-02" => -10))
+ end
+
+ test "opens before transactions that predate the balance history" do
+ history = history_for("2024-01-03" => 50)
+
+ assert_equal [ [ day("2023-12-31"), 55 ] ],
+ anchors(history: history, flows: amounts("2024-01-01" => -10, "2024-01-02" => 5))
+ end
+
+ test "opens before existing transactions that predate the imported ones" do
+ balance_history = MonarchImport::BalanceHistory.new(history: history_for("2024-01-03" => 50),
+ flows: amounts("2024-01-02" => 5), existing_flows: amounts("2024-01-01" => -10))
+
+ assert_equal [ [ day("2023-12-31"), 55 ] ], balance_history.anchors
+ assert_equal 50, balance_history.replay(through: day("2024-01-03"))[day("2024-01-03")]
+ end
+
+ test "a closed account drops to zero the day after its last balance" do
+ assert_equal [ [ day("2024-01-01"), 100 ], [ day("2024-01-02"), 0 ] ],
+ anchors(history: history_for("2024-01-01" => 100), closed: true)
+ end
+
+ test "replay reproduces every day of the history" do
+ history = history_for("2024-01-01" => 100, "2024-01-02" => 90, "2024-01-03" => 93, "2024-01-05" => 80)
+ flows = amounts("2024-01-02" => -10, "2024-01-03" => 4, "2024-01-04" => -13)
+ balance_history = MonarchImport::BalanceHistory.new(history: history, flows: flows)
+
+ replayed = balance_history.replay(through: day("2024-01-05"))
+ history.each { |date, balance| assert_equal balance, replayed[date], date }
+ end
+
+ test "a current balance adds a valuation only when it differs" do
+ balance_history = MonarchImport::BalanceHistory.new(history: history_for("2024-01-01" => 100))
+
+ assert_equal balance_history.anchors, balance_history.anchors_with_current_balance(day("2024-01-10"), 100)
+ assert_equal [ [ day("2024-01-01"), 100 ], [ day("2024-01-10"), 120 ] ],
+ balance_history.anchors_with_current_balance(day("2024-01-10"), 120)
+ end
+
+ test "replay only visits the dates with entries" do
+ balance_history = MonarchImport::BalanceHistory.new(history: history_for("1970-01-01" => 100, "2030-01-01" => 90))
+
+ assert_equal [ day("1970-01-01"), day("2030-01-01"), day("2031-01-01") ],
+ balance_history.replay(through: day("2031-01-01")).keys
+ end
+
+ test "a day that conflicts with both the history and the current balance is reported once" do
+ balance_history = MonarchImport::BalanceHistory.new(history: history_for("2024-01-01" => 100, "2024-01-10" => 100),
+ existing_valuations: amounts("2024-01-10" => 70))
+
+ balance_history.anchors_with_current_balance(day("2024-01-10"), 120)
+ assert_equal [ day("2024-01-10") ], balance_history.conflicts
+ end
+
+ test "existing transactions count toward the balance" do
+ history = history_for("2024-01-01" => 100, "2024-01-02" => 90)
+ balance_history = MonarchImport::BalanceHistory.new(history: history, existing_flows: amounts("2024-01-02" => -10))
+
+ assert_equal [ [ day("2024-01-01"), 100 ] ], balance_history.anchors
+ assert_equal 90, balance_history.replay[day("2024-01-02")]
+ end
+
+ test "existing valuations are kept and disagreements are conflicts" do
+ history = history_for("2024-01-01" => 100, "2024-01-02" => 90, "2024-01-03" => 90)
+ balance_history = MonarchImport::BalanceHistory.new(history: history, existing_valuations: amounts("2024-01-02" => 70))
+
+ assert_equal [ [ day("2024-01-01"), 100 ], [ day("2024-01-03"), 90 ] ], balance_history.anchors
+ assert_equal [ day("2024-01-02") ], balance_history.conflicts
+ end
+
+ test "a closed account reuses an existing closing balance" do
+ balance_history = MonarchImport::BalanceHistory.new(history: history_for("2024-01-01" => 100), closed: true,
+ existing_valuations: amounts("2024-01-01" => 100, "2024-01-02" => 0))
+
+ assert_empty balance_history.anchors
+ assert_empty balance_history.conflicts
+ end
+
+ private
+ def day(value)
+ Date.iso8601(value)
+ end
+
+ def amounts(values)
+ values.to_h { |date, amount| [ day(date), BigDecimal(amount.to_s) ] }
+ end
+ alias_method :history_for, :amounts
+
+ def anchors(**options)
+ MonarchImport::BalanceHistory.new(**options).anchors
+ end
+end
diff --git a/test/models/monarch_import/converter_test.rb b/test/models/monarch_import/converter_test.rb
new file mode 100644
index 0000000000..c95ae39cec
--- /dev/null
+++ b/test/models/monarch_import/converter_test.rb
@@ -0,0 +1,266 @@
+require "test_helper"
+
+class MonarchImport::ConverterTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:empty)
+ @exports = MonarchImport::Exports.new(
+ balances_csv: file_fixture("imports/monarch_balances.csv").read,
+ transactions_csv: file_fixture("imports/monarch_transactions.csv").read
+ )
+ end
+
+ test "transactions flip sign and link their category, merchant and tags" do
+ transaction = records("Transaction")["monarch-transaction:1"]
+
+ assert_equal "10.00", transaction["amount"]
+ assert_equal "monarch-category:Groceries", transaction["category_id"]
+ assert_equal "monarch-merchant:Grocer", transaction["merchant_id"]
+ assert_equal [ "monarch-tag:Food" ], transaction["tag_ids"]
+ end
+
+ test "transfers and card payments become transaction kinds without a category" do
+ payment = records("Transaction")["monarch-transaction:4"]
+
+ assert_equal "cc_payment", payment["kind"]
+ assert_nil payment["category_id"]
+ end
+
+ test "pending transactions are left out" do
+ assert_not records("Transaction").key?("monarch-transaction:5")
+ end
+
+ test "liability balances are positive in Sure" do
+ assert_equal "70.00", records("Account")["monarch-account:Card"]["balance"]
+ end
+
+ test "new accounts open with the first Monarch balance" do
+ opening = records("Valuation")["monarch-valuation:Checking:2024-01-01"]
+
+ assert_equal [ "opening_anchor", "100.00" ], opening.values_at("kind", "amount")
+ assert records("Account")["monarch-account:Checking"]["skip_opening_balance_import"]
+ end
+
+ test "a new account takes the chosen name but keeps Monarch's for matching" do
+ account = records("Account", "Checking" => { account_name: "Everyday" })["monarch-account:Checking"]
+
+ assert_equal "Everyday", account["name"]
+ assert records("Transaction", "Checking" => { account_name: "Everyday" }).values.any? { |t| t["account_id"] == "monarch-account:Checking" }
+ end
+
+ test "closed accounts drop to zero and are disabled" do
+ valuations = records("Valuation", "Old Savings" => { closed: true })
+
+ assert_equal "0.00", valuations["monarch-valuation:Old Savings:2024-01-02"]["amount"]
+ assert_equal "disabled", records("Account", "Old Savings" => { closed: true })["monarch-account:Old Savings"]["status"]
+ end
+
+ test "skipped accounts and their transactions are left out" do
+ result = convert("Card" => { include: false })
+
+ assert_not record_ids(result, "Account").include?("monarch-account:Card")
+ assert_equal 1, result.stats["transactions_skipped_excluded_account"]
+ end
+
+ test "balances-only accounts keep their history without transactions" do
+ result = convert("Checking" => { transactions: false })
+ checking = result.records.select { |r| r["type"] == "Valuation" && r["data"]["account_id"] == "monarch-account:Checking" }
+
+ assert_equal %w[100.00 90.00 95.00], checking.map { |r| r["data"]["amount"] }
+ assert_equal 3, result.stats["transactions_skipped_balances_only"]
+ end
+
+ test "a changed current balance adds a valuation today" do
+ valuations = records("Valuation", { "Checking" => { current_balance: BigDecimal("120") }, "Card" => { current_balance: BigDecimal("80") } },
+ today: Date.new(2024, 1, 10))
+
+ assert_equal "120.00", valuations["monarch-valuation:Checking:2024-01-10"]["amount"]
+ assert_equal "80.00", valuations["monarch-valuation:Card:2024-01-10"]["amount"]
+ end
+
+ test "accounts whose balance ignores transactions get a valuation for every change" do
+ result = convert("Checking" => { type: "Property" })
+ checking = result.records.select { |r| r["type"] == "Valuation" && r["data"]["account_id"] == "monarch-account:Checking" }
+
+ assert_equal %w[100.00 90.00 95.00], checking.map { |r| r["data"]["amount"] }
+ assert record_ids(result, "Transaction").include?("monarch-transaction:1")
+ end
+
+ test "existing entries count in the account's currency, without split parents" do
+ account = existing_account(opening_date: Date.new(2023, 12, 1), opening_balance: 100)
+ ExchangeRate.create!(date: Date.new(2024, 1, 2), from_currency: "EUR", to_currency: "USD", rate: 1.1)
+ account.entries.create!(date: Date.new(2024, 1, 2), amount: 10, currency: "EUR", name: "Paris", entryable: Transaction.new)
+ parent = account.entries.create!(date: Date.new(2024, 1, 2), amount: 4, currency: "USD", name: "Shop", entryable: Transaction.new)
+ parent.split!([ { name: "One", amount: 1, category_id: nil }, { name: "Two", amount: 3, category_id: nil } ])
+ exports = MonarchImport::Exports.new(balances_csv: "Date,Balance,Account\n2024-01-01,100.00,Checking\n2024-01-02,85.00,Checking\n")
+ choice = MonarchImport::Converter::Choice.new(name: "Checking", type: "Depository", closed: false, include: true,
+ transactions: true, current_balance: nil, target: account)
+
+ result = MonarchImport::Converter.new(exports: exports, choices: [ choice ], family: @family, today: Date.new(2024, 1, 4)).result
+ assert_empty record_ids(result, "Valuation")
+ end
+
+ test "existing categories and merchants keep their look" do
+ @family.categories.create!(name: "Groceries", color: "#123456", lucide_icon: "carrot", classification_unused: "expense")
+ @family.merchants.create!(name: "Grocer", color: "#abcdef")
+ result = convert
+
+ category = result.records.find { |r| r["type"] == "Category" && r["data"]["name"] == "Groceries" }["data"]
+ merchant = result.records.find { |r| r["type"] == "Merchant" && r["data"]["name"] == "Grocer" }["data"]
+ assert_equal [ "#123456", "carrot" ], category.values_at("color", "lucide_icon")
+ assert_equal "#abcdef", merchant["color"]
+ assert_equal 1, result.stats["categories_reusing_existing"]
+ end
+
+ test "importing into an existing account moves its opening balance to the start of the history" do
+ account = existing_account(opening_date: Date.new(2024, 1, 3), opening_balance: 500)
+ result = convert("Checking" => { target: account })
+
+ assert_not record_ids(result, "Account").include?("monarch-account:Checking")
+ move = result.opening_balance_moves.sole
+ assert_equal [ Date.new(2024, 1, 1), BigDecimal("100") ], [ move.date, move.balance ]
+ assert_not record_ids(result, "Valuation").include?("monarch-valuation:Checking:2024-01-01")
+ end
+
+ test "an earlier opening balance stays, and disagreeing balance updates are reported" do
+ account = existing_account(opening_date: Date.new(2023, 12, 1), opening_balance: 100)
+ account.entries.create!(date: Date.new(2024, 1, 2), amount: 70, currency: "USD", name: "Manual", entryable: Valuation.new(kind: "reconciliation"))
+ result = convert("Checking" => { target: account })
+
+ assert_empty result.opening_balance_moves
+ assert_equal [ Date.new(2024, 1, 2) ], result.conflicts["Checking"]
+ end
+
+ test "transactions keep their Monarch ID outside external_id, and are import locked" do
+ transaction = records("Transaction")["monarch-transaction:1"]
+
+ assert_equal({ "monarch" => { "transaction_id" => "1" } }, transaction["extra"])
+ assert transaction["import_locked"]
+ assert_not transaction.key?("external_id")
+ end
+
+ test "transactions already imported from Monarch are skipped" do
+ account = existing_account(opening_date: Date.new(2023, 12, 1), opening_balance: 100)
+ account.entries.create!(date: Date.new(2024, 1, 2), amount: 10, currency: "USD", name: "Grocer",
+ external_id: "sfin-1", source: "simplefin", entryable: Transaction.new(extra: { "monarch" => { "transaction_id" => "1" } }))
+ result = convert("Checking" => { target: account })
+
+ assert_not record_ids(result, "Transaction").include?("monarch-transaction:1")
+ assert_equal 1, result.stats["transactions_skipped_already_in_sure"]
+ assert_equal 0, result.overlapping_transactions["Checking"]
+ end
+
+ test "transactions imported earlier through the Monarch to Sure tool are recognised" do
+ account = existing_account(opening_date: Date.new(2023, 12, 1), opening_balance: 100)
+ account.entries.create!(date: Date.new(2024, 1, 2), amount: 10, currency: "USD", name: "Grocer",
+ source: "sure_import_session:abc", external_id: "Transaction:monarch-transaction:1", entryable: Transaction.new)
+
+ assert_equal 1, convert("Checking" => { target: account }).stats["transactions_skipped_already_in_sure"]
+ end
+
+ test "a tool-style external ID from another source is not taken as a Monarch import" do
+ account = existing_account(opening_date: Date.new(2023, 12, 1), opening_balance: 100)
+ account.entries.create!(date: Date.new(2024, 1, 3), amount: 25, currency: "USD", name: "Other",
+ source: "some_api_client", external_id: "Transaction:monarch-transaction:1", entryable: Transaction.new)
+ result = convert("Checking" => { target: account })
+
+ assert record_ids(result, "Transaction").include?("monarch-transaction:1")
+ assert_equal 1, result.overlapping_transactions["Checking"]
+ end
+
+ test "a source that only resembles the tool's isn't taken as one" do
+ account = existing_account(opening_date: Date.new(2023, 12, 1), opening_balance: 100)
+ account.entries.create!(date: Date.new(2024, 1, 3), amount: 25, currency: "USD", name: "Other",
+ source: "sure-import-session-abc", external_id: "Transaction:monarch-transaction:1", entryable: Transaction.new)
+
+ assert record_ids(convert("Checking" => { target: account }), "Transaction").include?("monarch-transaction:1")
+ end
+
+ test "an entry matched by Monarch ID isn't matched again by date and amount" do
+ account = existing_account(opening_date: Date.new(2023, 12, 1), opening_balance: 100)
+ account.entries.create!(date: Date.new(2024, 1, 2), amount: 10, currency: "USD", name: "Grocer",
+ entryable: Transaction.new(extra: { "monarch" => { "transaction_id" => "1" } }))
+ @exports = MonarchImport::Exports.new(
+ balances_csv: file_fixture("imports/monarch_balances.csv").read,
+ transactions_csv: file_fixture("imports/monarch_transactions.csv").read +
+ "2024-01-02,Grocer,Groceries,Checking,GROCER #12,,-10.00,,Me,false,,,false,6\n"
+ )
+ result = convert("Checking" => { target: account })
+
+ assert_not record_ids(result, "Transaction").include?("monarch-transaction:1")
+ assert record_ids(result, "Transaction").include?("monarch-transaction:6")
+ end
+
+ test "a new account's balance is today's, with later valuations still imported" do
+ @exports = MonarchImport::Exports.new(balances_csv: "Date,Balance,Account\n2024-01-01,100.00,Checking\n2024-01-10,200.00,Checking\n")
+ result = convert(today: Date.new(2024, 1, 4))
+
+ assert_equal "100.00", records_of(result, "Account")["monarch-account:Checking"]["balance"]
+ assert records_of(result, "Valuation").key?("monarch-valuation:Checking:2024-01-10")
+ end
+
+ test "transactions from the Monarch to Sure tool don't count as unmatched" do
+ account = existing_account(opening_date: Date.new(2023, 12, 1), opening_balance: 100)
+ account.entries.create!(date: Date.new(2024, 1, 3), amount: 25, currency: "USD", name: "Older export",
+ source: "sure_import_session:abc", external_id: "Transaction:monarch-transaction:99", entryable: Transaction.new)
+
+ assert_equal 0, convert("Checking" => { target: account }).overlapping_transactions["Checking"]
+ end
+
+ test "Sure's matcher skips a transaction already entered by hand, once" do
+ account = existing_account(opening_date: Date.new(2023, 12, 1), opening_balance: 100)
+ account.entries.create!(date: Date.new(2024, 1, 2), amount: 10, currency: "USD", name: "Groceries", entryable: Transaction.new)
+ exports = MonarchImport::Exports.new(
+ balances_csv: file_fixture("imports/monarch_balances.csv").read,
+ transactions_csv: file_fixture("imports/monarch_transactions.csv").read +
+ "2024-01-02,Grocer,Groceries,Checking,GROCER #12,,-10.00,,Me,false,,,false,6\n"
+ )
+ choices = exports.suggestions.map do |s|
+ MonarchImport::Converter::Choice.new(name: s.name, type: s.type, closed: false, include: true, transactions: true,
+ current_balance: nil, target: (account if s.name == "Checking"))
+ end
+ result = MonarchImport::Converter.new(exports: exports, choices: choices, family: @family, today: Date.new(2024, 1, 4)).result
+
+ assert_equal 1, result.stats["transactions_skipped_already_in_sure"]
+ assert_equal 1, record_ids(result, "Transaction").count { |id| id.in?(%w[monarch-transaction:1 monarch-transaction:6]) }
+ end
+
+ test "existing transactions in the same period that match nothing are counted" do
+ account = existing_account(opening_date: Date.new(2023, 12, 1), opening_balance: 100)
+ account.entries.create!(date: Date.new(2024, 1, 2), amount: 7, currency: "USD", name: "Bakery", entryable: Transaction.new)
+
+ assert_equal 1, convert("Checking" => { target: account }).overlapping_transactions["Checking"]
+ end
+
+ private
+ def choices(overrides = {})
+ @exports.suggestions.map do |suggestion|
+ MonarchImport::Converter::Choice.new(
+ name: suggestion.name, type: suggestion.type, closed: false, include: true, transactions: true,
+ current_balance: nil, target: nil, **overrides.fetch(suggestion.name, {})
+ )
+ end
+ end
+
+ def convert(overrides = {}, today: Date.new(2024, 1, 4), **by_name)
+ MonarchImport::Converter.new(exports: @exports, choices: choices(overrides.merge(by_name)), family: @family, today: today).result
+ end
+
+ def records(type, overrides = {}, **options)
+ convert(overrides, **options).records.select { |r| r["type"] == type }.to_h { |r| [ r["data"]["id"], r["data"] ] }
+ end
+
+ def records_of(result, type)
+ result.records.select { |r| r["type"] == type }.to_h { |r| [ r["data"]["id"], r["data"] ] }
+ end
+
+ def record_ids(result, type)
+ result.records.select { |r| r["type"] == type }.map { |r| r["data"]["id"] }
+ end
+
+ def existing_account(opening_date:, opening_balance:)
+ account = @family.accounts.create!(name: "Sure Checking", balance: opening_balance, currency: "USD", accountable: Depository.new)
+ account.entries.create!(date: opening_date, amount: opening_balance, currency: "USD", name: "Opening balance",
+ entryable: Valuation.new(kind: "opening_anchor"))
+ account
+ end
+end
diff --git a/test/models/monarch_import/exports_test.rb b/test/models/monarch_import/exports_test.rb
new file mode 100644
index 0000000000..37153ed032
--- /dev/null
+++ b/test/models/monarch_import/exports_test.rb
@@ -0,0 +1,84 @@
+require "test_helper"
+
+class MonarchImport::ExportsTest < ActiveSupport::TestCase
+ setup do
+ @exports = MonarchImport::Exports.new(
+ balances_csv: file_fixture("imports/monarch_balances.csv").read,
+ transactions_csv: file_fixture("imports/monarch_transactions.csv").read
+ )
+ end
+
+ test "suggests types from the balances and counts every transaction" do
+ suggestions = @exports.suggestions.index_by(&:name)
+
+ assert_equal({ "Checking" => "Depository", "Card" => "CreditCard", "Old Savings" => "Investment" },
+ suggestions.transform_values(&:type))
+ assert_equal 4, suggestions["Checking"].transactions_count
+ end
+
+ test "lists the most recently active accounts first" do
+ assert_equal "Old Savings", @exports.suggestions.last.name
+ end
+
+ test "only suggests long-inactive accounts as closed" do
+ balances = "Date,Balance,Account\n2023-01-01,5.00,Old\n2024-12-30,5.00,Recent\n"
+ suggestions = MonarchImport::Exports.new(balances_csv: balances).suggestions.index_by(&:name)
+
+ assert suggestions["Old"].closed
+ assert_not suggestions["Recent"].closed
+ end
+
+ test "pending transactions are left out unless asked for" do
+ assert_equal 4, @exports.transactions_for(include_pending: false).size
+ assert_equal 5, @exports.transactions_for(include_pending: true).size
+ end
+
+ test "without a transactions export it is balances only" do
+ exports = MonarchImport::Exports.new(balances_csv: file_fixture("imports/monarch_balances.csv").read)
+
+ assert exports.balances_only?
+ assert_equal %w[Card Checking Old\ Savings], exports.account_names
+ end
+
+ test "rejects dates outside the range Sure imports" do
+ error = assert_raises(MonarchImport::Exports::Error) do
+ MonarchImport::Exports.new(balances_csv: "Date,Balance,Account\n9999-12-31,5.00,Checking\n")
+ end
+ assert_match "9999-12-31", error.message
+ end
+
+ test "rejects amounts that aren't finite" do
+ assert_raises(MonarchImport::Exports::Error) do
+ MonarchImport::Exports.new(balances_csv: "Date,Balance,Account\n2024-01-01,Infinity,Checking\n")
+ end
+ end
+
+ test "rejects rows without an account name" do
+ error = assert_raises(MonarchImport::Exports::Error) do
+ MonarchImport::Exports.new(balances_csv: "Date,Balance,Account\n2024-01-01,5.00, \n")
+ end
+ assert_match "no account name", error.message
+ end
+
+ test "rejects transactions without an Id" do
+ transactions = "Date,Merchant,Category,Account,Amount,Id\n2024-01-02,Grocer,Groceries,Checking,-10.00, \n"
+ error = assert_raises(MonarchImport::Exports::Error) do
+ MonarchImport::Exports.new(balances_csv: file_fixture("imports/monarch_balances.csv").read, transactions_csv: transactions)
+ end
+ assert_match "no Id", error.message
+ end
+
+ test "rejects exports without any accounts" do
+ error = assert_raises(MonarchImport::Exports::Error) do
+ MonarchImport::Exports.new(balances_csv: "Date,Balance,Account\n")
+ end
+ assert_match "don't contain any accounts", error.message
+ end
+
+ test "rejects a file that isn't the right export" do
+ error = assert_raises(MonarchImport::Exports::Error) do
+ MonarchImport::Exports.new(balances_csv: file_fixture("imports/monarch_transactions.csv").read)
+ end
+ assert_match "Balance", error.message
+ end
+end
diff --git a/test/models/monarch_import_test.rb b/test/models/monarch_import_test.rb
new file mode 100644
index 0000000000..95d8e09794
--- /dev/null
+++ b/test/models/monarch_import_test.rb
@@ -0,0 +1,364 @@
+require "test_helper"
+
+class MonarchImportTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:empty)
+ @import = @family.imports.create!(type: "MonarchImport")
+ @import.attach_exports!(
+ balances_csv: file_fixture("imports/monarch_balances.csv").read,
+ transactions_csv: file_fixture("imports/monarch_transactions.csv").read
+ )
+ end
+
+ test "attaching the exports suggests a choice for every account" do
+ mappings = @import.ordered_account_mappings
+
+ assert_equal [ "Checking", "Card", "Old Savings" ], mappings.map(&:key)
+ assert_equal %w[Depository CreditCard Investment], mappings.map(&:type)
+ assert @import.publishable?
+ end
+
+ test "an invalid choice stops the import from being publishable" do
+ mapping("Checking").update_column(:value, { "type" => "Boat" })
+
+ assert_not @import.reload.publishable?
+ end
+
+ test "Sure's recalculated balances match the Monarch history" do
+ mapping("Old Savings").update!(choices: { "closed" => true })
+ publish!
+
+ history = monarch_history
+ { "Checking" => 1, "Card" => -1, "Old Savings" => 1 }.each do |name, sign|
+ account = @family.accounts.find_by!(name: name)
+ assert_balances_match history[name], account, sign
+ end
+
+ old_savings = @family.accounts.find_by!(name: "Old Savings")
+ assert old_savings.disabled?
+ assert_equal 0, old_savings.balances.find_by(date: Date.new(2024, 1, 2)).balance
+ assert_equal 4, @family.entries.where(entryable_type: "Transaction").count
+ end
+
+ test "importing into an existing account keeps it, reproduces the history and reverts cleanly" 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)
+ publish!
+
+ assert_not @family.accounts.exists?(name: "Checking")
+ assert_equal Date.new(2024, 1, 1), opening.reload.date
+ assert_balances_match monarch_history["Checking"], account, 1
+
+ @import.revert
+ assert @import.reload.pending?
+ assert @family.accounts.exists?(account.id)
+ assert_equal [ Date.new(2024, 1, 3), 500 ], [ opening.reload.date, opening.amount ]
+ assert_equal [ opening.id ], account.entries.pluck(:id)
+ end
+
+ test "only a move of an opening balance is still worth publishing, and counts as committed" do
+ account = @family.accounts.create!(name: "My Checking", balance: 500, currency: "USD", accountable: Depository.new)
+ account.entries.create!(date: Date.new(2024, 1, 3), amount: 500, currency: "USD", name: "Opening balance",
+ entryable: Valuation.new(kind: "opening_anchor"))
+ @import.attach_exports!(balances_csv: "Date,Balance,Account\n2024-01-01,100.00,Checking\n")
+ mapping("Checking").update!(mappable: account)
+
+ assert @import.changes_existing_records?
+ assert_not @import.data_committed?
+ publish!
+ assert_empty @import.entries
+ assert_empty @import.accounts
+ assert @import.reload.data_committed?
+ end
+
+ test "deleting an import that failed after committing puts the opening balance back" 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)
+ publish!
+ @import.update!(status: :failed)
+
+ @import.destroy!
+ assert_equal [ Date.new(2024, 1, 3), 500 ], [ opening.reload.date, opening.amount ]
+ end
+
+ test "an opening balance in another currency moves in the account's and comes back in its own" 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: "EUR", name: "Opening balance",
+ entryable: Valuation.new(kind: "opening_anchor"))
+ ExchangeRate.create!(date: Date.new(2024, 1, 3), from_currency: "EUR", to_currency: "USD", rate: 1)
+ mapping("Checking").update!(mappable: account)
+ publish!
+
+ assert_equal [ Date.new(2024, 1, 1), 100, "USD" ], [ opening.reload.date, opening.amount, opening.currency ]
+ @import.revert
+ assert_equal [ Date.new(2024, 1, 3), 500, "EUR" ], [ opening.reload.date, opening.amount, opening.currency ]
+ end
+
+ test "an opening balance edited after the conversion read it 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)
+ @import.conversion
+ opening.update_column(:amount, 1)
+
+ @import.publish
+ assert @import.reload.failed?
+ assert_match "My Checking", @import.error
+ assert_equal 1, opening.reload.amount
+ end
+
+ test "a lost job that committed is completed, not failed" do
+ publish!
+ @import.update_columns(status: "importing", updated_at: 2.hours.ago)
+
+ assert @import.force_fail!
+ assert @import.reload.complete?
+ end
+
+ test "the API reports an import with every account skipped as not publishable" do
+ @import.account_mappings.each { |m| m.update!(choices: { "include" => false }) }
+
+ assert_not @import.reload.publishable_from_validation_stats?(invalid_rows_count: 0)
+ end
+
+ test "accounts with holdings or trades can't be destinations" do
+ plain = @family.accounts.create!(name: "Plain", balance: 0, currency: "USD", accountable: Investment.new)
+ traded = @family.accounts.create!(name: "Traded", balance: 0, currency: "USD", accountable: Investment.new)
+ security = Security.create!(ticker: "MONA", name: "Monarch Test")
+ traded.entries.create!(date: Date.new(2024, 1, 2), amount: 10, currency: "USD", name: "Buy",
+ entryable: Trade.new(security: security, qty: 1, price: 10, currency: "USD"))
+
+ targets = Import::MonarchAccountMapping.target_accounts_for(@import)
+ assert_includes targets, plain
+ assert_not_includes targets, traded
+ end
+
+ test "a skipped mapping's destination doesn't need write access" do
+ account = @family.accounts.create!(name: "Private", balance: 0, currency: "USD", accountable: Depository.new, owner: users(:empty))
+ mapping("Checking").update!(mappable: account, choices: { "include" => false })
+
+ assert_empty @import.preexisting_target_account_ids
+ end
+
+ test "publishing needs write access to the existing accounts it imports into" do
+ account = @family.accounts.create!(name: "Private", balance: 0, currency: "USD", accountable: Depository.new, owner: users(:empty))
+ mapping("Checking").update!(mappable: account)
+
+ assert_equal [ account.id ], @import.preexisting_target_account_ids
+ assert @import.accounts_writable_by?(users(:empty))
+ assert_not @import.accounts_writable_by?(users(:josh))
+ end
+
+ test "an existing account marked closed is disabled, and enabled again on undo" do
+ account = @family.accounts.create!(name: "My Savings", balance: 10, currency: "USD", accountable: Depository.new)
+ mapping("Old Savings").update!(mappable: account, choices: { "closed" => true })
+ assert @import.changes_existing_records?
+ publish!
+
+ assert account.reload.disabled?
+ @import.revert
+ assert account.reload.active?
+ end
+
+ test "undo leaves an account that was reopened and closed again" do
+ account = @family.accounts.create!(name: "My Savings", balance: 10, currency: "USD", accountable: Depository.new)
+ mapping("Old Savings").update!(mappable: account, choices: { "closed" => true })
+ publish!
+ account.reload.enable!
+ travel 1.minute do
+ account.disable!
+ end
+
+ @import.revert
+ assert account.reload.disabled?
+ end
+
+ test "a disabled destination marked Open is enabled, and disabled again on undo" do
+ account = @family.accounts.create!(name: "My Savings", balance: 10, currency: "USD", accountable: Depository.new)
+ account.disable!
+ disabled_at = account.reload.disabled_at
+ mapping("Old Savings").update!(mappable: account, choices: { "closed" => false })
+ publish!
+
+ assert account.reload.active?
+ @import.revert
+ assert account.reload.disabled?
+ assert_in_delta disabled_at, account.disabled_at, 1.second
+ end
+
+ test "deleting a published import puts a moved opening balance back" 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)
+ publish!
+
+ @import.destroy!
+ assert_equal [ Date.new(2024, 1, 3), 500 ], [ opening.reload.date, opening.amount ]
+ end
+
+ test "an unchanged balance is compared with what the form showed for the saved destination" do
+ loan = @family.accounts.create!(name: "My Loan", balance: 0, currency: "USD", accountable: Loan.new)
+ mapping("Checking").update!(mappable: loan)
+ shown = @import.suggested_current_balance(mapping("Checking"))
+
+ @import.apply_account_choices!(
+ { mapping("Checking").id => { type: "Depository", include: "1", target_id: loan.id, current_balance: shown } },
+ target_accounts: @family.accounts
+ )
+
+ assert_nil mapping("Checking").current_balance
+ end
+
+ test "renamed accounts are created with the new name" do
+ @import.apply_account_choices!(
+ { mapping("Checking").id => { name: "Everyday", type: "Depository", include: "1", transactions: "1" } },
+ target_accounts: @family.accounts
+ )
+ publish!
+
+ assert @family.accounts.exists?(name: "Everyday")
+ assert_not @family.accounts.exists?(name: "Checking")
+ end
+
+ test "an unchanged or blank name keeps Monarch's" do
+ @import.apply_account_choices!(
+ { mapping("Checking").id => { name: "Checking", type: "Depository", include: "1" },
+ mapping("Card").id => { name: " ", type: "CreditCard", include: "1" } },
+ target_accounts: @family.accounts
+ )
+
+ assert_nil mapping("Checking").choices["name"]
+ assert_equal "Card", mapping("Card").account_name
+ end
+
+ test "importing the same exports into the accounts they created skips every transaction" do
+ publish!
+ second = @family.imports.create!(type: "MonarchImport")
+ second.attach_exports!(
+ balances_csv: file_fixture("imports/monarch_balances.csv").read,
+ transactions_csv: file_fixture("imports/monarch_transactions.csv").read
+ )
+ %w[Checking Card Old\ Savings].each do |name|
+ second.account_mappings.find_by!(key: name).update!(mappable: @family.accounts.find_by!(name: name))
+ end
+
+ assert_no_difference -> { @family.entries.where(entryable_type: "Transaction").count } do
+ second.reload.publish
+ end
+ assert second.reload.complete?, second.error
+ assert_balances_match monarch_history["Checking"], @family.accounts.find_by!(name: "Checking"), 1
+ end
+
+ # Provider handoff: an account imported from Monarch and later linked to a
+ # bank connection. The sync claims the imported transaction instead of adding
+ # a copy, keeps what Monarch imported, and a repeat Monarch import still
+ # recognises it by its Monarch ID.
+ test "a later provider sync claims imported transactions instead of duplicating them" do
+ publish!
+ checking = @family.accounts.find_by!(name: "Checking")
+ imported = checking.entries.find_by!(name: "Grocer")
+ transactions_before = checking.entries.where(entryable_type: "Transaction").count
+
+ synced = Account::ProviderImportAdapter.new(checking).import_transaction(
+ external_id: "sfin-1", amount: 10, currency: "USD", date: Date.new(2024, 1, 2), name: "GROCER #12 POS", source: "simplefin"
+ )
+
+ assert_equal imported.id, synced.id
+ assert_equal transactions_before, checking.entries.where(entryable_type: "Transaction").count
+ imported.reload
+ assert_equal [ "sfin-1", "simplefin", "Grocer" ], [ imported.external_id, imported.source, imported.name ]
+ assert_equal "1", imported.transaction.extra.dig("monarch", "transaction_id")
+
+ second = @family.imports.create!(type: "MonarchImport")
+ second.attach_exports!(balances_csv: file_fixture("imports/monarch_balances.csv").read,
+ transactions_csv: file_fixture("imports/monarch_transactions.csv").read)
+ second.account_mappings.find_by!(key: "Checking").update!(mappable: checking)
+ assert_equal 3, second.conversion.stats["transactions_skipped_already_in_sure"]
+ end
+
+ test "an existing account takes only one Monarch account" do
+ account = @family.accounts.create!(name: "My Checking", balance: 0, currency: "USD", accountable: Depository.new)
+ mapping("Checking").update!(mappable: account)
+
+ error = assert_raises(ActiveRecord::RecordInvalid) { mapping("Card").update!(mappable: account) }
+ assert_match "already the destination", error.message
+ end
+
+ test "a destination can move between Monarch accounts in one save" do
+ account = @family.accounts.create!(name: "My Checking", balance: 0, currency: "USD", accountable: Depository.new)
+ mapping("Checking").update!(mappable: account)
+
+ @import.apply_account_choices!({
+ mapping("Checking").id => { type: "Depository", include: "1", target_id: "" },
+ mapping("Card").id => { type: "CreditCard", include: "1", target_id: account.id }
+ }, target_accounts: @family.accounts)
+
+ assert_equal [ nil, account ], [ mapping("Checking").target, mapping("Card").target ]
+ end
+
+ test "undo keeps an opening balance edited after 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)
+ publish!
+ opening.reload.update!(amount: 123)
+
+ @import.revert
+
+ assert_equal 123, opening.reload.amount
+ assert_equal [ "My Checking" ], @import.reload.opening_balances_kept_after_revert
+ end
+
+ test "existing categories and merchants are reused unchanged" do
+ category = @family.categories.create!(name: "Groceries", color: "#123456", lucide_icon: "carrot", classification_unused: "expense")
+ merchant = @family.merchants.create!(name: "Grocer", color: "#abcdef")
+ publish!
+
+ assert_equal [ "#123456", "carrot" ], [ category.reload.color, category.lucide_icon ]
+ assert_equal "#abcdef", merchant.reload.color
+ transaction = @family.entries.find_by!(name: "Grocer").entryable
+ assert_equal [ category.id, merchant.id ], [ transaction.category_id, transaction.merchant_id ]
+ end
+
+ test "reverting removes the accounts it created" do
+ publish!
+ @import.revert
+
+ assert_empty @family.accounts.reload
+ assert @import.reload.pending?
+ end
+
+ private
+ def mapping(name)
+ @import.account_mappings.find_by!(key: name)
+ end
+
+ def publish!
+ @import.reload.publish
+ assert @import.reload.complete?, @import.error
+ end
+
+ def monarch_history
+ MonarchImport::Exports.new(balances_csv: file_fixture("imports/monarch_balances.csv").read).balances
+ end
+
+ # Runs Sure's own balance calculation, then checks every day of the
+ # Monarch history against what Sure stored.
+ def assert_balances_match(history, account, sign)
+ Balance::Materializer.new(account, strategy: :forward).materialize_balances
+ stored = account.balances.where(currency: account.currency).pluck(:date, :balance).to_h
+
+ history.each do |date, balance|
+ expected = balance * sign
+ actual = stored.fetch(date) { stored.select { |day, _| day < date }.max_by(&:first)&.last }
+ assert_equal expected, actual, "#{account.name} on #{date}"
+ end
+ end
+end
diff --git a/test/system/imports_test.rb b/test/system/imports_test.rb
index dd398490d8..dbf5db188c 100644
--- a/test/system/imports_test.rb
+++ b/test/system/imports_test.rb
@@ -263,4 +263,42 @@ class ImportsTest < ApplicationSystemTestCase
click_on "Back to dashboard"
end
+
+ test "monarch import" do
+ visit new_import_path
+
+ click_on "Financial Tools"
+ click_on "Import from Monarch"
+
+ attach_file "import[balances_file]", file_fixture("imports/monarch_balances.csv")
+ attach_file "import[transactions_file]", file_fixture("imports/monarch_transactions.csv")
+ click_on "Upload exports"
+
+ assert_selector "h1", text: "Check each Monarch account"
+ find("select[aria-label='Type of Card']").select("Loan")
+ click_toggle "Old Savings is open"
+ assert_selector "td", text: "Closed"
+ click_toggle "Transactions for every account"
+ assert_no_selector "input[type=checkbox][data-checkbox-group=transactions]:checked", visible: :all
+ click_on "Review import"
+
+ assert_selector "h1", text: "Confirm your import data"
+ click_on "Publish import"
+
+ assert_text "Import in progress"
+ perform_enqueued_jobs
+ click_on "Check status"
+ assert_text "Import successful"
+
+ accounts = @user.family.accounts
+ assert_equal "Loan", accounts.find_by!(name: "Card").accountable_type
+ assert accounts.find_by!(name: "Old Savings").disabled?
+ assert_equal 0, accounts.where(name: %w[Checking Card]).joins(:entries).where(entries: { entryable_type: "Transaction" }).count
+ end
+
+ private
+ # DS::Toggle hides its checkbox; people click the switch, its label.
+ def click_toggle(aria_label)
+ find("input[aria-label='#{aria_label}']", visible: :all).find(:xpath, "following-sibling::label").click
+ end
end