Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
7.1 KB
Raw Blame
require "csv"

class Assistant::Function::ImportBankStatement < Assistant::Function
  self.ai_feature = :extract_pdf

  class << self
    def name
      "import_bank_statement"
    end

    def description
      <<~INSTRUCTIONS
        Use this to import transactions from a bank statement PDF that has already been uploaded.

        This function will:
        1. Extract transaction data from the PDF using AI
        2. Create a transaction import with the extracted data
        3. Return the import ID and extracted transactions for review

        The PDF must have already been uploaded via the PDF import feature.
        Only use this for PDFs that are identified as bank statements.

        Example:

        ```
        import_bank_statement({
          pdf_import_id: "abc123-def456",
          account_id: "xyz789"
        })
        ```

        If account_id is not provided, you should ask the user which account to import to.
      INSTRUCTIONS
    end
  end

  def strict_mode?
    false
  end

  def params_schema
    build_schema(
      required: [ "pdf_import_id" ],
      properties: {
        pdf_import_id: {
          type: "string",
          description: "The ID of the PDF import to extract transactions from"
        },
        account_id: {
          type: "string",
          description: "The ID of the account to import transactions into. If not provided, will return available accounts."
        }
      }
    )
  end

  def call(params = {})
    pdf_import = find_pdf_import(params["pdf_import_id"])

    unless pdf_import
      return {
        success: false,
        error: "PDF import not found",
        message: "Could not find a PDF import with ID: #{params["pdf_import_id"]}"
      }
    end

    # The web lets only those who can manage a statement act on its import, and
    # the import made here carries the statement, so the same rule applies.
    statement = pdf_import.account_statement
    if statement && !statement.manageable_by?(user)
      return {
        success: false,
        error: "statement_not_manageable",
        message: "You can view this statement but not import from it"
      }
    end

    unless pdf_import.document_type == "bank_statement"
      return {
        success: false,
        error: "not_bank_statement",
        message: "This PDF is not a bank statement. Document type: #{pdf_import.document_type}",
        available_actions: [ "Use a different PDF that is a bank statement" ]
      }
    end

    # If no account specified, return available accounts
    if params["account_id"].blank?
      return {
        success: false,
        error: "account_required",
        message: "Please specify which account to import transactions into",
        available_accounts: account_choices
      }
    end

    account = writable_accounts.find_by(id: params["account_id"]) if valid_uuid?(params["account_id"])
    unless account
      return {
        success: false,
        error: "account_not_found",
        message: "No writable account matched that account_id",
        available_accounts: account_choices
      }
    end

    availability = Ai.availability(:extract_pdf, family:, user:)
    return ai_unavailable(availability) unless availability.available?

    # The first provider in extract_pdf's route. Settings can clear the last key between the
    # availability check and this lookup, so a missing provider is the same refusal
    # (PdfImport::AiProcessor#route_provider refuses the same way).
    provider = Provider::Registry.preferred_llm_provider
    return ai_unavailable(Ai::Availability.unavailable(:extract_pdf, :not_configured)) unless provider

    response = provider.extract_bank_statement(
      pdf_content: pdf_import.pdf_file_content,
      model: model_for(provider),
      family: family
    )

    unless response.success?
      error_message = response.error&.message || "Unknown extraction error"
      return {
        success: false,
        error: "extraction_failed",
        message: "Failed to extract transactions: #{error_message}"
      }
    end

    result = response.data

    if result[:transactions].blank?
      return {
        success: false,
        error: "no_transactions_found",
        message: "Could not extract any transactions from the bank statement"
      }
    end

    # Create a CSV from extracted transactions
    csv_content = generate_csv(result[:transactions])

    # The transactions come from the statement, so the import keeps its privacy.
    import = family.imports.create!(
      type: "TransactionImport",
      account: account,
      account_statement: statement,
      raw_file_str: csv_content,
      date_col_label: "date",
      amount_col_label: "amount",
      name_col_label: "name",
      category_col_label: "category",
      notes_col_label: "notes",
      date_format: "%Y-%m-%d",
      signage_convention: "inflows_positive"
    )

    import.generate_rows_from_csv

    {
      success: true,
      import_id: import.id,
      transaction_count: result[:transactions].size,
      transactions_preview: result[:transactions].first(5),
      statement_period: result[:period],
      account_holder: result[:account_holder],
      message: "Successfully extracted #{result[:transactions].size} transactions. Import created with ID: #{import.id}. Review and publish when ready."
    }
  rescue Provider::Error, Faraday::Error, Timeout::Error, RuntimeError => e
    Rails.logger.error("ImportBankStatement error: #{e.class.name} - #{e.message}")
    Rails.logger.error(e.backtrace.first(10).join("\n"))
    {
      success: false,
      error: "extraction_failed",
      message: "Failed to extract transactions: #{e.message.truncate(200)}"
    }
  end

  private
    # Same visibility as the web's import page: another member's private
    # statement is not found, so it is neither sent to the model nor echoed back.
    def find_pdf_import(id)
      pdf_import = family.imports.find_by(id: id, type: "PdfImport")
      pdf_import if pdf_import&.viewable_by?(user)
    end

    # The import writes transactions into the account, so the user needs write
    # access to it, as the web requires to publish and the API to create.
    def writable_accounts
      family.accounts.writable_by(user)
    end

    def account_choices
      writable_accounts.visible.depositories.map { |a| { id: a.id, name: a.name } }
    end

    # The refusal every AI gate on this path returns: the router's reason and its message.
    def ai_unavailable(availability)
      { success: false, error: "ai_unavailable", reason: availability.reason.to_s, message: availability.message_for(user) }
    end

    def generate_csv(transactions)
      CSV.generate do |csv|
        csv << %w[date amount name category notes]
        transactions.each do |txn|
          csv << [
            txn[:date],
            txn[:amount],
            txn[:name] || txn[:description],
            txn[:category],
            txn[:notes]
          ]
        end
      end
    end

    # Only OpenAI takes the OpenAI model setting; other providers (Anthropic)
    # resolve their own default when given nil.
    def model_for(provider)
      Provider::Openai.effective_model if provider.is_a?(Provider::Openai)
    end
end