Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Allow uploading a logo for family merchants (#4511)

Dov Benyomin Sohacheski8726dce04f29
diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rb
index 18b1538f27..a3e3e82c6b 100644
--- a/app/controllers/accounts_controller.rb
+++ b/app/controllers/accounts_controller.rb
@@ -143,7 +143,7 @@ class AccountsController < ApplicationController
if transactions.any?
ActiveRecord::Associations::Preloader.new(
records: transactions,
- associations: [ :transfer_as_inflow, :transfer_as_outflow, :category, :merchant, :tags ]
+ associations: [ :transfer_as_inflow, :transfer_as_outflow, :category, { merchant: { logo_attachment: :blob } }, :tags ]
).call
end
@@ -165,7 +165,7 @@ class AccountsController < ApplicationController
split_parent_ids = @entries.filter_map(&:parent_entry_id).uniq
if split_parent_ids.any?
Entry.where(id: split_parent_ids)
- .includes(:account, entryable: [ :category, :merchant ])
+ .includes(:account, entryable: [ :category, { merchant: { logo_attachment: :blob } } ])
.index_by(&:id)
else
{}
diff --git a/app/controllers/bills_controller.rb b/app/controllers/bills_controller.rb
index 2c11af7f8a..cce0c2b85a 100644
--- a/app/controllers/bills_controller.rb
+++ b/app/controllers/bills_controller.rb
@@ -89,7 +89,7 @@ class BillsController < ApplicationController
# work, so the strip lives on this page as well as in Settings.
# Loaded once: the view asks any?/none? and the partial counts and
# iterates, which would otherwise be separate queries.
- @suggested_series = accessible_suggested_series.includes(:merchant).order(next_expected_date: :asc).load
+ @suggested_series = accessible_suggested_series.includes(merchant: { logo_attachment: :blob }).order(next_expected_date: :asc).load
@has_transaction_history = Current.family.entries.where(entryable_type: "Transaction").exists?
@suggested_allocations = suggested_allocations(open_occurrences + @paid_this_month)
# A row waiting on a match decision offers Review rather than Find.
@@ -144,7 +144,7 @@ class BillsController < ApplicationController
def show
@series = Current.family.recurring_transactions
.accessible_by(Current.user)
- .includes(:merchant)
+ .includes(merchant: { logo_attachment: :blob })
.find(params[:id])
# Outside a frame (a new tab, a pasted link, a notification) there is
@@ -289,7 +289,7 @@ class BillsController < ApplicationController
def load_all_series
scope = Current.family.recurring_transactions
.accessible_by(Current.user)
- .includes(:merchant)
+ .includes(merchant: { logo_attachment: :blob })
if (search = params.dig(:q, :search)).present?
pattern = "%#{ActiveRecord::Base.sanitize_sql_like(search)}%"
@@ -431,7 +431,7 @@ class BillsController < ApplicationController
occurrences = Current.family.recurring_occurrences
.where(recurring_transaction_id: payable_series_ids)
.due_between(@grid_start, @grid_end)
- .includes(recurring_transaction: :merchant)
+ .includes(recurring_transaction: { merchant: { logo_attachment: :blob } })
.to_a
preload_allocation_sums(occurrences)
@@ -486,7 +486,7 @@ class BillsController < ApplicationController
.where(recurring_transaction_id: payable_series_ids)
.where("#{RecurringOccurrence::EFFECTIVE_DUE_ON_SQL} >= ? OR status = 'scheduled'", Date.current.beginning_of_month)
.where("due_on <= ?", Date.current + 90)
- .includes(recurring_transaction: [ :merchant, :recurring_price_changes, :recurrence_rules ])
+ .includes(recurring_transaction: [ { merchant: { logo_attachment: :blob } }, :recurring_price_changes, :recurrence_rules ])
.to_a
end
@@ -646,7 +646,7 @@ class BillsController < ApplicationController
# Income never reviews here: the matcher no longer suggests it, and
# this filter also retires any suggestion written before that rule.
.merge(RecurringTransaction.not_typed_income)
- .includes(:entry, recurring_occurrence: { recurring_transaction: :merchant })
+ .includes(:entry, recurring_occurrence: { recurring_transaction: { merchant: { logo_attachment: :blob } } })
# The confidence the matcher scored these with was sitting unused on
# the row while the queue ordered itself by when the job happened to
# run. Most-certain question first.
diff --git a/app/controllers/family_merchants_controller.rb b/app/controllers/family_merchants_controller.rb
index 7d2fe3590e..14519dd8af 100644
--- a/app/controllers/family_merchants_controller.rb
+++ b/app/controllers/family_merchants_controller.rb
@@ -31,7 +31,7 @@ class FamilyMerchantsController < ApplicationController
@enhanceable_count = @all_provider_merchants.where(website_url: [ nil, "" ]).count
@llm_available = Provider::Registry.get_provider(:openai).present?
- @pagy_family_merchants, @family_merchants = pagy(family_scope, page_param: :family_page, limit: safe_per_page)
+ @pagy_family_merchants, @family_merchants = pagy(family_scope.with_attached_logo, page_param: :family_page, limit: safe_per_page)
@pagy_provider_merchants, @provider_merchants = pagy(provider_scope, page_param: :provider_page, limit: safe_per_page)
render layout: "settings"
@@ -123,7 +123,7 @@ class FamilyMerchantsController < ApplicationController
end
def merge
- @merchants = all_family_merchants
+ @merchants = all_family_merchants.with_attached_logo
end
def perform_merge
@@ -174,7 +174,7 @@ class FamilyMerchantsController < ApplicationController
def merchant_params
# Handle both family_merchant and provider_merchant param keys
key = params.key?(:family_merchant) ? :family_merchant : :provider_merchant
- params.require(key).permit(:name, :color, :website_url)
+ params.require(key).permit(:name, :color, :website_url, :logo, :remove_logo)
end
def merchant_json(merchant)
diff --git a/app/controllers/splits_controller.rb b/app/controllers/splits_controller.rb
index 9966c96ea2..d2cf5f3978 100644
--- a/app/controllers/splits_controller.rb
+++ b/app/controllers/splits_controller.rb
@@ -97,7 +97,7 @@ class SplitsController < ApplicationController
def set_form_options
@categories = grouped_categories
- @merchants = Current.family.available_merchants_for(Current.user).alphabetically
+ @merchants = Current.family.available_merchants_for(Current.user).with_attached_logo.alphabetically
@tags = Current.family.tags.alphabetically
end
diff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rb
index b2ae330d0f..9ddb811c97 100644
--- a/app/controllers/transactions_controller.rb
+++ b/app/controllers/transactions_controller.rb
@@ -28,7 +28,7 @@ class TransactionsController < ApplicationController
.reverse_chronological
.includes(
{ entry: :account },
- :category, :merchant, :tags,
+ :category, { merchant: { logo_attachment: :blob } }, :tags,
# Union of #2643 counterpart UI + Skylight category-menu N+1:
# - outflow rows need inflow_transaction (to_account) for both
# counterpart display and Transfer#categorizable?/#payment?
@@ -62,7 +62,7 @@ class TransactionsController < ApplicationController
split_parent_ids = @transactions.filter_map { |t| t.entry.parent_entry_id }.uniq
if split_parent_ids.any?
Entry.where(id: split_parent_ids)
- .includes(:account, entryable: [ :category, :merchant ])
+ .includes(:account, entryable: [ :category, { merchant: { logo_attachment: :blob } } ])
.index_by(&:id)
else
{}
@@ -96,7 +96,7 @@ class TransactionsController < ApplicationController
[]
else
Current.family.recurring_transactions.accessible_by(Current.user)
- .where(id: projected_recurring_ids).includes(:merchant).to_a
+ .where(id: projected_recurring_ids).includes(merchant: { logo_attachment: :blob }).to_a
end
@breadcrumbs = [ [ t("breadcrumbs.home"), root_path ], [ t("breadcrumbs.transactions"), nil ] ]
@@ -725,7 +725,7 @@ class TransactionsController < ApplicationController
.includes(:account_providers, logo_attachment: :blob)
.to_a
@categories = Current.family.categories.alphabetically_by_hierarchy.to_a
- @merchants = Current.family.available_merchants_for(Current.user).alphabetically.to_a
+ @merchants = Current.family.available_merchants_for(Current.user).with_attached_logo.alphabetically.to_a
@tags = Current.family.tags.alphabetically.to_a
end
diff --git a/app/models/family_merchant.rb b/app/models/family_merchant.rb
index cd11a7b60e..ef831a5a4c 100644
--- a/app/models/family_merchant.rb
+++ b/app/models/family_merchant.rb
@@ -1,13 +1,19 @@
class FamilyMerchant < Merchant
COLORS = %w[#e99537 #4da568 #6471eb #db5a54 #df4e92 #c44fe9 #eb5429 #61c9ea #805dee #6ad28a]
+ LOGO_CONTENT_TYPES = %w[image/jpeg image/png image/webp].freeze
+ LOGO_MAX_SIZE = 5.megabytes
belongs_to :family
+ attribute :remove_logo, :boolean, default: false
+
before_validation :set_default_color
before_save :generate_logo_url_from_website, if: :should_generate_logo?
+ after_save :purge_logo, if: -> { remove_logo && !attachment_changes.key?("logo") }
validates :color, presence: true, format: { with: /\A#[0-9A-Fa-f]{6}\z/ }
validates :name, uniqueness: { scope: :family }
+ validate :logo_is_small_image, if: -> { logo.attached? }
# Reuses a family's existing merchant of this name instead of raising on the
# uniqueness validation, and survives a concurrent create for the same name
@@ -29,7 +35,28 @@ class FamilyMerchant < Merchant
end
end
+ def logo_url
+ return super unless logo.attached?
+
+ Rails.application.routes.url_helpers.rails_representation_path(logo.variant(:small), only_path: true)
+ end
+
private
+ def purge_logo
+ self.logo_attachment = nil
+ self.remove_logo = false
+ end
+
+ def logo_is_small_image
+ unless logo.content_type.in?(LOGO_CONTENT_TYPES)
+ errors.add(:logo, :invalid_content_type)
+ end
+
+ if logo.byte_size > LOGO_MAX_SIZE
+ errors.add(:logo, :invalid_file_size, max_megabytes: LOGO_MAX_SIZE / 1.megabyte)
+ end
+ end
+
def set_default_color
self.color = COLORS.sample unless valid_hex_color?
end
@@ -39,7 +66,7 @@ class FamilyMerchant < Merchant
end
def should_generate_logo?
- website_url_changed? || (website_url.present? && logo_url.blank?)
+ website_url_changed? || (website_url.present? && self[:logo_url].blank?)
end
def generate_logo_url_from_website
diff --git a/app/models/merchant.rb b/app/models/merchant.rb
index ab6f2bed31..1d3091a837 100644
--- a/app/models/merchant.rb
+++ b/app/models/merchant.rb
@@ -12,6 +12,11 @@ class Merchant < ApplicationRecord
has_many :transactions, dependent: :nullify
has_many :recurring_transactions, dependent: :destroy
+ # Declared here rather than on FamilyMerchant so lists mixing both types can preload it.
+ has_one_attached :logo, dependent: :purge_later do |attachable|
+ attachable.variant :small, resize_to_fill: [ 128, 128 ], convert: :webp, saver: { quality: 80 }, preprocessed: true
+ end
+
validates :name, presence: true
validates :name, exclusion: { in: [ NO_MERCHANT_FILTER_VALUE ] }
validates :type, inclusion: { in: TYPES }
diff --git a/app/views/family_merchants/_form.html.erb b/app/views/family_merchants/_form.html.erb
index 8e885b08c4..bcaaaba952 100644
--- a/app/views/family_merchants/_form.html.erb
+++ b/app/views/family_merchants/_form.html.erb
@@ -25,6 +25,24 @@
<%= f.text_field :website_url, placeholder: t(".website_placeholder") %>
</div>
<p class="text-xs text-subdued"><%= t(".website_hint") %></p>
+
+ <% if family_merchant.is_a?(FamilyMerchant) %>
+ <% saved_logo = family_merchant.logo.attached? && family_merchant.logo.persisted? %>
+ <div class="flex items-center gap-3">
+ <% if saved_logo %>
+ <%= image_tag family_merchant.logo_url, class: "w-10 h-10 rounded-full shrink-0", alt: "" %>
+ <% end %>
+ <%= f.file_field :logo, label: t(".logo_label"), accept: FamilyMerchant::LOGO_CONTENT_TYPES.join(","), container_class: "flex-1" %>
+ </div>
+ <p class="text-xs text-subdued"><%= t(".logo_hint", max_megabytes: FamilyMerchant::LOGO_MAX_SIZE / 1.megabyte) %></p>
+
+ <% if saved_logo %>
+ <div class="flex items-center justify-between gap-4">
+ <span id="remove_logo_label" class="text-sm text-primary"><%= t(".remove_logo_label") %></span>
+ <%= f.toggle :remove_logo, "aria-labelledby": "remove_logo_label" %>
+ </div>
+ <% end %>
+ <% end %>
</section>
<section>
diff --git a/app/views/transactions/searches/filters/_merchant_filter.html.erb b/app/views/transactions/searches/filters/_merchant_filter.html.erb
index bbf2a40e1f..ad143bb4ab 100644
--- a/app/views/transactions/searches/filters/_merchant_filter.html.erb
+++ b/app/views/transactions/searches/filters/_merchant_filter.html.erb
@@ -10,7 +10,7 @@
}
) %>
<div class="my-2" id="list" data-list-filter-target="list">
- <% ([ Merchant.no_merchant ] + Current.family.assigned_merchants_for(Current.user).alphabetically).each do |merchant| %>
+ <% ([ Merchant.no_merchant ] + Current.family.assigned_merchants_for(Current.user).with_attached_logo.alphabetically).each do |merchant| %>
<div class="filterable-item flex items-center gap-2 p-2" data-filter-name="<%= merchant.name %>">
<%= form.check_box :merchants,
{
diff --git a/app/views/transactions/show.html.erb b/app/views/transactions/show.html.erb
index 09e0feb3c7..d3b15eee74 100644
--- a/app/views/transactions/show.html.erb
+++ b/app/views/transactions/show.html.erb
@@ -133,7 +133,7 @@
<%= render DS::MerchantSelect.new(
form: ef,
method: :merchant_id,
- merchants: Current.family.available_merchants_for(Current.user).alphabetically,
+ merchants: Current.family.available_merchants_for(Current.user).with_attached_logo.alphabetically,
selected_id: ef.object.merchant_id,
include_blank: t(".none"),
label: t(".merchant_label"),
diff --git a/config/locales/models/merchant/en.yml b/config/locales/models/merchant/en.yml
index 12e51031c1..119fb49525 100644
--- a/config/locales/models/merchant/en.yml
+++ b/config/locales/models/merchant/en.yml
@@ -3,3 +3,11 @@ en:
models:
merchant:
no_merchant: No merchant
+ activerecord:
+ errors:
+ models:
+ family_merchant:
+ attributes:
+ logo:
+ invalid_content_type: must be a JPEG, PNG or WebP image
+ invalid_file_size: file size must be less than %{max_megabytes}MB
diff --git a/config/locales/views/merchants/en.yml b/config/locales/views/merchants/en.yml
index a65741b001..8d52abf570 100644
--- a/config/locales/views/merchants/en.yml
+++ b/config/locales/views/merchants/en.yml
@@ -13,6 +13,9 @@ en:
name_placeholder: Merchant name
website_placeholder: Website (e.g., starbucks.com)
website_hint: Enter the merchant's website to automatically display their logo
+ logo_label: Logo
+ logo_hint: Overrides the website logo. JPEG, PNG or WebP, up to %{max_megabytes}MB.
+ remove_logo_label: Remove uploaded logo
index:
empty: No merchants yet
new: New merchant
diff --git a/test/controllers/family_merchants_controller_test.rb b/test/controllers/family_merchants_controller_test.rb
index 4906cf2a05..68c0414367 100644
--- a/test/controllers/family_merchants_controller_test.rb
+++ b/test/controllers/family_merchants_controller_test.rb
@@ -79,6 +79,24 @@ class FamilyMerchantsControllerTest < ActionDispatch::IntegrationTest
assert_equal "#000000", @merchant.reload.color
end
+ test "should upload merchant logo" do
+ patch family_merchant_url(@merchant), params: {
+ family_merchant: { logo: file_fixture_upload("profile_image.png", "image/png", :binary) }
+ }
+
+ assert_redirected_to family_merchants_path
+ assert @merchant.reload.logo.attached?
+ end
+
+ test "should remove merchant logo" do
+ @merchant.logo.attach(io: file_fixture("profile_image.png").open, filename: "logo.png", content_type: "image/png")
+
+ patch family_merchant_url(@merchant), params: { family_merchant: { remove_logo: "1" } }
+
+ assert_redirected_to family_merchants_path
+ assert_not @merchant.reload.logo.attached?
+ end
+
test "should destroy merchant" do
assert_difference("FamilyMerchant.count", -1) do
delete family_merchant_url(@merchant)
diff --git a/test/integration/active_storage_authorization_test.rb b/test/integration/active_storage_authorization_test.rb
index 25db6db0f0..b316596d06 100644
--- a/test/integration/active_storage_authorization_test.rb
+++ b/test/integration/active_storage_authorization_test.rb
@@ -446,7 +446,7 @@ class ActiveStorageAuthorizationTest < ActionDispatch::IntegrationTest
test "every attachment is either access-checked or intentionally public" do
# Logos and avatars are not sensitive. Archived exports have no owning family;
# ArchivedExportsController releases them by download token.
- public_attachments = %w[User#profile_image ArchivedExport#export_file Account#logo]
+ public_attachments = %w[User#profile_image ArchivedExport#export_file Account#logo Merchant#logo]
Rails.application.eager_load!
unchecked = ActiveRecord::Base.descendants.reject(&:abstract_class?).flat_map do |model|
diff --git a/test/models/family_merchant_test.rb b/test/models/family_merchant_test.rb
index 823fae44c4..ddcfc50802 100644
--- a/test/models/family_merchant_test.rb
+++ b/test/models/family_merchant_test.rb
@@ -3,10 +3,49 @@
require "test_helper"
class FamilyMerchantTest < ActiveSupport::TestCase
+ include ActiveJob::TestHelper
+
setup do
@family = families(:dylan_family)
end
+ test "uploaded logo takes precedence over the website logo" do
+ merchant = FamilyMerchant.create!(family: @family, name: "Logo Merchant", logo_url: "https://cdn.example/logo.png")
+ merchant.logo.attach(io: file_fixture("profile_image.png").open, filename: "logo.png", content_type: "image/png")
+
+ assert_match %r{\A/rails/active_storage/representations/}, merchant.logo_url
+ end
+
+ test "rejects a logo that is not an image" do
+ merchant = FamilyMerchant.new(family: @family, name: "Text Logo Merchant")
+ merchant.logo.attach(io: file_fixture("test.txt").open, filename: "logo.txt", content_type: "text/plain")
+
+ assert_not merchant.valid?
+ assert merchant.errors.of_kind?(:logo, :invalid_content_type)
+ end
+
+ test "remove_logo purges the uploaded logo and falls back to the website logo" do
+ merchant = FamilyMerchant.create!(family: @family, name: "Removed Logo Merchant", logo_url: "https://cdn.example/logo.png")
+ merchant.logo.attach(io: file_fixture("profile_image.png").open, filename: "logo.png", content_type: "image/png")
+
+ merchant.update!(remove_logo: true)
+
+ assert_not merchant.reload.logo.attached?
+ assert_equal "https://cdn.example/logo.png", merchant.logo_url
+ end
+
+ test "remove_logo enqueues the blob purge only after the save commits" do
+ merchant = FamilyMerchant.create!(family: @family, name: "Committed Purge Merchant")
+ merchant.logo.attach(io: file_fixture("profile_image.png").open, filename: "logo.png", content_type: "image/png")
+
+ FamilyMerchant.transaction do
+ merchant.update!(remove_logo: true)
+ assert_no_enqueued_jobs only: ActiveStorage::PurgeJob
+ end
+
+ assert_enqueued_jobs 1, only: ActiveStorage::PurgeJob
+ end
+
test "preserves user-selected color on creation" do
merchant = FamilyMerchant.create!(
family: @family,