Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Let users pick, upload or fetch account institution icons (#4141)

Andrei Shkarind4c89e9ee221
diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rb
index 47e65a8542..9b45de96b1 100644
--- a/app/controllers/accounts_controller.rb
+++ b/app/controllers/accounts_controller.rb
@@ -2,7 +2,7 @@ class AccountsController < ApplicationController
include StreamExtensions
before_action :set_account, only: %i[show sparkline sync set_default remove_default clear_filter]
- before_action :set_manageable_account, only: %i[toggle_active toggle_exclude_from_reports destroy unlink confirm_unlink select_provider]
+ before_action :set_manageable_account, only: %i[logo_options toggle_active toggle_exclude_from_reports destroy unlink confirm_unlink select_provider]
before_action :ensure_linked_account, only: %i[confirm_unlink unlink]
include Periodable
@@ -244,6 +244,21 @@ class AccountsController < ApplicationController
end
end
+ # Loads the icons found for the domain into the account form's icon block,
+ # so the rest of the form keeps what the user typed. Nothing is saved here.
+ def logo_options
+ return redirect_to account_path(@account) unless turbo_frame_request?
+
+ render_logo_options(@account)
+ end
+
+ # The same for the form of an account that is not created yet.
+ def new_logo_options
+ return redirect_to accounts_path unless turbo_frame_request?
+
+ render_logo_options(Current.family.accounts.build)
+ end
+
# Saves the drag-and-drop order of one account group for the current user.
def reorder
if Current.user.update_manual_account_order(params[:group], params[:account_ids])
@@ -378,6 +393,12 @@ class AccountsController < ApplicationController
end
private
+ # The form may hold a domain or name that is not saved yet.
+ def render_logo_options(account)
+ account.assign_attributes(params.permit(:institution_domain, :institution_name))
+ render partial: "accounts/logo_field", locals: { account: account, candidates: Account::LogoFetcher.new(account).candidates }
+ end
+
# Built here rather than in the template: assembling a chart payload is
# domain work, and `show` asks for it exactly once per request, so there
# is nothing to memoise.
diff --git a/app/controllers/concerns/accountable_resource.rb b/app/controllers/concerns/accountable_resource.rb
index 63883fed09..da0e5c5060 100644
--- a/app/controllers/concerns/accountable_resource.rb
+++ b/app/controllers/concerns/accountable_resource.rb
@@ -42,11 +42,12 @@ module AccountableResource
end || (Time.zone.today - 2.years)
Account.transaction do
@account = Current.family.accounts.create_and_sync(
- account_params.except(:return_to, :opening_balance_date).merge(owner: Current.user),
+ account_params.except(:return_to, :opening_balance_date).merge(owner: Current.user, logo_chosen: logo_chosen?),
opening_balance_date: opening_balance_date
)
@account.lock_saved_attributes!
end
+ apply_logo_choice
# Prefer the form-carried return_to, then the session value StoreLocation
# captured from `?return_to=` (survives multi-step flows where the param
@@ -84,6 +85,9 @@ module AccountableResource
# other submitted fields. Keep them available for the 422 form without
# persisting them.
update_params = account_params.except(:return_to, :balance, :opening_balance_date)
+ # An uploaded logo is meant to be seen, so it takes over from Brandfetch.
+ update_params[:logo_selection] = "automatic" if account_params[:logo].present?
+ @account.logo_chosen = logo_chosen?
# The balance change and the attribute update are one form, so they commit
# or roll back as one. `set_current_balance` writes a valuation and the
@@ -125,10 +129,34 @@ module AccountableResource
return
end
+ apply_logo_choice
+
redirect_back_or_to account_path(@account), notice: t("accounts.update.success", type: accountable_type.name.underscore.humanize)
end
private
+ def logo_choice
+ params.dig(:account, :logo_choice).presence
+ end
+
+ # An icon picked or uploaded in the form wins over the automatic fetch
+ # that a new domain would otherwise queue.
+ def logo_chosen?
+ logo_choice.present? || account_params[:logo].present?
+ end
+
+ # The icon picked in the form downloads only on save, after the account
+ # committed, and an upload in the same submit wins over it.
+ def apply_logo_choice
+ return unless logo_choice && account_params[:logo].blank?
+ return if @account.choose_logo(logo_choice)
+
+ flash[:alert] = t("accounts.update.logo_not_applied")
+ # The choice held back the automatic fetch; with it gone, that fetch
+ # replaces or drops an automatic icon left from an earlier domain.
+ AccountLogoFetchJob.perform_paced(@account)
+ end
+
# The account the 422 form renders when the exception carried none.
#
# `accountable_attributes` is defaulted the way `create_and_sync` defaults
@@ -172,7 +200,7 @@ module AccountableResource
:name, :balance, :subtype, :currency, :accountable_type, :return_to,
:opening_balance_date,
:institution_name, :institution_domain, :notes, :exclude_from_reports,
- :enable_category_matcher,
+ :enable_category_matcher, :logo,
accountable_attributes: self.class.permitted_accountable_attributes
)
end
diff --git a/app/helpers/accounts_helper.rb b/app/helpers/accounts_helper.rb
index df868443dd..ed35f62745 100644
--- a/app/helpers/accounts_helper.rb
+++ b/app/helpers/accounts_helper.rb
@@ -68,6 +68,10 @@ module AccountsHelper
# (this partial renders with skip_digest: true, so the template digest
# would not otherwise reflect the change).
Current.user&.always_expanded_account_groups&.sort,
+ # Brandfetch logo URLs carry the client id and the logo size, so
+ # changing either in Settings must bust the cached sidebar too.
+ Digest::SHA256.hexdigest(Setting.brand_fetch_client_id.to_s),
+ Setting.brand_fetch_logo_size,
# Changing the account order, or dragging an account in the manual
# order, must re-render the sidebar right away rather than after the
# 12h expiry.
@@ -75,4 +79,48 @@ module AccountsHelper
Current.user&.account_order&.manual? ? Digest::SHA256.hexdigest(Current.user.manual_account_order.to_json) : nil
]
end
+
+ # Where the icon shown for the account comes from, for the account form.
+ def account_logo_caption(account)
+ key = if account.logo_brandfetch? && account.brandfetch_logo_url then "brandfetch"
+ elsif account.stored_logo_url then account.logo_source || "uploaded"
+ elsif account.brandfetch_logo_url then "brandfetch"
+ else "none"
+ end
+
+ name = account.logo.blob.metadata["logo_name"] if key == account.logo_source
+ [ t("accounts.logo_caption.#{key}"), name ].compact.join(" · ")
+ end
+
+ LogoOption = Data.define(:source, :src, :label, :detail, :title, :current)
+
+ # Tiles of the logo picker: the icons found for the domain, the stored logo
+ # while Brandfetch is shown instead, and Brandfetch when configured.
+ # `source` is what Account#choose_logo receives when the form is saved.
+ def account_logo_options(account, candidates)
+ shows_stored = account.logo_automatic?
+
+ options = candidates.map do |icon|
+ LogoOption.new(
+ source: icon.key,
+ src: "data:#{icon.content_type};base64,#{Base64.strict_encode64(icon.body)}",
+ label: t("accounts.logo_options.sources.#{icon.source}"),
+ detail: t("accounts.logo_options.size", size: icon.size),
+ title: icon.name,
+ current: shows_stored && account.stored_logo?(icon.key, body: icon.body)
+ )
+ end
+
+ if !shows_stored && account.stored_logo_url
+ options.unshift(LogoOption.new(source: "stored", src: account.stored_logo_url, label: t("accounts.logo_options.stored"),
+ detail: nil, title: nil, current: false))
+ end
+
+ if account.brandfetch_logo_url
+ options << LogoOption.new(source: "brandfetch", src: account.brandfetch_logo_url, label: t("accounts.logo_options.sources.brandfetch"),
+ detail: nil, title: nil, current: !shows_stored || !account.logo.attached?)
+ end
+
+ options
+ end
end
diff --git a/app/javascript/controllers/account_logo_picker_controller.js b/app/javascript/controllers/account_logo_picker_controller.js
new file mode 100644
index 0000000000..1e5b106b40
--- /dev/null
+++ b/app/javascript/controllers/account_logo_picker_controller.js
@@ -0,0 +1,185 @@
+import { Controller } from "@hotwired/stimulus";
+
+// A whole domain, as Account.normalize_institution_domain leaves it.
+const DOMAIN = /^([a-z0-9-]+\.)+(xn--[a-z0-9-]+|[a-z]{2,})$/;
+
+function normalizeDomain(value) {
+ return (value || "")
+ .trim()
+ .toLowerCase()
+ .replace(/^[a-z][a-z0-9+.-]*:\/\//, "")
+ .split(/[/?#]/)[0]
+ .replace(/:\d+$/, "")
+ .replace(/^www\./, "");
+}
+
+// Previews the icon chosen in the account form. Nothing is saved until the
+// form is submitted: a picked or removed icon travels in a hidden field, an
+// upload in the file field.
+export default class extends Controller {
+ static targets = [
+ "preview",
+ "image",
+ "caption",
+ "choice",
+ "file",
+ "option",
+ "fallback",
+ "blank",
+ "pick",
+ "pickHint",
+ ];
+ static values = { pending: String, removal: String, providerDomain: String };
+
+ // Stimulus connects targets before connect(), so the field is looked up
+ // on demand and the button state is set again once listening.
+ connect() {
+ this.listenedField = this.domainField;
+ this.listenedField?.addEventListener("input", this.updatePick);
+ this.updatePick();
+ }
+
+ get domainField() {
+ return this.element
+ .closest("form")
+ ?.elements.namedItem("account[institution_domain]");
+ }
+
+ disconnect() {
+ this.listenedField?.removeEventListener("input", this.updatePick);
+ this.revokePreview();
+ }
+
+ pickTargetConnected() {
+ this.updatePick();
+ }
+
+ // "Pick icon" stays clickable when there is no domain yet, so a hover or a
+ // tap can say why it does nothing; a disabled button would show neither.
+ updatePick = () => {
+ if (!this.hasPickTarget) return;
+
+ const ready = this.domainReady();
+ this.pickTarget.setAttribute("aria-disabled", String(!ready));
+ this.pickTarget.classList.toggle("opacity-50", !ready);
+ this.pickTarget.classList.toggle("cursor-not-allowed", !ready);
+ this.pickTarget.title = ready ? "" : this.pickHintTarget.textContent.trim();
+ if (ready) this.pickHintTarget.classList.add("hidden");
+ };
+
+ // A linked account may take its domain from the provider while the field is blank.
+ domainReady() {
+ const typed = normalizeDomain(this.domainField?.value);
+ return DOMAIN.test(typed || this.providerDomainValue);
+ }
+
+ // The picker reloads the icon block from the server, which shows the saved
+ // icon, so an earlier choice starts over; a selected file is kept.
+ previewTargetConnected() {
+ this.savedImage = [...this.imageTarget.childNodes].map((node) =>
+ node.cloneNode(true),
+ );
+ this.savedCaption = this.captionTarget.textContent;
+ this.choiceTarget.value = "";
+ this.showFile();
+ }
+
+ // The picker searches what the account form holds now, not what was saved.
+ search(event) {
+ if (!this.domainReady()) {
+ event.preventDefault();
+ this.pickHintTarget.classList.remove("hidden");
+ return;
+ }
+
+ const { currentTarget } = event;
+ const typed = this.element.closest("form").elements;
+ const query = currentTarget.form.elements;
+
+ for (const name of ["institution_domain", "institution_name"]) {
+ const field = typed.namedItem(`account[${name}]`);
+ const input = query.namedItem(name);
+ if (field && input) input.value = field.value;
+ }
+ }
+
+ choose({ params: { choice, label }, currentTarget }) {
+ this.clearFile();
+
+ if (choice) {
+ this.choiceTarget.value = choice;
+ this.showImage(
+ currentTarget.querySelector("img")?.src,
+ `${label} · ${this.pendingValue}`,
+ );
+ } else {
+ this.restore();
+ }
+
+ this.highlight(currentTarget);
+ }
+
+ // Removing brings back the automatic icon, so that is what the preview shows.
+ remove() {
+ this.clearFile();
+ this.restore();
+ this.choiceTarget.value = "remove";
+ this.imageTarget.replaceChildren(
+ this.fallbackTarget.content.cloneNode(true),
+ );
+ this.captionTarget.textContent = this.removalValue;
+ this.highlight(null);
+ }
+
+ showFile() {
+ const file = this.hasFileTarget && this.fileTarget.files[0];
+ if (!file) return;
+
+ this.choiceTarget.value = "";
+ this.revokePreview();
+ this.previewUrl = URL.createObjectURL(file);
+ this.showImage(this.previewUrl, `${file.name} · ${this.pendingValue}`);
+ this.highlight(null);
+ }
+
+ // The image comes from the server-rendered blank, so it keeps the shape of
+ // every other account logo and falls back to the initials like one.
+ // Without a source (the option's image failed to load and removed itself)
+ // the preview shows the initials, as the option does.
+ showImage(src, caption) {
+ const logo = this.blankTarget.content.cloneNode(true);
+ const image = logo.querySelector("img");
+ if (src) image.src = src;
+ else image.remove();
+ this.imageTarget.replaceChildren(logo);
+ this.captionTarget.textContent = caption;
+ }
+
+ restore() {
+ this.choiceTarget.value = "";
+ this.imageTarget.replaceChildren(
+ ...this.savedImage.map((node) => node.cloneNode(true)),
+ );
+ this.captionTarget.textContent = this.savedCaption;
+ }
+
+ clearFile() {
+ if (this.hasFileTarget) this.fileTarget.value = "";
+ this.revokePreview();
+ }
+
+ revokePreview() {
+ if (!this.previewUrl) return;
+
+ URL.revokeObjectURL(this.previewUrl);
+ this.previewUrl = null;
+ }
+
+ highlight(selected) {
+ for (const option of this.optionTargets) {
+ const active = option === selected;
+ option.classList.toggle("border-primary", active);
+ option.classList.toggle("border-secondary", !active);
+ }
+ }
+}
diff --git a/app/jobs/account_logo_backfill_job.rb b/app/jobs/account_logo_backfill_job.rb
new file mode 100644
index 0000000000..c59a8fa08b
--- /dev/null
+++ b/app/jobs/account_logo_backfill_job.rb
@@ -0,0 +1,31 @@
+# Nightly retry for accounts whose domain has no logo yet: new accounts whose
+# first fetch failed, and accounts that had a domain before auto-fetching existed.
+class AccountLogoBackfillJob < ApplicationJob
+ queue_as :scheduled
+
+ # The iTunes Search API allows about 20 requests a minute, and each fetch
+ # makes up to three of them.
+ SPACING = 20.seconds
+ # Spread over about 17 hours, so a run is done before the next one starts.
+ # Larger backlogs continue from a cursor the next night.
+ BATCH_SIZE = 3_000
+ CURSOR_KEY = "account_logo_backfill_cursor"
+
+ def perform(batch_size: BATCH_SIZE)
+ cursor = Rails.cache.read(CURSOR_KEY)
+ batch = accounts.where(cursor ? [ "accounts.id > ?", cursor ] : nil).limit(batch_size).to_a
+ batch = accounts.limit(batch_size).to_a if batch.empty? && cursor
+
+ Rails.cache.write(CURSOR_KEY, (batch.last.id if batch.size == batch_size))
+ batch.each { |account| AccountLogoFetchJob.perform_paced(account) }
+ end
+
+ private
+ def accounts
+ Account.visible
+ .where.not(institution_domain: [ nil, "" ])
+ .logo_automatic
+ .where.missing(:logo_attachment)
+ .order(:id)
+ end
+end
diff --git a/app/jobs/account_logo_fetch_job.rb b/app/jobs/account_logo_fetch_job.rb
new file mode 100644
index 0000000000..6f478b3646
--- /dev/null
+++ b/app/jobs/account_logo_fetch_job.rb
@@ -0,0 +1,41 @@
+class AccountLogoFetchJob < ApplicationJob
+ queue_as :low_priority
+
+ PACE_KEY = "account_logo_fetch_pace"
+ MAX_SLOT_PROBES = 50
+
+ # Spaces fetches for the iTunes Search API limit: each one claims the next
+ # free time slot in the shared cache (Redis in production), so imports, the
+ # nightly backfill and single domain changes share one queue. A claim lasts
+ # until its slot has passed; a lone domain change usually fetches at once.
+ def self.perform_paced(account)
+ spacing = AccountLogoBackfillJob::SPACING.to_i
+ now = Time.current.to_i
+ # The next slot others claimed is only a hint where to start probing.
+ first = [ now / spacing, Rails.cache.read(PACE_KEY).to_i ].max
+ slot = (first...first + MAX_SLOT_PROBES).find do |candidate|
+ Rails.cache.write("#{PACE_KEY}:#{candidate}", true, unless_exist: true, expires_in: (candidate * spacing - now + 60).seconds)
+ end
+ # A cache that refuses every claim (Redis down) must not hold up the
+ # caller, so the fetch goes unpaced.
+ return perform_later(account) unless slot
+
+ Rails.cache.write(PACE_KEY, slot + 1, expires_in: 1.day)
+
+ set(wait: [ slot * spacing - now, 0 ].max.seconds).perform_later(account)
+ end
+
+ def perform(account)
+ return unless account.logo_auto_fetchable?
+ return if Account::LogoFetcher.new(account).fetch(auto: true)
+
+ # Nothing found for a new domain: the automatic icon of the old one goes,
+ # unless an icon or Brandfetch was chosen while the search ran.
+ account.with_lock do
+ if account.logo_auto_fetchable? && account.logo_auto? && !account.stored_logo?(account.logo_key)
+ account.logo.purge_later
+ account.touch
+ end
+ end
+ end
+end
diff --git a/app/models/account.rb b/app/models/account.rb
index ac56db95b4..b3f2f8e938 100644
--- a/app/models/account.rb
+++ b/app/models/account.rb
@@ -1,5 +1,5 @@
class Account < ApplicationRecord
- include AASM, Syncable, Monetizable, Chartable, Linkable, Enrichable, Anchorable, Reconcileable, TaxTreatable
+ include AASM, Syncable, Monetizable, Chartable, Linkable, Enrichable, Anchorable, Reconcileable, TaxTreatable, Logoable
before_validation :assign_default_owner, if: -> { owner_id.blank? }
@@ -134,7 +134,9 @@ class Account < ApplicationRecord
.distinct
}
- has_one_attached :logo, dependent: :purge_later
+ # People paste whole URLs ("https://www.tbank.ru/") into the domain field,
+ # but the Brandfetch logo URL needs the bare host ("tbank.ru").
+ normalizes :institution_domain, with: ->(value) { normalize_institution_domain(value) }
# No dependent: option; before_destroy captures IDs, after_destroy_commit moves statements back to inbox.
has_many :account_statements
@@ -228,6 +230,15 @@ class Account < ApplicationRecord
end
class << self
+ def normalize_institution_domain(value)
+ host = value.to_s.strip.downcase
+ .sub(%r{\A[a-z][a-z0-9+.-]*://}, "")
+ .split(%r{[/?#]}, 2).first.to_s
+ .sub(/:\d+\z/, "")
+ .delete_prefix("www.")
+ host.presence
+ end
+
def human_attribute_name(attribute, options = {})
options = { moniker: Current.family&.moniker_label || "Family" }.merge(options)
super(attribute, options)
@@ -618,7 +629,8 @@ class Account < ApplicationRecord
end
def institution_domain
- read_attribute(:institution_domain).presence || provider&.institution_domain
+ # Normalized on read too, so domains saved before normalization existed still resolve a logo.
+ self.class.normalize_institution_domain(read_attribute(:institution_domain)) || provider&.institution_domain
end
def manual_crypto_exchange?
@@ -669,18 +681,6 @@ class Account < ApplicationRecord
balance.to_d - goal_earmarked_total
end
- def logo_url
- if institution_domain.present? && Setting.brand_fetch_client_id.present?
- logo_size = Setting.brand_fetch_logo_size
-
- "https://cdn.brandfetch.io/#{institution_domain}/icon/fallback/lettermark/w/#{logo_size}/h/#{logo_size}?c=#{Setting.brand_fetch_client_id}"
- elsif provider&.logo_url.present?
- provider.logo_url
- elsif logo.attached?
- Rails.application.routes.url_helpers.rails_blob_path(logo, only_path: true)
- end
- end
-
# Marks the account pending_deletion and enqueues DestroyJob. If the enqueue
# fails, the account goes back to the status it had, so it is not left hidden
# from every list with no job coming to delete it. Mirrors DestroyableLater,
diff --git a/app/models/account/logo_fetcher.rb b/app/models/account/logo_fetcher.rb
new file mode 100644
index 0000000000..0fa8d72e5d
--- /dev/null
+++ b/app/models/account/logo_fetcher.rb
@@ -0,0 +1,180 @@
+# Finds an institution's icon and stores it as the account's own logo.
+# Brandfetch refuses server-side downloads and bank sites block bots, so the
+# icons come from services that already collected them: favicon services
+# (the sites' touch and manifest icons) and the institution's mobile apps in
+# the App Store, Google Play and RuStore, matched by the developer's website
+# (or, in RuStore, by the package name).
+class Account::LogoFetcher
+ FAVICON_SOURCES = {
+ "google" => ->(domain) { "https://www.google.com/s2/favicons?domain=#{domain}&sz=256" },
+ "duckduckgo" => ->(domain) { "https://icons.duckduckgo.com/ip3/#{domain}.ico" },
+ "yandex" => ->(domain) { "https://favicon.yandex.net/favicon/v2/#{domain}?size=120" }
+ }.freeze
+
+ CANDIDATES_CACHE_KEY = "account_logo_candidates"
+ CANDIDATES_CACHE_TTL = 5.minutes
+
+ DOMAIN_FORMAT = /\A[a-z0-9-]+(\.[a-z0-9-]+)+\z/
+ # Country-code TLDs that differ from the ISO country code the stores use.
+ CCTLD_COUNTRIES = { "uk" => "gb" }.freeze
+
+ # `key` identifies the icon for fetch(source:): a favicon service name, or
+ # "appstore:<track id>", "googleplay:<package>" or "rustore:<package>" for an app.
+ # `auto` is false for icons only offered in the picker, never picked automatically.
+ Icon = Data.define(:key, :source, :name, :body, :size, :content_type, :extension, :auto) do
+ def initialize(auto: true, **attributes)
+ super
+ end
+ end
+
+ attr_reader :account
+
+ # The developer site is the institution's domain or one of its subdomains.
+ def self.own_site?(host, domain)
+ host = Account.normalize_institution_domain(host)
+ host.present? && (host == domain || host.end_with?(".#{domain}"))
+ end
+
+ # Also a parent of the domain: Ozon Bank's apps list ozon.ru for
+ # finance.ozon.ru. A parent can be shared by unrelated sites (yandex.ru
+ # for every Yandex app, github.io), so such apps are offered in the picker
+ # but never picked automatically.
+ def self.same_site?(host, domain)
+ host = Account.normalize_institution_domain(host)
+ own_site?(host, domain) || (host.present? && domain.end_with?(".#{host}"))
+ end
+
+ def initialize(account)
+ @account = account
+ end
+
+ # Real icons from every source, largest first; ties keep the source order.
+ # RuStore is asked only for the picker: it may match an app by its package
+ # name, which anyone can choose, and it puts clients that read many of its
+ # store pages behind a bot challenge.
+ def candidates(for_picker: true)
+ return [] unless domain
+ return search_candidates(for_picker:) unless for_picker
+
+ # Opening the picker again, or for a sibling account of the same bank,
+ # reuses the icons found a moment ago instead of searching the stores anew.
+ key = [ CANDIDATES_CACHE_KEY, domain, search_term, countries ]
+ Rails.cache.read(key) || search_candidates(for_picker:).tap do |icons|
+ Rails.cache.write(key, icons, expires_in: CANDIDATES_CACHE_TTL) if icons.any?
+ end
+ end
+
+ # Attaches the icon with `source` key, or the largest one fit for an
+ # automatic pick when no source is given. `auto` marks the icon as picked by Sure,
+ # so later automatic fetches may replace it. Returns true when an icon was
+ # attached.
+ def fetch(source: nil, auto: false)
+ return false unless domain
+
+ fetched_for = domain
+ logo_before = logo_state
+ icon = source ? icon_for(source) : candidates(for_picker: false).find(&:auto)
+ return false unless icon
+
+ # The search takes seconds. Under the row lock, which the account form's
+ # save also holds, a fetch yields to a domain changed meanwhile and to an
+ # icon chosen, uploaded or removed meanwhile; a user's pick still replaces
+ # an icon an automatic fetch attached in the meantime. Touching the account
+ # busts the sidebar cache, which an attachment alone does not.
+ account.with_lock do
+ if account.institution_domain != fetched_for || changed_since?(logo_before, auto:) || (auto && !account.logo_auto_fetchable?)
+ false
+ else
+ # Attachment and flags go into one save: attach saves on its own only
+ # when the record has no other pending changes.
+ account.assign_attributes(logo_selection: :automatic, updated_at: Time.current)
+ account.logo.attach(
+ io: StringIO.new(icon.body),
+ filename: "#{fetched_for}.#{icon.extension}",
+ content_type: icon.content_type,
+ metadata: { "logo_source" => icon.source, "logo_key" => icon.key, "logo_name" => icon.name,
+ "logo_domain" => fetched_for, "logo_auto" => auto }.compact
+ )
+ account.save
+ end
+ end
+ end
+
+ private
+ def search_candidates(for_picker:)
+ # Built here, not in the threads, so database reads stay on this thread's connection.
+ stores = [ app_store, google_play, (ru_store if for_picker) ].compact
+ icons = client.in_parallel([ -> { favicon_icons }, *stores.map { |store| -> { store.icons } } ]).flatten
+ icons.each_with_index.sort_by { |icon, index| [ -icon.size, index ] }.map(&:first)
+ end
+
+ def logo_state
+ [ account.logo.attachment&.blob_id, account.logo_selection, account.logo_auto? ]
+ end
+
+ # A pick yields to an icon uploaded or picked meanwhile, to a Brandfetch
+ # switch and to the removal of a chosen icon, which only a user does. It
+ # does not yield to an automatic fetch attaching or dropping its own icon:
+ # removing an automatic icon only goes back to the automatic default.
+ def changed_since?(logo_before, auto:)
+ return false if logo_state == logo_before
+ return true if auto
+
+ blob_before, selection_before, auto_before = logo_before
+ return true if account.logo_selection != selection_before
+
+ account.logo.attached? ? !account.logo_auto? : blob_before.present? && !auto_before
+ end
+
+ def domain
+ value = account.institution_domain
+ value if value.to_s.match?(DOMAIN_FORMAT)
+ end
+
+ def icon_for(key)
+ group, id = key.to_s.split(":", 2)
+
+ case group
+ when *FAVICON_SOURCES.keys then favicon_icon(group) if id.nil?
+ when "appstore" then app_store.icon(id)
+ when "googleplay" then google_play.icon(id)
+ when "rustore" then ru_store.icon(id)
+ end
+ end
+
+ def favicon_icons
+ client.in_parallel(FAVICON_SOURCES.keys.map { |source| -> { favicon_icon(source) } }).compact
+ end
+
+ def favicon_icon(source)
+ client.icon(FAVICON_SOURCES.fetch(source).call(domain), key: source, source: source)
+ end
+
+ def app_store
+ @app_store ||= Account::LogoFetcher::AppStore.new(domain:, term: search_term, countries:, client:)
+ end
+
+ def google_play
+ @google_play ||= Account::LogoFetcher::GooglePlay.new(domain:, term: search_term, country: countries.first, client:)
+ end
+
+ def ru_store
+ @ru_store ||= Account::LogoFetcher::RuStore.new(domain:, term: search_term, client:)
+ end
+
+ def search_term
+ account.institution_name.presence || domain.split(".").first
+ end
+
+ # App catalogues differ per country: the domain's own country ("bankffin.kz"),
+ # the family's, then the US store, which lists most international apps.
+ def countries
+ tld = domain.split(".").last
+ tld = CCTLD_COUNTRIES.fetch(tld, tld)
+ [ (tld if tld.length == 2), account.family&.country, "us" ].compact.map(&:downcase).uniq
+ end
+
+ def client
+ @client ||= Account::LogoFetcher::Client.new
+ end
+end
diff --git a/app/models/account/logo_fetcher/app_store.rb b/app/models/account/logo_fetcher/app_store.rb
new file mode 100644
index 0000000000..1701377b70
--- /dev/null
+++ b/app/models/account/logo_fetcher/app_store.rb
@@ -0,0 +1,55 @@
+# Institution app icons (512px) from the iTunes Search API, which needs no key.
+# Only apps whose developer website is the institution's domain count, so a
+# similarly named app from someone else never becomes the logo.
+class Account::LogoFetcher::AppStore
+ SEARCH_URL = "https://itunes.apple.com/search"
+ LOOKUP_URL = "https://itunes.apple.com/lookup"
+ ARTWORK_HOST = /\A[a-z0-9-]+\.mzstatic\.com\z/
+ MAX_APPS = 3
+
+ def initialize(domain:, term:, countries:, client:)
+ @domain = domain
+ @term = term
+ @countries = countries
+ @client = client
+ end
+
+ # Countries are searched and icons downloaded at once, so a slow store
+ # costs one timeout, not one per request.
+ def icons
+ apps = in_countries { |country| results(SEARCH_URL, term: @term, country: country, entity: "software", limit: 10) }
+ own = apps.uniq { |app| app["trackId"] }.select { |app| own_app?(app) }.first(MAX_APPS)
+ @client.in_parallel(own.map { |app| -> { icon_from(app) } }).compact
+ end
+
+ def icon(track_id)
+ return unless track_id.to_s.match?(/\A\d+\z/)
+
+ app = in_countries { |country| results(LOOKUP_URL, id: track_id, country: country) }.first
+ icon_from(app) if app && own_app?(app)
+ end
+
+ private
+ # Results of every country, in country order.
+ def in_countries(&search)
+ @client.in_parallel(@countries.map { |country| -> { search.call(country) } }).flatten
+ end
+
+ def results(url, params)
+ Array(@client.json("#{url}?#{params.to_query}")&.dig("results"))
+ end
+
+ def own_app?(app)
+ Account::LogoFetcher.same_site?(app["sellerUrl"], @domain)
+ end
+
+ def icon_from(app)
+ url = app["artworkUrl512"].to_s
+ return unless URI.parse(url).then { |uri| uri.scheme == "https" && uri.host.to_s.match?(ARTWORK_HOST) }
+
+ @client.icon(url, key: "appstore:#{app["trackId"]}", source: "appstore", name: app["trackName"],
+ auto: Account::LogoFetcher.own_site?(app["sellerUrl"], @domain))
+ rescue URI::InvalidURIError
+ nil
+ end
+end
diff --git a/app/models/account/logo_fetcher/client.rb b/app/models/account/logo_fetcher/client.rb
new file mode 100644
index 0000000000..57bc437245
--- /dev/null
+++ b/app/models/account/logo_fetcher/client.rb
@@ -0,0 +1,105 @@
+# HTTP for Account::LogoFetcher: follows https redirects, treats network
+# failures as "nothing found", and turns image responses into sized icons.
+class Account::LogoFetcher::Client
+ # Favicon services answer unknown domains with a 16px (or 1px) placeholder.
+ MIN_SIZE = 17
+ MAX_REDIRECTS = 3
+ # The IEND chunk with its CRC, which closes every complete PNG.
+ PNG_END = "IEND\xAEB`\x82".b
+ # Store pages and search results stay well under this.
+ MAX_BODY = 5.megabytes
+
+ BodyTooLarge = Class.new(StandardError)
+
+ # The body of a 200 response, following https redirects, or nil. Bodies
+ # are read in chunks and dropped once they pass `max_bytes`, so a redirect
+ # to an oversized file never sits in memory whole.
+ def get(url, max_bytes: MAX_BODY, redirects_left: MAX_REDIRECTS)
+ body = +""
+ response = connection.get(url) do |request|
+ request.options.on_data = proc do |chunk, received|
+ raise BodyTooLarge if received > max_bytes
+
+ body << chunk
+ end
+ end
+ location = response.headers["location"].to_s
+
+ if response.status.in?(300..399)
+ get(location, max_bytes:, redirects_left: redirects_left - 1) if redirects_left.positive? && location.start_with?("https://")
+ elsif response.status == 200
+ body
+ end
+ rescue Faraday::Error, BodyTooLarge => e
+ Rails.logger.info("Account logo request failed: url=#{url} error=#{e.class}: #{e.message}")
+ nil
+ end
+
+ def json(url)
+ body = get(url)
+ JSON.parse(body) if body
+ rescue JSON::ParserError
+ nil
+ end
+
+ def icon(url, key:, source:, name: nil, auto: true)
+ body = get(url, max_bytes: Account::LOGO_MAX_SIZE)&.b
+ return if body.nil?
+
+ size, content_type, extension = image_format(body)
+ Account::LogoFetcher::Icon.new(key:, source:, name:, body:, size:, content_type:, extension:, auto:) if size.to_i >= MIN_SIZE
+ end
+
+ # Runs the lambdas in threads (the work is waiting on HTTP) and returns their results in order.
+ def in_parallel(tasks)
+ threads = tasks.map { |task| Thread.new { Rails.application.executor.wrap { task.call } } }
+ ActiveSupport::Dependencies.interlock.permit_concurrent_loads { threads.map(&:value) }
+ end
+
+ private
+ def connection
+ @connection ||= Faraday.new(request: { open_timeout: 5, timeout: 10 })
+ end
+
+ # Reads the pixel width from the file header; formats we cannot size are
+ # skipped, and so are files cut short (no end marker), which would be
+ # stored as a broken logo.
+ def image_format(body)
+ if body.start_with?("\x89PNG\r\n\x1a\n".b) && body.byteslice(12, 4) == "IHDR" && body.end_with?(PNG_END)
+ [ body.byteslice(16, 4).unpack1("N"), "image/png", "png" ]
+ elsif body.start_with?("\x00\x00\x01\x00".b) && body.bytesize >= 6
+ [ ico_width(body), "image/vnd.microsoft.icon", "ico" ]
+ elsif body.start_with?("GIF8") && body.bytesize >= 8 && body.end_with?(";")
+ [ body.byteslice(6, 2).unpack1("v"), "image/gif", "gif" ]
+ elsif body.start_with?("\xFF\xD8".b) && body.end_with?("\xFF\xD9".b)
+ [ jpeg_width(body), "image/jpeg", "jpg" ]
+ end
+ end
+
+ # The widest image an ICO holds, counting only directory entries whose
+ # image data is in the file; nil when the directory itself is cut short.
+ def ico_width(body)
+ count = body.byteslice(4, 2).unpack1("v")
+ return if count.zero? || body.bytesize < 6 + count * 16
+
+ widths = (0...count).filter_map do |i|
+ entry = 6 + i * 16
+ data_size, data_offset = body.byteslice(entry + 8, 8).unpack("VV")
+ width = body.getbyte(entry)
+ # A width byte of 0 means 256px.
+ (width.zero? ? 256 : width) if data_size.positive? && data_offset + data_size <= body.bytesize
+ end
+ widths.max
+ end
+
+ # Walks the JPEG segments to the start-of-frame one, which holds the dimensions.
+ def jpeg_width(body)
+ position = 2
+ while position + 9 <= body.bytesize && body.getbyte(position) == 0xFF
+ marker = body.getbyte(position + 1)
+ return body.byteslice(position + 7, 2).unpack1("n") if marker.between?(0xC0, 0xCF) && ![ 0xC4, 0xC8, 0xCC ].include?(marker)
+
+ position += 2 + body.byteslice(position + 2, 2).unpack1("n")
+ end
+ end
+end
diff --git a/app/models/account/logo_fetcher/google_play.rb b/app/models/account/logo_fetcher/google_play.rb
new file mode 100644
index 0000000000..fd1ffb8fb1
--- /dev/null
+++ b/app/models/account/logo_fetcher/google_play.rb
@@ -0,0 +1,43 @@
+# Institution app icons from Google Play. There is no public API, so this
+# reads the store pages' meta tags (developer website and icon), which have
+# stayed stable while the page layout around them changes. Only apps whose
+# developer website is the institution's domain count.
+class Account::LogoFetcher::GooglePlay
+ SEARCH_URL = "https://play.google.com/store/search"
+ APP_URL = "https://play.google.com/store/apps/details"
+ PACKAGE_FORMAT = /\A[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)+\z/
+ ICON_FORMAT = %r{\Ahttps://play-lh\.googleusercontent\.com/[\w-]+\z}
+ MAX_APPS = 3
+
+ def initialize(domain:, term:, country:, client:)
+ @domain = domain
+ @term = term
+ @country = country
+ @client = client
+ end
+
+ def icons
+ page = @client.get("#{SEARCH_URL}?#{{ q: @term, c: "apps", hl: "en", gl: @country }.to_query}").to_s
+ packages = page.scan(%r{/store/apps/details\?id=([\w.]+)}).flatten.uniq.first(MAX_APPS)
+ @client.in_parallel(packages.map { |package| -> { icon(package) } }).compact
+ end
+
+ def icon(package)
+ return unless package.to_s.match?(PACKAGE_FORMAT)
+
+ page = @client.get("#{APP_URL}?#{{ id: package, hl: "en" }.to_query}").to_s
+ developer_url = meta(page, "name", "appstore:developer_url")
+ icon_url = meta(page, "property", "og:image").to_s.split("=").first
+ return unless Account::LogoFetcher.same_site?(developer_url, @domain) && icon_url.to_s.match?(ICON_FORMAT)
+
+ name = meta(page, "property", "og:title").to_s.delete_suffix(" - Apps on Google Play").presence
+ @client.icon("#{icon_url}=s512", key: "googleplay:#{package}", source: "googleplay", name: name,
+ auto: Account::LogoFetcher.own_site?(developer_url, @domain))
+ end
+
+ private
+ def meta(page, attribute, value)
+ content = page[/<meta #{attribute}="#{Regexp.escape(value)}" content="([^"]*)"/, 1]
+ CGI.unescapeHTML(content) if content
+ end
+end
diff --git a/app/models/account/logo_fetcher/ru_store.rb b/app/models/account/logo_fetcher/ru_store.rb
new file mode 100644
index 0000000000..5f2c834660
--- /dev/null
+++ b/app/models/account/logo_fetcher/ru_store.rb
@@ -0,0 +1,67 @@
+# Institution app icons (512px) from RuStore, the Russian Android store that
+# lists banks missing from Google Play and the App Store. Its catalogue search
+# needs no key but returns no developer details, and its store pages sit
+# behind a bot challenge, so apps are matched on what the search returns:
+# a package name holding the domain's brand ("com.yandex.bank" for
+# bank.yandex.ru), an app name starting with the institution's ("Т-Банк:
+# карты, вклады, кредиты"), and other apps of the brands found that way
+# ("ru.tinkoff.sme" next to "com.idamob.tinkoff.android"). Anyone can choose
+# such names, so Account::LogoFetcher offers these icons in the picker only.
+class Account::LogoFetcher::RuStore
+ SEARCH_URL = "https://backapi.rustore.ru/applicationData/apps"
+ ICON_HOST = "static.rustore.ru"
+ PACKAGE_FORMAT = /\A[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)+\z/
+ # Domain labels and package segments that name no one in particular.
+ GENERIC_NAMES = %w[www com net org ru kz by ua bank online finance app apps android mobile my].freeze
+ MAX_APPS = 3
+
+ def initialize(domain:, term:, client:)
+ @domain = domain
+ @term = term
+ @client = client
+ end
+
+ def icons
+ @client.in_parallel(own_apps.first(MAX_APPS).map { |app| -> { icon_from(app) } }).compact
+ end
+
+ # RuStore has no public lookup by package, so the picked app is found again
+ # through the same search that listed it.
+ def icon(package)
+ app = own_apps.find { |candidate| candidate["packageName"] == package }
+ icon_from(app) if app
+ end
+
+ private
+ def own_apps
+ apps = Array(@client.json("#{SEARCH_URL}?#{{ query: @term, pageSize: 10 }.to_query}")&.dig("body", "content"))
+ .select { |app| app["packageName"].to_s.match?(PACKAGE_FORMAT) }
+ named = apps.select { |app| simplify(app["appName"]).start_with?(simplify(@term)) && simplify(@term).present? }
+ brands = names(@domain.split(".")[0...-1]) + named.flat_map { |app| names(app["packageName"].split(".")) }
+
+ apps.select { |app| named.include?(app) || branded?(app["packageName"], brands) }
+ end
+
+ def branded?(package, brands)
+ segments = package.downcase.split(".")
+ brands.any? { |brand| segments.any? { |segment| segment.start_with?(brand) } }
+ end
+
+ def names(parts)
+ parts.map(&:downcase).select { |part| part.length >= 3 } - GENERIC_NAMES
+ end
+
+ # "Т-Банк: карты" and "т банк" both become "тбанк…".
+ def simplify(name)
+ name.to_s.downcase.gsub(/[^[:alnum:]]/, "")
+ end
+
+ def icon_from(app)
+ url = app["iconUrl"].to_s
+ return unless URI.parse(url).then { |uri| uri.scheme == "https" && uri.host == ICON_HOST }
+
+ @client.icon(url, key: "rustore:#{app["packageName"]}", source: "rustore", name: app["appName"])
+ rescue URI::InvalidURIError
+ nil
+ end
+end
diff --git a/app/models/account/logoable.rb b/app/models/account/logoable.rb
new file mode 100644
index 0000000000..b6e73e40b1
--- /dev/null
+++ b/app/models/account/logoable.rb
@@ -0,0 +1,128 @@
+# The account's icon: an uploaded or fetched logo, the Brandfetch logo for the
+# institution domain, or the provider's logo, in that order unless the user
+# chose Brandfetch over the stored logo.
+module Account::Logoable
+ extend ActiveSupport::Concern
+
+ LOGO_CONTENT_TYPES = %w[image/png image/jpeg image/gif image/webp image/vnd.microsoft.icon image/x-icon].freeze
+ LOGO_MAX_SIZE = 1.megabyte
+
+ included do
+ has_one_attached :logo, dependent: :purge_later
+ # "brandfetch" shows the Brandfetch logo over a stored one, which is kept
+ # to switch back to.
+ enum :logo_selection, { automatic: "automatic", brandfetch: "brandfetch" }, default: :automatic, prefix: :logo
+ # Only new uploads: logos stored before this check must not block saves.
+ validate :logo_is_small_raster_image, if: -> { attachment_changes.key?("logo") && logo.attached? }
+ # The account sidebar is cached by the accounts' updated_at, which an
+ # attachment alone does not change.
+ before_save { self.updated_at = Time.current if attachment_changes.key?("logo") }
+
+ # The account form saves more than once in one transaction (attribute
+ # locks last), so the domain change is remembered until the commit.
+ after_save { @institution_domain_saved = true if saved_change_to_institution_domain? }
+ after_commit :fetch_logo_for_new_domain
+ after_rollback { @institution_domain_saved = false }
+ end
+
+ # Set when the same save also picks an icon in the form, so an automatic
+ # fetch for the new domain cannot overwrite it.
+ attr_accessor :logo_chosen
+
+ def logo_url
+ if logo_brandfetch? && brandfetch_logo_url
+ brandfetch_logo_url
+ else
+ stored_logo_url || fallback_logo_url
+ end
+ end
+
+ # What shows without a stored logo, and so what removing it brings back.
+ def fallback_logo_url
+ brandfetch_logo_url || provider&.logo_url.presence
+ end
+
+ # A rejected upload re-rendered in the form is attached but unsaved and has no URL yet.
+ def stored_logo_url
+ Rails.application.routes.url_helpers.rails_blob_path(logo, only_path: true) if logo.attached? && logo.blob.persisted?
+ end
+
+ def brandfetch_logo_url
+ return if institution_domain.blank? || Setting.brand_fetch_client_id.blank?
+
+ logo_size = Setting.brand_fetch_logo_size
+ "https://cdn.brandfetch.io/#{institution_domain}/icon/fallback/lettermark/w/#{logo_size}/h/#{logo_size}?c=#{Setting.brand_fetch_client_id}"
+ end
+
+ # Where the stored logo came from: a favicon service, "appstore",
+ # "googleplay" or "rustore", or nil for an upload.
+ def logo_source
+ logo.blob.metadata["logo_source"] if logo.attached?
+ end
+
+ # The Account::LogoFetcher key of the stored logo, e.g. "appstore:123".
+ def logo_key
+ logo.blob.metadata["logo_key"] || logo_source if logo.attached?
+ end
+
+ # Whether the stored logo is the icon with `key` for the current domain,
+ # and, given its `body`, still the same image. Favicon keys name only the
+ # service, so the domain it was fetched for has to match too; icons stored
+ # before that was recorded carry it in their filename ("tbank.ru.png").
+ def stored_logo?(key, body: nil)
+ return false unless logo.attached? && logo_key == key
+ return false if body && logo.blob.checksum != Digest::MD5.base64digest(body)
+
+ (logo.blob.metadata["logo_domain"] || logo.filename.base) == institution_domain
+ end
+
+ def logo_auto?
+ logo.attached? && logo.blob.metadata["logo_auto"] == true
+ end
+
+ # Applies the icon chosen in the account form: an Account::LogoFetcher key,
+ # "brandfetch" or "stored" to switch what is shown without deleting the
+ # stored logo, or "remove", which goes back to the automatic icon (the
+ # fallback, and the nightly fetch). Returns false when the choice could not apply.
+ def choose_logo(choice)
+ case choice
+ when "brandfetch" then brandfetch_logo_url.present? && update!(logo_selection: :brandfetch)
+ when "stored" then logo.attached? && update!(logo_selection: :automatic)
+ when "remove"
+ logo.purge if logo.attached?
+ update!(logo_selection: :automatic, updated_at: Time.current)
+ else Account::LogoFetcher.new(self).fetch(source: choice)
+ end
+ end
+
+ # Sure only picks logos nobody chose: an empty slot or its own earlier pick.
+ def logo_auto_fetchable?
+ institution_domain.present? && logo_automatic? && (!logo.attached? || logo_auto?)
+ end
+
+ private
+ # SVG is excluded: it can carry scripts and is not served inline anyway.
+ def logo_is_small_raster_image
+ unless logo.content_type.in?(LOGO_CONTENT_TYPES)
+ errors.add(:logo, :invalid_content_type)
+ end
+
+ if logo.blob.byte_size > LOGO_MAX_SIZE
+ errors.add(:logo, :too_large, max_size: LOGO_MAX_SIZE / 1.megabyte)
+ end
+ end
+
+ def fetch_logo_for_new_domain
+ domain_saved, @institution_domain_saved = @institution_domain_saved, false
+ return unless domain_saved && !logo_chosen
+
+ # A cleared override may fall back to the provider's domain.
+ if institution_domain.present?
+ AccountLogoFetchJob.perform_paced(self)
+ elsif logo_auto?
+ # The automatic icon belonged to the institution that was removed.
+ logo.purge_later
+ touch
+ end
+ end
+end
diff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rb
index c069c2c907..4494b73763 100644
--- a/app/models/family/data_importer.rb
+++ b/app/models/family/data_importer.rb
@@ -330,6 +330,8 @@ class Family::DataImporter
notes: data["notes"],
status: importable_account_status(data["status"])
)
+ # Older exports predate the choice and keep the account's own.
+ account.logo_selection = data["logo_selection"] if Account.logo_selections.key?(data["logo_selection"])
account.save!
diff --git a/app/views/accounts/_form.html.erb b/app/views/accounts/_form.html.erb
index 60be71cdc1..35ae602c2d 100644
--- a/app/views/accounts/_form.html.erb
+++ b/app/views/accounts/_form.html.erb
@@ -1,4 +1,6 @@
-<%# locals: (account:, url:) %>
+<%# locals: (account:, url:, logo: true) %>
+<%# `logo: false` hides the icon block for forms whose controller does not
+ save it (properties). %>
<% if @error_message.present? %>
<%= render DS::Alert.new(message: @error_message, variant: :error) %>
@@ -45,9 +47,36 @@
label: t(".institution_name_label"),
placeholder: account.provider&.institution_name || t(".institution_name_placeholder") %>
- <%= form.text_field :institution_domain,
- label: t(".institution_domain_label"),
- placeholder: account.provider&.institution_domain || t(".institution_domain_placeholder") %>
+ <div class="space-y-1">
+ <%= form.text_field :institution_domain,
+ label: t(".institution_domain_label"),
+ placeholder: account.provider&.institution_domain || t(".institution_domain_placeholder") %>
+ <p class="text-xs text-secondary" data-testid="institution-domain-hint">
+ <% if Setting.brand_fetch_client_id.present? %>
+ <%= t(".institution_domain_hint") %>
+ <% else %>
+ <%= t(".institution_domain_missing_logo_key_hint") %>
+ <% if self_hosted? && Current.user&.admin? %>
+ <%= link_to t(".institution_domain_settings_link"), settings_hosting_path, class: "underline" %>
+ <% end %>
+ <% end %>
+ </p>
+ </div>
+
+ <% if logo %>
+ <div class="space-y-2"
+ data-controller="account-logo-picker"
+ data-account-logo-picker-pending-value="<%= t("accounts.logo_field.pending") %>"
+ data-account-logo-picker-removal-value="<%= t("accounts.logo_field.removal") %>"
+ data-account-logo-picker-provider-domain-value="<%= account.provider&.institution_domain %>">
+ <%= form.label :logo, t(".logo_label"), class: "form-field__label" %>
+ <%= render "accounts/logo_field", account: account %>
+ <%= hidden_field_tag "#{form.object_name}[logo_choice]", nil, id: nil, data: { account_logo_picker_target: "choice" } %>
+ <%= form.file_field :logo, accept: Account::LOGO_CONTENT_TYPES.join(","), class: "form-field__input",
+ data: { account_logo_picker_target: "file", action: "account-logo-picker#showFile" } %>
+ <p class="text-xs text-secondary"><%= t(".logo_hint") %></p>
+ </div>
+ <% end %>
<%= form.text_area :notes,
label: t(".notes_label"),
@@ -64,3 +93,7 @@
<%= form.submit %>
<% end %>
+
+<% if logo %>
+ <%= render "accounts/logo_forms", account: account %>
+<% end %>
diff --git a/app/views/accounts/_logo.html.erb b/app/views/accounts/_logo.html.erb
index cb82b28ac6..a553f27eba 100644
--- a/app/views/accounts/_logo.html.erb
+++ b/app/views/accounts/_logo.html.erb
@@ -1,4 +1,4 @@
-<%# locals: (account:, size: "md", color: nil) %>
+<%# locals: (account:, size: "md", color: nil, url: account.logo_url) %>
<% size_classes = {
"sm" => "w-6 h-6",
@@ -7,16 +7,26 @@
"full" => "w-full h-full"
} %>
-<% if account.logo_url.present? %>
- <%= image_tag account.logo_url,
- class: "shrink-0 rounded-full #{size_classes[size]}",
- loading: "lazy" %>
+<% initials = {
+ variant: :text,
+ hex_color: color || account.accountable&.color,
+ text: account.name.to_s,
+ size: size,
+ rounded: true
+} %>
+
+<% if url.present? %>
+ <%# The ProviderLogo recipe: the initials sit under the image, and a logo the
+ browser cannot show (an upload whose file is gone, a dead favicon or
+ Brandfetch URL) removes itself to reveal them. %>
+ <%= tag.span class: "relative block shrink-0 #{size_classes[size]}" do %>
+ <%= render DS::FilledIcon.new(**initials, class_name: "absolute inset-0 w-full! h-full!") %>
+ <%= image_tag url,
+ class: "absolute inset-0 w-full h-full rounded-full object-contain bg-container",
+ alt: "",
+ loading: "lazy",
+ onerror: ProviderLogo::REMOVE_ON_ERROR %>
+ <% end %>
<% else %>
- <%= render DS::FilledIcon.new(
- variant: :text,
- hex_color: color || account.accountable&.color,
- text: account.name,
- size: size,
- rounded: true
- ) %>
+ <%= render DS::FilledIcon.new(**initials) %>
<% end %>
diff --git a/app/views/accounts/_logo_field.html.erb b/app/views/accounts/_logo_field.html.erb
new file mode 100644
index 0000000000..190bd1399b
--- /dev/null
+++ b/app/views/accounts/_logo_field.html.erb
@@ -0,0 +1,77 @@
+<%# locals: (account:, candidates: nil) %>
+<%# Sits inside the account form and only previews: the account-logo-picker
+ controller around it (accounts/_form) keeps the choice in a hidden field,
+ and saving the form applies it. "Pick icon" submits the form rendered
+ after the account form (accounts/_logo_forms) through its `form` attribute,
+ with the domain and name currently typed in the account form. %>
+<%= turbo_frame_tag dom_id(account, :logo_field), class: "block space-y-2", data: { testid: "account-logo-field" } do %>
+ <div class="space-y-1" data-account-logo-picker-target="preview">
+ <div data-account-logo-picker-target="image">
+ <%= render "accounts/logo", account: account, size: "lg" %>
+ </div>
+ <p class="text-xs text-secondary" data-account-logo-picker-target="caption"><%= account_logo_caption(account) %></p>
+ </div>
+
+ <%# The shapes the preview switches to: an uploaded file (its src is set
+ in the browser) and, for "Remove", the automatic icon. %>
+ <template data-account-logo-picker-target="blank">
+ <%= render "accounts/logo", account: account, size: "lg", url: "data:," %>
+ </template>
+ <% if account.logo.attached? %>
+ <template data-account-logo-picker-target="fallback">
+ <%= render "accounts/logo", account: account, size: "lg", url: account.fallback_logo_url %>
+ </template>
+ <% end %>
+
+ <div class="flex flex-wrap items-center gap-2">
+ <%= render DS::Button.new(
+ text: t("accounts.logo_field.pick"),
+ variant: :outline,
+ size: :sm,
+ icon: "images",
+ type: "submit",
+ form: dom_id(account, :logo_options),
+ # The account form opts out of Turbo; this submit must stay in it to fill the logo frame.
+ data: { turbo: true, action: "account-logo-picker#search", account_logo_picker_target: "pick",
+ turbo_submits_with: t("accounts.logo_field.searching") }
+ ) %>
+ <% if account.logo.attached? %>
+ <%= render DS::Button.new(
+ text: t("accounts.logo_field.remove"),
+ variant: :outline,
+ size: :sm,
+ icon: "trash-2",
+ type: "button",
+ data: { action: "account-logo-picker#remove" }
+ ) %>
+ <% end %>
+ </div>
+
+ <p class="text-xs text-secondary hidden" data-account-logo-picker-target="pickHint"><%= t("accounts.logo_field.domain_needed") %></p>
+
+ <% if candidates %>
+ <% options = account_logo_options(account, candidates) %>
+ <% if options.empty? %>
+ <p class="text-xs text-secondary"><%= t("accounts.logo_field.empty") %></p>
+ <% else %>
+ <div class="grid grid-cols-3 sm:grid-cols-4 gap-2">
+ <% options.each do |option| %>
+ <%= tag.button type: "button", title: option.title,
+ data: {
+ account_logo_picker_target: "option",
+ action: "account-logo-picker#choose",
+ account_logo_picker_choice_param: (option.source unless option.current),
+ account_logo_picker_label_param: option.label
+ },
+ class: "flex flex-col items-center gap-1 p-2 rounded-lg border min-w-0 hover:bg-surface-hover cursor-pointer #{option.current ? "border-primary" : "border-secondary"}" do %>
+ <%= render "accounts/logo", account: account, size: "lg", url: option.src %>
+ <span class="text-xs text-primary truncate w-full text-center"><%= option.label %></span>
+ <span class="text-xs text-secondary truncate w-full text-center">
+ <%= option.current ? t("accounts.logo_field.current") : option.detail %>
+ </span>
+ <% end %>
+ <% end %>
+ </div>
+ <% end %>
+ <% end %>
+<% end %>
diff --git a/app/views/accounts/_logo_forms.html.erb b/app/views/accounts/_logo_forms.html.erb
new file mode 100644
index 0000000000..b49c908999
--- /dev/null
+++ b/app/views/accounts/_logo_forms.html.erb
@@ -0,0 +1,9 @@
+<%# locals: (account:) %>
+<%# Target of the "Pick icon" button in accounts/_logo_field. It lives outside
+ the account form because forms cannot nest, and loads the icons into the
+ logo frame only. The account-logo-picker controller fills in the domain
+ and name typed in the account form before it submits. %>
+<%= form_with url: account.persisted? ? logo_options_account_path(account) : logo_options_accounts_path, method: :get, id: dom_id(account, :logo_options), class: "hidden", data: { turbo_frame: dom_id(account, :logo_field) } do %>
+ <%= hidden_field_tag :institution_domain, account.institution_domain, id: nil %>
+ <%= hidden_field_tag :institution_name, account.institution_name, id: nil %>
+<% end %>
diff --git a/app/views/properties/_form.html.erb b/app/views/properties/_form.html.erb
index e81b38b75c..196ebe48de 100644
--- a/app/views/properties/_form.html.erb
+++ b/app/views/properties/_form.html.erb
@@ -1,6 +1,6 @@
<%# locals: (account:, url:) %>
-<%= render "accounts/form", account: account, url: url do |form| %>
+<%= render "accounts/form", account: account, url: url, logo: false do |form| %>
<%= form.select :subtype,
Property.subtype_options_for_select,
{ label: true, prompt: t("properties.form.subtype_prompt"), include_blank: t("properties.form.none") } %>
diff --git a/config/locales/models/account/en.yml b/config/locales/models/account/en.yml
index e7ca999cb3..9c09be4b2e 100644
--- a/config/locales/models/account/en.yml
+++ b/config/locales/models/account/en.yml
@@ -23,8 +23,16 @@ en:
currency: Currency
family: "%{moniker}"
family_id: "%{moniker}"
+ logo: Logo
name: Name
subtype: Subtype
+ errors:
+ models:
+ account:
+ attributes:
+ logo:
+ invalid_content_type: must be a PNG, JPEG, GIF, WebP or ICO image
+ too_large: must be smaller than %{max_size} MB
models:
account: Account
account/credit: Credit Card
diff --git a/config/locales/models/account/ru.yml b/config/locales/models/account/ru.yml
index 06415f5709..1c74bb4bc5 100644
--- a/config/locales/models/account/ru.yml
+++ b/config/locales/models/account/ru.yml
@@ -20,8 +20,16 @@ ru:
currency: Валюта
family: "%{moniker}"
family_id: "%{moniker}"
+ logo: Иконка
name: Имя
subtype: Подтип
+ errors:
+ models:
+ account:
+ attributes:
+ logo:
+ invalid_content_type: должна быть изображением PNG, JPEG, GIF, WebP или ICO
+ too_large: должна быть меньше %{max_size} МБ
models:
account: Счёт
account/credit: Кредитная карта
diff --git a/config/locales/views/accounts/en.yml b/config/locales/views/accounts/en.yml
index aecdacf2a2..51bb643f0c 100644
--- a/config/locales/views/accounts/en.yml
+++ b/config/locales/views/accounts/en.yml
@@ -28,6 +28,36 @@ en:
data_not_available: Data not available for the selected period
create:
success: "%{type} account created"
+ logo_caption:
+ appstore: From the App Store
+ brandfetch: From Brandfetch
+ duckduckgo: From DuckDuckGo
+ google: From Google
+ googleplay: From Google Play
+ none: No icon yet
+ rustore: From RuStore
+ uploaded: Uploaded by you
+ yandex: From Yandex
+ logo_field:
+ current: current
+ domain_needed: Enter the institution domain, such as tbank.ru, to pick an icon.
+ empty: No icons found for this domain. Upload your own below.
+ pick: Pick icon
+ pending: Applied when you save
+ remove: Remove
+ removal: Removed when you save; the automatic icon comes back
+ searching: Searching…
+ logo_options:
+ size: "%{size} px"
+ sources:
+ appstore: App Store
+ brandfetch: Brandfetch
+ duckduckgo: DuckDuckGo
+ google: Google
+ googleplay: Google Play
+ rustore: RuStore
+ yandex: Yandex
+ stored: Saved icon
set_default:
depository_only: "Only cash and credit card accounts can be set as default."
destroy:
@@ -48,6 +78,11 @@ en:
institution_name_placeholder: e.g., Chase Bank
institution_domain_label: Institution domain
institution_domain_placeholder: e.g., chase.com
+ institution_domain_hint: Used to find the institution's icon.
+ institution_domain_missing_logo_key_hint: Used to find the institution's icon. Brandfetch logos are not available because no Brandfetch client ID is configured.
+ institution_domain_settings_link: Add one in Self-Hosting settings
+ logo_label: Icon
+ logo_hint: Or upload your own PNG, JPEG, GIF, WebP or ICO image up to 1 MB. It replaces the Brandfetch logo.
notes_label: Notes
notes_placeholder: Store additional information like account numbers, sort codes, IBAN, routing numbers, etc.
exclude_from_reports: Exclude from all reports
@@ -133,6 +168,7 @@ en:
include_in_reports: Include in reports
update:
success: "%{type} account updated"
+ logo_not_applied: The account was saved, but the chosen icon could not be downloaded. Try again or upload your own.
sidebar:
missing_data: Missing historical data
missing_data_description: "%{product} uses third party providers to fetch historical exchange rates, security prices, and more. This data is required to calculate accurate historical account balances."
diff --git a/config/locales/views/accounts/ru.yml b/config/locales/views/accounts/ru.yml
index 8fe6c7f6da..2c5cf8d43e 100644
--- a/config/locales/views/accounts/ru.yml
+++ b/config/locales/views/accounts/ru.yml
@@ -54,6 +54,11 @@ ru:
exclude_from_reports: Исключить из всех отчётов
institution_domain_label: Домен учреждения
institution_domain_placeholder: например, sberbank.ru
+ institution_domain_hint: Используется, чтобы найти иконку учреждения.
+ institution_domain_missing_logo_key_hint: Используется, чтобы найти иконку учреждения. Логотипы Brandfetch недоступны, потому что не задан Client ID Brandfetch.
+ institution_domain_settings_link: Задать в настройках Self-Hosting
+ logo_label: Иконка
+ logo_hint: Или загрузите свою картинку PNG, JPEG, GIF, WebP или ICO до 1 МБ. Она заменяет логотип Brandfetch.
institution_name_label: Название учреждения
institution_name_placeholder: например, Сбербанк
name_label: Название счёта
@@ -93,6 +98,36 @@ ru:
description: Выберите, какого провайдера вы хотите использовать для связи %{account_name}
no_providers: В настоящее время провайдеры не настроены
title: Выберите провайдера для связи
+ logo_caption:
+ appstore: Из App Store
+ brandfetch: Из Brandfetch
+ duckduckgo: Из DuckDuckGo
+ google: Из Google
+ googleplay: Из Google Play
+ none: Иконки пока нет
+ rustore: Из RuStore
+ uploaded: Загружена вами
+ yandex: Из Яндекса
+ logo_field:
+ current: сейчас
+ domain_needed: Введите домен учреждения, например tbank.ru, чтобы подобрать иконку.
+ empty: Для этого домена иконок не нашлось. Загрузите свою ниже.
+ pick: Подобрать иконку
+ pending: Применится после сохранения
+ remove: Удалить
+ removal: Удалится после сохранения, вернётся автоматическая иконка
+ searching: Ищем…
+ logo_options:
+ size: "%{size} px"
+ sources:
+ appstore: App Store
+ brandfetch: Brandfetch
+ duckduckgo: DuckDuckGo
+ google: Google
+ googleplay: Google Play
+ rustore: RuStore
+ yandex: Яндекс
+ stored: Сохранённая иконка
set_default:
depository_only: По умолчанию можно установить только денежные счета и счета
кредитных карт.
@@ -212,6 +247,7 @@ ru:
success: Счёт успешно отвязан. Теперь это ручной счёт.
update:
success: Счёт %{type} обновлён
+ logo_not_applied: Счёт сохранён, но выбранную иконку скачать не удалось. Попробуйте ещё раз или загрузите свою.
email_confirmations:
new:
invalid_token: Неверная или истекшая ссылка подтверждения.
diff --git a/config/routes.rb b/config/routes.rb
index f05d9701cf..960bfbe1d8 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -705,6 +705,7 @@ Rails.application.routes.draw do
resources :accounts, only: %i[index new show destroy], shallow: true do
member do
post :sync
+ get :logo_options
get :sparkline
patch :toggle_active
patch :toggle_exclude_from_reports
@@ -718,6 +719,7 @@ Rails.application.routes.draw do
collection do
post :sync_all
+ get :logo_options, action: :new_logo_options
patch :reorder
end
diff --git a/config/schedule.yml b/config/schedule.yml
index 5d76d1c5d3..ea00d3227c 100644
--- a/config/schedule.yml
+++ b/config/schedule.yml
@@ -101,3 +101,10 @@ refresh_maintained_goal_targets:
active_job: true
queue: "scheduled"
description: "Recomputes the floor of reserves expressed in months of expenses"
+
+backfill_account_logos:
+ cron: "30 3 * * *" # 3:30 AM every day
+ class: "AccountLogoBackfillJob"
+ active_job: true
+ queue: "scheduled"
+ description: "Fetches icons for accounts with an institution domain and no logo"
diff --git a/db/migrate/20261030120000_add_logo_selection_to_accounts.rb b/db/migrate/20261030120000_add_logo_selection_to_accounts.rb
new file mode 100644
index 0000000000..8ff756f298
--- /dev/null
+++ b/db/migrate/20261030120000_add_logo_selection_to_accounts.rb
@@ -0,0 +1,9 @@
+# Which icon an account shows: "automatic" is the stored logo, then the
+# Brandfetch one, then the provider's; "brandfetch" shows Brandfetch over the
+# stored logo, which is kept to switch back to. The enum in Account::Logoable
+# lists the values; a string, so a new source needs no schema change.
+class AddLogoSelectionToAccounts < ActiveRecord::Migration[8.1]
+ def change
+ add_column :accounts, :logo_selection, :string, default: "automatic", null: false
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 270850daaa..6692a18228 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -113,6 +113,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_31_120000) do
t.string "institution_domain"
t.string "institution_name"
t.jsonb "locked_attributes", default: {}
+ t.string "logo_selection", default: "automatic", null: false
t.string "name"
t.text "notes"
t.uuid "owner_id"
diff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rb
index ecd44ee79b..2b994573ef 100644
--- a/test/controllers/accounts_controller_test.rb
+++ b/test/controllers/accounts_controller_test.rb
@@ -1427,6 +1427,73 @@ class AccountsControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to account_url(accounts(:credit_card))
end
+ test "logo_options shows the icons found and Brandfetch inside the logo frame without saving" do
+ Setting.stubs(:brand_fetch_client_id).returns("test-client-id")
+ @account.update!(institution_domain: "krungsri.com")
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "krungsri.com.png",
+ metadata: { "logo_source" => "yandex", "logo_key" => "yandex", "logo_auto" => true })
+ icons = [ logo_icon("appstore:123", "appstore", 512, name: "krungsri"),
+ logo_icon("yandex", "yandex", 120, body: file_fixture("square-placeholder.png").binread) ]
+ Account::LogoFetcher.any_instance.stubs(:candidates).returns(icons)
+
+ get logo_options_account_url(@account), headers: { "Turbo-Frame" => dom_id(@account, :logo_field) }
+
+ assert_response :success
+ assert_select "turbo-frame##{dom_id(@account, :logo_field)}"
+ assert_select "button[type=button][data-account-logo-picker-choice-param='appstore:123'][title=krungsri]"
+ assert_select "button[type=button][data-account-logo-picker-choice-param=brandfetch]"
+ assert_select "button[type=button][data-account-logo-picker-choice-param]", 2, "the current icon only resets the choice"
+ assert_select "button[type=submit]:not([form])", 0, "choosing an icon saves nothing"
+ assert_select "img[src^='data:image/png;base64,']", 2
+ end
+
+ test "logo_options searches the domain typed in the form without saving it" do
+ @account.update!(institution_domain: "tbank.ru")
+ Account::LogoFetcher.expects(:new).with { |account| account.institution_domain == "krungsri.com" && account.institution_name == "Krungsri" }
+ .returns(stub(candidates: []))
+
+ get logo_options_account_url(@account), params: { institution_domain: "https://www.krungsri.com/", institution_name: "Krungsri" },
+ headers: { "Turbo-Frame" => dom_id(@account, :logo_field) }
+
+ assert_response :success
+ assert_equal "tbank.ru", @account.reload.institution_domain
+ end
+
+ test "logo_options for a new account searches the typed domain" do
+ Account::LogoFetcher.expects(:new).with { |account| account.new_record? && account.institution_domain == "krungsri.com" }
+ .returns(stub(candidates: []))
+
+ get logo_options_accounts_url, params: { institution_domain: "krungsri.com", institution_name: "Krungsri" },
+ headers: { "Turbo-Frame" => "logo_field_account" }
+
+ assert_response :success
+ assert_select "turbo-frame#logo_field_account"
+ end
+
+ test "logo_options keeps an icon selectable when its source now serves a different image" do
+ @account.update!(institution_domain: "krungsri.com")
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "krungsri.com.png",
+ metadata: { "logo_source" => "yandex", "logo_key" => "yandex", "logo_auto" => true })
+ Account::LogoFetcher.any_instance.stubs(:candidates).returns([ logo_icon("yandex", "yandex", 120) ])
+
+ get logo_options_account_url(@account), headers: { "Turbo-Frame" => dom_id(@account, :logo_field) }
+
+ assert_select "button[data-account-logo-picker-choice-param=yandex]"
+ end
+
+ test "logo_options outside the frame goes to the account" do
+ get logo_options_account_url(@account)
+
+ assert_redirected_to account_url(@account)
+ end
+
+ test "logo_options requires write permission" do
+ sign_in users(:family_member)
+
+ get logo_options_account_url(accounts(:credit_card))
+ assert_redirected_to account_url(accounts(:credit_card))
+ end
+
test "select_provider shows available providers" do
get select_provider_account_url(@account)
assert_response :success
@@ -1665,6 +1732,10 @@ class AccountsControllerTest < ActionDispatch::IntegrationTest
end
private
+ def logo_icon(key, source, size, name: nil, body: "\x89PNG".b)
+ Account::LogoFetcher::Icon.new(key:, source:, name:, body:, size:, content_type: "image/png", extension: "png")
+ end
+
# #3630. Links a shared and an unshared account to +item+ through two fresh
# provider rows built by the block, and returns them in that order. Shares
# are reset first so the member's access is exactly the one granted here.
diff --git a/test/controllers/depositories_controller_test.rb b/test/controllers/depositories_controller_test.rb
index 5a33bb11ce..40f8e91009 100644
--- a/test/controllers/depositories_controller_test.rb
+++ b/test/controllers/depositories_controller_test.rb
@@ -2,6 +2,7 @@ require "test_helper"
class DepositoriesControllerTest < ActionDispatch::IntegrationTest
include AccountableResourceInterfaceTest
+ include ActionView::RecordIdentifier
setup do
sign_in @user = users(:family_admin)
@@ -137,4 +138,181 @@ class DepositoriesControllerTest < ActionDispatch::IntegrationTest
assert_response :success
assert_select "a[href=?]", new_depository_path, count: 1
end
+
+ test "edit form explains the institution domain and links to Brandfetch settings when the key is missing" do
+ Setting.stubs(:brand_fetch_client_id).returns(nil)
+
+ with_self_hosting do
+ get edit_account_url(@account)
+ end
+
+ assert_response :success
+ assert_select "[data-testid=institution-domain-hint]", text: /Brandfetch/
+ assert_select "[data-testid=institution-domain-hint] a[href=?]", settings_hosting_path
+ end
+
+ test "edit form only explains the institution domain when Brandfetch is configured" do
+ Setting.stubs(:brand_fetch_client_id).returns("test-client-id")
+
+ get edit_account_url(@account)
+
+ assert_response :success
+ assert_select "[data-testid=institution-domain-hint]", text: I18n.t("accounts.form.institution_domain_hint")
+ assert_select "[data-testid=institution-domain-hint] a", 0
+ end
+
+ test "update uploads a logo that replaces Brandfetch" do
+ @account.update!(logo_selection: "brandfetch")
+
+ patch depository_path(@account), params: {
+ account: { logo: fixture_file_upload("square-placeholder.png", "image/png") }
+ }
+
+ assert_redirected_to account_path(@account)
+ assert @account.reload.logo.attached?
+ assert @account.logo_automatic?, "an upload is shown instead of Brandfetch"
+ end
+
+ test "update rejects a logo that is not an image" do
+ patch depository_path(@account), params: {
+ account: { logo: fixture_file_upload("test.txt", "text/plain") }
+ }
+
+ assert_response :unprocessable_entity
+ assert_not @account.reload.logo.attached?
+ end
+
+ test "update applies the icon chosen in the form" do
+ Account::LogoFetcher.any_instance.expects(:fetch).with(source: "appstore:123").returns(true)
+
+ patch depository_path(@account), params: { account: { name: "Renamed", logo_choice: "appstore:123" } }
+
+ assert_redirected_to account_path(@account)
+ assert_equal "Renamed", @account.reload.name
+ assert_nil flash[:alert]
+ end
+
+ test "create with an institution domain fetches an icon for the new account" do
+ assert_enqueued_with(job: AccountLogoFetchJob) do
+ post depositories_path, params: {
+ account: { name: "Krungsri savings", balance: 100, currency: "USD", accountable_type: "Depository",
+ institution_domain: "https://www.krungsri.com/", accountable_attributes: { subtype: "savings" } }
+ }
+ end
+
+ assert_equal "krungsri.com", Account.order(:created_at).last.read_attribute(:institution_domain)
+ end
+
+ test "create applies the icon picked in the new account form instead of fetching one" do
+ Account::LogoFetcher.any_instance.expects(:fetch).with(source: "appstore:1").returns(true)
+
+ assert_no_enqueued_jobs only: AccountLogoFetchJob do
+ post depositories_path, params: { account: { name: "Krungsri savings", balance: 100, currency: "USD", accountable_type: "Depository",
+ institution_domain: "krungsri.com", accountable_attributes: { subtype: "savings" } }.merge(logo_choice: "appstore:1") }
+ end
+
+ assert_redirected_to account_path(Account.order(:created_at).last)
+ assert_nil flash[:alert]
+ end
+
+ test "create attaches an icon uploaded in the new account form" do
+ post depositories_path, params: { account: { name: "Krungsri savings", balance: 100, currency: "USD", accountable_type: "Depository",
+ institution_domain: "krungsri.com", accountable_attributes: { subtype: "savings" } }.merge(logo: fixture_file_upload("square-placeholder.png", "image/png")) }
+
+ assert Account.order(:created_at).last.logo.attached?
+ end
+
+ test "new account form offers the picker without an account id" do
+ get new_depository_path
+
+ assert_response :success
+ assert_select "[data-controller=account-logo-picker] button[form=?]", "logo_options_account"
+ assert_select "form#logo_options_account[action=?][data-turbo-frame=?]", logo_options_accounts_path, "logo_field_account"
+ end
+
+ test "update with a chosen icon skips the automatic fetch for a new domain" do
+ Account::LogoFetcher.any_instance.expects(:fetch).with(source: "yandex").returns(true)
+
+ assert_no_enqueued_jobs only: AccountLogoFetchJob do
+ patch depository_path(@account), params: { account: { institution_domain: "krungsri.com", logo_choice: "yandex" } }
+ end
+
+ assert_redirected_to account_path(@account)
+ end
+
+ test "update without a chosen icon fetches one for a new domain" do
+ assert_enqueued_with(job: AccountLogoFetchJob) do
+ patch depository_path(@account), params: { account: { institution_domain: "krungsri.com" } }
+ end
+ end
+
+ test "update saves the account when the chosen icon cannot be downloaded" do
+ Account::LogoFetcher.any_instance.expects(:fetch).returns(false)
+
+ patch depository_path(@account), params: { account: { name: "Renamed", logo_choice: "yandex" } }
+
+ assert_redirected_to account_path(@account)
+ assert_equal "Renamed", @account.reload.name
+ assert_equal I18n.t("accounts.update.logo_not_applied"), flash[:alert]
+ end
+
+ test "update falls back to the paced automatic fetch when the chosen icon fails for a new domain" do
+ Account::LogoFetcher.any_instance.expects(:fetch).returns(false)
+ AccountLogoFetchJob.expects(:perform_paced).once
+
+ patch depository_path(@account), params: { account: { institution_domain: "krungsri.com", logo_choice: "yandex" } }
+
+ assert_redirected_to account_path(@account)
+ end
+
+ test "update lets an upload win over an icon chosen in the same form" do
+ Account::LogoFetcher.any_instance.expects(:fetch).never
+
+ patch depository_path(@account), params: {
+ account: { logo: fixture_file_upload("square-placeholder.png", "image/png"), logo_choice: "yandex" }
+ }
+
+ assert_redirected_to account_path(@account)
+ assert @account.reload.logo.attached?
+ end
+
+ test "update leaves the icon alone when the form fails" do
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "mine.png")
+
+ patch depository_path(@account), params: { account: { name: "", logo_choice: "remove" } }
+
+ assert_response :unprocessable_entity
+ assert @account.reload.logo.attached?
+ end
+
+ test "edit form previews the icon and keeps the choice for saving" do
+ @account.update!(institution_domain: "tbank.ru")
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "mine.png")
+
+ get edit_account_url(@account)
+
+ assert_response :success
+ frame = dom_id(@account, :logo_field)
+ assert_select "[data-controller=account-logo-picker]" do
+ assert_select "turbo-frame##{frame}" do
+ assert_select "button[form=?][data-action='account-logo-picker#search'][data-turbo=true]", dom_id(@account, :logo_options)
+ assert_select "button[type=button][data-action='account-logo-picker#remove']"
+ assert_select "template[data-account-logo-picker-target=fallback]"
+ end
+ assert_select "input[type=hidden][name='account[logo_choice]'][data-account-logo-picker-target=choice]"
+ assert_select "input[type=file][name='account[logo]'][data-account-logo-picker-target=file]"
+ end
+ assert_select "form[id=?][action=?][method=get][data-turbo-frame=?]", dom_id(@account, :logo_options), logo_options_account_path(@account), frame do
+ assert_select "input[type=hidden][name=institution_domain][value=?]", "tbank.ru"
+ assert_select "input[type=hidden][name=institution_name]"
+ end
+ end
+
+ test "edit form offers the picker before a domain is saved" do
+ @account.update!(institution_domain: nil)
+
+ get edit_account_url(@account)
+
+ assert_select "button[form=?]", dom_id(@account, :logo_options)
+ end
end
diff --git a/test/controllers/properties_controller_test.rb b/test/controllers/properties_controller_test.rb
index 7ac0d0ca2c..b51ca1f42c 100644
--- a/test/controllers/properties_controller_test.rb
+++ b/test/controllers/properties_controller_test.rb
@@ -553,6 +553,14 @@ class PropertiesControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to new_property_path
end
+ test "edit form leaves out the icon picker, which property updates do not save" do
+ get edit_property_url(@account)
+
+ assert_response :success
+ assert_select "[data-controller=account-logo-picker]", 0
+ assert_select "form##{dom_id(@account, :logo_options)}", 0
+ end
+
# Chimnie (UK, UPRN-based) lookups
def chimnie_avm_response
diff --git a/test/helpers/accounts_helper_test.rb b/test/helpers/accounts_helper_test.rb
index 20fdd28f53..34dae77ed0 100644
--- a/test/helpers/accounts_helper_test.rb
+++ b/test/helpers/accounts_helper_test.rb
@@ -1,13 +1,50 @@
require "test_helper"
class AccountsHelperTest < ActionView::TestCase
+ include AccountsHelper
+
setup do
@user = users(:family_admin)
Current.session = @user.sessions.create!
+ @family = @user.family
end
teardown { Current.session = nil }
+ test "sidebar cache key changes with the Brandfetch client id" do
+ Setting.stubs(:brand_fetch_client_id).returns(nil)
+ without_key = account_sidebar_tabs_cache_key(family: @family, active_tab: "all", mobile: false)
+
+ Setting.stubs(:brand_fetch_client_id).returns("test-client-id")
+ with_key = account_sidebar_tabs_cache_key(family: @family, active_tab: "all", mobile: false)
+
+ assert_not_equal without_key, with_key
+
+ Setting.stubs(:brand_fetch_client_id).returns("other-client-id")
+ other_key = account_sidebar_tabs_cache_key(family: @family, active_tab: "all", mobile: false)
+ assert_not_equal with_key, other_key
+
+ Setting.stubs(:brand_fetch_logo_size).returns(120)
+ assert_not_equal other_key, account_sidebar_tabs_cache_key(family: @family, active_tab: "all", mobile: false)
+ end
+
+ test "logo caption names where the shown icon comes from" do
+ account = accounts(:depository)
+ account.update!(institution_domain: "tbank.ru")
+ Setting.stubs(:brand_fetch_client_id).returns(nil)
+ assert_equal I18n.t("accounts.logo_caption.none"), account_logo_caption(account)
+
+ Setting.stubs(:brand_fetch_client_id).returns("test-client-id")
+ assert_equal I18n.t("accounts.logo_caption.brandfetch"), account_logo_caption(account)
+
+ account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "tbank.ru.png",
+ metadata: { "logo_source" => "yandex", "logo_auto" => true })
+ assert_equal I18n.t("accounts.logo_caption.yandex"), account_logo_caption(account)
+
+ account.update!(logo_selection: "brandfetch")
+ assert_equal I18n.t("accounts.logo_caption.brandfetch"), account_logo_caption(account)
+ end
+
test "sidebar cache key changes with the account order" do
@user.update!(default_account_order: "name_asc")
name_key = sidebar_key
diff --git a/test/jobs/account_logo_backfill_job_test.rb b/test/jobs/account_logo_backfill_job_test.rb
new file mode 100644
index 0000000000..8f716aec08
--- /dev/null
+++ b/test/jobs/account_logo_backfill_job_test.rb
@@ -0,0 +1,38 @@
+require "test_helper"
+
+class AccountLogoBackfillJobTest < ActiveJob::TestCase
+ test "queues a fetch for visible accounts with a domain and no logo" do
+ Account.update_all(institution_domain: nil)
+ without_logo = accounts(:depository)
+ without_logo.update_columns(institution_domain: "tbank.ru")
+ with_logo = accounts(:credit_card)
+ with_logo.update_columns(institution_domain: "sberbank.ru")
+ with_logo.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "mine.png")
+
+ AccountLogoBackfillJob.perform_now
+
+ assert_enqueued_jobs 1, only: AccountLogoFetchJob
+ assert_enqueued_with(job: AccountLogoFetchJob, args: [ without_logo ])
+ end
+
+ test "queues a bounded batch per run and continues from where it stopped" do
+ Account.update_all(institution_domain: nil)
+ first, second = [ accounts(:depository), accounts(:credit_card) ].sort_by(&:id)
+ [ first, second ].each { |account| account.update_columns(institution_domain: "tbank.ru") }
+ cache = ActiveSupport::Cache::MemoryStore.new
+ Rails.stubs(:cache).returns(cache)
+
+ AccountLogoBackfillJob.perform_now(batch_size: 1)
+ assert_enqueued_with(job: AccountLogoFetchJob, args: [ first ])
+ clear_enqueued_jobs
+
+ AccountLogoBackfillJob.perform_now(batch_size: 1)
+ assert_enqueued_jobs 1, only: AccountLogoFetchJob
+ assert_enqueued_with(job: AccountLogoFetchJob, args: [ second ])
+ clear_enqueued_jobs
+
+ AccountLogoBackfillJob.perform_now(batch_size: 1)
+ # Starts over after the last batch.
+ assert_enqueued_with(job: AccountLogoFetchJob, args: [ first ])
+ end
+end
diff --git a/test/jobs/account_logo_fetch_job_test.rb b/test/jobs/account_logo_fetch_job_test.rb
new file mode 100644
index 0000000000..def60aaa95
--- /dev/null
+++ b/test/jobs/account_logo_fetch_job_test.rb
@@ -0,0 +1,106 @@
+require "test_helper"
+
+class AccountLogoFetchJobTest < ActiveJob::TestCase
+ setup do
+ @account = accounts(:depository)
+ @account.update_columns(institution_domain: "tbank.ru")
+ end
+
+ test "paces fetches queued together" do
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+
+ travel_to Time.zone.at(1_800_000_000) do
+ 3.times { AccountLogoFetchJob.perform_paced(@account) }
+
+ assert_equal [ 0, 20, 40 ], enqueued_waits
+ end
+ end
+
+ test "keeps pacing after a minute while earlier slots are still pending" do
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+
+ travel_to Time.zone.at(1_800_000_000)
+ 10.times { AccountLogoFetchJob.perform_paced(@account) }
+ clear_enqueued_jobs
+
+ travel 90.seconds
+ AccountLogoFetchJob.perform_paced(@account)
+
+ assert_equal [ 110 ], enqueued_waits
+ end
+
+ test "does not reuse a slot claimed by another worker" do
+ cache = ActiveSupport::Cache::MemoryStore.new
+ Rails.stubs(:cache).returns(cache)
+
+ travel_to Time.zone.at(1_800_000_000) do
+ cache.write("#{AccountLogoFetchJob::PACE_KEY}:#{1_800_000_000 / 20}", true)
+ AccountLogoFetchJob.perform_paced(@account)
+
+ assert_equal [ 20 ], enqueued_waits
+ end
+ end
+
+ test "fetches at once after a bounded number of probes when the cache refuses every claim" do
+ cache = ActiveSupport::Cache::MemoryStore.new
+ cache.expects(:write).times(AccountLogoFetchJob::MAX_SLOT_PROBES).returns(false)
+ Rails.stubs(:cache).returns(cache)
+
+ travel_to Time.zone.at(1_800_000_000) do
+ AccountLogoFetchJob.perform_paced(@account)
+
+ assert_equal [ 0 ], enqueued_waits
+ end
+ end
+
+ test "picks a logo automatically" do
+ Account::LogoFetcher.any_instance.expects(:fetch).with(auto: true).returns(true)
+
+ AccountLogoFetchJob.perform_now(@account)
+ end
+
+ test "drops the old domain's automatic icon when nothing is found for the new one" do
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "sberbank.ru.png",
+ metadata: { "logo_source" => "google", "logo_key" => "google", "logo_auto" => true })
+ Account::LogoFetcher.any_instance.expects(:fetch).returns(false)
+
+ AccountLogoFetchJob.perform_now(@account)
+
+ assert_not @account.reload.logo.attached?
+ end
+
+ test "keeps the old automatic icon when Brandfetch was chosen during the search" do
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "sberbank.ru.png",
+ metadata: { "logo_source" => "google", "logo_key" => "google", "logo_auto" => true })
+ Account::LogoFetcher.any_instance.stubs(:fetch).with do
+ Account.find(@account.id).update!(logo_selection: "brandfetch")
+ true
+ end.returns(false)
+
+ AccountLogoFetchJob.perform_now(@account)
+
+ assert @account.reload.logo.attached?
+ end
+
+ test "keeps the automatic icon of the same domain when a refetch finds nothing" do
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "tbank.ru.png",
+ metadata: { "logo_source" => "google", "logo_key" => "google", "logo_auto" => true })
+ Account::LogoFetcher.any_instance.expects(:fetch).returns(false)
+
+ AccountLogoFetchJob.perform_now(@account)
+
+ assert @account.reload.logo.attached?
+ end
+
+ test "leaves a logo the user uploaded" do
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "mine.png")
+ Account::LogoFetcher.any_instance.expects(:fetch).never
+
+ AccountLogoFetchJob.perform_now(@account)
+ end
+
+ private
+ def enqueued_waits
+ enqueued_jobs.map { |job| ((job[:at] || Time.current.to_f) - Time.current.to_f).round }
+ end
+end
diff --git a/test/models/account/logo_fetcher/app_store_test.rb b/test/models/account/logo_fetcher/app_store_test.rb
new file mode 100644
index 0000000000..cae074faac
--- /dev/null
+++ b/test/models/account/logo_fetcher/app_store_test.rb
@@ -0,0 +1,54 @@
+require "test_helper"
+
+class Account::LogoFetcher::AppStoreTest < ActiveSupport::TestCase
+ ARTWORK = "https://is1-ssl.mzstatic.com/image/thumb/krungsri/512x512bb.jpg"
+
+ setup do
+ @store = Account::LogoFetcher::AppStore.new(domain: "krungsri.com", term: "Krungsri", countries: %w[th us], client: Account::LogoFetcher::Client.new)
+ stub_request(:get, ARTWORK).to_return(status: 200, body: png(512))
+ end
+
+ test "returns icons of the institution's own apps only" do
+ stub_search("th", [ app(1, "krungsri", "https://www.krungsri.com"), app(2, "UCHOOSE", "https://www.krungsriconsumer.com") ])
+ stub_search("us", [ app(1, "krungsri", "https://www.krungsri.com"), app(3, "GO by Krungsri Auto", nil) ])
+
+ icons = @store.icons
+
+ assert_equal [ "appstore:1" ], icons.map(&:key)
+ assert_equal [ 512, "appstore", "krungsri" ], [ icons.first.size, icons.first.source, icons.first.name ]
+ end
+
+ test "looks an app up by id and still checks its developer" do
+ stub_request(:get, "https://itunes.apple.com/lookup?country=th&id=1").to_return(status: 200, body: { results: [ app(1, "krungsri", "https://www.krungsri.com") ] }.to_json)
+ stub_request(:get, "https://itunes.apple.com/lookup?country=th&id=2").to_return(status: 200, body: { results: [ app(2, "Other", "https://other.com") ] }.to_json)
+ stub_request(:get, "https://itunes.apple.com/lookup?country=us&id=2").to_return(status: 200, body: { results: [] }.to_json)
+ stub_request(:get, "https://itunes.apple.com/lookup?country=us&id=1").to_return(status: 200, body: { results: [] }.to_json)
+
+ assert_equal "appstore:1", @store.icon("1").key
+ assert_nil @store.icon("2")
+ assert_nil @store.icon("../1")
+ end
+
+ test "ignores artwork outside Apple's image hosts" do
+ stub_search("th", [ app(1, "krungsri", "https://www.krungsri.com", artwork: "https://evil.example/icon.png") ])
+ stub_search("us", [])
+
+ assert_empty @store.icons
+ end
+
+ private
+ def app(id, name, seller_url, artwork: ARTWORK)
+ { trackId: id, trackName: name, sellerUrl: seller_url, artworkUrl512: artwork }
+ end
+
+ def stub_search(country, apps)
+ stub_request(:get, "https://itunes.apple.com/search")
+ .with(query: hash_including(country: country, term: "Krungsri"))
+ .to_return(status: 200, body: { results: apps }.to_json)
+ end
+
+ def png(size)
+ "\x89PNG\r\n\x1a\n".b + [ 13 ].pack("N") + "IHDR" + [ size, size ].pack("NN") + "\x08\x06\x00\x00\x00".b + "\x00" * 4 +
+ [ 0 ].pack("N") + "IEND\xAEB`\x82".b
+ end
+end
diff --git a/test/models/account/logo_fetcher/google_play_test.rb b/test/models/account/logo_fetcher/google_play_test.rb
new file mode 100644
index 0000000000..c9c4f7c442
--- /dev/null
+++ b/test/models/account/logo_fetcher/google_play_test.rb
@@ -0,0 +1,44 @@
+require "test_helper"
+
+class Account::LogoFetcher::GooglePlayTest < ActiveSupport::TestCase
+ ICON = "https://play-lh.googleusercontent.com/kma-icon"
+
+ setup do
+ @store = Account::LogoFetcher::GooglePlay.new(domain: "krungsri.com", term: "Krungsri", country: "th", client: Account::LogoFetcher::Client.new)
+ stub_request(:get, "#{ICON}=s512").to_return(status: 200, body: png(512))
+ end
+
+ test "returns icons of apps whose developer website is the institution" do
+ stub_request(:get, "https://play.google.com/store/search")
+ .with(query: hash_including(q: "Krungsri", gl: "th"))
+ .to_return(status: 200, body: %(<a href="/store/apps/details?id=com.krungsri.kma">x</a><a href="/store/apps/details?id=com.other.app">y</a>))
+ stub_app("com.krungsri.kma", "https://www.krungsri.com/", "krungsri &amp; you - Apps on Google Play")
+ stub_app("com.other.app", "https://other.example/", "Other - Apps on Google Play")
+
+ icons = @store.icons
+
+ assert_equal [ "googleplay:com.krungsri.kma" ], icons.map(&:key)
+ assert_equal [ 512, "googleplay", "krungsri & you" ], [ icons.first.size, icons.first.source, icons.first.name ]
+ end
+
+ test "rejects malformed packages and icons outside Google's image host" do
+ assert_nil @store.icon("../../evil")
+
+ stub_app("com.krungsri.kma", "https://www.krungsri.com/", "krungsri", icon: "https://evil.example/icon")
+ assert_nil @store.icon("com.krungsri.kma")
+ end
+
+ private
+ def stub_app(package, developer_url, title, icon: ICON)
+ page = %(<meta property="og:title" content="#{title}"><meta property="og:image" content="#{icon}=s0-br30">) +
+ %(<meta name="appstore:developer_url" content="#{developer_url}">)
+ stub_request(:get, "https://play.google.com/store/apps/details")
+ .with(query: hash_including(id: package))
+ .to_return(status: 200, body: page)
+ end
+
+ def png(size)
+ "\x89PNG\r\n\x1a\n".b + [ 13 ].pack("N") + "IHDR" + [ size, size ].pack("NN") + "\x08\x06\x00\x00\x00".b + "\x00" * 4 +
+ [ 0 ].pack("N") + "IEND\xAEB`\x82".b
+ end
+end
diff --git a/test/models/account/logo_fetcher/ru_store_test.rb b/test/models/account/logo_fetcher/ru_store_test.rb
new file mode 100644
index 0000000000..f79884a5e4
--- /dev/null
+++ b/test/models/account/logo_fetcher/ru_store_test.rb
@@ -0,0 +1,65 @@
+require "test_helper"
+
+class Account::LogoFetcher::RuStoreTest < ActiveSupport::TestCase
+ SEARCH_URL = "https://backapi.rustore.ru/applicationData/apps"
+ ICON = "https://static.rustore.ru/apk/2063500440/content/ICON/bank.png"
+
+ setup do
+ @store = Account::LogoFetcher::RuStore.new(domain: "bank.yandex.ru", term: "Яндекс Банк", client: Account::LogoFetcher::Client.new)
+ stub_request(:get, ICON).to_return(status: 200, body: png(512))
+ end
+
+ test "returns icons of apps whose package name holds the domain's brand" do
+ stub_search(
+ app("com.yandex.bank", "Яндекс Пэй"),
+ app("ru.ozon.fintech.finance", "Ozon Банк"),
+ app("com.bank.online", "Some bank")
+ )
+
+ icons = @store.icons
+
+ assert_equal [ "rustore:com.yandex.bank" ], icons.map(&:key)
+ assert_equal [ 512, "rustore", "Яндекс Пэй" ], [ icons.first.size, icons.first.source, icons.first.name ]
+ end
+
+ test "returns apps named after the institution and other apps of their brand" do
+ store = Account::LogoFetcher::RuStore.new(domain: "tbank.ru", term: "Т-Банк", client: Account::LogoFetcher::Client.new)
+ stub_search(
+ app("com.idamob.tinkoff.android", "Т-Банк: карты, вклады, кредиты"),
+ app("ru.sberbankmobile", "СберБанк Онлайн"),
+ app("ru.tinkoff.sme", "Т-Бизнес"),
+ term: "Т-Банк"
+ )
+
+ assert_equal [ "rustore:com.idamob.tinkoff.android", "rustore:ru.tinkoff.sme" ], store.icons.map(&:key)
+ end
+
+ test "finds a picked app again by its package" do
+ stub_search(app("ru.yandex.searchplugin", "Яндекс Старт", icon: "https://static.rustore.ru/other.png"), app("com.yandex.bank", "Яндекс Пэй"))
+
+ assert_equal "rustore:com.yandex.bank", @store.icon("com.yandex.bank").key
+ assert_nil @store.icon("ru.ozon.fintech.finance")
+ end
+
+ test "rejects icons outside RuStore's image host" do
+ stub_search(app("com.yandex.bank", "Яндекс Пэй", icon: "https://evil.example/icon.png"))
+
+ assert_empty @store.icons
+ end
+
+ private
+ def stub_search(*apps, term: "Яндекс Банк")
+ stub_request(:get, SEARCH_URL)
+ .with(query: hash_including(query: term))
+ .to_return(status: 200, body: { code: "OK", body: { content: apps } }.to_json)
+ end
+
+ def app(package, name, icon: ICON)
+ { packageName: package, appName: name, iconUrl: icon }
+ end
+
+ def png(size)
+ "\x89PNG\r\n\x1a\n".b + [ 13 ].pack("N") + "IHDR" + [ size, size ].pack("NN") + "\x08\x06\x00\x00\x00".b + "\x00" * 4 +
+ [ 0 ].pack("N") + "IEND\xAEB`\x82".b
+ end
+end
diff --git a/test/models/account/logo_fetcher_test.rb b/test/models/account/logo_fetcher_test.rb
new file mode 100644
index 0000000000..ac2d727e90
--- /dev/null
+++ b/test/models/account/logo_fetcher_test.rb
@@ -0,0 +1,298 @@
+require "test_helper"
+
+class Account::LogoFetcherTest < ActiveSupport::TestCase
+ GOOGLE_URL = "https://www.google.com/s2/favicons?domain=tbank.ru&sz=256"
+ DUCKDUCKGO_URL = "https://icons.duckduckgo.com/ip3/tbank.ru.ico"
+ YANDEX_URL = "https://favicon.yandex.net/favicon/v2/tbank.ru?size=120"
+
+ setup do
+ @account = accounts(:depository)
+ @account.update_columns(institution_domain: "tbank.ru")
+ stub_request(:get, YANDEX_URL).to_return(status: 404)
+ stub_request(:get, /itunes\.apple\.com/).to_return(status: 200, body: { results: [] }.to_json)
+ stub_request(:get, /play\.google\.com/).to_return(status: 404)
+ stub_request(:get, /backapi\.rustore\.ru/).to_return(status: 404)
+ end
+
+ test "lists the real icons of every service, largest first" do
+ stub_request(:get, GOOGLE_URL).to_return(status: 200, body: png(64))
+ stub_request(:get, DUCKDUCKGO_URL).to_return(status: 200, body: ico(128))
+ stub_request(:get, YANDEX_URL).to_return(status: 200, body: png(16))
+
+ candidates = Account::LogoFetcher.new(@account).candidates
+
+ assert_equal [ [ "duckduckgo", 128 ], [ "google", 64 ] ], candidates.map { |icon| [ icon.source, icon.size ] }
+ end
+
+ test "reuses the icons found for the picker a moment ago" do
+ cache = ActiveSupport::Cache::MemoryStore.new
+ Rails.stubs(:cache).returns(cache)
+ google = stub_request(:get, GOOGLE_URL).to_return(status: 200, body: png(64))
+ stub_request(:get, DUCKDUCKGO_URL).to_return(status: 404)
+
+ first = Account::LogoFetcher.new(@account).candidates
+ second = Account::LogoFetcher.new(@account).candidates
+
+ assert_equal [ "google" ], second.map(&:key)
+ assert_equal first.map(&:body), second.map(&:body)
+ assert_requested google, times: 1
+ end
+
+ test "does not cache an empty picker search" do
+ cache = ActiveSupport::Cache::MemoryStore.new
+ Rails.stubs(:cache).returns(cache)
+ stub_request(:get, GOOGLE_URL).to_return(status: 404)
+ stub_request(:get, DUCKDUCKGO_URL).to_return(status: 404)
+
+ assert_empty Account::LogoFetcher.new(@account).candidates
+
+ stub_request(:get, GOOGLE_URL).to_return(status: 200, body: png(64))
+
+ assert_equal [ "google" ], Account::LogoFetcher.new(@account).candidates.map(&:key)
+ end
+
+ test "prefers an app icon of the institution over favicons" do
+ stub_request(:get, GOOGLE_URL).to_return(status: 200, body: png(180))
+ stub_request(:get, DUCKDUCKGO_URL).to_return(status: 404)
+ Account::LogoFetcher::AppStore.any_instance.stubs(:icons).returns([
+ Account::LogoFetcher::Icon.new(key: "appstore:1", source: "appstore", name: "T-Bank", body: png(512), size: 512, content_type: "image/png", extension: "png")
+ ])
+
+ assert Account::LogoFetcher.new(@account).fetch(auto: true)
+
+ @account.reload
+ assert_equal "appstore", @account.logo_source
+ assert_equal "appstore:1", @account.logo_key
+ assert_equal "T-Bank", @account.logo.blob.metadata["logo_name"]
+ end
+
+ test "a picked icon yields to a newer choice made while it downloaded" do
+ stub_request(:get, YANDEX_URL).to_return(status: 200, body: png(120))
+ fetcher = Account::LogoFetcher.new(@account)
+ fetcher.stubs(:icon_for).with do
+ Account.find(@account.id).update!(logo_selection: "brandfetch")
+ true
+ end.returns(Account::LogoFetcher::Icon.new(key: "yandex", source: "yandex", name: nil, body: png(120), size: 120,
+ content_type: "image/png", extension: "png"))
+
+ assert_not fetcher.fetch(source: "yandex")
+ assert_not @account.reload.logo.attached?
+ assert @account.logo_brandfetch?
+ end
+
+ test "a picked icon replaces an automatic one attached while it downloaded" do
+ fetcher = Account::LogoFetcher.new(@account)
+ fetcher.stubs(:icon_for).with do
+ Account.find(@account.id).logo.attach(io: file_fixture("square-placeholder.png").open, filename: "tbank.ru.png",
+ metadata: { "logo_source" => "google", "logo_key" => "google", "logo_auto" => true })
+ true
+ end.returns(Account::LogoFetcher::Icon.new(key: "yandex", source: "yandex", name: nil, body: png(120), size: 120,
+ content_type: "image/png", extension: "png"))
+
+ assert fetcher.fetch(source: "yandex")
+ assert_equal "yandex", @account.reload.logo_source
+ assert_not @account.logo_auto?
+ end
+
+ test "a picked icon is applied even if an automatic job dropped the old icon meanwhile" do
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "sberbank.ru.png",
+ metadata: { "logo_source" => "google", "logo_key" => "google", "logo_auto" => true })
+ fetcher = Account::LogoFetcher.new(@account)
+ fetcher.stubs(:icon_for).with do
+ Account.find(@account.id).logo.purge
+ true
+ end.returns(Account::LogoFetcher::Icon.new(key: "yandex", source: "yandex", name: nil, body: png(120), size: 120,
+ content_type: "image/png", extension: "png"))
+
+ assert fetcher.fetch(source: "yandex")
+ assert_equal "yandex", @account.reload.logo_source
+ end
+
+ test "a picked icon yields to the removal of a chosen icon while it downloaded" do
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "mine.png")
+ fetcher = Account::LogoFetcher.new(@account)
+ fetcher.stubs(:icon_for).with do
+ Account.find(@account.id).choose_logo("remove")
+ true
+ end.returns(Account::LogoFetcher::Icon.new(key: "yandex", source: "yandex", name: nil, body: png(120), size: 120,
+ content_type: "image/png", extension: "png"))
+
+ assert_not fetcher.fetch(source: "yandex")
+ assert_not @account.reload.logo.attached?
+ end
+
+ test "an automatic fetch yields to an icon chosen while it searched" do
+ icon = Account::LogoFetcher::Icon.new(key: "google", source: "google", name: nil, body: png(180), size: 180, content_type: "image/png", extension: "png")
+ fetcher = Account::LogoFetcher.new(@account)
+ fetcher.stubs(:candidates).with do
+ Account.find(@account.id).logo.attach(io: file_fixture("square-placeholder.png").open, filename: "mine.png")
+ true
+ end.returns([ icon ])
+
+ assert_not fetcher.fetch(auto: true)
+ assert_equal "mine.png", @account.reload.logo.filename.to_s
+ end
+
+ test "attaching an icon touches the account so the cached sidebar updates" do
+ stub_request(:get, GOOGLE_URL).to_return(status: 200, body: png(180))
+ stub_request(:get, DUCKDUCKGO_URL).to_return(status: 404)
+ @account.update_columns(updated_at: 1.day.ago)
+
+ assert Account::LogoFetcher.new(@account).fetch(auto: true)
+
+ assert_operator @account.reload.updated_at, :>, 1.hour.ago
+ end
+
+ test "an automatic fetch skips apps matched only by a parent domain" do
+ stub_request(:get, GOOGLE_URL).to_return(status: 200, body: png(180))
+ stub_request(:get, DUCKDUCKGO_URL).to_return(status: 404)
+ Account::LogoFetcher::GooglePlay.any_instance.stubs(:icons).returns([
+ Account::LogoFetcher::Icon.new(key: "googleplay:ru.yandex.maps", source: "googleplay", name: "Maps", body: png(512), size: 512,
+ content_type: "image/png", extension: "png", auto: false)
+ ])
+
+ assert Account::LogoFetcher.new(@account).fetch(auto: true)
+
+ assert_equal "google", @account.reload.logo_source
+ end
+
+ test "never asks RuStore when fetching automatically" do
+ stub_request(:get, GOOGLE_URL).to_return(status: 200, body: png(180))
+ stub_request(:get, DUCKDUCKGO_URL).to_return(status: 404)
+ Account::LogoFetcher::RuStore.any_instance.expects(:icons).never
+
+ assert Account::LogoFetcher.new(@account).fetch(auto: true)
+
+ assert_equal "google", @account.reload.logo_source
+ end
+
+ test "matches app developer websites to the institution domain" do
+ assert Account::LogoFetcher.same_site?("https://www.krungsri.com/en", "krungsri.com")
+ assert Account::LogoFetcher.same_site?("https://bankffin.kz/ru", "bankffin.kz")
+ assert Account::LogoFetcher.same_site?("https://ozon.ru", "finance.ozon.ru")
+ assert_not Account::LogoFetcher.own_site?("https://ozon.ru", "finance.ozon.ru"), "a parent may be shared"
+ assert Account::LogoFetcher.own_site?("https://app.krungsri.com", "krungsri.com")
+ assert_not Account::LogoFetcher.same_site?("https://notkrungsri.com", "krungsri.com")
+ assert_not Account::LogoFetcher.same_site?(nil, "krungsri.com")
+ end
+
+ test "attaches the largest icon and remembers it was picked automatically" do
+ stub_request(:get, GOOGLE_URL).to_return(status: 200, body: png(64))
+ stub_request(:get, DUCKDUCKGO_URL).to_return(status: 200, body: ico(128))
+
+ assert Account::LogoFetcher.new(@account).fetch(auto: true)
+
+ @account.reload
+ assert_equal ico(128).bytesize, @account.logo.blob.byte_size
+ assert_equal "tbank.ru.ico", @account.logo.filename.to_s
+ assert_equal "duckduckgo", @account.logo_source
+ assert @account.logo_auto?
+ end
+
+ test "attaches the chosen source and stops preferring Brandfetch" do
+ @account.update_columns(logo_selection: "brandfetch")
+ stub_request(:get, YANDEX_URL).to_return(status: 200, body: png(120))
+
+ assert Account::LogoFetcher.new(@account).fetch(source: "yandex")
+
+ @account.reload
+ assert_equal "yandex", @account.logo_source
+ assert_not @account.logo_auto?
+ assert @account.logo_automatic?
+ assert_not_requested :get, GOOGLE_URL
+ end
+
+ test "follows the favicon service redirect" do
+ stub_request(:get, GOOGLE_URL)
+ .to_return(status: 301, headers: { "Location" => "https://t3.gstatic.com/faviconV2?url=http://tbank.ru&size=256" })
+ stub_request(:get, "https://t3.gstatic.com/faviconV2?url=http://tbank.ru&size=256").to_return(status: 200, body: png(128))
+
+ assert Account::LogoFetcher.new(@account).fetch(source: "google")
+
+ assert_equal png(128).bytesize, @account.reload.logo.blob.byte_size
+ assert_equal "image/png", @account.logo.content_type
+ end
+
+ test "reads the size of JPEG icons" do
+ stub_request(:get, GOOGLE_URL).to_return(status: 200, body: jpeg(128))
+ stub_request(:get, DUCKDUCKGO_URL).to_return(status: 200, body: png(32))
+
+ assert Account::LogoFetcher.new(@account).fetch
+
+ assert_equal "image/jpeg", @account.reload.logo.content_type
+ assert_equal "tbank.ru.jpg", @account.logo.filename.to_s
+ end
+
+ test "skips an ICO whose directory or image data is cut short" do
+ stub_request(:get, GOOGLE_URL).to_return(status: 200, body: png(64))
+ [ "\x00\x00\x01\x00\x01\x00".b, "\x00\x00\x01\x00\x01\x00\x20".b, ico(128).byteslice(0, 40) ].each do |cut|
+ stub_request(:get, DUCKDUCKGO_URL).to_return(status: 200, body: cut)
+
+ assert_equal [ "google" ], Account::LogoFetcher.new(@account).candidates.map(&:key)
+ end
+ end
+
+ test "drops an icon over the size limit while reading it" do
+ stub_request(:get, GOOGLE_URL).to_return(status: 200, body: png(180) + "\x00" * Account::LOGO_MAX_SIZE)
+ stub_request(:get, DUCKDUCKGO_URL).to_return(status: 404)
+ stub_request(:get, YANDEX_URL).to_return(status: 200, body: png(120))
+
+ assert_equal [ "yandex" ], Account::LogoFetcher.new(@account).candidates.map(&:key)
+ end
+
+ test "skips a PNG or JPEG cut short" do
+ stub_request(:get, GOOGLE_URL).to_return(status: 200, body: png(180).byteslice(0, 24))
+ stub_request(:get, DUCKDUCKGO_URL).to_return(status: 200, body: jpeg(128).delete_suffix("\xFF\xD9".b))
+ stub_request(:get, YANDEX_URL).to_return(status: 200, body: png(120))
+
+ assert_equal [ "yandex" ], Account::LogoFetcher.new(@account).candidates.map(&:key)
+ end
+
+ test "searches the GB App Store for .uk domains" do
+ @account.update_columns(institution_domain: "barclays.co.uk")
+
+ assert_equal "gb", Account::LogoFetcher.new(@account).send(:countries).first
+ end
+
+ test "keeps the current logo when nothing usable is found" do
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "mine.png")
+ stub_request(:get, GOOGLE_URL).to_timeout
+ stub_request(:get, DUCKDUCKGO_URL).to_return(status: 200, body: "<html>blocked</html>")
+ stub_request(:get, YANDEX_URL).to_return(status: 200, body: png(1))
+
+ assert_not Account::LogoFetcher.new(@account).fetch
+
+ assert_equal "mine.png", @account.reload.logo.filename.to_s
+ end
+
+ test "does nothing without a usable institution domain or with an unknown source" do
+ @account.update_columns(institution_domain: nil)
+ assert_empty Account::LogoFetcher.new(@account).candidates
+
+ @account.update_columns(institution_domain: "bad domain.ru")
+ assert_not Account::LogoFetcher.new(@account).fetch
+
+ @account.update_columns(institution_domain: "tbank.ru")
+ assert_not Account::LogoFetcher.new(@account).fetch(source: "bing")
+
+ assert_not_requested :get, /google|duckduckgo|yandex|itunes/
+ end
+
+ private
+ def png(size)
+ "\x89PNG\r\n\x1a\n".b + [ 13 ].pack("N") + "IHDR" + [ size, size ].pack("NN") + "\x08\x06\x00\x00\x00".b + "\x00" * 4 +
+ [ 0 ].pack("N") + "IEND\xAEB`\x82".b
+ end
+
+ def jpeg(size)
+ app0 = "\xFF\xE0".b + [ 16 ].pack("n") + "JFIF\x00".b + "\x00" * 9
+ sof0 = "\xFF\xC0".b + [ 17, 8, size, size, 3 ].pack("nCnnC") + "\x00" * 9
+ "\xFF\xD8".b + app0 + sof0 + "\xFF\xD9".b
+ end
+
+ def ico(size)
+ image = png(size)
+ dimension = size >= 256 ? 0 : size
+ "\x00\x00\x01\x00".b + [ 1 ].pack("v") + [ dimension, dimension, 0, 0 ].pack("C4") + [ 1, 32, image.bytesize, 22 ].pack("vvVV") + image
+ end
+end
diff --git a/test/models/account_test.rb b/test/models/account_test.rb
index 70d75f17be..f1dd8b07d6 100644
--- a/test/models/account_test.rb
+++ b/test/models/account_test.rb
@@ -1210,6 +1210,181 @@ class AccountTest < ActiveSupport::TestCase
assert_includes Account.annotatable_by(member).pluck(:id), accounts(:credit_card).id, "read_write share"
end
+ test "institution_domain is normalized to a bare host" do
+ {
+ "https://www.tbank.ru/" => "tbank.ru",
+ "https://www.krungsri.com/en/personal" => "krungsri.com",
+ " HTTP://Chase.com:443/?q=1#top " => "chase.com",
+ "www.example.co.uk" => "example.co.uk",
+ "sberbank.ru" => "sberbank.ru"
+ }.each do |input, expected|
+ @account.update!(institution_domain: input)
+ assert_equal expected, @account.read_attribute(:institution_domain), "for #{input.inspect}"
+ end
+
+ @account.update!(institution_domain: " ")
+ assert_nil @account.read_attribute(:institution_domain)
+ end
+
+ test "logo_url builds a Brandfetch URL from a legacy unnormalized domain" do
+ Setting.stubs(:brand_fetch_client_id).returns("test-client-id")
+ @account.update_column(:institution_domain, "https://www.tbank.ru/")
+
+ assert_match %r{\Ahttps://cdn\.brandfetch\.io/tbank\.ru/icon/}, @account.logo_url
+ end
+
+ test "an uploaded logo wins over the Brandfetch icon" do
+ Setting.stubs(:brand_fetch_client_id).returns("test-client-id")
+ @account.update!(institution_domain: "tbank.ru")
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "logo.png")
+
+ assert_equal Rails.application.routes.url_helpers.rails_blob_path(@account.logo, only_path: true), @account.logo_url
+ end
+
+ test "logo must be a small raster image" do
+ @account.logo = { io: file_fixture("test.txt").open, filename: "logo.txt" }
+ assert_not @account.valid?
+ assert @account.errors.added?(:logo, :invalid_content_type)
+
+ @account.logo = { io: StringIO.new("\x89PNG\r\n\x1a\n".b + "\x00" * Account::LOGO_MAX_SIZE), filename: "logo.png", content_type: "image/png" }
+ assert_not @account.valid?
+ assert @account.errors.added?(:logo, :too_large, max_size: 1)
+ end
+
+ test "choosing Brandfetch shows it while keeping the stored logo" do
+ @account.update!(institution_domain: "tbank.ru", logo_selection: "brandfetch")
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "logo.png")
+
+ Setting.stubs(:brand_fetch_client_id).returns("test-client-id")
+ assert_match %r{\Ahttps://cdn\.brandfetch\.io/tbank\.ru/}, @account.logo_url
+ assert @account.logo.attached?
+
+ Setting.stubs(:brand_fetch_client_id).returns(nil)
+ assert_equal Rails.application.routes.url_helpers.rails_blob_path(@account.logo, only_path: true), @account.logo_url
+ end
+
+ test "choose_logo switches between Brandfetch and the stored logo without deleting it" do
+ Setting.stubs(:brand_fetch_client_id).returns("test-client-id")
+ @account.update!(institution_domain: "tbank.ru")
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "mine.png")
+ Account::LogoFetcher.any_instance.expects(:fetch).never
+
+ assert @account.choose_logo("brandfetch")
+ assert @account.reload.logo_brandfetch?
+
+ assert @account.choose_logo("stored")
+ assert @account.reload.logo_automatic?
+ assert @account.logo.attached?
+ end
+
+ test "choose_logo downloads a picked icon by its key" do
+ Account::LogoFetcher.any_instance.expects(:fetch).with(source: "appstore:123").returns(true)
+
+ assert @account.choose_logo("appstore:123")
+ end
+
+ test "removing the stored logo brings back the fallback" do
+ Setting.stubs(:brand_fetch_client_id).returns("test-client-id")
+ @account.update!(institution_domain: "tbank.ru")
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "mine.png")
+ assert_equal @account.stored_logo_url, @account.logo_url
+
+ @account.choose_logo("remove")
+
+ assert_equal @account.brandfetch_logo_url, @account.reload.logo_url
+ assert_equal @account.fallback_logo_url, @account.logo_url
+ end
+
+ test "clearing the domain drops an automatic icon but keeps an uploaded one" do
+ @account.update!(institution_domain: "tbank.ru")
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "tbank.ru.png",
+ metadata: { "logo_source" => "google", "logo_key" => "google", "logo_auto" => true })
+ @account.update!(institution_domain: "")
+ assert_not @account.reload.logo.attached?
+
+ @account.update!(institution_domain: "tbank.ru")
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "mine.png")
+ @account.update!(institution_domain: "")
+ assert @account.reload.logo.attached?
+ end
+
+ test "stored_logo? matches a favicon key only for the domain it was fetched for" do
+ @account.update!(institution_domain: "tbank.ru")
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "tbank.ru.png",
+ metadata: { "logo_source" => "google", "logo_key" => "google" })
+ assert @account.stored_logo?("google")
+
+ @account.institution_domain = "sberbank.ru"
+ assert_not @account.stored_logo?("google")
+ end
+
+ test "a stored logo from before the upload check does not block saves" do
+ # Attached around the validation, as a logo stored before it existed.
+ blob = ActiveStorage::Blob.create_and_upload!(io: StringIO.new("<svg/>"), filename: "old.svg", content_type: "image/svg+xml")
+ ActiveStorage::Attachment.create!(name: "logo", record: @account, blob: blob)
+ assert @account.reload.logo.attached?
+
+ assert @account.update(name: "Renamed")
+ end
+
+ test "clearing the domain keeps the automatic icon when the provider supplies one" do
+ @account.update!(institution_domain: "tbank.ru")
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "tbank.ru.png",
+ metadata: { "logo_source" => "google", "logo_key" => "google", "logo_auto" => true })
+ @account.stubs(:provider).returns(stub(institution_domain: "tbank.ru"))
+
+ assert_enqueued_with(job: AccountLogoFetchJob) { @account.update!(institution_domain: "") }
+ assert @account.reload.logo.attached?
+ end
+
+ test "uploading or removing a logo touches the account" do
+ @account.update_columns(updated_at: 1.day.ago)
+ @account.update!(logo: { io: file_fixture("square-placeholder.png").open, filename: "mine.png", content_type: "image/png" })
+ assert_operator @account.reload.updated_at, :>, 1.hour.ago
+
+ @account.update_columns(updated_at: 1.day.ago)
+ @account.choose_logo("remove")
+ assert_operator @account.reload.updated_at, :>, 1.hour.ago
+ end
+
+ test "choose_logo removes the stored logo" do
+ @account.update!(logo_selection: "brandfetch")
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "mine.png")
+
+ assert @account.choose_logo("remove")
+ assert_not @account.reload.logo.attached?
+ assert @account.logo_automatic?
+ end
+
+ test "only empty or automatically picked logos are fetched automatically" do
+ @account.update!(institution_domain: "tbank.ru")
+ assert @account.logo_auto_fetchable?
+
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "mine.png")
+ assert_not @account.logo_auto_fetchable?, "an uploaded logo stays"
+
+ @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "tbank.ru.png",
+ metadata: { "logo_source" => "google", "logo_auto" => true })
+ assert @account.logo_auto_fetchable?
+
+ @account.update!(logo_selection: "brandfetch")
+ assert_not @account.logo_auto_fetchable?, "a chosen Brandfetch logo stays"
+
+ @account.update!(logo_selection: "automatic", institution_domain: nil)
+ assert_not @account.logo_auto_fetchable?
+ end
+
+ test "setting or changing the institution domain fetches a logo in the background" do
+ assert_enqueued_with(job: AccountLogoFetchJob, args: [ @account ]) do
+ @account.update!(institution_domain: "tbank.ru")
+ end
+
+ assert_no_enqueued_jobs(only: AccountLogoFetchJob) do
+ @account.update!(name: "Renamed")
+ @account.update!(institution_domain: nil)
+ end
+ end
+
private
def create_loan_with_start_date(start_date, opening_balance_date)
Account.create_and_sync(
diff --git a/test/models/family/data_importer_test.rb b/test/models/family/data_importer_test.rb
index f475dcacb1..1c36ec7611 100644
--- a/test/models/family/data_importer_test.rb
+++ b/test/models/family/data_importer_test.rb
@@ -31,6 +31,50 @@ class Family::DataImporterTest < ActiveSupport::TestCase
assert_equal "Depository", account.accountable_type
end
+ test "restores the Brandfetch logo choice so no fetched icon replaces it" do
+ ndjson = build_ndjson([
+ {
+ type: "Account",
+ data: {
+ id: "old-account-1",
+ name: "Test Checking",
+ balance: "1500.00",
+ currency: "USD",
+ institution_domain: "tbank.ru",
+ logo_selection: "brandfetch",
+ accountable_type: "Depository",
+ accountable: { subtype: "checking" }
+ }
+ }
+ ])
+
+ account = Family::DataImporter.new(@family, ndjson).import![:accounts].first
+
+ assert account.reload.logo_brandfetch?
+ assert_not account.logo_auto_fetchable?
+ end
+
+ test "an unknown logo selection imports as the automatic one" do
+ ndjson = build_ndjson([
+ {
+ type: "Account",
+ data: {
+ id: "old-account-1",
+ name: "Test Checking",
+ balance: "1500.00",
+ currency: "USD",
+ logo_selection: "some-future-source",
+ accountable_type: "Depository",
+ accountable: { subtype: "checking" }
+ }
+ }
+ ])
+
+ account = Family::DataImporter.new(@family, ndjson).import![:accounts].first
+
+ assert account.reload.logo_automatic?
+ end
+
test "imports non-destructive account status from ndjson" do
ndjson = build_ndjson([
{
diff --git a/test/system/accounts_test.rb b/test/system/accounts_test.rb
index 5bb7740eb1..d07fe854a5 100644
--- a/test/system/accounts_test.rb
+++ b/test/system/accounts_test.rb
@@ -14,6 +14,43 @@ class AccountsTest < ApplicationSystemTestCase
assert_account_created("Depository")
end
+ test "pick icon waits for a whole institution domain" do
+ click_link Accountable.from_type("Depository").singular_display_name
+ click_link "Enter account balance"
+ find("summary", text: "Additional details").click
+
+ assert_equal "true", find_button("Pick icon")["aria-disabled"]
+ click_button "Pick icon"
+ assert_text "Enter the institution domain"
+
+ fill_in "Institution domain", with: "tbank"
+ assert_equal "true", find_button("Pick icon")["aria-disabled"]
+
+ fill_in "Institution domain", with: "https://www.tbank.ru/"
+ assert_no_text "Enter the institution domain"
+ assert_equal "false", find_button("Pick icon")["aria-disabled"]
+ end
+
+ test "pick icon is ready in the edit form of an account with a saved domain" do
+ account = accounts(:depository)
+ account.update!(institution_domain: "tbank.ru")
+ visit account_url(account)
+ open_account_edit_dialog
+ find("summary", text: "Additional details").click
+
+ assert_equal "false", find_button("Pick icon")["aria-disabled"]
+ end
+
+ test "an account logo the browser cannot load gives way to the initials" do
+ Account.any_instance.stubs(:logo_url).returns("/missing-account-logo.png")
+ visit account_url(accounts(:depository))
+
+ within("header span.relative", match: :first) do
+ assert_no_selector "img"
+ assert_selector "div", text: accounts(:depository).name.first
+ end
+ end
+
test "can create investment account" do
assert_account_created("Investment")
end
diff --git a/test/views/accounts/logo_view_test.rb b/test/views/accounts/logo_view_test.rb
new file mode 100644
index 0000000000..562845d323
--- /dev/null
+++ b/test/views/accounts/logo_view_test.rb
@@ -0,0 +1,23 @@
+require "test_helper"
+
+class AccountsLogoViewTest < ActionView::TestCase
+ setup do
+ @account = accounts(:depository)
+ end
+
+ test "a logo sits over the initials and removes itself when it fails to load" do
+ render partial: "accounts/logo", locals: { account: @account, url: "https://example.com/logo.png" }
+
+ assert_select "span.relative" do
+ assert_select "div", text: @account.name.first
+ assert_select "img[src='https://example.com/logo.png'][onerror=?]", ProviderLogo::REMOVE_ON_ERROR
+ end
+ end
+
+ test "an account without a logo shows only the initials" do
+ render partial: "accounts/logo", locals: { account: @account, url: nil }
+
+ assert_select "img", count: 0
+ assert_select "div", text: @account.name.first
+ end
+end