Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
77.3 KB
Raw Blame
require "set"

class Family::DataImporter
  MissingReferenceError = Class.new(StandardError) do
    attr_reader :code, :details

    def initialize(record_type:, source_type:, source_id:)
      @code = "missing_source_reference"
      @details = {
        record_type: record_type,
        source_type: source_type,
        source_id: source_id
      }

      super("#{record_type} references missing #{source_type} source id #{source_id}")
    end
  end

  InvalidRecordError = Class.new(StandardError) do
    attr_reader :code, :details

    def initialize(record_type:, field:, value:)
      @code = "invalid_import_record"
      @details = {
        record_type: record_type,
        field: field,
        value: value
      }

      super("#{record_type} has invalid #{field}: #{value.inspect}")
    end
  end

  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
  PROPERTY_DETAIL_ATTRIBUTES = %w[year_built area_value area_unit].freeze
  PROPERTY_ADDRESS_ATTRIBUTES = %w[line1 line2 locality region county postal_code country].freeze
  VEHICLE_DETAIL_ATTRIBUTES = %w[make model year mileage_value mileage_unit].freeze
  ACCOUNTABLE_TYPE_CLASSES = {
    "Depository" => Depository, "Investment" => Investment, "Crypto" => Crypto,
    "Property" => Property, "Vehicle" => Vehicle, "OtherAsset" => OtherAsset,
    "CreditCard" => CreditCard, "Loan" => Loan, "OtherLiability" => OtherLiability
  }.freeze

  # What the loan and credit card forms edit, restored on import. The loan's
  # rate schedule is restored separately (see assign_liability_details).
  LOAN_DETAIL_ATTRIBUTES = %w[
    interest_rate rate_type term_months start_date down_payment initial_balance
    insurance_rate insurance_rate_type day_count_convention principal_only_transfers
  ].freeze
  CREDIT_CARD_DETAIL_ATTRIBUTES = %w[apr annual_fee minimum_payment available_credit due_day statement_close_day expiration_date].freeze

  def self.accountable_class_for(type)
    ACCOUNTABLE_TYPE_CLASSES[type.to_s]
  end

  MAPPING_TYPES = {
    accounts: "Account",
    categories: "Category",
    tags: "Tag",
    merchants: "Merchant",
    recurring_transactions: "RecurringTransaction",
    recurring_occurrences: "RecurringOccurrence",
    transactions: "Transaction",
    budgets: "Budget",
    securities: "Security",
    rules: "Rule"
  }.freeze
  SUMMARY_KEYS = {
    "Account" => "accounts",
    "Balance" => "balances",
    "Category" => "categories",
    "Tag" => "tags",
    "Merchant" => "merchants",
    "ProviderMerchant" => "provider_merchants",
    "RecurringTransaction" => "recurring_transactions",
    "RecurrenceRule" => "recurrence_rules",
    "RecurringOccurrence" => "recurring_occurrences",
    "RecurringAllocation" => "recurring_allocations",
    "RecurringPriceChange" => "recurring_price_changes",
    "RecurringMatchRejection" => "recurring_match_rejections",
    "Transaction" => "transactions",
    "Transfer" => "transfers",
    "RejectedTransfer" => "rejected_transfers",
    "Trade" => "trades",
    "Holding" => "holdings",
    "Valuation" => "valuations",
    "Budget" => "budgets",
    "BudgetCategory" => "budget_categories",
    "Rule" => "rules"
  }.freeze

  # 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
    @import = import
    @strict_references = import_session.present?
    @id_mappings = {
      accounts: {},
      categories: {},
      tags: {},
      merchants: {},
      recurring_transactions: {},
      recurring_occurrences: {},
      transactions: {},
      budgets: {},
      securities: {},
      rules: {}
    }
    account_targets.each { |source_id, account| @id_mappings[:accounts][source_id] = account.id }
    @security_cache = {}
    @pending_replacements = {}
    @created_account_ids = []
    @created_entry_ids = []
    @rollover_user_ids = Set.new
    @summary = Hash.new { |hash, key| hash[key] = empty_summary_bucket }
  end

  def import!
    records = parse_ndjson
    @oldest_import_entry_dates_by_account = oldest_import_entry_dates_by_account(records)
    @imported_opening_anchor_account_ids = imported_opening_anchor_account_ids(records["Valuation"] || [])

    Import.transaction do
      # Import in dependency order
      import_accounts(records["Account"] || [])
      import_balances(records["Balance"] || [])
      import_categories(records["Category"] || [])
      import_tags(records["Tag"] || [])
      link_property_cost_tags(records["Account"] || [])
      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
      # rest also need transactions, so all of it replays here.
      import_recurrence_rules(records["RecurrenceRule"] || [])
      import_recurring_occurrences(records["RecurringOccurrence"] || [])
      import_recurring_allocations(records["RecurringAllocation"] || [])
      import_recurring_price_changes(records["RecurringPriceChange"] || [])
      import_recurring_match_rejections(records["RecurringMatchRejection"] || [])
      import_transfers(records["Transfer"] || [])
      import_rejected_transfers(records["RejectedTransfer"] || [])
      import_trades(records["Trade"] || [])
      import_holdings(records["Holding"] || [])
      import_valuations(records["Valuation"] || [])
      import_budgets(records["Budget"] || [])
      import_budget_categories(records["BudgetCategory"] || [])
      import_rules(records["Rule"] || [])
    end

    recompute_rollover_chains

    { account_ids: @created_account_ids, entry_ids: @created_entry_ids, summary: compact_summary }
  end

  # A session imports each chunk through its own importer, so a property can
  # land in an earlier chunk than its cost tag. The session calls this for
  # every chunk after all of them are in, when every tag has its new id.
  def link_property_cost_tags!
    records = parse_ndjson
    Import.transaction { link_property_cost_tags(records["Account"] || []) }
  end

  private

    def parse_ndjson
      records = Hash.new { |h, k| h[k] = [] }

      @ndjson_content.each_line do |line|
        next if line.strip.empty?

        begin
          record = JSON.parse(line)
          type = record["type"]
          next unless SUPPORTED_TYPES.include?(type)

          records[type] << record
        rescue JSON::ParserError
          # Skip invalid lines
        end
      end

      records
    end

    def empty_summary_bucket
      { "created" => 0, "updated" => 0, "skipped" => 0, "failed" => 0 }
    end

    def compact_summary
      @summary.select { |_entity_type, counts| counts.values.any?(&:positive?) }
    end

    def increment_summary(record_type, status)
      @summary[SUMMARY_KEYS.fetch(record_type)].tap do |counts|
        counts[status.to_s] = counts.fetch(status.to_s, 0) + 1
      end
    end

    def map_source!(mapping_key, source_id, target)
      return if source_id.blank? || target.blank?

      @id_mappings[mapping_key][source_id] = target.id
      return unless @import_session

      source_type = MAPPING_TYPES.fetch(mapping_key)
      # The session outlives every chunk, so nothing here may append the mapping
      # (and, through its target, the imported record) to one of its
      # associations, or memory grows with the file. That rules out building
      # through @import_session.source_mappings, and also assigning
      # `import_session:`/`family:` objects, which only avoids it while the
      # belongs_to has no inverse_of. Ids plus association(...).target= never
      # inverse, and keep the loaded owners so validations don't reload them.
      mapping = ImportSourceMapping.find_or_initialize_by(
        import_session_id: @import_session.id,
        family_id: @family.id,
        source_type: source_type,
        source_id: source_id
      )
      mapping.association(:import_session).target = @import_session
      mapping.association(:family).target = @family
      mapping.target = target
      mapping.save!
    end

    def mapped_id(mapping_key, old_id, record_type:, required: true)
      if old_id.blank?
        missing_reference(record_type, mapping_key, "(blank)") if required
        return
      end

      return @id_mappings[mapping_key][old_id] if @id_mappings[mapping_key].key?(old_id)

      source_type = MAPPING_TYPES.fetch(mapping_key)
      mapping = @import_session&.source_mappings&.find_by(
        family: @family,
        source_type: source_type,
        source_id: old_id
      )

      if mapping
        @id_mappings[mapping_key][old_id] = mapping.target_id
        return mapping.target_id
      end

      if required && @strict_references
        raise MissingReferenceError.new(
          record_type: record_type,
          source_type: source_type,
          source_id: old_id
        )
      end

      nil
    end

    def mapped_record(mapping_key, old_id, scope, record_type:)
      target_id = mapped_id(mapping_key, old_id, record_type: record_type, required: false)
      return if target_id.blank?

      scope.find_by(id: target_id)
    end

    def missing_reference(record_type, mapping_key, old_id)
      if @strict_references
        increment_summary(record_type, :failed)
        raise MissingReferenceError.new(
          record_type: record_type,
          source_type: MAPPING_TYPES.fetch(mapping_key),
          source_id: old_id
        )
      end

      increment_summary(record_type, :skipped)
      nil
    end

    def require_source_id!(record_type, source_id)
      return if source_id.present? || !@strict_references

      increment_summary(record_type, :failed)
      raise MissingReferenceError.new(
        record_type: record_type,
        source_type: record_type,
        source_id: "(blank)"
      )
    end

    def invalid_record!(record_type, field, value)
      if @strict_references
        increment_summary(record_type, :failed)
        raise InvalidRecordError.new(record_type: record_type, field: field, value: value)
      end

      increment_summary(record_type, :skipped)
      nil
    end

    def session_entry_source
      return unless @import_session

      "sure_import_session:#{@import_session.id}"
    end

    def session_entry_external_id(record_type, source_id)
      return if @import_session.blank? || source_id.blank?

      "#{record_type}:#{source_id}"
    end

    def session_imported_entry(account, record_type, source_id)
      external_id = session_entry_external_id(record_type, source_id)
      return if external_id.blank?

      account.entries.find_by(source: session_entry_source, external_id: external_id)
    end

    # A missing or null value keeps the column's default, so older exports,
    # which carry none of these, still import.
    def assign_liability_details(accountable, accountable_data)
      attributes = case accountable
      when Loan then LOAN_DETAIL_ATTRIBUTES
      when CreditCard then CREDIT_CARD_DETAIL_ATTRIBUTES
      end
      return unless attributes

      accountable.assign_attributes(accountable_data.slice(*attributes).compact)

      # Through the form's own parser, so a schedule the loan could not read
      # back is rejected instead of stored.
      schedule = accountable_data["variable_rate_schedule"]
      if accountable.is_a?(Loan) && schedule.is_a?(Hash)
        accountable.rate_changes = schedule.map { |date, rate| { "effective_date" => date, "rate" => rate } }
      end
    end

    def import_accounts(records)
      records.each do |record|
        data = record["data"]
        old_id = data["id"]
        accountable_data = data["accountable"] || {}
        accountable_type = data["accountable_type"]

        require_source_id!("Account", old_id)

        accountable_class = self.class.accountable_class_for(accountable_type)

        unless accountable_class
          invalid_record!("Account", "accountable_type", accountable_type)
          next
        end

        account = mapped_record(:accounts, old_id, @family.accounts, record_type: "Account")
        created = account.blank?

        if account
          accountable = account.accountable
        else
          # Build accountable
          accountable = accountable_class.new
          accountable.subtype = accountable_data["subtype"] if accountable.respond_to?(:subtype=) && accountable_data["subtype"].present?
          assign_liability_details(accountable, accountable_data)

          # Copy any other accountable attributes
          safe_accountable_attrs = %w[subtype locked_attributes]
          safe_accountable_attrs.each do |attr|
            if accountable.respond_to?("#{attr}=") && accountable_data[attr].present?
              accountable.send("#{attr}=", accountable_data[attr])
            end
          end

          assign_property_details(accountable, accountable_data) if accountable.is_a?(Property)
          assign_vehicle_details(accountable, accountable_data) if accountable.is_a?(Vehicle)

          account = @family.accounts.build(accountable: accountable)
        end

        account.assign_attributes(
          name: data["name"],
          balance: data["balance"].to_d,
          cash_balance: data["cash_balance"]&.to_d || data["balance"].to_d,
          currency: data["currency"] || @family.currency,
          institution_name: data["institution_name"],
          institution_domain: data["institution_domain"],
          notes: data["notes"],
          status: importable_account_status(data["status"])
        )
        # `Account#subtype=` writes through to the accountable, so assigning a
        # nil top-level subtype would wipe the nested one. The nested value
        # wins, matching SureImport::Preflight#validate_accountables.
        imported_subtype = accountable_data["subtype"].presence || data["subtype"].presence
        account.subtype = imported_subtype if imported_subtype
        # A file from before the setting existed leaves the account's own.
        account.cost_basis_method = data["cost_basis_method"] if Account.cost_basis_methods.key?(data["cost_basis_method"])
        # Older exports predate the choice and keep the account's own.
        account.logo_selection = data["logo_selection"] if Account.logo_selections.key?(data["logo_selection"])

        account.save!

        # Set opening balance if we have a historical balance and the import
        # does not provide either an explicit opening-anchor valuation or an
        # authoritative balance-history stream for this account.
        if created && data["balance"].present? && !skip_opening_balance_import?(old_id, data)
          manager = Account::OpeningBalanceManager.new(account)
          result = manager.set_opening_balance(
            balance: data["balance"].to_d,
            date: opening_balance_date_for(old_id, data)
          )
          log_failed_opening_balance_import(account, old_id, result) unless result.success?
        end

        map_source!(:accounts, old_id, account)
        @created_account_ids << account.id if created
        increment_summary("Account", created ? :created : :updated)
      end
    end

    # What the property form edits. Provider links (avm_*) are left out: the
    # restored family has to link its own provider. A missing or null value
    # keeps the model's default, such as the area unit.
    def assign_property_details(property, accountable_data)
      property.assign_attributes(accountable_data.slice(*PROPERTY_DETAIL_ATTRIBUTES).compact)

      address_data = accountable_data["address"]
      property.build_address(address_data.slice(*PROPERTY_ADDRESS_ATTRIBUTES)) if address_data.is_a?(Hash)
    end

    # What the vehicle form edits. A missing or null value keeps the model's
    # default, such as the mileage unit.
    def assign_vehicle_details(vehicle, accountable_data)
      vehicle.assign_attributes(accountable_data.slice(*VEHICLE_DETAIL_ATTRIBUTES).compact)
    end

    def importable_account_status(status)
      status.to_s.in?(%w[active disabled draft]) ? status.to_s : "active"
    end

    def import_balances(records)
      records.each do |record|
        data = record["data"] || {}
        new_account_id = mapped_id(:accounts, data["account_id"], record_type: "Balance")
        balance_date = parse_import_date(data["date"])
        next if new_account_id.blank?

        if balance_date.blank? || data["balance"].blank?
          increment_summary("Balance", :skipped)
          next
        end

        account = @family.accounts.find(new_account_id)
        currency = data["currency"].presence || account.currency
        balance = account.balances.find_or_initialize_by(date: balance_date, currency: currency)
        created = balance.new_record?

        balance.assign_attributes(imported_balance_attributes(data))
        balance.save!
        increment_summary("Balance", created ? :created : :updated)
      end
    end

    def imported_balance_attributes(data)
      attributes = {
        balance: data["balance"].to_d,
        cash_balance: optional_decimal(data["cash_balance"]),
        start_cash_balance: optional_decimal(data["start_cash_balance"]),
        start_non_cash_balance: optional_decimal(data["start_non_cash_balance"]),
        cash_inflows: optional_decimal(data["cash_inflows"]),
        cash_outflows: optional_decimal(data["cash_outflows"]),
        non_cash_inflows: optional_decimal(data["non_cash_inflows"]),
        non_cash_outflows: optional_decimal(data["non_cash_outflows"]),
        net_market_flows: optional_decimal(data["net_market_flows"]),
        cash_adjustments: optional_decimal(data["cash_adjustments"]),
        non_cash_adjustments: optional_decimal(data["non_cash_adjustments"])
      }.compact

      attributes[:flows_factor] = balance_flows_factor_for(data["flows_factor"]) if data["flows_factor"].present?
      attributes
    end

    def optional_decimal(value)
      value.presence&.to_d
    end

    def balance_flows_factor_for(value)
      value.to_i.in?([ -1, 1 ]) ? value.to_i : 1
    end

    def import_categories(records)
      # First pass: create all categories without parent relationships
      parent_mappings = {}

      records.each do |record|
        data = record["data"]
        old_id = data["id"]
        parent_id = data["parent_id"]

        require_source_id!("Category", old_id)

        # 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

        category.assign_attributes(
          name: data["name"],
          color: data["color"] || Category::UNCATEGORIZED_COLOR,
          classification_unused: data["classification_unused"] || data["classification"] || "expense",
          lucide_icon: data["lucide_icon"] || "shapes"
        )
        category.save!
        map_source!(:categories, old_id, category)
        increment_summary("Category", created ? :created : :updated)
      end

      # Second pass: establish parent relationships
      parent_mappings.each do |old_id, old_parent_id|
        new_id = mapped_id(:categories, old_id, record_type: "Category")
        new_parent_id = mapped_id(:categories, old_parent_id, record_type: "Category")

        next unless new_id && new_parent_id

        category = @family.categories.find(new_id)
        category.update!(parent_id: new_parent_id)
      end
    end

    def import_tags(records)
      records.each do |record|
        data = record["data"]
        old_id = data["id"]

        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
        # Keep replayed session imports deterministic when the source omits a color.
        color ||= Tag::COLORS.first if created

        tag.assign_attributes(
          name: data["name"],
          color: color
        )
        tag.save!
        map_source!(:tags, old_id, tag)
        increment_summary("Tag", created ? :created : :updated)
      end
    end

    # A property's cost tag is imported after the accounts, so the link is
    # restored once both have their new ids. A record that carries the key
    # sets the link: no tag, a tag the import does not carry, or a session
    # mapping to a tag since deleted leaves the property unlinked, clearing a
    # link an earlier import made. A record without the key (an older export,
    # or another app's) keeps the property's link.
    def link_property_cost_tags(records)
      records.each do |record|
        data = record["data"] || {}
        accountable = data["accountable"]
        next unless data["accountable_type"] == "Property" && accountable.is_a?(Hash) && accountable.key?("cost_tag_id")

        account = mapped_record(:accounts, data["id"], @family.accounts, record_type: "Account")
        next unless account&.property?

        tag_id = mapped_id(:tags, accountable["cost_tag_id"], record_type: "Account", required: false)
        tag_id = nil unless tag_id && @family.tags.exists?(id: tag_id)
        account.property.update!(cost_tag_id: tag_id) unless account.property.cost_tag_id == tag_id
      end
    end

    def import_merchants(records)
      records.each do |record|
        data = record["data"]
        old_id = data["id"]

        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

        merchant.assign_attributes(
          name: data["name"],
          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 by every family on the instance, and bank syncs
    # find it by provider_merchant_id, which most providers derive from the payee
    # name (e.g. "simplefin_" + MD5 of it). So an import only reuses one that
    # already exists, as-is, and never creates one: otherwise any user could
    # choose the name, logo and website that other families' synced transactions
    # attach to. A merchant the instance does not know yet becomes this family's
    # own FamilyMerchant.
    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

        if (merchant = ProviderMerchant.find_by_import_data(data, source))
          increment_summary("ProviderMerchant", :updated)
        else
          merchant, created = FamilyMerchant.find_or_create_with_name(
            @family,
            data["name"],
            logo_url: data["logo_url"],
            website_url: data["website_url"]
          )
          increment_summary("ProviderMerchant", created ? :created : :updated)
        end

        map_source!(:merchants, old_id, merchant)
      end
    end

    def import_recurring_transactions(records)
      records.each do |record|
        data = record["data"]
        old_id = data["id"]

        require_source_id!("RecurringTransaction", old_id)

        recurring_transaction = mapped_record(
          :recurring_transactions,
          old_id,
          @family.recurring_transactions,
          record_type: "RecurringTransaction"
        )
        created = recurring_transaction.blank?

        new_account_id = remap_optional_id(:accounts, data["account_id"], record_type: "RecurringTransaction")
        next if data["account_id"].present? && new_account_id.blank?

        new_merchant_id = remap_optional_id(:merchants, data["merchant_id"], record_type: "RecurringTransaction")
        # 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
        last_occurrence_date = parse_import_date(data["last_occurrence_date"])
        next_expected_date = parse_import_date(data["next_expected_date"])
        next unless last_occurrence_date && next_expected_date

        recurring_transaction ||= @family.recurring_transactions.build
        recurring_transaction.assign_attributes(
          account_id: new_account_id,
          merchant_id: new_merchant_id,
          amount: data["amount"].to_d,
          currency: data["currency"] || @family.currency,
          expected_day_of_month: expected_day_of_month,
          last_occurrence_date: last_occurrence_date,
          next_expected_date: next_expected_date,
          status: recurring_transaction_status_for(data["status"]),
          occurrence_count: data["occurrence_count"].to_i,
          name: data["name"],
          manual: boolean_import_value(data, "manual", default: false),
          payment_url: data["payment_url"],
          autopay: boolean_import_value(data, "autopay", default: false),
          notes: data["notes"],
          expected_amount_min: data["expected_amount_min"]&.to_d,
          expected_amount_max: data["expected_amount_max"]&.to_d,
          expected_amount_avg: data["expected_amount_avg"]&.to_d,
          bill_type: imported_bill_type(data["bill_type"]),
          category_id: remap_optional_id(:categories, data["category_id"], record_type: "RecurringTransaction"),
          amount_strategy: imported_enum_value(data["amount_strategy"], RecurringTransaction.amount_strategies, "fixed"),
          notify_days_before: data["notify_days_before"],
          upcoming_window_days: data["upcoming_window_days"],
          overdue_grace_days: data["overdue_grace_days"],
          renews_on: parse_import_date(data["renews_on"]),
          trial_ends_on: parse_import_date(data["trial_ends_on"]),
          cancelled_on: parse_import_date(data["cancelled_on"]),
          anchor_date: parse_import_date(data["anchor_date"]),
          end_mode: imported_enum_value(data["end_mode"], RecurringTransaction.end_modes, "never"),
          end_on: parse_import_date(data["end_on"]),
          end_after_count: data["end_after_count"],
          weekend_adjust: imported_enum_value(data["weekend_adjust"], RecurringTransaction.weekend_adjusts, "none"),
          holiday_calendar: data["holiday_calendar"],
          matcher_hints: data["matcher_hints"] || {}
        )
        # These columns are NOT NULL with database defaults. An export written
        # before they existed omits them, and assigning nil would replace a
        # good default with a constraint violation, so they are only applied
        # when the export actually carries a value.
        recurring_transaction.assign_attributes(
          {
            amount_tolerance_pct: data["amount_tolerance_pct"]&.to_d,
            match_days_early: data["match_days_early"],
            match_days_late: data["match_days_late"],
            dedup_scope: data["dedup_scope"]
          }.compact
        )

        recurring_transaction.save!
        map_source!(:recurring_transactions, old_id, recurring_transaction)
        # A replacement points at another series that may not exist yet, so it
        # is resolved once every series has landed.
        @pending_replacements[old_id] = data["replaced_by_id"] if data["replaced_by_id"].present?
        increment_summary("RecurringTransaction", created ? :created : :updated)
      end

      resolve_pending_replacements!
    end

    def resolve_pending_replacements!
      @pending_replacements.each do |source_id, source_replacement_id|
        series_id = mapped_id(:recurring_transactions, source_id, record_type: "RecurringTransaction", required: false)
        replacement_id = mapped_id(:recurring_transactions, source_replacement_id, record_type: "RecurringTransaction", required: false)
        next if series_id.blank? || replacement_id.blank?

        @family.recurring_transactions.where(id: series_id).update_all(replaced_by_id: replacement_id)
      end
      @pending_replacements.clear
    end

    def imported_bill_type(value)
      imported_enum_value(value, RecurringTransaction.bill_types, "bill")
    end

    def imported_enum_value(value, allowed, fallback)
      value.to_s.in?(allowed.keys) ? value.to_s : fallback
    end

    def remap_optional_id(mapping_key, old_id, record_type:)
      return if old_id.blank?

      mapped_id(mapping_key, old_id, record_type: record_type)
    end

    # --- Bills subsystem -------------------------------------------------
    #
    # Creating a series generates its own occurrences, so each of these matches
    # on natural identity rather than inserting blindly: the same export
    # replayed twice lands on the same rows.

    def import_recurrence_rules(records)
      records.each do |record|
        data = record["data"]
        series = imported_series_for(data, "RecurrenceRule")
        next if series.blank?

        rule = series.recurrence_rules.find_or_initialize_by(position: data["position"].to_i)
        created = rule.new_record?
        rule.assign_attributes(
          # Enum writers raise on unknown values, and one stale export value
          # must not abort the whole import.
          frequency: imported_enum_value(data["frequency"], RecurrenceRule.frequencies, "monthly"),
          interval: data["interval"].to_i,
          day_of_month: data["day_of_month"],
          weekday: data["weekday"],
          weekday_ordinal: data["weekday_ordinal"],
          month_of_year: data["month_of_year"]
        )
        rule.save!
        increment_summary("RecurrenceRule", created ? :created : :updated)
      rescue ActiveRecord::RecordInvalid
        # The enum fallback keeps unknown cadences from raising, but the
        # substituted monthly can still be incoherent with the row's other day
        # fields, and a missing interval reads as zero. One stale export row is
        # a skip, never a rollback of every record type in the file.
        increment_summary("RecurrenceRule", :skipped)
      end
    end

    def import_recurring_occurrences(records)
      records.each do |record|
        data = record["data"]
        series = imported_series_for(data, "RecurringOccurrence")
        next if series.blank?

        original_due_on = parse_import_date(data["original_due_on"])
        if original_due_on.blank?
          increment_summary("RecurringOccurrence", :skipped)
          next
        end

        occurrence = series.recurring_occurrences.find_or_initialize_by(original_due_on: original_due_on)
        created = occurrence.new_record?
        occurrence.assign_attributes(
          family: @family,
          due_on: parse_import_date(data["due_on"]) || original_due_on,
          currency: data["currency"] || series.currency,
          expected_amount: data["expected_amount"]&.to_d,
          status: imported_occurrence_status(data["status"]),
          snoozed_until: parse_import_date(data["snoozed_until"]),
          closed_at: data["closed_at"].presence && Time.zone.parse(data["closed_at"].to_s),
          # A check constraint limits closed_source; an unknown export value
          # degrades to nil rather than aborting the import.
          closed_source: data["closed_source"].to_s.presence_in(%w[auto user]),
          notes: data["notes"]
        )
        # A check constraint ties status and closed_at together, so a closed row
        # exported without a timestamp would otherwise fail the insert. The
        # stand-in derives from the due date, not the import time, so replaying
        # the same export lands on the same value.
        if occurrence.status == "scheduled"
          occurrence.closed_at = nil
        else
          occurrence.closed_at ||= occurrence.due_on.in_time_zone
        end

        occurrence.save!
        map_source!(:recurring_occurrences, data["id"], occurrence)
        increment_summary("RecurringOccurrence", created ? :created : :updated)
      end
    end

    def import_recurring_allocations(records)
      records.each do |record|
        data = record["data"]
        # Session imports arrive in chunks, each through a fresh importer. An
        # in-memory map died with its chunk, so an allocation landing after its
        # occurrence's chunk was silently skipped. The persisted mapping is the
        # one source that survives.
        occurrence_id = mapped_id(:recurring_occurrences, data["recurring_occurrence_id"],
                                  record_type: "RecurringAllocation", required: false)
        occurrence = RecurringOccurrence.find_by(id: occurrence_id) if occurrence_id.present?
        if occurrence.blank?
          increment_summary("RecurringAllocation", :skipped)
          next
        end

        entry_id = imported_entry_id(data["transaction_id"], "RecurringAllocation")
        paid_on = parse_import_date(data["paid_on"])
        amount = data["allocated_amount"].to_d

        # A hand-recorded payment is matched on its values, and paid_on is one
        # of them; without it the default (today) would make a replay on a
        # later day miss the row and insert a duplicate.
        if entry_id.blank? && paid_on.blank?
          invalid_record!("RecurringAllocation", "paid_on", data["paid_on"])
          next
        end

        allocation = if entry_id
          RecurringAllocation.find_or_initialize_by(
            recurring_occurrence_id: occurrence_id, entry_id: entry_id
          )
        else
          # A hand-recorded payment has no natural key, so it is matched on the
          # values that make it the same payment.
          RecurringAllocation.find_or_initialize_by(
            recurring_occurrence_id: occurrence_id, entry_id: nil,
            allocated_amount: amount, paid_on: paid_on
          )
        end

        created = allocation.new_record?
        allocation.assign_attributes(
          allocated_amount: amount,
          currency: occurrence.currency,
          source_amount: data["source_amount"]&.to_d,
          source_currency: data["source_currency"],
          state: imported_allocation_value(data["state"], RecurringAllocation.states, "confirmed"),
          source: imported_allocation_value(data["source"], RecurringAllocation.sources, "user_created"),
          match_confidence: data["match_confidence"]&.to_d,
          match_signals: data["match_signals"] || {},
          paid_on: paid_on
        )
        allocation.save!
        increment_summary("RecurringAllocation", created ? :created : :updated)
      end
    end

    def import_recurring_price_changes(records)
      records.each do |record|
        data = record["data"]
        series = imported_series_for(data, "RecurringPriceChange")
        next if series.blank?

        effective_on = parse_import_date(data["effective_on"])
        if effective_on.blank?
          increment_summary("RecurringPriceChange", :skipped)
          next
        end

        change = RecurringPriceChange.find_or_initialize_by(
          recurring_transaction_id: series.id, effective_on: effective_on
        )
        created = change.new_record?
        change.assign_attributes(
          previous_amount: data["previous_amount"].to_d,
          new_amount: data["new_amount"].to_d,
          currency: data["currency"] || series.currency,
          source: imported_enum_value(data["source"], RecurringPriceChange.sources, "detected"),
          entry_id: imported_entry_id(data["transaction_id"], "RecurringPriceChange")
        )
        change.save!
        increment_summary("RecurringPriceChange", created ? :created : :updated)
      end
    end

    def import_recurring_match_rejections(records)
      records.each do |record|
        data = record["data"]
        series = imported_series_for(data, "RecurringMatchRejection")
        next if series.blank?

        entry_id = imported_entry_id(data["transaction_id"], "RecurringMatchRejection")
        # entry_id is NOT NULL here, so a rejection whose transaction did not
        # come across cannot be represented and is dropped rather than faked.
        if entry_id.blank?
          increment_summary("RecurringMatchRejection", :skipped)
          next
        end

        rejection = RecurringMatchRejection.find_or_initialize_by(
          recurring_transaction_id: series.id, entry_id: entry_id
        )
        created = rejection.new_record?
        rejection.save!
        increment_summary("RecurringMatchRejection", created ? :created : :updated)
      end
    end

    # Counts the dropped record as skipped on every nil return, so a non-strict
    # import cannot silently discard rows whose series never came across.
    def imported_series_for(data, record_type)
      series_id = remap_optional_id(
        :recurring_transactions, data["recurring_transaction_id"], record_type: record_type
      )
      series = @family.recurring_transactions.find_by(id: series_id) if series_id.present?
      increment_summary(record_type, :skipped) if series.nil?
      series
    end

    # Allocations travel with the transaction that owns their entry, because
    # that is the only id map the importer carries. An unresolvable one leaves
    # the link null: the payment and its amount still survive, which is the
    # shape the model already supports for hand-recorded payments.
    def imported_entry_id(source_transaction_id, record_type)
      return if source_transaction_id.blank?

      new_transaction_id = mapped_id(
        :transactions, source_transaction_id, record_type: record_type, required: false
      )
      return if new_transaction_id.blank?

      Entry.find_by(entryable_type: "Transaction", entryable_id: new_transaction_id)&.id
    end

    def imported_occurrence_status(status)
      status.to_s.in?(RecurringOccurrence.statuses.keys) ? status.to_s : "scheduled"
    end

    def imported_allocation_value(value, allowed, fallback)
      value.to_s.in?(allowed.keys) ? value.to_s : fallback
    end

    def recurring_transaction_status_for(status)
      status.to_s.in?(RecurringTransaction.statuses.keys) ? status.to_s : "active"
    end

    def recurring_expected_day_for(value)
      return if value.blank?

      expected_day = value.to_i
      expected_day if expected_day.between?(1, 31)
    end

    def boolean_import_value(data, key, default:)
      return default unless data.key?(key)

      ActiveModel::Type::Boolean.new.cast(data[key])
    end

    def import_transactions(records)
      records.each do |record|
        data = record["data"]
        old_id = data["id"]

        require_source_id!("Transaction", old_id)

        # Map account ID
        new_account_id = mapped_id(:accounts, data["account_id"], record_type: "Transaction")
        next unless new_account_id

        account = @family.accounts.find(new_account_id)

        # Map category ID (optional)
        new_category_id = nil
        if data["category_id"].present?
          new_category_id = mapped_id(:categories, data["category_id"], record_type: "Transaction")
        end

        # Map merchant ID (optional)
        new_merchant_id = nil
        if data["merchant_id"].present?
          new_merchant_id = mapped_id(:merchants, data["merchant_id"], record_type: "Transaction")
        end

        # Map tag IDs (optional)
        new_tag_ids = mapped_tag_ids(data["tag_ids"], record_type: "Transaction")

        entry = session_imported_entry(account, "Transaction", old_id)
        transaction = entry&.entryable if entry&.entryable.is_a?(Transaction)
        created = transaction.blank?

        transaction ||= Transaction.new
        transaction.assign_attributes(
          category_id: new_category_id,
          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(
          account: account,
          date: Date.parse(data["date"].to_s),
          amount: data["amount"].to_d,
          name: data["name"] || "Imported transaction",
          currency: data["currency"] || account.currency,
          notes: data["notes"],
          excluded: data["excluded"] || false
        )
        if @import_session
          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!

        map_source!(:transactions, old_id, transaction)
        split_rows = importable_split_rows(data)

        if split_rows.any?
          @created_entry_ids << entry.id if created
          import_split_lines!(entry, split_rows, fallback_tag_ids: new_tag_ids)
        else
          transaction.taggings.destroy_all unless created
          new_tag_ids.each do |tag_id|
            transaction.taggings.create!(tag_id: tag_id)
          end

          @created_entry_ids << entry.id if created
        end

        increment_summary("Transaction", created ? :created : :updated)
      end
    end

    def mapped_tag_ids(old_tag_ids, record_type:)
      Array(old_tag_ids).map do |old_tag_id|
        mapped_id(:tags, old_tag_id, record_type: record_type)
      end.compact.uniq
    end

    def importable_split_rows(data)
      rows = data["split_lines"].presence || data["splitLines"].presence || data["splits"].presence
      Array(rows).filter_map do |row|
        next unless row.is_a?(Hash)

        amount = row["amount"] || row["amount_money"] || row["amount_decimal"]
        next if amount.blank?

        category_id = remap_optional_id(:categories, row["category_id"], record_type: "Transaction")
        merchant_id = remap_optional_id(:merchants, row["merchant_id"], record_type: "Transaction")

        {
          old_id: row["id"],
          name: row["name"].presence || row["memo"].presence || row["description"].presence || "Imported split",
          amount: amount.to_d,
          category_id: category_id,
          merchant_id: merchant_id,
          merchant_id_provided: row.key?("merchant_id"),
          notes: row["notes"],
          excluded: boolean_import_value(row, "excluded", default: false),
          tag_ids: mapped_tag_ids(row["tag_ids"], record_type: "Transaction"),
          tag_ids_provided: row.key?("tag_ids"),
          kind: row["kind"]
        }
      end
    end

    def import_split_lines!(entry, split_rows, fallback_tag_ids:)
      children = entry.split!(
        split_rows.map do |row|
          {
            name: row[:name],
            amount: row[:amount],
            category_id: row[:category_id],
            excluded: row[:excluded]
          }
        end
      )

      children.zip(split_rows).each do |child_entry, row|
        transaction = child_entry.entryable
        transaction.update!(
          merchant_id: row[:merchant_id_provided] ? row[:merchant_id] : transaction.merchant_id,
          kind: row[:kind].presence || transaction.kind
        )
        child_entry.update!(notes: row[:notes]) if row[:notes].present?

        tag_ids = row[:tag_ids_provided] ? row[:tag_ids] : fallback_tag_ids
        tag_ids.each do |tag_id|
          transaction.taggings.create!(tag_id: tag_id)
        end

        map_source!(:transactions, row[:old_id], transaction) if row[:old_id].present?
        @created_entry_ids << child_entry.id
      end
    end

    def import_transfers(records)
      records.each do |record|
        data = record["data"]
        inflow_transaction_id = mapped_id(:transactions, data["inflow_transaction_id"], record_type: "Transfer")
        outflow_transaction_id = mapped_id(:transactions, data["outflow_transaction_id"], record_type: "Transfer")
        next unless inflow_transaction_id && outflow_transaction_id

        transfer = Transfer.find_or_create_by!(
          inflow_transaction_id: inflow_transaction_id,
          outflow_transaction_id: outflow_transaction_id
        ) do |transfer|
          transfer.status = transfer_status_for(data["status"])
          transfer.notes = data["notes"]
        end
        # Transfer kinds only apply once a transfer is confirmed (see Transfer#confirm!)
        if transfer.confirmed?
          apply_transfer_transaction_kinds!(transfer)
          # Restores a user's explicit choice over the destination's default kind.
          transfer.update_investment_contribution!(truthy?(data["investment_contribution"])) unless data["investment_contribution"].nil?
        end
        increment_summary("Transfer", transfer.previously_new_record? ? :created : :updated)
      end
    end

    def apply_transfer_transaction_kinds!(transfer)
      destination_account = transfer.inflow_transaction.entry.account
      outflow_kind = imported_transfer_outflow_kind(transfer)
      outflow_attrs = { kind: outflow_kind }
      if outflow_kind == "investment_contribution" && transfer.outflow_transaction.category_id.blank?
        outflow_attrs[:category] = destination_account.family.investment_contributions_category
      end

      transfer.outflow_transaction.update!(outflow_attrs)
      transfer.inflow_transaction.update!(kind: "funds_movement")
    end

    def imported_transfer_outflow_kind(transfer)
      source_account = transfer.outflow_transaction.entry.account
      destination_account = transfer.inflow_transaction.entry.account
      Transfer.kind_for_account(destination_account, from_account: source_account)
    end

    def import_rejected_transfers(records)
      records.each do |record|
        data = record["data"]
        # A rejected transfer is an advisory hint that stops two transactions from
        # being re-matched. When either side is missing (e.g. the transaction was
        # deleted after the rejection), skip the row instead of failing the import.
        inflow_transaction_id = mapped_id(:transactions, data["inflow_transaction_id"], record_type: "RejectedTransfer", required: false)
        outflow_transaction_id = mapped_id(:transactions, data["outflow_transaction_id"], record_type: "RejectedTransfer", required: false)
        unless inflow_transaction_id && outflow_transaction_id
          increment_summary("RejectedTransfer", :skipped)
          next
        end

        rejected_transfer = RejectedTransfer.find_or_create_by!(
          inflow_transaction_id: inflow_transaction_id,
          outflow_transaction_id: outflow_transaction_id
        )
        increment_summary("RejectedTransfer", rejected_transfer.previously_new_record? ? :created : :updated)
      end
    end

    def transfer_status_for(status)
      status = status.to_s
      return status if Transfer.statuses.key?(status)

      Rails.logger.debug("Unknown transfer status #{status.inspect}; defaulting to pending") if status.present?
      "pending"
    end

    def import_trades(records)
      imported = {}

      records.each do |record|
        data = record["data"]
        old_id = data["id"]

        require_source_id!("Trade", old_id)

        # Map account ID
        new_account_id = mapped_id(:accounts, data["account_id"], record_type: "Trade")
        next unless new_account_id

        account = @family.accounts.find(new_account_id)

        # Resolve or create security
        ticker = data["ticker"]
        next unless ticker.present?

        security = find_or_create_security(
          ticker,
          data["currency"],
          old_security_id: data["security_id"],
          name: data["security_name"],
          exchange_operating_mic: data["exchange_operating_mic"]
        )

        entry = session_imported_entry(account, "Trade", old_id)
        trade = entry&.entryable if entry&.entryable.is_a?(Trade)
        created = trade.blank?

        trade ||= Trade.new
        trade.assign_attributes(
          security: security,
          qty: data["qty"].to_d,
          price: data["price"].to_d,
          currency: data["currency"] || account.currency
        )

        entry ||= Entry.new(entryable: trade)
        entry.assign_attributes(
          account: account,
          date: Date.parse(data["date"].to_s),
          amount: data["amount"].to_d,
          name: "#{data["qty"].to_d >= 0 ? 'Buy' : 'Sell'} #{ticker}",
          currency: data["currency"] || account.currency
        )
        if @import_session
          entry.external_id = session_entry_external_id("Trade", old_id)
          entry.source = session_entry_source
        end

        entry.save!
        imported[old_id] = entry
        import_lot_total_cost(entry, data["lot_total_cost"])
        @created_entry_ids << entry.id if created
        increment_summary("Trade", created ? :created : :updated)
      end

      import_lot_sources(records, imported)
    end

    # The lot is rebuilt from its trade on the next sync, which keeps a cost
    # already on the row, so the user's cost is seeded on the row now. A file
    # without one clears a cost an earlier import of this trade set. A value
    # the lot cannot hold drops the cost, not the trade.
    def import_lot_total_cost(entry, raw)
      trade = entry.trade
      # Only a buy's entry keys a lot (source_entry_id is the acquiring
      # trade's entry), so a sell never queries. A buy's lookup is per row
      # and indexed, with no chunk-wide load.
      lot = trade.qty.positive? ? HoldingLot.find_by(account_id: entry.account_id, source_entry_id: entry.id) : nil

      if raw.blank?
        lot.unlock_cost! if lot&.manual_cost?
        return
      end

      total = BigDecimal(raw.to_s, exception: false)
      return invalid_record!("Trade", "lot_total_cost", raw) unless total&.finite? && !total.negative? && trade.qty.positive?

      lot ||= HoldingLot.new(account_id: entry.account_id, source_entry: entry, security: trade.security,
                             acquired_on: entry.date, qty: trade.qty, currency: entry.account.currency)
      lot.manual_total_cost = total
      invalid_record!("Trade", "lot_total_cost", raw) unless lot.save
    end

    # A sale names its lot by the acquiring trade, which the export writes
    # ahead of it: in this file, or in an earlier chunk of the same session.
    # The choice is restored as stored, whatever the account's method, since
    # an average account keeps but ignores it (Trade#lot_choices); it must
    # still be a sale, not a transfer out, naming an acquisition of its
    # security, in its account, that replays before it: an earlier date, or
    # the same date and entered no later. Entries are stamped in file order,
    # so a same-day lot listed after its sale is refused. A file without one
    # clears an earlier import's choice.
    def import_lot_sources(records, imported)
      unnamed = []

      records.each do |record|
        data = record["data"]
        row = imported[data["id"]]
        next unless row

        source_id = data["lot_source_trade_id"]
        if source_id.blank?
          unnamed << row.entryable_id
          next
        end

        source = imported[source_id] || session_imported_entry(row.account, "Trade", source_id)
        if source && lot_source_for?(row, source)
          Trade.where(id: row.entryable_id).update_all(lot_source_entry_id: source.id)
        else
          invalid_record!("Trade", "lot_source_trade_id", source_id)
        end
      end

      Trade.where(id: unnamed).where.not(lot_source_entry_id: nil).update_all(lot_source_entry_id: nil) if unnamed.any?
    end

    # The rule Trade#lot_choices applies to a sale and its lot, short of the
    # account's method and of whether the lot is still open.
    def lot_source_for?(sale, source)
      sale.trade.qty.negative? && !sale.trade.internal_movement? && source.trade.qty.positive? &&
        source.account_id == sale.account_id && source.trade.security_id == sale.trade.security_id &&
        ([ source.date, source.created_at ] <=> [ sale.date, sale.created_at ]) <= 0
    end

    def import_holdings(records)
      account_ids = records.filter_map do |record|
        mapped_id(:accounts, record.dig("data", "account_id"), record_type: "Holding", required: false)
      end
      accounts_by_id = @family.accounts.where(id: account_ids).index_by(&:id)

      records.each do |record|
        data = record["data"]

        new_account_id = mapped_id(:accounts, data["account_id"], record_type: "Holding")
        next unless new_account_id

        account = accounts_by_id[new_account_id]
        next unless account

        ticker = data["ticker"]
        next unless ticker.present?

        security = find_or_create_security(
          ticker,
          data["currency"],
          old_security_id: data["security_id"],
          name: data["security_name"],
          exchange_operating_mic: data["exchange_operating_mic"],
          exchange_mic: data["exchange_mic"],
          exchange_acronym: data["exchange_acronym"],
          country_code: data["country_code"],
          kind: data["kind"],
          website_url: data["website_url"]
        )

        holding_date = Date.parse(data["date"].to_s)
        holding_currency = data["currency"] || account.currency
        holding_attributes = {
          qty: data["qty"].to_d,
          price: data["price"].to_d,
          amount: data["amount"].to_d,
          currency: holding_currency,
          cost_basis: data["cost_basis"]&.to_d,
          cost_basis_source: importable_cost_basis_source(data["cost_basis_source"]),
          cost_basis_locked: truthy?(data["cost_basis_locked"]) || false,
          security_locked: truthy?(data["security_locked"]) || false
        }

        created = upsert_imported_holding!(account, security, holding_date, holding_currency, holding_attributes)
        increment_summary("Holding", created ? :created : :updated)
      end
    end

    def import_valuations(records)
      records.each do |record|
        data = record["data"]
        old_id = data["id"]

        require_source_id!("Valuation", old_id)

        # Map account ID
        new_account_id = mapped_id(:accounts, data["account_id"], record_type: "Valuation")
        next unless new_account_id

        account = @family.accounts.find(new_account_id)

        entry = session_imported_entry(account, "Valuation", old_id)
        valuation = entry&.entryable if entry&.entryable.is_a?(Valuation)
        created = valuation.blank?
        valuation ||= Valuation.new
        valuation.kind = valuation_kind_for(data["kind"])

        entry ||= Entry.new(entryable: valuation)
        entry.assign_attributes(
          account: account,
          date: Date.parse(data["date"].to_s),
          amount: data["amount"].to_d,
          name: data["name"] || "Valuation",
          currency: data["currency"] || account.currency
        )
        if @import_session
          entry.external_id = session_entry_external_id("Valuation", old_id)
          entry.source = session_entry_source
        end

        entry.save!
        @created_entry_ids << entry.id if created
        increment_summary("Valuation", created ? :created : :updated)
      end
    end

    def oldest_import_entry_dates_by_account(records)
      dates_by_account = {}

      # Account-level opening balances must precede every imported account
      # activity, including standalone valuation snapshots.
      %w[Balance Transaction Trade Holding Valuation].each do |type|
        records[type].to_a.each do |record|
          data = record["data"] || {}
          account_id = data["account_id"]
          date = parse_import_date(data["date"])
          next if account_id.blank? || date.blank?

          dates_by_account[account_id] = [ dates_by_account[account_id], date ].compact.min
        end
      end

      dates_by_account
    end

    def imported_opening_anchor_account_ids(records)
      records.each_with_object(Set.new) do |record, account_ids|
        data = record["data"] || {}
        next unless data["kind"].to_s == "opening_anchor"
        next if data["account_id"].blank?

        account_ids.add(data["account_id"])
      end
    end

    def skip_opening_balance_import?(old_id, data)
      @imported_opening_anchor_account_ids.include?(old_id) ||
        truthy?(data["skip_opening_balance_import"]) ||
        truthy?(data["authoritative_balance_history"])
    end

    def opening_balance_date_for(old_id, data)
      explicit_date = parse_import_date(
        data["opening_balance_date"] || data["opening_balance_on"]
      )

      max_allowed_date = @oldest_import_entry_dates_by_account[old_id]&.prev_day
      [ explicit_date, max_allowed_date ].compact.min
    end

    def log_failed_opening_balance_import(account, old_id, result)
      Rails.logger.warn(
        "Failed to import opening balance for account #{account.id} from source account #{old_id}: #{result.error}"
      )
    end

    def valuation_kind_for(value)
      kind = value.to_s
      Valuation.kinds.key?(kind) ? kind : "reconciliation"
    end

    def parse_import_date(value)
      return if value.blank?

      Date.parse(value.to_s)
    rescue Date::Error
      nil
    end

    def import_budgets(records)
      records.each do |record|
        data = record["data"]
        old_id = data["id"]

        require_source_id!("Budget", old_id)

        start_date = Date.parse(data["start_date"].to_s)
        end_date = Date.parse(data["end_date"].to_s)

        budget = mapped_record(:budgets, old_id, @family.budgets, record_type: "Budget")
        budget ||= untouched_household_budget(start_date, end_date) if data["user_id"].blank?
        created = budget.blank?
        budget ||= @family.budgets.build

        budget.assign_attributes(
          start_date: start_date,
          end_date: end_date,
          budgeted_spending: data["budgeted_spending"]&.to_d,
          expected_income: data["expected_income"]&.to_d,
          currency: data["currency"] || @family.currency
        )

        budget.save!
        map_source!(:budgets, old_id, budget)
        increment_summary("Budget", created ? :created : :updated)
      end
    end

    # A new family already has the household budget for the current period, with zeroed category
    # rows. Reuse it instead of colliding on the unique period; a budget that holds a plan (any
    # non-nil top-level amount, an explicit 0 included) is left alone, so the import fails on the uniqueness validation rather than overwriting it. An exported
    # personal budget (with a user) is never merged into the household budget.
    def untouched_household_budget(start_date, end_date)
      budget = @family.budgets.find_by(user_id: nil, start_date: start_date, end_date: end_date)
      return if budget.blank?
      return if budget.initialized? || budget.expected_income.present?
      return if budget.budget_categories.any? { |budget_category| budget_category.budgeted_spending.to_d.nonzero? }

      budget
    end

    def import_budget_categories(records)
      records.each do |record|
        data = record["data"]

        # Map budget ID
        new_budget_id = mapped_id(:budgets, data["budget_id"], record_type: "BudgetCategory")
        next unless new_budget_id

        # Map category ID
        new_category_id = mapped_id(:categories, data["category_id"], record_type: "BudgetCategory")
        next unless new_category_id

        budget = @family.budgets.find(new_budget_id)

        budget_category = budget.budget_categories.find_or_initialize_by(category_id: new_category_id)
        created = budget_category.new_record?
        # Only budget_id/category_id are required. A budgeted amount or
        # rollover flag the line leaves out (or leaves blank) keeps its current
        # value -- both columns are NOT NULL, so assigning nil would fail the
        # save; a new row with no amount budgets 0.
        rollover = ActiveModel::Type::Boolean.new.cast(data["rollover_enabled"])
        budget_category.assign_attributes(
          category_id: new_category_id,
          budgeted_spending: data["budgeted_spending"].present? ? data["budgeted_spending"].to_d : (budget_category.budgeted_spending || 0),
          rollover_enabled: rollover.nil? ? budget_category.rollover_enabled : rollover,
          currency: data["currency"] || budget.currency
        )

        budget_category.save!
        @rollover_user_ids << budget.user_id
        increment_summary("BudgetCategory", created ? :created : :updated)
      end
    end

    # The carried-over amount is derived state that only the calculator
    # writes, so restoring the toggle refreshes each affected chain (household,
    # or one member's personal budgets). It runs after the import's transaction
    # has committed, because the calculator takes an advisory lock. The data is
    # already in by then and the next budget load recomputes the same chain, so
    # a failure is logged rather than failing an import that has committed.
    def recompute_rollover_chains
      @rollover_user_ids.each do |user_id|
        owner = user_id && @family.users.find_by(id: user_id)
        Budget::RolloverCalculator.new(family: @family, user: owner).recompute!
      rescue StandardError => e
        DebugLogEntry.capture(
          category: "import",
          level: "warn",
          message: "Could not recompute rollover amounts after a budget import",
          source: self.class.name,
          family: @family,
          metadata: { user_id: user_id, error_class: e.class.name, error_message: e.message }
        )
      end
    end

    # New rules are appended after the family's existing ones, in the exported
    # run order; rules that already exist keep their place.
    def import_rules(records)
      records = records.each_with_index.sort_by do |record, index|
        position = Integer(record.dig("data", "position"), exception: false)
        [ position || Float::INFINITY, index ]
      end.map(&:first)
      with_stored_email_action = Rule.ids_with_stored_email_notification_action(@family.rules)
      # The last rule each group lost in this import, keyed by group id.
      left_group_last = {}

      records.each do |record|
        data = record["data"]
        old_id = data["id"]

        require_source_id!("Rule", old_id)

        rule = mapped_record(:rules, old_id, @family.rules, record_type: "Rule")
        created = rule.blank?
        rule ||= @family.rules.build

        rule.assign_attributes(
          name: data["name"],
          resource_type: data["resource_type"] || "transaction",
          active: data["active"] || false,
          effective_date: data["effective_date"].present? ? Date.parse(data["effective_date"].to_s) : nil,
          stop_processing: data["stop_processing"] || false
        )
        # Exports made before this setting existed don't carry it; keep the stored value then.
        rule.apply_immediately = data["apply_immediately"] || false if data.key?("apply_immediately")
        # Exports from before rule groups have no group key; an existing rule
        # then keeps its group.
        rule.rule_group = find_or_create_rule_group(data["group"]) if data.key?("group")

        # An email action replacing the rule's own keeps the baseline it recorded
        # (see Rule::Action#keep_notification_baseline), as stored before this
        # import: not one an earlier record of it wrote.
        had_email_action = rule.persisted? && with_stored_email_action.include?(rule.id)

        # Marked rather than destroyed now, so the rule's save removes them and
        # sees its conditions change (Rule re-seeds an email rule's baseline then).
        rule.conditions.each(&:mark_for_destruction) unless created
        rule.actions.destroy_all unless created

        # Build conditions
        (data["conditions"] || []).each do |condition_data|
          build_rule_condition(rule, condition_data)
        end

        # Build actions
        (data["actions"] || []).each do |action_data|
          build_rule_action(rule, action_data).keep_notification_baseline = had_email_action
        end

        left_group_id = rule.rule_group_id_was if rule.will_save_change_to_rule_group_id? && rule.rule_group.nil?

        rule.save!
        if left_group_id
          # Each rule leaving a group lands right below it (Rule#place_in_rule_group),
          # so one that left the same group earlier in this import would end up
          # after it. Keep the exported run order instead.
          previous = left_group_last[left_group_id] || session_rule_left_earlier(rule)
          Rule::Layout.new(@family).place_after_rule!(rule, previous) if previous
          left_group_last[left_group_id] = rule
        end
        map_source!(:rules, old_id, rule)
        increment_summary("Rule", created ? :created : :updated)
      end
    end

    # Session imports arrive in chunks, each through a fresh importer, so a rule
    # that left the same group in an earlier chunk is not in the importer's own
    # map. Rules this session has already imported come earlier in the run
    # order, and those that left the group now sit right below this one: the
    # last of that run is where this rule belongs.
    def session_rule_left_earlier(rule)
      return unless @import_session

      session_rule_ids = @import_session.source_mappings.where(source_type: "Rule").pluck(:target_id).to_set
      items = Rule::Layout.new(@family).items
      index = items.index { |item| !item.group? && item.rule.id == rule.id }
      return unless index

      items.drop(index + 1).take_while { |item| !item.group? && session_rule_ids.include?(item.rule.id) }.last&.rule
    end

    def find_or_create_rule_group(name)
      validate_rule_text!(name, field: "group")
      name = name.to_s.strip
      return if name.empty?

      @family.rule_groups.find_or_create_named!(name)
    end

    def build_rule_condition(rule, condition_data, parent: nil)
      value = resolve_rule_condition_value(condition_data)

      condition = if parent
        parent.sub_conditions.build(
          condition_type: condition_data["condition_type"],
          operator: condition_data["operator"],
          value: value
        )
      else
        rule.conditions.build(
          condition_type: condition_data["condition_type"],
          operator: condition_data["operator"],
          value: value
        )
      end

      # Handle nested sub_conditions for compound conditions
      (condition_data["sub_conditions"] || []).each do |sub_condition_data|
        build_rule_condition(rule, sub_condition_data, parent: condition)
      end

      condition
    end

    def build_rule_action(rule, action_data)
      value = resolve_rule_action_value(action_data)

      rule.actions.build(
        action_type: action_data["action_type"],
        value: value
      )
    end

    def resolve_rule_condition_value(condition_data)
      condition_type = condition_data["condition_type"]
      value = rule_operand_value(condition_data)

      return value unless value.present?

      # Map category names to IDs
      if condition_type == "transaction_category"
        return find_or_create_rule_category(value).id
      end

      # Map merchant names to IDs
      if condition_type == "transaction_merchant"
        return resolve_rule_merchant_id(condition_data, value)
      end

      # Map tag names to IDs
      if condition_type == "transaction_tag"
        return find_or_create_rule_tag(value).id
      end

      value
    end

    def resolve_rule_action_value(action_data)
      action_type = action_data["action_type"]

      # Tags store a comma-separated list of ids (see Rule::Action#value=) and
      # value_ref may be an array for multi-tag actions, so this needs its own
      # resolution path rather than the generic scalar one below (which
      # assumes value_ref is nil or a single hash).
      return resolve_multi_tag_action_value(action_data) if action_type == "set_transaction_tags"
      return resolve_split_action_value(action_data["value"]) if action_type == "split_transaction"

      value = rule_operand_value(action_data)

      return value unless value.present?

      # Map category names to IDs
      if action_type == "set_transaction_category"
        return find_or_create_rule_category(value).id
      end

      # Map merchant names to IDs
      if action_type == "set_transaction_merchant"
        return resolve_rule_merchant_id(action_data, value)
      end

      value
    end

    def resolve_multi_tag_action_value(action_data)
      value_ref = action_data["value_ref"]
      validate_rule_text!(value_ref, field: "value_ref")
      validate_rule_text!(action_data["value"], field: "value")
      refs = case value_ref
      when Array then value_ref
      when Hash then [ value_ref ]
      else []
      end

      names = refs.any? ? refs.map { |ref| ref["name"] } : Rule::Action.decode_multi_value_names(action_data["value"])

      tag_ids = names.filter_map do |name|
        next if name.blank?

        find_or_create_rule_tag(name).id
      end

      tag_ids.join(",")
    end

    # Names resolve like the other rule actions. A raw id (older exports, hand-built files) is
    # remapped through this import's source mappings, kept if it already belongs to the family,
    # and otherwise dropped.
    def resolve_split_action_value(value)
      # Checked like every other rule text, before find_or_create can hit the database with a name.
      unless Rule::ActionExecutor::SplitTransaction.acceptable_text?(value)
        raise InvalidRecordError.new(record_type: "Rule", field: "value", value: "(invalid text)")
      end

      Rule::ActionExecutor::SplitTransaction.localize_value(value) do |kind, name: nil, id: nil|
        relation = kind.to_s.pluralize.to_sym
        next mapped_id(relation, id, record_type: kind.to_s.classify, required: false) || (id if family_record_ids(relation).include?(id)) unless name

        case kind
        when :category then find_or_create_rule_category(name).id
        when :merchant then find_or_create_rule_merchant(name).id
        when :tag then find_or_create_rule_tag(name).id
        end
      end
    end

    def family_record_ids(relation)
      @family_record_ids ||= {}
      @family_record_ids[relation] ||= @family.public_send(relation).pluck(:id).to_set
    end

    # Preloaded once per import and extended in place on cache-miss, so a
    # category/merchant/tag created for an earlier record is immediately
    # visible to a later record referencing the same name, instead of one
    # query per condition/action across every imported rule.
    def rule_categories_by_name
      @rule_categories_by_name ||= @family.categories.index_by(&:name)
    end

    def rule_merchants_by_name
      @rule_merchants_by_name ||= @family.merchants.index_by(&:name)
    end

    def rule_tags_by_name
      @rule_tags_by_name ||= @family.tags.index_by(&:name)
    end

    def find_or_create_rule_category(name)
      rule_categories_by_name[name] ||= @family.categories.create!(
        name: name,
        color: Category::UNCATEGORIZED_COLOR,
        classification_unused: "expense",
        lucide_icon: "shapes"
      )
    end

    # A merchant this import already mapped (a FamilyMerchant, or a reused
    # ProviderMerchant, see import_provider_merchants) keeps the rule on the same
    # record as the restored transactions. Anything else is found or created by
    # name.
    def resolve_rule_merchant_id(data, name)
      value_ref = data["value_ref"]
      ref_id = value_ref["id"] if value_ref.is_a?(Hash) && value_ref["type"] == "Merchant"
      mapped = mapped_id(:merchants, ref_id.to_s, record_type: "Rule", required: false) if ref_id.present?

      mapped || find_or_create_rule_merchant(name).id
    end

    def find_or_create_rule_merchant(name)
      rule_merchants_by_name[name] ||= @family.merchants.create!(name: name)
    end

    def find_or_create_rule_tag(name)
      rule_tags_by_name[name] ||= @family.tags.create!(name: name)
    end

    def rule_operand_value(data)
      raw_value = data["value"]
      validate_rule_text!(raw_value, field: "value")
      validate_rule_text!(data["value_ref"], field: "value_ref")
      value = raw_value.is_a?(String) ? raw_value.presence : raw_value
      value_ref_name = data.dig("value_ref", "name")

      return value_ref_name if value.is_a?(String) && uuid_like?(value) && value_ref_name.present?
      return value unless value.nil?

      value_ref_name
    end

    def validate_rule_text!(value, field:)
      return if DatabaseTextValidator.acceptable?(value)

      raise InvalidRecordError.new(record_type: "Rule", field: field, value: "(invalid text)")
    end

    def uuid_like?(value)
      UuidFormat.valid?(value)
    end

    def importable_cost_basis_source(value)
      source = value.to_s
      Holding::COST_BASIS_SOURCES.include?(source) ? source : nil
    end

    def truthy?(value)
      ActiveModel::Type::Boolean.new.cast(value)
    end

    def find_or_create_security(ticker, currency, old_security_id: nil, **attributes)
      # Check cache first
      normalized_ticker = ticker.to_s.upcase
      exchange_operating_mic = attributes[:exchange_operating_mic].presence&.upcase
      cache_key = "#{normalized_ticker}:#{exchange_operating_mic}:#{currency}"

      if @security_cache[cache_key]
        security = @security_cache[cache_key]
        apply_security_metadata(security, normalized_ticker, attributes)
        return security
      end

      mapped_security_id = mapped_id(:securities, old_security_id, record_type: "Security", required: false)
      if old_security_id.present? && mapped_security_id
        security = Security.find(mapped_security_id)
        apply_security_metadata(security, normalized_ticker, attributes)
        @security_cache[cache_key] = security
        return security
      end

      security = find_security_by_identity(normalized_ticker, exchange_operating_mic)
      apply_security_metadata(security, normalized_ticker, attributes)

      @security_cache[cache_key] = security
      map_source!(:securities, old_security_id, security) if old_security_id.present?
      security
    end

    def find_security_by_identity(ticker, exchange_operating_mic)
      if exchange_operating_mic.present?
        return Security.find_or_initialize_by(ticker: ticker, exchange_operating_mic: exchange_operating_mic)
      end

      # Without an exchange MIC, matching by ticker is a best-effort restore path and can merge same-ticker securities from different venues.
      Security.find_by(ticker: ticker, exchange_operating_mic: nil) ||
        Security.where(ticker: ticker).order(:created_at).first ||
        Security.new(ticker: ticker)
    end

    def apply_security_metadata(security, ticker, attributes)
      assign_if_blank_or_placeholder(security, :name, attributes[:name].presence, placeholder: ticker)
      assign_if_blank(security, :exchange_operating_mic, attributes[:exchange_operating_mic].presence&.upcase)
      assign_if_blank(security, :exchange_mic, attributes[:exchange_mic].presence)
      assign_if_blank(security, :exchange_acronym, attributes[:exchange_acronym].presence)
      assign_if_blank(security, :country_code, attributes[:country_code].presence)
      assign_if_blank(security, :website_url, attributes[:website_url].presence)
      security.kind = security_kind_for(attributes[:kind]) if security.new_record? || security.kind.blank?

      security.save! if security.new_record? || security.changed?
    end

    def assign_if_blank(record, attribute, value)
      return if value.blank?
      return if record.public_send(attribute).present?

      record.public_send("#{attribute}=", value)
    end

    def assign_if_blank_or_placeholder(record, attribute, value, placeholder:)
      return if value.blank?

      current_value = record.public_send(attribute)
      return if current_value.present? && current_value != placeholder

      record.public_send("#{attribute}=", value)
    end

    def upsert_imported_holding!(account, security, date, currency, attributes)
      holding = account.holdings.find_or_initialize_by(security: security, date: date, currency: currency)
      created = holding.new_record?
      holding.assign_attributes(attributes)

      begin
        Holding.transaction(requires_new: true) { holding.save! }
      rescue ActiveRecord::RecordNotUnique
        existing = account.holdings.find_by!(security: security, date: date, currency: currency)
        existing.update!(attributes)
        created = false
      end

      created
    end

    def security_kind_for(value)
      kind = value.to_s
      Security::KINDS.include?(kind) ? kind : Security::KINDS.first
    end
end