Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
7.8 KB
Raw Blame
class MonobankItem < ApplicationRecord
  include Syncable, Provided, Unlinking, Encryptable, DestroyableLater

  enum :status, { good: "good", requires_update: "requires_update" }, default: :good

  if encryption_ready?
    encrypts :access_token, deterministic: true
    encrypts :raw_payload
    encrypts :raw_institution_payload
  end

  belongs_to :family
  has_one_attached :logo, dependent: :purge_later
  has_many :monobank_accounts, dependent: :destroy
  has_many :accounts, through: :monobank_accounts

  validates :name, presence: true
  validates :access_token, presence: true, on: :create

  # Monobank is a single institution, so unlike an aggregator its metadata is known up
  # front instead of being discovered per connection. Applied on the model so both the
  # settings panel and Family#create_monobank_item! get it.
  before_validation :apply_institution_defaults, on: :create

  scope :active, -> { where(scheduled_for_deletion: false) }
  scope :syncable, -> { active }
  scope :ordered, -> { order(created_at: :desc) }
  scope :needs_update, -> { where(status: :requires_update) }

  # Run the importer to fetch the latest accounts/transactions from Monobank.
  def import_latest_monobank_data
    provider = monobank_provider
    unless provider
      DebugLogEntry.capture(
        category: "provider_sync_error",
        level: "error",
        message: "Cannot import: Monobank provider is not configured",
        source: self.class.name,
        provider_key: "monobank",
        family: family,
        metadata: { monobank_item_id: id }
      )
      raise StandardError.new("Monobank provider is not configured")
    end

    MonobankItem::Importer.new(self, monobank_provider: provider).import
  rescue => e
    DebugLogEntry.capture(
      category: "provider_sync_error",
      level: "error",
      message: "Failed to import data",
      source: self.class.name,
      provider_key: "monobank",
      family: family,
      metadata: { monobank_item_id: id, error_class: e.class.name, error_message: e.message }
    )
    raise
  end

  # Process each linked, visible Monobank account, returning a per-account result array.
  def process_accounts
    return [] if monobank_accounts.empty?

    monobank_accounts.joins(:account).merge(Account.visible).map do |monobank_account|
      result = MonobankAccount::Processor.new(monobank_account).process
      if result.is_a?(Hash) && result.with_indifferent_access[:success] == false
        { monobank_account_id: monobank_account.id, success: false, error: I18n.t("monobank_item.errors.account_processing_failed") }
      else
        { monobank_account_id: monobank_account.id, success: true, result: result }
      end
    rescue => e
      DebugLogEntry.capture(
        category: "provider_sync_error",
        level: "error",
        message: "Failed to process account",
        source: self.class.name,
        provider_key: "monobank",
        family: family,
        account_provider: monobank_account.account_provider,
        metadata: { monobank_item_id: id, monobank_account_id: monobank_account.id, error_class: e.class.name, error_message: e.message }
      )
      { monobank_account_id: monobank_account.id, success: false, error: I18n.t("monobank_item.errors.account_processing_failed") }
    end
  end

  # Enqueue a balance sync for each visible linked account, returning per-account results.
  def schedule_account_syncs(parent_sync: nil, window_start_date: nil, window_end_date: nil)
    return [] if accounts.empty?

    accounts.visible.map do |account|
      account.sync_later(
        parent_sync: parent_sync,
        window_start_date: window_start_date,
        window_end_date: window_end_date
      )
      { account_id: account.id, success: true }
    rescue => e
      DebugLogEntry.capture(
        category: "provider_sync_error",
        level: "error",
        message: "Failed to schedule sync for account",
        source: self.class.name,
        provider_key: "monobank",
        family: family,
        account: account,
        metadata: { monobank_item_id: id, account_id: account.id, error_class: e.class.name, error_message: e.message }
      )
      { account_id: account.id, success: false, error: I18n.t("monobank_item.errors.account_sync_schedule_failed") }
    end
  end

  # Persist the latest client-info payload for this item.
  #
  # The client's personal name is dropped before storing: it is never used for syncing
  # or display, and raw_payload is only encrypted at rest when the deployment has
  # ActiveRecord encryption configured. The Monobank client id is kept as the
  # institution id so support can correlate a connection without holding a name.
  def upsert_monobank_snapshot!(client_info_snapshot)
    snapshot = client_info_snapshot.to_h.with_indifferent_access.except(:name)

    assign_attributes(
      institution_id: snapshot[:clientId].presence || institution_id,
      raw_payload: snapshot
    )
    save!
  end

  # True once at least one Monobank account has been linked to a Sure account.
  def has_completed_initial_setup?
    accounts.any?
  end

  # Human-readable summary of linked vs. unlinked account counts.
  def sync_status_summary
    total_accounts = total_accounts_count
    linked_count = linked_accounts_count
    unlinked_count = unlinked_accounts_count

    if total_accounts.zero?
      I18n.t("monobank_item.sync_status.no_accounts")
    elsif unlinked_count.zero?
      I18n.t("monobank_item.sync_status.all_synced", count: linked_count)
    else
      I18n.t("monobank_item.sync_status.partial", linked: linked_count, unlinked: unlinked_count)
    end
  end

  # Number of Monobank accounts linked to a Sure account.
  def linked_accounts_count
    account_counts[:linked]
  end

  # Number of unlinked Monobank accounts still awaiting setup.
  def unlinked_accounts_count
    account_counts[:unlinked]
  end

  # Total number of Monobank accounts under this item.
  def total_accounts_count
    account_counts[:total]
  end

  # Best available display name for the connected institution.
  def institution_display_name
    institution_name.presence || institution_domain.presence || name
  end

  # Distinct institution metadata across this item's accounts.
  def connected_institutions
    monobank_accounts.includes(:account)
               .where.not(institution_metadata: nil)
               .map(&:institution_metadata)
               .uniq { |inst| inst["name"] || inst["domain"] }
  end

  # Human-readable summary of connected institutions (none/one/count).
  def institution_summary
    institutions = connected_institutions
    case institutions.count
    when 0
      I18n.t("monobank_item.institution_summary.none")
    when 1
      institutions.first["name"].presence || I18n.t("monobank_item.institution_summary.one")
    else
      I18n.t("monobank_item.institution_summary.count", count: institutions.count)
    end
  end

  # True when an access token is present and the item can call the Monobank API.
  def credentials_configured?
    access_token.present?
  end

  private

    def apply_institution_defaults
      self.institution_name ||= MonobankAccount::INSTITUTION_NAME
      self.institution_domain ||= MonobankAccount::INSTITUTION_DOMAIN
      self.institution_url ||= "https://#{MonobankAccount::INSTITUTION_DOMAIN}"
    end

    # Single query for all three account counts, reused across sync_status_summary
    # and the settings partial to avoid 3+ separate COUNT queries per rendered item.
    def account_counts
      @account_counts ||= begin
        rows = monobank_accounts
                 .left_joins(:account_provider)
                 .pluck(Arel.sql("account_providers.id IS NOT NULL"), :ignored)

        linked = rows.count { |has_provider, _ignored| has_provider }
        unlinked = rows.count { |has_provider, ignored| !has_provider && !ignored }

        { linked: linked, unlinked: unlinked, total: rows.size }
      end
    end
end