Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Filter the Reports page by one or more tags (#5136)

Artur Kalimullin4f82d0be16ff
diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rb
index 7f60dce175..0634ffb58a 100644
--- a/app/controllers/reports_controller.rb
+++ b/app/controllers/reports_controller.rb
@@ -6,6 +6,8 @@ class ReportsController < ApplicationController
skip_authentication only: :export_transactions
before_action :authenticate_for_export, only: :export_transactions
+ helper_method :filter_tags
+
def index
setup_report_data(show_flash: true)
@@ -81,7 +83,8 @@ class ReportsController < ApplicationController
start_date: params[:start_date],
end_date: params[:end_date],
sort_by: params[:sort_by],
- sort_direction: params[:sort_direction]
+ sort_direction: params[:sort_direction],
+ filter_tag_ids: filter_tags.map(&:id).presence
}.compact
# The CSV URL the instructions tell people to add their API key to
@@ -113,6 +116,9 @@ class ReportsController < ApplicationController
@period = Period.custom(start_date: @start_date, end_date: @end_date)
@previous_period = build_previous_period
+ @tags = Current.family.tags.alphabetically
+ @filter_tags = filter_tags
+
# Get aggregated data
@income_statement = Current.family.income_statement(user: Current.user)
@current_income_totals = @income_statement.income_totals(period: @period)
@@ -210,7 +216,8 @@ class ReportsController < ApplicationController
transactions: @transactions,
period_type: @period_type,
start_date: @start_date,
- end_date: @end_date
+ end_date: @end_date,
+ filter_tags: filter_tags
},
visible: @has_accounts,
collapsible: true
@@ -296,13 +303,19 @@ class ReportsController < ApplicationController
def build_summary_metrics
# Ensure we always have Money objects
- current_income = ensure_money(@current_income_totals.total)
- current_expenses = ensure_money(@current_expense_totals.total)
+ if filter_tags.any?
+ current = @income_statement.totals_for(@period, tag_ids: filter_tags.map(&:id))
+ previous = @income_statement.totals_for(@previous_period, tag_ids: filter_tags.map(&:id))
+ current_income, current_expenses = current.income_money, current.expense_money
+ previous_income, previous_expenses = previous.income_money, previous.expense_money
+ else
+ current_income = ensure_money(@current_income_totals.total)
+ current_expenses = ensure_money(@current_expense_totals.total)
+ previous_income = ensure_money(@previous_income_totals.total)
+ previous_expenses = ensure_money(@previous_expense_totals.total)
+ end
net_savings = current_income - current_expenses
- previous_income = ensure_money(@previous_income_totals.total)
- previous_expenses = ensure_money(@previous_expense_totals.total)
-
# Calculate percentage changes
income_change = calculate_percentage_change(previous_income, current_income)
expense_change = calculate_percentage_change(previous_expenses, current_expenses)
@@ -365,8 +378,14 @@ class ReportsController < ApplicationController
period = Period.custom(start_date: month_start, end_date: month_end)
- income = income_statement.income_totals(period: period).total
- expenses = income_statement.expense_totals(period: period).total
+ if filter_tags.any?
+ totals = income_statement.totals_for(period, tag_ids: filter_tags.map(&:id))
+ income = totals.income_money.amount
+ expenses = totals.expense_money.amount
+ else
+ income = income_statement.income_totals(period: period).total
+ expenses = income_statement.expense_totals(period: period).total
+ end
trends << {
month: month_start.strftime("%b %Y"),
@@ -767,14 +786,21 @@ class ReportsController < ApplicationController
def apply_transaction_filters(scope)
scope = apply_entry_filters(scope)
- # Filter by tag (Transaction-specific — trades don't have taggings)
- if params[:filter_tag_id].present?
- scope = scope.joins(:taggings).where(taggings: { tag_id: params[:filter_tag_id] })
- end
+ scope = scope.with_any_tag(filter_tags.map(&:id)) if filter_tags.any?
scope
end
+ def filter_tag_ids
+ @filter_tag_ids ||= params[:filter_tag_ids].is_a?(Array) ? params[:filter_tag_ids].grep(String).compact_blank : []
+ end
+
+ # The family's tags among filter_tag_ids. Ids that match none of them
+ # (another family's tag, a deleted one) are ignored.
+ def filter_tags
+ @filter_tags ||= filter_tag_ids.any? ? Current.family.tags.where(id: filter_tag_ids).alphabetically.to_a : []
+ end
+
def exclude_tax_advantaged_accounts(scope)
tax_advantaged_account_ids = Current.family.tax_advantaged_account_ids
return scope if tax_advantaged_account_ids.blank?
@@ -798,6 +824,9 @@ class ReportsController < ApplicationController
scope = scope.model == Trade ? scope.none : scope.where(category_id: all_category_ids)
end
+ # Trades carry no tags, so a tag filter leaves them out.
+ scope = scope.none if scope.model == Trade && filter_tags.any?
+
# Filter by account
if params[:filter_account_id].present?
scope = scope.where(entries: { account_id: params[:filter_account_id] })
diff --git a/app/helpers/reports_helper.rb b/app/helpers/reports_helper.rb
index 3aab7df44d..6aedd3a7b5 100644
--- a/app/helpers/reports_helper.rb
+++ b/app/helpers/reports_helper.rb
@@ -2,10 +2,18 @@ module ReportsHelper
# Where a breakdown row links: its category's transactions in the period.
# /transactions only lists Transaction rows, so trade-only rows (e.g. Other
# Investments) link nowhere rather than to an empty list.
- def breakdown_transactions_path(item, start_date, end_date)
+ def breakdown_transactions_path(item, start_date, end_date, tags: [])
return unless item[:has_transactions] && start_date.present? && end_date.present?
- transactions_path(q: { categories: [ item[:category_filter_value] ], start_date: start_date, end_date: end_date })
+ query = { categories: [ item[:category_filter_value] ], start_date: start_date, end_date: end_date }
+ query[:tags] = tags.map(&:filter_value) if tags.any?
+ transactions_path(q: query)
+ end
+
+ # The Reports filters that period controls carry over, so changing the dates
+ # keeps the filter that is applied.
+ def reports_filter_params
+ { filter_tag_ids: filter_tags.map(&:id).presence }.compact
end
# Returns the DS::Pill tone for a given tax treatment. Mirrors the
diff --git a/app/models/family.rb b/app/models/family.rb
index 54f8502857..7fc4374e51 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -741,6 +741,17 @@ class Family < ApplicationRecord
"#{categories.count}-#{categories.maximum(:updated_at)&.to_f || 0}"
end
+ # Tag changes write taggings without touching their entries, so caches
+ # whose results depend on tag membership key on this too. The tag count
+ # catches a merge or a deletion, which moves or drops taggings without
+ # adding one.
+ def tags_version
+ tag_count, tag_max_at = tags.pick(Arel.sql("count(*)"), Arel.sql('max("tags"."updated_at")'))
+ tagging_count, tagging_max_at = Tagging.joins(:tag).where(tags: { family_id: id })
+ .pick(Arel.sql("count(*)"), Arel.sql('max("taggings"."updated_at")'))
+ "#{tag_count}-#{tag_max_at&.to_f}-#{tagging_count}-#{tagging_max_at&.to_f}"
+ end
+
# Used for invalidating caches keyed on recurring transactions (e.g. the
# transactions index's projected recurring list). See #entries_version for
# why .count is included alongside the timestamp.
diff --git a/app/models/income_statement.rb b/app/models/income_statement.rb
index 0af5b4e6ae..95b92ecd8b 100644
--- a/app/models/income_statement.rb
+++ b/app/models/income_statement.rb
@@ -150,9 +150,10 @@ class IncomeStatement
daily_expense_by_category(period).map(&:category_id).uniq
end
- def totals_for(period, account_ids: nil)
+ def totals_for(period, account_ids: nil, tag_ids: nil)
scope = family.transactions.visible.excluding_pending.merge(Entry.excluding_scheduled).in_period(period)
scope = scope.where(entries: { account_id: account_ids }) if account_ids.present?
+ scope = scope.with_any_tag(tag_ids) if tag_ids.present?
totals(transactions_scope: scope, date_range: period.date_range)
end
@@ -340,13 +341,14 @@ class IncomeStatement
# An IncomeStatement is a request-scoped reporting snapshot, like its memoized
# period totals. Share these aggregate reads across totals and daily series.
- # Rates, target currency and whether investing counts as spending can
- # change without touching entries or accounts. Scheduled entries are
+ # Rates, target currency, tag membership and whether investing counts as
+ # spending can change without touching entries or accounts. Scheduled entries are
# excluded as of "today", so the key also rolls over daily.
def cache_freshness_key
@cache_freshness_key ||= [
Date.current,
family.entries_cache_version,
+ family.tags_version,
family.accounts_status_version,
family.currency,
ExchangeRate.maximum(:updated_at)&.to_i,
diff --git a/app/models/transaction.rb b/app/models/transaction.rb
index c0a8db18bf..6130b18288 100644
--- a/app/models/transaction.rb
+++ b/app/models/transaction.rb
@@ -210,6 +210,12 @@ class Transaction < ApplicationRecord
scope :excluding_pending, -> { where(Transaction.not_pending_sql) }
+ # Transactions carrying any of the given tags. A subquery rather than a
+ # join, so a transaction with several of them is returned once.
+ scope :with_any_tag, ->(tag_ids) {
+ where(id: Tagging.where(tag_id: tag_ids, taggable_type: "Transaction").select(:taggable_id))
+ }
+
# SQL snippet for raw queries that must exclude pending transactions.
# Use in income statements, balance sheets, and raw analytics.
#
diff --git a/app/views/reports/_breakdown_table.html.erb b/app/views/reports/_breakdown_table.html.erb
index bb283ec7f8..b783e56e32 100644
--- a/app/views/reports/_breakdown_table.html.erb
+++ b/app/views/reports/_breakdown_table.html.erb
@@ -1,5 +1,5 @@
<%# Renders a breakdown table for income or expense groups %>
-<%# Local variables: groups, total, type (:income or :expense), amount_sort_params, current_sort_by, current_sort_direction, start_date, end_date %>
+<%# Local variables: groups, total, type (:income or :expense), amount_sort_params, current_sort_by, current_sort_direction, start_date, end_date, filter_tags %>
<%
color_class = type == :income ? "text-success" : "text-primary"
@@ -17,7 +17,7 @@
<%
rows = groups.flat_map do |group|
[ group.merge(level: :category), *Array(group[:subcategories]).map { |subcategory| subcategory.merge(level: :subcategory) } ]
- end.map { |item| item.merge(href: breakdown_transactions_path(item, start_date, end_date)) }
+ end.map { |item| item.merge(href: breakdown_transactions_path(item, start_date, end_date, tags: local_assigns[:filter_tags] || [])) }
amount_header = link_to reports_path(amount_sort_params), class: "inline-flex items-center gap-1 hover:text-primary" do
concat t("reports.transactions_breakdown.table.amount")
concat icon(current_sort_direction == "desc" ? "chevron-down" : "chevron-up", class: "w-3 h-3") if current_sort_by == "amount"
diff --git a/app/views/reports/_period_picker.html.erb b/app/views/reports/_period_picker.html.erb
index f5937f8aac..5d13a9a046 100644
--- a/app/views/reports/_period_picker.html.erb
+++ b/app/views/reports/_period_picker.html.erb
@@ -8,7 +8,7 @@
<%= render DS::Link.new(
variant: "icon",
icon: "chevron-left",
- href: picker_reports_path(period_type: :monthly, start_date: start_date.beginning_of_year - 1.year),
+ href: picker_reports_path(period_type: :monthly, start_date: start_date.beginning_of_year - 1.year, **reports_filter_params),
aria: { label: t("reports.index.previous_year") },
frame: "reports_picker"
) %>
@@ -22,7 +22,7 @@
<%= render DS::Link.new(
variant: "icon",
icon: "chevron-right",
- href: picker_reports_path(period_type: :monthly, start_date: next_year_start),
+ href: picker_reports_path(period_type: :monthly, start_date: next_year_start, **reports_filter_params),
aria: { label: t("reports.index.next_year") },
frame: "reports_picker"
) %>
@@ -41,7 +41,7 @@
<%= render DS::Link.new(
variant: date.month == start_date.month ? "secondary" : "ghost",
text: month_name,
- href: reports_path(period_type: :monthly, start_date: date, end_date: date.end_of_month),
+ href: reports_path(period_type: :monthly, start_date: date, end_date: date.end_of_month, **reports_filter_params),
full_width: true,
frame: :_top
) %>
@@ -56,7 +56,7 @@
<%= render DS::Link.new(
variant: "icon",
icon: "chevron-left",
- href: picker_reports_path(period_type: :quarterly, start_date: Date.new(start_date.year - 1, 1, 1)),
+ href: picker_reports_path(period_type: :quarterly, start_date: Date.new(start_date.year - 1, 1, 1), **reports_filter_params),
aria: { label: t("reports.index.previous_year") },
frame: "reports_picker"
) %>
@@ -70,7 +70,7 @@
<%= render DS::Link.new(
variant: "icon",
icon: "chevron-right",
- href: picker_reports_path(period_type: :quarterly, start_date: next_year_start),
+ href: picker_reports_path(period_type: :quarterly, start_date: next_year_start, **reports_filter_params),
aria: { label: t("reports.index.next_year") },
frame: "reports_picker"
) %>
@@ -89,7 +89,7 @@
<%= render DS::Link.new(
variant: quarter_start.quarter == start_date.quarter && start_date.year == quarter_start.year ? "secondary" : "ghost",
text: t("reports.index.period_picker.quarter", quarter: q, year: start_date.year),
- href: reports_path(period_type: :quarterly, start_date: quarter_start, end_date: quarter_end),
+ href: reports_path(period_type: :quarterly, start_date: quarter_start, end_date: quarter_end, **reports_filter_params),
full_width: true,
frame: :_top
) %>
@@ -107,7 +107,7 @@
<%= render DS::Link.new(
variant: "icon",
icon: "chevron-left",
- href: picker_reports_path(period_type: :ytd, start_date: Date.new(decade_start - 1, 1, 1)),
+ href: picker_reports_path(period_type: :ytd, start_date: Date.new(decade_start - 1, 1, 1), **reports_filter_params),
aria: { label: t("reports.index.previous_decade") },
frame: "reports_picker"
) %>
@@ -120,7 +120,7 @@
<%= render DS::Link.new(
variant: "icon",
icon: "chevron-right",
- href: picker_reports_path(period_type: :ytd, start_date: Date.new(decade_start + 10, 1, 1)),
+ href: picker_reports_path(period_type: :ytd, start_date: Date.new(decade_start + 10, 1, 1), **reports_filter_params),
aria: { label: t("reports.index.next_decade") },
frame: "reports_picker"
) %>
@@ -139,7 +139,7 @@
<%= render DS::Link.new(
variant: year == start_date.year ? "secondary" : "ghost",
text: year == Date.current.year ? t("reports.index.period_picker.ytd", year: year) : year.to_s,
- href: reports_path(period_type: :ytd, start_date: year_start, end_date: year_end),
+ href: reports_path(period_type: :ytd, start_date: year_start, end_date: year_end, **reports_filter_params),
full_width: true,
frame: :_top
) %>
diff --git a/app/views/reports/_transactions_breakdown.html.erb b/app/views/reports/_transactions_breakdown.html.erb
index e90194f20c..2ce774bda9 100644
--- a/app/views/reports/_transactions_breakdown.html.erb
+++ b/app/views/reports/_transactions_breakdown.html.erb
@@ -1,3 +1,4 @@
+<%# locals: (transactions:, period_type:, start_date:, end_date:, filter_tags:) %>
<div>
<%# Export Controls %>
<div class="flex items-center justify-end mb-4 flex-wrap gap-3">
@@ -8,7 +9,8 @@
start_date: start_date,
end_date: end_date,
sort_by: params[:sort_by],
- sort_direction: params[:sort_direction]
+ sort_direction: params[:sort_direction],
+ filter_tag_ids: filter_tags.map(&:id).presence
}.compact
%>
@@ -61,7 +63,8 @@
current_sort_by: current_sort_by,
current_sort_direction: current_sort_direction,
start_date: start_date,
- end_date: end_date %>
+ end_date: end_date,
+ filter_tags: filter_tags %>
<% end %>
<%# Expenses Section %>
@@ -74,7 +77,8 @@
current_sort_by: current_sort_by,
current_sort_direction: current_sort_direction,
start_date: start_date,
- end_date: end_date %>
+ end_date: end_date,
+ filter_tags: filter_tags %>
<% end %>
</div>
diff --git a/app/views/reports/index.html.erb b/app/views/reports/index.html.erb
index d70a870dba..8bc44ebd1e 100644
--- a/app/views/reports/index.html.erb
+++ b/app/views/reports/index.html.erb
@@ -18,7 +18,7 @@
<% end %>
<%# Print Report Button %>
- <%= link_to print_reports_path(period_type: @period_type, start_date: @start_date, end_date: @end_date),
+ <%= link_to print_reports_path(period_type: @period_type, start_date: @start_date, end_date: @end_date, **reports_filter_params),
target: "_blank",
rel: "noopener",
aria: { label: t("reports.index.print_report") },
@@ -29,21 +29,48 @@
</header>
<%# Period Navigation Tabs %>
- <div class="flex items-center justify-between gap-4">
- <%= render DS::SegmentedControl.new(aria_label: t("reports.index.period_aria", default: "Report period"), class: "overflow-x-auto no-scrollbar") do |sc| %>
+ <div class="flex flex-wrap items-center justify-between gap-4">
+ <%= render DS::SegmentedControl.new(aria_label: t("reports.index.period_aria", default: "Report period"), class: "max-w-full overflow-x-auto no-scrollbar") do |sc| %>
<% %i[monthly quarterly ytd last_6_months custom].each do |ptype| %>
<% sc.with_segment(t("reports.index.periods.#{ptype}"),
active: @period_type == ptype,
- href: reports_path(period_type: ptype),
+ href: reports_path(period_type: ptype, **reports_filter_params),
class: "whitespace-nowrap") %>
<% end %>
<% end %>
+
+ <% if @tags.any? %>
+ <%= render layout: "pages/dashboard/filter_popover", locals: {
+ button_text: @filter_tags.empty? ? t("reports.index.tag_filter.all") : t("reports.index.tag_filter.selected", count: @filter_tags.size),
+ search_label: t("reports.index.tag_filter.search"),
+ apply_text: t("reports.index.tag_filter.apply"),
+ hidden_fields: { period_type: @period_type, start_date: @start_date, end_date: @end_date },
+ url: reports_path,
+ form_data: { turbo_action: "advance" }
+ } do %>
+ <% @tags.each do |tag| %>
+ <%= render layout: "pages/dashboard/filter_popover_option", locals: {
+ name: "filter_tag_ids[]",
+ value: tag.id,
+ checked: @filter_tags.include?(tag),
+ filter_name: tag.name
+ } do %>
+ <%= render "tags/badge", tag: tag %>
+ <% end %>
+ <% end %>
+ <% end %>
+ <% end %>
</div>
<%# Custom Date Range Picker (only shown when custom is selected) %>
<% if @period_type == :custom %>
<%= form_with url: reports_path, method: :get, data: { controller: "auto-submit-form" }, class: "flex items-center gap-3 bg-surface-inset p-3 rounded-lg" do |f| %>
<%= f.hidden_field :period_type, value: :custom %>
+ <% reports_filter_params.each do |key, values| %>
+ <% Array(values).each do |value| %>
+ <%= hidden_field_tag "#{key}[]", value, id: nil %>
+ <% end %>
+ <% end %>
<div class="flex items-center gap-2">
<label class="text-sm font-medium text-secondary"><%= t("reports.index.date_range.from") %></label>
@@ -74,7 +101,7 @@
<%= render DS::Link.new(
variant: "icon",
icon: "chevron-left",
- href: reports_path(period_type: @period_type, start_date: @nav[:prev_start], end_date: @nav[:prev_end]),
+ href: reports_path(period_type: @period_type, start_date: @nav[:prev_start], end_date: @nav[:prev_end], **reports_filter_params),
aria: { label: t("reports.index.previous_period"), keyshortcuts: "ArrowLeft" },
data: { controller: "hotkey", hotkey: "ArrowLeft" },
) %>
@@ -91,7 +118,7 @@
<%= render DS::Link.new(
variant: "icon",
icon: "chevron-right",
- href: reports_path(period_type: @period_type, start_date: @nav[:next_start], end_date: @nav[:next_end]),
+ href: reports_path(period_type: @period_type, start_date: @nav[:next_start], end_date: @nav[:next_end], **reports_filter_params),
aria: { label: t("reports.index.next_period"), keyshortcuts: "ArrowRight" },
data: { controller: "hotkey", hotkey: "ArrowRight" },
) %>
@@ -119,7 +146,7 @@
<%= render DS::Link.new(
text: t("reports.index.today"),
variant: "outline",
- href: reports_path(period_type: @period_type),
+ href: reports_path(period_type: @period_type, **reports_filter_params),
) %>
</div>
</div>
diff --git a/config/locales/views/reports/en.yml b/config/locales/views/reports/en.yml
index 05f5445002..10c4c266b8 100644
--- a/config/locales/views/reports/en.yml
+++ b/config/locales/views/reports/en.yml
@@ -6,6 +6,13 @@ en:
subtitle: Comprehensive insights into your financial health
export: Export CSV
print_report: Print Report
+ tag_filter:
+ all: All tags
+ selected:
+ one: "%{count} tag"
+ other: "%{count} tags"
+ search: Search tags
+ apply: Apply
section_aria: "%{title} section. Press Enter or Space to grab for reordering, then use arrow keys to move."
sections_aria: Reports sections
periods:
diff --git a/test/controllers/reports_controller_test.rb b/test/controllers/reports_controller_test.rb
index 47cfc6121e..e76c5b722a 100644
--- a/test/controllers/reports_controller_test.rb
+++ b/test/controllers/reports_controller_test.rb
@@ -4,6 +4,8 @@ class ReportsControllerTest < ActionDispatch::IntegrationTest
include EntriesTestHelper
include SqlQueryCapture
+ TAGGED_MONTH = Date.new(2021, 3, 1)
+
setup do
sign_in @user = users(:family_admin)
@family = @user.family
@@ -1188,7 +1190,157 @@ class ReportsControllerTest < ActionDispatch::IntegrationTest
assert_select "form[action=?]", settings_api_keys_path, count: 0
end
+ test "google sheets instructions give an export URL with the selected tags" do
+ tag = @family.tags.create!(name: "Sheets tag")
+
+ get google_sheets_instructions_reports_url(period_type: :monthly, filter_tag_ids: [ tag.id ])
+
+ assert_response :success
+ assert_includes CGI.unescapeHTML(@response.body), export_transactions_reports_url(period_type: :monthly, filter_tag_ids: [ tag.id ], format: :csv)
+ end
+
+ test "the tag filter limits the summary, trends and breakdown to transactions with any of the tags" do
+ travel, work = seed_tagged_month
+
+ get reports_path(period_type: :monthly, start_date: TAGGED_MONTH, end_date: TAGGED_MONTH.end_of_month,
+ filter_tag_ids: [ travel.id, work.id ])
+
+ assert_response :ok
+ # $30 travel + $50 work + $20 carrying both, counted once; the $1,000
+ # "Other" expense and the untagged $500 salary are left out.
+ assert_equal "$10.00", summary_value(I18n.t("reports.summary.total_income"))
+ assert_equal "$100.00", summary_value(I18n.t("reports.summary.total_expenses"))
+ assert_select "[data-section-key=trends_insights] tbody tr", count: 1 do
+ assert_select "td", text: "$10.00"
+ assert_select "td", text: "$100.00"
+ end
+ breakdown = css_select("[data-section-key=transactions_breakdown]").text.squish
+ assert_includes breakdown, "#{I18n.t("reports.transactions_breakdown.table.income")}: $10.00"
+ assert_includes breakdown, "#{I18n.t("reports.transactions_breakdown.table.expense")}: $100.00"
+ end
+
+ test "without a tag filter every transaction is counted" do
+ seed_tagged_month
+
+ get reports_path(period_type: :monthly, start_date: TAGGED_MONTH, end_date: TAGGED_MONTH.end_of_month)
+
+ assert_response :ok
+ assert_equal "$510.00", summary_value(I18n.t("reports.summary.total_income"))
+ assert_equal "$1,100.00", summary_value(I18n.t("reports.summary.total_expenses"))
+ end
+
+ test "the tag filter leaves trades out of the breakdown" do
+ tag = @family.tags.create!(name: "Filtered tag")
+ create_transaction(account: accounts(:depository), name: "Tagged spend", amount: 42, tags: [ tag ])
+ create_trade(securities(:aapl), account: accounts(:investment), qty: 1, date: Date.current, price: 100)
+
+ get reports_path(period_type: :monthly, filter_tag_ids: [ tag.id ])
+
+ assert_response :ok
+ assert_select "[data-section-key=transactions_breakdown] tr[data-category]", count: 1
+ assert_select "tr[data-category='category-uncategorized']", text: /\$42\.00/
+ assert_select "tr[data-category='category-other_investments']", count: 0
+ end
+
+ test "tag ids that are not the family's are ignored" do
+ seed_tagged_month
+ foreign_tag = families(:empty).tags.create!(name: "Someone else's")
+
+ get reports_path(period_type: :monthly, start_date: TAGGED_MONTH, end_date: TAGGED_MONTH.end_of_month,
+ filter_tag_ids: [ foreign_tag.id, "not-a-uuid" ])
+
+ assert_response :ok
+ assert_equal "$1,100.00", summary_value(I18n.t("reports.summary.total_expenses"))
+ assert_select "button", text: I18n.t("reports.index.tag_filter.all")
+ assert_select "input[name='filter_tag_ids[]'][checked]", count: 0
+ end
+
+ test "the tag filter lists the family's tags and checks the selected ones" do
+ travel, work, other = seed_tagged_month
+
+ get reports_path(period_type: :monthly, filter_tag_ids: [ travel.id, work.id ])
+
+ assert_response :ok
+ assert_select "button", text: I18n.t("reports.index.tag_filter.selected", count: 2)
+ assert_select "input[name='filter_tag_ids[]'][value=?][checked]", travel.id
+ assert_select "input[name='filter_tag_ids[]'][value=?][checked]", work.id
+ assert_select "input[name='filter_tag_ids[]'][value=?]:not([checked])", other.id
+ end
+
+ test "period controls keep the tag filter" do
+ travel, = seed_tagged_month
+
+ get reports_path(period_type: :monthly, start_date: TAGGED_MONTH, end_date: TAGGED_MONTH.end_of_month,
+ filter_tag_ids: [ travel.id ])
+
+ assert_response :ok
+ report_links = css_select("a[href^='/reports?']").map { |link| link["href"] }
+ assert_operator report_links.size, :>, 5
+ report_links.each { |href| assert_includes CGI.unescape(href), "filter_tag_ids[]=#{travel.id}", href }
+
+ get reports_path(period_type: :custom, filter_tag_ids: [ travel.id ])
+
+ assert_select "form[action='#{reports_path}'] input[type=date][name=start_date]" do |inputs|
+ form = inputs.first.ancestors("form").first
+ assert form.at_css("input[type=hidden][name='filter_tag_ids[]'][value='#{travel.id}']"), "custom range form drops the tag filter"
+ end
+ end
+
+ test "breakdown rows link to transactions filtered by category and the selected tags" do
+ tag = @family.tags.create!(name: "Linked tag")
+ category = @family.categories.create!(name: "Tagged groceries", color: "#ABCDEF")
+ create_transaction(account: accounts(:depository), name: "Groceries", amount: 42, category: category, tags: [ tag ])
+ start_date = Date.current.beginning_of_month
+ end_date = Date.current.end_of_month
+
+ get reports_path(period_type: :monthly, start_date: start_date, end_date: end_date, filter_tag_ids: [ tag.id ])
+
+ href = transactions_path(q: { categories: [ category.name ], start_date: start_date, end_date: end_date, tags: [ tag.name ] })
+ assert_select "tr[data-category='category-#{category.id}'] a[href=?]", href
+ end
+
+ test "export transactions keeps only the selected tags" do
+ tag = @family.tags.create!(name: "Export tag")
+ tagged = @family.categories.create!(name: "Export Tagged Spend", color: "#111111")
+ untagged = @family.categories.create!(name: "Export Untagged Spend", color: "#222222")
+ create_transaction(account: accounts(:depository), name: "Tagged", amount: 10, category: tagged, tags: [ tag ])
+ create_transaction(account: accounts(:depository), name: "Untagged", amount: 20, category: untagged)
+
+ get export_transactions_reports_path(format: :csv, period_type: :monthly, start_date: Date.current.beginning_of_month,
+ end_date: Date.current.end_of_month, filter_tag_ids: [ tag.id ])
+
+ assert_response :ok
+ assert_match(/Export Tagged Spend/, @response.body)
+ assert_no_match(/Export Untagged Spend/, @response.body)
+ end
+
private
+ # Travel, Work and Other tags on a month of their own, away from the
+ # fixture transactions, with expenses of $30 (travel), $50 (work), $20
+ # (both) and $1,000 (other), and income of $10 (travel) and $500 (none).
+ def seed_tagged_month
+ travel = @family.tags.create!(name: "Travel")
+ work = @family.tags.create!(name: "Work")
+ other = @family.tags.create!(name: "Other")
+ account = accounts(:depository)
+ date = TAGGED_MONTH + 9.days
+
+ create_transaction(account: account, date: date, name: "Hotel", amount: 30, tags: [ travel ])
+ create_transaction(account: account, date: date, name: "Laptop stand", amount: 50, tags: [ work ])
+ create_transaction(account: account, date: date, name: "Airport lunch", amount: 20, tags: [ travel, work ])
+ create_transaction(account: account, date: date, name: "Rent", amount: 1000, tags: [ other ])
+ create_transaction(account: account, date: date, name: "Refund", amount: -10, tags: [ travel ])
+ create_transaction(account: account, date: date, name: "Salary", amount: -500)
+
+ [ travel, work, other ]
+ end
+
+ # The figure on the summary card headed by label.
+ def summary_value(label)
+ heading = css_select("h3").find { |node| node.text.strip == label }
+ heading.ancestors("div.bg-container").first.at_css("p.text-2xl").text.strip
+ end
+
# Takes every fixture investment account out of the card's scope, so an
# account the test creates is the family's only one; otherwise the
# fixtures satisfy the visible-accounts gate on their own.
diff --git a/test/models/family_test.rb b/test/models/family_test.rb
index 0833f780d3..cabd4f5378 100644
--- a/test/models/family_test.rb
+++ b/test/models/family_test.rb
@@ -241,6 +241,19 @@ class FamilyTest < ActiveSupport::TestCase
assert_equal "Groups", family.moniker_label_plural
end
+ test "tags_version changes when tags are added, removed, merged or deleted" do
+ family = families(:dylan_family)
+ tag = family.tags.create!(name: "Version tag")
+ other = family.tags.create!(name: "Other version tag")
+ transaction = family.transactions.first
+
+ assert_tags_version_changes(family) { transaction.toggle_tag!(tag) }
+ assert_tags_version_changes(family) { transaction.toggle_tag!(tag) }
+ assert_tags_version_changes(family) { transaction.toggle_tag!(other) }
+ assert_tags_version_changes(family) { other.replace_and_destroy!(tag) }
+ assert_tags_version_changes(family) { tag.destroy! }
+ end
+
test "entries_cache_version changes when an older entry is destroyed" do
family = families(:dylan_family)
newer_entry = entries(:transaction)
@@ -923,6 +936,12 @@ class FamilyTest < ActiveSupport::TestCase
end
private
+ def assert_tags_version_changes(family)
+ before = family.tags_version
+ yield
+ assert_not_equal before, family.reload.tags_version
+ end
+
def set_preview_features(user, enabled)
user.update!(preferences: (user.preferences || {}).merge("preview_features_enabled" => enabled))
end
diff --git a/test/models/income_statement_test.rb b/test/models/income_statement_test.rb
index 4d56505313..89f0912f4a 100644
--- a/test/models/income_statement_test.rb
+++ b/test/models/income_statement_test.rb
@@ -282,6 +282,43 @@ class IncomeStatementTest < ActiveSupport::TestCase
assert_equal Money.new(200, @family.currency), checking_only_totals.expense_money
end
+ test "totals_for limits totals to transactions carrying any of the tag ids" do
+ travel = @family.tags.create!(name: "Travel")
+ work = @family.tags.create!(name: "Work")
+ create_transaction(account: @checking_account, amount: 30, category: @food_category, tags: [ travel ])
+ create_transaction(account: @checking_account, amount: 50, category: @food_category, tags: [ work ])
+ create_transaction(account: @checking_account, amount: 20, category: @food_category, tags: [ travel, work ])
+ create_transaction(account: @checking_account, amount: -10, category: @income_category, tags: [ travel ])
+
+ totals = IncomeStatement.new(@family).totals_for(Period.last_30_days, tag_ids: [ travel.id, work.id ])
+
+ assert_equal Money.new(10, @family.currency), totals.income_money
+ assert_equal Money.new(30 + 50 + 20, @family.currency), totals.expense_money
+ assert_equal 4, totals.transactions_count
+ end
+
+ test "cached tagged totals follow tag changes that do not touch entries" do
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ period = Period.last_30_days
+ travel = @family.tags.create!(name: "Travel")
+ trip = @family.tags.create!(name: "Trip")
+ create_transaction(account: @checking_account, amount: 30, category: @food_category, tags: [ travel ])
+ toggled = create_transaction(account: @checking_account, amount: 50, category: @food_category).transaction
+ create_transaction(account: @checking_account, amount: 20, category: @food_category, tags: [ trip ])
+ expenses = -> { IncomeStatement.new(@family).totals_for(period, tag_ids: [ travel.id ]).expense_money }
+
+ assert_equal Money.new(30, @family.currency), expenses.call
+
+ toggled.toggle_tag!(travel)
+ assert_equal Money.new(80, @family.currency), expenses.call
+
+ trip.replace_and_destroy!(travel)
+ assert_equal Money.new(100, @family.currency), expenses.call
+
+ toggled.toggle_tag!(travel)
+ assert_equal Money.new(50, @family.currency), expenses.call
+ end
+
test "eligible_accounts excludes accounts not reflected in totals" do
tax_advantaged_account = @family.accounts.create! name: "401k", currency: @family.currency, balance: 10000, accountable: Investment.new(subtype: "401k")
excluded_account = @family.accounts.create! name: "Excluded", currency: @family.currency, balance: 0, exclude_from_reports: true, accountable: Depository.new
diff --git a/test/models/transaction_test.rb b/test/models/transaction_test.rb
index bd25cc9d93..6b950d3b6d 100644
--- a/test/models/transaction_test.rb
+++ b/test/models/transaction_test.rb
@@ -3,6 +3,19 @@ require "test_helper"
class TransactionTest < ActiveSupport::TestCase
include EntriesTestHelper
+ test "with_any_tag returns transactions carrying any of the tags, each once" do
+ travel = families(:dylan_family).tags.create!(name: "Travel")
+ work = families(:dylan_family).tags.create!(name: "Work")
+ other = families(:dylan_family).tags.create!(name: "Other")
+ hotel = create_transaction(name: "Hotel", tags: [ travel ]).transaction
+ laptop = create_transaction(name: "Laptop", tags: [ work ]).transaction
+ lunch = create_transaction(name: "Airport lunch", tags: [ travel, work ]).transaction
+ create_transaction(name: "Rent", tags: [ other ])
+ create_transaction(name: "Untagged")
+
+ assert_equal [ hotel, laptop, lunch ].map(&:id).sort, Transaction.with_any_tag([ travel.id, work.id ]).pluck(:id).sort
+ end
+
test "pending? is true when extra.simplefin.pending is truthy" do
transaction = Transaction.new(extra: { "simplefin" => { "pending" => true } })