The personal finance app for everyone (by everyone)
Ruby
Add a per-connection sync frequency (#4718)
Yong Cong Sin596562ff75c9
diff --git a/app/controllers/sync_schedules_controller.rb b/app/controllers/sync_schedules_controller.rbnew file mode 100644index 0000000000..0d39a1a550--- /dev/null+++ b/app/controllers/sync_schedules_controller.rb@@ -0,0 +1,54 @@+# The per-connection sync schedule, edited from the connection's card menu+# on the accounts page. The connection itself is addressed by type and id,+# since every provider keeps its own *_items table.+class SyncSchedulesController < ApplicationController+ before_action :set_syncable++ def edit+ @sync_schedule = @syncable.sync_schedule || @syncable.build_sync_schedule+ end++ def update+ # Blank is the form's "no schedule" choice; a request without the field+ # is malformed and must not delete anything.+ return head :unprocessable_entity unless sync_schedule_params.key?(:interval_minutes)++ interval = sync_schedule_params[:interval_minutes].presence++ if interval.nil?+ @syncable.sync_schedule&.destroy!+ redirect_to accounts_path, notice: t(".cleared")+ else+ @sync_schedule = SyncSchedule.assign(@syncable, interval)++ if @sync_schedule.errors.none?+ redirect_to accounts_path, notice: t(".updated")+ else+ render :edit, status: :unprocessable_entity+ end+ end+ end++ private+ def sync_schedule_params+ params.fetch(:sync_schedule, {}).permit(:interval_minutes)+ end++ # Looked up through the family's own association, so a type outside the+ # schedulable set or an id from another family is a 404.+ def set_syncable+ association = SyncSchedule.schedulable_associations.fetch(params[:syncable_type].to_s) do+ raise ActiveRecord::RecordNotFound+ end+ @syncable = Current.family.public_send(association).find(params[:syncable_id])+ raise ActiveRecord::RecordNotFound if @syncable.try(:scheduled_for_deletion?)++ # The same check the card's menu uses to offer the entry.+ return if SyncSchedule.editable_by?(@syncable, Current.user)++ respond_to do |format|+ format.html { redirect_to accounts_path, alert: t("shared.require_admin") }+ format.any { head :forbidden }+ end+ end+enddiff --git a/app/helpers/sync_schedules_helper.rb b/app/helpers/sync_schedules_helper.rbnew file mode 100644index 0000000000..8ca4e35b8d--- /dev/null+++ b/app/helpers/sync_schedules_helper.rb@@ -0,0 +1,33 @@+module SyncSchedulesHelper+ # The "Sync frequency" entry of a connection card's menu. Every provider card+ # has its own partial; this is the one line they all share. Left out for a+ # viewer the editor would turn away, whatever the card's own menu shows.+ def sync_schedule_menu_item(menu, syncable)+ return unless SyncSchedule.editable_by?(syncable, Current.user)++ menu.with_item(+ variant: "link",+ text: t("sync_schedules.menu_item"),+ icon: "clock",+ href: edit_sync_schedule_path(syncable_type: syncable.class.name, syncable_id: syncable.id),+ frame: :modal+ )+ end++ def sync_schedule_interval_options+ SyncSchedule::INTERVALS.map { |minutes| [ sync_schedule_interval_label(minutes), minutes ] }+ end++ def sync_schedule_interval_label(minutes)+ if minutes < 60+ t("sync_schedules.intervals.minutes", count: minutes)+ else+ t("sync_schedules.intervals.hours", count: minutes / 60)+ end+ end++ # Not every provider item has a name (FinanceKit's doesn't).+ def sync_schedule_syncable_name(syncable)+ syncable.try(:name).presence || syncable.model_name.human+ end+enddiff --git a/app/jobs/sync_scheduled_items_job.rb b/app/jobs/sync_scheduled_items_job.rbnew file mode 100644index 0000000000..940317fadb--- /dev/null+++ b/app/jobs/sync_scheduled_items_job.rb@@ -0,0 +1,62 @@+# Ticks every SyncSchedule::TICK (config/schedule.yml) and syncs the provider+# connections whose own schedule has come due. The daily family sync+# (SyncAllJob) is untouched; this runs in between it.+class SyncScheduledItemsJob < ApplicationJob+ queue_as :scheduled+ sidekiq_options lock: :until_executed, on_conflict: :log++ def perform+ SyncSchedule.due.find_each do |schedule|+ # A provider removed from the app leaves rows no validation accepts, so+ # they could never be advanced.+ unless SyncSchedule.schedulable_associations.key?(schedule.syncable_type)+ schedule.destroy!+ next+ end++ # Advanced first, so a connection whose sync keeps failing is retried+ # at its own cadence rather than on every tick. A schedule changed or+ # removed since it was loaded is no longer due.+ next unless schedule.advance!+ item = schedule.syncable++ if item.nil?+ schedule.destroy!+ elsif item.class.syncable.exists?(item.id)+ sync(item)+ end+ rescue => e+ capture_failure(schedule, item, e)+ end+ end++ private+ # Plaid only hands over transactions it has pulled from the bank on its+ # own cadence unless asked to refresh, as every other sync entry point+ # does (its cooldown keeps the requests apart).+ def sync(item)+ if item.respond_to?(:sync_later_with_provider_refresh)+ item.sync_later_with_provider_refresh+ else+ item.sync_later+ end+ end++ def capture_failure(schedule, item, error)+ Rails.logger.error("[SyncScheduledItemsJob] Failed to sync #{schedule.syncable_type} #{schedule.syncable_id}: #{error.message}")++ DebugLogEntry.capture(+ category: "provider_sync",+ level: "error",+ message: "Scheduled sync could not be started",+ source: self.class.name,+ provider_key: schedule.syncable_type.to_s.delete_suffix("Item").underscore.presence,+ family: item.try(:family),+ metadata: {+ syncable_type: schedule.syncable_type,+ syncable_id: schedule.syncable_id,+ error_class: error.class.name+ }+ )+ end+enddiff --git a/app/models/concerns/syncable.rb b/app/models/concerns/syncable.rbindex 90809b4d12..dfd8957436 100644--- a/app/models/concerns/syncable.rb+++ b/app/models/concerns/syncable.rb@@ -3,6 +3,7 @@ module Syncableincluded dohas_many :syncs, as: :syncable, dependent: :destroy+ has_one :sync_schedule, as: :syncable, dependent: :destroyenddef syncing?diff --git a/app/models/family/syncer.rb b/app/models/family/syncer.rbindex 67df952b94..128c92c786 100644--- a/app/models/family/syncer.rb+++ b/app/models/family/syncer.rb@@ -27,27 +27,27 @@ class Family::SyncerApplyRulesJob.perform_later(family)end- private+ # Every `*_items` association whose model is Syncable, found by reflection+ # so a new integration takes part in the nightly family sync (and may carry+ # a SyncSchedule) as soon as it includes Syncable and exposes a `syncable`+ # scope.+ def self.syncable_item_associations+ Family.reflect_on_all_associations(:has_many).filter_map do |association|+ next unless association.name.to_s.end_with?("_items")+ next unless association.klass.included_modules.include?(Syncable)++ association.name+ rescue NameError+ nil+ end+ end- # Collect all syncable provider items via reflection so new `*_items`- # integrations participate in nightly family sync as soon as they include- # Syncable and expose a `syncable` scope.+ privatedef child_syncables- provider_items = syncable_item_associations.flat_map do |association|+ provider_items = self.class.syncable_item_associations.flat_map do |association|family.public_send(association).syncableendprovider_items + family.accounts.manualend-- def syncable_item_associations- Family.reflect_on_all_associations(:has_many).filter_map do |association|- next unless association.name.to_s.end_with?("_items")- next unless association.klass.included_modules.include?(Syncable)-- association.name- rescue NameError- nil- end- endenddiff --git a/app/models/sync_schedule.rb b/app/models/sync_schedule.rbnew file mode 100644index 0000000000..b42551e498--- /dev/null+++ b/app/models/sync_schedule.rb@@ -0,0 +1,101 @@+# How often one provider connection syncs on its own, on top of the daily+# family sync (AutoSyncScheduler / SyncAllJob). A connection without a+# schedule only takes part in the daily sync. SyncScheduledItemsJob ticks+# every TICK and syncs whatever has come due.+#+# Per connection rather than global because connections differ in what a+# sync costs: Plaid bills per transactions refresh and banks rate-limit,+# while an exchange API key is cheap to poll every few minutes.+class SyncSchedule < ApplicationRecord+ TICK = 15.minutes++ # Offered intervals, in minutes. Each divides a day, so with next_run_at+ # aligned to multiples of the interval a connection syncs at the same+ # clock times every day instead of drifting.+ INTERVALS = [ 15, 30, 60, 120, 240, 360, 720 ].freeze++ belongs_to :syncable, polymorphic: true++ validates :interval_minutes, inclusion: { in: INTERVALS }+ validates :syncable_type, inclusion: { in: ->(_schedule) { schedulable_associations.keys } }+ validates :syncable_id, uniqueness: { scope: :syncable_type }++ before_validation :align_next_run_at, if: -> { interval_minutes_changed? || next_run_at.blank? }++ scope :due, -> { where(next_run_at: ..Time.current) }++ class << self+ # The connections a schedule may point at, as { class name => Family+ # association }: every `*_items` association whose model is Syncable,+ # the same set the daily family sync fans out to.+ def schedulable_associations+ Family::Syncer.syncable_item_associations.to_h do |association|+ [ Family.reflect_on_association(association).klass.name, association ]+ end+ end++ # Sets `syncable`'s interval, creating its schedule on first use, and+ # returns the schedule (with errors if the interval is rejected). Two+ # requests creating the same connection's schedule at once both pass+ # the uniqueness validation; the one the unique index turns away applies+ # its interval to the row the other created.+ def assign(syncable, interval_minutes)+ schedule = syncable.sync_schedule || syncable.build_sync_schedule+ schedule.interval_minutes = interval_minutes+ schedule.save+ schedule+ rescue ActiveRecord::RecordNotUnique+ schedule = syncable.reload_sync_schedule+ schedule.interval_minutes = interval_minutes+ schedule.save+ schedule+ end++ # Whether `user` may change `syncable`'s schedule: admins manage every+ # connection, a member only one they own on a provider that allows it+ # (ProviderItemOwnable). A connection being deleted takes no schedule.+ def editable_by?(syncable, user)+ return false if user.nil? || syncable.try(:scheduled_for_deletion?)++ if syncable.respond_to?(:manageable_by?)+ syncable.manageable_by?(user)+ else+ user.admin?+ end+ end+ end++ def interval+ interval_minutes.minutes+ end++ # Moves a due schedule to the first boundary after `from` and returns+ # whether it was due. Locked and reloaded first, so the interval saved+ # since this row was loaded is the one the next run is counted in, and a+ # schedule changed meanwhile (which realigns it to the future) or removed+ # is not run.+ def advance!(from: Time.current)+ with_lock do+ next false if next_run_at > from++ update!(next_run_at: next_boundary_after(from))+ true+ end+ rescue ActiveRecord::RecordNotFound+ false+ end++ private+ def align_next_run_at+ return unless INTERVALS.include?(interval_minutes)++ self.next_run_at = next_boundary_after(Time.current)+ end++ # Multiples of the interval counted from the Unix epoch, i.e. from+ # midnight UTC: "every 6 hours" runs at 00:00, 06:00, 12:00 and 18:00.+ def next_boundary_after(time)+ seconds = interval.to_i+ Time.zone.at((time.to_i / seconds + 1) * seconds)+ end+enddiff --git a/app/views/akahu_items/_akahu_item.html.erb b/app/views/akahu_items/_akahu_item.html.erbindex 9d9475fc11..72c825422a 100644--- a/app/views/akahu_items/_akahu_item.html.erb+++ b/app/views/akahu_items/_akahu_item.html.erb@@ -48,6 +48,7 @@<% if Current.user&.admin? %><div class="flex items-center gap-2"><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, akahu_item) %><% menu.with_item(variant: "button",text: t(".delete"),diff --git a/app/views/binance_items/_binance_item.html.erb b/app/views/binance_items/_binance_item.html.erbindex 1c2ec3606f..b18dbeb49f 100644--- a/app/views/binance_items/_binance_item.html.erb+++ b/app/views/binance_items/_binance_item.html.erb@@ -63,6 +63,7 @@<% end %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, binance_item) %><% if binance_item.unlinked_accounts_count > 0 %><% menu.with_item(variant: "link",diff --git a/app/views/brex_items/_brex_item.html.erb b/app/views/brex_items/_brex_item.html.erbindex cb61ed8631..180fc5e52c 100644--- a/app/views/brex_items/_brex_item.html.erb+++ b/app/views/brex_items/_brex_item.html.erb@@ -71,6 +71,7 @@<% end %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, brex_item) %><% menu.with_item(variant: "button",text: t(".delete"),diff --git a/app/views/coinbase_items/_coinbase_item.html.erb b/app/views/coinbase_items/_coinbase_item.html.erbindex 93dca0c22e..d1e05c1af9 100644--- a/app/views/coinbase_items/_coinbase_item.html.erb+++ b/app/views/coinbase_items/_coinbase_item.html.erb@@ -78,6 +78,7 @@<% end %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, coinbase_item) %><% if unlinked_count.to_i > 0 %><% menu.with_item(variant: "link",diff --git a/app/views/coinspot_items/_coinspot_item.html.erb b/app/views/coinspot_items/_coinspot_item.html.erbindex 8e75832bc3..9370bc40a1 100644--- a/app/views/coinspot_items/_coinspot_item.html.erb+++ b/app/views/coinspot_items/_coinspot_item.html.erb@@ -54,6 +54,7 @@) %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, coinspot_item) %><% if unlinked_count.to_i > 0 %><% menu.with_item(variant: "link",diff --git a/app/views/coinstats_items/_coinstats_item.html.erb b/app/views/coinstats_items/_coinstats_item.html.erbindex 8e171269de..493157c094 100644--- a/app/views/coinstats_items/_coinstats_item.html.erb+++ b/app/views/coinstats_items/_coinstats_item.html.erb@@ -62,6 +62,7 @@<% end %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, coinstats_item) %><% menu.with_item(variant: "button",text: t(".delete"),diff --git a/app/views/enable_banking_items/_enable_banking_item.html.erb b/app/views/enable_banking_items/_enable_banking_item.html.erbindex 2a2bce7bc4..de8290816f 100644--- a/app/views/enable_banking_items/_enable_banking_item.html.erb+++ b/app/views/enable_banking_items/_enable_banking_item.html.erb@@ -61,6 +61,7 @@<% end %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, enable_banking_item) %><% unless enable_banking_item.requires_update? %><%# Always-available manual reconnect, independent of the automaticrequires_update detection above. Enable Banking sometimes rejectsdiff --git a/app/views/fio_items/_fio_item.html.erb b/app/views/fio_items/_fio_item.html.erbindex 1eb5bdb616..02220b2e2e 100644--- a/app/views/fio_items/_fio_item.html.erb+++ b/app/views/fio_items/_fio_item.html.erb@@ -49,6 +49,7 @@<% if Current.user&.admin? %><div class="flex items-center gap-2"><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, fio_item) %><% menu.with_item(variant: "button",text: t(".delete"),diff --git a/app/views/ibkr_items/_ibkr_item.html.erb b/app/views/ibkr_items/_ibkr_item.html.erbindex a0b4d54703..196fd30cce 100644--- a/app/views/ibkr_items/_ibkr_item.html.erb+++ b/app/views/ibkr_items/_ibkr_item.html.erb@@ -56,6 +56,7 @@) %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, ibkr_item) %><% if unlinked_count > 0 %><% menu.with_item(variant: "link",diff --git a/app/views/indexa_capital_items/_indexa_capital_item.html.erb b/app/views/indexa_capital_items/_indexa_capital_item.html.erbindex f82263cc7c..0d9e2f7935 100644--- a/app/views/indexa_capital_items/_indexa_capital_item.html.erb+++ b/app/views/indexa_capital_items/_indexa_capital_item.html.erb@@ -66,6 +66,7 @@<% end %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, indexa_capital_item) %><% if unlinked_count > 0 %><% menu.with_item(variant: "link",diff --git a/app/views/kraken_items/_kraken_item.html.erb b/app/views/kraken_items/_kraken_item.html.erbindex fce833d660..2e7ecfb45b 100644--- a/app/views/kraken_items/_kraken_item.html.erb+++ b/app/views/kraken_items/_kraken_item.html.erb@@ -54,6 +54,7 @@) %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, kraken_item) %><% if unlinked_count.to_i > 0 %><% menu.with_item(variant: "link",diff --git a/app/views/lunchflow_items/_lunchflow_item.html.erb b/app/views/lunchflow_items/_lunchflow_item.html.erbindex 97ad199092..cccab040ee 100644--- a/app/views/lunchflow_items/_lunchflow_item.html.erb+++ b/app/views/lunchflow_items/_lunchflow_item.html.erb@@ -60,6 +60,7 @@<% end %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, lunchflow_item) %><% menu.with_item(variant: "button",text: t(".delete"),diff --git a/app/views/mercury_items/_mercury_item.html.erb b/app/views/mercury_items/_mercury_item.html.erbindex 51296ee398..8e78e84392 100644--- a/app/views/mercury_items/_mercury_item.html.erb+++ b/app/views/mercury_items/_mercury_item.html.erb@@ -60,6 +60,7 @@<% end %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, mercury_item) %><% menu.with_item(variant: "button",text: t(".delete"),diff --git a/app/views/monobank_items/_monobank_item.html.erb b/app/views/monobank_items/_monobank_item.html.erbindex b4124f42ae..a77813e9a1 100644--- a/app/views/monobank_items/_monobank_item.html.erb+++ b/app/views/monobank_items/_monobank_item.html.erb@@ -48,6 +48,7 @@<% if Current.user&.admin? %><div class="flex items-center gap-2"><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, monobank_item) %><% menu.with_item(variant: "button",text: t(".delete"),diff --git a/app/views/onchain_wallet_items/_wallet_card.html.erb b/app/views/onchain_wallet_items/_wallet_card.html.erbindex ff7e665c9c..6dadecf45b 100644--- a/app/views/onchain_wallet_items/_wallet_card.html.erb+++ b/app/views/onchain_wallet_items/_wallet_card.html.erb@@ -50,6 +50,7 @@a navigation link. %><% if Current.user&.admin? %><%= render DS::Menu.new(icon_vertical: true, mobile_fullwidth: false, max_width: "280px") do |menu| %>+ <% sync_schedule_menu_item(menu, onchain_wallet_item) %><% unless onchain_wallet_item.syncing? %><% menu.with_item(variant: "button",diff --git a/app/views/plaid_items/_plaid_item.html.erb b/app/views/plaid_items/_plaid_item.html.erbindex 6b93384d1e..639d59a3bb 100644--- a/app/views/plaid_items/_plaid_item.html.erb+++ b/app/views/plaid_items/_plaid_item.html.erb@@ -67,6 +67,7 @@<% end %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, plaid_item) %><% menu.with_item(variant: "button",text: t(".delete"),diff --git a/app/views/questrade_items/_questrade_item.html.erb b/app/views/questrade_items/_questrade_item.html.erbindex 09ac3a2d0f..5d2e0b32e6 100644--- a/app/views/questrade_items/_questrade_item.html.erb+++ b/app/views/questrade_items/_questrade_item.html.erb@@ -48,6 +48,7 @@<%= icon("refresh-cw", as_button: true, href: sync_questrade_item_path(questrade_item), disabled: questrade_item.syncing?) %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, questrade_item) %><% menu.with_item(variant: "button",text: t(".delete"),diff --git a/app/views/redbark_items/_redbark_item.html.erb b/app/views/redbark_items/_redbark_item.html.erbindex a28cab3152..324104f4ba 100644--- a/app/views/redbark_items/_redbark_item.html.erb+++ b/app/views/redbark_items/_redbark_item.html.erb@@ -62,6 +62,7 @@<% end %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, redbark_item) %><% menu.with_item(variant: "button",text: t(".delete"),diff --git a/app/views/simplefin_items/_simplefin_item.html.erb b/app/views/simplefin_items/_simplefin_item.html.erbindex 1c3e805aa4..85791b646e 100644--- a/app/views/simplefin_items/_simplefin_item.html.erb+++ b/app/views/simplefin_items/_simplefin_item.html.erb@@ -162,6 +162,7 @@<% end %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, simplefin_item) %><% if unlinked_count.to_i > 0 %><% menu.with_item(variant: "link",diff --git a/app/views/snaptrade_items/_snaptrade_item.html.erb b/app/views/snaptrade_items/_snaptrade_item.html.erbindex 0e7294cbe5..07a16bf748 100644--- a/app/views/snaptrade_items/_snaptrade_item.html.erb+++ b/app/views/snaptrade_items/_snaptrade_item.html.erb@@ -76,6 +76,7 @@<% end %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, snaptrade_item) %><% menu.with_item(variant: "link",text: t(".connect_brokerage"),diff --git a/app/views/sophtron_items/_sophtron_item.html.erb b/app/views/sophtron_items/_sophtron_item.html.erbindex 6a15d5eca9..1f3df2305e 100644--- a/app/views/sophtron_items/_sophtron_item.html.erb+++ b/app/views/sophtron_items/_sophtron_item.html.erb@@ -74,6 +74,7 @@<% end %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, sophtron_item) %><% if all_accounts_visible && connected_institution_options.many? %><% connected_institution_options.each do |institution| %><% institution_manual_sync_required = sophtron_item.manual_sync_required_for_institution?(institution[:institution_key]) %>diff --git a/app/views/sync_schedules/edit.html.erb b/app/views/sync_schedules/edit.html.erbnew file mode 100644index 0000000000..03e35c0ff0--- /dev/null+++ b/app/views/sync_schedules/edit.html.erb@@ -0,0 +1,30 @@+<%= render DS::Dialog.new do |dialog| %>+ <% dialog.with_header(title: t(".title")) %>++ <% dialog.with_body do %>+ <%= styled_form_with model: @sync_schedule,+ url: sync_schedule_path(syncable_type: @syncable.class.name, syncable_id: @syncable.id),+ method: :patch,+ data: { turbo_frame: "_top" },+ class: "space-y-4" do |form| %>+ <% if @sync_schedule.errors.any? %>+ <%= render "shared/form_errors", model: @sync_schedule %>+ <% end %>++ <p class="text-sm text-secondary">+ <%= t(".description", name: sync_schedule_syncable_name(@syncable)) %>+ </p>++ <%# The saved interval, not a rejected one: no option matches a rejected+ value, so the blank "no schedule" choice would show and a resubmit+ would delete the schedule. %>+ <%= form.select :interval_minutes,+ sync_schedule_interval_options,+ { include_blank: t(".no_schedule"), label: t(".interval_label"), selected: @sync_schedule.interval_minutes_in_database } %>++ <p class="text-xs text-secondary"><%= t(".hint") %></p>++ <%= render DS::Button.new(text: t(".save"), type: "submit", full_width: true) %>+ <% end %>+ <% end %>+<% end %>diff --git a/app/views/trade_republic_items/_trade_republic_item.html.erb b/app/views/trade_republic_items/_trade_republic_item.html.erbindex fb1631b88e..b3cf124de5 100644--- a/app/views/trade_republic_items/_trade_republic_item.html.erb+++ b/app/views/trade_republic_items/_trade_republic_item.html.erb@@ -58,6 +58,7 @@) %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, trade_republic_item) %><% if unlinked_count > 0 %><% menu.with_item(variant: "link",diff --git a/app/views/trading212_items/_trading212_item.html.erb b/app/views/trading212_items/_trading212_item.html.erbindex 5b13e7a76f..b3503b0a4f 100644--- a/app/views/trading212_items/_trading212_item.html.erb+++ b/app/views/trading212_items/_trading212_item.html.erb@@ -56,6 +56,7 @@) %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, trading212_item) %><% if unlinked_count > 0 %><% menu.with_item(variant: "link",diff --git a/app/views/truelayer_items/_truelayer_item.html.erb b/app/views/truelayer_items/_truelayer_item.html.erbindex 51848a50b2..865c56071b 100644--- a/app/views/truelayer_items/_truelayer_item.html.erb+++ b/app/views/truelayer_items/_truelayer_item.html.erb@@ -75,6 +75,7 @@<% end %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, truelayer_item) %><% menu.with_item(variant: "button",text: t(".delete"),diff --git a/app/views/up_items/_up_item.html.erb b/app/views/up_items/_up_item.html.erbindex 0f664aad22..118f6e05b3 100644--- a/app/views/up_items/_up_item.html.erb+++ b/app/views/up_items/_up_item.html.erb@@ -48,6 +48,7 @@<% if Current.user&.admin? %><div class="flex items-center gap-2"><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, up_item) %><% menu.with_item(variant: "button",text: t(".delete"),diff --git a/app/views/wise_items/_wise_item.html.erb b/app/views/wise_items/_wise_item.html.erbindex f808572213..75c18fa6f4 100644--- a/app/views/wise_items/_wise_item.html.erb+++ b/app/views/wise_items/_wise_item.html.erb@@ -48,6 +48,7 @@) %><%= render DS::Menu.new do |menu| %>+ <% sync_schedule_menu_item(menu, wise_item) %><% menu.with_item(variant: "button",text: t(".delete"),diff --git a/config/locales/views/sync_schedules/en.yml b/config/locales/views/sync_schedules/en.ymlnew file mode 100644index 0000000000..c6cebf3c42--- /dev/null+++ b/config/locales/views/sync_schedules/en.yml@@ -0,0 +1,19 @@+---+en:+ sync_schedules:+ menu_item: Sync frequency+ intervals:+ minutes: Every %{count} minutes+ hours:+ one: Every hour+ other: Every %{count} hours+ edit:+ title: Sync frequency+ description: Every connection syncs with the family sync, once a day for most providers. Pick an interval to also sync %{name} on its own through the day.+ interval_label: Sync+ no_schedule: Usual sync only+ hint: Frequent syncs count against the provider's rate limits, and some providers bill per request.+ save: Save+ update:+ updated: Sync frequency saved.+ cleared: Sync frequency removed. The connection is back to its usual sync.diff --git a/config/routes.rb b/config/routes.rbindex 5dd41429bc..ea446b404c 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -348,6 +348,9 @@ Rails.application.routes.draw doendend+ # Per-connection sync cadence; the connection is given as ?syncable_type=&syncable_id=+ resource :sync_schedule, only: %i[edit update]+get "exports/archive/:token", to: "archived_exports#show", as: :archived_exportget "changelog", to: "pages#changelog"diff --git a/config/schedule.yml b/config/schedule.ymlindex ea00d3227c..57cadfb46c 100644--- a/config/schedule.yml+++ b/config/schedule.yml@@ -32,6 +32,13 @@ sync_hourly:queue: "scheduled"description: "Syncs provider items that opt-in to hourly syncing"+sync_scheduled_items:+ cron: "*/15 * * * *" # SyncSchedule::TICK+ class: "SyncScheduledItemsJob"+ active_job: true+ queue: "scheduled"+ description: "Syncs provider connections whose per-connection schedule has come due"+sync_property_valuations:cron: "30 1 1 * *" # monthly on the 1st at 1:30 AMclass: "SyncPropertyValuationsJob"diff --git a/db/migrate/20261101120000_create_sync_schedules.rb b/db/migrate/20261101120000_create_sync_schedules.rbnew file mode 100644index 0000000000..12060a7895--- /dev/null+++ b/db/migrate/20261101120000_create_sync_schedules.rb@@ -0,0 +1,13 @@+class CreateSyncSchedules < ActiveRecord::Migration[8.1]+ def change+ create_table :sync_schedules, id: :uuid do |t|+ t.references :syncable, polymorphic: true, type: :uuid, null: false, index: { unique: true }+ t.integer :interval_minutes, null: false+ t.datetime :next_run_at, null: false++ t.timestamps+ end++ add_index :sync_schedules, :next_run_at+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 64f77314fc..a6d49a005e 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -10,7 +10,7 @@## It's strongly recommended that you check this file into your version control system.-ActiveRecord::Schema[8.1].define(version: 2026_10_31_120000) do+ActiveRecord::Schema[8.1].define(version: 2026_11_01_120000) do# These are extensions that must be enabled in order to support this databaseenable_extension "pg_catalog.plpgsql"enable_extension "pgcrypto"@@ -2634,6 +2634,17 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_31_120000) dot.index ["family_id"], name: "index_subscriptions_on_family_id", unique: trueend+ create_table "sync_schedules", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|+ t.datetime "created_at", null: false+ t.integer "interval_minutes", null: false+ t.datetime "next_run_at", null: false+ t.uuid "syncable_id", null: false+ t.string "syncable_type", null: false+ t.datetime "updated_at", null: false+ t.index ["next_run_at"], name: "index_sync_schedules_on_next_run_at"+ t.index ["syncable_type", "syncable_id"], name: "index_sync_schedules_on_syncable", unique: true+ end+create_table "syncs", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|t.datetime "cancel_requested_at"t.datetime "completed_at"diff --git a/lib/generators/provider/family/templates/item_partial.html.erb.tt b/lib/generators/provider/family/templates/item_partial.html.erb.ttindex 5f6c35cef2..6fe9e404c0 100644--- a/lib/generators/provider/family/templates/item_partial.html.erb.tt+++ b/lib/generators/provider/family/templates/item_partial.html.erb.tt@@ -61,6 +61,7 @@<%% end %><%%= render DS::Menu.new do |menu| %>+ <%% sync_schedule_menu_item(menu, <%= file_name %>_item) %><%% menu.with_item(variant: "button",text: t(".delete"),diff --git a/test/controllers/sync_schedules_controller_test.rb b/test/controllers/sync_schedules_controller_test.rbnew file mode 100644index 0000000000..1e90dfa662--- /dev/null+++ b/test/controllers/sync_schedules_controller_test.rb@@ -0,0 +1,138 @@+require "test_helper"++class SyncSchedulesControllerTest < ActionDispatch::IntegrationTest+ setup do+ sign_in @user = users(:family_admin)+ @item = plaid_items(:one)+ @target = { syncable_type: "PlaidItem", syncable_id: @item.id }+ end++ test "the accounts page offers the schedule from a connection's menu" do+ get accounts_url++ assert_response :ok+ assert_select "a[href=?]", edit_sync_schedule_path(@target), text: I18n.t("sync_schedules.menu_item")+ end++ test "edit shows the interval choices with no schedule as the default" do+ get edit_sync_schedule_url(@target)++ assert_response :ok+ assert_select "turbo-frame#modal form[action=?]", sync_schedule_path(@target) do+ # DS::Button renders type="button" unless told otherwise, which submits nothing.+ assert_select "button[type=submit]", text: I18n.t("sync_schedules.edit.save")+ end+ assert_select "select[name='sync_schedule[interval_minutes]']" do+ assert_select "option[value='']", text: I18n.t("sync_schedules.edit.no_schedule")+ assert_select "option[value]", count: SyncSchedule::INTERVALS.size + 1+ assert_select "option[selected]", count: 0+ end+ end++ test "edit preselects the current interval" do+ @item.create_sync_schedule!(interval_minutes: 120)++ get edit_sync_schedule_url(@target)++ assert_select "option[selected][value='120']", text: "Every 2 hours"+ end++ test "update creates the schedule" do+ assert_difference "SyncSchedule.count", 1 do+ patch sync_schedule_url(@target), params: { sync_schedule: { interval_minutes: 30 } }+ end++ assert_redirected_to accounts_path+ assert_equal 30, @item.reload.sync_schedule.interval_minutes+ end++ test "update changes the interval of an existing schedule" do+ @item.create_sync_schedule!(interval_minutes: 30)++ assert_no_difference "SyncSchedule.count" do+ patch sync_schedule_url(@target), params: { sync_schedule: { interval_minutes: 240 } }+ end++ assert_equal 240, @item.reload.sync_schedule.interval_minutes+ end++ test "update with no interval removes the schedule" do+ @item.create_sync_schedule!(interval_minutes: 30)++ patch sync_schedule_url(@target), params: { sync_schedule: { interval_minutes: "" } }++ assert_redirected_to accounts_path+ assert_nil @item.reload.sync_schedule+ end++ test "update rejects an interval that is not offered" do+ patch sync_schedule_url(@target), params: { sync_schedule: { interval_minutes: 45 } }++ assert_response :unprocessable_entity+ assert_nil @item.reload.sync_schedule+ end++ test "a rejected interval is reported and the saved one stays selected" do+ @item.create_sync_schedule!(interval_minutes: 120)++ patch sync_schedule_url(@target), params: { sync_schedule: { interval_minutes: 45 } }++ assert_response :unprocessable_entity+ assert_select "p.text-destructive", text: /Interval minutes/+ assert_select "option[selected][value='120']"+ assert_equal 120, @item.reload.sync_schedule.interval_minutes+ end++ test "update without the interval field changes nothing" do+ @item.create_sync_schedule!(interval_minutes: 30)++ patch sync_schedule_url(@target), params: { sync_schedule: { other: "x" } }++ assert_response :unprocessable_entity+ assert_equal 30, @item.reload.sync_schedule.interval_minutes+ end++ test "a connection being deleted is not found" do+ @item.update_column(:scheduled_for_deletion, true)++ get edit_sync_schedule_url(@target)++ assert_response :not_found+ end++ test "a member who does not own the connection is turned away" do+ sign_in users(:family_member)++ patch sync_schedule_url(@target), params: { sync_schedule: { interval_minutes: 30 } }++ assert_redirected_to accounts_path+ assert_equal I18n.t("shared.require_admin"), flash[:alert]+ assert_nil @item.reload.sync_schedule+ end++ # Plaid is a per-connection credential, so a member may manage their own.+ test "a member may schedule a connection they own" do+ member = users(:family_member)+ @item.update!(owner: member)+ sign_in member++ patch sync_schedule_url(@target), params: { sync_schedule: { interval_minutes: 30 } }++ assert_redirected_to accounts_path+ assert_equal 30, @item.reload.sync_schedule.interval_minutes+ end++ test "a connection of another family is not found" do+ other = PlaidItem.create!(family: families(:empty), plaid_id: "item_other", access_token: "token", name: "Elsewhere")++ get edit_sync_schedule_url(syncable_type: "PlaidItem", syncable_id: other.id)++ assert_response :not_found+ end++ test "a type that is not a provider connection is not found" do+ get edit_sync_schedule_url(syncable_type: "Account", syncable_id: accounts(:depository).id)++ assert_response :not_found+ end+enddiff --git a/test/helpers/sync_schedules_helper_test.rb b/test/helpers/sync_schedules_helper_test.rbnew file mode 100644index 0000000000..fb36b51ca2--- /dev/null+++ b/test/helpers/sync_schedules_helper_test.rb@@ -0,0 +1,48 @@+require "test_helper"++class SyncSchedulesHelperTest < ActionView::TestCase+ class RecordingMenu+ attr_reader :items++ def initialize+ @items = []+ end++ def with_item(**options)+ @items << options+ end+ end++ setup do+ @menu = RecordingMenu.new+ end++ teardown { Current.session = nil }++ test "offers the entry to a viewer who may edit the schedule" do+ Current.session = users(:family_admin).sessions.create!++ sync_schedule_menu_item(@menu, redbark_items(:one))++ assert_equal [ edit_sync_schedule_path(syncable_type: "RedbarkItem", syncable_id: redbark_items(:one).id) ], @menu.items.map { |item| item[:href] }+ end++ # Redbark's and Sophtron's cards show their menu to members, whom the+ # editor would turn away.+ test "leaves the entry out for a member the editor would turn away" do+ Current.session = users(:family_member).sessions.create!++ sync_schedule_menu_item(@menu, redbark_items(:one))++ assert_empty @menu.items+ end++ test "leaves the entry out for a connection being deleted" do+ Current.session = users(:family_admin).sessions.create!+ redbark_items(:one).update_column(:scheduled_for_deletion, true)++ sync_schedule_menu_item(@menu, redbark_items(:one))++ assert_empty @menu.items+ end+enddiff --git a/test/jobs/sync_scheduled_items_job_test.rb b/test/jobs/sync_scheduled_items_job_test.rbnew file mode 100644index 0000000000..707ac15b30--- /dev/null+++ b/test/jobs/sync_scheduled_items_job_test.rb@@ -0,0 +1,98 @@+require "test_helper"++class SyncScheduledItemsJobTest < ActiveJob::TestCase+ setup do+ @plaid_item = plaid_items(:one)+ @wise_item = wise_items(:one)+ end++ test "syncs the connections whose schedule is due and advances them" do+ schedule = due_schedule(@plaid_item)++ assert_difference -> { @plaid_item.syncs.count }, 1 do+ SyncScheduledItemsJob.perform_now+ end++ assert_enqueued_with(job: SyncJob)+ assert_operator schedule.reload.next_run_at, :>, Time.current+ end++ test "a Plaid connection is asked to refresh, as every other sync entry point does" do+ due_schedule(@plaid_item)+ PlaidItem.any_instance.expects(:sync_later_with_provider_refresh).once++ SyncScheduledItemsJob.perform_now+ end++ test "does not sync a schedule that is no longer due once locked" do+ due_schedule(@plaid_item)+ SyncSchedule.any_instance.stubs(:advance!).returns(false)++ assert_no_difference -> { @plaid_item.syncs.count } do+ SyncScheduledItemsJob.perform_now+ end+ end++ test "leaves schedules that are not yet due alone" do+ schedule = @plaid_item.create_sync_schedule!(interval_minutes: 720)++ assert_no_difference -> { @plaid_item.syncs.count } do+ SyncScheduledItemsJob.perform_now+ end++ assert_equal schedule.next_run_at, schedule.reload.next_run_at+ end++ # A connection on its way out, or otherwise outside the class's `syncable`+ # scope, is skipped the same way the daily family sync skips it.+ test "skips connections the provider no longer syncs" do+ schedule = due_schedule(@plaid_item)+ @plaid_item.update_column(:scheduled_for_deletion, true)++ assert_no_difference -> { @plaid_item.syncs.count } do+ SyncScheduledItemsJob.perform_now+ end++ assert_operator schedule.reload.next_run_at, :>, Time.current+ end++ test "drops a schedule whose connection is gone" do+ schedule = due_schedule(@plaid_item)+ schedule.update_columns(syncable_id: SecureRandom.uuid)++ SyncScheduledItemsJob.perform_now++ assert_not SyncSchedule.exists?(schedule.id)+ end++ test "drops a schedule whose provider no longer exists" do+ schedule = due_schedule(@plaid_item)+ schedule.update_columns(syncable_type: "RetiredProviderItem")++ assert_nothing_raised { SyncScheduledItemsJob.perform_now }++ assert_not SyncSchedule.exists?(schedule.id)+ end++ test "keeps going when one connection fails to sync, and records the failure for support" do+ due_schedule(@plaid_item)+ due_schedule(@wise_item)+ PlaidItem.any_instance.stubs(:sync_later_with_provider_refresh).raises(StandardError, "boom")++ assert_difference -> { @wise_item.syncs.count }, 1 do+ assert_nothing_raised { SyncScheduledItemsJob.perform_now }+ end++ entry = DebugLogEntry.order(:created_at).last+ assert_equal [ "provider_sync", "error", "SyncScheduledItemsJob", "plaid" ], [ entry.category, entry.level, entry.source, entry.provider_key ]+ assert_equal @plaid_item.family, entry.family+ assert_equal({ "syncable_type" => "PlaidItem", "syncable_id" => @plaid_item.id, "error_class" => "StandardError" }, entry.metadata)+ end++ private+ def due_schedule(item)+ item.create_sync_schedule!(interval_minutes: 15).tap do |schedule|+ schedule.update_column(:next_run_at, 1.minute.ago)+ end+ end+enddiff --git a/test/lib/generators/provider/family_generator_test.rb b/test/lib/generators/provider/family_generator_test.rbindex a17e1643e6..2c0f512e05 100644--- a/test/lib/generators/provider/family_generator_test.rb+++ b/test/lib/generators/provider/family_generator_test.rb@@ -372,7 +372,7 @@ class Provider::FamilyGeneratorTest < ActiveSupport::TestCaseassert_includes generated, "<%= tag.div id: dom_id(gocardless_item) do %>"end- test "the generated item card renders the visible accounts it is given" do+ test "the generated item card renders sync frequency and the visible accounts it is given" doCurrent.session = Session.create!(user: users(:family_admin))item = redbark_items(:one)linked = accounts(:depository)@@ -388,6 +388,7 @@ class Provider::FamilyGeneratorTest < ActiveSupport::TestCaseother = render_card.call(-> { [ accounts(:investment) ] })assert_includes after, item.name+ assert_includes after, I18n.t("sync_schedules.menu_item")assert_not_includes before, linked.nameassert_includes after, linked.nameassert_not_includes after, accounts(:investment).namediff --git a/test/models/sync_schedule_test.rb b/test/models/sync_schedule_test.rbnew file mode 100644index 0000000000..b5788029ef--- /dev/null+++ b/test/models/sync_schedule_test.rb@@ -0,0 +1,156 @@+require "test_helper"++class SyncScheduleTest < ActiveSupport::TestCase+ setup do+ @item = plaid_items(:one)+ end++ test "only the offered intervals are accepted" do+ schedule = @item.build_sync_schedule(interval_minutes: 45)++ assert_not schedule.valid?+ assert_includes schedule.errors[:interval_minutes], "is not included in the list"++ schedule.interval_minutes = 30+ assert schedule.valid?+ end++ test "a connection carries at most one schedule" do+ @item.create_sync_schedule!(interval_minutes: 60)+ duplicate = SyncSchedule.new(syncable: @item, interval_minutes: 30)++ assert_not duplicate.valid?+ assert duplicate.errors[:syncable_id].any?+ end++ test "only provider connections may be scheduled" do+ account = SyncSchedule.new(syncable: accounts(:depository), interval_minutes: 30)+ family = SyncSchedule.new(syncable: families(:dylan_family), interval_minutes: 30)++ assert_not account.valid?+ assert_not family.valid?+ assert SyncSchedule.new(syncable: wise_items(:one), interval_minutes: 30).valid?+ end++ test "schedulable associations are the family's syncable item associations" do+ associations = SyncSchedule.schedulable_associations++ assert_equal :plaid_items, associations["PlaidItem"]+ assert_equal :truelayer_items, associations["TruelayerItem"]+ assert_not associations.key?("Account")+ end++ # Runs land on multiples of the interval from midnight UTC, so a connection+ # on "every 6 hours" syncs at the same clock times every day.+ test "the next run is the first interval boundary after now" do+ travel_to Time.utc(2026, 11, 1, 10, 7, 30) do+ quarter_hourly = @item.create_sync_schedule!(interval_minutes: 15)+ assert_equal Time.utc(2026, 11, 1, 10, 15), quarter_hourly.next_run_at++ quarter_hourly.update!(interval_minutes: 360)+ assert_equal Time.utc(2026, 11, 1, 12, 0), quarter_hourly.next_run_at+ end+ end++ test "advancing moves to the boundary after the given time, never the same one" do+ schedule = @item.create_sync_schedule!(interval_minutes: 30)+ schedule.update_column(:next_run_at, Time.utc(2026, 11, 1, 10, 30))++ assert schedule.advance!(from: Time.utc(2026, 11, 1, 10, 30, 0, 400_000))+ assert_equal Time.utc(2026, 11, 1, 11, 0), schedule.next_run_at++ assert schedule.advance!(from: Time.utc(2026, 11, 1, 11, 0))+ assert_equal Time.utc(2026, 11, 1, 11, 30), schedule.next_run_at+ end++ test "advancing counts in the interval saved since the row was loaded" do+ schedule = @item.create_sync_schedule!(interval_minutes: 15)+ SyncSchedule.where(id: schedule.id).update_all(interval_minutes: 720, next_run_at: Time.utc(2026, 11, 1, 10, 0))++ assert schedule.advance!(from: Time.utc(2026, 11, 1, 10, 5))++ assert_equal Time.utc(2026, 11, 1, 12, 0), schedule.next_run_at+ end++ # The job loads every due row before advancing any of them; a schedule+ # changed in between was realigned to the future and is not run.+ test "advancing a schedule that is no longer due leaves it and reports false" do+ travel_to Time.utc(2026, 11, 1, 10, 7) do+ loaded = @item.create_sync_schedule!(interval_minutes: 15)+ loaded.update_column(:next_run_at, Time.utc(2026, 11, 1, 10, 0))+ SyncSchedule.find(loaded.id).update!(interval_minutes: 60)++ assert_not loaded.advance!+ assert_equal Time.utc(2026, 11, 1, 11, 0), loaded.next_run_at+ assert_equal 60, loaded.interval_minutes+ end+ end++ test "advancing a schedule removed since it was loaded reports false" do+ loaded = @item.create_sync_schedule!(interval_minutes: 15)+ SyncSchedule.where(id: loaded.id).delete_all++ assert_not loaded.advance!+ end++ test "assign creates the schedule on first use and changes it after" do+ schedule = SyncSchedule.assign(@item, 60)+ assert schedule.persisted?+ assert_equal 60, @item.reload.sync_schedule.interval_minutes++ SyncSchedule.assign(@item, 30)+ assert_equal 30, @item.reload.sync_schedule.interval_minutes+ assert_equal 1, SyncSchedule.where(syncable: @item).count+ end++ test "assign reports a rejected interval without saving" do+ schedule = SyncSchedule.assign(@item, 45)++ assert schedule.errors[:interval_minutes].any?+ assert_nil @item.reload.sync_schedule+ end++ # Two requests for a connection with no schedule both find none and both+ # pass the uniqueness validation; the unique index turns the second away.+ test "assign applies the interval to a schedule created by a concurrent request" do+ assert_nil @item.sync_schedule+ competing = SyncSchedule.create!(syncable_type: "PlaidItem", syncable_id: @item.id, interval_minutes: 60)+ ActiveRecord::Validations::UniquenessValidator.any_instance.stubs(:validate_each)++ schedule = SyncSchedule.assign(@item, 30)++ assert_equal competing.id, schedule.id+ assert_equal 30, competing.reload.interval_minutes+ assert_equal 1, SyncSchedule.where(syncable: @item).count+ end++ test "admins may edit any connection's schedule, members only one they own on an ownable provider" do+ admin = users(:family_admin)+ member = users(:family_member)+ redbark = redbark_items(:one)++ assert SyncSchedule.editable_by?(@item, admin)+ assert SyncSchedule.editable_by?(redbark, admin)+ assert_not SyncSchedule.editable_by?(@item, member)+ assert_not SyncSchedule.editable_by?(redbark, member)+ assert_not SyncSchedule.editable_by?(@item, nil)++ @item.update!(owner: member)+ assert SyncSchedule.editable_by?(@item, member)+ end++ test "a connection being deleted takes no schedule" do+ @item.update_column(:scheduled_for_deletion, true)++ assert_not SyncSchedule.editable_by?(@item, users(:family_admin))+ end++ test "due lists schedules whose time has come" do+ due = @item.create_sync_schedule!(interval_minutes: 15)+ due.update_column(:next_run_at, 1.minute.ago)+ later = wise_items(:one).create_sync_schedule!(interval_minutes: 15)++ assert_includes SyncSchedule.due, due+ assert_not_includes SyncSchedule.due, later+ end+end