The personal finance app for everyone
Stock filter (#1376)
Josh Pigford7d8028b5059b
diff --git a/Gemfile b/Gemfileindex cdb9fca0..61bb7c5c 100644--- a/Gemfile+++ b/Gemfile@@ -21,6 +21,7 @@ gem "lucide-rails", github: "maybe-finance/lucide-rails"# Hotwiregem "stimulus-rails"gem "turbo-rails"+gem "hotwire_combobox"# Background Jobsgem "good_job"diff --git a/Gemfile.lock b/Gemfile.lockindex dc2c8dee..e1e5558e 100644--- a/Gemfile.lock+++ b/Gemfile.lock@@ -188,6 +188,10 @@ GEMactioncable (>= 6.0.0)listen (>= 3.0.0)railties (>= 6.0.0)+ hotwire_combobox (0.3.2)+ rails (>= 7.0.7.2)+ stimulus-rails (>= 1.2)+ turbo-rails (>= 1.2)i18n (1.14.6)concurrent-ruby (~> 1.0)i18n-tasks (1.0.14)@@ -485,6 +489,7 @@ DEPENDENCIESgood_jobholidayshotwire-livereload+ hotwire_comboboxi18n-tasksimage_processing (>= 1.2)importmap-railsdiff --git a/app/assets/stylesheets/application.tailwind.css b/app/assets/stylesheets/application.tailwind.cssindex 33711536..f96f0c88 100644--- a/app/assets/stylesheets/application.tailwind.css+++ b/app/assets/stylesheets/application.tailwind.css@@ -19,7 +19,8 @@@apply focus-within:border-gray-900 focus-within:shadow-none focus-within:ring-4 focus-within:ring-gray-100;}- .form-field__label {++ .form-field__label, .hw-combobox__label {@apply block text-xs text-gray-500 peer-disabled:text-gray-400;}@@ -120,6 +121,33 @@}}+.combobox {+ .hw-combobox__main__wrapper, .hw-combobox__input {+ @apply w-full;+ }++ .hw-combobox__main__wrapper {+ @apply border-0 p-0 focus:border-0 ring-0 focus:ring-0 shadow-none focus:shadow-none focus-within:shadow-none;+ }++ .hw-combobox__listbox {+ @apply absolute top-[160%] right-0 w-full bg-transparent rounded z-30;+ }++ .hw_combobox__pagination__wrapper {+ @apply h-px;++ &:only-child {+ @apply bg-transparent;+ }+ }++ --hw-border-color: rgba(0, 0, 0, 0.2);+ --hw-handle-width: 20px;+ --hw-handle-height: 20px;+ --hw-handle-offset-right: 0px;+}+/* Small, single purpose classes that should take precedence over other styles */@layer utilities {.scrollbar::-webkit-scrollbar {diff --git a/app/controllers/account/trades_controller.rb b/app/controllers/account/trades_controller.rbindex b5b6092a..8b5a878c 100644--- a/app/controllers/account/trades_controller.rb+++ b/app/controllers/account/trades_controller.rb@@ -33,6 +33,10 @@ class Account::TradesController < ApplicationControllerendend+ def securities+ @pagy, @securities = pagy(Security.order(:name).search(params[:q]), limit: 20)+ end+privatedef set_accountdiff --git a/app/models/account/trade_builder.rb b/app/models/account/trade_builder.rbindex 1dfad971..4610407f 100644--- a/app/models/account/trade_builder.rb+++ b/app/models/account/trade_builder.rb@@ -31,6 +31,7 @@ class Account::TradeBuilder < Account::EntryBuilderenddef security+ return Security.find(ticker) if ticker.match?(/\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/i)Security.find_or_create_by(ticker: ticker)enddiff --git a/app/models/security.rb b/app/models/security.rbindex 196835ad..94077182 100644--- a/app/models/security.rb+++ b/app/models/security.rb@@ -6,12 +6,36 @@ class Security < ApplicationRecordvalidates :ticker, presence: truevalidates :ticker, uniqueness: { scope: :exchange_mic, case_sensitive: false }+ scope :search, ->(query) {+ return none if query.blank? || query.length < 2++ # Clean and normalize the search terms+ sanitized_query = query.split.map do |term|+ cleaned_term = term.gsub(/[^a-zA-Z0-9]/, " ").strip+ next if cleaned_term.blank?+ cleaned_term+ end.compact.join(" | ")++ return none if sanitized_query.blank?++ sanitized_query = ActiveRecord::Base.connection.quote(sanitized_query)++ where("search_vector @@ to_tsquery('simple', #{sanitized_query}) AND exchange_mic IS NOT NULL")+ .select("securities.*, ts_rank_cd(search_vector, to_tsquery('simple', #{sanitized_query})) AS rank")+ .reorder("rank DESC")+ }+def current_price@current_price ||= Security::Price.find_price(ticker:, date: Date.current)return nil if @current_price.nil?Money.new(@current_price.price, @current_price.currency)end+ def to_combobox_display+ "#{ticker} - #{name} (#{exchange_acronym})"+ end++privatedef upcase_tickerdiff --git a/app/views/account/trades/_form.html.erb b/app/views/account/trades/_form.html.erbindex e39c7b15..283a7725 100644--- a/app/views/account/trades/_form.html.erb+++ b/app/views/account/trades/_form.html.erb@@ -7,10 +7,12 @@<div class="space-y-2"><%= form.select :type, options_for_select([%w[Buy buy], %w[Sell sell], %w[Deposit transfer_in], %w[Withdrawal transfer_out], %w[Interest interest]], "buy"), { label: t(".type") }, { data: { "trade-form-target": "typeInput" } } %><div data-trade-form-target="tickerInput">- <%= form.text_field :ticker, value: nil, label: t(".holding"), placeholder: t(".ticker_placeholder") %>+ <div class="form-field combobox">+ <%= form.combobox :ticker, securities_account_trades_path(entry.account), label: t(".holding"), placeholder: t(".ticker_placeholder"), autocomplete: :list, free_text: true %>+ </div></div>- <%= form.date_field :date, label: true %>+ <%= form.date_field :date, label: true, value: Date.current %><div data-trade-form-target="amountInput" hidden><%= form.money_field :amount, label: t(".amount"), disable_currency: true %>diff --git a/app/views/account/trades/_tickers.turbo_stream.erb b/app/views/account/trades/_tickers.turbo_stream.erbnew file mode 100644index 00000000..56436ab8--- /dev/null+++ b/app/views/account/trades/_tickers.turbo_stream.erb@@ -0,0 +1,7 @@+<div class="flex items-center">+ <%= image_tag("https://logo.synthfinance.com/ticker/#{tickers&.ticker}", class: "rounded-full h-8 w-8 inline-block mr-2") %>+ <div class="flex flex-col">+ <span class="text-sm font-medium"><%= tickers&.name.presence || tickers&.ticker %></span>+ <span class="text-xs text-gray-500"><%= "#{tickers&.ticker} (#{tickers&.exchange_acronym})" %></span>+ </div>+</div>diff --git a/app/views/account/trades/securities.turbo_stream.erb b/app/views/account/trades/securities.turbo_stream.erbnew file mode 100644index 00000000..7ed8e90e--- /dev/null+++ b/app/views/account/trades/securities.turbo_stream.erb@@ -0,0 +1,3 @@+<%= async_combobox_options @securities,+ render_in: { partial: "account/trades/tickers" },+ next_page: @pagy.next %>\ No newline at end of filediff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erbindex 1cead360..1c4d3b4e 100644--- a/app/views/layouts/application.html.erb+++ b/app/views/layouts/application.html.erb@@ -9,6 +9,8 @@<%= stylesheet_link_tag "tailwind", "inter-font", "data-turbo-track": "reload" %><%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>+ <%= combobox_style_tag %>+<%= javascript_importmap_tags %><%= hotwire_livereload_tags if Rails.env.development? %><%= turbo_refreshes_with method: :morph, scroll: :preserve %>diff --git a/config/routes.rb b/config/routes.rbindex 978e349a..70e59032 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -77,7 +77,9 @@ Rails.application.routes.draw doresources :transactions, only: %i[index update]resources :valuations, only: %i[index new create]- resources :trades, only: %i[index new create update]+ resources :trades, only: %i[index new create update] do+ get :securities, on: :collection+ endresources :entries, only: %i[edit update show destroy]enddiff --git a/db/migrate/20241025182612_add_search_vector_to_securities.rb b/db/migrate/20241025182612_add_search_vector_to_securities.rbnew file mode 100644index 00000000..67617e31--- /dev/null+++ b/db/migrate/20241025182612_add_search_vector_to_securities.rb@@ -0,0 +1,6 @@+class AddSearchVectorToSecurities < ActiveRecord::Migration[7.2]+ def change+ add_column :securities, :search_vector, :virtual, type: :tsvector, as: "setweight(to_tsvector('simple', coalesce(ticker, '')), 'B') || to_tsvector('simple', coalesce(name, ''))", stored: true+ add_index :securities, :search_vector, using: :gin+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 7445d127..5b2b4310 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -10,7 +10,7 @@## It's strongly recommended that you check this file into your version control system.-ActiveRecord::Schema[7.2].define(version: 2024_10_25_174650) do+ActiveRecord::Schema[7.2].define(version: 2024_10_25_182612) do# These are extensions that must be enabled in order to support this databaseenable_extension "pgcrypto"enable_extension "plpgsql"@@ -481,7 +481,9 @@ ActiveRecord::Schema[7.2].define(version: 2024_10_25_174650) dot.string "country_code"t.string "exchange_mic"t.string "exchange_acronym"+ t.virtual "search_vector", type: :tsvector, as: "(setweight(to_tsvector('simple'::regconfig, (COALESCE(ticker, ''::character varying))::text), 'B'::\"char\") || to_tsvector('simple'::regconfig, (COALESCE(name, ''::character varying))::text))", stored: truet.index ["country_code"], name: "index_securities_on_country_code"+ t.index ["search_vector"], name: "index_securities_on_search_vector", using: :gint.index ["ticker", "exchange_mic"], name: "index_securities_on_ticker_and_exchange_mic", unique: trueenddiff --git a/test/fixtures/securities.yml b/test/fixtures/securities.ymlindex 20c676a5..16d48a55 100644--- a/test/fixtures/securities.yml+++ b/test/fixtures/securities.yml@@ -1,7 +1,9 @@aapl:ticker: AAPLname: Apple+ exchange_mic: XNASmsft:ticker: MSFTname: Microsoft+ exchange_mic: XNASdiff --git a/test/system/trades_test.rb b/test/system/trades_test.rbindex c9f7835b..c79c3507 100644--- a/test/system/trades_test.rb+++ b/test/system/trades_test.rb@@ -16,7 +16,8 @@ class TradesTest < ApplicationSystemTestCaseopen_new_trade_modal- fill_in "Ticker symbol", with: "NVDA"+ fill_in "Ticker symbol", with: "AAPL"+ select_combobox_option("Apple")fill_in "Date", with: Date.currentfill_in "Quantity", with: shares_qtyfill_in "account_entry[price]", with: 214.23@@ -27,7 +28,7 @@ class TradesTest < ApplicationSystemTestCasewithin_trades doassert_text "Purchase 10 shares of AAPL"- assert_text "Buy #{shares_qty} shares of NVDA"+ assert_text "Buy #{shares_qty} shares of AAPL"endend@@ -38,6 +39,7 @@ class TradesTest < ApplicationSystemTestCaseselect "Sell", from: "Type"fill_in "Ticker symbol", with: aapl.ticker+ select_combobox_option(aapl.security.name)fill_in "Date", with: Date.currentfill_in "Quantity", with: aapl.qtyfill_in "account_entry[price]", with: 215.33@@ -64,4 +66,10 @@ class TradesTest < ApplicationSystemTestCasedef visit_account_tradesvisit account_url(@account, tab: "transactions")end++ def select_combobox_option(text)+ within "#account_entry_ticker-hw-listbox" do+ find("li", text: text).click+ end+ endend