Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
13.1 KB
Raw Blame
class ImportsController < ApplicationController
  include ViewableImports
  include SettingsHelper

  before_action :set_import, only: %i[show update publish destroy revert apply_template cancel summary]
  before_action :require_statement_import_permission!, only: %i[update publish destroy revert apply_template cancel]
  before_action :require_writable_import_accounts!, only: %i[publish revert destroy]
  before_action :reject_guest_family_config_import!, except: %i[index new show summary]
  before_action :require_guest_writable_created_accounts!, only: %i[revert destroy]
  before_action :reject_guest_new_categories_or_tags!, only: :publish

  def update
    # Handle both pdf_import[account_id] and import[account_id] param formats
    account_id = params.dig(:pdf_import, :account_id) || params.dig(:import, :account_id)

    if account_id.present?
      account = accessible_accounts.find_by(id: account_id)
      unless account
        redirect_back_or_to import_path(@import), alert: t("imports.update.invalid_account", default: "Account not found.")
        return
      end
      return if @import.account_statement.present? && !require_account_permission!(account)

      if @import.is_a?(PdfImport)
        # Refused for an import whose data already landed -- see
        # PdfImport#reassignable?. A replayed or back-button PATCH gets the
        # explanation rather than a silent unwind.
        unless @import.assign_account!(account)
          redirect_back_or_to import_path(@import), alert: t("imports.update.account_locked")
          return
        end
      else
        @import.update!(account: account)
      end
    end

    redirect_to import_path(@import), notice: t("imports.update.account_saved", default: "Account saved.")
  end

  def publish
    # A failed import can stop being publishable, for example when a Monarch
    # destination gained trades. The import page then sends it back to the
    # step that needs a new choice.
    return redirect_to import_path(@import) if @import.failed? && !@import.publishable?

    @import.publish_later

    redirect_to import_path(@import), notice: t(".started")
  rescue Import::MaxRowCountExceededError
    redirect_back_or_to import_path(@import), alert: t(".max_rows_exceeded", max: @import.max_row_count)
  end

  # Statement imports only: what became of each extracted transaction. Without it
  # a statement whose lines all matched finishes on the generic complete screen,
  # which cannot distinguish "everything was already recorded" from "nothing was
  # found".
  def summary
    raise ActiveRecord::RecordNotFound unless @import.is_a?(PdfImport)
  end

  def cancel
    if @import.force_fail!
      redirect_to imports_path, notice: t(".cancelled")
    else
      redirect_to imports_path, alert: t(".not_cancellable")
    end
  end

  def index
    @pagy, @imports = pagy(viewable_imports.where(type: Import::TYPES).ordered, limit: safe_per_page)
    @breadcrumbs = [
      [ t("breadcrumbs.home"), root_path ],
      [ t("breadcrumbs.imports"), imports_path ]
    ]
    respond_to do |format|
      format.html { render layout: "settings" }
    end
  end

  def new
    @pending_import = viewable_imports.ordered.pending.first
    @document_upload_extensions = document_upload_supported_extensions
  end

  def create
    file = import_params[:import_file]

    if file.present? && document_upload_request?
      create_document_import(file)
      return
    end

    if file.present? && sure_import_request?
      create_sure_import(file)
      return
    end

    # These types require a file; without one (e.g. a dropped multipart part) don't fall through to a bogus TransactionImport.
    if file.blank? && (document_upload_request? || sure_import_request?)
      redirect_to new_import_path, alert: t("imports.create.missing_upload")
      return
    end

    # Handle PDF file uploads - process with AI
    if file.present? && Import::ALLOWED_PDF_MIME_TYPES.include?(file.content_type)
      unless valid_pdf_file?(file)
        redirect_to new_import_path, alert: t("imports.create.invalid_pdf")
        return
      end
      create_pdf_import(file)
      return
    end

    type = params.dig(:import, :type).to_s
    type = "TransactionImport" unless Import::TYPES.include?(type)

    account = accessible_accounts.find_by(id: params.dig(:import, :account_id))
    import = Current.family.imports.create!(
      type: type,
      account: account,
      date_format: Current.family.date_format,
    )

    if file.present?
      if file.size > Import::MAX_CSV_SIZE
        import.destroy
        redirect_to new_import_path, alert: t("imports.create.file_too_large", max_size: Import::MAX_CSV_SIZE / 1.megabyte)
        return
      end

      unless Import::ALLOWED_CSV_MIME_TYPES.include?(file.content_type)
        import.destroy
        redirect_to new_import_path, alert: t("imports.create.invalid_file_type")
        return
      end

      # Stream reading is not fully applicable here as we store the raw string in the DB,
      # but we have validated size beforehand to prevent memory exhaustion from massive files.
      import.raw_file_str = file.read
      import.preset_for_uploaded_csv
      import.save!

      redirect_to import_configuration_path(import), notice: t("imports.create.csv_uploaded")
    else
      redirect_to import_upload_path(import)
    end
  rescue ActionController::ParameterMissing
    redirect_to new_import_path, alert: t("imports.create.missing_upload")
  end

  def show
    unless @import.requires_csv_workflow?
      if !@import.uploaded?
        redirect_to import_upload_path(@import), alert: t("imports.show.finalize_upload")
      elsif @import.is_a?(MonarchImport) && (@import.pending? || @import.failed?) && !@import.publishable?
        redirect_to import_configuration_path(@import), alert: (@import.failed? && @import.error.presence) || t("imports.show.finalize_mappings")
      end
      return
    end

    if !@import.uploaded?
      redirect_to import_upload_path(@import), alert: t("imports.show.finalize_upload")
    elsif !@import.publishable?
      next_path = @import.mapping_steps.empty? ? import_clean_path(@import) : import_confirm_path(@import)
      redirect_to next_path, alert: t("imports.show.finalize_mappings")
    end
  end

  def revert
    @import.revert_later
    redirect_to imports_path, notice: t(".started")
  end

  def apply_template
    if @import.suggested_template
      @import.apply_template!(@import.suggested_template)
      redirect_to import_configuration_path(@import), notice: t(".template_applied")
    else
      redirect_to import_configuration_path(@import), alert: t(".no_template_found")
    end
  end

  def destroy
    @import.destroy

    redirect_to imports_path, notice: t(".deleted")
  end

  private
    def set_import
      @import = viewable_imports.includes(:account, :account_statement).find(params[:id])
    end

    def import_params
      params.require(:import).permit(:import_file)
    end

    def reject_guest_family_config_import!
      type = @import ? @import.type : params.dig(:import, :type).to_s
      require_non_guest! if Import::FAMILY_CONFIG_TYPES.include?(type)
    end

    # Reverting or deleting an import also destroys the accounts it created,
    # which require_writable_import_accounts! leaves out. Guests are read-only
    # by design, so they may only do that to accounts they can write.
    def require_guest_writable_created_accounts!
      return unless Current.user.guest?

      created_ids = @import.accounts.pluck(:id)
      writable_ids = Current.family.accounts.writable_by(Current.user).where(id: created_ids).pluck(:id)
      return if (created_ids - writable_ids).empty?

      deny_import_change(t("accounts.not_authorized"), fallback: imports_path)
    end

    # Categories and tags are family-wide configuration, so a guest's import
    # must map every category and tag to an existing one (or leave it empty).
    def reject_guest_new_categories_or_tags!
      return unless Current.user.guest? && @import.creates_categories_or_tags?

      deny_import_change(t("imports.publish.guest_new_categories_or_tags"), fallback: import_confirm_path(@import))
    end

    def deny_import_change(alert, fallback:)
      respond_to do |format|
        format.html { redirect_back_or_to fallback, alert: alert }
        format.turbo_stream { head :forbidden }
        format.json { head :forbidden }
        format.any { head :forbidden }
      end
    end

    def require_statement_import_permission!
      return if @import.account_statement.blank? || @import.account_statement.manageable_by?(Current.user)

      redirect_target = @import.account || @import.account_statement
      redirect_back_or_to redirect_target, alert: t("accounts.not_authorized")
    end

    # Imports are family-scoped, so a member can reach an import configured by
    # someone else, or one whose target account was unshared since. Publishing,
    # reverting or deleting writes into its accounts, so require write access
    # to all.
    def require_writable_import_accounts!
      return if @import.accounts_writable_by?(Current.user)

      redirect_back_or_to import_path(@import), alert: t("accounts.not_authorized")
    end

    def create_pdf_import(file)
      return redirect_to new_import_path, alert: t("accounts.not_authorized") unless AccountStatement.statement_manager?(Current.user)
      return redirect_to new_import_path, alert: t("imports.create.pdf_too_large", max_size: Import::MAX_PDF_SIZE / 1.megabyte) if file.size > Import::MAX_PDF_SIZE

      pdf_import = PdfImport.create_from_upload!(family: Current.family, file: file, user: Current.user)
      pdf_import.process_with_ai_later
      redirect_to import_path(pdf_import), notice: t("imports.create.pdf_processing")
    rescue AccountStatement::DuplicateUploadError
      redirect_to new_import_path, alert: t("imports.create.duplicate_pdf_unavailable")
    rescue AccountStatement::InvalidUploadError
      redirect_to new_import_path, alert: t("imports.create.invalid_pdf")
    end

    def create_document_import(file)
      availability = Ai.availability(:embed, family: Current.family, user: Current.user)
      unless availability.available?
        redirect_to new_import_path, alert: availability.message_for(Current.user)
        return
      end

      adapter = VectorStore.adapter
      unless adapter
        redirect_to new_import_path, alert: t("imports.create.document_provider_not_configured")
        return
      end

      if file.size > Import::MAX_PDF_SIZE
        redirect_to new_import_path, alert: t("imports.create.document_too_large", max_size: Import::MAX_PDF_SIZE / 1.megabyte)
        return
      end

      filename = file.original_filename.to_s
      ext = File.extname(filename).downcase
      supported_extensions = adapter.supported_extensions.map(&:downcase)

      unless supported_extensions.include?(ext)
        redirect_to new_import_path, alert: t("imports.create.invalid_document_file_type")
        return
      end

      if ext == ".pdf"
        unless valid_pdf_file?(file)
          redirect_to new_import_path, alert: t("imports.create.invalid_pdf")
          return
        end

        create_pdf_import(file)
        return
      end

      family_document = Current.family.upload_document(
        file_content: file.read,
        filename: filename
      )

      if family_document
        redirect_to new_import_path, notice: t("imports.create.document_uploaded")
      else
        redirect_to new_import_path, alert: t("imports.create.document_upload_failed")
      end
    end

    def document_upload_supported_extensions
      adapter = document_store
      return [] unless adapter

      adapter.supported_extensions.map(&:downcase).uniq.sort
    end

    # Nil when `embed` isn't available, or when its store can't be built (pgvector without its extension).
    def document_store
      VectorStore.adapter if Ai.available?(:embed, family: Current.family, user: Current.user)
    end

    def document_upload_request?
      params.dig(:import, :type) == "DocumentImport"
    end

    def sure_import_request?
      params.dig(:import, :type) == "SureImport"
    end

    def create_sure_import(file)
      if file.size > SureImport.max_ndjson_size
        redirect_to new_import_path, alert: t("imports.create.file_too_large", max_size: SureImport.max_ndjson_size / 1.megabyte)
        return
      end

      ext = File.extname(file.original_filename.to_s).downcase
      unless ext.in?(%w[.ndjson .json])
        redirect_to new_import_path, alert: t("imports.create.invalid_ndjson_file_type")
        return
      end

      content = file.read
      file.rewind
      unless SureImport.valid_ndjson_first_line?(content)
        redirect_to new_import_path, alert: t("imports.create.invalid_ndjson_file_type")
        return
      end

      import = Current.family.imports.create!(type: "SureImport")
      import.ndjson_file.attach(
        io: StringIO.new(content),
        filename: file.original_filename,
        content_type: file.content_type
      )
      import.sync_ndjson_rows_count!

      redirect_to import_path(import), notice: t("imports.create.ndjson_uploaded")
    end

    def valid_pdf_file?(file)
      header = file.read(5)
      file.rewind
      header&.start_with?("%PDF-")
    end
end