Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Export and import provider-assigned merchants, reuse existing taxonomy on Sure import (#3671)

Mikael Møller63c636208f1d
diff --git a/app/models/family/data_exporter.rb b/app/models/family/data_exporter.rb
index 49a7603131..b02ad94ba2 100644
--- a/app/models/family/data_exporter.rb
+++ b/app/models/family/data_exporter.rb
@@ -312,6 +312,27 @@ class Family::DataExporter
}.to_json
end
+ # Export provider-assigned merchants (auto-detected by bank sync/AI enrichment)
+ # referenced by this family's transactions and recurring transactions. These
+ # are shared across every family on the instance, so only the ones actually
+ # in use here are included -- see #3113.
+ referenced_provider_merchants.each do |merchant|
+ lines << {
+ type: "ProviderMerchant",
+ data: {
+ id: merchant.id,
+ name: merchant.name,
+ source: merchant.source,
+ provider_merchant_id: merchant.provider_merchant_id,
+ color: merchant.color,
+ logo_url: merchant.logo_url,
+ website_url: merchant.website_url,
+ created_at: merchant.created_at,
+ updated_at: merchant.updated_at
+ }
+ }.to_json
+ end
+
# Export recurring transactions after accounts and merchants so import can remap dependencies.
@family.recurring_transactions.includes(:account, :merchant).find_each do |recurring_transaction|
lines << {
@@ -569,6 +590,16 @@ class Family::DataExporter
end
end
+ def referenced_provider_merchants
+ @referenced_provider_merchants ||= ProviderMerchant.where(id: referenced_merchant_ids).to_a
+ end
+
+ def referenced_merchant_ids
+ transaction_ids = @family.transactions.where.not(merchant_id: nil).distinct.pluck(:merchant_id)
+ recurring_ids = @family.recurring_transactions.where.not(merchant_id: nil).distinct.pluck(:merchant_id)
+ (transaction_ids + recurring_ids).uniq
+ end
+
def family_transaction_ids
@family_transaction_ids ||= exportable_transactions.select(:id)
end
diff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rb
index 67137d3900..04c1c49867 100644
--- a/app/models/family/data_importer.rb
+++ b/app/models/family/data_importer.rb
@@ -31,7 +31,7 @@ class Family::DataImporter
end
end
- SUPPORTED_TYPES = %w[Account Balance Category Tag Merchant RecurringTransaction RecurrenceRule RecurringOccurrence RecurringAllocation RecurringPriceChange RecurringMatchRejection Transaction Transfer RejectedTransfer Trade Holding Valuation Budget BudgetCategory Rule].freeze
+ SUPPORTED_TYPES = %w[Account Balance Category Tag Merchant ProviderMerchant RecurringTransaction RecurrenceRule RecurringOccurrence RecurringAllocation RecurringPriceChange RecurringMatchRejection Transaction Transfer RejectedTransfer Trade Holding Valuation Budget BudgetCategory Rule].freeze
ACCOUNTABLE_TYPE_CLASSES = {
"Depository" => Depository, "Investment" => Investment, "Crypto" => Crypto,
"Property" => Property, "Vehicle" => Vehicle, "OtherAsset" => OtherAsset,
@@ -60,6 +60,7 @@ class Family::DataImporter
"Category" => "categories",
"Tag" => "tags",
"Merchant" => "merchants",
+ "ProviderMerchant" => "provider_merchants",
"RecurringTransaction" => "recurring_transactions",
"RecurrenceRule" => "recurrence_rules",
"RecurringOccurrence" => "recurring_occurrences",
@@ -114,6 +115,7 @@ class Family::DataImporter
import_categories(records["Category"] || [])
import_tags(records["Tag"] || [])
import_merchants(records["Merchant"] || [])
+ import_provider_merchants(records["ProviderMerchant"] || [])
import_recurring_transactions(records["RecurringTransaction"] || [])
import_transactions(records["Transaction"] || [])
# Bills: rules and occurrences need their series, allocations and the
@@ -417,7 +419,12 @@ class Family::DataImporter
# Store parent relationship for second pass
parent_mappings[old_id] = parent_id if parent_id.present?
+ # A same-named category almost always exists already: onboarding seeds a
+ # default set for every family, so a plain (non-session) import would
+ # otherwise try to create a second "Groceries" and hit the unique index.
+ # Preflight already treats this as a reusable match, not a collision.
category = mapped_record(:categories, old_id, @family.categories, record_type: "Category")
+ category ||= @family.categories.find_by(name: data["name"])
created = category.blank?
category ||= @family.categories.build
@@ -452,6 +459,7 @@ class Family::DataImporter
require_source_id!("Tag", old_id)
tag = mapped_record(:tags, old_id, @family.tags, record_type: "Tag")
+ tag ||= @family.tags.find_by(name: data["name"])
created = tag.blank?
tag ||= @family.tags.build
color = data["color"] || tag.color
@@ -476,6 +484,7 @@ class Family::DataImporter
require_source_id!("Merchant", old_id)
merchant = mapped_record(:merchants, old_id, @family.merchants, record_type: "Merchant")
+ merchant ||= @family.merchants.find_by(name: data["name"])
created = merchant.blank?
merchant ||= @family.merchants.build
@@ -484,12 +493,60 @@ class Family::DataImporter
color: data["color"],
logo_url: data["logo_url"]
)
+ # Older or hand-built files omit website_url; don't clear an existing one.
+ merchant.website_url = data["website_url"] if data.key?("website_url")
merchant.save!
map_source!(:merchants, old_id, merchant)
increment_summary("Merchant", created ? :created : :updated)
end
end
+ # ProviderMerchant rows share the :merchants id-mapping namespace with
+ # Merchant, so Transaction/RecurringTransaction merchant_id resolution below
+ # needs no changes to accept either source. A ProviderMerchant is shared
+ # across every family on the instance, so an existing match is reused as-is:
+ # an import never writes to a record it did not create.
+ def import_provider_merchants(records)
+ records.each do |record|
+ data = record["data"]
+ old_id = data["id"]
+
+ require_source_id!("ProviderMerchant", old_id)
+
+ source = data["source"].to_s
+ unless ProviderMerchant.sources.key?(source)
+ invalid_record!("ProviderMerchant", "source", data["source"])
+ next
+ end
+
+ merchant = ProviderMerchant.find_by_import_data(data, source)
+ merchant ||= create_provider_merchant(data, source)
+ created = merchant.previously_new_record?
+
+ map_source!(:merchants, old_id, merchant)
+ increment_summary("ProviderMerchant", created ? :created : :updated)
+ end
+ end
+
+ # The savepoint keeps a lost race from aborting the surrounding import transaction.
+ # A race usually surfaces as the name-uniqueness validation (RecordInvalid) rather
+ # than the index (RecordNotUnique); either way, reuse the winner if it exists and
+ # let anything else propagate.
+ def create_provider_merchant(data, source)
+ ProviderMerchant.transaction(requires_new: true) do
+ ProviderMerchant.create!(
+ name: data["name"],
+ source: source,
+ provider_merchant_id: data["provider_merchant_id"].presence,
+ color: data["color"],
+ logo_url: data["logo_url"],
+ website_url: data["website_url"]
+ )
+ end
+ rescue ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid
+ ProviderMerchant.find_by_import_data(data, source) || raise
+ end
+
def import_recurring_transactions(records)
records.each do |record|
data = record["data"]
@@ -509,7 +566,11 @@ class Family::DataImporter
next if data["account_id"].present? && new_account_id.blank?
new_merchant_id = remap_optional_id(:merchants, data["merchant_id"], record_type: "RecurringTransaction")
- next if data["merchant_id"].present? && new_merchant_id.blank?
+ # A series needs a merchant or a name; a named one imports without its merchant.
+ if data["merchant_id"].present? && new_merchant_id.blank? && data["name"].blank?
+ increment_summary("RecurringTransaction", :skipped)
+ next
+ end
expected_day_of_month = recurring_expected_day_for(data["expected_day_of_month"])
next unless expected_day_of_month
diff --git a/app/models/provider_merchant.rb b/app/models/provider_merchant.rb
index ce27634eb3..97e7b723ea 100644
--- a/app/models/provider_merchant.rb
+++ b/app/models/provider_merchant.rb
@@ -4,6 +4,22 @@ class ProviderMerchant < Merchant
validates :name, uniqueness: { scope: [ :source ] }
validates :source, presence: true
+ def self.find_by_import_data(data, source)
+ provider_merchant_id = data["provider_merchant_id"].presence
+ by_provider_id = find_by(provider_merchant_id: provider_merchant_id, source: source) if provider_merchant_id
+ by_provider_id || find_by(name: data["name"], source: source)
+ end
+
+ # color is deliberately not compared: nothing ever sets it on a ProviderMerchant.
+ def import_diff(data)
+ %w[website_url name provider_merchant_id].filter_map do |field|
+ imported_value = data[field].presence
+ next if imported_value.blank? || imported_value == self[field]
+
+ { field: field, imported_value: imported_value, kept_value: self[field] }
+ end
+ end
+
# Convert this ProviderMerchant to a FamilyMerchant for a specific family.
# Only affects transactions belonging to that family.
# Returns the newly created FamilyMerchant.
diff --git a/app/models/sure_import.rb b/app/models/sure_import.rb
index 4593ec4d36..a4e213953a 100644
--- a/app/models/sure_import.rb
+++ b/app/models/sure_import.rb
@@ -148,7 +148,7 @@ class SureImport < Import
update!(summary: result[:summary]) if has_attribute?(:summary)
end
- record_readback_verification!(before_counts:)
+ record_readback_verification!(before_counts:, reused_counts: reused_counts_from(result[:summary]))
result
rescue => error
record_failed_readback_verification!(before_counts:, error:)
@@ -270,9 +270,15 @@ class SureImport < Import
)
end
- def record_readback_verification!(before_counts:)
+ # Category/Tag/Merchant rows matched to an existing family record by name are
+ # "updated", not created, so they add nothing to the readback delta.
+ def reused_counts_from(summary)
+ %w[categories tags merchants].index_with { |key| (summary || {}).dig(key, "updated").to_i }
+ end
+
+ def record_readback_verification!(before_counts:, reused_counts: {})
update_columns(
- readback_verification: build_readback_verification(before_counts:, status_for_mismatch: "mismatch"),
+ readback_verification: build_readback_verification(before_counts:, status_for_mismatch: "mismatch", reused_counts:),
updated_at: Time.current
)
end
@@ -291,12 +297,13 @@ class SureImport < Import
Rails.logger.warn("Failed to record Sure import readback verification for import #{id}: #{verification_error.message}")
end
- def build_readback_verification(before_counts:, status_for_mismatch:)
+ def build_readback_verification(before_counts:, status_for_mismatch:, reused_counts: {})
after_counts = readback_count_snapshot
actual_delta_counts = delta_counts(before_counts, after_counts)
expected_counts = normalized_expected_record_counts
+ expected_creations = expected_counts.merge(reused_counts) { |_key, expected, reused| [ expected - reused, 0 ].max }
checked_counts = (actual_delta_counts.keys | expected_counts.keys).index_with do |key|
- expected_counts.fetch(key, 0).to_i
+ expected_creations.fetch(key, 0).to_i
end
mismatches = checked_counts.each_with_object({}) do |(key, expected_count), result|
actual_count = actual_delta_counts.fetch(key, 0)
@@ -316,6 +323,7 @@ class SureImport < Import
"after_counts" => after_counts,
"actual_delta_counts" => actual_delta_counts,
"checked_counts" => checked_counts,
+ "reused_record_counts" => reused_counts.select { |_key, count| count.positive? },
"mismatches" => mismatches
}
end
diff --git a/app/models/sure_import/preflight.rb b/app/models/sure_import/preflight.rb
index 68c7335b1d..ba441f7e90 100644
--- a/app/models/sure_import/preflight.rb
+++ b/app/models/sure_import/preflight.rb
@@ -8,6 +8,33 @@ class SureImport::Preflight
def error_messages = errors.map { |error| error[:message] }
def error_message = valid? ? "" : ([ "Sure import preflight failed:" ] + error_messages).join("\n")
def payload = { valid: valid?, stats: stats, errors: errors, warnings: warnings }
+
+ # Rows that will import without a merchant because this export predates
+ # provider-merchant support (#3113) -- surfaced as a single friendly count
+ # rather than one line per row, which is what skipped_missing_merchant_reference
+ # warnings would otherwise read as.
+ def skipped_missing_merchant_count
+ warnings.count { |warning| warning[:code] == "skipped_missing_merchant_reference" }
+ end
+
+ # Rows whose Category/Tag/Merchant name already exists in the family and will
+ # be reused instead of duplicated -- same rollup rationale as above.
+ def reused_taxonomy_count
+ warnings.count { |warning| warning[:code] == "existing_taxonomy_collision" }
+ end
+
+ # Shared ProviderMerchants that already exist with different details than the
+ # file carries. The existing record is kept as-is, so the user sees what differs.
+ # Unnamed recurring transactions whose merchant is missing can't be imported
+ # (a series needs a merchant or a name), so they are skipped rather than
+ # imported without a merchant.
+ def skipped_unnamed_recurring_count
+ warnings.count { |warning| warning[:code] == "skipped_unnamed_recurring" }
+ end
+
+ def provider_merchant_diff_warnings
+ warnings.select { |warning| warning[:code] == "provider_merchant_diff" }
+ end
end
REQUIRED_FIELDS = {
@@ -16,6 +43,7 @@ class SureImport::Preflight
"Category" => %w[id name],
"Tag" => %w[id name],
"Merchant" => %w[id name],
+ "ProviderMerchant" => %w[id name source],
"RecurringTransaction" => %w[id amount expected_day_of_month last_occurrence_date next_expected_date],
"Transaction" => %w[id account_id date amount],
"Transfer" => %w[inflow_transaction_id outflow_transaction_id],
@@ -33,9 +61,27 @@ class SureImport::Preflight
# a warning rather than a blocking error.
SOFT_REFERENCE_TYPES = %w[RejectedTransfer].freeze
+ # merchant_id specifically (not account_id/category_id) is advisory on these
+ # types: the importer already nulls an unresolved merchant_id rather than
+ # failing (see Family::DataImporter#import_transactions), and an export taken
+ # before #3113 shipped never included the provider-assigned merchants a
+ # transaction could reference -- so a dangling merchant_id is expected on
+ # older exports, not a sign of corrupt data.
+ SOFT_REFERENCE_FIELDS = {
+ "Transaction" => %w[merchant_id],
+ "RecurringTransaction" => %w[merchant_id],
+ "Transaction split line" => %w[merchant_id]
+ }.freeze
+
TAXONOMY_TYPES = { "Category" => :categories, "Tag" => :tags, "Merchant" => :merchants }.freeze
+ # ProviderMerchant shares the :merchants reference namespace with Merchant (a
+ # Transaction/RecurringTransaction's merchant_id can point at either), but it is
+ # a cross-family shared record, not family-owned taxonomy -- so it's deliberately
+ # excluded from TAXONOMY_TYPES, whose collision/duplicate-name checks assume
+ # family-scoped uniqueness.
SOURCE_ID_TYPES = TAXONOMY_TYPES.merge(
+ "ProviderMerchant" => :merchants,
"Account" => :accounts,
"RecurringTransaction" => :recurring_transactions,
"Transaction" => :transactions,
@@ -77,6 +123,7 @@ class SureImport::Preflight
validate_accountables
validate_split_lines
validate_references
+ validate_provider_merchant_diffs
validate_duplicate_valuations
Result.new(
errors: @errors,
@@ -149,15 +196,19 @@ class SureImport::Preflight
end
end
+ # A name collision is advisory, not blocking: Family::DataImporter reuses the
+ # family's existing Category/Tag/Merchant with that name (a common case for
+ # Category/Tag on a fresh family, whose onboarding seeds a default set) rather
+ # than trying to create a second record with the same name.
def validate_taxonomy_collisions
TAXONOMY_TYPES.each do |type, association|
existing_names = family.public_send(association).pluck(:name).to_set
@records[type].each do |record|
name = record[:data]["name"].to_s
next if name.blank? || !existing_names.include?(name)
- add_error(
+ add_warning(
:existing_taxonomy_collision,
- "Line #{record[:line_number]} #{type} name #{name.inspect} already exists in this family."
+ "Line #{record[:line_number]} #{type} name #{name.inspect} already exists in this family and will be reused."
)
end
end
@@ -278,11 +329,19 @@ class SureImport::Preflight
}
if SOFT_REFERENCE_TYPES.include?(type)
add_warning(:skipped_missing_reference, I18n.t("sure_import.preflight.skipped_missing_reference", **interpolations))
+ elsif unnamed_recurring_without_merchant?(record, type, field)
+ add_warning(:skipped_unnamed_recurring, I18n.t("sure_import.preflight.skipped_unnamed_recurring", **interpolations))
+ elsif SOFT_REFERENCE_FIELDS.fetch(type, []).include?(field)
+ add_warning(:skipped_missing_merchant_reference, I18n.t("sure_import.preflight.skipped_missing_merchant_reference", **interpolations))
else
add_error(:missing_reference, I18n.t("sure_import.preflight.missing_reference", **interpolations))
end
end
+ def unnamed_recurring_without_merchant?(record, type, field)
+ type == "RecurringTransaction" && field == "merchant_id" && record[:data]["name"].blank?
+ end
+
def validate_tag_references(record, type)
Array(record[:data]["tag_ids"]).each do |tag_id|
validate_reference(record, type, :tags, "tag_ids", tag_id)
@@ -321,9 +380,35 @@ class SureImport::Preflight
end
end
+ def validate_provider_merchant_diffs
+ @records["ProviderMerchant"].each do |record|
+ data = record[:data]
+ source = data["source"].to_s
+ next unless ProviderMerchant.sources.key?(source)
+
+ diff = ProviderMerchant.find_by_import_data(data, source)&.import_diff(data)
+ next if diff.blank?
+
+ add_warning(
+ :provider_merchant_diff,
+ I18n.t(
+ "sure_import.preflight.provider_merchant_diff",
+ line: record[:line_number],
+ name: data["name"],
+ fields: diff.pluck(:field).join(", ")
+ ),
+ details: { merchant_name: data["name"], diff: diff }
+ )
+ end
+ end
+
def blank_required_value?(value) = value.blank?
def add_error(code, message) = @errors << { code: code.to_s, message: message }
- def add_warning(code, message) = @warnings << { code: code.to_s, message: message }
+ def add_warning(code, message, details: nil)
+ warning = { code: code.to_s, message: message }
+ warning[:details] = details if details
+ @warnings << warning
+ end
end
diff --git a/app/views/imports/_ready.html.erb b/app/views/imports/_ready.html.erb
index 9e2e0236d8..85b8e93ad9 100644
--- a/app/views/imports/_ready.html.erb
+++ b/app/views/imports/_ready.html.erb
@@ -2,6 +2,11 @@
<% dry_run = import.dry_run %>
<% resources_with_counts = dry_run.select { |_, count| count > 0 }.filter_map { |key, count| [dry_run_resource(key), count] if dry_run_resource(key) } %>
<% import_summary_empty = resources_with_counts.empty? %>
+<% sure_preflight_result = import.is_a?(SureImport) ? import.sure_preflight : nil %>
+<% missing_merchant_count = sure_preflight_result&.skipped_missing_merchant_count.to_i %>
+<% skipped_recurring_count = sure_preflight_result&.skipped_unnamed_recurring_count.to_i %>
+<% reused_taxonomy_count = sure_preflight_result&.reused_taxonomy_count.to_i %>
+<% provider_merchant_diffs = sure_preflight_result&.provider_merchant_diff_warnings || [] %>
<div class="text-center space-y-2 mb-4 mx-auto max-w-md">
<h1 class="text-3xl text-primary font-medium"><%= t(".title") %></h1>
@@ -9,6 +14,58 @@
</div>
<div class="mx-auto max-w-2xl space-y-4">
+ <% if missing_merchant_count > 0 || skipped_recurring_count > 0 %>
+ <%= render DS::Alert.new(
+ variant: :warning,
+ title: t(".missing_merchant_warning_title"),
+ message: [
+ (t(".missing_merchant_warning_description", count: missing_merchant_count) if missing_merchant_count > 0),
+ (t(".skipped_recurring_description", count: skipped_recurring_count) if skipped_recurring_count > 0)
+ ].compact.join(" ")
+ ) %>
+ <% end %>
+
+ <% if reused_taxonomy_count > 0 %>
+ <%= render DS::Alert.new(
+ variant: :info,
+ title: t(".reused_taxonomy_notice_title"),
+ message: t(".reused_taxonomy_notice_description", count: reused_taxonomy_count)
+ ) %>
+ <% end %>
+
+ <% if provider_merchant_diffs.any? %>
+ <div>
+ <%= render DS::Alert.new(
+ variant: :info,
+ title: t(".provider_merchant_diff_title"),
+ message: t(".provider_merchant_diff_description", count: provider_merchant_diffs.size)
+ ) %>
+
+ <%= render DS::Disclosure.new(variant: :inline, body_class: "space-y-3 mt-2 pl-4 border-l border-primary") do |disclosure| %>
+ <% disclosure.with_summary_content do %>
+ <span class="text-sm text-secondary hover:text-primary flex items-center gap-1 py-2">
+ <%= icon "chevron-right", size: "sm", class: "group-open:rotate-90 transition-transform" %>
+ <%= t(".provider_merchant_diff_summary") %>
+ </span>
+ <% end %>
+
+ <% provider_merchant_diffs.each do |warning| %>
+ <div class="text-sm space-y-1">
+ <p class="text-primary font-medium"><%= warning.dig(:details, :merchant_name) %></p>
+ <% warning.dig(:details, :diff).each do |change| %>
+ <p class="text-secondary">
+ <%= t(".provider_merchant_diff_row",
+ field: t(".provider_merchant_diff_fields.#{change[:field]}"),
+ kept: change[:kept_value].presence || t(".provider_merchant_diff_none"),
+ imported: change[:imported_value]) %>
+ </p>
+ <% end %>
+ </div>
+ <% end %>
+ <% end %>
+ </div>
+ <% end %>
+
<div class="bg-container-inset rounded-xl p-1 space-y-1">
<div class="flex justify-between items-center text-xs font-medium text-secondary uppercase px-5 py-3">
<p><%= t(".summary_item_label") %></p>
diff --git a/config/locales/models/sure_import/preflight/en.yml b/config/locales/models/sure_import/preflight/en.yml
index f446b14f86..46e0e3c741 100644
--- a/config/locales/models/sure_import/preflight/en.yml
+++ b/config/locales/models/sure_import/preflight/en.yml
@@ -4,3 +4,6 @@ en:
preflight:
missing_reference: "Line %{line} %{type} references missing %{field} %{value}."
skipped_missing_reference: "Line %{line} %{type} references missing %{field} %{value}. It will be skipped during import."
+ skipped_missing_merchant_reference: "Line %{line} %{type} references a merchant (%{value}) that isn't included in this export. This can happen with an export taken before provider-assigned merchants were added to Sure exports. It will import without that merchant."
+ skipped_unnamed_recurring: "Line %{line} %{type} has no name and references a merchant (%{value}) that isn't included in this export. It will be skipped during import."
+ provider_merchant_diff: "Line %{line} ProviderMerchant %{name} already exists with a different %{fields}. The existing merchant will be kept."
diff --git a/config/locales/views/imports/en.yml b/config/locales/views/imports/en.yml
index 49d9771340..d4dedfdc96 100644
--- a/config/locales/views/imports/en.yml
+++ b/config/locales/views/imports/en.yml
@@ -467,6 +467,50 @@ en:
empty_summary: We could not find any importable records in this file. It may be empty, or the lines may not match the expected export format (each line should be a JSON object with "type" and "data" keys, using types this import supports).
publish_import: Publish import
back_to_imports: Back to imports
+ missing_merchant_warning_title: Some merchants are missing from this export
+ missing_merchant_warning_description:
+ one: >-
+ 1 merchant reference in this file points to a merchant that isn't included. This can happen
+ with an export taken before provider-assigned merchants were added to Sure exports. You can still
+ publish this import -- the affected record will just import without a merchant, and you can tag
+ it afterward.
+ other: >-
+ %{count} merchant references in this file point to merchants that aren't included. This can happen
+ with an export taken before provider-assigned merchants were added to Sure exports. You can still
+ publish this import -- the affected records will just import without a merchant, and you can tag
+ them afterward.
+ skipped_recurring_description:
+ one: >-
+ 1 recurring transaction has no name and its merchant is missing, so it will be skipped.
+ Automatically detected recurring transactions are rebuilt after the import.
+ other: >-
+ %{count} recurring transactions have no name and their merchants are missing, so they will be skipped.
+ Automatically detected recurring transactions are rebuilt after the import.
+ reused_taxonomy_notice_title: Some categories, tags or merchants already exist
+ reused_taxonomy_notice_description:
+ one: >-
+ 1 category, tag or merchant in this file already exists in your account (for
+ example, from onboarding's default categories). It'll be reused and updated with this file's
+ data instead of creating a duplicate.
+ other: >-
+ %{count} categories, tags or merchants in this file already exist in your account (for
+ example, from onboarding's default categories). They'll be reused and updated with this file's
+ data instead of creating duplicates.
+ provider_merchant_diff_title: Some merchants already exist with different details
+ provider_merchant_diff_description:
+ one: >-
+ 1 merchant in this file already exists with different details. The existing merchant
+ will be kept and this file's values won't be applied.
+ other: >-
+ %{count} merchants in this file already exist with different details. The existing merchants
+ will be kept and this file's values won't be applied.
+ provider_merchant_diff_summary: View differences
+ provider_merchant_diff_none: none
+ provider_merchant_diff_fields:
+ website_url: Website
+ name: Name
+ provider_merchant_id: Provider ID
+ provider_merchant_diff_row: "%{field}: keeping %{kept}, file has %{imported}"
errors:
custom_column_requires_inflow: "Custom column imports require an inflow column to be selected"
interrupted: "The background worker was interrupted before this finished. Imported data was rolled back — you can safely try again."
diff --git a/test/controllers/api/v1/imports_controller_test.rb b/test/controllers/api/v1/imports_controller_test.rb
index e7bb3579f3..5f0aace517 100644
--- a/test/controllers/api/v1/imports_controller_test.rb
+++ b/test/controllers/api/v1/imports_controller_test.rb
@@ -558,13 +558,15 @@ class Api::V1::ImportsControllerTest < ActionDispatch::IntegrationTest
end
test "should preserve Sure import and return preflight errors when auto publish fails preflight" do
- @family.categories.create!(
- name: "Groceries",
- color: "#407706",
- lucide_icon: "shopping-basket"
- )
ndjson_content = [
- { type: "Category", data: { id: "category_1", name: "Groceries" } }
+ { type: "Transaction", data: {
+ id: "transaction_1",
+ account_id: "missing_account",
+ date: "2024-01-15",
+ amount: "42.50",
+ name: "Orphaned transaction",
+ currency: "USD"
+ } }
].map(&:to_json).join("\n")
assert_difference("Import.count") do
@@ -580,7 +582,7 @@ class Api::V1::ImportsControllerTest < ActionDispatch::IntegrationTest
assert_response :unprocessable_entity
json_response = JSON.parse(response.body)
assert_equal "preflight_failed", json_response["error"]
- assert_includes json_response["errors"].join("\n"), "Category name \"Groceries\" already exists"
+ assert_includes json_response["errors"].join("\n"), "references missing account_id"
import = Import.find(json_response["import_id"])
assert_equal "failed", import.status
@@ -946,7 +948,7 @@ class Api::V1::ImportsControllerTest < ActionDispatch::IntegrationTest
assert_empty data["errors"]
end
- test "should preflight Sure import taxonomy collisions in strict mode" do
+ test "should reuse an existing Sure import taxonomy match by name instead of blocking preflight (#3113)" do
@family.tags.create!(name: "Reviewed", color: "#12B76A")
ndjson_content = [
{ type: "Tag", data: { id: "tag_1", name: "Reviewed" } }
@@ -963,8 +965,9 @@ class Api::V1::ImportsControllerTest < ActionDispatch::IntegrationTest
assert_response :success
data = JSON.parse(response.body)["data"]
- assert_equal false, data["valid"]
- assert_equal "existing_taxonomy_collision", data["errors"].first["code"]
+ assert_equal true, data["valid"]
+ assert_empty data["errors"]
+ assert data["warnings"].any? { |warning| warning.include?("already exists in this family and will be reused") }
end
test "should report invalid Sure import accountable type during preflight" do
diff --git a/test/controllers/imports_controller_test.rb b/test/controllers/imports_controller_test.rb
index 10d34ae0b9..3593ff56e3 100644
--- a/test/controllers/imports_controller_test.rb
+++ b/test/controllers/imports_controller_test.rb
@@ -434,6 +434,146 @@ class ImportsControllerTest < ActionDispatch::IntegrationTest
assert_equal I18n.t("imports.create.file_too_large", max_size: configured_limit / 1.megabyte), flash[:alert]
end
+ test "shows a friendly warning when a Sure import's transactions reference merchants missing from the export (#3113)" do
+ import = @user.family.imports.create!(type: "SureImport")
+ ndjson = [
+ { type: "Account", data: {
+ id: "account-1", name: "Old Export Checking", balance: "1000.00", currency: "USD",
+ accountable_type: "Depository", accountable: { subtype: "checking" }
+ } },
+ { type: "Transaction", data: {
+ id: "transaction-1", account_id: "account-1", merchant_id: "merchant-never-exported",
+ date: "2024-01-15", amount: "42.50", name: "Amazon purchase", currency: "USD"
+ } }
+ ].map(&:to_json).join("\n")
+ import.ndjson_file.attach(io: StringIO.new(ndjson), filename: "all.ndjson", content_type: "application/x-ndjson")
+ import.sync_ndjson_rows_count!
+
+ get import_url(import)
+
+ assert_response :success
+ assert_includes response.body, I18n.t("imports.ready.missing_merchant_warning_title")
+ end
+
+ test "does not show the missing merchant warning for a Sure import with no unresolved merchant references" do
+ import = @user.family.imports.create!(type: "SureImport")
+ ndjson = [
+ { type: "Account", data: {
+ id: "account-1", name: "Clean Export Checking", balance: "1000.00", currency: "USD",
+ accountable_type: "Depository", accountable: { subtype: "checking" }
+ } }
+ ].map(&:to_json).join("\n")
+ import.ndjson_file.attach(io: StringIO.new(ndjson), filename: "all.ndjson", content_type: "application/x-ndjson")
+ import.sync_ndjson_rows_count!
+
+ get import_url(import)
+
+ assert_response :success
+ assert_not_includes response.body, I18n.t("imports.ready.missing_merchant_warning_title")
+ end
+
+ test "explains that unnamed recurring transactions with a missing merchant will be skipped" do
+ import = @user.family.imports.create!(type: "SureImport")
+ ndjson = [
+ { type: "Account", data: {
+ id: "account-1", name: "Checking", balance: "1000.00", currency: "USD",
+ accountable_type: "Depository", accountable: { subtype: "checking" }
+ } },
+ { type: "RecurringTransaction", data: {
+ id: "recurring-1", account_id: "account-1", merchant_id: "merchant-never-exported",
+ amount: "11.99", currency: "USD", expected_day_of_month: 28,
+ last_occurrence_date: "2026-08-28", next_expected_date: "2026-09-28"
+ } }
+ ].map(&:to_json).join("\n")
+ import.ndjson_file.attach(io: StringIO.new(ndjson), filename: "all.ndjson", content_type: "application/x-ndjson")
+ import.sync_ndjson_rows_count!
+
+ get import_url(import)
+
+ assert_response :success
+ assert_includes response.body, I18n.t("imports.ready.missing_merchant_warning_title")
+ assert_includes response.body, I18n.t("imports.ready.skipped_recurring_description", count: 1).squish
+ assert_not_includes response.body, "merchant reference in this file"
+ end
+
+ test "shows a friendly notice when a Sure import reuses existing categories, tags or merchants by name (#3113)" do
+ @user.family.categories.create!(name: "Groceries", color: "#407706", lucide_icon: "shopping-basket")
+ import = @user.family.imports.create!(type: "SureImport")
+ ndjson = [
+ { type: "Category", data: { id: "category-1", name: "Groceries" } }
+ ].map(&:to_json).join("\n")
+ import.ndjson_file.attach(io: StringIO.new(ndjson), filename: "all.ndjson", content_type: "application/x-ndjson")
+ import.sync_ndjson_rows_count!
+
+ get import_url(import)
+
+ assert_response :success
+ assert_includes response.body, I18n.t("imports.ready.reused_taxonomy_notice_title")
+ end
+
+ test "does not show the reused taxonomy notice for a Sure import with no name collisions" do
+ import = @user.family.imports.create!(type: "SureImport")
+ ndjson = [
+ { type: "Category", data: { id: "category-1", name: "A Brand New Category Name" } }
+ ].map(&:to_json).join("\n")
+ import.ndjson_file.attach(io: StringIO.new(ndjson), filename: "all.ndjson", content_type: "application/x-ndjson")
+ import.sync_ndjson_rows_count!
+
+ get import_url(import)
+
+ assert_response :success
+ assert_not_includes response.body, I18n.t("imports.ready.reused_taxonomy_notice_title")
+ end
+
+ test "shows the differences when an existing provider merchant differs from the Sure import file" do
+ ProviderMerchant.create!(name: "AMZN MKTP", source: "plaid", website_url: "https://amazon.com")
+ import = @user.family.imports.create!(type: "SureImport")
+ ndjson = [
+ { type: "Account", data: {
+ id: "account-1", name: "Checking", balance: "1000.00", currency: "USD",
+ accountable_type: "Depository", accountable: { subtype: "checking" }
+ } },
+ { type: "ProviderMerchant", data: { id: "pm-1", name: "AMZN MKTP", source: "plaid", website_url: "https://amazon.co.uk" } }
+ ].map(&:to_json).join("\n")
+ import.ndjson_file.attach(io: StringIO.new(ndjson), filename: "all.ndjson", content_type: "application/x-ndjson")
+ import.sync_ndjson_rows_count!
+
+ get import_url(import)
+
+ assert_response :success
+ assert_includes response.body, I18n.t("imports.ready.provider_merchant_diff_title")
+ assert_includes response.body, "AMZN MKTP"
+ assert_includes response.body, "keeping https://amazon.com, file has https://amazon.co.uk"
+ end
+
+ test "does not show the provider merchant differences notice without a difference" do
+ import = @user.family.imports.create!(type: "SureImport")
+ ndjson = [
+ { type: "Account", data: {
+ id: "account-1", name: "Checking", balance: "1000.00", currency: "USD",
+ accountable_type: "Depository", accountable: { subtype: "checking" }
+ } }
+ ].map(&:to_json).join("\n")
+ import.ndjson_file.attach(io: StringIO.new(ndjson), filename: "all.ndjson", content_type: "application/x-ndjson")
+ import.sync_ndjson_rows_count!
+
+ get import_url(import)
+
+ assert_response :success
+ assert_not_includes response.body, I18n.t("imports.ready.provider_merchant_diff_title")
+ end
+
+ test "import ready notices use singular and plural wording" do
+ {
+ "imports.ready.missing_merchant_warning_description" => [ "1 merchant reference in this file", "2 merchant references in this file" ],
+ "imports.ready.reused_taxonomy_notice_description" => [ "1 category, tag or merchant", "2 categories, tags or merchants" ],
+ "imports.ready.provider_merchant_diff_description" => [ "1 merchant in this file", "2 merchants in this file" ]
+ }.each do |key, (singular, plural)|
+ assert_includes I18n.t(key, count: 1), singular
+ assert_includes I18n.t(key, count: 2), plural
+ end
+ end
+
test "PDF import account select does not leak unshared family accounts (#1803)" do
sign_in users(:family_member)
pdf_import = imports(:pdf_with_rows)
diff --git a/test/models/family/data_exporter_test.rb b/test/models/family/data_exporter_test.rb
index 141b6b5d83..39b9c786e7 100644
--- a/test/models/family/data_exporter_test.rb
+++ b/test/models/family/data_exporter_test.rb
@@ -859,6 +859,62 @@ class Family::DataExporterTest < ActiveSupport::TestCase
end
end
+ test "exports provider merchants referenced by transactions in NDJSON" do
+ provider_merchant = ProviderMerchant.create!(name: "AMZN MKTP", source: "plaid", provider_merchant_id: "plaid_amzn")
+ @account.entries.create!(
+ date: Date.parse("2024-05-02"),
+ amount: 42.50,
+ name: "Amazon purchase",
+ currency: "USD",
+ entryable: Transaction.new(merchant: provider_merchant)
+ )
+
+ zip_data = @exporter.generate_export
+
+ Zip::File.open_buffer(zip_data) do |zip|
+ ndjson_records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }
+ provider_merchant_data = ndjson_records.find do |record|
+ record["type"] == "ProviderMerchant" && record.dig("data", "id") == provider_merchant.id
+ end
+
+ assert provider_merchant_data
+ assert_equal "AMZN MKTP", provider_merchant_data["data"]["name"]
+ assert_equal "plaid", provider_merchant_data["data"]["source"]
+ assert_equal "plaid_amzn", provider_merchant_data["data"]["provider_merchant_id"]
+ end
+ end
+
+ test "exports provider merchants referenced by recurring transactions in NDJSON" do
+ provider_merchant = ProviderMerchant.create!(name: "Recurring Provider Merchant", source: "ai")
+ @family.recurring_transactions.create!(
+ account: @account,
+ merchant: provider_merchant,
+ amount: -12.99,
+ currency: "USD",
+ expected_day_of_month: 5,
+ last_occurrence_date: Date.parse("2024-01-05"),
+ next_expected_date: Date.parse("2024-02-05")
+ )
+
+ zip_data = @exporter.generate_export
+
+ Zip::File.open_buffer(zip_data) do |zip|
+ ndjson_records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }
+ assert ndjson_records.any? { |record| record["type"] == "ProviderMerchant" && record.dig("data", "id") == provider_merchant.id }
+ end
+ end
+
+ test "excludes provider merchants not referenced by the family from NDJSON" do
+ unreferenced = ProviderMerchant.create!(name: "Unrelated Provider Merchant", source: "plaid")
+
+ zip_data = @exporter.generate_export
+
+ Zip::File.open_buffer(zip_data) do |zip|
+ ndjson_records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }
+ refute ndjson_records.any? { |record| record["type"] == "ProviderMerchant" && record.dig("data", "id") == unreferenced.id }
+ end
+ end
+
test "exports transfer decisions and rejected transfers in NDJSON" do
destination_account = @family.accounts.create!(
name: "Savings Account",
diff --git a/test/models/provider_merchant_test.rb b/test/models/provider_merchant_test.rb
index 0f15aeaa18..d08e4d5d61 100644
--- a/test/models/provider_merchant_test.rb
+++ b/test/models/provider_merchant_test.rb
@@ -34,4 +34,44 @@ class ProviderMerchantTest < ActiveSupport::TestCase
assert_nil entry.entryable.merchant_id
assert entry.user_modified?, "unlinked transaction's entry must be flagged so provider sync won't re-link it"
end
+
+ test "find_by_import_data prefers provider_merchant_id over name, scoped to source" do
+ by_id = ProviderMerchant.create!(name: "Renamed Upstream", source: "plaid", provider_merchant_id: "plaid_acme")
+ ProviderMerchant.create!(name: "Acme", source: "lunchflow")
+
+ found = ProviderMerchant.find_by_import_data({ "name" => "Old Name", "provider_merchant_id" => "plaid_acme" }, "plaid")
+
+ assert_equal by_id, found
+ assert_equal @provider_merchant, ProviderMerchant.find_by_import_data({ "name" => "Acme Synced" }, "plaid")
+ assert_nil ProviderMerchant.find_by_import_data({ "name" => "Acme Synced" }, "lunchflow")
+ end
+
+ test "import_diff reports only non-blank website_url and name differences" do
+ merchant = ProviderMerchant.create!(name: "Acme", source: "plaid", provider_merchant_id: "plaid_acme", website_url: "https://acme.com")
+
+ assert_empty merchant.import_diff({ "name" => "Acme", "website_url" => "https://acme.com", "color" => "#123456" })
+ assert_empty merchant.import_diff({ "name" => "Acme", "website_url" => "" })
+
+ assert_equal(
+ [ { field: "website_url", imported_value: "https://acme.io", kept_value: "https://acme.com" },
+ { field: "name", imported_value: "Acme Inc", kept_value: "Acme" } ],
+ merchant.import_diff({ "name" => "Acme Inc", "website_url" => "https://acme.io" })
+ )
+ end
+
+ test "import_diff flags a non-blank provider_merchant_id that differs from, or is missing on, the existing merchant" do
+ with_id = ProviderMerchant.create!(name: "Acme", source: "lunchflow", provider_merchant_id: "id-1")
+ without_id = ProviderMerchant.create!(name: "Acme", source: "akahu")
+
+ assert_equal(
+ [ { field: "provider_merchant_id", imported_value: "id-2", kept_value: "id-1" } ],
+ with_id.import_diff({ "name" => "Acme", "provider_merchant_id" => "id-2" })
+ )
+ assert_empty with_id.import_diff({ "name" => "Acme", "provider_merchant_id" => "id-1" })
+ assert_equal(
+ [ { field: "provider_merchant_id", imported_value: "id-2", kept_value: nil } ],
+ without_id.import_diff({ "name" => "Acme", "provider_merchant_id" => "id-2" })
+ )
+ assert_empty without_id.import_diff({ "name" => "Acme" })
+ end
end
diff --git a/test/models/sure_import_test.rb b/test/models/sure_import_test.rb
index 12b685bbe4..3f040383a5 100644
--- a/test/models/sure_import_test.rb
+++ b/test/models/sure_import_test.rb
@@ -518,20 +518,12 @@ class SureImportTest < ActiveSupport::TestCase
end
test "preflight reports blocking errors before publish_later enqueues" do
- @family.categories.create!(
- name: "Groceries",
- color: "#407706",
- lucide_icon: "shopping-basket"
- )
attach_ndjson(build_ndjson([
- { type: "Account", data: {
- id: "account-1",
- name: "Blocked Account",
- balance: "100",
- currency: "USD",
- accountable_type: "Depository"
- } },
- { type: "Category", data: { id: "category-1", name: "Groceries" } }
+ { type: "Valuation", data: {
+ account_id: "missing-account",
+ date: "2024-01-01",
+ amount: "100"
+ } }
]))
assert_no_enqueued_jobs do
@@ -541,7 +533,7 @@ class SureImportTest < ActiveSupport::TestCase
end
assert_equal "failed", @import.reload.status
- assert_includes @import.error, "Category name \"Groceries\" already exists"
+ assert_includes @import.error, "references missing account_id"
end
test "publish_later reports unsupported records through preflight before publishable check" do
@@ -762,6 +754,304 @@ class SureImportTest < ActiveSupport::TestCase
assert_includes result.error_message, "references missing parent_id"
end
+ test "provider merchant referenced by a transaction resolves during preflight and publish" do
+ attach_ndjson(build_ndjson([
+ { type: "Account", data: {
+ id: "account-1",
+ name: "Provider Merchant Checking",
+ balance: "1000.00",
+ currency: "USD",
+ accountable_type: "Depository",
+ accountable: { subtype: "checking" }
+ } },
+ { type: "ProviderMerchant", data: {
+ id: "provider-merchant-1",
+ name: "AMZN MKTP",
+ source: "plaid",
+ provider_merchant_id: "plaid_amzn"
+ } },
+ { type: "Transaction", data: {
+ id: "transaction-1",
+ account_id: "account-1",
+ merchant_id: "provider-merchant-1",
+ date: "2024-01-15",
+ amount: "42.50",
+ name: "Amazon purchase",
+ currency: "USD"
+ } }
+ ]))
+
+ result = @import.sure_preflight
+ assert result.valid?, result.error_message
+
+ assert_difference -> { ProviderMerchant.count }, 1 do
+ @import.publish
+ end
+
+ assert_equal "complete", @import.status
+
+ entry = @family.entries.find_by!(name: "Amazon purchase")
+ merchant = entry.entryable.merchant
+
+ assert_instance_of ProviderMerchant, merchant
+ assert_equal "AMZN MKTP", merchant.name
+ assert_equal "plaid", merchant.source
+ assert_equal "plaid_amzn", merchant.provider_merchant_id
+ end
+
+ test "provider merchant import reuses an existing matching record instead of duplicating or overwriting it" do
+ existing = ProviderMerchant.create!(
+ name: "AMZN MKTP", source: "plaid", provider_merchant_id: "plaid_amzn", website_url: "https://amazon.com"
+ )
+
+ attach_ndjson(build_ndjson([
+ { type: "Account", data: {
+ id: "account-1",
+ name: "Provider Merchant Checking",
+ balance: "1000.00",
+ currency: "USD",
+ accountable_type: "Depository",
+ accountable: { subtype: "checking" }
+ } },
+ { type: "ProviderMerchant", data: {
+ id: "provider-merchant-1",
+ name: "AMZN MKTP",
+ source: "plaid",
+ provider_merchant_id: "plaid_amzn",
+ website_url: "https://should-not-overwrite.example.com"
+ } },
+ { type: "Transaction", data: {
+ id: "transaction-1",
+ account_id: "account-1",
+ merchant_id: "provider-merchant-1",
+ date: "2024-01-15",
+ amount: "42.50",
+ name: "Amazon purchase",
+ currency: "USD"
+ } }
+ ]))
+
+ assert_no_difference -> { ProviderMerchant.count } do
+ @import.publish
+ end
+
+ assert_equal "complete", @import.status
+
+ existing.reload
+ assert_equal "https://amazon.com", existing.website_url
+
+ entry = @family.entries.find_by!(name: "Amazon purchase")
+ assert_equal existing.id, entry.entryable.merchant_id
+ end
+
+ test "provider merchant import never writes to an existing match, even when its fields are blank" do
+ existing = ProviderMerchant.create!(name: "AMZN MKTP", source: "plaid", provider_merchant_id: "plaid_amzn")
+
+ attach_ndjson(provider_merchant_ndjson(
+ website_url: "https://amazon.com", logo_url: "https://cdn.example.com/amzn.png", color: "#123456"
+ ))
+
+ assert_no_difference -> { ProviderMerchant.count } do
+ @import.publish
+ end
+
+ assert_equal "complete", @import.status
+ existing.reload
+ assert_nil existing.website_url
+ assert_nil existing.logo_url
+ assert_nil existing.color
+ assert_equal existing.id, @family.entries.find_by!(name: "Amazon purchase").entryable.merchant_id
+ end
+
+ {
+ "RecordNotUnique" => -> { ActiveRecord::RecordNotUnique.new("duplicate key") },
+ "RecordInvalid" => -> { ActiveRecord::RecordInvalid.new(ProviderMerchant.new.tap { |merchant| merchant.errors.add(:name, :taken) }) }
+ }.each do |label, build_error|
+ test "provider merchant import recovers when another import wins the creation race (#{label})" do
+ winner = ProviderMerchant.create!(name: "AMZN MKTP", source: "plaid", provider_merchant_id: "plaid_amzn")
+ attach_ndjson(provider_merchant_ndjson)
+
+ ProviderMerchant.stubs(:find_by_import_data).returns(nil).then.returns(winner)
+ ProviderMerchant.stubs(:create!).raises(build_error.call)
+
+ assert_no_difference -> { ProviderMerchant.count } do
+ @import.import!
+ end
+
+ assert_equal winner.id, @family.entries.find_by!(name: "Amazon purchase").entryable.merchant_id
+ end
+ end
+
+ test "provider merchant import surfaces validation errors that are not a lost creation race" do
+ attach_ndjson(provider_merchant_ndjson)
+ invalid = ActiveRecord::RecordInvalid.new(ProviderMerchant.new.tap { |merchant| merchant.errors.add(:name, :blank) })
+ ProviderMerchant.stubs(:find_by_import_data).returns(nil)
+ ProviderMerchant.stubs(:create!).raises(invalid)
+
+ assert_raises(ActiveRecord::RecordInvalid) { @import.import! }
+ end
+
+ test "preflight warns with the actual diff when an existing provider merchant differs from the file" do
+ ProviderMerchant.create!(name: "AMZN MKTP", source: "plaid", provider_merchant_id: "plaid_amzn", website_url: "https://amazon.com")
+ attach_ndjson(provider_merchant_ndjson(website_url: "https://amazon.co.uk"))
+
+ result = @import.sure_preflight
+
+ assert result.valid?, result.error_message
+ assert_equal 1, result.provider_merchant_diff_warnings.size
+ details = result.provider_merchant_diff_warnings.first[:details]
+ assert_equal "AMZN MKTP", details[:merchant_name]
+ assert_equal(
+ [ { field: "website_url", imported_value: "https://amazon.co.uk", kept_value: "https://amazon.com" } ],
+ details[:diff]
+ )
+ end
+
+ test "preflight does not warn when the provider merchant is new or identical" do
+ attach_ndjson(provider_merchant_ndjson(website_url: "https://amazon.com"))
+ assert_empty @import.sure_preflight.provider_merchant_diff_warnings
+
+ ProviderMerchant.create!(name: "AMZN MKTP", source: "plaid", provider_merchant_id: "plaid_amzn", website_url: "https://amazon.com")
+ assert_empty @import.sure_preflight.provider_merchant_diff_warnings
+ end
+
+ test "a transaction merchant_id unresolvable in the export is a warning, not a blocking preflight error (#3113)" do
+ attach_ndjson(build_ndjson([
+ { type: "Account", data: {
+ id: "account-1",
+ name: "Old Export Checking",
+ balance: "1000.00",
+ currency: "USD",
+ accountable_type: "Depository",
+ accountable: { subtype: "checking" }
+ } },
+ { type: "Transaction", data: {
+ id: "transaction-1",
+ account_id: "account-1",
+ merchant_id: "merchant-never-exported",
+ date: "2024-01-15",
+ amount: "42.50",
+ name: "Amazon purchase",
+ currency: "USD"
+ } }
+ ]))
+
+ result = @import.sure_preflight
+ assert result.valid?, result.error_message
+ assert_equal 1, result.skipped_missing_merchant_count
+ assert result.warnings.any? { |warning| warning[:code] == "skipped_missing_merchant_reference" }
+
+ @import.publish
+
+ assert_equal "complete", @import.status
+ entry = @family.entries.find_by!(name: "Amazon purchase")
+ assert_nil entry.entryable.merchant_id
+ end
+
+ test "a missing account_id (not merchant_id) on a transaction is still a blocking preflight error" do
+ attach_ndjson(build_ndjson([
+ { type: "Transaction", data: {
+ id: "transaction-1",
+ account_id: "missing-account",
+ date: "2024-01-15",
+ amount: "42.50",
+ name: "Orphaned transaction",
+ currency: "USD"
+ } }
+ ]))
+
+ result = @import.sure_preflight
+
+ assert_not result.valid?
+ assert_equal 0, result.skipped_missing_merchant_count
+ assert result.errors.any? { |error| error[:code] == "missing_reference" }
+ end
+
+ test "publishing reuses an existing family category, tag and merchant matched by name instead of failing (#3113)" do
+ existing_category = @family.categories.create!(name: "Groceries", color: "#111111", lucide_icon: "shapes")
+ existing_tag = @family.tags.create!(name: "Reviewed", color: "#222222")
+ existing_merchant = @family.merchants.create!(name: "Local Cafe", color: "#333333")
+
+ category_count = @family.categories.count
+ tag_count = @family.tags.count
+ merchant_count = @family.merchants.count
+
+ attach_ndjson(build_ndjson([
+ { type: "Category", data: { id: "category-1", name: "Groceries", color: "#407706", lucide_icon: "shopping-cart" } },
+ { type: "Tag", data: { id: "tag-1", name: "Reviewed", color: "#12B76A" } },
+ { type: "Merchant", data: { id: "merchant-1", name: "Local Cafe", color: "#12B76A" } }
+ ]))
+
+ result = @import.sure_preflight
+ assert result.valid?, result.error_message
+ assert_equal 3, result.warnings.count { |warning| warning[:code] == "existing_taxonomy_collision" }
+
+ @import.publish
+
+ assert_equal "complete", @import.status
+ assert_equal category_count, @family.categories.count
+ assert_equal tag_count, @family.tags.count
+ assert_equal merchant_count, @family.merchants.count
+
+ assert_equal "#407706", existing_category.reload.color
+ assert_equal "#12B76A", existing_tag.reload.color
+ assert_equal "#12B76A", existing_merchant.reload.color
+
+ @import.reload
+ assert_equal "matched", @import.verification_status
+ assert_equal({ "categories" => 1, "tags" => 1, "merchants" => 1 }, @import.readback_verification["reused_record_counts"])
+ end
+
+ test "family merchant import carries website_url and leaves an existing one alone when the file omits it" do
+ kept = @family.merchants.create!(name: "Kept Cafe", website_url: "https://kept.example")
+ updated = @family.merchants.create!(name: "Updated Cafe", website_url: "https://old.example")
+
+ attach_ndjson(build_ndjson([
+ { type: "Merchant", data: { id: "m-new", name: "New Cafe", website_url: "https://new.example" } },
+ { type: "Merchant", data: { id: "m-kept", name: "Kept Cafe" } },
+ { type: "Merchant", data: { id: "m-updated", name: "Updated Cafe", website_url: "https://fresh.example" } }
+ ]))
+
+ @import.publish
+
+ assert_equal "complete", @import.status
+ assert_equal "https://new.example", @family.merchants.find_by!(name: "New Cafe").website_url
+ assert_equal "https://kept.example", kept.reload.website_url
+ assert_equal "https://fresh.example", updated.reload.website_url
+ end
+
+ test "a named recurring transaction whose merchant is missing imports without a merchant" do
+ attach_ndjson(recurring_with_missing_merchant_ndjson(name: "Gym membership"))
+
+ result = @import.sure_preflight
+ assert result.valid?, result.error_message
+ assert_equal 1, result.skipped_missing_merchant_count
+ assert_equal 0, result.skipped_unnamed_recurring_count
+
+ assert_difference -> { @family.recurring_transactions.count }, 1 do
+ @import.publish
+ end
+
+ assert_equal "complete", @import.status
+ recurring = @family.recurring_transactions.find_by!(name: "Gym membership")
+ assert_nil recurring.merchant_id
+ end
+
+ test "an unnamed recurring transaction whose merchant is missing is skipped and reported as such" do
+ attach_ndjson(recurring_with_missing_merchant_ndjson)
+
+ result = @import.sure_preflight
+ assert result.valid?, result.error_message
+ assert_equal 1, result.skipped_unnamed_recurring_count
+ assert_equal 0, result.skipped_missing_merchant_count
+
+ assert_no_difference -> { @family.recurring_transactions.count } do
+ @import.publish
+ end
+
+ assert_equal "complete", @import.status
+ end
+
private
def attach_ndjson(ndjson)
@@ -773,6 +1063,36 @@ class SureImportTest < ActiveSupport::TestCase
@import.sync_ndjson_rows_count!
end
+ def provider_merchant_ndjson(**merchant_attrs)
+ build_ndjson([
+ { type: "Account", data: {
+ id: "account-1", name: "Provider Merchant Checking", balance: "1000.00", currency: "USD",
+ accountable_type: "Depository", accountable: { subtype: "checking" }
+ } },
+ { type: "ProviderMerchant", data: {
+ id: "provider-merchant-1", name: "AMZN MKTP", source: "plaid", provider_merchant_id: "plaid_amzn"
+ }.merge(merchant_attrs) },
+ { type: "Transaction", data: {
+ id: "transaction-1", account_id: "account-1", merchant_id: "provider-merchant-1",
+ date: "2024-01-15", amount: "42.50", name: "Amazon purchase", currency: "USD"
+ } }
+ ])
+ end
+
+ def recurring_with_missing_merchant_ndjson(**recurring_attrs)
+ build_ndjson([
+ { type: "Account", data: {
+ id: "account-1", name: "Recurring Checking", balance: "1000.00", currency: "USD",
+ accountable_type: "Depository", accountable: { subtype: "checking" }
+ } },
+ { type: "RecurringTransaction", data: {
+ id: "recurring-1", account_id: "account-1", merchant_id: "merchant-never-exported",
+ amount: "11.99", currency: "USD", expected_day_of_month: 28,
+ last_occurrence_date: "2026-08-28", next_expected_date: "2026-09-28"
+ }.merge(recurring_attrs) }
+ ])
+ end
+
def build_ndjson(records)
records.map(&:to_json).join("\n")
end
@@ -832,7 +1152,7 @@ class Import::PreflightTest < ActiveSupport::TestCase
@family = families(:dylan_family)
end
- test "SureImport preflight reports strict taxonomy collisions" do
+ test "SureImport preflight reuses an existing taxonomy match by name instead of blocking (#3113)" do
@family.tags.create!(name: "Reviewed", color: "#12B76A")
ndjson = build_ndjson([
{ type: "Tag", data: { id: "tag-1", name: "Reviewed" } }
@@ -846,8 +1166,9 @@ class Import::PreflightTest < ActiveSupport::TestCase
payload = response.payload[:data]
assert_equal :ok, response.status
- assert_equal false, payload[:valid]
- assert_equal "existing_taxonomy_collision", payload[:errors].first[:code]
+ assert_equal true, payload[:valid]
+ assert_empty payload[:errors]
+ assert_includes payload[:warnings], "Line 1 Tag name \"Reviewed\" already exists in this family and will be reused."
end
end