Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Improve investment activity labels UX and add convert-to-trade feature (#649)

LPW0c2026680cde
diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rb
index 1524b25d02..b71318b62b 100644
--- a/app/controllers/accounts_controller.rb
+++ b/app/controllers/accounts_controller.rb
@@ -36,7 +36,7 @@ class AccountsController < ApplicationController
@chart_view = params[:chart_view] || "balance"
@tab = params[:tab]
@q = params.fetch(:q, {}).permit(:search, status: [])
- entries = @account.entries.search(@q).reverse_chronological
+ entries = @account.entries.where(excluded: false).search(@q).reverse_chronological
@pagy, @entries = pagy(entries, limit: params[:per_page] || "10")
diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rb
index 91593f801f..9a076701d2 100644
--- a/app/controllers/reports_controller.rb
+++ b/app/controllers/reports_controller.rb
@@ -123,6 +123,9 @@ class ReportsController < ApplicationController
# Investment metrics
@investment_metrics = build_investment_metrics
+ # Investment flows (contributions/withdrawals)
+ @investment_flows = InvestmentFlowStatement.new(Current.family).period_totals(period: @period)
+
# Flags for view rendering
@has_accounts = Current.family.accounts.any?
end
@@ -161,6 +164,14 @@ class ReportsController < ApplicationController
visible: @investment_metrics[:has_investments],
collapsible: true
},
+ {
+ key: "investment_flows",
+ title: "reports.investment_flows.title",
+ partial: "reports/investment_flows",
+ locals: { investment_flows: @investment_flows },
+ visible: @investment_metrics[:has_investments] && (@investment_flows.contributions.amount > 0 || @investment_flows.withdrawals.amount > 0),
+ collapsible: true
+ },
{
key: "transactions_breakdown",
title: "reports.transactions_breakdown.title",
@@ -345,14 +356,6 @@ class ReportsController < ApplicationController
# Apply filters
transactions = apply_transaction_filters(transactions)
- # Get trades in the period (matching income_statement logic)
- trades = Trade
- .joins(:entry)
- .joins(entry: :account)
- .where(accounts: { family_id: Current.family.id, status: [ "draft", "active" ] })
- .where(entries: { entryable_type: "Trade", excluded: false, date: @period.date_range })
- .includes(entry: :account, category: [])
-
# Get sort parameters
sort_by = params[:sort_by] || "amount"
sort_direction = params[:sort_direction] || "desc"
@@ -378,24 +381,6 @@ class ReportsController < ApplicationController
grouped_data[key][:total] += converted_amount
end
- # Process trades
- trades.each do |trade|
- entry = trade.entry
- is_expense = entry.amount > 0
- type = is_expense ? "expense" : "income"
- # Use "Other Investments" for trades without category
- category_name = trade.category&.name || Category.other_investments_name
- category_color = trade.category&.color || Category::OTHER_INVESTMENTS_COLOR
-
- # Convert to family currency
- converted_amount = Money.new(entry.amount.abs, entry.currency).exchange_to(family_currency, fallback_rate: 1).amount
-
- key = [ category_name, type, category_color ]
- grouped_data[key] ||= { total: 0, count: 0 }
- grouped_data[key][:count] += 1
- grouped_data[key][:total] += converted_amount
- end
-
# Convert to array
result = grouped_data.map do |key, data|
{
@@ -562,14 +547,6 @@ class ReportsController < ApplicationController
transactions = apply_transaction_filters(transactions)
- # Get trades in the period (matching income_statement logic)
- trades = Trade
- .joins(:entry)
- .joins(entry: :account)
- .where(accounts: { family_id: Current.family.id, status: [ "draft", "active" ] })
- .where(entries: { entryable_type: "Trade", excluded: false, date: @period.date_range })
- .includes(entry: :account, category: [])
-
# Group by category, type, and month
breakdown = {}
family_currency = Current.family.currency
@@ -592,25 +569,6 @@ class ReportsController < ApplicationController
breakdown[key][:total] += converted_amount
end
- # Process trades
- trades.each do |trade|
- entry = trade.entry
- is_expense = entry.amount > 0
- type = is_expense ? "expense" : "income"
- # Use "Other Investments" for trades without category
- category_name = trade.category&.name || Category.other_investments_name
- month_key = entry.date.beginning_of_month
-
- # Convert to family currency
- converted_amount = Money.new(entry.amount.abs, entry.currency).exchange_to(family_currency, fallback_rate: 1).amount
-
- key = [ category_name, type ]
- breakdown[key] ||= { category: category_name, type: type, months: {}, total: 0 }
- breakdown[key][:months][month_key] ||= 0
- breakdown[key][:months][month_key] += converted_amount
- breakdown[key][:total] += converted_amount
- end
-
# Convert to array and sort by type and total (descending)
result = breakdown.map do |key, data|
{
diff --git a/app/controllers/trades_controller.rb b/app/controllers/trades_controller.rb
index 46cd1f39a0..f131c47eff 100644
--- a/app/controllers/trades_controller.rb
+++ b/app/controllers/trades_controller.rb
@@ -55,7 +55,7 @@ class TradesController < ApplicationController
def entry_params
params.require(:entry).permit(
:name, :date, :amount, :currency, :excluded, :notes, :nature,
- entryable_attributes: [ :id, :qty, :price, :category_id ]
+ entryable_attributes: [ :id, :qty, :price, :investment_activity_label ]
)
end
@@ -73,11 +73,27 @@ class TradesController < ApplicationController
qty = update_params[:entryable_attributes][:qty]
price = update_params[:entryable_attributes][:price]
+ nature = update_params[:nature]
if qty.present? && price.present?
- qty = update_params[:nature] == "inflow" ? -qty.to_d : qty.to_d
+ is_sell = nature == "inflow"
+ qty = is_sell ? -qty.to_d.abs : qty.to_d.abs
update_params[:entryable_attributes][:qty] = qty
update_params[:amount] = qty * price.to_d
+
+ # Sync investment_activity_label with Buy/Sell type if not explicitly set to something else
+ # Check both the submitted param and the existing record's label
+ current_label = update_params[:entryable_attributes][:investment_activity_label].presence ||
+ @entry.trade&.investment_activity_label
+ if current_label.blank? || current_label == "Buy" || current_label == "Sell"
+ update_params[:entryable_attributes][:investment_activity_label] = is_sell ? "Sell" : "Buy"
+ end
+
+ # Update entry name to reflect Buy/Sell change
+ ticker = @entry.trade&.security&.ticker
+ if ticker.present?
+ update_params[:name] = Trade.build_name(is_sell ? "sell" : "buy", qty.abs, ticker)
+ end
end
update_params.except(:nature)
diff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rb
index 58220bd997..8c8ef6a21e 100644
--- a/app/controllers/transactions_controller.rb
+++ b/app/controllers/transactions_controller.rb
@@ -149,6 +149,87 @@ class TransactionsController < ApplicationController
redirect_back_or_to transactions_path
end
+ def convert_to_trade
+ @transaction = Current.family.transactions.includes(entry: :account).find(params[:id])
+ @entry = @transaction.entry
+
+ unless @entry.account.investment?
+ flash[:alert] = t("transactions.convert_to_trade.errors.not_investment_account")
+ redirect_back_or_to transactions_path
+ return
+ end
+
+ render :convert_to_trade
+ end
+
+ def create_trade_from_transaction
+ @transaction = Current.family.transactions.includes(entry: :account).find(params[:id])
+ @entry = @transaction.entry
+
+ # Pre-transaction validations
+ unless @entry.account.investment?
+ flash[:alert] = t("transactions.convert_to_trade.errors.not_investment_account")
+ redirect_back_or_to transactions_path
+ return
+ end
+
+ if @entry.excluded?
+ flash[:alert] = t("transactions.convert_to_trade.errors.already_converted")
+ redirect_back_or_to transactions_path
+ return
+ end
+
+ # Resolve security before transaction
+ security = resolve_security_for_conversion
+ return if performed? # Early exit if redirect already happened
+
+ # Validate and calculate qty/price before transaction
+ qty, price = calculate_qty_and_price
+ return if performed? # Early exit if redirect already happened
+
+ activity_label = params[:investment_activity_label].presence
+ # Infer sell from amount sign: negative amount = money coming in = sell
+ is_sell = activity_label == "Sell" || (activity_label.blank? && @entry.amount < 0)
+
+ ActiveRecord::Base.transaction do
+ # For trades: positive qty = buy (money out), negative qty = sell (money in)
+ signed_qty = is_sell ? -qty : qty
+ trade_amount = qty * price
+ # Sells bring money in (negative amount), Buys take money out (positive amount)
+ signed_amount = is_sell ? -trade_amount : trade_amount
+
+ # Default activity label if not provided
+ activity_label ||= is_sell ? "Sell" : "Buy"
+
+ # Create trade entry
+ @entry.account.entries.create!(
+ name: params[:trade_name] || Trade.build_name(is_sell ? "sell" : "buy", qty, security.ticker),
+ date: @entry.date,
+ amount: signed_amount,
+ currency: @entry.currency,
+ entryable: Trade.new(
+ security: security,
+ qty: signed_qty,
+ price: price,
+ currency: @entry.currency,
+ investment_activity_label: activity_label
+ )
+ )
+
+ # Mark original transaction as excluded (soft delete)
+ @entry.update!(excluded: true)
+ end
+
+ flash[:notice] = t("transactions.convert_to_trade.success")
+ redirect_to account_path(@entry.account), status: :see_other
+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved => e
+ flash[:alert] = t("transactions.convert_to_trade.errors.conversion_failed", error: e.message)
+ redirect_back_or_to transactions_path, status: :see_other
+ rescue StandardError => e
+ flash[:alert] = t("transactions.convert_to_trade.errors.unexpected_error", error: e.message)
+ redirect_back_or_to transactions_path, status: :see_other
+ end
+
def mark_as_recurring
transaction = Current.family.transactions.includes(entry: :account).find(params[:id])
@@ -280,4 +361,64 @@ class TransactionsController < ApplicationController
def preferences_params
params.require(:preferences).permit(collapsed_sections: {})
end
+
+ # Helper methods for convert_to_trade
+
+ def resolve_security_for_conversion
+ if params[:security_id] == "__custom__"
+ ticker = params[:custom_ticker].presence
+ unless ticker.present?
+ flash[:alert] = t("transactions.convert_to_trade.errors.enter_ticker")
+ redirect_back_or_to transactions_path
+ return nil
+ end
+
+ Security::Resolver.new(
+ ticker.strip,
+ exchange_operating_mic: params[:exchange_operating_mic].presence
+ ).resolve
+ elsif params[:security_id].present?
+ found = Security.find_by(id: params[:security_id])
+ unless found
+ flash[:alert] = t("transactions.convert_to_trade.errors.security_not_found")
+ redirect_back_or_to transactions_path
+ return nil
+ end
+ found
+ elsif params[:ticker].present?
+ Security::Resolver.new(
+ params[:ticker].strip,
+ exchange_operating_mic: params[:exchange_operating_mic].presence
+ ).resolve
+ end.tap do |security|
+ if security.nil? && !performed?
+ flash[:alert] = t("transactions.convert_to_trade.errors.select_security")
+ redirect_back_or_to transactions_path
+ end
+ end
+ end
+
+ def calculate_qty_and_price
+ amount = @entry.amount.abs
+ qty = params[:qty].present? ? params[:qty].to_d.abs : nil
+ price = params[:price].present? ? params[:price].to_d : nil
+
+ if qty.nil? && price.nil?
+ flash[:alert] = t("transactions.convert_to_trade.errors.enter_qty_or_price")
+ redirect_back_or_to transactions_path, status: :see_other
+ return [ nil, nil ]
+ elsif qty.nil? && price.present? && price > 0
+ qty = (amount / price).round(6)
+ elsif price.nil? && qty.present? && qty > 0
+ price = (amount / qty).round(4)
+ end
+
+ if qty.nil? || qty <= 0 || price.nil? || price <= 0
+ flash[:alert] = t("transactions.convert_to_trade.errors.invalid_qty_or_price")
+ redirect_back_or_to transactions_path, status: :see_other
+ return [ nil, nil ]
+ end
+
+ [ qty, price ]
+ end
end
diff --git a/app/javascript/controllers/activity_label_quick_edit_controller.js b/app/javascript/controllers/activity_label_quick_edit_controller.js
new file mode 100644
index 0000000000..ee10fdf2cf
--- /dev/null
+++ b/app/javascript/controllers/activity_label_quick_edit_controller.js
@@ -0,0 +1,108 @@
+import { Controller } from "@hotwired/stimulus"
+
+export default class extends Controller {
+ static targets = ["dropdown", "badge"]
+ static values = {
+ url: String,
+ entryableId: String,
+ currentLabel: String,
+ entryableType: String,
+ convertUrl: String
+ }
+
+ connect() {
+ // Close dropdown when clicking outside
+ this.boundCloseOnClickOutside = this.closeOnClickOutside.bind(this)
+ document.addEventListener("click", this.boundCloseOnClickOutside)
+ }
+
+ disconnect() {
+ document.removeEventListener("click", this.boundCloseOnClickOutside)
+ }
+
+ toggle(event) {
+ event.preventDefault()
+ event.stopPropagation()
+
+ if (this.hasDropdownTarget) {
+ this.dropdownTarget.classList.toggle("hidden")
+ }
+ }
+
+ closeOnClickOutside(event) {
+ if (!this.element.contains(event.target)) {
+ this.close()
+ }
+ }
+
+ close() {
+ if (this.hasDropdownTarget) {
+ this.dropdownTarget.classList.add("hidden")
+ }
+ }
+
+ async select(event) {
+ event.preventDefault()
+ event.stopPropagation()
+
+ const label = event.currentTarget.dataset.label
+
+ // Don't update if it's the same label
+ if (label === this.currentLabelValue) {
+ this.close()
+ return
+ }
+
+ // For Transactions: Buy/Sell should prompt to convert to trade
+ if (this.entryableTypeValue === "Transaction" && (label === "Buy" || label === "Sell") && this.hasConvertUrlValue) {
+ this.close()
+ // Navigate to convert-to-trade modal in a Turbo frame, passing the selected label
+ const url = new URL(this.convertUrlValue, window.location.origin)
+ url.searchParams.set("activity_label", label)
+ Turbo.visit(url.toString(), { frame: "modal" })
+ return
+ }
+
+ // For other labels (Dividend, Interest, Fee, etc.) or for Trades, just save the label
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content
+ if (!csrfToken) {
+ console.error("CSRF token not found")
+ return
+ }
+
+ try {
+ const response = await fetch(this.urlValue, {
+ method: "PATCH",
+ headers: {
+ "Content-Type": "application/json",
+ "X-CSRF-Token": csrfToken,
+ "Accept": "text/vnd.turbo-stream.html"
+ },
+ body: JSON.stringify({
+ entry: {
+ entryable_attributes: {
+ id: this.entryableIdValue,
+ investment_activity_label: label
+ }
+ }
+ })
+ })
+
+ if (response.ok) {
+ const contentType = response.headers.get("content-type")
+ if (contentType?.includes("text/vnd.turbo-stream.html")) {
+ // Let Turbo handle the stream response
+ const html = await response.text()
+ Turbo.renderStreamMessage(html)
+ }
+ // Update local state and badge
+ this.currentLabelValue = label
+ this.close()
+ } else {
+ console.error("Failed to update activity label:", response.status)
+ }
+ } catch (error) {
+ console.error("Error updating activity label:", error)
+ }
+ }
+}
diff --git a/app/javascript/controllers/convert_to_trade_controller.js b/app/javascript/controllers/convert_to_trade_controller.js
new file mode 100644
index 0000000000..c0e71663b9
--- /dev/null
+++ b/app/javascript/controllers/convert_to_trade_controller.js
@@ -0,0 +1,21 @@
+import { Controller } from "@hotwired/stimulus"
+
+export default class extends Controller {
+ static targets = ["customWrapper", "customField", "tickerSelect"]
+
+ toggleCustomTicker(event) {
+ const value = event.target.value
+
+ if (value === "__custom__") {
+ // Show custom ticker field
+ this.customWrapperTarget.classList.remove("hidden")
+ this.customFieldTarget.required = true
+ this.customFieldTarget.focus()
+ } else {
+ // Hide custom ticker field
+ this.customWrapperTarget.classList.add("hidden")
+ this.customFieldTarget.required = false
+ this.customFieldTarget.value = ""
+ }
+ }
+}
diff --git a/app/models/account/provider_import_adapter.rb b/app/models/account/provider_import_adapter.rb
index bae56389eb..932edf57f2 100644
--- a/app/models/account/provider_import_adapter.rb
+++ b/app/models/account/provider_import_adapter.rb
@@ -142,10 +142,28 @@ class Account::ProviderImportAdapter
entry.transaction.save!
end
- # Set investment activity label if provided and not already set
- if investment_activity_label.present? && entry.entryable.is_a?(Transaction)
- if entry.transaction.investment_activity_label.blank?
- entry.transaction.assign_attributes(investment_activity_label: investment_activity_label)
+ # Auto-detect investment activity labels for investment accounts
+ detected_label = investment_activity_label
+ if account.investment? && detected_label.nil? && entry.entryable.is_a?(Transaction)
+ detected_label = detect_activity_label(name, amount)
+ end
+
+ # Auto-set kind for internal movements and contributions
+ auto_kind = nil
+ if Transaction::INTERNAL_MOVEMENT_LABELS.include?(detected_label)
+ auto_kind = "funds_movement"
+ elsif detected_label == "Contribution"
+ auto_kind = "investment_contribution"
+ end
+
+ # Set investment activity label and kind if detected
+ if entry.entryable.is_a?(Transaction)
+ if detected_label.present? && entry.transaction.investment_activity_label.blank?
+ entry.transaction.assign_attributes(investment_activity_label: detected_label)
+ end
+
+ if auto_kind.present?
+ entry.transaction.assign_attributes(kind: auto_kind)
end
end
@@ -484,8 +502,9 @@ class Account::ProviderImportAdapter
# @param name [String, nil] Optional custom name for the trade
# @param external_id [String, nil] Provider's unique ID (optional, for deduplication)
# @param source [String] Provider name
+ # @param activity_label [String, nil] Investment activity label (e.g., "Buy", "Sell", "Reinvestment")
# @return [Entry] The created entry with trade
- def import_trade(security:, quantity:, price:, amount:, currency:, date:, name: nil, external_id: nil, source:)
+ def import_trade(security:, quantity:, price:, amount:, currency:, date:, name: nil, external_id: nil, source:, activity_label: nil)
raise ArgumentError, "security is required" if security.nil?
raise ArgumentError, "source is required" if source.blank?
@@ -522,7 +541,8 @@ class Account::ProviderImportAdapter
security: security,
qty: quantity,
price: price,
- currency: currency
+ currency: currency,
+ investment_activity_label: activity_label || (quantity > 0 ? "Buy" : "Sell")
)
entry.assign_attributes(
@@ -790,6 +810,36 @@ class Account::ProviderImportAdapter
)
end
+ # Auto-detects investment activity label from transaction name and amount
+ # Only detects extremely obvious cases to maintain high accuracy
+ # Users can always manually adjust the label afterward
+ #
+ # @param name [String] Transaction name/description
+ # @param amount [BigDecimal, Numeric] Transaction amount (positive or negative)
+ # @return [String, nil] Detected activity label or nil if no pattern matches
+ def detect_activity_label(name, amount)
+ return nil if name.blank?
+
+ name_lower = name.downcase.strip
+
+ # Only detect the most obvious patterns - be conservative to avoid false positives
+ # Users can manually adjust labels for edge cases
+ case name_lower
+ when /^dividend\b/, /\bdividend payment\b/, /\bqualified dividend\b/, /\bordinary dividend\b/
+ "Dividend"
+ when /^interest\b/, /\binterest income\b/, /\binterest payment\b/
+ "Interest"
+ when /^fee\b/, /\bmanagement fee\b/, /\badvisory fee\b/, /\btransaction fee\b/
+ "Fee"
+ when /\bemployer match\b/, /\bemployer contribution\b/
+ "Contribution"
+ when /\b401[k\(]/, /\bira contribution\b/, /\broth contribution\b/
+ "Contribution"
+ else
+ nil # Let user categorize manually - default to nil for safety
+ end
+ end
+
# Determines why an entry should be skipped during sync.
# Returns nil if entry should NOT be skipped.
#
diff --git a/app/models/category.rb b/app/models/category.rb
index f668ac1fcf..b6586492e9 100644
--- a/app/models/category.rb
+++ b/app/models/category.rb
@@ -1,6 +1,5 @@
class Category < ApplicationRecord
has_many :transactions, dependent: :nullify, class_name: "Transaction"
- has_many :trades, dependent: :nullify
has_many :import_mappings, as: :mappable, dependent: :destroy, class_name: "Import::Mapping"
belongs_to :family
diff --git a/app/models/income_statement/totals.rb b/app/models/income_statement/totals.rb
index 758ae6be33..ffcb468b1e 100644
--- a/app/models/income_statement/totals.rb
+++ b/app/models/income_statement/totals.rb
@@ -96,6 +96,10 @@ class IncomeStatement::Totals
er.to_currency = :target_currency
)
WHERE at.kind NOT IN ('funds_movement', 'one_time', 'cc_payment', 'investment_contribution')
+ AND (
+ at.investment_activity_label IS NULL
+ OR at.investment_activity_label NOT IN ('Transfer', 'Sweep In', 'Sweep Out', 'Exchange')
+ )
AND ae.excluded = false
AND a.family_id = :family_id
AND a.status IN ('draft', 'active')
@@ -104,30 +108,14 @@ class IncomeStatement::Totals
end
def trades_subquery_sql
- # Get trades for the same family and date range as transactions
- # Trades without categories appear as "Uncategorized Investments" (separate from regular uncategorized)
+ # Trades are completely excluded from income/expense budgets
+ # Rationale: Trades represent portfolio rebalancing, not cash flow
+ # Example: Selling $10k AAPL to buy MSFT = no net worth change, not an expense
+ # Contributions/withdrawals are tracked separately as Transactions with activity labels
<<~SQL
- SELECT
- c.id as category_id,
- c.parent_id as parent_category_id,
- CASE WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END as classification,
- ABS(SUM(ae.amount * COALESCE(er.rate, 1))) as total,
- COUNT(ae.id) as entry_count,
- CASE WHEN t.category_id IS NULL THEN true ELSE false END as is_uncategorized_investment
- FROM trades t
- JOIN entries ae ON ae.entryable_id = t.id AND ae.entryable_type = 'Trade'
- JOIN accounts a ON a.id = ae.account_id
- LEFT JOIN categories c ON c.id = t.category_id
- LEFT JOIN exchange_rates er ON (
- er.date = ae.date AND
- er.from_currency = ae.currency AND
- er.to_currency = :target_currency
- )
- WHERE a.family_id = :family_id
- AND a.status IN ('draft', 'active')
- AND ae.excluded = false
- AND ae.date BETWEEN :start_date AND :end_date
- GROUP BY c.id, c.parent_id, CASE WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END, CASE WHEN t.category_id IS NULL THEN true ELSE false END
+ SELECT NULL as category_id, NULL as parent_category_id, NULL as classification,
+ NULL as total, NULL as entry_count, NULL as is_uncategorized_investment
+ WHERE false
SQL
end
diff --git a/app/models/investment_flow_statement.rb b/app/models/investment_flow_statement.rb
new file mode 100644
index 0000000000..d17a712666
--- /dev/null
+++ b/app/models/investment_flow_statement.rb
@@ -0,0 +1,30 @@
+class InvestmentFlowStatement
+ include Monetizable
+
+ attr_reader :family
+
+ def initialize(family)
+ @family = family
+ end
+
+ # Get contribution/withdrawal totals for a period
+ def period_totals(period: Period.current_month)
+ transactions = family.transactions
+ .visible
+ .excluding_pending
+ .where(entries: { date: period.date_range })
+ .where(kind: %w[standard investment_contribution])
+ .where(investment_activity_label: %w[Contribution Withdrawal])
+
+ contributions = transactions.where(investment_activity_label: "Contribution").sum("entries.amount").abs
+ withdrawals = transactions.where(investment_activity_label: "Withdrawal").sum("entries.amount").abs
+
+ PeriodTotals.new(
+ contributions: Money.new(contributions, family.currency),
+ withdrawals: Money.new(withdrawals, family.currency),
+ net_flow: Money.new(contributions - withdrawals, family.currency)
+ )
+ end
+
+ PeriodTotals = Data.define(:contributions, :withdrawals, :net_flow)
+end
diff --git a/app/models/plaid_account/investments/transactions_processor.rb b/app/models/plaid_account/investments/transactions_processor.rb
index d90657ce67..5cabccb2ca 100644
--- a/app/models/plaid_account/investments/transactions_processor.rb
+++ b/app/models/plaid_account/investments/transactions_processor.rb
@@ -72,7 +72,8 @@ class PlaidAccount::Investments::TransactionsProcessor
currency: transaction["iso_currency_code"],
date: transaction["date"],
name: transaction["name"],
- source: "plaid"
+ source: "plaid",
+ activity_label: label_from_plaid_type(transaction)
)
end
diff --git a/app/models/trade.rb b/app/models/trade.rb
index b9233f9db0..0692fae96e 100644
--- a/app/models/trade.rb
+++ b/app/models/trade.rb
@@ -4,10 +4,13 @@ class Trade < ApplicationRecord
monetize :price
belongs_to :security
- belongs_to :category, optional: true
+
+ # Use the same activity labels as Transaction
+ ACTIVITY_LABELS = Transaction::ACTIVITY_LABELS.dup.freeze
validates :qty, presence: true
validates :price, :currency, presence: true
+ validates :investment_activity_label, inclusion: { in: ACTIVITY_LABELS }, allow_nil: true
# Trade types for categorization
def buy?
@@ -35,4 +38,10 @@ class Trade < ApplicationRecord
Trend.new(current: current_value, previous: cost_basis)
end
+
+ # Trades are always excluded from expense budgets
+ # They represent portfolio management, not living expenses
+ def excluded_from_budget?
+ true
+ end
end
diff --git a/app/models/trade/create_form.rb b/app/models/trade/create_form.rb
index a6973df722..d822131c56 100644
--- a/app/models/trade/create_form.rb
+++ b/app/models/trade/create_form.rb
@@ -42,7 +42,7 @@ class Trade::CreateForm
price: price,
currency: currency,
security: security,
- category: investment_category_for(type)
+ investment_activity_label: type.capitalize # "buy" → "Buy", "sell" → "Sell"
)
)
@@ -54,14 +54,6 @@ class Trade::CreateForm
trade_entry
end
- def investment_category_for(trade_type)
- # Buy trades are categorized as "Savings & Investments" (expense)
- # Sell trades are left uncategorized for now
- return nil unless trade_type == "buy"
-
- account.family.categories.find_by(name: "Savings & Investments")
- end
-
def create_interest_income
signed_amount = amount.to_d * -1
diff --git a/app/models/trade_import.rb b/app/models/trade_import.rb
index ed0f17bcda..e8372bed40 100644
--- a/app/models/trade_import.rb
+++ b/app/models/trade_import.rb
@@ -21,7 +21,7 @@ class TradeImport < Import
qty: row.qty,
currency: row.currency.presence || mapped_account.currency,
price: row.price,
- category: investment_category_for(row.qty, mapped_account.family),
+ investment_activity_label: investment_activity_label_for(row.qty),
entry: Entry.new(
account: mapped_account,
date: row.date_iso,
@@ -78,12 +78,11 @@ class TradeImport < Import
end
private
- def investment_category_for(qty, family)
- # Buy trades (positive qty) are categorized as "Savings & Investments"
- # Sell trades are left uncategorized - users will be prompted to categorize
- return nil unless qty.to_d.positive?
-
- family.categories.find_by(name: "Savings & Investments")
+ def investment_activity_label_for(qty)
+ # Set activity label based on quantity signage
+ # Buy trades have positive qty, Sell trades have negative qty
+ return nil if qty.blank? || qty.to_d.zero?
+ qty.to_d.positive? ? "Buy" : "Sell"
end
def find_or_create_security(ticker: nil, exchange_operating_mic: nil)
diff --git a/app/models/transaction.rb b/app/models/transaction.rb
index e1a86afb5b..4850923b2f 100644
--- a/app/models/transaction.rb
+++ b/app/models/transaction.rb
@@ -26,6 +26,9 @@ class Transaction < ApplicationRecord
"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
+
# 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, -> {
diff --git a/app/views/investment_activity/_badge.html.erb b/app/views/investment_activity/_badge.html.erb
new file mode 100644
index 0000000000..549d5b33f0
--- /dev/null
+++ b/app/views/investment_activity/_badge.html.erb
@@ -0,0 +1,33 @@
+<%# locals: (label:) %>
+<%# Simple non-interactive badge for displaying activity labels %>
+<%
+ # Color mapping for different investment activity labels
+ color = case label
+ when "Buy"
+ "rgb(59 130 246)" # blue
+ when "Sell"
+ "rgb(239 68 68)" # red
+ when "Dividend", "Interest"
+ "rgb(34 197 94)" # green
+ when "Contribution"
+ "rgb(168 85 247)" # purple
+ when "Withdrawal"
+ "rgb(249 115 22)" # orange
+ when "Fee"
+ "rgb(107 114 128)" # gray
+ when "Transfer", "Sweep In", "Sweep Out", "Exchange"
+ "rgb(107 114 128)" # gray
+ when "Reinvestment"
+ "rgb(59 130 246)" # blue
+ else
+ "rgb(107 114 128)" # gray for "Other"
+ end
+%>
+
+<span class="inline-flex items-center gap-1 text-xs font-medium rounded px-1.5 py-0.5 border"
+ style="
+ background-color: color-mix(in oklab, <%= color %> 10%, transparent);
+ border-color: color-mix(in oklab, <%= color %> 20%, transparent);
+ color: <%= color %>;">
+ <%= label %>
+</span>
diff --git a/app/views/investment_activity/_quick_edit_badge.html.erb b/app/views/investment_activity/_quick_edit_badge.html.erb
new file mode 100644
index 0000000000..4db357ef2b
--- /dev/null
+++ b/app/views/investment_activity/_quick_edit_badge.html.erb
@@ -0,0 +1,95 @@
+<%# locals: (entry:, entryable:) %>
+<%
+ label = entryable.investment_activity_label
+ has_label = label.present?
+
+ # Build the correct URL based on entryable type
+ update_url = entryable.is_a?(Transaction) ? transaction_path(entry) : trade_path(entry)
+
+ # Color mapping for different investment activity labels using design system tokens
+ color = if has_label
+ case label
+ when "Buy"
+ "var(--color-blue-500)"
+ when "Sell"
+ "var(--color-red-500)"
+ when "Dividend", "Interest"
+ "var(--color-green-500)"
+ when "Contribution"
+ "var(--color-violet-500)"
+ when "Withdrawal"
+ "var(--color-orange-500)"
+ when "Fee"
+ "var(--color-gray-500)"
+ when "Transfer", "Sweep In", "Sweep Out", "Exchange"
+ "var(--color-gray-500)"
+ when "Reinvestment"
+ "var(--color-blue-500)"
+ else
+ "var(--color-gray-500)" # for "Other"
+ end
+ else
+ "var(--color-gray-400)" # slightly lighter for empty state
+ end
+
+ activity_labels = entryable.is_a?(Trade) ? Trade::ACTIVITY_LABELS : Transaction::ACTIVITY_LABELS
+ entryable_type = entryable.is_a?(Trade) ? "Trade" : "Transaction"
+ convert_url = entryable.is_a?(Transaction) ? convert_to_trade_transaction_path(entryable) : nil
+%>
+
+<div class="relative"
+ data-controller="activity-label-quick-edit"
+ data-activity-label-quick-edit-url-value="<%= update_url %>"
+ data-activity-label-quick-edit-entryable-id-value="<%= entryable.id %>"
+ data-activity-label-quick-edit-current-label-value="<%= label %>"
+ data-activity-label-quick-edit-entryable-type-value="<%= entryable_type %>"
+ <% if convert_url %>
+ data-activity-label-quick-edit-convert-url-value="<%= convert_url %>"
+ <% end %>>
+
+ <button type="button"
+ class="inline-flex items-center gap-1 text-xs font-medium rounded-full px-2.5 py-1 cursor-pointer hover:opacity-80 transition-opacity"
+ style="<% if has_label %>
+ background-color: color-mix(in oklab, <%= color %> 15%, transparent);
+ border: 1px solid color-mix(in oklab, <%= color %> 25%, transparent);
+ color: <%= color %>;
+ <% else %>
+ background-color: var(--color-surface-inset);
+ border: 1px solid var(--color-border-secondary);
+ color: var(--color-text-secondary);
+ <% end %>"
+ data-action="click->activity-label-quick-edit#toggle"
+ data-activity-label-quick-edit-target="badge"
+ title="<%= has_label ? t("transactions.transaction.activity_type_tooltip") : t("transactions.show.activity_type") %>">
+ <% if has_label %>
+ <%= label %>
+ <% else %>
+ <%= icon "tag", size: "xs", color: "current" %>
+ <span><%= t("transactions.show.activity_type") %></span>
+ <% end %>
+ <%= icon "chevron-down", size: "xs", color: "current" %>
+ </button>
+
+ <!-- Dropdown menu -->
+ <div class="hidden absolute right-0 z-50 mt-1 w-44 rounded-lg border border-primary bg-container shadow-lg"
+ data-activity-label-quick-edit-target="dropdown">
+ <div class="py-1 max-h-64 overflow-y-auto">
+ <% if has_label %>
+ <button type="button"
+ class="w-full text-left px-3 py-1.5 text-sm text-secondary hover:bg-surface-inset transition-colors border-b border-primary"
+ data-action="click->activity-label-quick-edit#select"
+ data-label="">
+ <span class="italic"><%= t("transactions.form.none") %></span>
+ </button>
+ <% end %>
+ <% activity_labels.each do |activity_label| %>
+ <button type="button"
+ class="w-full text-left px-3 py-1.5 text-sm text-primary hover:bg-surface-inset transition-colors <%= activity_label == label ? "font-semibold bg-surface-inset" : "" %>"
+ data-action="click->activity-label-quick-edit#select"
+ data-label="<%= activity_label %>">
+ <%= activity_label %>
+ </button>
+ <% end %>
+ </div>
+ </div>
+</div>
diff --git a/app/views/pages/dashboard/_investment_summary.html.erb b/app/views/pages/dashboard/_investment_summary.html.erb
index e35a5e443a..30b83a067c 100644
--- a/app/views/pages/dashboard/_investment_summary.html.erb
+++ b/app/views/pages/dashboard/_investment_summary.html.erb
@@ -77,21 +77,40 @@
<%# Investment Activity Summary %>
<% totals = investment_statement.totals(period: period) %>
- <% if totals.trades_count > 0 %>
- <div class="px-4 pt-2">
- <p class="text-xs text-secondary uppercase font-medium mb-2"><%= t(".period_activity", period: period.label) %></p>
- <div class="flex gap-4 text-sm">
- <div>
- <span class="text-secondary"><%= t(".contributions") %>:</span>
- <span class="font-medium text-primary"><%= format_money(totals.contributions) %></span>
- </div>
- <div>
- <span class="text-secondary"><%= t(".withdrawals") %>:</span>
- <span class="font-medium text-primary"><%= format_money(totals.withdrawals) %></span>
- </div>
- <div>
- <span class="text-secondary"><%= t(".trades") %>:</span>
- <span class="font-medium text-primary"><%= totals.trades_count %></span>
+ <% if totals.trades_count > 0 || totals.contributions.to_f > 0 || totals.withdrawals.to_f > 0 %>
+ <div class="bg-container-inset rounded-xl p-1 mx-4">
+ <div class="px-4 py-2 flex items-center uppercase text-xs font-medium text-secondary">
+ <%= t(".period_activity", period: period.label) %>
+ </div>
+ <div class="shadow-border-xs rounded-lg bg-container font-medium text-sm">
+ <div class="p-4 flex items-center justify-between gap-4">
+ <div class="flex items-center gap-2">
+ <div class="w-8 h-8 rounded-full bg-green-500/10 flex items-center justify-center">
+ <%= icon "trending-up", size: "sm", color: "green" %>
+ </div>
+ <div>
+ <p class="text-xs text-secondary"><%= t(".contributions") %></p>
+ <p class="font-medium text-green-600"><%= format_money(totals.contributions) %></p>
+ </div>
+ </div>
+ <div class="flex items-center gap-2">
+ <div class="w-8 h-8 rounded-full bg-orange-500/10 flex items-center justify-center">
+ <%= icon "trending-down", size: "sm", color: "orange" %>
+ </div>
+ <div>
+ <p class="text-xs text-secondary"><%= t(".withdrawals") %></p>
+ <p class="font-medium text-orange-600"><%= format_money(totals.withdrawals) %></p>
+ </div>
+ </div>
+ <div class="flex items-center gap-2">
+ <div class="w-8 h-8 rounded-full bg-blue-500/10 flex items-center justify-center">
+ <%= icon "arrow-left-right", size: "sm", color: "blue" %>
+ </div>
+ <div>
+ <p class="text-xs text-secondary"><%= t(".trades") %></p>
+ <p class="font-medium text-primary"><%= totals.trades_count %></p>
+ </div>
+ </div>
</div>
</div>
</div>
diff --git a/app/views/reports/_investment_flows.html.erb b/app/views/reports/_investment_flows.html.erb
new file mode 100644
index 0000000000..99a01273a1
--- /dev/null
+++ b/app/views/reports/_investment_flows.html.erb
@@ -0,0 +1,44 @@
+<%# locals: (investment_flows:) %>
+<div class="space-y-4">
+ <p class="text-sm text-secondary">
+ Track money flowing into and out of your investment accounts through contributions and withdrawals.
+ </p>
+
+ <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
+ <!-- Contributions -->
+ <div class="bg-container border border-primary rounded-lg p-4">
+ <div class="flex items-center gap-2 mb-2">
+ <%= icon("trending-up", size: "sm", class: "text-green-600") %>
+ <h3 class="text-sm font-medium text-secondary">Contributions</h3>
+ </div>
+ <div class="text-2xl font-semibold" style="color: rgb(34 197 94);">
+ <%= format_money(investment_flows.contributions) %>
+ </div>
+ <p class="text-xs text-secondary mt-1">Money added to investments</p>
+ </div>
+
+ <!-- Withdrawals -->
+ <div class="bg-container border border-primary rounded-lg p-4">
+ <div class="flex items-center gap-2 mb-2">
+ <%= icon("trending-down", size: "sm", class: "text-orange-600") %>
+ <h3 class="text-sm font-medium text-secondary">Withdrawals</h3>
+ </div>
+ <div class="text-2xl font-semibold" style="color: rgb(249 115 22);">
+ <%= format_money(investment_flows.withdrawals) %>
+ </div>
+ <p class="text-xs text-secondary mt-1">Money withdrawn from investments</p>
+ </div>
+
+ <!-- Net Flow -->
+ <div class="bg-container border border-primary rounded-lg p-4">
+ <div class="flex items-center gap-2 mb-2">
+ <%= icon("arrow-right-left", size: "sm", class: "text-primary") %>
+ <h3 class="text-sm font-medium text-secondary">Net Flow</h3>
+ </div>
+ <div class="text-2xl font-semibold text-primary">
+ <%= format_money(investment_flows.net_flow) %>
+ </div>
+ <p class="text-xs text-secondary mt-1">Total net change</p>
+ </div>
+ </div>
+</div>
diff --git a/app/views/trades/_trade.html.erb b/app/views/trades/_trade.html.erb
index 30a38226ba..d768430e6a 100644
--- a/app/views/trades/_trade.html.erb
+++ b/app/views/trades/_trade.html.erb
@@ -27,7 +27,7 @@
</div>
<div class="flex lg:hidden">
- <%= render "categories/badge_mobile", category: trade.category || trade_category %>
+ <%= render "investment_activity/quick_edit_badge", entry: entry, entryable: trade %>
</div>
<div class="truncate flex-shrink">
@@ -40,8 +40,8 @@
</div>
</div>
- <div class="hidden lg:flex">
- <%= render "categories/badge", category: trade.category || trade_category %>
+ <div class="hidden lg:flex col-span-2 items-center">
+ <%= render "investment_activity/quick_edit_badge", entry: entry, entryable: trade %>
</div>
<div class="shrink-0 col-span-4 lg:col-span-2 ml-auto text-right">
diff --git a/app/views/trades/show.html.erb b/app/views/trades/show.html.erb
index 9d5cf3d032..227470fbaa 100644
--- a/app/views/trades/show.html.erb
+++ b/app/views/trades/show.html.erb
@@ -43,11 +43,6 @@
step: "any",
precision: 10,
disabled: @entry.linked? %>
-
- <%= ef.select :category_id,
- Current.family.categories.expenses.alphabetically.map { |c| [c.name, c.id] },
- { include_blank: t(".no_category"), label: t(".category_label") },
- { data: { "auto-submit-form-target": "auto" } } %>
<% end %>
<% end %>
</div>
diff --git a/app/views/transactions/_transaction.html.erb b/app/views/transactions/_transaction.html.erb
index 5eb0b822bb..3b30d1b3a3 100644
--- a/app/views/transactions/_transaction.html.erb
+++ b/app/views/transactions/_transaction.html.erb
@@ -78,13 +78,6 @@
</span>
<% end %>
- <%# Investment activity label badge %>
- <% if transaction.investment_activity_label.present? %>
- <span class="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-alpha-black-50 text-secondary" title="<%= t("transactions.transaction.activity_type_tooltip") %>">
- <%= t("transactions.activity_labels.#{transaction.investment_activity_label.parameterize(separator: '_')}") %>
- </span>
- <% end %>
-
<%# Pending indicator %>
<% if transaction.pending? %>
<span class="inline-flex items-center gap-1 text-xs font-medium rounded-full px-1.5 py-0.5 border border-secondary text-secondary" title="<%= t("transactions.transaction.pending_tooltip") %>">
@@ -144,7 +137,12 @@
</div>
<div class="hidden md:flex items-center gap-1 col-span-2">
- <%= render "transactions/transaction_category", transaction: transaction, variant: "desktop" %>
+ <% if entry.account.investment? && !transaction.transfer? %>
+ <%# For investment accounts, show activity label instead of category %>
+ <%= render "investment_activity/quick_edit_badge", entry: entry, entryable: transaction %>
+ <% else %>
+ <%= render "transactions/transaction_category", transaction: transaction, variant: "desktop" %>
+ <% end %>
</div>
<div class="shrink-0 col-span-4 lg:col-span-2 ml-auto text-right">
diff --git a/app/views/transactions/convert_to_trade.html.erb b/app/views/transactions/convert_to_trade.html.erb
new file mode 100644
index 0000000000..4c26097bc4
--- /dev/null
+++ b/app/views/transactions/convert_to_trade.html.erb
@@ -0,0 +1,141 @@
+<%
+ # Use activity_label param if provided (from quick-edit badge click),
+ # otherwise determine default based on amount sign
+ # Negative amount (money going out) = Buy, Positive (money coming in) = Sell
+ default_label = params[:activity_label].presence || (@entry.amount > 0 ? "Sell" : "Buy")
+
+ # Get unique securities from account holdings for ticker suggestions
+ account_securities = @entry.account.holdings
+ .includes(:security)
+ .where.not(security: nil)
+ .map(&:security)
+ .uniq(&:ticker)
+ .sort_by(&:ticker)
+%>
+
+<%= render DS::Dialog.new(variant: "modal", reload_on_close: true) do |dialog| %>
+ <% dialog.with_header do %>
+ <h2 class="text-lg font-semibold text-primary"><%= t(".title") %></h2>
+ <p class="text-sm text-secondary"><%= t(".description") %></p>
+ <% end %>
+
+ <% dialog.with_body do %>
+ <%= form_with url: create_trade_from_transaction_transaction_path(@transaction), method: :post, class: "space-y-4", data: { controller: "convert-to-trade", turbo_frame: "_top" } do |f| %>
+ <!-- Pre-filled Transaction Info (Read-only) -->
+ <div class="space-y-2 p-3 bg-surface-inset rounded-lg border border-primary">
+ <div class="text-sm">
+ <span class="text-secondary"><%= t(".date_label") %></span>
+ <span class="font-medium text-primary"><%= @entry.date.strftime("%b %d, %Y") %></span>
+ </div>
+ <div class="text-sm">
+ <span class="text-secondary"><%= t(".account_label") %></span>
+ <span class="font-medium text-primary"><%= @entry.account.name %></span>
+ </div>
+ <div class="text-sm">
+ <span class="text-secondary"><%= t(".amount_label") %></span>
+ <span class="font-medium <%= @entry.amount.negative? ? "text-green-600" : "text-primary" %>"><%= format_money(@entry.amount_money.abs) %></span>
+ </div>
+ </div>
+
+ <!-- Trade-Specific Fields -->
+ <div class="space-y-4">
+ <div class="space-y-1">
+ <%= f.label :security_id, t(".security_label"), class: "font-medium text-sm text-primary block" %>
+ <% if account_securities.any? %>
+ <%= f.select :security_id,
+ options_for_select(
+ [[t(".security_prompt"), ""]] +
+ account_securities.map { |s| ["#{s.ticker}#{s.name.present? ? " - #{s.name.truncate(30)}" : ""}", s.id] } +
+ [[t(".security_custom"), "__custom__"]],
+ nil
+ ),
+ {},
+ {
+ class: "form-field__input border border-secondary rounded-lg px-3 py-2 w-full text-primary bg-container",
+ data: {
+ action: "change->convert-to-trade#toggleCustomTicker",
+ convert_to_trade_target: "tickerSelect"
+ }
+ } %>
+ <div class="hidden mt-2" data-convert-to-trade-target="customWrapper">
+ <%= f.text_field :custom_ticker,
+ placeholder: t(".ticker_placeholder"),
+ class: "form-field__input border border-secondary rounded-lg px-3 py-2 w-full text-primary bg-container",
+ pattern: "[A-Za-z0-9.:-]{1,20}",
+ title: t(".ticker_hint"),
+ data: { convert_to_trade_target: "customField" } %>
+ </div>
+ <p class="text-xs text-secondary"><%= t(".security_hint") %></p>
+ <% else %>
+ <%= f.text_field :ticker,
+ placeholder: t(".ticker_placeholder"),
+ required: true,
+ class: "form-field__input border border-secondary rounded-lg px-3 py-2 w-full text-primary bg-container",
+ pattern: "[A-Za-z0-9.:-]{1,20}",
+ title: t(".ticker_hint") %>
+ <p class="text-xs text-secondary"><%= t(".ticker_hint") %></p>
+ <% end %>
+ </div>
+
+ <div class="grid grid-cols-2 gap-4">
+ <div class="space-y-1">
+ <%= f.label :qty, t(".quantity_label"), class: "font-medium text-sm text-primary block" %>
+ <%= f.number_field :qty,
+ step: "any",
+ placeholder: t(".quantity_placeholder"),
+ class: "form-field__input border border-secondary rounded-lg px-3 py-2 w-full text-primary bg-container" %>
+ <p class="text-xs text-secondary"><%= t(".quantity_hint") %></p>
+ </div>
+
+ <div class="space-y-1">
+ <%= f.label :price, t(".price_label"), class: "font-medium text-sm text-primary block" %>
+ <%= f.number_field :price,
+ step: "0.0001",
+ min: "0",
+ placeholder: t(".price_placeholder"),
+ class: "form-field__input border border-secondary rounded-lg px-3 py-2 w-full text-primary bg-container" %>
+ <p class="text-xs text-secondary"><%= t(".price_hint", currency: @entry.currency) %></p>
+ </div>
+ </div>
+
+ <p class="text-xs text-secondary bg-surface-inset p-2 rounded">
+ <%= icon "info", size: "xs", class: "inline-block mr-1" %>
+ <%= t(".qty_or_price_hint", amount: format_money(@entry.amount_money.abs)) %>
+ </p>
+
+ <div class="space-y-1">
+ <%= f.label :investment_activity_label, t(".trade_type_label"), class: "font-medium text-sm text-primary block" %>
+ <%= f.select :investment_activity_label,
+ options_for_select([[t("transactions.activity_labels.buy"), "Buy"], [t("transactions.activity_labels.sell"), "Sell"]], default_label),
+ {},
+ { class: "form-field__input border border-secondary rounded-lg px-3 py-2 w-full text-primary bg-container" } %>
+ <p class="text-xs text-secondary"><%= t(".trade_type_hint") %></p>
+ </div>
+
+ <div class="space-y-1">
+ <%= f.label :exchange_operating_mic, t(".exchange_label"), class: "font-medium text-sm text-primary block" %>
+ <%= f.text_field :exchange_operating_mic,
+ placeholder: t(".exchange_placeholder"),
+ class: "form-field__input border border-secondary rounded-lg px-3 py-2 w-full text-primary bg-container",
+ pattern: "[A-Z]{4}",
+ title: t(".exchange_hint") %>
+ <p class="text-xs text-secondary"><%= t(".exchange_hint") %></p>
+ </div>
+ </div>
+
+ <div class="flex justify-end gap-3 pt-4 border-t border-primary">
+ <%= render DS::Button.new(
+ text: t(".cancel"),
+ variant: "outline",
+ href: "#",
+ data: { action: "click->ds--dialog#close" }
+ ) %>
+ <%= render DS::Button.new(
+ text: t(".submit"),
+ variant: "primary",
+ type: "submit"
+ ) %>
+ </div>
+ <% end %>
+ <% end %>
+<% end %>
diff --git a/app/views/transactions/show.html.erb b/app/views/transactions/show.html.erb
index 3d8910dcb6..4fa75711d1 100644
--- a/app/views/transactions/show.html.erb
+++ b/app/views/transactions/show.html.erb
@@ -265,6 +265,25 @@
) %>
</div>
+ <!-- Convert to Trade (Investment Accounts Only, not already converted) -->
+ <% if @entry.account.investment? && @entry.entryable.is_a?(Transaction) && [email protected]? %>
+ <div class="flex items-center justify-between gap-2 p-3">
+ <div class="text-sm space-y-1">
+ <h4 class="text-primary">Convert to Security Trade</h4>
+ <p class="text-secondary">Convert this transaction into a security trade (buy/sell) by providing ticker, shares, and price.</p>
+ </div>
+
+ <%= render DS::Button.new(
+ text: "Convert",
+ variant: "outline",
+ icon: "arrow-right-left",
+ href: convert_to_trade_transaction_path(@entry.transaction),
+ method: :get,
+ frame: :modal
+ ) %>
+ </div>
+ <% end %>
+
<!-- Mark as Recurring Form -->
<div class="flex items-center justify-between gap-2 p-3">
<div class="text-sm space-y-1">
diff --git a/config/locales/views/reports/en.yml b/config/locales/views/reports/en.yml
index ceebbe74c0..189a99ebef 100644
--- a/config/locales/views/reports/en.yml
+++ b/config/locales/views/reports/en.yml
@@ -134,6 +134,12 @@ en:
value: Value
return: Return
accounts: Investment Accounts
+ investment_flows:
+ title: Investment Flows
+ description: Track money flowing into and out of your investment accounts
+ contributions: Contributions
+ withdrawals: Withdrawals
+ net_flow: Net Flow
google_sheets_instructions:
title_with_key: "✅ Copy URL for Google Sheets"
title_no_key: "⚠️ API Key Required"
diff --git a/config/locales/views/transactions/en.yml b/config/locales/views/transactions/en.yml
index ae7bb1cb36..35eb2308e3 100644
--- a/config/locales/views/transactions/en.yml
+++ b/config/locales/views/transactions/en.yml
@@ -37,6 +37,9 @@ en:
activity_type_description: Type of investment activity (Buy, Sell, Dividend, etc.). Auto-detected or set manually.
one_time_title: One-time %{type}
one_time_description: One-time transactions will be excluded from certain budgeting calculations and reports to help you see what's really important.
+ convert_to_trade_title: Convert to Security Trade
+ convert_to_trade_description: Convert this transaction into a Buy or Sell trade with security details for portfolio tracking.
+ convert_to_trade_button: Convert to Trade
activity_labels:
buy: Buy
sell: Sell
@@ -103,6 +106,43 @@ en:
category: Category
tag: Tag
merchant: Merchant
+ convert_to_trade:
+ title: Convert to Security Trade
+ description: Convert this transaction into a trade with security details
+ date_label: "Date:"
+ account_label: "Account:"
+ amount_label: "Amount:"
+ security_label: Security
+ security_prompt: Select a security...
+ security_custom: "+ Enter custom ticker"
+ security_hint: Select from your holdings or enter a custom ticker
+ ticker_placeholder: AAPL
+ ticker_hint: Enter the stock/ETF ticker symbol
+ quantity_label: Quantity (Shares)
+ quantity_placeholder: e.g. 20
+ quantity_hint: Number of shares traded
+ price_label: Price per Share
+ price_placeholder: e.g. 52.15
+ price_hint: Price per share (%{currency})
+ qty_or_price_hint: Enter at least qty OR price. The other will be calculated from the transaction amount (%{amount}).
+ trade_type_label: Trade Type
+ trade_type_hint: Buy or Sell shares of a security
+ exchange_label: Exchange (Optional)
+ exchange_placeholder: XNAS
+ exchange_hint: Leave blank to auto-detect
+ cancel: Cancel
+ submit: Convert to Trade
+ success: Transaction converted to trade
+ errors:
+ not_investment_account: Only transactions in investment accounts can be converted to trades
+ already_converted: This transaction has already been converted or excluded
+ enter_ticker: Please enter a ticker symbol
+ security_not_found: Selected security no longer exists. Please select another.
+ select_security: Please select or enter a security
+ enter_qty_or_price: Please enter either quantity or price per share. The other will be calculated from the transaction amount.
+ invalid_qty_or_price: Invalid quantity or price. Please enter valid positive values.
+ conversion_failed: "Failed to convert transaction: %{error}"
+ unexpected_error: "Unexpected error during conversion: %{error}"
searches:
filters:
amount_filter:
diff --git a/config/routes.rb b/config/routes.rb
index 07a70144ee..0106f6d176 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -197,6 +197,8 @@ Rails.application.routes.draw do
end
member do
+ get :convert_to_trade
+ post :create_trade_from_transaction
post :mark_as_recurring
post :merge_duplicate
post :dismiss_duplicate
diff --git a/db/migrate/20260113230414_add_investment_activity_label_to_trades.rb b/db/migrate/20260113230414_add_investment_activity_label_to_trades.rb
new file mode 100644
index 0000000000..9e8e3e8a8b
--- /dev/null
+++ b/db/migrate/20260113230414_add_investment_activity_label_to_trades.rb
@@ -0,0 +1,22 @@
+class AddInvestmentActivityLabelToTrades < ActiveRecord::Migration[7.2]
+ def change
+ # Add activity label to trades (matching Transaction)
+ add_column :trades, :investment_activity_label, :string
+ add_index :trades, :investment_activity_label
+
+ # Backfill existing trades with basic labels based on quantity
+ reversible do |dir|
+ dir.up do
+ execute <<~SQL
+ UPDATE trades
+ SET investment_activity_label = CASE
+ WHEN qty > 0 THEN 'Buy'
+ WHEN qty < 0 THEN 'Sell'
+ ELSE 'Other'
+ END
+ WHERE investment_activity_label IS NULL
+ SQL
+ end
+ end
+ end
+end
diff --git a/db/migrate/20260114002048_remove_category_from_trades.rb b/db/migrate/20260114002048_remove_category_from_trades.rb
new file mode 100644
index 0000000000..333f910d6c
--- /dev/null
+++ b/db/migrate/20260114002048_remove_category_from_trades.rb
@@ -0,0 +1,5 @@
+class RemoveCategoryFromTrades < ActiveRecord::Migration[7.2]
+ def change
+ remove_column :trades, :category_id, :bigint
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index fe90f4ce2a..4e123a2ab9 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1183,14 +1183,14 @@ ActiveRecord::Schema[7.2].define(version: 2026_01_15_100001) do
t.datetime "updated_at", null: false
t.string "currency"
t.jsonb "locked_attributes", default: {}
- t.uuid "category_id"
t.decimal "realized_gain", precision: 19, scale: 4
t.decimal "cost_basis_amount", precision: 19, scale: 4
t.string "cost_basis_currency"
t.integer "holding_period_days"
t.string "realized_gain_confidence"
t.string "realized_gain_currency"
- t.index ["category_id"], name: "index_trades_on_category_id"
+ t.string "investment_activity_label"
+ t.index ["investment_activity_label"], name: "index_trades_on_investment_activity_label"
t.index ["realized_gain"], name: "index_trades_on_realized_gain_not_null", where: "(realized_gain IS NOT NULL)"
t.index ["security_id"], name: "index_trades_on_security_id"
end
@@ -1348,7 +1348,6 @@ ActiveRecord::Schema[7.2].define(version: 2026_01_15_100001) do
add_foreign_key "taggings", "tags"
add_foreign_key "tags", "families"
add_foreign_key "tool_calls", "messages"
- add_foreign_key "trades", "categories"
add_foreign_key "trades", "securities"
add_foreign_key "transactions", "categories", on_delete: :nullify
add_foreign_key "transactions", "merchants"
diff --git a/test/fixtures/trades.yml b/test/fixtures/trades.yml
index bf1acd710e..d421b51cc1 100644
--- a/test/fixtures/trades.yml
+++ b/test/fixtures/trades.yml
@@ -3,3 +3,4 @@ one:
qty: 10
price: 214
currency: USD
+ investment_activity_label: Buy
diff --git a/test/models/account/market_data_importer_test.rb b/test/models/account/market_data_importer_test.rb
index 828f348146..eead24bd5d 100644
--- a/test/models/account/market_data_importer_test.rb
+++ b/test/models/account/market_data_importer_test.rb
@@ -79,7 +79,7 @@ class Account::MarketDataImporterTest < ActiveSupport::TestCase
security = Security.create!(ticker: "AAPL", exchange_operating_mic: "XNAS")
trade_date = 10.days.ago.to_date
- trade = Trade.new(security: security, qty: 1, price: 100, currency: "USD")
+ trade = Trade.new(security: security, qty: 1, price: 100, currency: "USD", investment_activity_label: "Buy")
account.entries.create!(
name: "Buy AAPL",
@@ -129,7 +129,7 @@ class Account::MarketDataImporterTest < ActiveSupport::TestCase
security = Security.create!(ticker: "INVALID", exchange_operating_mic: "XNAS")
trade_date = 10.days.ago.to_date
- trade = Trade.new(security: security, qty: 1, price: 100, currency: "USD")
+ trade = Trade.new(security: security, qty: 1, price: 100, currency: "USD", investment_activity_label: "Buy")
account.entries.create!(
name: "Buy INVALID",
diff --git a/test/models/trade_import_test.rb b/test/models/trade_import_test.rb
index 7914fe9328..3fbdd3c11f 100644
--- a/test/models/trade_import_test.rb
+++ b/test/models/trade_import_test.rb
@@ -63,20 +63,13 @@ class TradeImportTest < ActiveSupport::TestCase
assert_equal "complete", @import.status
end
- test "auto-categorizes buy trades and leaves sell trades uncategorized" do
+ test "auto-assigns investment activity labels to buy and sell trades" do
aapl = securities(:aapl)
aapl_resolver = mock
aapl_resolver.stubs(:resolve).returns(aapl)
Security::Resolver.stubs(:new).returns(aapl_resolver)
- # Create the investment category if it doesn't exist
account = accounts(:depository)
- family = account.family
- savings_category = family.categories.find_or_create_by!(name: "Savings & Investments") do |c|
- c.color = "#059669"
- c.classification = "expense"
- c.lucide_icon = "piggy-bank"
- end
import = <<~CSV
date,ticker,qty,price,currency,name
@@ -109,7 +102,7 @@ class TradeImportTest < ActiveSupport::TestCase
assert_not_nil buy_trade, "Buy trade should have been created"
assert_not_nil sell_trade, "Sell trade should have been created"
- assert_equal savings_category, buy_trade.category, "Buy trade should be auto-categorized as Savings & Investments"
- assert_nil sell_trade.category, "Sell trade should not be auto-categorized"
+ assert_equal "Buy", buy_trade.investment_activity_label, "Buy trade should have 'Buy' activity label"
+ assert_equal "Sell", sell_trade.investment_activity_label, "Sell trade should have 'Sell' activity label"
end
end
diff --git a/test/models/trade_test.rb b/test/models/trade_test.rb
index c86f442103..ab8ba56ba2 100644
--- a/test/models/trade_test.rb
+++ b/test/models/trade_test.rb
@@ -30,7 +30,8 @@ class TradeTest < ActiveSupport::TestCase
security: security,
price: precise_price,
qty: 10000,
- currency: "USD"
+ currency: "USD",
+ investment_activity_label: "Buy"
)
trade.reload
@@ -47,7 +48,8 @@ class TradeTest < ActiveSupport::TestCase
security: security,
price: price_with_too_many_decimals,
qty: 1,
- currency: "USD"
+ currency: "USD",
+ investment_activity_label: "Buy"
)
trade.reload
diff --git a/test/support/entries_test_helper.rb b/test/support/entries_test_helper.rb
index f586b14882..90ecd92208 100644
--- a/test/support/entries_test_helper.rb
+++ b/test/support/entries_test_helper.rb
@@ -41,7 +41,8 @@ module EntriesTestHelper
qty: qty,
security: security,
price: trade_price,
- currency: currency
+ currency: currency,
+ investment_activity_label: qty > 0 ? "Buy" : "Sell"
account.entries.create! \
name: "Trade",
diff --git a/test/support/ledger_testing_helper.rb b/test/support/ledger_testing_helper.rb
index d5e08aec48..a2266b679a 100644
--- a/test/support/ledger_testing_helper.rb
+++ b/test/support/ledger_testing_helper.rb
@@ -77,7 +77,8 @@ module LedgerTestingHelper
qty: entry_data[:qty],
security: security,
price: entry_data[:price],
- currency: currency
+ currency: currency,
+ investment_activity_label: entry_data[:qty] > 0 ? "Buy" : "Sell"
)
created_account.entries.create!(