Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix: expose sync_start_date field in Redbark account setup (#4306)

BenTriByte73917b2f78bd
diff --git a/app/controllers/redbark_items_controller.rb b/app/controllers/redbark_items_controller.rb
index fbb5f86f3b..5d81c76fba 100644
--- a/app/controllers/redbark_items_controller.rb
+++ b/app/controllers/redbark_items_controller.rb
@@ -163,8 +163,9 @@ class RedbarkItemsController < ApplicationController
ActiveRecord::Base.transaction do
account = create_account_from_redbark(redbark_account, accountable_type, config)
redbark_account.ensure_account_provider!(account)
- redbark_account.update!(ignored: false)
- redbark_account.update!(sync_start_date: config[:sync_start_date]) if config[:sync_start_date].present?
+ attributes = { ignored: false }
+ attributes[:sync_start_date] = config[:sync_start_date] if config[:sync_start_date].present?
+ redbark_account.update!(attributes)
end
created_count += 1
rescue => e
diff --git a/app/models/redbark_account.rb b/app/models/redbark_account.rb
index 5b77b2065a..e8889bace7 100644
--- a/app/models/redbark_account.rb
+++ b/app/models/redbark_account.rb
@@ -19,6 +19,41 @@ class RedbarkAccount < ApplicationRecord
validates :name, :currency, :redbark_account_id, presence: true
validates :redbark_account_id, uniqueness: { scope: :redbark_item_id }
+ # Redbark rejects a `from` date 2555+ days back ("too far in the past -
+ # banking providers serve at most ~7 years of history"), confirmed
+ # empirically against the live API. That's a flat 7 * 365 day count with no
+ # leap-day adjustment, so `7.years.ago` (which Rails computes against actual
+ # calendar years, landing past 2555 days whenever a leap day falls in the
+ # range) is rejected every time. MAX_SYNC_START_DATE_LOOKBACK_DAYS stays a
+ # few days inside that boundary as margin against timezone/day-of-fetch
+ # drift between our `Date.current` and Redbark's.
+ MAX_SYNC_START_DATE_LOOKBACK_DAYS = 2550
+
+ # The window RedbarkItem::Importer pulls on an account's first sync when no
+ # sync_start_date was chosen. Named here (rather than left as a literal in
+ # both the setup view's default and the importer's fallback) so the two
+ # can't quietly drift apart.
+ DEFAULT_INITIAL_HISTORY_DAYS = 90
+
+ # Scoped to the change itself: this is a rolling window, so a date that was
+ # valid when set drifts outside it over time. Without the guard, every
+ # unrelated update! (upsert_from_redbark! touching balance, name, currency
+ # on a routine sync) would re-validate the unchanged sync_start_date and
+ # start failing once enough time passed -- blocking updates that have
+ # nothing to do with it.
+ validates :sync_start_date,
+ inclusion: { in: ->(_account) { MAX_SYNC_START_DATE_LOOKBACK_DAYS.days.ago.to_date..Date.current } },
+ allow_nil: true,
+ if: :will_save_change_to_sync_start_date?
+
+ # A nonblank value Rails couldn't parse (e.g. "foo") casts to nil before
+ # validation ever sees it, and allow_nil above would then quietly accept
+ # it -- silently clearing whatever was previously stored instead of
+ # rejecting the bad input. *_before_type_cast still has the raw value, so
+ # this distinguishes "the user explicitly cleared the field" (blank raw
+ # value, fine) from "the user's input didn't parse" (nonblank raw value,
+ # reject it).
+ validate :reject_unparseable_sync_start_date, if: :will_save_change_to_sync_start_date?
# Scopes
scope :with_linked, -> { joins(:account_provider) }
@@ -88,6 +123,12 @@ class RedbarkAccount < ApplicationRecord
private
+ def reject_unparseable_sync_start_date
+ return unless sync_start_date.nil? && sync_start_date_before_type_cast.present?
+
+ errors.add(:sync_start_date, :invalid)
+ end
+
def enqueue_connection_cleanup
return unless redbark_item
diff --git a/app/models/redbark_item/importer.rb b/app/models/redbark_item/importer.rb
index 08c8111e6a..71919006ca 100644
--- a/app/models/redbark_item/importer.rb
+++ b/app/models/redbark_item/importer.rb
@@ -250,10 +250,16 @@ class RedbarkItem::Importer
# through the API's row ceiling on busy accounts.
(redbark_item.last_synced_at - 7.days).to_date
elsif redbark_account.sync_start_date.present?
- redbark_account.sync_start_date
+ # The stored date was validated against the rolling lookback window
+ # when it was set, but time passes between then and this first real
+ # fetch (a delayed initial sync, a long-stuck job). Clamp to today's
+ # window so an expired date doesn't get sent to Redbark and rejected
+ # outright -- the user still gets as much history as is still
+ # available, instead of nothing.
+ [ redbark_account.sync_start_date, RedbarkAccount::MAX_SYNC_START_DATE_LOOKBACK_DAYS.days.ago.to_date ].max
else
- # First sync for this account: pull a 90 day history
- 90.days.ago.to_date
+ # First sync for this account: pull the default history window
+ RedbarkAccount::DEFAULT_INITIAL_HISTORY_DAYS.days.ago.to_date
end
end
diff --git a/app/views/redbark_items/setup_accounts.html.erb b/app/views/redbark_items/setup_accounts.html.erb
index d2c74faa58..7f577eff2e 100644
--- a/app/views/redbark_items/setup_accounts.html.erb
+++ b/app/views/redbark_items/setup_accounts.html.erb
@@ -35,6 +35,13 @@
</div>
</div>
+ <%
+ # Loop-invariant: the same for every row, computed once rather than
+ # recomputed on each iteration below.
+ default_sync_start_date = RedbarkAccount::DEFAULT_INITIAL_HISTORY_DAYS.days.ago.to_date
+ min_sync_start_date = RedbarkAccount::MAX_SYNC_START_DATE_LOOKBACK_DAYS.days.ago.to_date
+ max_sync_start_date = Date.current
+ %>
<div class="space-y-4 max-h-96 overflow-y-auto">
<% @unlinked_accounts.each do |redbark_account| %>
<div class="border border-primary rounded-lg p-4">
@@ -54,6 +61,19 @@
<option value="loan"><%= t(".account_types.loan") %></option>
<option value="skip"><%= t(".account_types.skip") %></option>
</select>
+
+ <p class="text-xs font-medium text-secondary mt-3 mb-1"><%= t(".historical_data_range") %></p>
+ <label class="block text-sm text-secondary mb-1" for="sync_start_date_<%= redbark_account.id %>">
+ <%= t(".sync_start_date_label") %>
+ </label>
+ <%= date_field_tag "accounts[#{redbark_account.id}][sync_start_date]",
+ redbark_account.sync_start_date || default_sync_start_date,
+ id: "sync_start_date_#{redbark_account.id}",
+ min: min_sync_start_date,
+ max: max_sync_start_date,
+ autocomplete: "off",
+ class: "bg-container border border-primary rounded px-2 py-1 text-sm text-primary w-full" %>
+ <p class="text-xs text-secondary mt-1"><%= t(".sync_start_date_help") %></p>
</div>
<% end %>
</div>
diff --git a/test/controllers/redbark_items_controller_test.rb b/test/controllers/redbark_items_controller_test.rb
index 57be0917e6..2cd0758418 100644
--- a/test/controllers/redbark_items_controller_test.rb
+++ b/test/controllers/redbark_items_controller_test.rb
@@ -114,4 +114,46 @@ class RedbarkItemsControllerTest < ActionDispatch::IntegrationTest
assert @redbark_account.reload.ignored?
assert_not @redbark_item.reload.unlinked_redbark_accounts.exists?(id: @redbark_account.id)
end
+
+ test "complete_account_setup persists the chosen sync_start_date on the account" do
+ start_date = 6.months.ago.to_date
+
+ assert_difference "Account.count", 1 do
+ post complete_account_setup_redbark_item_url(@redbark_item), params: {
+ accounts: { @redbark_account.id => { account_type: "depository", sync_start_date: start_date.to_s } }
+ }
+ end
+
+ assert_equal start_date, @redbark_account.reload.sync_start_date
+ end
+
+ test "complete_account_setup without a sync_start_date leaves it blank" do
+ post complete_account_setup_redbark_item_url(@redbark_item), params: {
+ accounts: { @redbark_account.id => { account_type: "depository" } }
+ }
+
+ assert_nil @redbark_account.reload.sync_start_date
+ end
+
+ test "complete_account_setup rejects an out-of-range sync_start_date" do
+ out_of_range_date = 8.years.ago.to_date
+
+ assert_no_difference "Account.count" do
+ post complete_account_setup_redbark_item_url(@redbark_item), params: {
+ accounts: { @redbark_account.id => { account_type: "depository", sync_start_date: out_of_range_date.to_s } }
+ }
+ end
+
+ assert_not @redbark_account.reload.account_provider.present?
+ assert_nil @redbark_account.sync_start_date
+ end
+
+ test "setup_accounts pre-fills the stored sync_start_date instead of resetting it" do
+ stored_date = 6.months.ago.to_date
+ @redbark_account.update!(sync_start_date: stored_date)
+
+ get setup_accounts_redbark_item_url(@redbark_item)
+
+ assert_select "input#sync_start_date_#{@redbark_account.id}[value='#{stored_date}']"
+ end
end
diff --git a/test/models/redbark_account_test.rb b/test/models/redbark_account_test.rb
new file mode 100644
index 0000000000..ed916643a5
--- /dev/null
+++ b/test/models/redbark_account_test.rb
@@ -0,0 +1,70 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class RedbarkAccountTest < ActiveSupport::TestCase
+ setup do
+ @redbark_account = redbark_accounts(:savings_account)
+ end
+
+ test "sync_start_date allows nil" do
+ @redbark_account.sync_start_date = nil
+ assert @redbark_account.valid?
+ end
+
+ test "sync_start_date allows any date within the max lookback window" do
+ @redbark_account.sync_start_date = 6.months.ago.to_date
+ assert @redbark_account.valid?
+
+ @redbark_account.sync_start_date = Date.current
+ assert @redbark_account.valid?
+
+ @redbark_account.sync_start_date = RedbarkAccount::MAX_SYNC_START_DATE_LOOKBACK_DAYS.days.ago.to_date
+ assert @redbark_account.valid?
+ end
+
+ test "sync_start_date rejects a date older than the max lookback window" do
+ @redbark_account.sync_start_date = (RedbarkAccount::MAX_SYNC_START_DATE_LOOKBACK_DAYS + 1).days.ago.to_date
+ assert_not @redbark_account.valid?
+ assert_includes @redbark_account.errors[:sync_start_date], "is not included in the list"
+ end
+
+ test "sync_start_date rejects a future date" do
+ @redbark_account.sync_start_date = 1.day.from_now.to_date
+ assert_not @redbark_account.valid?
+ assert_includes @redbark_account.errors[:sync_start_date], "is not included in the list"
+ end
+
+ test "an unrelated update does not re-validate an unchanged, now-expired sync_start_date" do
+ # Bypasses validation on write, simulating a date that was valid when set
+ # but has since rolled outside the window - exactly what update_column
+ # (not update!) would leave behind if it had ever been written that way.
+ @redbark_account.update_column(:sync_start_date, (RedbarkAccount::MAX_SYNC_START_DATE_LOOKBACK_DAYS + 50).days.ago.to_date)
+
+ assert_nothing_raised { @redbark_account.update!(current_balance: 999) }
+ end
+
+ test "changing sync_start_date to an out-of-range value is still rejected" do
+ @redbark_account.update_column(:sync_start_date, 6.months.ago.to_date)
+
+ @redbark_account.sync_start_date = (RedbarkAccount::MAX_SYNC_START_DATE_LOOKBACK_DAYS + 1).days.ago.to_date
+ assert_not @redbark_account.valid?
+ assert_includes @redbark_account.errors[:sync_start_date], "is not included in the list"
+ end
+
+ test "rejects a nonblank sync_start_date that fails to parse instead of silently clearing it" do
+ @redbark_account.update_column(:sync_start_date, 6.months.ago.to_date)
+
+ @redbark_account.sync_start_date = "not-a-date"
+ assert_nil @redbark_account.sync_start_date, "Rails casts an unparseable date string to nil before validation sees it"
+ assert_not @redbark_account.valid?
+ assert_includes @redbark_account.errors[:sync_start_date], "is invalid"
+ end
+
+ test "an explicitly blank sync_start_date is still allowed" do
+ @redbark_account.update_column(:sync_start_date, 6.months.ago.to_date)
+
+ @redbark_account.sync_start_date = ""
+ assert @redbark_account.valid?
+ end
+end
diff --git a/test/models/redbark_item/importer_test.rb b/test/models/redbark_item/importer_test.rb
index e740ffa92c..de52b9539e 100644
--- a/test/models/redbark_item/importer_test.rb
+++ b/test/models/redbark_item/importer_test.rb
@@ -52,4 +52,51 @@ class RedbarkItem::ImporterTest < ActiveSupport::TestCase
assert_equal %w[old_posted post_1], merged.map { |t| t["id"] }.sort
end
+
+ test "import_transactions fetches from the stored sync_start_date when it's still within the lookback window" do
+ redbark_account = redbark_accounts(:savings_account)
+ redbark_account.update!(sync_start_date: 6.months.ago.to_date)
+
+ assert_fetches_from(redbark_account, 6.months.ago.to_date)
+ end
+
+ test "import_transactions clamps an expired sync_start_date to the current max lookback" do
+ redbark_account = redbark_accounts(:savings_account)
+ # Bypass the model's own validation to simulate a date that was valid when
+ # set but has since drifted outside the rolling window by the time a
+ # delayed first fetch actually runs.
+ redbark_account.update_column(:sync_start_date, (RedbarkAccount::MAX_SYNC_START_DATE_LOOKBACK_DAYS + 50).days.ago.to_date)
+
+ assert_fetches_from(redbark_account, RedbarkAccount::MAX_SYNC_START_DATE_LOOKBACK_DAYS.days.ago.to_date)
+ end
+
+ test "import_transactions falls back to the default history window when there's no stored date" do
+ redbark_account = redbark_accounts(:savings_account)
+ redbark_account.update!(sync_start_date: nil)
+
+ assert_fetches_from(redbark_account, RedbarkAccount::DEFAULT_INITIAL_HISTORY_DAYS.days.ago.to_date)
+ end
+
+ private
+
+ # Asserts the date window import_transactions actually sends to Redbark,
+ # rather than calling calculate_transaction_start_date directly -- that
+ # private method's return value composing correctly with the rest of
+ # import_transactions is exactly what's under test here.
+ def assert_fetches_from(redbark_account, expected_start_date)
+ provider = mock("redbark_provider")
+ importer = RedbarkItem::Importer.new(@redbark_item, redbark_provider: provider)
+ importer.stubs(:transactable_connection?).returns(true)
+ importer.stubs(:connections_by_id).returns({})
+
+ provider.expects(:get_transactions).with(
+ connection_id: redbark_account.connection_id,
+ account_id: redbark_account.redbark_account_id,
+ start_date: expected_start_date,
+ end_date: Date.current,
+ include_pending: Rails.configuration.x.redbark.include_pending
+ ).returns([])
+
+ importer.send(:import_transactions, redbark_account)
+ end
end