Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
18.6 KB
Raw Blame
# frozen_string_literal: true

class Api::V1::TradesController < Api::V1::BaseController
  include Pagy::Backend

  UPDATE_NATURES = %w[inflow outflow].freeze

  before_action :ensure_read_scope, only: [ :index, :show ]
  before_action :ensure_write_scope, only: [ :create, :update, :destroy ]
  before_action :set_trade, only: [ :show, :update, :destroy ]
  before_action :ensure_write_permission, only: [ :update, :destroy ]

  def index
    family = current_resource_owner.family
    trades_query = family.trades.visible

    trades_query = apply_filters(accessible_trades)
    trades_query = trades_query.includes({ entry: :account }, :security, :category, :lot_source_entry).reverse_chronological

    @pagy, @trades = pagy(
      trades_query,
      page: safe_page_param,
      limit: safe_per_page_param
    )
    @per_page = safe_per_page_param

    render :index
  rescue ArgumentError => e
    render_validation_error(e.message, [ e.message ])
  rescue => e
    log_and_render_error("index", e)
  end

  def show
    render :show
  rescue => e
    log_and_render_error("show", e)
  end

  def create
    unless trade_params[:account_id].present?
      return render_validation_error("Account ID is required", [ "Account ID is required" ])
    end

    account = current_resource_owner.family.accounts.writable_by(current_resource_owner).visible.find(trade_params[:account_id])

    unless account.supports_trades?
      return render_validation_error(
        "Account does not support trades (investment or crypto exchange only)",
        [ "Account must be an investment or crypto exchange account" ]
      )
    end

    create_params = build_create_form_params(account)
    return if performed? # build_create_form_params may have rendered validation errors

    create_options = build_trade_create_options(create_params[:type])
    return if performed?

    model = ApplicationRecord.transaction do
      created_model = Trade::CreateForm.new(create_params).create
      created_trade = trade_from_created_model(created_model)
      created_trade.update!(create_options) if created_model.persisted? && created_trade && create_options.any?
      created_model
    end

    unless model.persisted?
      errors = model.is_a?(Entry) ? model.errors.full_messages : [ "Trade could not be created" ]
      return render_validation_error("Trade could not be created", errors)
    end

    if model.is_a?(Entry)
      model.lock_saved_attributes!
      model.mark_user_modified!
      model.sync_account_later

      if model.entryable.is_a?(Transaction)
        @transaction = model.entryable
        render template: "api/v1/transactions/show", status: :created
      else
        @trade = model.trade
        @entry = @trade.entry
        render :show, status: :created
      end
    elsif model.is_a?(Transfer)
      @transfer = model
      render template: "api/v1/transfers/show", status: :created
    else
      @trade = model
      @entry = @trade.entry
      render :show, status: :created
    end
  rescue ActiveRecord::RecordNotFound => e
    message = (e.model == "Account") ? "Account not found" : "Security not found"
    render json: { error: "not_found", message: message }, status: :not_found
  rescue => e
    log_and_render_error("create", e)
  end

  def update
    return unless valid_trade_update_semantics?

    updatable = build_entry_params_for_update
    return if performed? # build_entry_params_for_update may have rendered validation errors

    # The edit and its follow-up writes commit together, as in
    # TransactionsController#update: if one fails, a retry still finds the
    # change to make.
    Entry.transaction do
      if @entry.update(updatable.except(:nature))
        # Read before the follow-up writes below reset saved_changes. A request
        # that changes nothing must not mark the entry user-modified, which would
        # stop provider imports from updating it.
        if @entry.saved_changes.any? || @entry.entryable.saved_changes.any?
          @entry.lock_saved_attributes!
          @entry.mark_user_modified!
          @entry.sync_account_later
        end
        @trade = @entry.trade
        render :show
      else
        render_validation_error("Trade could not be updated", @entry.errors.full_messages)
        raise ActiveRecord::Rollback
      end
    end
  rescue => e
    log_and_render_error("update", e)
  end

  def destroy
    @entry = @trade.entry
    @entry.destroy!
    @entry.sync_account_later

    render json: { message: "Trade deleted successfully" }, status: :ok
  rescue => e
    log_and_render_error("destroy", e)
  end

  private

    # Trades on accounts the caller can at least read.
    def accessible_trades
      family = current_resource_owner.family
      family.trades.visible
        .where(entries: { account_id: family.accounts.accessible_by(current_resource_owner).select(:id) })
    end

    def set_trade
      # Load through accessible accounts only: a trade on an account the caller
      # cannot see is a 404. Write access is checked next (ensure_write_permission).
      @trade = accessible_trades.find(params[:id])
      @entry = @trade.entry
    rescue ActiveRecord::RecordNotFound
      render json: { error: "not_found", message: "Trade not found" }, status: :not_found
    end

    # A trade the caller can see but not change is a 403, not a 404.
    def ensure_write_permission
      require_api_account_permission!(@entry.account, resource: "trade")
    end

    def ensure_read_scope
      authorize_scope!(:read)
    end

    def ensure_write_scope
      authorize_scope!(:write)
    end

    def apply_filters(query)
      need_entry_join = params[:account_id].present? || params[:account_ids].present? ||
                        params[:start_date].present? || params[:end_date].present?
      query = query.joins(:entry) if need_entry_join

      if params[:account_id].present?
        query = query.where(entries: { account_id: params[:account_id] })
      end
      if params[:account_ids].present?
        query = query.where(entries: { account_id: Array(params[:account_ids]) })
      end
      if params[:start_date].present?
        query = query.where("entries.date >= ?", parse_date!(params[:start_date], "start_date"))
      end
      if params[:end_date].present?
        query = query.where("entries.date <= ?", parse_date!(params[:end_date], "end_date"))
      end
      query
    end

    def trade_params
      params.require(:trade).permit(
        :account_id, :date, :qty, :price, :currency,
        :security_id, :ticker, :manual_ticker, :investment_activity_label,
        :fee, :type, :amount, :transfer_account_id
      )
    end

    def trade_update_params
      params.require(:trade).permit(
        :name, :date, :amount, :currency, :notes, :nature, :type,
        :qty, :price, :investment_activity_label
      )
    end

    def build_entry_params_for_update
      flat = trade_update_params.to_h
      entry_params = {
        name: flat[:name],
        date: flat[:date],
        amount: flat[:amount],
        currency: flat[:currency],
        notes: flat[:notes],
        entryable_type: "Trade",
        entryable_attributes: {
          id: @trade.id,
          investment_activity_label: flat[:investment_activity_label]
        }.compact_blank
      }.compact

      type_or_nature = flat[:type].presence || flat[:nature].presence
      return entry_params unless flat.key?(:qty) || flat.key?(:price) || type_or_nature

      # Any of qty, price, type or nature rewrites the trade as create builds
      # it, taking what the request leaves out from the stored trade. A qty or
      # price sent blank is invalid, not left out.
      qty, price = parse_qty_and_price!(flat.fetch(:qty) { @trade.qty.abs }, flat.fetch(:price) { @trade.price })
      return if performed?

      is_sell = type_or_nature ? trade_sell_from_type_or_nature?(type_or_nature) : @trade.qty.negative?
      signed_qty = is_sell ? -qty : qty
      entry_params[:entryable_attributes].merge!(qty: signed_qty, price: price)
      entry_params[:amount] = signed_qty * price + @trade.fee
      ticker = @trade.security&.ticker
      entry_params[:name] = Trade.build_name(is_sell ? "sell" : "buy", qty, ticker) if ticker.present?
      type_label = Trade::CreateForm::SECURITY_TRADE_LABELS[flat[:type].to_s.downcase]
      entry_params[:entryable_attributes][:investment_activity_label] = flat[:investment_activity_label].presence || type_label || @trade.label_for_side(sell: is_sell)

      entry_params
    end

    # True for sell: "sell", "sweep_out", or "inflow". False for buy: "buy", "outflow", or blank. Keeps create (buy/sell) and update (type or nature) consistent.
    def trade_sell_from_type_or_nature?(value)
      return false if value.blank?

      normalized = value.to_s.downcase.strip
      %w[sell sweep_out inflow].include?(normalized)
    end

    def build_create_form_params(account)
      type = params.dig(:trade, :type).to_s.downcase
      unless Trade::CreateForm::SUPPORTED_TYPES.include?(type)
        supported_types = Trade::CreateForm::SUPPORTED_TYPES.join(", ")
        render_validation_error(
          I18n.t("trades.api_errors.invalid_type"),
          [ I18n.t("trades.api_errors.supported_types", types: supported_types) ]
        )
        return nil
      end

      case type
      when "deposit", "withdrawal"
        unless trade_params[:amount].present?
          render_validation_error("Amount is required", [ "amount must be present for deposit/withdrawal" ])
          return nil
        end

        unless trade_params[:date].present?
          render_validation_error("Date is required", [ "date must be present" ])
          return nil
        end

        {
          account: account,
          date: trade_params[:date],
          amount: parse_positive_amount!(trade_params[:amount], context: "deposit/withdrawal"),
          currency: trade_params[:currency].presence || account.currency,
          type: type,
          transfer_account_id: writable_transfer_account_id
        }.compact

      when "interest", "fee"
        unless trade_params[:date].present?
          render_validation_error("Date is required", [ "date must be present" ])
          return nil
        end

        unless trade_params[:amount].present?
          render_validation_error("Amount is required", [ "amount must be present" ])
          return nil
        end

        ticker_value = nil
        manual_ticker_value = nil
        if trade_params[:security_id].present?
          security = Security.find(trade_params[:security_id])
          ticker_value = ticker_from_security(security)
        elsif trade_params[:ticker].present?
          ticker_value = trade_params[:ticker]
        elsif trade_params[:manual_ticker].present?
          manual_ticker_value = trade_params[:manual_ticker]
        end

        {
          account: account,
          date: trade_params[:date],
          amount: parse_positive_amount!(trade_params[:amount], context: type),
          currency: trade_params[:currency].presence || account.currency,
          type: type,
          ticker: ticker_value,
          manual_ticker: manual_ticker_value
        }.compact

      when "dividend"
        build_dividend_params(account)

      else
        build_investment_trade_params(account)
      end
    end

    def build_investment_trade_params(account)
      ticker_value = nil
      manual_ticker_value = nil

      unless trade_params[:date].present?
        render_validation_error("Date is required", [ "date must be present" ])
        return nil
      end

      if trade_params[:security_id].present?
        security = Security.find(trade_params[:security_id])
        ticker_value = ticker_from_security(security)
      elsif trade_params[:ticker].present?
        ticker_value = trade_params[:ticker]
      elsif trade_params[:manual_ticker].present?
        manual_ticker_value = trade_params[:manual_ticker]
      else
        render_validation_error("Security identifier required", [ "Provide security_id, ticker, or manual_ticker" ])
        return nil
      end

      qty, price = parse_qty_and_price!(trade_params[:qty], trade_params[:price])
      return if performed?

      fee = parse_fee!(trade_params[:fee])
      return if performed?

      {
        account: account,
        date: trade_params[:date],
        qty: qty,
        price: price,
        fee: fee,
        currency: trade_params[:currency].presence || account.currency,
        type: trade_params[:type].to_s.downcase,
        ticker: ticker_value,
        manual_ticker: manual_ticker_value
      }.compact
    end

    def build_dividend_params(account)
      ticker_value = nil
      manual_ticker_value = nil

      unless trade_params[:date].present?
        render_validation_error("Date is required", [ "date must be present" ])
        return nil
      end

      if trade_params[:security_id].present?
        security = Security.find(trade_params[:security_id])
        ticker_value = ticker_from_security(security)
      elsif trade_params[:ticker].present?
        ticker_value = trade_params[:ticker]
      elsif trade_params[:manual_ticker].present?
        manual_ticker_value = trade_params[:manual_ticker]
      else
        render_validation_error("Security identifier required", [ "Provide security_id, ticker, or manual_ticker" ])
        return nil
      end

      unless trade_params[:amount].present?
        render_validation_error("Amount is required", [ "amount must be present for dividend" ])
        return nil
      end

      {
        account: account,
        date: trade_params[:date],
        amount: parse_positive_amount!(trade_params[:amount], context: "dividend"),
        currency: trade_params[:currency].presence || account.currency,
        type: "dividend",
        ticker: ticker_value,
        manual_ticker: manual_ticker_value
      }.compact
    end

    def build_trade_create_options(type)
      return {} unless Trade::CreateForm::ACTIVITY_LABELS.key?(type)

      attrs = {}
      if trade_params[:investment_activity_label].present?
        label = trade_params[:investment_activity_label]
        expected_label = Trade::CreateForm::ACTIVITY_LABELS.fetch(type)
        unless label == expected_label
          render_validation_error(
            I18n.t("trades.api_errors.invalid_activity_label"),
            [ I18n.t("trades.api_errors.activity_label_must_match_type", label: expected_label, type: type) ]
          )
          return {}
        end
        attrs[:investment_activity_label] = label
      end
      attrs
    end

    def trade_from_created_model(model)
      return model.trade if model.is_a?(Entry) && model.entryable_type == "Trade"
      return model if model.is_a?(Trade)

      nil
    end

    def valid_trade_update_semantics?
      nature = trade_update_params[:nature]
      if nature.present? && UPDATE_NATURES.exclude?(nature.to_s.downcase)
        render_validation_error("Invalid nature", [ "nature must be one of: #{UPDATE_NATURES.join(", ")}" ])
        return false
      end

      type = trade_update_params[:type].to_s.downcase
      label = trade_update_params[:investment_activity_label]
      return true if type.blank?

      expected_label = Trade::CreateForm::SECURITY_TRADE_LABELS[type]
      unless expected_label
        render_validation_error(
          I18n.t("trades.api_errors.invalid_type"),
          [ I18n.t("trades.api_errors.supported_types", types: Trade::CreateForm::SECURITY_TRADE_LABELS.keys.join(", ")) ]
        )
        return false
      end

      if label.present? && label != expected_label
        render_validation_error(
          I18n.t("trades.api_errors.invalid_activity_label"),
          [ I18n.t("trades.api_errors.activity_label_must_match_type", label: expected_label, type: type) ]
        )
        return false
      end

      true
    end

    def ticker_from_security(security)
      return security.ticker if security.exchange_operating_mic.blank?

      "#{security.ticker}|#{security.exchange_operating_mic}"
    end

    # A deposit or withdrawal also books an entry on the other account, so it
    # has to be one the key's user may write to. Raises RecordNotFound, which
    # #create answers with "Account not found".
    def writable_transfer_account_id
      return if trade_params[:transfer_account_id].blank?

      current_resource_owner.family.accounts.writable_by(current_resource_owner)
        .find(trade_params[:transfer_account_id]).id
    end

    def render_validation_error(message, errors)
      render json: {
        error: "validation_failed",
        message: message,
        errors: errors
      }, status: :unprocessable_entity
    end

    def parse_date!(value, param_name)
      Date.parse(value)
    rescue Date::Error, ArgumentError, TypeError
      raise ArgumentError, "Invalid #{param_name} format"
    end

    def log_and_render_error(action, exception)
      Rails.logger.error "TradesController##{action} error: #{exception.message}"
      Rails.logger.error exception.backtrace.join("\n")
      render json: {
        error: "internal_server_error",
        message: "An unexpected error occurred"
      }, status: :internal_server_error
    end

    def parse_positive_amount!(raw, context:)
      return render_validation_error("Amount is required", [ "amount must be present for #{context}" ]) if raw.to_s.strip.blank?

      value = parse_decimal(raw)
      return render_validation_error("Amount must be a valid number", [ "amount must be a valid positive number" ]) if value.nil? || value <= 0

      value
    end

    # Positive quantity and price, or nothing after rendering a 422.
    def parse_qty_and_price!(qty_raw, price_raw)
      if qty_raw.to_s.strip.blank? || price_raw.to_s.strip.blank?
        return render_validation_error("Quantity and price are required", [ "qty and price must be present and positive" ])
      end

      values = [ qty_raw, price_raw ].map { |raw| parse_decimal(raw) }
      if values.any?(&:nil?)
        return render_validation_error("Quantity and price must be valid numbers", [ "qty and price must be valid positive numbers" ])
      end
      return render_validation_error("Quantity and price are required", [ "qty and price must be present and positive" ]) unless values.all?(&:positive?)

      values
    end

    # A non-negative fee, zero when absent, or nothing after rendering a 422.
    def parse_fee!(raw)
      return 0 if raw.to_s.strip.blank?

      fee = parse_decimal(raw)
      return render_validation_error("Fee must be a valid number", [ "fee must be a valid non-negative number" ]) if fee.nil? || fee.negative?

      fee
    end

    def safe_page_param
      page = params[:page].to_i
      page > 0 ? page : 1
   end

    def safe_per_page_param
      per_page = params[:per_page].to_i
      case per_page
      when 1..100
        per_page
      else
        25
      end
    end
end