Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
40.7 KB
Raw Blame
class Transaction < ApplicationRecord
  include Entryable, Transferable, Ruleable, Splittable

  belongs_to :category, optional: true
  belongs_to :merchant, optional: true
  belongs_to :transfer, optional: true

  has_many :taggings, as: :taggable, dependent: :destroy
  has_many :tags, through: :taggings

  # Enrichment rows recording automatic category assignments (AI, Bayes),
  # newest first; read by Transaction::CategoryProvenance.
  has_many :auto_category_enrichments,
    -> { where(attribute_name: "category_id", source: AUTO_CATEGORY_SOURCES).order(updated_at: :desc) },
    class_name: "DataEnrichment", as: :enrichable

  # File attachments (receipts, invoices, etc.) using Active Storage
  # Supports images (JPEG, PNG, GIF, WebP) and PDFs up to 10MB each
  # Maximum 10 attachments per transaction, family-scoped access
  has_many_attached :attachments do |attachable|
    attachable.variant :thumbnail, resize_to_limit: [ 150, 150 ]
  end

  # Attachment validation constants
  MAX_ATTACHMENTS_PER_TRANSACTION = 10
  MAX_ATTACHMENT_SIZE = 10.megabytes
  ALLOWED_CONTENT_TYPES = %w[
    image/jpeg image/jpg image/png image/gif image/webp
    application/pdf
  ].freeze

  validate :validate_attachments, if: -> { attachments.attached? }

  accepts_nested_attributes_for :taggings, allow_destroy: true

  # A tag can be applied to a transaction only once, but assigning the same
  # tag twice would insert two taggings. Collapse repeats first, comparing
  # ids as the database does. The original values go on to `super`: Rails
  # drops blanks before it casts, so passing a malformed id cast to nil would
  # discard it silently instead of raising RecordNotFound.
  def tag_ids=(ids)
    id_type = Tag.type_for_attribute(:id)
    super(Array(ids).uniq { |id| id_type.cast(id) || id })
  end

  def tags=(tags)
    super(Array(tags).uniq)
  end

  after_save :clear_merchant_unlinked_association, if: :merchant_id_previously_changed?
  after_save :supersede_automatic_category_claims, if: :saved_change_to_category_id?

  # A leg that becomes a plain transfer (funds_movement, cc_payment) is left
  # uncategorized (see UNCATEGORIZED_EXCLUDED_KINDS), so the Investment
  # Contributions category its old kind gave it goes with that kind, as in
  # Transfer#update_investment_contribution!. A category set in the same save,
  # or one the user locked, stays.
  after_save :drop_stale_contribution_category,
             if: -> { saved_change_to_kind? && !saved_change_to_category_id? }

  # Plain-transfer legs still carrying an Investment Contributions category
  # from an older kind, where the user has not locked the category. One a
  # rule of the user's set (and still holds) is theirs too: rules don't lock
  # what they set, and a rule run after the kind change would set it again.
  scope :with_stale_contribution_category, -> {
    without_user_category_lock
      .joins(:category)
      .where(kind: UNCATEGORIZED_EXCLUDED_KINDS, categories: { name: Category.all_investment_contributions_names })
      .where.not(category_from_sql("rule"))
  }

  # No lock on the category, or only one an automatic categorizer set itself
  # while the category is still its value: the AI, which locks every category
  # it assigns, or Bayes with lock_results. A category the user changed since
  # is theirs, lock and all, as in Enrichable#clear_ai_cache and
  # Family#clear_bayes_locks!.
  scope :without_user_category_lock, -> {
    where("transactions.locked_attributes ->> 'category_id' IS NULL")
      .or(category_from("ai"))
      .or(category_from("bayes", metadata: { locked_by_bayes: true }))
  }

  # Clears the Investment Contributions category from the plain-transfer legs
  # in `scope` that still carry it without a lock of the user's, and touches
  # their entries. Rechecked under each row's lock (reassign_category!), so a
  # category or lock a user sets meanwhile is not overwritten. An automatic
  # categorizer's lock and claim go with the category it set, leaving the leg
  # as if never categorized. Returns how many it cleared.
  def self.drop_stale_contribution_categories!(scope = all)
    reassign_category!(scope.with_stale_contribution_category, nil) do |ids|
      where(id: ids).update_all("locked_attributes = locked_attributes - 'category_id'")
      drop_automatic_category_claims!(ids)
    end
  end

  # Drops the automatic categorizers' claim on these transactions' category,
  # so a lock on it counts as the user's even where it is the value they set:
  # the AI's enrichment goes (Enrichable#clear_ai_cache treats those as a
  # cache) and Bayes loses its lock flag, as in Family#clear_bayes_locks!.
  # Only a claim still current: one a later change superseded no longer
  # claims anything and stays, as the AI history filter lists it.
  def self.drop_automatic_category_claims!(ids)
    enrichments = DataEnrichment.where(enrichable_type: "Transaction", enrichable_id: ids, attribute_name: "category_id")
                                .where("data_enrichments.metadata->>'superseded' IS DISTINCT FROM 'true'")
    enrichments.where(source: "ai").delete_all
    enrichments.where(source: "bayes").drop_metadata_flag!("locked_by_bayes")
  end

  # Accessors for exchange_rate stored in extra jsonb field
  def exchange_rate
    extra&.dig("exchange_rate")
  end

  # The stored exchange rate as a number, read the way Money#exchange_to reads
  # it (to_d), or nil when the app would not use it: none is stored, it is not
  # a positive number that survives the conversion to Float, or the row is
  # already in the account's currency. The API and the data export read this,
  # so a malformed value written straight into extra, or an extra that is not
  # a hash, cannot break them.
  def numeric_exchange_rate
    return nil unless extra.is_a?(Hash)

    value = extra["exchange_rate"]
    return nil unless value.is_a?(Numeric) || value.is_a?(String)

    entry_currency = entry&.currency.to_s.upcase
    account_currency = entry&.account&.currency.to_s.upcase
    return nil if entry_currency.blank? || account_currency.blank? || entry_currency == account_currency

    rate = value.to_d.to_f
    rate if rate.finite? && rate.positive?
  end

  def exchange_rate=(value)
    if value.blank?
      self.extra = (extra || {}).merge("exchange_rate" => nil, "exchange_rate_invalid" => false)
    else
      begin
        normalized_value = Float(value)
        raise ArgumentError unless normalized_value.finite?

        self.extra = (extra || {}).merge("exchange_rate" => normalized_value, "exchange_rate_invalid" => false)
      rescue ArgumentError, TypeError
        # Store the raw value for validation error reporting
        self.extra = (extra || {}).merge("exchange_rate" => value, "exchange_rate_invalid" => true)
      end
    end
  end

  validate :exchange_rate_must_be_valid

  private

    # Checked and cleared in the database under the row lock rather than from
    # this record's copy, which may predate a category a categorizer or the
    # user set since it was loaded.
    def drop_stale_contribution_category
      return unless UNCATEGORIZED_EXCLUDED_KINDS.include?(kind)
      return if self.class.drop_stale_contribution_categories!(self.class.where(id: id)).zero?

      # Mirror the cleared row, so a later save or lock_attr! on this copy
      # does not write the category or its lock back.
      self.category_id, self.locked_attributes = self.class.where(id: id).pick(:category_id, :locked_attributes)
      clear_attribute_changes([ :category_id, :locked_attributes ])
    end

    def exchange_rate_must_be_valid
      if extra&.dig("exchange_rate_invalid")
        errors.add(:exchange_rate, "must be a number")
      elsif exchange_rate.present?
        numeric_rate = Float(exchange_rate) rescue nil
        if numeric_rate.nil? || !numeric_rate.finite? || numeric_rate <= 0
          errors.add(:exchange_rate, "must be greater than 0")
        end
      end
    end

  public

  enum :kind, {
    standard: "standard", # A regular transaction, included in budget analytics
    funds_movement: "funds_movement", # Movement of funds between accounts, excluded from budget analytics
    cc_payment: "cc_payment", # A CC payment, excluded from budget analytics (CC payments offset the sum of expense transactions)
    loan_payment: "loan_payment", # A payment to a Loan account, treated as an expense in budgets
    one_time: "one_time", # A one-time expense/income, excluded from budget analytics
    investment_contribution: "investment_contribution" # Transfer to investment/crypto account, treated as an expense in budgets
  }

  # All kinds where money moves between accounts (transfer? returns true).
  # Used for search filters, rule conditions, and UI display.
  TRANSFER_KINDS = %w[funds_movement cc_payment loan_payment investment_contribution].freeze

  # Kinds excluded from budget/income-statement analytics.
  # loan_payment and investment_contribution are intentionally NOT here —
  # they represent real cash outflow from a budgeting perspective.
  BUDGET_EXCLUDED_KINDS = %w[funds_movement one_time cc_payment].freeze

  # Kinds that never belong in the "Uncategorized" bucket, whichever surface
  # asks for it (the Transactions category filter, the uncategorized badge
  # count, the Quick Categorize wizard). These are the paired legs of a
  # Transfer between the user's own accounts, so they have nothing to
  # categorize. Every other kind with a NULL category does.
  #
  # This is deliberately neither of the two lists above:
  #   - vs TRANSFER_KINDS: loan_payment and investment_contribution are
  #     budget-tracked outflows the dashboard counts under Uncategorized, so
  #     hiding them left the dashboard figure unreproducible from the list
  #     with no way to find the transactions (see #2592).
  #   - vs BUDGET_EXCLUDED_KINDS: one_time is a real, categorizable
  #     expense/income that is only excluded from budget *analytics* so it
  #     doesn't skew medians. "Has no category" and "counts toward the
  #     budget" are different questions; only the former belongs here.
  UNCATEGORIZED_EXCLUDED_KINDS = %w[funds_movement cc_payment].freeze

  # All valid investment activity labels (for UI dropdown)
  ACTIVITY_LABELS = [
    "Buy", "Sell", "Sweep In", "Sweep Out", "Dividend", "Reinvestment",
    "Interest", "Fee", "Transfer", "Contribution", "Withdrawal", "Exchange", "Other"
  ].freeze

  # Internal movement labels that should be excluded from budget (auto cash management)
  INTERNAL_MOVEMENT_LABELS = [ "Transfer", "Sweep In", "Sweep Out", "Exchange" ].freeze

  # Providers that support pending transaction flags
  # sorted
  PENDING_PROVIDERS = %w[akahu enable_banking financekit lunchflow mercury monobank plaid redbark simplefin up].freeze

  # Slice size for the entry touch in reassign_category! — bounds the UPDATE
  # statement size when a merge or category destroy hits many transactions.
  REASSIGN_TOUCH_BATCH_SIZE = 5_000

  # DataEnrichment sources that represent automatic category assignment
  AUTO_CATEGORY_SOURCES = %w[ai bayes].freeze

  # Excludes enrichments (aliased de) whose value a later change superseded;
  # see #supersede_automatic_category_claims.
  UNSUPERSEDED_ENRICHMENT_SQL = "de.metadata->>'superseded' IS DISTINCT FROM 'true'".freeze

  # Stored flag values that do not mark a transaction pending: the strings
  # ActiveModel::Type::Boolean casts to false, plus "" (which it casts to nil).
  # Any other present value is pending, as #pending? decides.
  PENDING_FLAG_FALSE_VALUES = (ActiveModel::Type::Boolean::FALSE_VALUES.grep(String) + [ "" ]).uniq.freeze
  PENDING_FLAG_TYPE = ActiveModel::Type::Boolean.new.freeze

  # PENDING_FLAG_FALSE_VALUES as a list of SQL string literals. Built from the
  # constant alone, so class loading needs no database connection, and shared by
  # pending_sql and PENDING_CHECK_SQL so the two cannot quote the values
  # differently.
  PENDING_FLAG_FALSE_VALUES_SQL = PENDING_FLAG_FALSE_VALUES.map { |value| "'#{value.gsub("'", "''")}'" }.join(", ").freeze

  # Canonical reusable SQL form of the pending? decision. Callers that inspect
  # only provider namespaces they own can pass that subset in `providers:`.
  #
  # Deliberately not `(... ->> 'pending')::boolean`. PostgreSQL raises
  # PG::InvalidTextRepresentation on a value it cannot parse ("maybe"), which
  # aborts the whole query rather than one row, and it reads "no", "False" and
  # "Off" as false where ActiveModel reads them as true. Providers write JSON
  # booleans, which ->> renders as 'true', 'false' or NULL and both rules
  # classify alike, so only other values are affected.
  #
  # COALESCE maps a missing flag or JSON null to "", a false value, so no
  # provider's term is ever NULL and NOT (...) is exact.
  #
  # A JSON number 0.0 renders as '0.0' and is pending here; #pending? agrees,
  # because FALSE_VALUES is a Set keyed by eql? and 0.0 is not eql? to 0. The
  # parity test carries the case.
  def self.pending_sql(table_alias = "transactions", providers: PENDING_PROVIDERS)
    quoted_table = connection.quote_table_name(table_alias)
    selected_providers = Array(providers).map(&:to_s).uniq & PENDING_PROVIDERS
    return "FALSE" if selected_providers.empty?

    selected_providers
      .map do |provider|
        "COALESCE(#{quoted_table}.extra -> #{connection.quote(provider)} ->> #{connection.quote("pending")}, #{connection.quote("")}) NOT IN (#{PENDING_FLAG_FALSE_VALUES_SQL})"
      end
      .join(" OR ")
      .then { |predicate| "(#{predicate})" }
  end

  # Fixed-alias fragment for correlated SQL. Build from model constants without
  # borrowing a database connection during class loading.
  PENDING_CHECK_SQL = begin
    PENDING_PROVIDERS
      .map do |provider|
        "COALESCE(t.extra -> '#{provider}' ->> 'pending', '') NOT IN (#{PENDING_FLAG_FALSE_VALUES_SQL})"
      end
      .join(" OR ")
      .then { |predicate| "(#{predicate})" }
      .freeze
  end

  # The negation of pending_sql, for queries that must leave pending rows out.
  def self.not_pending_sql(table_alias = "transactions", providers: PENDING_PROVIDERS)
    "NOT (#{pending_sql(table_alias, providers: providers)})"
  end

  # The Ruby form of the same decision, over a provider metadata hash rather
  # than a record. #pending? is this method; the import adapter also needs it
  # before any record exists, for the payload it is about to write.
  #
  # Reads keys as strings, so pass string-keyed metadata or a
  # HashWithIndifferentAccess. A provider key holding anything but an object
  # says nothing about that provider and is skipped, as pending_sql skips it:
  # Hash#dig would instead raise on a scalar and take the whole caller with it.
  def self.pending_extra?(extra)
    return false unless extra.is_a?(Hash)

    PENDING_PROVIDERS.any? do |provider|
      provider_data = extra[provider]
      provider_data.is_a?(Hash) && PENDING_FLAG_TYPE.cast(provider_data["pending"])
    end
  rescue StandardError
    false
  end

  # Pending transaction scopes - filter based on provider pending flags in extra JSONB
  # Works with any provider that stores pending status in extra["provider_name"]["pending"]
  scope :pending, -> { where(Transaction.pending_sql) }

  scope :excluding_pending, -> { where(Transaction.not_pending_sql) }

  # Transactions carrying any of the given tags. A subquery rather than a
  # join, so a transaction with several of them is returned once.
  scope :with_any_tag, ->(tag_ids) {
    where(id: Tagging.where(tag_id: tag_ids, taggable_type: "Transaction").select(:taggable_id))
  }

  # SQL snippet for raw queries that must exclude pending transactions.
  # Use in income statements, balance sheets, and raw analytics.
  #
  # Emits a LEADING `AND`, so it appends to a WHERE that already has at least
  # one condition -- which is how all three callers use it
  # (IncomeStatement::FamilyStats, ::CategoryStats, ::ScopedTransactionsQuery),
  # interpolating it after their own `AND` clauses. As the first condition in a
  # WHERE it produces `WHERE AND NOT (...)`, a syntax error. Use
  # `not_pending_sql` for that position; this method is only the `AND`-prefixed
  # form of it.
  def self.pending_providers_sql(table_alias = "t", providers: PENDING_PROVIDERS)
    "AND #{not_pending_sql(table_alias, providers: providers)}"
  end

  # Transactions whose category is still the one an automatic source (e.g.
  # "ai", "bayes") set.
  scope :category_from, ->(*sources, since: nil, metadata: nil) { where(category_from_sql(*sources, since:, metadata:)) }

  def self.category_from_sql(*sources, **options)
    enriched_from_sql("category_id", *sources, **options)
  end

  # Transactions whose attribute (category_id, merchant_id; internal callers
  # only) is still the value an automatic source set: that source's
  # enrichment holds the current value and no change has superseded it since.
  # since: only enrichments written after it; metadata: only those whose
  # metadata contains it.
  def self.enriched_from_sql(attribute, *sources, since: nil, metadata: nil)
    sql = +<<~SQL.squish
      EXISTS (
        SELECT 1 FROM data_enrichments de
        WHERE de.enrichable_type = 'Transaction'
          AND de.enrichable_id = transactions.id
          AND de.attribute_name = :attribute
          AND de.source IN (:sources)
          AND de.value = to_jsonb(transactions.#{attribute}::text)
          AND #{UNSUPERSEDED_ENRICHMENT_SQL}
    SQL
    sql << " AND de.updated_at > :since" if since
    sql << " AND de.metadata @> CAST(:metadata AS jsonb)" if metadata
    sanitize_sql_array([ "#{sql})", { attribute: attribute, sources: sources.flatten.map(&:to_s), since: since, metadata: metadata&.to_json } ])
  end

  # Marks the AI's and Bayes' category enrichments of the given transactions
  # superseded: their category changed, so it is no longer the value they
  # recorded as theirs, even where it later equals it again. Callers hold the
  # transactions' row locks, so the enrichments are locked after them, as a
  # save followed by Enrichable#log_enrichment locks them.
  def self.supersede_automatic_category_claims!(transaction_ids)
    DataEnrichment.where(enrichable_type: name, enrichable_id: transaction_ids, attribute_name: "category_id", source: AUTO_CATEGORY_SOURCES)
                  .update_all(Arel.sql(%(metadata = COALESCE(metadata, '{}'::jsonb) || '{"superseded": true}'::jsonb)))
  end

  # Family-scoped query for Enrichable#clear_ai_cache
  def self.family_scope(family)
    joins(entry: :account).where(accounts: { family_id: family.id })
  end

  # Bulk category reassignment that still busts entry-keyed report caches.
  # update_all skips callbacks, so the `has_one :entry, touch: true` bump that
  # every normal save relies on (Family#entries_cache_version) never happens.
  # Expects a relation without eager loading so reselect(:id) produces
  # a single-column subquery for the IN clause. A block receives the
  # reassigned ids inside the same transaction, before their entries are
  # touched.
  def self.reassign_category!(scope, category_id)
    transaction do
      # Lock inside the scope so a concurrent category edit is rechecked before
      # its ID reaches the UPDATE, rather than overwriting the new category.
      sql = <<~SQL
        UPDATE #{quoted_table_name}
        SET category_id = #{connection.quote(category_id)}
        WHERE id IN (#{scope.reselect(:id).lock("FOR UPDATE OF transactions").to_sql})
        RETURNING id
      SQL

      # Execute the write without read-query memoization and clear cached
      # reads before selecting the affected entries.
      updated_ids = connection.exec_query(sql, "Transaction Reassign Category").rows.flatten
      connection.clear_query_cache

      next 0 if updated_ids.empty?

      yield updated_ids if block_given?

      # Touch exactly the rows the UPDATE reassigned (RETURNING), so a
      # transaction entering the scope mid-merge can't be updated without its
      # entry being touched. Locks are taken transactions-first, matching a
      # normal save; sliced to bound the entries UPDATE on large merges.
      updated_ids.each_slice(REASSIGN_TOUCH_BATCH_SIZE) do |batch|
        # The UPDATE skips the after_save that ends the automatic
        # categorizers' claims, so end them here for the rows reassigned.
        supersede_automatic_category_claims!(batch)
        Entry.where(entryable_type: "Transaction", entryable_id: batch).touch_all
      end

      updated_ids.size
    end
  end

  # Minimum characters typed before searching past transactions for name suggestions.
  MIN_LENGTH_FOR_NAME_SUGGESTION = 3

  # Past transaction names resembling the given query, each paired with the category most
  # commonly used for that exact name. Powers the "Libellé" autocomplete in the new
  # transaction form — call on a family-scoped relation, e.g. `family.transactions.name_suggestions_for(query)`.
  def self.name_suggestions_for(query, limit: 8)
    sanitized_query = query.to_s.strip
    return [] if sanitized_query.length < MIN_LENGTH_FOR_NAME_SUGGESTION

    # distinct(false) cancels any DISTINCT inherited from the caller's scope (e.g.
    # Account.accessible_by's left_joins(:account_shares).distinct) — Postgres rejects
    # SELECT DISTINCT combined with an ORDER BY expression absent from the select list.
    # Callers such as TransactionsController#name_suggestions merge in
    # Account.accessible_by, whose left_joins(:account_shares) fans out to one row per
    # share for accounts the current user owns (the owner predicate matches regardless of
    # which share row it's paired with) — so COUNT(*) below would over-count transactions
    # on any owned account shared with multiple family members. COUNT(DISTINCT
    # transactions.id) counts each transaction once no matter how the caller's scope joins.
    # Leading-wildcard ILIKE can't use index_entries_on_lower_name (a btree on
    # lower(name), which only accelerates prefix/exact matches) and falls back
    # to a scan — same tradeoff already accepted in EntrySearch#search and
    # Entry.uncategorized_matching for the same reason. Revisit with a shared
    # pg_trgm index across all three call sites if this becomes a bottleneck.
    matching_names = with_entry
      .distinct(false)
      .where("entries.name ILIKE ?", "%#{sanitize_sql_like(sanitized_query)}%")
      .group("entries.name")
      .order(Arel.sql("COUNT(DISTINCT transactions.id) DESC"))
      .limit(limit)
      .pluck(Arel.sql("entries.name"))

    name_suggestions_for_names(matching_names)
  end

  def self.name_suggestions_for_names(matching_names)
    return [] if matching_names.empty?

    # Winning (most-used) category_id per name, in one grouped query. Rows are ordered so
    # that for each name, its highest-count category_id comes first — the `||=` below then
    # keeps only that first (winning) row per name, avoiding a query per name.
    category_id_by_name = {}
    with_entry
      .distinct(false)
      .where(entries: { name: matching_names })
      .where.not(category_id: nil)
      .group("entries.name", :category_id)
      .order(Arel.sql("entries.name ASC, COUNT(DISTINCT transactions.id) DESC"))
      .pluck(Arel.sql("entries.name"), :category_id)
      .each { |name, category_id| category_id_by_name[name] ||= category_id }

    categories_by_id = Category.where(id: category_id_by_name.values.uniq).index_by(&:id)

    matching_names.map do |name|
      Transaction::NameSuggestion.new(name: name, category: categories_by_id[category_id_by_name[name]])
    end
  end

  # Overarching grouping method for all transfer-type transactions
  def transfer?
    TRANSFER_KINDS.include?(kind)
  end

  # Whether the user can assign a category (and merchant/tags) to this
  # transaction. Regular transactions always qualify. For transfers:
  #   - No Transfer record yet (e.g. an unmatched provider-imported leg):
  #     stay editable, same as a regular transaction, since there's no
  #     counterpart to defer to and no other way for the user to fix a
  #     provider mislabel.
  #   - Once matched, the category belongs to the outflow leg, the one
  #     budgets and reports count. Only that leg is editable, and only when
  #     Transfer#categorizable?, which is based on the (stable) destination
  #     account rather than either leg's kind, so it stays correct even if
  #     an older provider sync left a stale kind on this transaction. The
  #     inflow leg shows the outflow's category instead (see
  #     #category_set_on_transfer_outflow?), since a category picked there
  #     would look saved but never reach a budget.
  def category_editable?
    return false if category_set_on_transfer_outflow?
    return true unless transfer?
    return true unless transfer

    transfer.categorizable? && transfer.outflow_transaction_id == id
  end

  # The inflow leg of a categorizable transfer: its category is the
  # outflow's, shown read-only. Decided by the Transfer record rather than
  # this leg's kind, so editing the kind (e.g. to standard) cannot bypass
  # the outflow's ownership.
  def category_set_on_transfer_outflow?
    transfer_as_inflow.present? && transfer_as_inflow.categorizable?
  end

  # Whether this non-editable transfer leg is a liability payment (shown
  # with the "Payment" badge instead of "Transfer"). Defers to the attached
  # Transfer when one exists, since a matched transaction's own kind can be
  # stale (rows a provider sync overwrote before the import adapter derived
  # matched legs from their Transfer), which would otherwise let a stale
  # "cc_payment" kind override a transfer that isn't actually a payment.
  # Only falls back to the transaction's own kind when there's no Transfer
  # record yet (e.g. a provider-imported cc_payment leg whose counterpart
  # hasn't been matched), the same pattern category_editable? uses.
  def payment?
    transfer ? transfer.payment? : kind == "cc_payment"
  end

  # Automatic-categorization provenance for the UI, or nil when no
  # ai/bayes enrichment was ever recorded for this transaction.
  def category_provenance
    # ||= alone would re-run the lookup every call for transactions with no
    # automatic categorization history (nil is not memoized by ||=).
    return @category_provenance if defined?(@category_provenance)

    @category_provenance = Transaction::CategoryProvenance.for(self)
  end

  def set_category!(category)
    if category.is_a?(String)
      category = entry.account.family.categories.find_or_create_by!(
        name: category
      )
    end

    update!(category: category)
  end

  # Adds or removes one tag while holding the row lock. Assigning tag_ids
  # replaces the whole set, so two quick toggles computed from the same
  # snapshot would drop one of them; per-tagging writes under the lock can't.
  def toggle_tag!(tag)
    with_lock do
      existing = taggings.where(tag: tag)
      existing.exists? ? existing.destroy_all : taggings.create!(tag: tag)
    end
    tags.reset
  end

  # Applies a tag picker's changes (selected_ids against previous_ids, the set
  # it last saved) to the tags stored now, so tags another writer added in the
  # meantime stay. Takes the same row lock as toggle_tag! and the rule tag
  # action and reads the tags after it, so no concurrent write is lost.
  def merge_tag_changes!(selected_ids, previous_ids, available_tags:)
    selected_ids = selected_ids.map(&:to_s)
    previous_ids = previous_ids.map(&:to_s)

    with_lock do
      wanted_ids = tag_ids.map(&:to_s) - (previous_ids - selected_ids) | (selected_ids - previous_ids)
      self.tag_ids = available_tags.where(id: wanted_ids).pluck(:id)
    end
  end

  # Replaces the whole tag set with the given ids, limited to available_tags,
  # under the same row lock as toggle_tag! and merge_tag_changes!, so the
  # replacement can't interleave with another writer's tag change.
  def replace_tags!(tag_ids, available_tags:)
    with_lock do
      self.tag_ids = available_tags.where(id: tag_ids).pluck(:id)
    end
  end

  # Marks a category as recently used. Called explicitly from the manual
  # category-assignment controllers (picker, edit form, categorization
  # wizard, create-and-assign) after a successful save — not wired to a
  # blanket after_save callback because rule and import auto-assignment
  # also go through `category_id=`, and those shouldn't count as a "recent"
  # pick. See Category.recently_used_for.
  def record_category_usage!
    category.touch(:last_used_at) if saved_change_to_category_id? && category.present?
  end

  def pending?
    self.class.pending_extra?(extra)
  end

  def activity_security_id
    return nil unless extra.is_a?(Hash)

    nested_security = extra["security"]
    extra["security_id"].presence || (nested_security["id"].presence if nested_security.is_a?(Hash))
  end

  UUID_FORMAT = /\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\z/

  # activity_security_id as the API and the data export emit it: a uuid
  # string, or nil when extra holds anything else under the key.
  def serializable_security_id
    id = activity_security_id
    id if id.is_a?(String) && id.match?(UUID_FORMAT)
  end

  # The provider's own type for this row, such as IBKR's "Withholding Tax",
  # read from extra[<entry source>]["type"] where importers keep it. Only this
  # string is exposed; the rest of the provider payload stays internal.
  def provider_type
    source = entry&.source
    return nil if source.blank? || !extra.is_a?(Hash)

    payload = extra[source]
    type = payload["type"] if payload.is_a?(Hash)
    type.presence if type.is_a?(String)
  end

  def activity_security
    security_id = activity_security_id.to_s
    return @activity_security = nil if security_id.blank?
    return @activity_security if defined?(@activity_security_id) && @activity_security_id == security_id

    @activity_security_id = security_id
    @activity_security = Security.find_by(id: security_id)
  end

  def set_preloaded_activity_security(security)
    @activity_security_id = security&.id&.to_s
    @activity_security = security
  end

  # Potential duplicate matching methods
  # These help users review and resolve fuzzy-matched pending/posted pairs

  def has_potential_duplicate?
    potential_posted_match_data.present? && !potential_duplicate_dismissed?
  end

  def potential_duplicate_entry
    return nil unless has_potential_duplicate?
    Entry.find_by(id: potential_posted_match_data["entry_id"])
  end

  def potential_duplicate_reason
    potential_posted_match_data&.dig("reason")
  end

  def potential_duplicate_confidence
    potential_posted_match_data&.dig("confidence") || "medium"
  end

  def low_confidence_duplicate?
    potential_duplicate_confidence == "low"
  end

  def potential_duplicate_posted_amount
    potential_posted_match_data&.dig("posted_amount")&.to_d
  end

  def potential_duplicate_dismissed?
    potential_posted_match_data&.dig("dismissed") == true
  end

  # Merge this pending transaction with its suggested posted match.
  # The pending entry is destroyed; the posted entry survives with attributes inherited from both sides.
  # Attribute inheritance: Date + Category from pending, Name + Merchant from posted (booked).
  def merge_with_duplicate!
    return false unless pending?
    return false unless has_potential_duplicate?

    posted_entry = potential_duplicate_entry
    return false unless posted_entry

    pending_entry = entry

    # Guard: cross-account merges are never valid
    if posted_entry.account_id != pending_entry.account_id
      Rails.logger.warn("merge_with_duplicate! rejected: posted_entry #{posted_entry.id} belongs to different account than pending entry #{pending_entry.id}")
      return false
    end

    pending_entry_id = pending_entry.id
    merge_succeeded = false

    ApplicationRecord.transaction(requires_new: true) do
      # Row-level locks prevent concurrent merges on the same pair of entries.
      # If a concurrent request already destroyed the pending entry, lock! raises
      # RecordNotFound — treat that as an idempotent success.
      begin
        pending_entry.lock!
      rescue ActiveRecord::RecordNotFound
        Rails.logger.info("Pending entry #{pending_entry_id} already destroyed (concurrent merge), skipping")
        return true
      end

      begin
        posted_entry.lock!
      rescue ActiveRecord::RecordNotFound
        Rails.logger.info("Posted entry #{posted_entry.id} deleted concurrently; aborting merge")
        raise ActiveRecord::Rollback
      end

      # Capture after lock! (which reloads) to guarantee DB-fresh values and avoid
      # stale in-memory cached associations (e.g., loaded via touch: true).
      external_id        = pending_entry.external_id
      pending_entry_date = pending_entry.date

      # Batch all changes to the surviving posted Transaction into a single update!
      # to avoid firing after_save callbacks twice on the same row.
      # Lock the Transaction row so concurrent merges into the same posted entry
      # cannot race on reading/writing extra (e.g., the manual_merge array).
      posted_tx = posted_entry.entryable
      posted_tx.lock! if posted_tx.is_a?(Transaction)

      # Moving the attachments bypasses validation, so refuse a merge that would
      # leave the posted transaction over the limit instead of dropping files.
      if posted_tx.is_a?(Transaction) && pending_entry.entryable.is_a?(Transaction) &&
          attachment_count_after_merge(from: pending_entry.entryable, to: posted_tx) > MAX_ATTACHMENTS_PER_TRANSACTION
        Rails.logger.info("merge_with_duplicate! rejected: merging pending entry #{pending_entry_id} would exceed #{MAX_ATTACHMENTS_PER_TRANSACTION} attachments")
        raise ActiveRecord::Rollback
      end

      if posted_tx.is_a?(Transaction)
        tx_attrs = {}

        # Merge metadata — always written so the sync engine can skip re-importing.
        # Stored as an array so multiple pending entries merged into the same posted
        # transaction each preserve their external_id for future sync exclusion.
        # Legacy records written as a plain Hash are migrated to a single-element array
        # on first append, maintaining backward compatibility.
        if external_id.present?
          new_record = {
            "merged_from_entry_id"    => pending_entry_id,
            "merged_from_external_id" => external_id,
            "merged_at"               => Time.current.iso8601,
            "source"                  => pending_entry.source
          }
          prior = case posted_tx.extra["manual_merge"]
          when Array then posted_tx.extra["manual_merge"]
          when Hash  then [ posted_tx.extra["manual_merge"] ]
          else []
          end
          tx_attrs[:extra] = posted_tx.extra.merge("manual_merge" => prior + [ new_record ])
        end

        # Attribute inheritance — only when the posted entry is not already user-protected.
        unless posted_entry.protected_from_sync?
          pending_transaction = pending_entry.entryable
          if pending_transaction.is_a?(Transaction) && pending_transaction.category_id.present?
            tx_attrs[:category_id] = pending_transaction.category_id
          end
        end

        posted_tx.update!(tx_attrs) if tx_attrs.any?

        # Keep what the user added to the pending transaction (e.g. a receipt attached
        # before the bank booked it); destroying the pending entry would purge it.
        pending_transaction = pending_entry.entryable
        carry_over_user_additions(from: pending_transaction, to: posted_tx) if pending_transaction.is_a?(Transaction)
      end

      # Date inheritance on the Entry row — separate from the Transaction update above.
      entry_attrs = {}
      unless posted_entry.protected_from_sync?
        # Date: pending dates reflect actual transaction initiation time
        entry_attrs[:date] = pending_entry_date if posted_entry.date != pending_entry_date
        # Name + Merchant intentionally NOT inherited — booked values are canonical
      end

      # Notes are the user's own text, so they are kept even on a protected entry.
      notes = merged_notes(posted_entry.notes, pending_entry.notes)
      entry_attrs[:notes] = notes if notes != posted_entry.notes

      posted_entry.update!(entry_attrs) if entry_attrs.any?

      # Lock the posted entry so future syncs cannot overwrite the merged state
      posted_entry.mark_user_modified!

      Rails.logger.info("User merged pending entry #{pending_entry_id} (ext: #{external_id}) into posted entry #{posted_entry.id}")
      pending_entry.destroy!
      merge_succeeded = true
    end

    merge_succeeded
  end

  # Dismiss the duplicate suggestion - user says these are NOT the same transaction
  def dismiss_duplicate_suggestion!
    return false unless potential_posted_match_data.present?

    updated_extra = (extra || {}).deep_dup
    updated_extra["potential_posted_match"]["dismissed"] = true
    update!(extra: updated_extra)

    Rails.logger.info("User dismissed duplicate suggestion for entry #{entry.id}")
    true
  end

  # Clear the duplicate suggestion entirely
  def clear_duplicate_suggestion!
    return false unless potential_posted_match_data.present?

    updated_extra = (extra || {}).deep_dup
    updated_extra.delete("potential_posted_match")
    update!(extra: updated_extra)
    true
  end

  # Find potential posted transactions that might be duplicates of this pending transaction
  # Returns entries (not transactions) for UI consistency with transfer matcher
  # Lists recent posted transactions from the same account for manual merging
  def pending_duplicate_candidates(limit: 20, offset: 0)
    return Entry.none unless pending? && entry.present?

    account = entry.account
    currency = entry.currency

    # Find recent posted transactions from the same account
    account.entries
      .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'")
      .where.not(id: entry.id)
      .where(currency: currency)
      .where(Transaction.not_pending_sql)
      .order(date: :desc, created_at: :desc)
      .limit(limit)
      .offset(offset)
  end

  private
    # Moves the pending transaction's attachments (the attachment rows themselves, so the
    # blobs are not purged with the pending entry) and adds its tags to the posted one.
    def carry_over_user_additions(from:, to:)
      if from.attachments.attached?
        # A blob already attached to the posted transaction would collide with the
        # unique index on attachments once re-pointed, and is kept there anyway.
        from.attachments_attachments.where(blob_id: to.attachments_attachments.select(:blob_id)).delete_all
        from.attachments_attachments.update_all(record_id: to.id)
      end

      new_tags = from.tags.where.not(id: to.tags.select(:id))
      to.tags << new_tags if new_tags.any?
    end

    def attachment_count_after_merge(from:, to:)
      to_blob_ids = to.attachments_attachments.pluck(:blob_id)
      to_blob_ids.size + from.attachments_attachments.where.not(blob_id: to_blob_ids).count
    end

    # Notes merged earlier are joined by blank lines, so look for the pending
    # note's paragraphs, in order, among the posted note's: "Order 123" is not
    # already in "Order 1234", and a multi-paragraph note is not split apart.
    def merged_notes(posted_notes, pending_notes)
      return posted_notes if pending_notes.blank?
      return pending_notes if posted_notes.blank?
      posted_parts = posted_notes.split(/\n{2,}/).map(&:strip)
      pending_parts = pending_notes.split(/\n{2,}/).map(&:strip)
      return posted_notes if posted_parts.each_cons(pending_parts.size).include?(pending_parts)

      "#{posted_notes}\n\n#{pending_notes}"
    end

    def validate_attachments
      # Check attachment count limit
      if attachments.size > MAX_ATTACHMENTS_PER_TRANSACTION
        errors.add(:attachments, :too_many, max: MAX_ATTACHMENTS_PER_TRANSACTION)
      end

      # Validate each attachment
      attachments.each_with_index do |attachment, index|
        # Check file size
        if attachment.byte_size > MAX_ATTACHMENT_SIZE
          errors.add(:attachments, :too_large, index: index + 1, max_mb: MAX_ATTACHMENT_SIZE / 1.megabyte)
        end

        # Check content type
        unless ALLOWED_CONTENT_TYPES.include?(attachment.content_type)
          errors.add(:attachments, :invalid_format, index: index + 1, file_format: attachment.content_type)
        end
      end
    end

    def potential_posted_match_data
      return nil unless extra.is_a?(Hash)
      extra["potential_posted_match"]
    end

    def clear_merchant_unlinked_association
      return unless merchant_id.present? && merchant.is_a?(ProviderMerchant)

      family = entry&.account&.family
      return unless family

      FamilyMerchantAssociation.where(family: family, merchant: merchant).delete_all
    end

    # The AI's or Bayes' category counts as theirs while it is still the value
    # they recorded, which a category changed away and back again would
    # satisfy too. Any change marks their records superseded; the records stay
    # as history (the "AI history" filter). A change the source makes itself
    # rewrites its record's metadata right after the save
    # (Enrichable#log_enrichment), so only someone else's change ends a claim.
    def supersede_automatic_category_claims
      self.class.supersede_automatic_category_claims!([ id ])
    end
end