Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add Apple Wallet settings, diagnostics, and realistic demo data (#3684)

Juan José Mata5c3c07996141
diff --git a/app/components/settings/provider_card.html.erb b/app/components/settings/provider_card.html.erb
index f1f40355ee..a682f342b9 100644
--- a/app/components/settings/provider_card.html.erb
+++ b/app/components/settings/provider_card.html.erb
@@ -1,6 +1,10 @@
-<%= link_to connect_path,
- class: "bg-container shadow-border-xs hover:bg-surface-inset rounded-xl p-4 flex flex-col gap-2.5 text-primary transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-alpha-black-300",
- data: { turbo_frame: "drawer", turbo_prefetch: "false" }.merge(filter_data) do %>
+<%= content_tag(external_link ? :div : :a,
+ href: (connect_path unless external_link),
+ class: class_names(
+ "bg-container shadow-border-xs rounded-xl p-4 flex flex-col gap-2.5 text-primary",
+ "hover:bg-surface-inset transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-alpha-black-300" => !external_link
+ ),
+ data: filter_data.merge(external_link ? {} : { turbo_frame: "drawer", turbo_prefetch: "false" })) do %>
<div class="flex items-start gap-2.5">
<%= render ProviderLogo.new(provider_key: provider_key, class_name: "w-9 h-9 rounded-lg") %>
<div class="flex-1 min-w-0">
@@ -17,7 +21,19 @@
<p class="text-sm text-secondary grow leading-snug"><%= tagline %></p>
<% end %>
<div class="flex items-center justify-end gap-1.5 text-sm font-medium text-primary">
- <%= t("settings.providers.connect") %>
- <%= helpers.icon "arrow-right", size: "sm", class: "!w-3.5 !h-3.5" %>
+ <% if external_link %>
+ <% if external_link[:href].present? %>
+ <%= render DS::Link.new(text: external_link.fetch(:text), href: external_link[:href], variant: :secondary, size: :sm,
+ target: "_blank", data: { turbo: false }, title: external_link[:tooltip]) %>
+ <% else %>
+ <span title="<%= external_link[:tooltip] %>" tabindex="0" aria-label="<%= external_link.fetch(:text) %>" aria-description="<%= external_link[:tooltip] %>">
+ <%= render DS::Button.new(text: external_link.fetch(:text), variant: :secondary, size: :sm,
+ disabled: true, class: "pointer-events-none opacity-50", aria: { description: external_link[:tooltip] }) %>
+ </span>
+ <% end %>
+ <% else %>
+ <%= t("settings.providers.connect") %>
+ <%= helpers.icon "arrow-right", size: "sm", class: "!w-3.5 !h-3.5" %>
+ <% end %>
</div>
<% end %>
diff --git a/app/components/settings/provider_card.rb b/app/components/settings/provider_card.rb
index 4a739bfb78..639d98b60a 100644
--- a/app/components/settings/provider_card.rb
+++ b/app/components/settings/provider_card.rb
@@ -9,7 +9,7 @@ class Settings::ProviderCard < ApplicationComponent
I18n.t(key) if key
end
- def initialize(provider_key:, name:, tagline: nil, region: nil, kinds: nil, tier: nil, maturity: :stable)
+ def initialize(provider_key:, name:, tagline: nil, region: nil, kinds: nil, tier: nil, maturity: :stable, external_link: nil)
@provider_key = provider_key
@name = name
@tagline = tagline
@@ -17,9 +17,10 @@ class Settings::ProviderCard < ApplicationComponent
@kinds = Array(kinds).compact
@tier = tier
@maturity = maturity.to_sym
+ @external_link = external_link
end
- attr_reader :provider_key, :name, :tagline
+ attr_reader :provider_key, :name, :tagline, :external_link
def maturity_label
self.class.maturity_label(@maturity)
diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rb
index 99730c2b95..f0678dd480 100644
--- a/app/controllers/accounts_controller.rb
+++ b/app/controllers/accounts_controller.rb
@@ -3,6 +3,7 @@ class AccountsController < ApplicationController
before_action :set_account, only: %i[show sparkline sync set_default remove_default]
before_action :set_manageable_account, only: %i[toggle_active toggle_exclude_from_reports destroy unlink confirm_unlink select_provider]
+ before_action :ensure_linked_account, only: %i[confirm_unlink unlink]
include Periodable
def index
@@ -13,6 +14,10 @@ class AccountsController < ApplicationController
.with_attached_logo
.includes(:accountable, :account_providers, :plaid_account, :simplefin_account)
.order(:name)
+ @financekit_accounts = Current.family.accounts
+ .where(id: @accessible_account_ids).where.not(status: :pending_deletion)
+ .joins(:account_providers).where(account_providers: { provider_type: "FinancekitAccountLineage" })
+ .distinct.with_attached_logo.includes(:accountable, account_providers: :provider).order(:name)
@plaid_items = visible_provider_items(family.plaid_items.ordered.with_attached_logo.includes(:plaid_accounts))
@simplefin_items = visible_provider_items(family.simplefin_items.ordered.with_attached_logo)
@lunchflow_items = visible_provider_items(family.lunchflow_items.ordered.with_attached_logo.includes(:lunchflow_accounts))
@@ -232,19 +237,13 @@ class AccountsController < ApplicationController
end
def confirm_unlink
- unless @account.linked?
- redirect_to account_path(@account), alert: t("accounts.unlink.not_linked")
- end
end
def unlink
- unless @account.linked?
- redirect_to account_path(@account), alert: t("accounts.unlink.not_linked")
- return
- end
-
begin
Account.transaction do
+ @account.provider_account_for("FinancekitAccountLineage")&.disconnect!
+
# Detach holdings from provider links before destroying them
provider_link_ids = @account.account_providers.pluck(:id)
if provider_link_ids.any?
@@ -259,7 +258,7 @@ class AccountsController < ApplicationController
# This follows the Plaid pattern where the provider account survives as "unlinked".
# SnapTrade has limited connection slots (5 free), so preserving the record avoids
# wasting a slot on reconnect.
- @account.account_providers.destroy_all
+ @account.account_providers.reload.destroy_all
# Remove legacy system links (foreign keys)
@account.update!(plaid_account_id: nil, simplefin_account_id: nil)
@@ -313,6 +312,12 @@ class AccountsController < ApplicationController
end
private
+ def ensure_linked_account
+ return if @account.linked?
+
+ redirect_to account_path(@account), alert: t("accounts.unlink.not_linked")
+ end
+
def family
Current.family
end
@@ -397,7 +402,7 @@ class AccountsController < ApplicationController
@onchain_wallet_items
].flatten.compact
- accounts = @manual_accounts.to_a
+ accounts = @manual_accounts.to_a + @financekit_accounts.to_a
items.each do |item|
next unless item.respond_to?(:accounts)
accounts.concat(item.accounts)
diff --git a/app/controllers/settings/providers_controller.rb b/app/controllers/settings/providers_controller.rb
index fe230d89a0..27ae95912e 100644
--- a/app/controllers/settings/providers_controller.rb
+++ b/app/controllers/settings/providers_controller.rb
@@ -332,6 +332,15 @@ class Settings::ProvidersController < ApplicationController
@questrade_items = Current.family.questrade_items.active.ordered.select(:id)
@fio_items = Current.family.fio_items.active.ordered
+ # Wallet uploads are managed on iOS. Only expose linked accounts the
+ # current admin can access, including connections that need repair.
+ accessible_account_ids = Current.family.accounts.accessible_by(Current.user).pluck(:id).to_set
+ @financekit_connections = Current.family.financekit_items.where(status: %w[active repair_required])
+ .ordered.includes(:accounts).filter_map do |item|
+ accounts = item.accounts.select { |account| accessible_account_ids.include?(account.id) && !account.pending_deletion? }
+ { item: item, accounts: accounts } if accounts.any?
+ end
+
@provider_sync_health = compute_provider_sync_health(family_panel_items)
entries = build_provider_entries
@@ -339,6 +348,7 @@ class Settings::ProvidersController < ApplicationController
@connected = entries.select { |e| e[:summary][:status] == :ok }
@needs_attention = entries.select { |e| [ :warn, :err ].include?(e[:summary][:status]) }
@available = entries.select { |e| e[:summary][:status] == :off }
+ @can_sync_all = (@connected + @needs_attention).any? { |entry| entry[:sync_supported] != false }
@health = view_context.provider_health_strip(connected: @connected, needs_attention: @needs_attention)
end
@@ -434,6 +444,17 @@ class Settings::ProvidersController < ApplicationController
}
end
- (configuration_entries + family_entries).sort_by { |entry| entry[:title].downcase }
+ wallet_entry = {
+ provider_key: "financekit", title: Provider::Metadata.for(:financekit)[:name],
+ turbo_id: "financekit", partial: "financekit_panel", maturity: :beta,
+ external_link: {
+ text: t("settings.providers.financekit.app_store"), href: nil,
+ tooltip: t("settings.providers.financekit.coming_soon")
+ },
+ sync_supported: false,
+ summary: view_context.financekit_provider_summary(@financekit_connections)
+ }
+
+ (configuration_entries + family_entries + [ wallet_entry ]).sort_by { |entry| entry[:title].downcase }
end
end
diff --git a/app/helpers/settings_helper.rb b/app/helpers/settings_helper.rb
index 96aeac4b20..ef94df42dc 100644
--- a/app/helpers/settings_helper.rb
+++ b/app/helpers/settings_helper.rb
@@ -129,6 +129,18 @@ module SettingsHelper
end
end
+ def financekit_provider_summary(connections)
+ return { status: :off } if connections.empty?
+
+ items = connections.map { |connection| connection[:item] }
+ count = connections.flat_map { |connection| connection[:accounts].map(&:id) }.uniq.size
+ {
+ status: items.any? { |item| item.status == "repair_required" } ? :warn : :ok,
+ meta: t("settings.providers.financekit.linked_accounts", count: count),
+ last_synced_at: items.filter_map(&:last_imported_at).max
+ }
+ end
+
def settings_nav_footer
previous_setting = adjacent_setting(request.path, -1)
next_setting = adjacent_setting(request.path, 1)
diff --git a/app/models/demo/financekit_generator.rb b/app/models/demo/financekit_generator.rb
new file mode 100644
index 0000000000..80422b9357
--- /dev/null
+++ b/app/models/demo/financekit_generator.rb
@@ -0,0 +1,288 @@
+class Demo::FinancekitGenerator
+ ENROLLMENT_ID = "a332c972-621f-4d46-979a-559e9df26713".freeze
+ CARD_SOURCE_ID = "a99206b4-c093-47dc-b8c2-de55ac12d273".freeze
+ CASH_SOURCE_ID = "e2b91fd6-850c-457a-97ad-7c465070877a".freeze
+ NANCY_SOURCE_ID = "7e784bc2-5b62-4b3e-84d6-8ec834128efa".freeze
+ DAILY_CASH_RATE = BigDecimal("0.01") # Illustrative demo reward, not a live rate calculation.
+ CARD_MERCHANTS = [ "Delta Airlines", "Hilton Hotels", "Expedia", "Apple", "BestBuy", "Amazon" ].freeze
+ CASH_MERCHANTS = [ "Coffee Shop", "Corner Market", "Lunch", "Transit", "Farmers Market" ].freeze
+ MERCHANT_CATEGORIES = {
+ "Delta Airlines" => "Travel", "Hilton Hotels" => "Travel", "Expedia" => "Travel",
+ "Apple" => "Shopping", "BestBuy" => "Shopping", "Amazon" => "Shopping",
+ "Coffee Shop" => "Coffee & Takeout", "Corner Market" => "Groceries",
+ "Lunch" => "Restaurants", "Transit" => "Transportation", "Farmers Market" => "Groceries"
+ }.freeze
+ FUNDING_ENTRIES = [ "Apple Card Payment", "Apple Cash Top Up" ].freeze
+
+ def initialize(family, seed: 42)
+ @family = family
+ @rng = Random.new(seed.to_i)
+ end
+
+ # Additive and repeatable: never replace an existing Wallet enrollment or
+ # clear a family's data. These synthetic records need no device or feature flags.
+ def generate!
+ item = @family.with_lock do
+ create_accounts!
+ create_transactions!
+ end
+ (item.accounts.to_a + @funding_accounts_to_sync).uniq.each { |account| Sync.create!(syncable: account).perform }
+ item
+ end
+
+ def create_accounts!
+ @family.with_lock do
+ @item = @family.financekit_items.find_by(enrollment_id: ENROLLMENT_ID)
+ if @item
+ ensure_nancy_account!
+ next @item
+ end
+
+ user = @family.users.where(active: true, role: %w[admin super_admin]).order(:created_at).first!
+ @item = Financekit::Enrollment.create!(user, {
+ "enrollment_id" => ENROLLMENT_ID, "protocol_version" => Financekit::VERSION,
+ "consent" => {
+ "version" => 1, "granted_at" => Time.current.iso8601,
+ "selected_source_account_ids" => [ CARD_SOURCE_ID, CASH_SOURCE_ID, NANCY_SOURCE_ID ],
+ "upload_authorized" => true, "family_visibility_acknowledged" => true,
+ "remote_processing_acknowledged" => true
+ }
+ }).item
+ map_account!(CARD_SOURCE_ID, "Apple Card", "CreditCard", "credit_card")
+ map_account!(CASH_SOURCE_ID, "Apple Cash", "Depository", "cash")
+ map_account!(NANCY_SOURCE_ID, "Nancy's Apple Cash", "Depository", "cash")
+ @item.activate!
+ @item
+ end
+ end
+
+ def create_transactions!
+ @funding_accounts_to_sync = []
+ @family.with_lock do
+ @item = @family.financekit_items.find_by!(enrollment_id: ENROLLMENT_ID)
+ if @item.last_imported_at
+ complete_demo_activity!
+ generate_cash_family_activity!.each { |mapping| record_balance!(mapping) }
+ next @item
+ end
+
+ card = @item.financekit_accounts.find_by!(source_id: CARD_SOURCE_ID)
+ cash = @item.financekit_accounts.find_by!(source_id: CASH_SOURCE_ID)
+ generate_transactions!(card, cash)
+ complete_demo_activity!
+ generate_cash_family_activity!
+ @item.financekit_accounts.each { |mapping| record_balance!(mapping) }
+ now = Time.current
+ @item.update!(last_device_contact_at: now, last_accepted_at: now, last_imported_at: now)
+ @item.syncs.create!(status: "completed", completed_at: now,
+ sync_stats: { "total_accounts" => 3, "linked_accounts" => 3 })
+ Financekit::Diagnostics.capture(item: @item, source: self.class.name,
+ message: "FinanceKit demo accounts created", event: "demo_seeded", account_count: 3)
+ @item
+ end
+ end
+
+ private
+ def ensure_nancy_account!
+ return if @item.financekit_accounts.exists?(source_id: NANCY_SOURCE_ID)
+
+ # Only this synthetic enrollment is extended; real device enrollments
+ # continue to manage their own consent and mapping lifecycle.
+ @item.update!(status: "repair_required", consent: @item.consent.merge(
+ "selected_source_account_ids" => (@item.consented_source_ids + [ NANCY_SOURCE_ID ]).uniq))
+ map_account!(NANCY_SOURCE_ID, "Nancy's Apple Cash", "Depository", "cash")
+ @item.activate!
+ end
+
+ def map_account!(source_id, name, type, subtype)
+ FinancekitAccount.map!(@item, source_id, {
+ "expected_version" => 0, "action" => "create", "name" => name,
+ "institution_name" => "Apple Wallet", "currency" => "USD",
+ "accountable_type" => type, "subtype" => subtype,
+ "ledger_timezone" => "America/Los_Angeles",
+ "booked_balance" => { "amount" => "0.00", "currency" => "USD", "direction" => "credit" },
+ "observed_at" => Time.current.iso8601
+ })
+ end
+
+ def generate_transactions!(card, cash)
+ month = 11.months.ago.to_date.beginning_of_month
+ while month <= Date.current
+ last_day = [ month.end_of_month, Date.current ].min
+ total = 0
+ @rng.rand(15..22).times do
+ amount = @rng.rand(15..80)
+ total += amount
+ transaction!(card, amount, CARD_MERCHANTS.sample(random: @rng), @rng.rand(month..last_day))
+ end
+ transaction!(card, -(total * 0.92).round(2), "Apple Card Payment", last_day)
+
+ transaction!(cash, -300, "Apple Cash Top Up", month)
+ 10.times do
+ transaction!(cash, @rng.rand(5..25), CASH_MERCHANTS.sample(random: @rng), @rng.rand(month..last_day))
+ end
+ month = month.next_month
+ end
+ transaction!(card, 24.50, "Apple", Date.current, pending: true)
+ transaction!(cash, 8.75, "Coffee Shop", Date.current, pending: true)
+ end
+
+ # Upgrade the old synthetic dataset in place, retaining account/entry IDs and
+ # provider payloads. A marker preserves subsequent user edits on reruns.
+ def complete_demo_activity!
+ @item.financekit_accounts.where(source_id: [ CARD_SOURCE_ID, CASH_SOURCE_ID ]).each do |mapping|
+ mapping.financekit_transactions.includes(entry: :entryable).each do |identity|
+ entry = identity.entry
+ next unless entry&.transaction? && entry.source == "financekit"
+
+ transaction = entry.entryable
+ next if transaction.extra["demo_financekit_activity_version"] == 1
+
+ if (category_name = MERCHANT_CATEGORIES[entry.name]) && entry.amount.positive?
+ if transaction.category.nil? || transaction.category.name == "Shopping"
+ category = @family.categories.find_or_create_by!(name: category_name) do |record|
+ record.lucide_icon = Category.suggested_icon(category_name)
+ end
+ transaction.update!(category: category)
+ end
+ elsif FUNDING_ENTRIES.include?(entry.name) && entry.amount.negative? && !transaction.pending?
+ link_funding_transfer!(entry)
+ else
+ next
+ end
+ transaction.update!(extra: transaction.extra.merge("demo_financekit_activity_version" => 1))
+ end
+ end
+ end
+
+ def link_funding_transfer!(entry)
+ inflow = entry.entryable
+ unless inflow.transfer
+ from = funding_account
+ outflow = from.entries.create!(name: entry.name, date: entry.date, amount: -entry.amount,
+ currency: entry.currency, entryable: Transaction.new(kind: Transfer.kind_for_account(entry.account)))
+ Transfer.create!(inflow_transaction: inflow, outflow_transaction: outflow.entryable)
+ @funding_accounts_to_sync << from
+ end
+ inflow.update!(kind: "funds_movement", category: nil)
+ end
+
+ def funding_account
+ @funding_account ||= begin
+ # Reuse the demo checking account, never add synthetic withdrawals to a
+ # linked bank account or another household member's private account.
+ checking = @family.accounts.manual.active.where(owner_id: @item.user_id,
+ accountable_type: "Depository", currency: "USD", name: "Chase Premier Checking").first
+ checking || @family.accounts.create!(name: "Wallet Demo Checking", owner: @item.user,
+ currency: "USD", balance: 0, accountable: Depository.new(subtype: "checking")).tap do |account|
+ entries = Entry.where(account_id: @item.accounts.select(:id))
+ opening_balance = -entries.where("amount < 0").sum(:amount) + 5_000
+ result = Account::OpeningBalanceManager.new(account).set_opening_balance(
+ balance: opening_balance, date: entries.minimum(:date).prev_day)
+ raise result.error unless result.success?
+ end
+ end
+ end
+
+ def generate_cash_family_activity!
+ card = @item.financekit_accounts.find_by!(source_id: CARD_SOURCE_ID)
+ cash = @item.financekit_accounts.find_by!(source_id: CASH_SOURCE_ID)
+ nancy = @item.financekit_accounts.find_by!(source_id: NANCY_SOURCE_ID)
+
+ changed = []
+ today = Time.current.in_time_zone(cash.ledger_timezone).to_date
+ daily_charges = card.financekit_transactions.where(status: "booked").joins(:entry)
+ .where("entries.amount > 0 AND entries.date < ?", today).group("entries.date").sum("entries.amount")
+ daily_charges.each do |date, total|
+ source_id = Digest::UUID.uuid_v5(ENROLLMENT_ID, "daily-cash:#{date}")
+ next if cash.financekit_transactions.exists?(source_id: source_id)
+
+ reward = (total * DAILY_CASH_RATE).round(2)
+ next unless reward.positive?
+
+ identity = transaction!(cash, -reward, "Apple Card Daily Cash", date.next_day,
+ source_id: source_id, transaction_type: "cashback")
+ category = @family.categories.find_or_create_by!(name: "Cash Back")
+ identity.entry.entryable.update!(category: category)
+ changed << cash
+ end
+
+ # Six small gifts over the final weeks of the original demo history.
+ # Stable source IDs keep later reruns from adding another six gifts.
+ last_date = card.account.entries.maximum(:date)
+ [ [ 35, 5 ], [ 28, 10 ], [ 21, 3 ], [ 14, 8 ], [ 7, 15 ], [ 2, 5 ] ].each_with_index do |(days, amount), index|
+ sent_id = Digest::UUID.uuid_v5(ENROLLMENT_ID, "nancy-gift:#{index}:sent")
+ next if cash.financekit_transactions.exists?(source_id: sent_id)
+
+ received_id = Digest::UUID.uuid_v5(ENROLLMENT_ID, "nancy-gift:#{index}:received")
+ sent = transaction!(cash, amount, "Sent to Nancy", last_date - days,
+ source_id: sent_id, transaction_type: "transfer")
+ received = transaction!(nancy, -amount, "Received from Dad", last_date - days,
+ source_id: received_id, transaction_type: "transfer")
+ [ sent, received ].each { |identity| identity.entry.entryable.update!(kind: "funds_movement") }
+ Transfer.create!(outflow_transaction: sent.entry.entryable, inflow_transaction: received.entry.entryable)
+ changed.concat([ cash, nancy ])
+ end
+ changed << nancy if generate_nancy_purchases!(nancy)
+ changed.uniq
+ end
+
+ def generate_nancy_purchases!(nancy)
+ # Spend a little of each gift the following day: a few outings per month,
+ # all funded by the existing allowance rather than an overdraft.
+ purchases = [
+ [ "Candy Shop", "2.50", "Food & Dining" ],
+ [ "Movie Theater", "8.00", "Entertainment" ],
+ [ "After-School Snacks", "3.25", "Food & Dining" ],
+ [ "Movie Theater", "9.00", "Entertainment" ],
+ [ "Ice Cream Shop", "4.00", "Food & Dining" ],
+ [ "Candy Shop", "1.75", "Food & Dining" ]
+ ]
+ changed = false
+ purchases.each_with_index do |(name, amount, category_name), index|
+ source_id = Digest::UUID.uuid_v5(ENROLLMENT_ID, "nancy-purchase:#{index}")
+ next if nancy.financekit_transactions.exists?(source_id: source_id)
+
+ gift_id = Digest::UUID.uuid_v5(ENROLLMENT_ID, "nancy-gift:#{index}:received")
+ date = nancy.financekit_transactions.find_by!(source_id: gift_id).entry.date.next_day
+ next if date > Time.current.in_time_zone(nancy.ledger_timezone).to_date
+
+ identity = transaction!(nancy, amount.to_d, name, date, source_id: source_id)
+ category = @family.categories.find_or_create_by!(name: category_name) do |record|
+ record.lucide_icon = Category.suggested_icon(category_name)
+ end
+ identity.entry.entryable.update!(category: category)
+ changed = true
+ end
+ changed
+ end
+
+ def transaction!(mapping, amount, name, date, pending: false, source_id: SecureRandom.uuid, transaction_type: nil)
+ status = pending ? "pending" : "booked"
+ transacted_at = [ date.in_time_zone(mapping.ledger_timezone).noon, Time.current ].min
+ payload = {
+ "source_id" => source_id, "source_account_id" => mapping.source_id,
+ "lineage_id" => mapping.financekit_account_lineage_id, "mapping_version" => mapping.mapping_version,
+ "status" => status, "transaction_type" => transaction_type || (amount.negative? ? "payment" : "purchase"),
+ "transaction_description" => name, "original_transaction_description" => name,
+ "transacted_at" => transacted_at.iso8601,
+ "amount" => { "amount" => format("%.2f", amount.abs), "currency" => "USD",
+ "direction" => amount.negative? ? "credit" : "debit" }
+ }
+ payload["posted_at"] = transacted_at.iso8601 unless pending
+ entry = mapping.account.entries.create!(name: name, date: transacted_at.in_time_zone(mapping.ledger_timezone).to_date, amount: amount, currency: "USD",
+ source: "financekit", external_id: "financekit:#{mapping.financekit_account_lineage_id}:#{source_id}",
+ entryable: Transaction.new(extra: { "financekit" => payload.merge("pending" => pending) }))
+ mapping.financekit_transactions.create!(financekit_account: mapping, entry: entry, source_id: source_id,
+ generation: @item.generation, sequence: 1, status: status, ledger_imported: true, raw_payload: payload)
+ end
+
+ def record_balance!(mapping)
+ total = mapping.financekit_transactions.where(status: "booked").joins(:entry).sum("entries.amount")
+ balance = mapping.accountable_type == "CreditCard" ? total : -total
+ direction = mapping.accountable_type == "CreditCard" ? "debit" : "credit"
+ mapping.financekit_balance_observations.create!(financekit_account: mapping, source_id: SecureRandom.uuid,
+ kind: "booked", amount: balance, currency: "USD", direction: direction, observed_at: Time.current)
+ Account::ProviderImportAdapter.new(mapping.account).update_balance(balance: balance, source: "financekit")
+ end
+end
diff --git a/app/models/demo/generator.rb b/app/models/demo/generator.rb
index 19109de3f8..f5a09e5d0c 100644
--- a/app/models/demo/generator.rb
+++ b/app/models/demo/generator.rb
@@ -322,6 +322,9 @@ class Demo::Generator
@personal_loc = family.accounts.create!(accountable: OtherLiability.new, name: "Personal Line of Credit", balance: 0, currency: "USD")
+ @financekit_generator = Demo::FinancekitGenerator.new(family, seed: seed)
+ @financekit_generator.create_accounts!
+
# Other asset (USD)
@jewelry = family.accounts.create!(accountable: OtherAsset.new, name: "Jewelry Collection", balance: 0, currency: "USD")
end
@@ -377,6 +380,9 @@ class Demo::Generator
puts " 🔒 Generating crypto & misc asset transactions..."
generate_crypto_and_misc_assets!
+ puts " 👛 Generating Apple Wallet transactions..."
+ @financekit_generator.create_transactions!
+
puts " ✅ Reconciling balances to target snapshot..."
reconcile_balances!(family)
diff --git a/app/models/depository.rb b/app/models/depository.rb
index 96809cc619..bea5d54964 100644
--- a/app/models/depository.rb
+++ b/app/models/depository.rb
@@ -4,6 +4,7 @@ class Depository < ApplicationRecord
DEFAULT_SUBTYPE = "checking"
SUBTYPES = {
+ "cash" => { short: "Cash", long: "Cash" },
"checking" => { short: "Checking", long: "Checking" },
"savings" => { short: "Savings", long: "Savings" },
"hsa" => { short: "HSA", long: "Health Savings Account" },
diff --git a/app/models/financekit/diagnostics.rb b/app/models/financekit/diagnostics.rb
new file mode 100644
index 0000000000..52d0f052dd
--- /dev/null
+++ b/app/models/financekit/diagnostics.rb
@@ -0,0 +1,20 @@
+class Financekit::Diagnostics
+ # Only operational identifiers and counts belong here. Never pass exception
+ # messages, payloads, credentials, or financial fields into debug metadata.
+ def self.capture(item:, source:, message:, level: "info", batch: nil, account_provider: nil, **details)
+ metadata = {
+ connection_id: item.id, publisher_id: item.publisher_id,
+ generation: item.generation, stream_id: item.stream_id,
+ connection_status: item.status, next_sequence: item.next_sequence
+ }
+ if batch
+ metadata.merge!(batch_id: batch.batch_id, capture_id: batch.capture_id,
+ sequence: batch.sequence, chunk_index: batch.chunk_index, chunk_count: batch.chunk_count,
+ batch_status: batch.status, attempts: batch.attempts, retry_at: batch.retry_at&.iso8601)
+ end
+
+ DebugLogEntry.capture(category: "provider_sync", level: level, message: message,
+ source: source, provider_key: "financekit", family: item.family, user: item.user,
+ account_provider: account_provider, metadata: metadata.merge(details))
+ end
+end
diff --git a/app/models/financekit/downstream.rb b/app/models/financekit/downstream.rb
index 9619d9778b..f1c2f6edc9 100644
--- a/app/models/financekit/downstream.rb
+++ b/app/models/financekit/downstream.rb
@@ -7,18 +7,22 @@ class Financekit::Downstream
return if @batch.downstream_completed_at?
item = @batch.financekit_item
- item.selected_accounts.includes(financekit_account_lineage: :account).find_each do |mapping|
+ account_provider = nil
+ item.selected_accounts.includes(financekit_account_lineage: [ :account, :account_provider ]).find_each do |mapping|
+ account_provider = mapping.financekit_account_lineage.account_provider
mapping.account&.sync_later
end
+ account_provider = nil
item.family.auto_match_transfers!
item.family.rules.where(active: true).find_each(&:apply_later)
completed_at = Time.current
@batch.update!(downstream_completed_at: completed_at)
item.update!(last_downstream_at: completed_at)
- rescue StandardError
- DebugLogEntry.capture(category: "provider_sync", level: "error",
- message: "FinanceKit downstream scheduling failed", source: self.class.name,
- provider_key: "financekit", family: @batch.financekit_item.family,
- metadata: { batch_id: @batch.batch_id })
+ Financekit::Diagnostics.capture(item: item, batch: @batch, source: self.class.name,
+ message: "FinanceKit downstream scheduling completed", event: "downstream_completed")
+ rescue StandardError => error
+ Financekit::Diagnostics.capture(item: @batch.financekit_item, batch: @batch, source: self.class.name,
+ level: "error", message: "FinanceKit downstream scheduling failed", event: "downstream_failed",
+ account_provider: account_provider, error_class: error.class.name)
end
end
diff --git a/app/models/financekit/payload.rb b/app/models/financekit/payload.rb
index f9af5c2afb..99cb892bb5 100644
--- a/app/models/financekit/payload.rb
+++ b/app/models/financekit/payload.rb
@@ -152,7 +152,8 @@ class Financekit::Payload
Financekit.require!(record["merchant_category_code"].is_a?(Integer) && record["merchant_category_code"].between?(-32_768, 32_767))
end
Financekit.require!(timestamp!(record["transacted_at"]) <= capture)
- Financekit.require!(record.key?("posted_at")) if record["status"] == "booked"
+ # Apple Card can be booked without a posted date; ledger_date already
+ # falls back to the required transacted_at in the account's timezone.
Financekit.require!(timestamp!(record["posted_at"]) <= capture) if record.key?("posted_at")
unique!(seen, [ "transaction", mapping.financekit_account_lineage_id, record["source_id"].downcase ])
end
diff --git a/app/models/financekit/processor.rb b/app/models/financekit/processor.rb
index 913a1643e7..3acc784cca 100644
--- a/app/models/financekit/processor.rb
+++ b/app/models/financekit/processor.rb
@@ -40,6 +40,8 @@ class Financekit::Processor
last_imported_at: applied_at, last_captured_at: last.captured_at)
batch = last
end
+ Financekit::Diagnostics.capture(item: @item, batch: batch, source: self.class.name,
+ message: "FinanceKit capture imported", event: "capture_imported", counts: batch.counts, sync_id: batch.sync_id)
Financekit::Downstream.new(batch).perform!
true
rescue ActiveRecord::RecordInvalid => error
@@ -54,16 +56,16 @@ class Financekit::Processor
# unlucky save.
Rails.error.report(error, handled: true,
context: { financekit_item_id: @item.id, batch_id: batch&.batch_id })
- fail_batch!(batch, "import_validation", permanent: false)
+ fail_batch!(batch, "import_validation", permanent: false, error_class: error.class.name)
false
rescue Financekit::Error, JSON::ParserError => error
# Not retryable. The stored payload is immutable, so a protocol violation
# or bytes that no longer parse give every later attempt the same input.
- fail_batch!(batch, error.is_a?(Financekit::Error) ? error.code : "import_validation", permanent: true)
+ fail_batch!(batch, error.is_a?(Financekit::Error) ? error.code : "import_validation", permanent: true, error_class: error.class.name)
false
rescue StandardError => error
Rails.error.report(error, handled: true, context: { financekit_item_id: @item.id, batch_id: batch&.batch_id })
- fail_batch!(batch, "processing_error", permanent: false)
+ fail_batch!(batch, "processing_error", permanent: false, error_class: error.class.name)
false
end
@@ -219,10 +221,10 @@ class Financekit::Processor
end
end
identity.save!
- DebugLogEntry.capture(category: "provider_sync", level: "info", message: "FinanceKit tombstone processed",
- source: self.class.name, provider_key: "financekit", family: @item.family,
- metadata: { batch_id: batch.batch_id, source_identity_id: identity.id,
- review_required: identity.review_required })
+ Financekit::Diagnostics.capture(item: @item, batch: batch, source: self.class.name,
+ message: "FinanceKit tombstone processed", event: "tombstone_processed",
+ account_provider: mapping.financekit_account_lineage.account_provider,
+ source_identity_id: identity.id, review_required: identity.review_required)
end
# A conflict the family resolved with "keep_sure" settles that source
@@ -301,8 +303,12 @@ class Financekit::Processor
end
end
- def fail_batch!(batch, code, permanent:)
- return unless batch
+ def fail_batch!(batch, code, permanent:, error_class:)
+ unless batch
+ Financekit::Diagnostics.capture(item: @item, source: self.class.name, level: "error",
+ message: "FinanceKit import blocked", event: "import_blocked", error_code: code, error_class: error_class)
+ return
+ end
@item.with_lock do
batch.reload
@@ -319,8 +325,10 @@ class Financekit::Processor
retry_at: Time.current + (2**attempts).minutes)
end
end
- DebugLogEntry.capture(category: "provider_sync", level: "error", message: "FinanceKit import requires attention",
- source: self.class.name, provider_key: "financekit", family: @item.family,
- metadata: { batch_id: batch.batch_id, error_code: code })
+ retrying = batch.status == "accepted"
+ Financekit::Diagnostics.capture(item: @item, batch: batch, source: self.class.name,
+ level: retrying ? "warn" : "error",
+ message: retrying ? "FinanceKit import retry scheduled" : "FinanceKit import requires repair",
+ event: retrying ? "import_retry" : "import_failed", error_code: code, error_class: error_class)
end
end
diff --git a/app/models/financekit_account_lineage.rb b/app/models/financekit_account_lineage.rb
index f9518a6f60..cde903e68d 100644
--- a/app/models/financekit_account_lineage.rb
+++ b/app/models/financekit_account_lineage.rb
@@ -5,4 +5,13 @@ class FinancekitAccountLineage < ApplicationRecord
has_many :financekit_transactions, dependent: :destroy
has_many :financekit_balance_observations, dependent: :destroy
has_one :account_provider, as: :provider, dependent: :destroy
+
+ # A publisher credential covers every account in its connection. Fence its
+ # queued uploads before releasing links, retaining identities for re-enrollment.
+ def disconnect!
+ family.with_lock do
+ family.financekit_items.where(id: financekit_accounts.select(:financekit_item_id))
+ .where.not(status: "revoked").order(:id).each(&:disconnect!)
+ end
+ end
end
diff --git a/app/models/financekit_batch.rb b/app/models/financekit_batch.rb
index 47a5b76345..da005b31bd 100644
--- a/app/models/financekit_batch.rb
+++ b/app/models/financekit_batch.rb
@@ -56,10 +56,25 @@ class FinancekitBatch < ApplicationRecord
accepted_at: accepted_at, payload: raw_payload)
item.update!(last_device_contact_at: accepted_at, last_accepted_at: accepted_at)
end
- FinancekitInboxJob.perform_later(item.id) if batch.previously_new_record?
+ if batch.previously_new_record?
+ Financekit::Diagnostics.capture(item: item, batch: batch, source: name,
+ message: "FinanceKit upload accepted", event: "upload_accepted",
+ event_count: data["events"].size, payload_bytes: raw_payload.bytesize)
+ FinancekitInboxJob.perform_later(item.id)
+ end
batch
rescue JSON::ParserError
+ Financekit::Diagnostics.capture(item: item, source: name, level: "warn",
+ message: "FinanceKit upload rejected", event: "upload_rejected", error_code: "invalid_json")
raise Financekit::Error.new("invalid_json", 400)
+ rescue Financekit::Error => error
+ Financekit::Diagnostics.capture(item: item, source: name, level: "warn",
+ message: "FinanceKit upload rejected", event: "upload_rejected", error_code: error.code, http_status: error.status)
+ raise
+ rescue StandardError => error
+ Financekit::Diagnostics.capture(item: item, batch: batch, source: name, level: "error",
+ message: "FinanceKit upload failed", event: "upload_failed", error_class: error.class.name)
+ raise
end
def receipt
diff --git a/app/models/provider/metadata.rb b/app/models/provider/metadata.rb
index e956af53fd..1f8bed821b 100644
--- a/app/models/provider/metadata.rb
+++ b/app/models/provider/metadata.rb
@@ -1,6 +1,7 @@
class Provider
module Metadata
REGISTRY = {
+ financekit: { region: "US / UK", kinds: %w[Bank], maturity: :beta, logo_text: "AW", logo_color: nil, domain: "apple.com", name: "Apple Wallet" },
akahu: { region: "NZ", kinds: %w[Bank Investment], maturity: :beta, logo_text: "AK", logo_color: "#059669", domain: "akahu.nz" },
simplefin: { region: "US", kinds: %w[Bank Investment], maturity: :stable, logo_text: "SF", logo_color: "#2563eb", domain: "simplefin.org" },
lunchflow: { region: "Global", kinds: %w[Bank], maturity: :stable, logo_text: "LF", logo_color: "#f97316", domain: "lunchflow.app" },
diff --git a/app/views/accounts/_account_sidebar_tabs.html.erb b/app/views/accounts/_account_sidebar_tabs.html.erb
index 3213402613..d1115a04c3 100644
--- a/app/views/accounts/_account_sidebar_tabs.html.erb
+++ b/app/views/accounts/_account_sidebar_tabs.html.erb
@@ -111,10 +111,10 @@
<% end %>
<% end %>
</div>
-<%= javascript_tag nonce: true do %>
+<script nonce="<%= content_security_policy_nonce %>">
// Expand/Collapse all for the account sidebar. Event-delegated on document
// so it works for both the desktop and mobile sidebar instances and survives
- // Turbo re-renders. Wrapped in javascript_tag for CSP nonce compliance
+ // Turbo re-renders. Includes a nonce for CSP compliance
// (matches the dashboard balance sheet).
(function () {
function setLabel(btn, expanded) {
@@ -174,5 +174,5 @@
syncPanel(panel);
});
})();
-<% end %>
+</script>
<% end %>
diff --git a/app/views/accounts/confirm_unlink.html.erb b/app/views/accounts/confirm_unlink.html.erb
index e61cfd9252..6ca90cff14 100644
--- a/app/views/accounts/confirm_unlink.html.erb
+++ b/app/views/accounts/confirm_unlink.html.erb
@@ -9,6 +9,9 @@
<div class="mb-4">
<%= render DS::Alert.new(title: t("accounts.confirm_unlink.warning_title"), variant: :warning) do %>
<ul class="list-disc list-inside">
+ <% if @account.linked_to?("FinancekitAccountLineage") %>
+ <li><%= t("accounts.confirm_unlink.warning_wallet_connection") %></li>
+ <% end %>
<li><%= t("accounts.confirm_unlink.warning_no_sync") %></li>
<li><%= t("accounts.confirm_unlink.warning_manual_updates") %></li>
<li><%= t("accounts.confirm_unlink.warning_transactions_kept") %></li>
diff --git a/app/views/accounts/index.html.erb b/app/views/accounts/index.html.erb
index 3a2b228ba4..b9bb037e32 100644
--- a/app/views/accounts/index.html.erb
+++ b/app/views/accounts/index.html.erb
@@ -10,10 +10,14 @@
) %>
<% end %>
-<% if @manual_accounts.empty? && @plaid_items.empty? && @simplefin_items.empty? && @lunchflow_items.empty? && @redbark_items.empty? && @akahu_items.empty? && @up_items.empty? && @monobank_items.empty? && @fio_items.empty? && @enable_banking_items.empty? && @coinstats_items.empty? && @coinbase_items.empty? && @mercury_items.empty? && @brex_items.empty? && @ibkr_items.empty? && @snaptrade_items.empty? && @indexa_capital_items.empty? && @sophtron_items.empty? && @binance_items.empty? && @kraken_items.empty? && @coinspot_items.empty? && @questrade_items.empty? && @wise_items.empty? && @onchain_wallet_items.empty? && @trade_republic_items.empty? && @trading212_items.empty? %>
+<% if @manual_accounts.empty? && @financekit_accounts.empty? && @plaid_items.empty? && @simplefin_items.empty? && @lunchflow_items.empty? && @redbark_items.empty? && @akahu_items.empty? && @up_items.empty? && @monobank_items.empty? && @fio_items.empty? && @enable_banking_items.empty? && @coinstats_items.empty? && @coinbase_items.empty? && @mercury_items.empty? && @brex_items.empty? && @ibkr_items.empty? && @snaptrade_items.empty? && @indexa_capital_items.empty? && @sophtron_items.empty? && @binance_items.empty? && @kraken_items.empty? && @coinspot_items.empty? && @questrade_items.empty? && @wise_items.empty? && @onchain_wallet_items.empty? && @trade_republic_items.empty? && @trading212_items.empty? %>
<%= render "empty" %>
<% else %>
<div class="space-y-2">
+ <% if @financekit_accounts.any? %>
+ <%= render "accounts/index/financekit_accounts", accounts: @financekit_accounts %>
+ <% end %>
+
<% if @plaid_items.any? %>
<%= render @plaid_items.sort_by(&:created_at) %>
<% end %>
diff --git a/app/views/accounts/index/_financekit_accounts.html.erb b/app/views/accounts/index/_financekit_accounts.html.erb
new file mode 100644
index 0000000000..f75ad98e3a
--- /dev/null
+++ b/app/views/accounts/index/_financekit_accounts.html.erb
@@ -0,0 +1,16 @@
+<%# locals: (accounts:) %>
+
+<%= render DS::Disclosure.new(variant: :card, open: true, id: "financekit-accounts") do |disclosure| %>
+ <% disclosure.with_summary_content do %>
+ <div class="flex items-center gap-2">
+ <%= icon "chevron-right", class: "group-open:rotate-90 motion-safe:transition-transform motion-safe:duration-150" %>
+ <%= render ProviderLogo.new(provider_key: :financekit) %>
+ <span class="text-sm font-medium text-primary"><%= t(".title") %></span>
+ </div>
+ <% end %>
+
+ <div class="space-y-4 mt-4">
+ <p class="text-sm text-secondary"><%= t(".description") %></p>
+ <%= render "accounts/index/account_groups", accounts: accounts %>
+ </div>
+<% end %>
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index 0b2e0e9341..b2139db4e0 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -230,7 +230,7 @@ end %>
<% end %>
<% end %>
<%# Preserve the account sidebar's group open/closed state across Turbo Drive navigations so the sidebar height stays stable and the scroll position is not clamped to the top. See the inline script below for details. %>
-<%= javascript_tag nonce: true do %>
+<script nonce="<%= content_security_policy_nonce %>">
// Preserves the account sidebar's group open/closed state across Turbo Drive
// navigations so the sidebar height stays stable and the scroll position
// (restored by the `preserve-scroll` controller) is not clamped to the top.
@@ -377,6 +377,6 @@ end %>
restore();
})();
-<% end %>
+</script>
</div>
<% end %>
diff --git a/app/views/layouts/shared/_insights_button.html.erb b/app/views/layouts/shared/_insights_button.html.erb
index 4ec5fca140..e7402c0bd7 100644
--- a/app/views/layouts/shared/_insights_button.html.erb
+++ b/app/views/layouts/shared/_insights_button.html.erb
@@ -28,4 +28,4 @@
<span class="absolute top-1 right-1 min-w-4 h-4 px-1 rounded-full bg-inverse text-inverse text-[10px] font-medium flex items-center justify-center pointer-events-none"><%= unread_insights_count > 9 ? "9+" : unread_insights_count %></span>
<% end %>
<% end %>
-<% end %>
\ No newline at end of file
+<% end %>
diff --git a/app/views/pages/dashboard/_balance_sheet.html.erb b/app/views/pages/dashboard/_balance_sheet.html.erb
index ce165c1bb9..9b88898bff 100644
--- a/app/views/pages/dashboard/_balance_sheet.html.erb
+++ b/app/views/pages/dashboard/_balance_sheet.html.erb
@@ -148,10 +148,10 @@
in that manifest, so the browser would 404 it and the button would be dead on
the running image. An inline script is served with the HTML and re-runs
automatically when the surrounding Turbo frame re-renders (e.g. on a period
- change). Wrapped in javascript_tag for CSP nonce compliance.
+ change). Includes a nonce for CSP compliance.
%>
<% if balance_sheet.classification_groups.any? { |cg| cg.account_groups.any? } %>
-<%= javascript_tag nonce: true do %>
+<script nonce="<%= content_security_policy_nonce %>">
(function () {
var section = document.querySelector('section[data-section-key="balance_sheet"]');
var root = document.getElementById("balance-sheet");
@@ -207,5 +207,5 @@
syncButton();
})();
-<% end %>
+</script>
<% end %>
diff --git a/app/views/settings/providers/_connection_row.html.erb b/app/views/settings/providers/_connection_row.html.erb
index dfe88ea0da..16b088ac2a 100644
--- a/app/views/settings/providers/_connection_row.html.erb
+++ b/app/views/settings/providers/_connection_row.html.erb
@@ -9,7 +9,7 @@
when :err then "border border-destructive-subtle"
else "border border-transparent"
end
- sync_action = entry[:partial].present? ? render("settings/providers/sync_button", provider_key: entry[:provider_key], last_synced_at: last_synced) : nil
+ sync_action = entry[:partial].present? && entry[:sync_supported] != false ? render("settings/providers/sync_button", provider_key: entry[:provider_key], last_synced_at: last_synced) : nil
status_pill = render("settings/providers/status_pill", status: status)
maturity_lbl = Settings::ProviderCard.maturity_label(entry[:maturity])
details_data = entry[:auto_open_param].present? ? { controller: "auto-open", auto_open_param_value: entry[:auto_open_param] } : {}
diff --git a/app/views/settings/providers/_financekit_panel.html.erb b/app/views/settings/providers/_financekit_panel.html.erb
new file mode 100644
index 0000000000..f9aa7b0454
--- /dev/null
+++ b/app/views/settings/providers/_financekit_panel.html.erb
@@ -0,0 +1,35 @@
+<div class="space-y-4">
+ <p class="text-sm text-secondary"><%= t("settings.providers.financekit.description") %></p>
+
+ <% @financekit_connections.each do |connection| %>
+ <% item = connection[:item] %>
+ <section class="space-y-3" aria-label="<%= t("settings.providers.financekit.summary") %>">
+ <%= render DS::Pill.new(label: t("settings.providers.financekit.status.#{item.status}"),
+ tone: item.status == "active" ? :success : :warning, marker: false, show_dot: true, size: :sm) %>
+
+ <dl class="divide-y divide-primary text-sm">
+ <% { last_accepted_at: item.last_accepted_at, last_imported_at: item.last_imported_at }.each do |key, timestamp| %>
+ <div class="flex flex-wrap justify-between gap-2 py-2">
+ <dt class="text-primary"><%= t("settings.providers.financekit.#{key}") %></dt>
+ <dd class="text-secondary">
+ <% if timestamp %>
+ <%= tag.time l(timestamp, format: :long), datetime: timestamp.iso8601 %>
+ <% else %>
+ <%= t("settings.providers.financekit.not_yet") %>
+ <% end %>
+ </dd>
+ </div>
+ <% end %>
+ </dl>
+
+ <ul class="space-y-2" aria-label="<%= t("settings.providers.financekit.accounts") %>">
+ <% connection[:accounts].each do |account| %>
+ <li class="flex flex-wrap items-center justify-between gap-2 text-sm">
+ <%= link_to account.name, account_path(account), class: "text-primary underline", data: { turbo_frame: "_top" } %>
+ <span class="text-secondary"><%= format_money(account.balance_money) %></span>
+ </li>
+ <% end %>
+ </ul>
+ </section>
+ <% end %>
+</div>
diff --git a/app/views/settings/providers/show.html.erb b/app/views/settings/providers/show.html.erb
index df97f2fe38..851f821901 100644
--- a/app/views/settings/providers/show.html.erb
+++ b/app/views/settings/providers/show.html.erb
@@ -10,7 +10,7 @@
<% else %>
<div class="flex items-center justify-between gap-4">
<p class="text-secondary"><%= t("settings.providers.bank_sync.lede") %></p>
- <% if @connected.any? || @needs_attention.any? %>
+ <% if @can_sync_all %>
<% sync_all_disabled = Current.family.last_sync_all_attempted_at.present? && Current.family.last_sync_all_attempted_at > 30.seconds.ago %>
<%= render DS::Button.new(
text: t("settings.providers.sync_all"),
@@ -80,7 +80,8 @@
region: meta[:region],
kinds: meta[:kinds],
tier: meta[:tier],
- maturity: meta[:maturity] || :stable
+ maturity: meta[:maturity] || :stable,
+ external_link: entry[:external_link]
) %>
<% end %>
</div>
diff --git a/config/locales/views/accounts/en.yml b/config/locales/views/accounts/en.yml
index e76606734c..19e6b93fe6 100644
--- a/config/locales/views/accounts/en.yml
+++ b/config/locales/views/accounts/en.yml
@@ -55,6 +55,9 @@ en:
enable_category_matcher_hint: When enabled, the provider's suggested category is applied to imported transactions. Disable to leave new transactions uncategorized.
index:
accounts: Accounts
+ financekit_accounts:
+ title: Apple Wallet
+ description: Manage Apple Wallet connections and sync in the Sure iOS app.
cancel_sync: Cancel sync
manual_accounts:
other_accounts: Other accounts
@@ -188,6 +191,7 @@ en:
title: Unlink account from provider?
description_html: "You are about to unlink <strong>%{account_name}</strong> from <strong>%{provider_name}</strong>. This will convert it to a manual account."
warning_title: What this means
+ warning_wallet_connection: All accounts in this Apple Wallet connection will be unlinked. Their transactions and balances will be preserved. You can reconnect through the Sure iOS app with a new Wallet setup.
warning_no_sync: The account will no longer sync automatically with your provider
warning_manual_updates: You will need to add transactions and update balances manually
warning_transactions_kept: All existing transactions and balances will be preserved
diff --git a/config/locales/views/depositories/en.yml b/config/locales/views/depositories/en.yml
index 99cc944d15..551e26c76c 100644
--- a/config/locales/views/depositories/en.yml
+++ b/config/locales/views/depositories/en.yml
@@ -9,6 +9,9 @@ en:
new:
title: Enter account balance
subtypes:
+ cash:
+ long: Cash
+ short: Cash
cd:
long: Certificate of Deposit
short: CD
diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.yml
index 5fe78ba202..3e1e11b8b1 100644
--- a/config/locales/views/settings/en.yml
+++ b/config/locales/views/settings/en.yml
@@ -413,6 +413,21 @@ en:
eyebrow: Setup
need_help: "Need help?"
connect: Connect
+ financekit:
+ app_store: App Store
+ coming_soon: Coming soon!
+ description: "Manage Apple Wallet connections in the Sure iOS app. Wallet data syncs while the app is open; unattended background sync is not available yet."
+ summary: Wallet sync
+ accounts: Linked accounts
+ linked_accounts:
+ one: 1 linked account
+ other: "%{count} linked accounts"
+ status:
+ active: Sync active
+ repair_required: Repair required — open the Sure iOS app
+ last_accepted_at: Last accepted by Sure
+ last_imported_at: Last imported into your family
+ not_yet: Not yet
groups:
your_connections: Your connections
available: Available
@@ -437,6 +452,7 @@ en:
sync_provider_in_progress: Sync started.
recently_synced: Synced recently. Try again in a moment.
taglines:
+ financekit: Sync (some) FinanceKit accounts through the Sure iOS app.
akahu: Sync New Zealand financial institutions via Akahu.
simplefin: Connect US bank accounts via the open SimpleFIN protocol.
lunchflow: Connect 20k+ banks from 40+ countries (UK, EU, USA and more!)
diff --git a/docs/hosting/financekit.md b/docs/hosting/financekit.md
index 211772f15c..fe6bcb9232 100644
--- a/docs/hosting/financekit.md
+++ b/docs/hosting/financekit.md
@@ -32,12 +32,86 @@ After deploy:
Monitor queue depth, oldest accepted batch age, `repair_required` connections, and downstream lag. Diagnostics may include publisher, batch, sequence, generation, and typed error codes. They must not include credentials, raw request bodies, transaction descriptions, merchant names, amounts, account names, or server authentication headers.
+## Transaction dates
+
+`posted_at` is optional, including for booked Apple Card transactions. When
+supplied, it must still be a valid timestamp no later than the capture timestamp.
+Ledger dates retain their existing precedence: `posted_at`, otherwise the
+required `transacted_at`, converted into the mapped account's ledger timezone.
+
+## Wallet in settings
+
+Bank sync lists Apple Wallet as a US / UK bank provider. Existing connections
+appear under Your Connections with sync status, acceptance and import timestamps,
+and links to accounts the viewer can access. Wallet accounts also appear in Accounts.
+
+Accounts can be unlinked from the web UI. Because a publisher credential covers
+all selected Wallet accounts, unlinking one disconnects that Wallet connection
+and makes its accounts manual. This revokes the credential and queued uploads
+while preserving accounts, balances, transactions, and source identities. The
+iOS client can start a new enrollment with a new enrollment ID and map its Apple
+source account IDs again; existing accounts and imported transactions are reused
+without requiring the old connection or stream state.
+
+## Debugging uploads
+
+Super admins can open `/settings/debug?provider_key=financekit` and filter further
+by family, level, or source. Events share `connection_id`, `publisher_id`,
+`generation`, `stream_id`, and `next_sequence`. Accepted batches also include
+`batch_id`, `capture_id`, sequence/chunk information, payload size, and event count.
+
+- `upload_accepted` means Sure stored the upload; it does not mean ledger import
+ has completed. An accepted sequence ahead of `next_sequence` is waiting for its
+ predecessor; a multi-chunk capture waits for all its chunks.
+- `upload_rejected` records a typed protocol error and HTTP status when an
+ authenticated upload fails validation. Identical accepted retries reuse their
+ receipt without another acceptance log.
+- `capture_imported` records the resulting sync ID and counts, including records
+ requiring conflict review.
+- `import_retry` includes the attempt count, retry deadline, error code, and
+ exception class. `import_failed` means repair is required; `import_blocked`
+ covers failures before a batch could be selected.
+- `downstream_completed` means account updates and rules were scheduled.
+ `downstream_failed` includes the affected account/provider link when available;
+ the inbox sweep retries this stage.
+
+These diagnostics deliberately omit exception messages and financial payloads.
+Requests rejected before reaching the batch inbox (such as invalid publisher
+credentials or content type) do not create these model-level events.
+
+## Sample accounts
+
+The standard demo account and transaction phases include a synthetic Apple Wallet connection with Apple
+Card (`CreditCard`), Apple Cash, and Nancy's Apple Cash (`Depository`, subtype `cash`). It includes a
+year of card purchases/payments and cash purchases/top-ups, plus pending activity,
+source identities, balance observations, and acceptance/import timestamps.
+Apple Cash receives a simulated 1% Daily Cash reward the day after each day's
+booked Apple Card purchases (excluding pending charges and payments), categorized
+as Cash Back. Six small gifts link the parent's Apple Cash to Nancy's account.
+Nancy spends some of each gift on candy, movies, after-school snacks, and ice
+cream: a few categorized purchases per month, with a positive running balance.
+These additions also populate older demo enrollments in place; stable source IDs
+prevent duplicate rewards, gifts, and purchases on reruns.
+
+To add just these accounts to an existing demo family without replacing its data:
+
+```sh
+FAMILY_ID=<demo-family-uuid> bin/rails demo_data:financekit
+```
+
+Alternatively use `DEMO_EMAIL=<demo-user-email>` (defaults to the configured demo
+email). `SEED=42` controls the generated amounts and merchants. Reruns preserve
+the existing demo enrollment and transactions, and upgrade older synthetic data
+with merchant-specific categories and paired transfers. Apple Card payments and
+Apple Cash top-ups come from the demo owner's manual Chase Premier Checking
+account; if absent, a funded Wallet Demo Checking account is created. Subsequent
+reruns preserve category edits and do not duplicate either transfer leg.
+Wallet demo data is included in every environment by both the full generator
+and sample-data reset flow. It does not enable FinanceKit feature flags or change
+user permissions. These records simulate imported data; no iOS device is required.
+
## Capacity and retention
Protocol 2 limits each publisher to 20 selected accounts, 500 events per batch, 1 MiB of JSON, and 100 accepted/processing batches. Each capture is limited to 100 chunks so the complete capture fits in the inbox. A client can upload larger histories using multiple consecutive captures.
Exact payload bytes are retained for seven days after apply, permanent failure, or revocation for response-loss recovery and operational investigation. Canonical financial data and source identity records follow Sure's normal family retention and deletion behavior. Family financial-data reset removes FinanceKit connections, lineages, observations, identities, conflicts, and batch receipts for that family.
-
-## Rollback
-
-Disable `FINANCEKIT_ENABLED` first. Existing Sure data remains readable, uploads return a retryable unavailable response, and workers stop applying FinanceKit batches. Do not drop the tables during an application rollback; keep receipts and lineage data until all deployed versions no longer reference them and the retention decision is explicit.
diff --git a/lib/tasks/demo_data.rake b/lib/tasks/demo_data.rake
index 7e5c2f4b33..1762ad90c4 100644
--- a/lib/tasks/demo_data.rake
+++ b/lib/tasks/demo_data.rake
@@ -1,4 +1,16 @@
namespace :demo_data do
+ desc "Add Apple Card and family Apple Cash accounts to an existing demo family"
+ task financekit: :environment do
+ family = if ENV["FAMILY_ID"].present?
+ Family.find(ENV.fetch("FAMILY_ID"))
+ else
+ email = ENV.fetch("DEMO_EMAIL", Rails.application.config_for(:demo).fetch(:email))
+ User.find_by!(email: email).family
+ end
+ item = Demo::FinancekitGenerator.new(family, seed: ENV.fetch("SEED", 42)).generate!
+ puts "Apple Wallet demo ready: #{item.accounts.count} linked accounts."
+ end
+
desc "Load empty demo dataset (no financial data)"
task empty: :environment do
start = Time.now
diff --git a/test/components/provider_logo_test.rb b/test/components/provider_logo_test.rb
index a4d2f49b0b..9e7be0a0c1 100644
--- a/test/components/provider_logo_test.rb
+++ b/test/components/provider_logo_test.rb
@@ -16,6 +16,13 @@ class ProviderLogoTest < ViewComponent::TestCase
assert_selector "span[aria-hidden='true'] + img"
end
+ test "Apple Wallet uses the standard Apple domain logo" do
+ render_inline(ProviderLogo.new(provider_key: :financekit))
+
+ assert_selector "img[src='https://cdn.brandfetch.io/apple.com/icon/fallback/404/w/40/h/40?c=test-client-id']"
+ assert_selector "span[aria-hidden='true'] + img"
+ end
+
test "renders only the fallback when the provider has no domain" do
stub_metadata(logo_icon: "wallet", logo_text: "EX", logo_color: "#6b7280")
diff --git a/test/components/settings/provider_card_test.rb b/test/components/settings/provider_card_test.rb
index 33df478a9a..b3a2b8a4b5 100644
--- a/test/components/settings/provider_card_test.rb
+++ b/test/components/settings/provider_card_test.rb
@@ -1,6 +1,33 @@
require "test_helper"
-class Settings::ProviderCardTest < ActiveSupport::TestCase
+class Settings::ProviderCardTest < ViewComponent::TestCase
+ test "external setup uses the provider label and opens outside the connection drawer" do
+ render_inline(Settings::ProviderCard.new(provider_key: "example", name: "Example",
+ external_link: { text: "Provider website", href: "https://example.com/setup" }))
+
+ assert_selector "div[data-providers-filter-target='card']"
+ assert_selector "a[href='https://example.com/setup'][target='_blank'][rel='noopener noreferrer'][data-turbo='false']",
+ text: "Provider website"
+ assert_no_selector "a[data-turbo-frame='drawer']"
+ assert_no_selector "button[disabled]"
+ end
+
+ test "external setup without a URL shows the provider's disabled label and tooltip" do
+ render_inline(Settings::ProviderCard.new(provider_key: "example", name: "Example",
+ external_link: { text: "Provider website", href: nil, tooltip: "Setup unavailable" }))
+
+ assert_selector "button[disabled]", text: "Provider website"
+ assert_selector "[title='Setup unavailable'][tabindex='0'][aria-description='Setup unavailable']"
+ assert_no_selector "a"
+ end
+
+ test "regular providers still open the connection drawer" do
+ render_inline(Settings::ProviderCard.new(provider_key: "example", name: "Example"))
+
+ assert_selector "a[data-providers-filter-target='card'][data-turbo-frame='drawer'][href='/settings/providers/example/connect_form']",
+ text: "Connect"
+ end
+
test "metadata line displays multiple kinds" do
card = Settings::ProviderCard.new(
provider_key: "example",
diff --git a/test/controllers/financekit_accounts_test.rb b/test/controllers/financekit_accounts_test.rb
new file mode 100644
index 0000000000..ca7b008fa0
--- /dev/null
+++ b/test/controllers/financekit_accounts_test.rb
@@ -0,0 +1,194 @@
+require "test_helper"
+require_relative "../support/financekit_test_helper"
+
+class FinancekitAccountsTest < ActionDispatch::IntegrationTest
+ include FinancekitTestHelper
+ include ActionView::RecordIdentifier
+
+ setup do
+ ensure_tailwind_build
+ financekit_setup(user: users(:empty))
+ sign_in @user
+ end
+
+ test "a family with only FinanceKit accounts sees them on the accounts index" do
+ get accounts_url
+
+ assert_response :success
+ assert_select "#financekit-accounts" do
+ assert_select "summary", text: /Apple Wallet/
+ assert_select "a[href=?][data-turbo-frame='_top']", account_path(@source.account), text: "Test Wallet"
+ assert_select "turbo-frame##{dom_id(@source.account)}"
+ end
+ assert_select "#manual-accounts a[href=?]", account_path(@source.account), count: 0
+ end
+
+ test "FinanceKit account detail renders imported transactions" do
+ accept_and_apply
+
+ get account_url(@source.account)
+
+ assert_response :success
+ assert_select "header h2", text: "Test Wallet"
+ assert_includes response.body, "Synthetic shop"
+ end
+
+ test "Wallet accounts can unlink and reconnect from a fresh client enrollment" do
+ accept_and_apply
+ account = @source.account
+ entry = account.entries.sole
+ lineage = @source.financekit_account_lineage
+ old_stream = @item.reload.stream_id
+ queued, = accept_batch(financekit_payload(sequence: @item.next_sequence,
+ predecessor_digest: @item.predecessor_digest))
+
+ get accounts_url
+ assert_response :success
+ assert_select "a[href=?]", confirm_unlink_account_path(account)
+
+ get confirm_unlink_account_url(account)
+ assert_response :success
+ assert_includes response.body, I18n.t("accounts.confirm_unlink.warning_wallet_connection")
+
+ assert_no_difference [ "Account.count", "Entry.count", "FinancekitAccount.count", "FinancekitTransaction.count" ] do
+ delete unlink_account_url(account)
+ end
+ assert_redirected_to accounts_url
+ assert_not account.reload.linked?
+ assert_equal "revoked", @item.reload.status
+ assert_not @item.authenticate_credential?(@credential)
+ assert_equal "revoked", queued.reload.status
+ assert_equal "connection_revoked", queued.error_code
+ assert_nil queued.payload
+ assert_not Financekit::Processor.new(@item).apply_next!
+ error = assert_raises(Financekit::Error) { accept_batch }
+ assert_equal "connection_revoked", error.code
+
+ get accounts_url
+ assert_select "#manual-accounts a[href=?]", account_path(account)
+ get account_url(account)
+ assert_response :success
+ assert_includes response.body, "Synthetic shop"
+
+ # A reset Swift client knows only its stable Apple source IDs, not the old
+ # connection, lineage, mapping version, stream or sequence.
+ fresh = Financekit::Enrollment.create!(@user, @enrollment.merge("enrollment_id" => SecureRandom.uuid)).item
+ assert_no_difference [ "Account.count", "FinancekitAccountLineage.count" ] do
+ @source = FinancekitAccount.map!(fresh, @source_id, @mapping_input)
+ end
+ assert_equal account, @source.account
+ assert_equal lineage, @source.financekit_account_lineage
+ assert_equal 2, @source.mapping_version
+ credential = fresh.activate!
+ assert fresh.authenticate_credential?(credential)
+ assert_not_equal old_stream, fresh.stream_id
+ assert_equal 1, fresh.next_sequence
+ assert_nil fresh.predecessor_digest
+ assert account.reload.linked?
+
+ assert_no_difference "Entry.count" do
+ accept_and_apply(financekit_payload(item: fresh), item: fresh)
+ end
+ assert_equal [ entry.id ], account.entries.reload.pluck(:id)
+
+ events = financekit_events
+ events.last["transaction"]["source_id"] = SecureRandom.uuid
+ events.last["transaction"]["transaction_description"] = "New purchase after reconnect"
+ events.last["transaction"]["merchant_name"] = "New purchase after reconnect"
+ fresh.reload
+ assert_difference "Entry.count", 1 do
+ accept_and_apply(financekit_payload(item: fresh, sequence: fresh.next_sequence,
+ predecessor_digest: fresh.predecessor_digest, events: events), item: fresh)
+ end
+ assert account.entries.exists?(name: "New purchase after reconnect")
+ end
+
+ test "unlink disconnects all accounts sharing the publisher even when FinanceKit is unavailable" do
+ second_source = SecureRandom.uuid
+ @item.update!(status: "repair_required", consent: @item.consent.merge(
+ "selected_source_account_ids" => [ @source_id, second_source ]))
+ second_mapping = FinancekitAccount.map!(@item, second_source, @mapping_input.merge("name" => "Apple Cash"))
+ @item.activate!
+ Financekit.stubs(:enabled?).returns(false)
+ @item.mark_repair!("test_failure")
+
+ delete unlink_account_url(@source.account)
+
+ assert_redirected_to accounts_url
+ assert_not @source.account.reload.linked?
+ assert_not second_mapping.account.reload.linked?
+ assert_equal "revoked", @item.reload.status
+ error = assert_raises(Financekit::Error) { @item.repair! }
+ assert_equal "connection_revoked", error.code
+ end
+
+ test "read only sharing and another family cannot disconnect a Wallet publisher" do
+ account = @source.account
+ viewer = users(:new_email)
+ account.account_shares.find_or_initialize_by(user: viewer).update!(permission: "read_only")
+ sign_in viewer
+
+ delete unlink_account_url(account)
+ assert_redirected_to account_url(account)
+ assert_equal "active", @item.reload.status
+ assert account.reload.linked?
+
+ sign_in users(:family_admin)
+ delete unlink_account_url(account)
+ assert_response :not_found
+ assert_equal "active", @item.reload.status
+ assert account.reload.linked?
+ end
+
+ test "failed unlink rolls back the Wallet revocation and provider links" do
+ queued, = accept_batch
+ Account.any_instance.stubs(:update!).raises(ActiveRecord::RecordInvalid.new(@source.account))
+
+ delete unlink_account_url(@source.account)
+
+ assert_redirected_to account_url(@source.account)
+ assert_equal "active", @item.reload.status
+ assert @item.authenticate_credential?(@credential)
+ assert @source.account.reload.linked?
+ assert_equal "accepted", queued.reload.status
+ assert queued.payload.present?
+ end
+
+ test "index shows disabled Wallet accounts but excludes pending deletion" do
+ @source.account.update!(status: "disabled")
+ get accounts_url
+ assert_response :success
+ assert_select "#financekit-accounts a[href=?]", account_path(@source.account)
+
+ @source.account.update!(status: "pending_deletion")
+ get accounts_url
+ assert_response :success
+ assert_select "#financekit-accounts", count: 0
+ end
+
+ test "index limits Wallet accounts to the viewer's owned and shared accounts" do
+ private_source_id = SecureRandom.uuid
+ @item.update!(status: "repair_required", consent: @item.consent.merge(
+ "selected_source_account_ids" => [ @source_id, private_source_id ]))
+ private_mapping = FinancekitAccount.map!(@item, private_source_id, @mapping_input.merge("name" => "Private Wallet"))
+ @item.activate!
+ shared = @source.account
+ [ shared, private_mapping.account ].each { |account| account.account_shares.destroy_all }
+ viewer = users(:new_email)
+ assert_equal @family, viewer.family
+ shared.account_shares.create!(user: viewer, permission: "read_only")
+
+ sign_in viewer
+ get accounts_url
+
+ assert_response :success
+ assert_select "#financekit-accounts a[href=?]", account_path(shared)
+ assert_select "#financekit-accounts a[href=?]", account_path(private_mapping.account), count: 0
+ assert_not_includes response.body, "Private Wallet"
+
+ sign_in users(:family_admin)
+ get accounts_url
+ assert_response :success
+ assert_select "#financekit-accounts", count: 0
+ end
+end
diff --git a/test/controllers/settings/debugs_controller_test.rb b/test/controllers/settings/debugs_controller_test.rb
index 23ca351604..1b2e0ebce4 100644
--- a/test/controllers/settings/debugs_controller_test.rb
+++ b/test/controllers/settings/debugs_controller_test.rb
@@ -90,4 +90,18 @@ class Settings::DebugsControllerTest < ActionDispatch::IntegrationTest
assert_response :success
assert_match @entry.message, response.body
end
+
+ test "FinanceKit diagnostics are visible and filterable by provider and family" do
+ sign_in users(:sure_support_staff)
+ DebugLogEntry.capture(category: "provider_sync", level: "error", message: "FinanceKit import requires repair",
+ source: "Financekit::Processor", provider_key: "financekit", family: families(:dylan_family),
+ metadata: { event: "import_failed", error_code: "predecessor_conflict" })
+
+ get settings_debug_url, params: { provider_key: "financekit", family_id: families(:dylan_family).id }
+
+ assert_response :success
+ assert_includes response.body, "FinanceKit import requires repair"
+ assert_includes response.body, "predecessor_conflict"
+ refute_includes response.body, @entry.message
+ end
end
diff --git a/test/controllers/settings/providers_controller_test.rb b/test/controllers/settings/providers_controller_test.rb
index e23052cea1..2d32ef2b58 100644
--- a/test/controllers/settings/providers_controller_test.rb
+++ b/test/controllers/settings/providers_controller_test.rb
@@ -1,7 +1,9 @@
require "test_helper"
+require_relative "../../support/financekit_test_helper"
class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTest
include ActiveJob::TestHelper
+ include FinancekitTestHelper
setup do
ensure_tailwind_build
@@ -11,6 +13,126 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTest
Provider::Factory.ensure_adapters_loaded
end
+ test "Apple Wallet is available through a disabled App Store button" do
+ get settings_providers_url
+
+ assert_response :success
+ assert_select "div[data-provider-name='apple wallet'][data-provider-region='us / uk'][data-provider-kind='bank']" do
+ assert_select "button[disabled]", text: "App Store"
+ assert_select "span[title='Coming soon!']"
+ assert_select "a", count: 0
+ assert_select "p", text: "US / UK · Bank"
+ end
+ end
+
+ test "linked Wallet accounts appear with upload and import summaries" do
+ financekit_setup
+ @item.update!(last_accepted_at: 2.hours.ago, last_imported_at: 1.hour.ago)
+
+ get settings_providers_url
+
+ assert_response :success
+ assert_select "[data-provider-name='apple wallet']", count: 0
+ assert_select "turbo-frame#financekit-providers-panel" do
+ assert_select "a[href=?][data-turbo-frame='_top']", account_path(@source.account), text: "Test Wallet"
+ assert_select "span", text: "Sync active"
+ assert_select "dt", text: "Last accepted by Sure"
+ assert_select "dt", text: "Last imported into your family"
+ assert_select "time[datetime=?]", @item.last_accepted_at.iso8601
+ assert_select "time[datetime=?]", @item.last_imported_at.iso8601
+ assert_select "form", count: 0
+ end
+ assert_select "form[action=?]", sync_provider_settings_providers_path(provider_key: "financekit"), count: 0
+ assert_includes @controller.view_assigns["connected"].map { |entry| entry[:provider_key] }, "financekit"
+ end
+
+ test "Wallet repairs retain linked accounts and missing timestamps show Not yet" do
+ financekit_setup
+ @item.mark_repair!("test_repair")
+
+ get settings_providers_url
+
+ assert_response :success
+ assert_select "turbo-frame#financekit-providers-panel" do
+ assert_select "span", text: "Repair required — open the Sure iOS app"
+ assert_select "dd", text: "Not yet", count: 2
+ assert_select "a", text: "Test Wallet"
+ end
+ assert_includes @controller.view_assigns["needs_attention"].map { |entry| entry[:provider_key] }, "financekit"
+ end
+
+ test "revoked Wallet connections return to available providers" do
+ financekit_setup
+ @item.disconnect!
+
+ get settings_providers_url
+
+ assert_response :success
+ assert_select "turbo-frame#financekit-providers-panel", count: 0
+ assert_select "[data-provider-name='apple wallet'] button[disabled]", text: "App Store"
+ end
+
+ test "Wallet-only connections never offer Sync all including when repair is needed" do
+ Provider::PlaidAdapter.configuration.stubs(:configured?).returns(false)
+ Provider::PlaidEuAdapter.configuration.stubs(:configured?).returns(false)
+ users(:empty).update!(family: Family.create!(name: "Wallet only", currency: "USD"))
+ financekit_setup(user: users(:empty))
+ sign_in @user
+
+ [ "active", "repair_required" ].each do |status|
+ @item.update!(status: status)
+ get settings_providers_url
+
+ assert_response :success
+ assert_select "turbo-frame#financekit-providers-panel"
+ connections = @controller.view_assigns.values_at("connected", "needs_attention").flatten
+ assert_equal [ "financekit" ], connections.map { |entry| entry[:provider_key] }
+ assert_select "form[action=?]", sync_all_settings_providers_path, count: 0
+ end
+
+ @family.simplefin_items.create!(name: "Test bank", access_url: "https://example.com/access")
+ get settings_providers_url
+ assert_response :success
+ assert_select "form[action=?]", sync_all_settings_providers_path
+ end
+
+ test "Wallet settings retain disabled accounts but exclude pending deletion" do
+ financekit_setup
+ @source.account.update!(status: "disabled")
+ get settings_providers_url
+ assert_response :success
+ assert_select "turbo-frame#financekit-providers-panel a[href=?]", account_path(@source.account)
+
+ @source.account.update!(status: "pending_deletion")
+ get settings_providers_url
+ assert_response :success
+ assert_select "turbo-frame#financekit-providers-panel", count: 0
+ assert_select "a[href=?]", account_path(@source.account), count: 0
+ assert_select "[data-provider-name='apple wallet']"
+ end
+
+ test "Wallet summary excludes another family's connections" do
+ financekit_setup(user: users(:empty))
+
+ get settings_providers_url
+
+ assert_response :success
+ assert_select "turbo-frame#financekit-providers-panel", count: 0
+ assert_select "[data-provider-name='apple wallet']"
+ end
+
+ test "Wallet summary excludes accounts the current admin cannot access" do
+ financekit_setup
+ @source.account.account_shares.destroy_all
+ @source.account.update!(owner: users(:family_member))
+
+ get settings_providers_url
+
+ assert_response :success
+ assert_select "turbo-frame#financekit-providers-panel", count: 0
+ assert_select "[data-provider-name='apple wallet']"
+ end
+
test "GET /settings/bank_sync redirects permanently to /settings/providers" do
get "/settings/bank_sync"
assert_redirected_to "/settings/providers"
diff --git a/test/models/demo/financekit_generator_test.rb b/test/models/demo/financekit_generator_test.rb
new file mode 100644
index 0000000000..3eadc9fd44
--- /dev/null
+++ b/test/models/demo/financekit_generator_test.rb
@@ -0,0 +1,235 @@
+require "test_helper"
+
+class Demo::FinancekitGeneratorTest < ActiveSupport::TestCase
+ setup do
+ travel_to Time.utc(2026, 9, 23, 20)
+ @checking = accounts(:depository)
+ @checking.update!(name: "Chase Premier Checking")
+ @checking.depository.update!(subtype: "checking")
+ end
+
+ test "FinanceKit demo accounts and transactions can be generated in separate phases in production" do
+ Rails.stubs(:env).returns(ActiveSupport::EnvironmentInquirer.new("production"))
+ generator = Demo::FinancekitGenerator.new(families(:dylan_family))
+
+ item = nil
+ assert_no_difference "Entry.count" do
+ item = generator.create_accounts!
+ end
+ assert_equal [ "Apple Card", "Apple Cash", "Nancy's Apple Cash" ], item.accounts.order(:name).pluck(:name)
+ assert item.accounts.all?(&:linked?)
+ assert_nil item.last_imported_at
+
+ assert_no_difference "Account.count" do
+ generator.create_transactions!
+ end
+ assert item.reload.last_imported_at
+ assert item.accounts.all? { |account| account.entries.exists? }
+ assert_no_difference [ "Account.count", "Entry.count", "FinancekitTransaction.count", "Transfer.count" ] do
+ generator.create_accounts!
+ generator.create_transactions!
+ end
+ end
+
+ test "seeds linked Apple Card and Apple Cash with source identities and realistic activity" do
+ family = families(:dylan_family)
+ flags_before = ENV.values_at("FINANCEKIT_ENABLED", "FINANCEKIT_FAMILY_IDS")
+ item = Demo::FinancekitGenerator.new(family).generate!
+
+ assert_equal "active", item.status
+ assert_equal 3, item.accounts.count
+ assert item.last_accepted_at
+ assert item.last_imported_at
+ assert_equal flags_before, ENV.values_at("FINANCEKIT_ENABLED", "FINANCEKIT_FAMILY_IDS")
+
+ card = item.accounts.find_by!(name: "Apple Card")
+ cash = item.accounts.find_by!(name: "Apple Cash")
+ assert_equal "CreditCard", card.accountable_type
+ assert_equal "cash", cash.depository.subtype
+ assert card.entries.where(name: "Apple Card Payment").all? { |entry| entry.amount.negative? }
+ assert cash.entries.where(name: "Apple Cash Top Up").all? { |entry| entry.amount.negative? }
+ assert card.entries.where(name: Demo::FinancekitGenerator::CARD_MERCHANTS).exists?
+ assert cash.entries.where(name: Demo::FinancekitGenerator::CASH_MERCHANTS).exists?
+
+ [ card, cash ].each do |account|
+ account.entries.where(name: Demo::FinancekitGenerator::MERCHANT_CATEGORIES.keys).each do |entry|
+ assert_equal Demo::FinancekitGenerator::MERCHANT_CATEGORIES.fetch(entry.name), entry.entryable.category.name
+ end
+ payments = account.entries.where(name: Demo::FinancekitGenerator::FUNDING_ENTRIES)
+ assert_equal 12, payments.count
+ payments.each do |entry|
+ transfer = entry.entryable.transfer
+ assert_equal @checking, transfer.from_account
+ assert_equal account, transfer.to_account
+ assert_equal -entry.amount, transfer.outflow_transaction.entry.amount
+ assert_equal entry.date, transfer.outflow_transaction.entry.date
+ assert_equal "funds_movement", entry.entryable.kind
+ assert_equal(account.credit_card? ? "cc_payment" : "funds_movement", transfer.outflow_transaction.kind)
+ assert_nil entry.entryable.category
+ end
+ end
+
+ item.financekit_accounts.each do |mapping|
+ assert_equal "financekit", mapping.account.account_providers.first.provider_name
+ assert_equal mapping.account.entries.count, mapping.financekit_transactions.count
+ assert mapping.financekit_transactions.where(status: "pending").exists? unless mapping.source_id == Demo::FinancekitGenerator::NANCY_SOURCE_ID
+ assert mapping.financekit_transactions.where(status: "booked").exists?
+ assert mapping.financekit_transactions.all?(&:ledger_imported?)
+ assert_equal [ "financekit" ], mapping.account.entries.distinct.pluck(:source)
+ assert mapping.account.entries.all? { |entry| entry.date <= Date.current }
+ total = mapping.financekit_transactions.where(status: "booked").joins(:entry).sum("entries.amount")
+ expected = mapping.accountable_type == "CreditCard" ? total : -total
+ assert_in_delta expected, mapping.account.reload.balance, 0.01
+ end
+ end
+
+ test "rerunning demo seeding preserves existing accounts and transactions" do
+ family = families(:dylan_family)
+ generator = Demo::FinancekitGenerator.new(family)
+ item = generator.generate!
+ account = item.accounts.find_by!(name: "Apple Card")
+ account.update!(name: "Renamed Wallet account")
+
+ purchase = account.entries.where("amount > 0").first.entryable
+ purchase.update!(category: categories(:one))
+
+ assert_no_difference [ "Account.count", "Entry.count", "FinancekitItem.count", "FinancekitTransaction.count", "Transfer.count", "Category.count" ] do
+ assert_equal item.id, generator.generate!.id
+ end
+ assert_equal "Renamed Wallet account", account.reload.name
+ assert_equal categories(:one), purchase.reload.category
+ end
+
+ test "repairs old demo categories and unpaired payments without replacing source records" do
+ family = families(:dylan_family)
+ item = Demo::FinancekitGenerator.new(family).generate!
+ card = item.accounts.find_by!(name: "Apple Card")
+ cash = item.accounts.find_by!(name: "Apple Cash")
+ purchases = [ card.entries.find_by!(name: "Delta Airlines"), cash.entries.find_by!(name: "Coffee Shop") ]
+ payment = card.entries.find_by!(name: "Apple Card Payment")
+ transfer = payment.entryable.transfer
+ outflow = transfer.outflow_transaction.entry
+ transfer.destroy!
+ outflow.destroy!
+ (purchases + [ payment ]).each do |entry|
+ transaction = entry.entryable.reload
+ transaction.update!(category: family.categories.find_by!(name: "Shopping"),
+ extra: transaction.extra.except("demo_financekit_activity_version"))
+ end
+ source_records = item.financekit_accounts.flat_map { |mapping| mapping.financekit_transactions.pluck(:id, :entry_id, :raw_payload) }
+ balances = [ card.balance, cash.balance ]
+
+ assert_difference [ "Entry.count", "Transfer.count" ], 1 do
+ assert_no_difference [ "Account.count", "FinancekitTransaction.count" ] do
+ Demo::FinancekitGenerator.new(family).generate!
+ end
+ end
+
+ assert_equal "Travel", purchases.first.reload.entryable.category.name
+ assert_equal "Coffee & Takeout", purchases.last.reload.entryable.category.name
+ assert_equal @checking, payment.reload.entryable.transfer.from_account
+ assert_nil payment.entryable.category
+ assert_equal balances, [ card.reload.balance, cash.reload.balance ]
+ assert_equal source_records, item.financekit_accounts.flat_map { |mapping| mapping.financekit_transactions.pluck(:id, :entry_id, :raw_payload) }
+ end
+
+ test "standalone demo uses a funded synthetic checking account when demo checking is absent" do
+ family = families(:empty)
+ item = Demo::FinancekitGenerator.new(family).generate!
+ checking = family.accounts.find_by!(name: "Wallet Demo Checking")
+ assert_equal item.user, checking.owner
+ assert_in_delta 5_000, checking.balance, 0.01
+ assert_not @checking.entries.where(name: "Apple Card Payment").exists?
+
+ assert_no_difference [ "Account.count", "Entry.count", "Transfer.count" ] do
+ Demo::FinancekitGenerator.new(family).generate!
+ end
+ end
+
+ test "Daily Cash is next-day cash back on booked card purchases, not payments or pending charges" do
+ item = Demo::FinancekitGenerator.new(families(:dylan_family)).generate!
+ card = item.accounts.find_by!(name: "Apple Card")
+ cash = item.accounts.find_by!(name: "Apple Cash")
+ purchases = card.entries.excluding_pending.where("amount > 0 AND date < ?", Date.current)
+ totals = purchases.group(:date).sum(:amount)
+ rewards = cash.entries.where(name: "Apple Card Daily Cash")
+
+ assert_operator rewards.count, :>, 100
+ assert_equal totals.size, rewards.count
+ rewards.each do |entry|
+ assert_equal -(totals.fetch(entry.date.prev_day) * BigDecimal("0.01")).round(2), entry.amount
+ assert_equal "Cash Back", entry.entryable.category.name
+ assert_equal "standard", entry.entryable.kind
+ assert_nil entry.entryable.transfer
+ assert_operator entry.date, :<=, Date.current
+ end
+ end
+
+ test "upgrades an existing two-account demo with Nancy without replacing the original accounts" do
+ family = families(:dylan_family)
+ item = Demo::FinancekitGenerator.new(family).generate!
+ mapping = item.financekit_accounts.find_by!(source_id: Demo::FinancekitGenerator::NANCY_SOURCE_ID)
+ nancy = mapping.account
+ nancy.entries.each do |entry|
+ transfer = entry.entryable.transfer
+ next unless transfer
+
+ counterpart = transfer.outflow_transaction.entry
+ FinancekitTransaction.where(entry: counterpart).destroy_all
+ counterpart.destroy!
+ end
+ lineage = mapping.financekit_account_lineage
+ mapping.destroy!
+ lineage.destroy!
+ nancy.destroy!
+ item.update!(consent: item.consent.merge("selected_source_account_ids" => [ Demo::FinancekitGenerator::CARD_SOURCE_ID, Demo::FinancekitGenerator::CASH_SOURCE_ID ]))
+ original_accounts = item.accounts.pluck(:id)
+ original_entries = Entry.where(account_id: original_accounts).order(:id).pluck(:id, :amount)
+
+ assert_difference "Account.count", 1 do
+ Demo::FinancekitGenerator.new(family).generate!
+ end
+ assert_equal "active", item.reload.status
+ assert_equal 3, item.accounts.count
+ assert_equal 12, item.accounts.find_by!(name: "Nancy's Apple Cash").entries.count
+ assert_equal original_entries, Entry.where(id: original_entries.map(&:first)).order(:id).pluck(:id, :amount)
+ end
+
+ test "Nancy has six linked gifts and spends her allowance on small outings" do
+ item = Demo::FinancekitGenerator.new(families(:dylan_family)).generate!
+ cash = item.accounts.find_by!(name: "Apple Cash")
+ nancy = item.accounts.find_by!(name: "Nancy's Apple Cash")
+
+ assert_equal "cash", nancy.depository.subtype
+ assert_equal cash.family, nancy.family
+ assert_equal 12, nancy.entries.count
+ assert_includes item.consented_source_ids, Demo::FinancekitGenerator::NANCY_SOURCE_ID
+ gifts = nancy.entries.where("amount < 0")
+ assert_equal 6, gifts.count
+ gifts.each do |entry|
+ transfer = entry.entryable.transfer
+ assert_equal cash, transfer.from_account
+ assert_equal nancy, transfer.to_account
+ assert_equal entry.date, transfer.outflow_transaction.entry.date
+ assert_equal -entry.amount, transfer.outflow_transaction.entry.amount
+ assert_equal "funds_movement", entry.entryable.kind
+ assert_equal "funds_movement", transfer.outflow_transaction.kind
+ end
+ purchases = nancy.entries.where("amount > 0").order(:date)
+ assert_equal 6, purchases.count
+ assert_equal [ "Candy Shop", "Movie Theater", "After-School Snacks", "Movie Theater", "Ice Cream Shop", "Candy Shop" ], purchases.pluck(:name)
+ assert_equal [ "Food & Dining", "Entertainment", "Food & Dining", "Entertainment", "Food & Dining", "Food & Dining" ], purchases.map { |entry| entry.entryable.category.name }
+ purchases.each do |entry|
+ assert_nil entry.entryable.transfer
+ assert_equal "standard", entry.entryable.kind
+ assert_operator entry.date, :<=, Date.current
+ end
+ balance = 0
+ nancy.entries.order(:date).each do |entry|
+ balance -= entry.amount
+ assert_operator balance, :>=, 0, "Nancy cannot spend money before receiving it"
+ end
+ assert_in_delta 17.50, nancy.balance, 0.01
+ assert_equal -nancy.entries.sum(:amount), nancy.balance
+ end
+end
diff --git a/test/models/demo/generator_test.rb b/test/models/demo/generator_test.rb
index 5c216bbc33..79e5a899a5 100644
--- a/test/models/demo/generator_test.rb
+++ b/test/models/demo/generator_test.rb
@@ -6,6 +6,29 @@ class Demo::GeneratorTest < ActiveSupport::TestCase
@admin_user = create_user!(@family, "[email protected]")
end
+ test "production sample reset includes Wallet in the normal accounts and transactions phases" do
+ Rails.stubs(:env).returns(ActiveSupport::EnvironmentInquirer.new("production"))
+ generator = Demo::Generator.new(seed: 42)
+ stub_non_wallet_activity(generator)
+ @family.expects(:sync_later)
+
+ generator.generate_new_user_data_for!(@family, email: @admin_user.email)
+
+ assert_wallet_demo_activity
+ end
+
+ test "production default demo includes Wallet in the normal accounts and transactions phases" do
+ Rails.stubs(:env).returns(ActiveSupport::EnvironmentInquirer.new("production"))
+ generator = Demo::Generator.new(seed: 42)
+ generator.stubs(:create_family_and_users!).returns(@family)
+ generator.stubs(:create_monitoring_api_key!)
+ stub_non_wallet_activity(generator)
+
+ generator.generate_default_data!(skip_clear: true)
+
+ assert_wallet_demo_activity
+ end
+
test "monitoring api key creation reassigns stale demo monitoring key owned by another user" do
stale_family = Family.create!(name: "Old Demo Family")
stale_user = create_user!(stale_family, "[email protected]")
@@ -115,6 +138,35 @@ class Demo::GeneratorTest < ActiveSupport::TestCase
end
private
+ # Exercise the actual account/transaction orchestration without generating
+ # years of unrelated spending, securities, budgets and goals in each test.
+ def stub_non_wallet_activity(generator)
+ %i[load_securities! generate_salary_history! generate_housing_transactions!
+ generate_food_transactions! generate_transportation_transactions!
+ generate_entertainment_transactions! generate_shopping_transactions!
+ generate_healthcare_transactions! generate_travel_transactions!
+ generate_personal_care_transactions! generate_investment_transactions!
+ generate_major_purchases! generate_transfers_and_payments! generate_loan_payments!
+ generate_regular_expenses! generate_legacy_transactions! generate_crypto_and_misc_assets!
+ generate_budget_auto_fill! generate_goals! sync_family_accounts!].each do |step|
+ generator.stubs(step)
+ end
+ end
+
+ def assert_wallet_demo_activity
+ item = @family.financekit_items.find_by!(enrollment_id: Demo::FinancekitGenerator::ENROLLMENT_ID)
+ assert_equal [ "Apple Card", "Apple Cash", "Nancy's Apple Cash" ], item.accounts.order(:name).pluck(:name)
+ assert item.accounts.all?(&:linked?)
+ assert item.accounts.all? { |account| account.entries.exists? }
+ assert item.last_imported_at
+ card = item.accounts.find_by!(name: "Apple Card")
+ checking = @family.accounts.find_by!(name: "Chase Premier Checking")
+ assert_equal checking, card.entries.find_by!(name: "Apple Card Payment").entryable.transfer.from_account
+ assert item.accounts.find_by!(name: "Apple Cash").entries.exists?(name: "Apple Card Daily Cash")
+ assert item.accounts.find_by!(name: "Nancy's Apple Cash").entries.exists?(name: "Movie Theater")
+ assert_not @family.accounts.exists?(name: "Wallet Demo Checking")
+ end
+
def create_user!(family, email)
family.users.create!(
first_name: "Demo",
diff --git a/test/models/financekit/diagnostics_test.rb b/test/models/financekit/diagnostics_test.rb
new file mode 100644
index 0000000000..efed582712
--- /dev/null
+++ b/test/models/financekit/diagnostics_test.rb
@@ -0,0 +1,93 @@
+require "test_helper"
+require_relative "../../support/financekit_test_helper"
+
+class Financekit::DiagnosticsTest < ActiveSupport::TestCase
+ include FinancekitTestHelper
+
+ setup { financekit_setup }
+
+ test "accepted and imported batches can be traced without recording financial payloads" do
+ batch, = accept_batch
+ accepted = log_for("upload_accepted")
+ assert_equal @family, accepted.family
+ assert_equal @user, accepted.user
+ assert_equal batch.batch_id, accepted.metadata["batch_id"]
+ assert_equal @item.id, accepted.metadata["connection_id"]
+ assert_equal 3, accepted.metadata["event_count"]
+
+ assert Financekit::Processor.new(@item).apply_next!
+ imported = log_for("capture_imported")
+ assert_equal batch.batch_id, imported.metadata["batch_id"]
+ assert_equal 1, imported.metadata.dig("counts", "upserted")
+ assert log_for("downstream_completed")
+ assert_private_fields_absent
+ end
+
+ test "rejected uploads record typed errors even when their transaction rolls back" do
+ payload = financekit_payload.merge("generation" => @item.generation + 1)
+ assert_raises(Financekit::Error) { accept_batch(payload) }
+
+ rejected = log_for("upload_rejected")
+ assert_equal "generation_conflict", rejected.metadata["error_code"]
+ assert_equal "warn", rejected.level
+ assert_private_fields_absent
+
+ travel 1.second
+ assert_raises(Financekit::Error) { FinancekitBatch.accept!(@item, '{"secret":') }
+ assert_equal "invalid_json", log_for("upload_rejected").metadata["error_code"]
+ refute_includes log_for("upload_rejected").metadata.to_json, "secret"
+ end
+
+ test "retry diagnostics include attempts deadline and error class without exception messages" do
+ batch, = accept_batch
+ Account::ProviderImportAdapter.any_instance.stubs(:update_balance).raises(RuntimeError, "private-financial-details")
+ Rails.error.stubs(:report)
+
+ assert_not Financekit::Processor.new(@item).apply_next!
+ retry_log = log_for("import_retry")
+ assert_equal "warn", retry_log.level
+ assert_equal 1, retry_log.metadata["attempts"]
+ assert_equal batch.reload.retry_at.iso8601, retry_log.metadata["retry_at"]
+ assert_equal "RuntimeError", retry_log.metadata["error_class"]
+ refute_includes retry_log.metadata.to_json, "private-financial-details"
+ end
+
+ test "permanent failures and failures before selecting a batch are visible" do
+ batch, = accept_batch
+ batch.update!(predecessor_digest: "0" * 64)
+ assert_not Financekit::Processor.new(@item).apply_next!
+ failed = log_for("import_failed")
+ assert_equal "error", failed.level
+ assert_equal "repair_required", failed.metadata["connection_status"]
+ assert_equal "predecessor_conflict", failed.metadata["error_code"]
+
+ assert_not Financekit::Processor.new(@item).apply_next!
+ assert_equal "repair_required", log_for("import_blocked").metadata["error_code"]
+ end
+
+ test "downstream failures include the affected account provider" do
+ batch, = accept_batch
+ Account.any_instance.stubs(:sync_later).raises(RuntimeError, "private-financial-details")
+
+ Financekit::Downstream.new(batch).perform!
+
+ log = log_for("downstream_failed")
+ assert_equal @source.financekit_account_lineage.account_provider, log.account_provider
+ assert_equal @source.account, log.account
+ assert_equal "RuntimeError", log.metadata["error_class"]
+ refute_includes log.metadata.to_json, "private-financial-details"
+ assert_nil batch.reload.downstream_completed_at
+ end
+
+ private
+ def log_for(event)
+ DebugLogEntry.where(provider_key: "financekit").where("metadata ->> 'event' = ?", event).order(created_at: :desc, id: :desc).first!
+ end
+
+ def assert_private_fields_absent
+ logs = DebugLogEntry.where(provider_key: "financekit").pluck(:metadata).to_json
+ [ @credential, @item.credential_digest, "Synthetic shop", "SYNTHETIC SHOP", "Test Wallet", "112.66" ].each do |value|
+ refute_includes logs, value
+ end
+ end
+end
diff --git a/test/models/financekit/lifecycle_test.rb b/test/models/financekit/lifecycle_test.rb
index 71a885d734..2b9a09e76c 100644
--- a/test/models/financekit/lifecycle_test.rb
+++ b/test/models/financekit/lifecycle_test.rb
@@ -104,6 +104,29 @@ class Financekit::LifecycleTest < ActiveSupport::TestCase
assert_equal "lineage_writer_conflict", error.code
end
+ test "unlink fences mapped replacement publishers without disconnecting unrelated Wallet connections" do
+ pending = Financekit::Enrollment.create!(@user, @enrollment.merge("enrollment_id" => SecureRandom.uuid)).item
+ FinancekitAccount.map!(pending, @source_id, @mapping_input)
+
+ other_source = SecureRandom.uuid
+ other_enrollment = @enrollment.deep_dup
+ other_enrollment["enrollment_id"] = SecureRandom.uuid
+ other_enrollment["consent"]["selected_source_account_ids"] = [ other_source ]
+ other = Financekit::Enrollment.create!(@user, other_enrollment).item
+ other_mapping = FinancekitAccount.map!(other, other_source, @mapping_input)
+ other_credential = other.activate!
+
+ @source.financekit_account_lineage.disconnect!
+
+ assert_equal "revoked", @item.reload.status
+ assert_equal "revoked", pending.reload.status
+ error = assert_raises(Financekit::Error) { pending.activate! }
+ assert_equal "activation_conflict", error.code
+ assert_equal "active", other.reload.status
+ assert other.authenticate_credential?(other_credential)
+ assert other_mapping.account.reload.linked?
+ end
+
test "purging a publisher user releases provider links without another active writer" do
account = @source.account
lineage = @source.financekit_account_lineage
diff --git a/test/models/financekit/mapping_test.rb b/test/models/financekit/mapping_test.rb
index 73f841b707..962c138b52 100644
--- a/test/models/financekit/mapping_test.rb
+++ b/test/models/financekit/mapping_test.rb
@@ -32,6 +32,39 @@ class Financekit::MappingTest < ActiveSupport::TestCase
assert_equal Date.new(2026, 3, 1), Financekit::Mapping.ledger_date(record, "America/Los_Angeles")
end
+ { "present" => Date.new(2026, 9, 1), "omitted" => Date.new(2026, 8, 31) }.each do |posted_at, expected_date|
+ test "booked transactions with posted_at #{posted_at} import using the existing ledger date precedence" do
+ events = financekit_events
+ events.last.fetch("transaction").delete("posted_at") if posted_at == "omitted"
+
+ batch = accept_and_apply(financekit_payload(events: events))
+
+ assert_equal "applied", batch.status
+ entry = @source.account.entries.sole
+ assert_equal expected_date, entry.date
+ assert_equal "booked", @source.financekit_transactions.sole.status
+ assert_not entry.transaction.pending?
+ end
+ end
+
+ test "pending transactions settle without posted_at while preserving identity and transacted date" do
+ events = financekit_events
+ transaction = events.last.fetch("transaction")
+ transaction["status"] = "pending"
+ transaction.delete("posted_at")
+ first = accept_and_apply(financekit_payload(events: events))
+ entry = @source.account.entries.sole
+ assert entry.transaction.pending?
+ assert_equal Date.new(2026, 8, 31), entry.date
+
+ transaction["status"] = "booked"
+ accept_and_apply(financekit_payload(sequence: 2, predecessor_digest: first.payload_digest, events: events))
+
+ assert_equal entry.id, @source.account.entries.sole.id
+ assert_equal Date.new(2026, 8, 31), entry.reload.date
+ assert_not entry.transaction.reload.pending?
+ end
+
test "a malformed event rejects the whole batch before it enters the inbox" do
events = financekit_events
events.last.fetch("transaction")["amount"]["amount"] = 12.34
diff --git a/test/models/financekit/payload_test.rb b/test/models/financekit/payload_test.rb
new file mode 100644
index 0000000000..2dcf3daea4
--- /dev/null
+++ b/test/models/financekit/payload_test.rb
@@ -0,0 +1,45 @@
+require "test_helper"
+require_relative "../../support/financekit_test_helper"
+
+class Financekit::PayloadTest < ActiveSupport::TestCase
+ include FinancekitTestHelper
+
+ setup { financekit_setup }
+
+ test "posted_at is optional for every transaction status including booked" do
+ Financekit::Payload::STATUSES.each do |status|
+ payload = financekit_payload
+ transaction = payload.fetch("events").last.fetch("transaction")
+ transaction["status"] = status
+
+ assert_same payload, Financekit::Payload.validate_batch!(payload, @item)
+ transaction.delete("posted_at")
+ assert_same payload, Financekit::Payload.validate_batch!(payload, @item)
+ end
+ end
+
+ test "present posted_at must remain a valid nonfuture timestamp for every status" do
+ Financekit::Payload::STATUSES.each do |status|
+ [ nil, "", false, 123, "not-a-date", "2026-09-01T07:00:00", "2026-99-99T07:00:00Z", 1.minute.from_now.iso8601 ].each do |posted_at|
+ payload = financekit_payload
+ transaction = payload.fetch("events").last.fetch("transaction")
+ transaction.merge!("status" => status, "posted_at" => posted_at)
+
+ assert_no_difference "FinancekitBatch.count" do
+ assert_raises(Financekit::Error, "#{status} with posted_at=#{posted_at.inspect}") { accept_batch(payload) }
+ end
+ end
+ end
+ assert_empty @source.account.entries
+ end
+
+ test "transacted_at remains required when posted_at is omitted" do
+ payload = financekit_payload
+ transaction = payload.fetch("events").last.fetch("transaction")
+ transaction.delete("posted_at")
+ transaction.delete("transacted_at")
+
+ error = assert_raises(Financekit::Error) { accept_batch(payload) }
+ assert_equal "invalid_payload", error.code
+ end
+end
diff --git a/test/system/cash_flow_test.rb b/test/system/cash_flow_test.rb
index d669eacaa0..51cb7dbe73 100644
--- a/test/system/cash_flow_test.rb
+++ b/test/system/cash_flow_test.rb
@@ -90,7 +90,7 @@ class CashFlowTest < ApplicationSystemTestCase
end
assert_no_selector "#cashflow-preview-expanded-dialog[open]"
assert_selector "#cashflow-preview [data-sankey-preview-target='expandButton']:focus"
- assert_equal "true", find("[data-section-key='cashflow_sankey']")["draggable"]
+ assert_selector "[data-section-key='cashflow_sankey'][draggable='true']"
end
end
@@ -167,12 +167,12 @@ class CashFlowTest < ApplicationSystemTestCase
click_button "Expand", enable_aria_label: true
end
assert_selector "#cashflow-preview-expanded-dialog[open] svg .sankey-link"
- assert_equal "false", find("[data-section-key='cashflow_sankey']")["draggable"]
+ assert_selector "[data-section-key='cashflow_sankey'][draggable='false']"
assert_event_count "sankey_preview_displayed", 2
within "#cashflow-preview-expanded-dialog" do
find("button[data-action='DS--dialog#close']").click
end
- assert_equal "true", find("[data-section-key='cashflow_sankey']")["draggable"]
+ assert_selector "[data-section-key='cashflow_sankey'][draggable='true']"
[ "Looks right", "Something looks wrong" ].each_with_index do |rating, index|
within "#cashflow-preview" do
diff --git a/test/system/categories_test.rb b/test/system/categories_test.rb
index c3eff0be3e..4ac8f8c742 100644
--- a/test/system/categories_test.rb
+++ b/test/system/categories_test.rb
@@ -86,6 +86,11 @@ class CategoriesTest < ApplicationSystemTestCase
end
picker.click
+ # Wait for the close handler before reopening; browsers can coalesce
+ # back-to-back details toggles and skip the intermediate closed state.
+ within "[data-controller='list-filter']", visible: :all do
+ assert_field I18n.t("ds.icon_picker.search_placeholder"), with: "", visible: :all
+ end
picker.click
within "[data-controller='list-filter']" do
diff --git a/test/system/settings/ai_prompts_test.rb b/test/system/settings/ai_prompts_test.rb
index 22d18b45fe..f9f0f04ddb 100644
--- a/test/system/settings/ai_prompts_test.rb
+++ b/test/system/settings/ai_prompts_test.rb
@@ -143,7 +143,7 @@ class Settings::AiPromptsTest < ApplicationSystemTestCase
assert_no_selector "#confirm-dialog"
within editor do
- assert_equal default_text, find("textarea").value
+ assert_field "Prompt", with: default_text
assert_text "Using the built-in default"
assert find_button("Reset to default", disabled: true)
end
diff --git a/test/system/settings/providers_test.rb b/test/system/settings/providers_test.rb
index 549925ae00..af209026e9 100644
--- a/test/system/settings/providers_test.rb
+++ b/test/system/settings/providers_test.rb
@@ -1,12 +1,78 @@
require "application_system_test_case"
+require_relative "../../support/financekit_test_helper"
class Settings::ProvidersTest < ApplicationSystemTestCase
+ include FinancekitTestHelper
setup do
@user = users(:family_admin)
@family = families(:dylan_family)
login_as @user
end
+ test "Wallet account links leave the provider frame and open transaction activity" do
+ financekit_setup(user: @user)
+ accept_and_apply
+
+ visit settings_providers_path
+ find("summary", text: "Apple Wallet").click
+ find("details", text: "Apple Wallet").native.save_screenshot(Rails.root.join("tmp", "apple-wallet-connected.png"))
+ within "turbo-frame#financekit-providers-panel" do
+ click_link "Test Wallet"
+ end
+
+ assert_current_path account_path(@source.account)
+ assert_selector "header h2", text: "Test Wallet"
+ assert_text "Synthetic shop"
+
+ visit accounts_path
+ within "#financekit-accounts" do
+ click_link "Test Wallet"
+ end
+ assert_current_path account_path(@source.account)
+ assert_text "Synthetic shop"
+ end
+
+ test "Wallet advertises App Store availability without a web connection flow" do
+ visit settings_providers_path
+ find('[data-providers-filter-target="input"]').set("Apple Wallet")
+
+ within available_provider_cards_container do
+ assert_text "US / UK"
+ assert_text "Bank"
+ assert_button "App Store", disabled: true
+ assert_selector '[title="Coming soon!"]'
+ assert_no_selector "a[data-turbo-frame='drawer']", visible: true
+ find('[data-providers-filter-target="card"]', text: "Apple Wallet").native.save_screenshot(
+ Rails.root.join("tmp", "apple-wallet-available.png"))
+ end
+ end
+
+ test "Wallet unlink confirmation disconnects the publisher and keeps account activity" do
+ financekit_setup(user: @user)
+ accept_and_apply
+
+ visit accounts_path
+ within "#financekit-accounts" do
+ find("button[aria-haspopup='menu']").click
+ click_link "Unlink from provider"
+ end
+ dialog = find("dialog[open]")
+ within dialog do
+ assert_text I18n.t("accounts.confirm_unlink.warning_wallet_connection")
+ dialog.native.save_screenshot(Rails.root.join("tmp", "apple-wallet-unlink.png"))
+ click_on "Confirm and unlink"
+ end
+
+ assert_no_selector "dialog[open]"
+ assert_current_path accounts_path
+ within "#manual-accounts" do
+ click_link "Test Wallet"
+ end
+ assert_current_path account_path(@source.account)
+ assert_text "Synthetic shop"
+ assert_equal "revoked", @item.reload.status
+ end
+
test "shows status pill on section header for a configured provider" do
SimplefinItem.create!(family: @family, name: "Test SimpleFIN", access_url: "https://bridge.simplefin.org/simplefin/access")