Files
sure/app/models/provider/up_adapter.rb
Jake dc2a565b6a feat(up): add Up Bank (AU) provider integration (#2391)
* feat(up): add Up Bank (AU) provider integration

Adds Up Bank as a per-family, token-based bank sync provider, modelled on
the existing Akahu integration. Up uses a JSON:API REST API with a personal
access token (Bearer), cursor pagination via links.next, and returns both
HELD (pending) and SETTLED transactions from one endpoint.

New:
- Provider::Up client (JSON:API unwrap, links.next pagination, retries,
  typed errors, /util/ping) + Provider::UpAdapter (Factory-registered,
  Depository + Loan).
- UpItem / UpAccount models with Provided, Unlinking, Syncer,
  SyncCompleteEvent, Importer, Processor, Transactions::Processor, and
  UpEntry::Processor (amount sign flip, HELD->pending, foreignAmount FX,
  merchant from description, stale-pending pruning).
- Family::UpConnectable, UpItemsController, routes, settings panel + connect
  flow views, accounts index wiring, initializer, en locale, and model tests.

Core wiring:
- "up" added to Transaction::PENDING_PROVIDERS, the three pending-match SQL
  blocks in Account::ProviderImportAdapter, Provider::Metadata::REGISTRY,
  ProviderMerchant/DataEnrichment source enums, ProviderConnectionStatus,
  settings provider panels, and financial data reset.

Migration create_up_items_and_accounts must be run before use. No external
API endpoints added (no OpenAPI changes).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(up): dump up tables to schema and make since filter TZ-safe

The feature commit added the up_items/up_accounts migration but never
re-dumped db/schema.rb, leaving the schema version and tables stale.
Add the two table definitions and foreign keys and bump the schema
version so a fresh DB load matches the migration.

Also format a bare Date `since` as UTC midnight instead of the server's
local zone, so `filter[since]` is deterministic regardless of where the
app runs (previously shifted by the local UTC offset).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(up): address code review feedback

Behavior/correctness:
- Persist skipped accounts via a new up_accounts.ignored flag and a
  needs_setup scope, so skipped accounts stop resurfacing as "needs
  setup" on every sync. Linking clears the flag.
- destroy now checks unlink_all! per-account results and aborts deletion
  (alert) if any unlink failed, instead of swallowing failures.
- render_provider_panel_error redirect uses :see_other (was an invalid
  4xx redirect status).
- Up provider adapter falls back to item institution name/url when
  institution_metadata is absent (early return previously blocked it).

Resilience/security:
- fetch_all_resources guards against an API repeating the same
  links.next cursor (Set#add?), preventing infinite pagination.
- HTTP client validates absolute URLs (from links.next) against Up's
  HTTPS host before sending the bearer token, preventing credential
  leakage to untrusted hosts.

Diagnostics:
- Route provider sync/import failures through DebugLogEntry.capture
  (controller, UpItem, syncer, unlinking) with family/account context.
  Low-level HTTP client and currency-normalization warnings keep
  Rails.logger to match existing provider conventions.

Data integrity:
- up_accounts.name and currency are NOT NULL (align with model presence
  validations); account_id stays nullable (allow_nil uniqueness).

Forms:
- select_existing_account radio is required; controller guards a blank/
  unknown up_account_id with a friendly alert instead of RecordNotFound.

Tests:
- Add UpAccount needs_setup scope test, pagination loop guard test,
  untrusted-host rejection test; tighten filter[since] assertion to the
  exact UTC timestamp.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(up): address second-round review feedback

- Capture sync/import failures via DebugLogEntry so swallowed errors in
  account/transaction fetching and transaction processing surface in
  /settings/debug instead of only Rails.logger.
- Gate UP_DEBUG_RAW raw payload dump to local envs to avoid leaking PII
  (merchant names, amounts, account IDs) in managed/production logs.
- Collapse linked/unlinked/total account counts into one memoized query
  instead of 3 separate COUNTs per rendered item.
- Rename "Set Up Up Accounts" locale title to "Link Up Accounts".

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* docs(up): add method docstrings and align failed_result keys

Add docstrings to all Up provider source files (controller, models,
providers, concerns) to satisfy the 80% docstring coverage threshold.

Third-round review: failed_result now mirrors import's result shape
(accounts_updated/created/failed, transactions_imported/failed) instead
of the stale accounts_imported key, so failure results stay consistent.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-20 20:33:09 +02:00

112 lines
3.3 KiB
Ruby

class Provider::UpAdapter < Provider::Base
include Provider::Syncable
include Provider::InstitutionMetadata
Provider::Factory.register("UpAccount", self)
# Sure accountable types that can be created from Up accounts.
def self.supported_account_types
%w[Depository Loan]
end
# Connection config hashes for each of the family's configured Up items.
def self.connection_configs(family:)
return [] unless family.can_connect_up?
family.up_items.active.ordered.select(&:credentials_configured?).map do |up_item|
connection_config_for(up_item)
end
end
# Build an Up API client for the resolved item, or nil if none is usable.
def self.build_provider(family: nil, up_item_id: nil)
return nil unless family.present?
up_item = resolve_up_item(family, up_item_id)
return nil unless up_item&.credentials_configured?
Provider::Up.new(up_item.access_token)
end
# Build the settings connection-config hash for a single Up item.
def self.connection_config_for(up_item)
path_params = ->(extra = {}) { extra.merge(up_item_id: up_item.id) }
{
key: "up_#{up_item.id}",
name: up_item.name.presence || I18n.t("providers.up.name"),
description: I18n.t("providers.up.description"),
can_connect: true,
new_account_path: ->(accountable_type, return_to) {
Rails.application.routes.url_helpers.select_accounts_up_items_path(
path_params.call(accountable_type: accountable_type, return_to: return_to)
)
},
existing_account_path: ->(account_id) {
Rails.application.routes.url_helpers.select_existing_account_up_items_path(
path_params.call(account_id: account_id)
)
}
}
end
private_class_method :connection_config_for
# Provider key used across the sync/account-provider machinery.
def provider_name
"up"
end
# Route to trigger a manual sync for this provider account's item.
def sync_path
Rails.application.routes.url_helpers.sync_up_item_path(item)
end
# The UpItem backing this provider account.
def item
provider_account.up_item
end
# Up holdings are never deletable by the sync machinery.
def can_delete_holdings?
false
end
# Institution domain from account metadata, or nil.
def institution_domain
metadata = provider_account.institution_metadata
return nil unless metadata.present?
metadata["domain"]
end
# Institution name from account metadata, falling back to the item's.
def institution_name
metadata = provider_account.institution_metadata
metadata&.dig("name").presence || item&.institution_name
end
# Institution URL from account metadata, falling back to the item's.
def institution_url
metadata = provider_account.institution_metadata
metadata&.dig("url").presence || item&.institution_url
end
# Brand color for the institution, from the item.
def institution_color
item&.institution_color
end
# Resolve the target Up item: the requested one, else the first configured.
def self.resolve_up_item(family, up_item_id)
if up_item_id.present?
item = family.up_items.active.find_by(id: up_item_id)
return item if item&.credentials_configured?
return nil
end
family.up_items.active.ordered.find(&:credentials_configured?)
end
private_class_method :resolve_up_item
end