The personal finance app for everyone (by everyone)
Ruby
feat(monobank): add monobank (UA) bank sync (#3386)
Yaroslav Shparuk307d1b61d1d1
diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rbindex 8f36c864d7..05748dbfa5 100644--- a/app/controllers/accounts_controller.rb+++ b/app/controllers/accounts_controller.rb@@ -19,6 +19,7 @@ class AccountsController < ApplicationController@redbark_items = visible_provider_items(family.redbark_items.ordered.with_attached_logo.includes(:redbark_accounts))@akahu_items = visible_provider_items(family.akahu_items.ordered.with_attached_logo.includes(:akahu_accounts))@up_items = visible_provider_items(family.up_items.ordered.with_attached_logo.includes(:up_accounts))+ @monobank_items = visible_provider_items(family.monobank_items.ordered.with_attached_logo.includes(:monobank_accounts))@enable_banking_items = visible_provider_items(family.enable_banking_items.ordered.with_attached_logo)@coinstats_items = visible_provider_items(family.coinstats_items.ordered.with_attached_logo.includes(:coinstats_accounts, :accounts))@mercury_items = visible_provider_items(family.mercury_items.ordered.with_attached_logo.includes(:mercury_accounts))@@ -357,6 +358,7 @@ class AccountsController < ApplicationController@redbark_items,@akahu_items,@up_items,+ @monobank_items,@enable_banking_items,@coinstats_items,@mercury_items,@@ -503,6 +505,13 @@ class AccountsController < ApplicationController@up_sync_stats_map[item.id] = latest_sync&.sync_stats || {}end+ # Monobank sync stats+ @monobank_sync_stats_map = {}+ @monobank_items.each do |item|+ latest_sync = item.latest_sync_record+ @monobank_sync_stats_map[item.id] = latest_sync&.sync_stats || {}+ end+# Enable Banking sync stats@enable_banking_sync_stats_map = {}@enable_banking_latest_sync_error_map = {}diff --git a/app/controllers/monobank_items_controller.rb b/app/controllers/monobank_items_controller.rbnew file mode 100644index 0000000000..b001016718--- /dev/null+++ b/app/controllers/monobank_items_controller.rb@@ -0,0 +1,430 @@+# Connections are created, updated and removed from the providers settings panel+# (app/views/settings/providers/_monobank_panel.html.erb), and accounts are linked+# through the dialogs in app/views/monobank_items. There is deliberately no+# index/show/new/edit action: nothing links to them and they would have no template.+class MonobankItemsController < ApplicationController+ before_action :set_monobank_item, only: [ :update, :destroy, :sync, :setup_accounts, :complete_account_setup ]+ before_action :require_admin!, only: [+ :create, :preload_accounts, :select_accounts, :link_accounts,+ :select_existing_account, :link_existing_account, :update,+ :destroy, :sync, :setup_accounts, :complete_account_setup+ ]++ # Create a Monobank connection and kick off its first sync.+ def create+ @monobank_item = Current.family.monobank_items.build(monobank_item_params)+ @monobank_item.name = t("monobank_items.provider_panel.default_connection_name") if @monobank_item.name.blank?++ if @monobank_item.save+ @monobank_item.sync_later+ render_provider_panel(:notice, t(".success"))+ else+ render_provider_panel_error(@monobank_item.errors.full_messages.join(", "))+ end+ end++ # Update connection settings (name/token/start date).+ def update+ if @monobank_item.update(update_params)+ render_provider_panel(:notice, t(".success"))+ else+ render_provider_panel_error(@monobank_item.errors.full_messages.join(", "))+ end+ end++ # Unlink all accounts then schedule deletion of the connection.+ def destroy+ results = @monobank_item.unlink_all!(dry_run: false)++ if results.any? { |result| result[:error].present? }+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "warn",+ message: "Monobank unlink during destroy failed",+ source: self.class.name,+ provider_key: "monobank",+ family: @monobank_item.family,+ metadata: { monobank_item_id: @monobank_item.id, failures: results.select { |r| r[:error].present? } }+ )+ redirect_to settings_providers_path, alert: t(".unlink_failed"), status: :see_other+ return+ end++ @monobank_item.destroy_later+ redirect_to settings_providers_path, notice: t(".success"), status: :see_other+ rescue => e+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "warn",+ message: "Monobank unlink during destroy failed",+ source: self.class.name,+ provider_key: "monobank",+ family: @monobank_item&.family,+ metadata: { monobank_item_id: @monobank_item&.id, error_class: e.class.name, error_message: e.message }+ )+ redirect_to settings_providers_path, alert: t(".unlink_failed"), status: :see_other+ end++ # Trigger a manual sync unless one is already running.+ def sync+ @monobank_item.sync_later unless @monobank_item.syncing?++ respond_to do |format|+ format.html { redirect_back_or_to accounts_path }+ format.json { head :ok }+ end+ end++ # Fetch accounts from the API (JSON) so the UI can show whether any exist.+ def preload_accounts+ monobank_item = requested_monobank_item+ return render json: { success: false, error: "no_credentials", has_accounts: false } unless monobank_item.credentials_configured?++ error = fetch_monobank_accounts_from_api(monobank_item)+ render json: { success: error.blank?, error_message: error, has_accounts: monobank_item.monobank_accounts.exists? }+ end++ # Render the picker of unlinked Monobank accounts for a new Sure account.+ def select_accounts+ @accountable_type = params[:accountable_type] || "Depository"+ @return_to = safe_return_to_path+ @monobank_item = requested_monobank_item++ unless @monobank_item.credentials_configured?+ redirect_to settings_providers_path, alert: t(".no_credentials_configured")+ return+ end++ @api_error = fetch_monobank_accounts_from_api(@monobank_item)+ @monobank_accounts = @monobank_item.monobank_accounts+ .left_joins(:account_provider)+ .where(account_providers: { id: nil })+ .order(:name)++ render layout: false+ end++ # Create new Sure accounts for the selected Monobank accounts and link them.+ def link_accounts+ monobank_item = requested_monobank_item+ unless monobank_item.credentials_configured?+ redirect_to settings_providers_path, alert: t(".no_credentials_configured")+ return+ end++ selected_ids = Array(params[:account_ids]).compact_blank+ if selected_ids.empty?+ redirect_to select_accounts_monobank_items_path(monobank_item_id: monobank_item.id, accountable_type: params[:accountable_type], return_to: safe_return_to_path), alert: t(".no_accounts_selected")+ return+ end++ account_type = params[:accountable_type].presence || "Depository"+ unless Provider::MonobankAdapter.supported_account_types.include?(account_type)+ redirect_to new_account_path, alert: t(".unsupported_account_type")+ return+ end++ created_accounts = []++ ActiveRecord::Base.transaction do+ monobank_item.monobank_accounts.where(id: selected_ids).find_each do |monobank_account|+ next if monobank_account.account_provider.present?++ account = create_account_from_monobank(monobank_account, account_type)+ AccountProvider.create!(account: account, provider: monobank_account)+ created_accounts << account+ end+ end++ monobank_item.sync_later if created_accounts.any?++ if created_accounts.any?+ redirect_to safe_return_to_path || accounts_path, notice: t(".success", count: created_accounts.count)+ else+ redirect_to select_accounts_monobank_items_path(monobank_item_id: monobank_item.id, accountable_type: account_type, return_to: safe_return_to_path), alert: t(".link_failed")+ end+ rescue ActiveRecord::RecordNotUnique+ # A concurrent submit linked one of these accounts first; the transaction rolled the+ # whole batch back, so send the user back to the picker rather than a 500.+ redirect_to select_accounts_monobank_items_path(monobank_item_id: monobank_item.id, accountable_type: params[:accountable_type], return_to: safe_return_to_path), alert: t(".link_failed")+ end++ # Render the picker to attach a Monobank account to an existing Sure account.+ def select_existing_account+ @account = Current.family.accounts.find(params[:account_id])++ if @account.account_providers.exists?+ redirect_to accounts_path, alert: t(".account_already_linked")+ return+ end++ @monobank_item = requested_monobank_item+ unless @monobank_item.credentials_configured?+ redirect_to settings_providers_path, alert: t(".no_credentials_configured")+ return+ end++ @api_error = fetch_monobank_accounts_from_api(@monobank_item)+ @monobank_accounts = @monobank_item.monobank_accounts+ .left_joins(:account_provider)+ .where(account_providers: { id: nil })+ .order(:name)+ @return_to = safe_return_to_path++ render layout: false+ end++ # Link a selected Monobank account to an existing Sure account and sync.+ def link_existing_account+ account = Current.family.accounts.find(params[:account_id])+ monobank_item = requested_monobank_item++ unless monobank_item.credentials_configured?+ redirect_to settings_providers_path, alert: t("monobank_items.select_existing_account.no_credentials_configured")+ return+ end++ if params[:monobank_account_id].blank?+ redirect_to accounts_path, alert: t(".no_account_selected")+ return+ end++ monobank_account = monobank_item.monobank_accounts.find_by(id: params[:monobank_account_id])+ unless monobank_account+ redirect_to accounts_path, alert: t(".no_account_selected")+ return+ end++ if account.account_providers.exists?+ redirect_to accounts_path, alert: t(".account_already_linked")+ return+ end++ if monobank_account.account_provider.present?+ redirect_to accounts_path, alert: t(".monobank_account_already_linked")+ return+ end++ begin+ AccountProvider.create!(account: account, provider: monobank_account)+ rescue ActiveRecord::RecordNotUnique+ # The two guards above are reads; a double submit gets both requests past them and+ # the unique indexes on account_providers are what actually settle it. The request+ # that loses that race gets the same answer the guard would have given it.+ redirect_to accounts_path, alert: t(".account_already_linked")+ return+ end++ monobank_item.sync_later++ redirect_to safe_return_to_path || accounts_path, notice: t(".success", account_name: account.name)+ end++ # Render the post-sync setup screen for accounts still needing a decision.+ def setup_accounts+ @api_error = fetch_monobank_accounts_from_api(@monobank_item)+ @monobank_accounts = @monobank_item.monobank_accounts.needs_setup.order(:name)+ @account_type_options = [+ [ t(".account_types.skip"), "skip" ],+ [ t(".account_types.depository"), "Depository" ]+ ]+ @monobank_account_type_suggestions = @monobank_accounts.each_with_object({}) do |monobank_account, suggestions|+ suggestions[monobank_account.id] = monobank_account.suggested_account_type || "skip"+ end+ end++ # Apply the user's per-account setup choices (create/link or skip).+ def complete_account_setup+ account_types = params[:account_types] || {}+ created_accounts = []+ skipped_count = 0++ ActiveRecord::Base.transaction do+ account_types.each do |monobank_account_id, selected_type|+ monobank_account = @monobank_item.monobank_accounts.find_by(id: monobank_account_id)+ next unless monobank_account++ if selected_type.blank? || selected_type == "skip"+ # Persist the skip so the account stops resurfacing as "needs setup" on every sync.+ monobank_account.update!(ignored: true) unless monobank_account.account_provider.present?+ skipped_count += 1+ next+ end++ next unless Provider::MonobankAdapter.supported_account_types.include?(selected_type)+ next if monobank_account.account_provider.present?++ account = create_account_from_monobank(monobank_account, selected_type)+ AccountProvider.create!(account: account, provider: monobank_account)+ created_accounts << account+ end+ end++ @monobank_item.sync_later if created_accounts.any?++ flash[:notice] = if created_accounts.any?+ t(".success", count: created_accounts.count)+ elsif skipped_count.positive?+ t(".all_skipped")+ else+ t(".no_accounts")+ end++ redirect_to accounts_path, status: :see_other+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved, ActiveRecord::RecordNotUnique => e+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "Monobank account setup failed",+ source: self.class.name,+ provider_key: "monobank",+ family: @monobank_item&.family,+ metadata: { monobank_item_id: @monobank_item&.id, error_class: e.class.name, error_message: e.message }+ )+ redirect_to accounts_path, alert: t(".creation_failed"), status: :see_other+ end++ private++ # Load the requested item scoped to the current family.+ def set_monobank_item+ @monobank_item = Current.family.monobank_items.find(params[:id])+ end++ # Strong params for creating/updating a connection.+ def monobank_item_params+ params.require(:monobank_item).permit(:name, :sync_start_date, :access_token)+ end++ # Params for update, dropping a blank token so it isn't overwritten.+ def update_params+ permitted = monobank_item_params+ permitted = permitted.except(:access_token) if permitted[:access_token].blank?+ permitted+ end++ # Load the active item referenced by monobank_item_id, scoped to the family.+ def requested_monobank_item+ Current.family.monobank_items.active.find_by!(id: params[:monobank_item_id])+ end++ # Fetch and upsert account snapshots from the API; returns an error string or nil.+ def fetch_monobank_accounts_from_api(monobank_item)+ return t("monobank_items.setup_accounts.no_credentials") unless monobank_item.credentials_configured?++ provider = monobank_item.monobank_provider+ accounts = provider.get_accounts+ accounts.each do |account_data|+ account = account_data.with_indifferent_access+ account_id = account[:id].presence+ next if account_id.blank?++ monobank_account = monobank_item.monobank_accounts.find_or_initialize_by(account_id: account_id.to_s)+ monobank_account.upsert_monobank_snapshot!(account)+ end++ nil+ # One branch: a Provider::Monobank::Error and an unexpected one produced the same+ # entry and the same message for the user, and error_class already tells them apart+ # in /settings/debug.+ rescue StandardError => e+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "Failed to fetch Monobank accounts",+ source: self.class.name,+ provider_key: "monobank",+ family: monobank_item.family,+ metadata: { monobank_item_id: monobank_item.id, error_class: e.class.name, error_message: e.message }+ )+ t("monobank_items.setup_accounts.api_error")+ end++ # Create and sync a Sure account from a Monobank account snapshot.+ def create_account_from_monobank(monobank_account, account_type)+ # Linking an account clears any prior skip so a future unlink re-prompts for setup.+ monobank_account.update!(ignored: false) if monobank_account.ignored?++ balance = monobank_account.current_balance || 0+ subtype = if account_type == "Depository" && monobank_account.suggested_account_type == account_type+ monobank_account.suggested_subtype+ end++ Account.create_and_sync(+ {+ family: Current.family,+ name: monobank_account.name,+ balance: balance,+ cash_balance: balance,+ currency: monobank_account.currency || "UAH",+ accountable_type: account_type,+ accountable_attributes: subtype.present? ? { subtype: subtype } : {}+ },+ skip_initial_sync: true+ )+ end++ # Re-render the providers settings panel (Turbo) or redirect with a flash.+ def render_provider_panel(flash_type, message)+ if turbo_frame_request?+ flash.now[flash_type] = message+ @monobank_items = Current.family.monobank_items.active.ordered+ render turbo_stream: [+ turbo_stream.replace(+ "monobank-providers-panel",+ partial: "settings/providers/monobank_panel",+ locals: { monobank_items: @monobank_items }+ ),+ *flash_notification_stream_items+ ]+ else+ redirect_to settings_providers_path, { flash_type => message, status: :see_other }+ end+ end++ # Re-render the providers panel with an error (Turbo) or redirect with alert.+ def render_provider_panel_error(message)+ @error_message = message+ if turbo_frame_request?+ render turbo_stream: turbo_stream.replace(+ "monobank-providers-panel",+ partial: "settings/providers/monobank_panel",+ locals: { error_message: @error_message }+ ), status: :unprocessable_entity+ else+ redirect_to settings_providers_path, alert: @error_message, status: :see_other+ end+ end++ # Validate the return_to param as a safe in-app relative path, or nil.+ def safe_return_to_path+ return nil if params[:return_to].blank?++ return_to = params[:return_to].to_s.strip+ return nil unless return_to.start_with?("/")+ return nil if return_to[1] == "/" || return_to[1] == "\\"+ return nil if return_to.include?("\\") || return_to.match?(/[[:cntrl:]]/)+ return nil if encoded_path_separator?(return_to)++ uri = URI.parse(return_to)+ return nil unless uri.relative?++ Rails.application.routes.recognize_path(uri.path, method: :get)++ return_to+ rescue URI::InvalidURIError, ActionController::RoutingError+ nil+ end++ # True if the path's second char is a percent-encoded slash/backslash+ # (used to block protocol-relative redirect bypasses).+ def encoded_path_separator?(return_to)+ encoded_second_character = return_to[1, 3]+ return false unless encoded_second_character&.start_with?("%")++ decoded = URI.decode_www_form_component(encoded_second_character)+ decoded == "/" || decoded == "\\"+ rescue ArgumentError+ true+ end+enddiff --git a/app/controllers/settings/providers_controller.rb b/app/controllers/settings/providers_controller.rbindex 97845df660..2162fcfc93 100644--- a/app/controllers/settings/providers_controller.rb+++ b/app/controllers/settings/providers_controller.rb@@ -190,6 +190,7 @@ class Settings::ProvidersController < ApplicationControllerFAMILY_PANELS = [{ key: "akahu", title: "Akahu", turbo_id: "akahu", partial: "akahu_panel" },{ key: "up", title: "Up", turbo_id: "up", partial: "up_panel" },+ { key: "monobank", title: "monobank", turbo_id: "monobank", partial: "monobank_panel" },{ key: "lunchflow", title: "Lunch Flow", turbo_id: "lunchflow", partial: "lunchflow_panel" },{ key: "redbark", title: "Redbark", turbo_id: "redbark", partial: "redbark_panel" },{ key: "simplefin", title: "SimpleFIN", turbo_id: "simplefin", partial: "simplefin_panel" },@@ -217,6 +218,7 @@ class Settings::ProvidersController < ApplicationControllerPANEL_SYNCABLE_TYPES = {"akahu" => "AkahuItem","up" => "UpItem",+ "monobank" => "MonobankItem","simplefin" => "SimplefinItem","lunchflow" => "LunchflowItem","redbark" => "RedbarkItem",@@ -244,6 +246,8 @@ class Settings::ProvidersController < ApplicationController@akahu_items = Current.family.akahu_items.active.orderedwhen "up"@up_items = Current.family.up_items.active.ordered+ when "monobank"+ @monobank_items = Current.family.monobank_items.active.orderedwhen "simplefin"@simplefin_items = Current.family.simplefin_items.orderedwhen "lunchflow"@@ -295,6 +299,7 @@ class Settings::ProvidersController < ApplicationController@akahu_items = Current.family.akahu_items.active.ordered@up_items = Current.family.up_items.active.ordered+ @monobank_items = Current.family.monobank_items.active.ordered# Providers page only needs to know whether any SimpleFin/Lunchflow connections exist with valid credentials@simplefin_items = Current.family.simplefin_items.where.not(access_url: [ nil, "" ]).ordered.select(:id)@lunchflow_items = Current.family.lunchflow_items.where.not(api_key: [ nil, "" ]).ordered.select(:id)@@ -335,6 +340,7 @@ class Settings::ProvidersController < ApplicationController{"akahu" => @akahu_items,"up" => @up_items,+ "monobank" => @monobank_items,"simplefin" => @simplefin_items,"lunchflow" => @lunchflow_items,"redbark" => @redbark_items,diff --git a/app/helpers/settings_helper.rb b/app/helpers/settings_helper.rbindex 9580d52f0c..4fa638fa55 100644--- a/app/helpers/settings_helper.rb+++ b/app/helpers/settings_helper.rb@@ -63,6 +63,9 @@ module SettingsHelperwhen "up"return { status: :off } unless @up_items&.any?sync_based_summary(key)+ when "monobank"+ return { status: :off } unless @monobank_items&.any?+ sync_based_summary(key)when "simplefin"return { status: :off } unless @simplefin_items&.any?sync_based_summary(key)diff --git a/app/models/account/provider_import_adapter.rb b/app/models/account/provider_import_adapter.rbindex fb67a2a5fb..0753a475d8 100644--- a/app/models/account/provider_import_adapter.rb+++ b/app/models/account/provider_import_adapter.rb@@ -1,4 +1,14 @@class Account::ProviderImportAdapter+ # Matches a transaction any provider has flagged pending, for the lookups below that+ # join `transactions` directly. Derived from Transaction::PENDING_PROVIDERS rather+ # than spelled out, so a newly supported provider cannot silently drop out of+ # pending→posted reconciliation. Frozen constant built from a frozen provider list:+ # no user input reaches the SQL (same reasoning as Transaction::PENDING_CHECK_SQL).+ PENDING_LOOKUP_SQL = Transaction::PENDING_PROVIDERS+ .map { |provider| "(transactions.extra -> '#{provider}' ->> 'pending')::boolean = true" }+ .join(" OR ")+ .freeze+attr_reader :account, :skipped_entriesdef initialize(account)@@ -786,23 +796,15 @@ class Account::ProviderImportAdapter# 4. Same currency# 5. Date within window (pending can post days later)# 6. Is a Transaction (not Trade or Valuation)- # 7. Has pending=true in transaction.extra["simplefin"]["pending"] or extra["plaid"]["pending"]+ # 7. Has pending=true in transaction.extra[<provider>]["pending"] for any provider+ # in Transaction::PENDING_PROVIDERScandidates = account.entries.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'").where(source: source).where(amount: amount).where(currency: currency).where(date: (date - date_window.days)..date) # Pending must be ON or BEFORE posted date- .where(<<~SQL.squish)- (transactions.extra -> 'simplefin' ->> 'pending')::boolean = true- OR (transactions.extra -> 'plaid' ->> 'pending')::boolean = true- OR (transactions.extra -> 'lunchflow' ->> 'pending')::boolean = true- OR (transactions.extra -> 'enable_banking' ->> 'pending')::boolean = true- OR (transactions.extra -> 'akahu' ->> 'pending')::boolean = true- OR (transactions.extra -> 'up' ->> 'pending')::boolean = true- OR (transactions.extra -> 'mercury' ->> 'pending')::boolean = true- OR (transactions.extra -> 'redbark' ->> 'pending')::boolean = true- SQL+ .where(PENDING_LOOKUP_SQL).order(date: :desc) # Prefer most recent pending transactioncandidates.first@@ -844,16 +846,7 @@ class Account::ProviderImportAdapter.where(currency: currency).where(date: (date - date_window.days)..date) # Pending ON or BEFORE posted.where("ABS(entries.amount) BETWEEN ? AND ?", min_pending_abs, max_pending_abs)- .where(<<~SQL.squish)- (transactions.extra -> 'simplefin' ->> 'pending')::boolean = true- OR (transactions.extra -> 'plaid' ->> 'pending')::boolean = true- OR (transactions.extra -> 'lunchflow' ->> 'pending')::boolean = true- OR (transactions.extra -> 'enable_banking' ->> 'pending')::boolean = true- OR (transactions.extra -> 'akahu' ->> 'pending')::boolean = true- OR (transactions.extra -> 'up' ->> 'pending')::boolean = true- OR (transactions.extra -> 'mercury' ->> 'pending')::boolean = true- OR (transactions.extra -> 'redbark' ->> 'pending')::boolean = true- SQL+ .where(PENDING_LOOKUP_SQL)# If merchant_id is provided, prioritize matching by merchantif merchant_id.present?@@ -918,16 +911,7 @@ class Account::ProviderImportAdapter.where(currency: currency).where(date: (date - date_window.days)..date).where("ABS(entries.amount) BETWEEN ? AND ?", min_pending_abs, max_pending_abs)- .where(<<~SQL.squish)- (transactions.extra -> 'simplefin' ->> 'pending')::boolean = true- OR (transactions.extra -> 'plaid' ->> 'pending')::boolean = true- OR (transactions.extra -> 'lunchflow' ->> 'pending')::boolean = true- OR (transactions.extra -> 'enable_banking' ->> 'pending')::boolean = true- OR (transactions.extra -> 'akahu' ->> 'pending')::boolean = true- OR (transactions.extra -> 'up' ->> 'pending')::boolean = true- OR (transactions.extra -> 'mercury' ->> 'pending')::boolean = true- OR (transactions.extra -> 'redbark' ->> 'pending')::boolean = true- SQL+ .where(PENDING_LOOKUP_SQL)# For low confidence, require BOTH merchant AND name match (stronger signal needed)if merchant_id.present? && name.present?diff --git a/app/models/concerns/iso_numeric_currency.rb b/app/models/concerns/iso_numeric_currency.rbnew file mode 100644index 0000000000..5b05b6c34f--- /dev/null+++ b/app/models/concerns/iso_numeric_currency.rb@@ -0,0 +1,49 @@+# Translates ISO 4217 numeric currency codes into the alphabetic codes Sure stores.+#+# Most providers report currencies as "UAH"/"USD", which CurrencyNormalizable handles+# directly. Some (Monobank) report the numeric code instead (980, 840), so those values+# have to be mapped before parse_currency sees them — it rejects anything that is not+# three letters. Amounts from the same APIs arrive in minor units, so the minor-unit+# divisor is exposed here too rather than hardcoding 100 (JPY, KRW and friends use 1).+module IsoNumericCurrency+ extend ActiveSupport::Concern++ class << self+ # Memoized { "980" => "UAH" } map built from Sure's currency table. Built lazily so+ # the YAML is only read when a provider actually needs a numeric lookup.+ def alpha_by_numeric+ @alpha_by_numeric ||= Money::Currency.all.each_value.with_object({}) do |currency_data, map|+ numeric = currency_data["iso_numeric"].to_s.strip+ iso_code = currency_data["iso_code"].to_s.strip+ next if numeric.blank? || iso_code.blank?++ map[numeric.rjust(3, "0")] ||= iso_code.upcase+ end.freeze+ end+ end++ private++ # @param numeric_code [String, Integer, nil] ISO 4217 numeric code (e.g. 980, "036")+ # @return [String, nil] Alphabetic ISO code (e.g. "UAH"), or nil when unknown+ def alpha_currency_code(numeric_code)+ return nil if numeric_code.blank?++ IsoNumericCurrency.alpha_by_numeric[normalize_numeric_code(numeric_code)]+ end++ # Divisor that converts an amount in minor units into major units. Falls back to 100+ # for unknown currencies, which is right for every currency Monobank supports.+ def minor_unit_divisor(alpha_code)+ return 100 if alpha_code.blank?++ Money::Currency.new(alpha_code).minor_unit_conversion || 100+ rescue Money::Currency::UnknownCurrencyError+ 100+ end++ # ISO numeric codes are zero-padded to three digits in currencies.yml ("036").+ def normalize_numeric_code(numeric_code)+ numeric_code.to_s.strip.rjust(3, "0")+ end+enddiff --git a/app/models/data_enrichment.rb b/app/models/data_enrichment.rbindex d15b92548c..8d9f52d1fb 100644--- a/app/models/data_enrichment.rb+++ b/app/models/data_enrichment.rb@@ -8,6 +8,7 @@ class DataEnrichment < ApplicationRecordlunchflow: "lunchflow",akahu: "akahu",up: "up",+ monobank: "monobank",synth: "synth",ai: "ai",enable_banking: "enable_banking",diff --git a/app/models/family.rb b/app/models/family.rbindex e9efcabbf1..e661a3e1e1 100644--- a/app/models/family.rb+++ b/app/models/family.rb@@ -4,6 +4,7 @@ class Family < ApplicationRecordinclude CoinbaseConnectable, BinanceConnectable, KrakenConnectable, CoinstatsConnectable, SnaptradeConnectable, MercuryConnectable, BrexConnectable, SophtronConnectableinclude IndexaCapitalConnectable, IbkrConnectable, WiseConnectableinclude UpConnectable+ include MonobankConnectableinclude Trading212Connectableinclude TradeRepublicConnectableinclude QuestradeConnectablediff --git a/app/models/family/financial_data_reset.rb b/app/models/family/financial_data_reset.rbindex b52c8e3786..9ef4d4fbe3 100644--- a/app/models/family/financial_data_reset.rb+++ b/app/models/family/financial_data_reset.rb@@ -58,6 +58,7 @@ class Family::FinancialDataResetsnaptrade_itemssophtron_itemsup_items+ monobank_items].freezeResult = Struct.new(:user, :family, :dry_run, :before_counts, :deleted_counts, :after_counts, keyword_init: true)diff --git a/app/models/family/monobank_connectable.rb b/app/models/family/monobank_connectable.rbnew file mode 100644index 0000000000..867ffb778d--- /dev/null+++ b/app/models/family/monobank_connectable.rb@@ -0,0 +1,28 @@+module Family::MonobankConnectable+ extend ActiveSupport::Concern++ included do+ has_many :monobank_items, dependent: :destroy+ end++ # Whether this family may connect Monobank accounts (always true).+ def can_connect_monobank?+ true+ end++ # Create a Monobank connection with the given personal token and start its first sync.+ def create_monobank_item!(access_token:, item_name: nil)+ monobank_item = monobank_items.create!(+ name: item_name || I18n.t("family.monobank.create_monobank_item.default_name"),+ access_token: access_token+ )++ monobank_item.sync_later+ monobank_item+ end++ # True when any active Monobank item has usable credentials.+ def has_monobank_credentials?+ monobank_items.active.any?(&:credentials_configured?)+ end+enddiff --git a/app/models/monobank_account.rb b/app/models/monobank_account.rbnew file mode 100644index 0000000000..6d98b16272--- /dev/null+++ b/app/models/monobank_account.rb@@ -0,0 +1,173 @@+class MonobankAccount < ApplicationRecord+ include CurrencyNormalizable, IsoNumericCurrency, Encryptable++ # Monobank card types (and jars) mapped onto Sure accountable types/subtypes.+ # Everything Monobank exposes on the personal API is a current account holding the+ # client's own money, so all of them land on Depository. A card with a credit limit is+ # still Depository rather than CreditCard: the limit is subtracted out of the balance+ # (see #upsert_monobank_snapshot!), leaving own funds, which is what Sure tracks for a+ # cash account.+ MONOBANK_ACCOUNT_TYPE_MAP = {+ "black" => { accountable_type: "Depository", subtype: "checking" },+ "white" => { accountable_type: "Depository", subtype: "checking" },+ "platinum" => { accountable_type: "Depository", subtype: "checking" },+ "iron" => { accountable_type: "Depository", subtype: "checking" },+ "yellow" => { accountable_type: "Depository", subtype: "checking" },+ "eaid" => { accountable_type: "Depository", subtype: "checking" },+ "fop" => { accountable_type: "Depository", subtype: "checking" },+ "jar" => { accountable_type: "Depository", subtype: "savings" }+ }.freeze++ JAR_KIND = "jar".freeze+ CARD_KIND = "card".freeze++ INSTITUTION_NAME = "Monobank".freeze+ INSTITUTION_DOMAIN = "monobank.ua".freeze++ if encryption_ready?+ encrypts :raw_payload+ encrypts :raw_transactions_payload+ # Not deterministic: neither column is ever looked up by value, and an IBAN plus a+ # partial card number are exactly the fields worth keeping opaque at rest.+ encrypts :masked_pan+ encrypts :iban+ end++ belongs_to :monobank_item++ has_one :account_provider, as: :provider, dependent: :destroy+ has_one :account, through: :account_provider, source: :account+ has_one :linked_account, through: :account_provider, source: :account++ validates :name, :currency, presence: true+ validates :account_id, uniqueness: { scope: :monobank_item_id, allow_nil: true }++ # Monobank accounts with no linked Sure account.+ scope :unlinked, -> { left_joins(:account_provider).where(account_providers: { id: nil }) }+ # Unlinked accounts that still need a setup decision (i.e. not explicitly skipped).+ scope :needs_setup, -> { unlinked.where(ignored: false) }++ # The linked Sure account, if any.+ def current_account+ account+ end++ # True when this record is a savings jar rather than a card.+ def jar?+ account_kind == JAR_KIND+ end++ # Localized label for this account's Monobank product ("Black card", "Jar"), used in+ # the account pickers where the stored name may already have been renamed by the user.+ def type_label+ return I18n.t("monobank_account.card_types.jar") if jar?++ card_type_label(account_type)+ end++ # Suggested Sure accountable type for this account, or nil when the card type is+ # unrecognized (a new Monobank product), in which case setup asks the user.+ def suggested_account_type+ type_mapping&.fetch(:accountable_type, nil)+ end++ # Suggested Sure subtype (checking for cards, savings for jars), or nil.+ def suggested_subtype+ type_mapping&.[](:subtype)+ end++ # Persist the latest Monobank account snapshot.+ #+ # Monobank reports money in the currency's minor units and reports `balance` for a+ # card *including* its credit limit, so own funds are balance - creditLimit. Currency+ # arrives as an ISO 4217 numeric code (980), which is translated before the shared+ # currency normalizer sees it.+ def upsert_monobank_snapshot!(account_snapshot)+ snapshot = account_snapshot.with_indifferent_access+ kind = snapshot[:kind].presence || CARD_KIND+ alpha_currency = alpha_currency_code(snapshot[:currencyCode])+ log_invalid_currency(snapshot[:currencyCode]) if snapshot[:currencyCode].present? && alpha_currency.blank?+ divisor = minor_unit_divisor(alpha_currency)++ raw_balance = to_decimal(snapshot[:balance])+ raw_credit_limit = to_decimal(snapshot[:creditLimit])++ assign_attributes(+ current_balance: (raw_balance - raw_credit_limit) / divisor,+ credit_limit: raw_credit_limit / divisor,+ currency: parse_currency(alpha_currency) || "UAH",+ name: display_name_for(snapshot, kind: kind),+ account_id: snapshot[:id],+ account_kind: kind,+ account_type: account_type_for(snapshot, kind: kind),+ masked_pan: Array(snapshot[:maskedPan]).first.presence,+ iban: snapshot[:iban].presence,+ provider: "monobank",+ institution_metadata: {+ name: INSTITUTION_NAME,+ domain: INSTITUTION_DOMAIN+ }.compact,+ raw_payload: account_snapshot+ )++ save!+ end++ # Persist the latest raw transactions payload for this account.+ def upsert_monobank_transactions_snapshot!(transactions_snapshot)+ assign_attributes(raw_transactions_payload: transactions_snapshot)+ save!+ end++ private++ def type_mapping+ MONOBANK_ACCOUNT_TYPE_MAP[account_type.to_s.downcase]+ end++ # Jars are typed "jar" so they get their own mapping and label; cards keep the type+ # Monobank reports ("black", "fop", ...).+ def account_type_for(snapshot, kind:)+ return JAR_KIND if kind == JAR_KIND++ snapshot[:type].presence+ end++ # Monobank gives jars a title but leaves cards unnamed, so a card is labelled by its+ # localized product name plus the last four digits when a masked PAN is present.+ def display_name_for(snapshot, kind:)+ if kind == JAR_KIND+ return snapshot[:title].presence || I18n.t("monobank_account.jar_fallback")+ end++ label = card_type_label(snapshot[:type])+ last_four = Array(snapshot[:maskedPan]).first.to_s[-4..]++ last_four.present? ? "#{label} ·#{last_four}" : label+ end++ # Localized product name for a card type, falling back to the raw value so an+ # unmapped new product still shows something recognizable.+ def card_type_label(type)+ key = type.to_s.downcase.presence || "unknown"++ I18n.t(+ "monobank_account.card_types.#{key}",+ default: I18n.t("monobank_account.card_types.unknown")+ )+ end++ # Monobank sends integer minor units; be tolerant of strings and nils.+ def to_decimal(value)+ return BigDecimal("0") if value.blank?++ BigDecimal(value.to_s)+ rescue ArgumentError+ BigDecimal("0")+ end++ # CurrencyNormalizable hook: warn when a Monobank currency code is unrecognized.+ def log_invalid_currency(currency_value)+ Rails.logger.warn("Invalid currency code '#{currency_value}' for Monobank account #{id}, defaulting to UAH")+ end+enddiff --git a/app/models/monobank_account/processor.rb b/app/models/monobank_account/processor.rbnew file mode 100644index 0000000000..f2cabfca31--- /dev/null+++ b/app/models/monobank_account/processor.rb@@ -0,0 +1,90 @@+class MonobankAccount::Processor+ include CurrencyNormalizable++ SanitizedProcessingError = Class.new(StandardError)++ attr_reader :monobank_account++ # Build a processor for the given +monobank_account+.+ def initialize(monobank_account)+ @monobank_account = monobank_account+ end++ # Sync the linked account's balance and process its transactions. No-op when+ # the Monobank account isn't linked to a Sure account.+ def process+ unless monobank_account.current_account.present?+ Rails.logger.info "MonobankAccount::Processor - No linked account for monobank_account #{monobank_account.id}, skipping processing"+ return+ end++ process_account!+ process_transactions+ rescue StandardError => e+ Rails.logger.error "MonobankAccount::Processor - Failed to process account monobank_account_id=#{monobank_account.id} error_class=#{e.class.name}"+ report_exception(e, "account")+ raise+ end++ private++ # Update the linked Sure account's balance/currency from the Monobank snapshot.+ def process_account!+ account = monobank_account.current_account+ # Own funds: MonobankAccount already subtracted the card's credit limit out of the+ # balance Monobank reports, so this can go straight onto the cash account.+ balance = monobank_account.current_balance || 0+ currency = parse_currency(monobank_account.currency) || account.currency || "UAH"++ account.update!(+ balance: balance,+ cash_balance: balance,+ currency: currency+ )+ end++ # Delegate to the transactions processor, capturing and logging failures.+ def process_transactions+ MonobankAccount::Transactions::Processor.new(monobank_account).process+ rescue => e+ report_exception(e, "transactions")+ Rails.logger.error "MonobankAccount::Processor - Failed to process transactions monobank_account_id=#{monobank_account.id} error_class=#{e.class.name}"+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "Failed to process transactions",+ source: self.class.name,+ provider_key: "monobank",+ family: monobank_account.monobank_item.family,+ account_provider: monobank_account.account_provider,+ metadata: { monobank_account_id: monobank_account.id, error_class: e.class.name, error_message: e.message }+ )+ { success: false, failed: 1, errors: [ { error: I18n.t("monobank_item.errors.account_processing_failed") } ] }+ end++ # Report a processing error to Sentry with a sanitized message and tags.+ def report_exception(error, context)+ safe_error = SanitizedProcessingError.new("Monobank account processing failed")++ Sentry.capture_exception(safe_error) do |scope|+ scope.set_tags(+ monobank_account_id: monobank_account.id,+ context: context,+ error_class: error.class.name+ )+ scope.set_context(+ "monobank_account_processor",+ {+ monobank_account_id: monobank_account.id,+ context: context,+ error_class: error.class.name+ }+ )+ end+ end++ # CurrencyNormalizable hook: warn when a Monobank currency code is unrecognized.+ def log_invalid_currency(currency_value)+ Rails.logger.warn("Invalid currency code '#{currency_value}' for Monobank account #{monobank_account.id}, falling back to account currency")+ end+enddiff --git a/app/models/monobank_account/transactions/category_matcher.rb b/app/models/monobank_account/transactions/category_matcher.rbnew file mode 100644index 0000000000..4e6925597e--- /dev/null+++ b/app/models/monobank_account/transactions/category_matcher.rb@@ -0,0 +1,85 @@+# Auto-matches a Monobank transaction's MCC to one of the family's existing Sure+# categories. Mirrors PlaidAccount::Transactions::CategoryMatcher and its Up equivalent:+# a fast, cheap, high-confidence pass that never creates categories and never overwrites+# user data (the import adapter applies the result via enrich_attribute, which respects+# locks). The MCC table lives in MonobankAccount::Transactions::CategoryTaxonomy.+#+# Unlike the Plaid and Up matchers, matching is locale-aware. Those providers hand over+# an English category slug and are matched against English aliases, which quietly+# matches nothing for a family whose categories are named in their own language.+# Monobank's users are Ukrainian by definition, so each MCC group also carries the Sure+# default-category translation key and the family's own locale is tried first.+class MonobankAccount::Transactions::CategoryMatcher+ include MonobankAccount::Transactions::CategoryTaxonomy++ # @param user_categories [Array<Category>] the family's existing categories+ # @param locale [String, Symbol, nil] the family's locale, used to compare against+ # default category names as the family sees them+ def initialize(user_categories = [], locale: nil)+ @user_categories = user_categories+ @locale = locale+ end++ # mcc is the transaction's Merchant Category Code (Monobank's `mcc` field). Returns a+ # matching Category, or nil when the code is unmapped or has no equivalent among the+ # user's categories.+ def match(mcc)+ group = mcc_group(mcc)+ return nil unless group++ match_candidates(default_category_names(group[:key])) || match_candidates(group[:aliases])+ end++ private+ attr_reader :user_categories, :locale++ # Sure's own name for the default category behind this MCC group, in the family's+ # locale and in the default locale. A family that kept Sure's generated categories+ # matches here regardless of the language they set up in.+ def default_category_names(key)+ return [] if key.blank?++ [ locale, I18n.default_locale ].compact.map(&:to_s).uniq.filter_map do |candidate_locale|+ I18n.t("models.category.defaults.#{key}", locale: candidate_locale, default: nil)+ end+ end++ def match_candidates(candidates)+ return nil if candidates.blank?++ hit = normalized_user_categories.find do |category|+ name = category[:name]+ candidates.any? { |candidate| names_match?(name, normalize_category_name(candidate)) }+ end++ hit && user_categories.find { |c| c.id == hit[:id] }+ end++ def names_match?(name, candidate)+ return false if name.blank? || candidate.blank?+ return true if name == candidate+ return true if name.singularize == candidate || name.pluralize == candidate+ return true if candidate.singularize == name || candidate.pluralize == name++ # Strip the standalone "and" conjunction (word-boundaried so it does not eat "and"+ # inside a word, e.g. errand), plus "&" and whitespace, so "Gifts & Donations"+ # matches the alias "gifts and donations".+ squash(name) == squash(candidate)+ end++ def squash(value)+ value.gsub(/(\band\b|&|\s+)/, "").strip+ end++ def normalized_user_categories+ @normalized_user_categories ||= user_categories.map do |user_category|+ { id: user_category.id, name: normalize_category_name(user_category.name) }+ end+ end++ # Case- and punctuation-insensitive form. [[:alnum:]] is Unicode-aware in Ruby, so+ # Cyrillic category names survive normalization instead of being blanked out.+ def normalize_category_name(name)+ name.to_s.downcase.gsub(/[^[:alnum:]]+/, " ").strip+ end+enddiff --git a/app/models/monobank_account/transactions/category_taxonomy.rb b/app/models/monobank_account/transactions/category_taxonomy.rbnew file mode 100644index 0000000000..7addc1e6c1--- /dev/null+++ b/app/models/monobank_account/transactions/category_taxonomy.rb@@ -0,0 +1,163 @@+# Maps Merchant Category Codes (ISO 18245) onto the family's existing Sure categories.+#+# Monobank does not categorise transactions; it reports the merchant's MCC (`mcc`, plus+# `originalMcc` when the acquirer rewrote it). That is a far coarser signal than a+# provider-assigned category, so the table below is deliberately conservative: only+# codes whose meaning maps cleanly onto one of Sure's default categories are listed.+#+# Codes with no honest Sure equivalent are intentionally absent, and that includes ones+# it would be tempting to guess at:+#+# * 6011 / 6012 / 4829 / 6051 — cash withdrawals, transfers and quasi-cash. These are+# money movement, not spending; Sure's transfer matcher pairs them up instead.+# * 5921 / 5993 / 7995 — alcohol, tobacco and gambling, which most people track under+# their own categories if at all.+# * 8211 / 8220 — education, which has no Sure default category.+#+# A wrong auto-category is worse than none: the import adapter applies matches via+# enrich_attribute, so anything left unmapped simply stays uncategorised for the user's+# own rules (or the AI categoriser) to handle.+module MonobankAccount::Transactions::CategoryTaxonomy+ # Each group carries two ways of finding the user's category:+ #+ # * `key` is the Sure default-category translation key+ # (Category::DEFAULT_CATEGORY_TRANSLATION_KEYS), so the matcher can compare against+ # the category name as the family actually sees it in their own locale — the common+ # case for a Monobank user, whose categories are unlikely to be named in English.+ # * `aliases` are English fallbacks, matched case/punctuation-insensitively, which+ # also cover categories the user renamed or created by hand.+ MCC_GROUPS = [+ {+ key: :groceries,+ aliases: [ "groceries" ],+ # Supermarkets, plus the specialised food retailers (butcher, bakery, dairy).+ mccs: [ 5411, 5422, 5441, 5451, 5462, 5499 ]+ },+ {+ key: :food_and_drink,+ aliases: [ "food and drink", "dining", "restaurants" ],+ # Caterers, restaurants, drinking places and fast food.+ mccs: [ 5811, 5812, 5813, 5814 ]+ },+ {+ key: :transportation,+ aliases: [ "transportation", "transport" ],+ # Local transit, taxis, rail and bus, fuel, parking, repairs and parts.+ mccs: [ 4111, 4112, 4121, 4131, 4789, 5533, 5541, 5542, 7523, 7531, 7534, 7538, 7549 ]+ },+ {+ key: :travel,+ aliases: [ "travel" ],+ # Airlines (3000-3299 are individual carriers), lodging (3500-3999 are individual+ # hotel chains), cruise lines, travel agencies and vehicle rental.+ mccs: [ 4411, 4457, 4511, 4722, 7011, 7512, 7513, 7519 ],+ mcc_ranges: [ 3000..3299, 3500..3999 ]+ },+ {+ key: :entertainment,+ aliases: [ "entertainment" ],+ # Cinemas, theatres, attractions, amusement parks and recreation services.+ mccs: [ 7832, 7911, 7922, 7929, 7991, 7993, 7994, 7996, 7998, 7999 ]+ },+ {+ key: :healthcare,+ aliases: [ "healthcare", "health" ],+ # Pharmacies, doctors, dentists, hospitals, labs and other medical services.+ mccs: [ 5912, 5975, 5976, 8011, 8021, 8031, 8041, 8042, 8043, 8049, 8050, 8062, 8071, 8099 ]+ },+ {+ key: :personal_care,+ aliases: [ "personal care" ],+ # Barbers and salons, massage, spas and cosmetics retail.+ mccs: [ 5977, 7230, 7297, 7298 ]+ },+ {+ key: :sports_and_fitness,+ aliases: [ "sports and fitness", "fitness" ],+ # Sporting goods, sports clubs and fields, membership (gym) clubs.+ mccs: [ 5941, 7941, 7997 ]+ },+ {+ key: :shopping,+ aliases: [ "shopping" ],+ # General merchandise, clothing and footwear, electronics, furniture, hobby and+ # stationery retail.+ mccs: [+ 5300, 5310, 5311, 5399, 5611, 5621, 5631, 5641, 5651, 5655, 5661, 5691, 5699,+ 5712, 5713, 5714, 5719, 5722, 5732, 5733, 5734, 5735, 5931, 5942, 5943, 5945,+ 5946, 5948, 5949, 5950, 5970, 5999+ ]+ },+ {+ key: :home_improvement,+ aliases: [ "home improvement" ],+ # Building materials, hardware, garden centres and the building trades.+ mccs: [ 1520, 1711, 1731, 1740, 1750, 1761, 1771, 5200, 5211, 5231, 5251, 5261 ]+ },+ {+ key: :utilities,+ aliases: [ "utilities" ],+ # Utilities, and telecom services (a mobile bill is the common case here).+ mccs: [ 4812, 4813, 4814, 4900 ]+ },+ {+ key: :subscriptions,+ aliases: [ "subscriptions" ],+ # Digital media (books, films, music) sold as downloads or subscriptions.+ mccs: [ 5815 ]+ },+ {+ key: :insurance,+ aliases: [ "insurance" ],+ mccs: [ 5960, 6300 ]+ },+ {+ key: :mortgage_rent,+ aliases: [ "mortgage rent", "rent", "mortgage" ],+ # Real estate agents and property managers, i.e. rent payments.+ mccs: [ 6513 ]+ },+ {+ key: :gifts_and_donations,+ aliases: [ "gifts and donations", "donations", "charity" ],+ mccs: [ 8398 ]+ },+ {+ key: :taxes,+ aliases: [ "taxes", "tax" ],+ mccs: [ 9311 ]+ },+ {+ key: :services,+ aliases: [ "services" ],+ # Couriers and post, laundry and dry cleaning, photography, repairs, funeral,+ # legal, accounting, consulting and other professional services.+ mccs: [+ 4215, 7210, 7216, 7217, 7221, 7251, 7261, 7276, 7277, 7299, 7311, 7392, 7393,+ 7399, 8111, 8931, 9402+ ]+ }+ ].freeze++ # { 5411 => group } lookup built from MCC_GROUPS. Ranges are expanded once at first+ # use; the whole table is only a few thousand small integer keys.+ def self.group_by_mcc+ @group_by_mcc ||= MCC_GROUPS.each_with_object({}) do |group, map|+ codes = Array(group[:mccs]) + Array(group[:mcc_ranges]).flat_map(&:to_a)++ codes.each { |mcc| map[mcc] ||= group }+ end.freeze+ end++ # The taxonomy group for an MCC, or nil when the code has no confident mapping.+ #+ # @param mcc [Integer, String, nil] Merchant Category Code from a Monobank statement+ def mcc_group(mcc)+ return nil if mcc.blank?++ code = Integer(mcc.to_s, exception: false)+ return nil if code.nil?++ MonobankAccount::Transactions::CategoryTaxonomy.group_by_mcc[code]+ end+enddiff --git a/app/models/monobank_account/transactions/processor.rb b/app/models/monobank_account/transactions/processor.rbnew file mode 100644index 0000000000..b3b6512f9c--- /dev/null+++ b/app/models/monobank_account/transactions/processor.rb@@ -0,0 +1,179 @@+class MonobankAccount::Transactions::Processor+ attr_reader :monobank_account++ # Build a transactions processor for the given +monobank_account+.+ def initialize(monobank_account)+ @monobank_account = monobank_account+ end++ # Process each stored raw transaction into a Sure entry, prune stale pending+ # entries, and return a stats hash (total/imported/failed/pruned/errors).+ def process+ unless monobank_account.raw_transactions_payload.present?+ Rails.logger.info "MonobankAccount::Transactions::Processor - No Monobank transactions available to process"+ prune_stats = prune_stale_pending_entries([])+ return {+ success: true, total: 0, imported: 0, failed: 0,+ pruned_pending: prune_stats[:pruned], protected_pending: prune_stats[:protected], errors: []+ }+ end++ total_count = monobank_account.raw_transactions_payload.count+ imported_count = 0+ failed_count = 0+ errors = []+ current_pending_external_ids = pending_external_ids++ monobank_account.raw_transactions_payload.each_with_index do |transaction_data, index|+ result = MonobankEntry::Processor.new(+ transaction_data,+ monobank_account: monobank_account,+ category_matcher: category_matcher+ ).process++ if result.nil?+ failed_count += 1+ errors << { index: index, transaction_id: transaction_id(transaction_data), error: "No linked account" }+ else+ imported_count += 1+ end+ rescue ArgumentError => e+ failed_count += 1+ errors << { index: index, transaction_id: transaction_id(transaction_data), error: "Validation error: #{e.message}" }+ Rails.logger.error "MonobankAccount::Transactions::Processor - Validation error processing transaction #{transaction_id(transaction_data)}: #{e.message}"+ rescue => e+ failed_count += 1+ errors << { index: index, transaction_id: transaction_id(transaction_data), error: "#{e.class}: #{e.message}" }+ Rails.logger.error "MonobankAccount::Transactions::Processor - Error processing transaction #{transaction_id(transaction_data)}: #{e.class} - #{e.message}"+ Rails.logger.error e.backtrace.join("\n")+ end+ prune_stats = prune_stale_pending_entries(current_pending_external_ids)++ {+ success: failed_count.zero?,+ total: total_count,+ imported: imported_count,+ failed: failed_count,+ pruned_pending: prune_stats[:pruned],+ protected_pending: prune_stats[:protected],+ errors: errors+ }+ end++ private++ # A single category matcher reused across this account's transactions, built from+ # the family's existing categories.+ def category_matcher+ @category_matcher ||= MonobankAccount::Transactions::CategoryMatcher.new(+ family_categories,+ locale: family&.locale+ )+ end++ # The family's existing categories. Importing transactions is intentionally+ # non-destructive with respect to the family's category structure: we do NOT+ # bootstrap Sure's defaults here. A family that has no categories (deliberately+ # cleared, or pre-onboarding) simply gets uncategorised transactions, and matching+ # resumes once the user sets monobank categories through the normal UI flow. Returns []+ # when the account isn't linked (each entry is skipped before the matcher is used).+ def family_categories+ @family_categories ||= family&.categories&.to_a || []+ end++ # The family behind the linked account, or nil when the account isn't linked (each+ # entry is skipped before the matcher is used).+ def family+ return @family if defined?(@family)++ @family = monobank_account.current_account&.family+ end++ # Extract the Monobank transaction id from raw data, or "unknown".+ def transaction_id(transaction_data)+ transaction_data.try(:[], :id) || transaction_data.try(:[], "id") || "unknown"+ end++ # Canonical external ids of the currently-HELD (pending) transactions.+ def pending_external_ids+ monobank_account.raw_transactions_payload.filter_map do |transaction_data|+ next unless transaction_data.is_a?(Hash)+ next unless MonobankEntry::Processor.pending?(transaction_data)++ MonobankEntry::Processor.canonical_external_id(transaction_data)+ end+ end++ # Retire previously-imported pending entries no longer present in the latest fetch+ # (cancelled or settled holds), returning how many were destroyed and how many were+ # kept because the user had taken them over.+ #+ # An entry the user has touched is never destroyed: the same three flags+ # Account::ProviderImportAdapter refuses to overwrite (excluded, user-modified,+ # import-locked) protect it here too, because destroying one would take its splits+ # (has_many :child_entries, dependent: :destroy) and any transfer it belongs to+ # (transfers.on_delete: :cascade) with it. Those entries just lose the pending flag,+ # which is what the hold disappearing actually tells us.+ def prune_stale_pending_entries(current_pending_external_ids)+ account = monobank_account.current_account+ return { pruned: 0, protected: 0 } unless account.present?++ stale_pending_entries = account.entries+ .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'")+ .where(source: "monobank")+ .where("(transactions.extra -> 'monobank' ->> 'pending')::boolean = true")+ stale_pending_entries = stale_pending_entries.where.not(external_id: current_pending_external_ids) if current_pending_external_ids.any?++ pruned = 0+ protected_count = 0++ stale_pending_entries.includes(:entryable).find_each do |entry|+ if entry.protected_from_sync?+ clear_pending_flag(entry)+ protected_count += 1+ else+ entry.destroy!+ pruned += 1+ end+ end++ capture_protected_pending(account, protected_count) if protected_count.positive?++ { pruned: pruned, protected: protected_count }+ end++ # Drop only the pending flag, leaving the rest of the Monobank metadata and every+ # user edit in place, so the entry stops being treated as an unsettled hold.+ def clear_pending_flag(entry)+ transaction = entry.entryable+ return unless transaction.is_a?(Transaction)++ extra = (transaction.extra || {}).deep_dup+ monobank_extra = extra["monobank"]+ return unless monobank_extra.is_a?(Hash)++ monobank_extra.delete("pending")+ extra.delete("monobank") if monobank_extra.empty?+ transaction.update!(extra: extra)+ end++ # Surface kept-but-unflagged entries for support: the hold is gone upstream but the+ # entry stays, so a family asking why a pending transaction turned into a normal one+ # has an audit trail.+ def capture_protected_pending(account, count)+ DebugLogEntry.capture(+ category: "provider_sync",+ level: "info",+ message: "Monobank kept user-owned pending entries and cleared their pending flag",+ source: self.class.name,+ provider_key: "monobank",+ family: family,+ account_provider: monobank_account.account_provider,+ metadata: {+ monobank_account_id: monobank_account.id,+ account_id: account.id,+ protected_pending: count+ }+ )+ end+enddiff --git a/app/models/monobank_entry/processor.rb b/app/models/monobank_entry/processor.rbnew file mode 100644index 0000000000..5816e2cb5f--- /dev/null+++ b/app/models/monobank_entry/processor.rb@@ -0,0 +1,267 @@+require "digest/md5"++class MonobankEntry::Processor+ include CurrencyNormalizable, IsoNumericCurrency++ # Stable external id for a transaction: its Monobank id when present, else a content+ # hash so an id-less record still deduplicates across syncs.+ def self.canonical_external_id(monobank_transaction)+ data = monobank_transaction.with_indifferent_access+ id = data[:id].presence+ return "monobank_#{id}" if id.present?++ "monobank_pending_#{content_hash_for(data)}"+ end++ # Monobank flags an authorization that has not settled yet with hold: true.+ #+ # A hold and the settled record that replaces it do not necessarily share an id, so+ # pending entries are pruned when they drop out of the latest statement window rather+ # than being matched up by id (see MonobankAccount::Transactions::Processor).+ def self.pending?(monobank_transaction)+ data = monobank_transaction.with_indifferent_access++ ActiveModel::Type::Boolean.new.cast(data[:hold]) || false+ end++ # MD5 of account/time/amount/description, used to identify id-less records.+ def self.content_hash_for(data)+ attributes = [+ data[:account_id],+ data[:time],+ data[:amount],+ data[:description]+ ].compact.join("|")++ Digest::MD5.hexdigest(attributes)+ end++ # Build a processor for a single raw Monobank transaction tied to +monobank_account+.+ #+ # category_matcher (optional) maps the transaction's MCC onto one of the family's+ # existing Sure categories. It is injected by MonobankAccount::Transactions::Processor+ # so a single matcher (built once per account) is reused across the account's+ # transactions.+ def initialize(monobank_transaction, monobank_account:, category_matcher: nil)+ @monobank_transaction = monobank_transaction+ @monobank_account = monobank_account+ @category_matcher = category_matcher+ end++ # Import the transaction into the linked Sure account via the import adapter.+ # Returns nil when the account isn't linked; re-raises on validation/save errors.+ def process+ unless account.present?+ Rails.logger.warn "MonobankEntry::Processor - No linked account for monobank_account #{monobank_account.id}, skipping transaction #{external_id}"+ return nil+ end++ import_adapter.import_transaction(+ external_id: external_id,+ amount: amount,+ currency: currency,+ date: date,+ name: name,+ source: "monobank",+ category_id: matched_category_id,+ merchant: merchant,+ notes: notes,+ extra: extra_metadata+ )+ rescue ArgumentError => e+ Rails.logger.error "MonobankEntry::Processor - Validation error for transaction #{external_id}: #{e.message}"+ raise+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved => e+ Rails.logger.error "MonobankEntry::Processor - Failed to save transaction #{external_id}: #{e.message}"+ raise StandardError.new("Failed to import transaction: #{e.message}")+ rescue => e+ Rails.logger.error "MonobankEntry::Processor - Unexpected error processing transaction #{external_id}: #{e.class} - #{e.message}"+ Rails.logger.error e.backtrace.join("\n")+ raise StandardError.new("Unexpected error importing transaction: #{e.message}")+ end++ private++ attr_reader :monobank_transaction, :monobank_account++ # Memoized adapter that writes provider transactions into the Sure account.+ def import_adapter+ @import_adapter ||= Account::ProviderImportAdapter.new(account)+ end++ # The linked Sure account for this transaction, if any.+ def account+ @account ||= monobank_account.current_account+ end++ # The raw transaction as an indifferent-access hash.+ def data+ @data ||= monobank_transaction.with_indifferent_access+ end++ # Canonical external id for this transaction (see .canonical_external_id).+ def external_id+ @external_id ||= self.class.canonical_external_id(data)+ end++ # Display name: Monobank's description (merchant or counterparty), or a fallback.+ def name+ data[:description].presence || I18n.t("transactions.unknown_name")+ end++ # The id of the Sure category the transaction's MCC maps to, or nil when no matcher+ # was injected, the MCC is missing, or it has no confident equivalent among the+ # family's categories. The import adapter applies this via enrich_attribute, so it+ # never overwrites a category the user has set or locked.+ def matched_category_id+ return nil unless @category_matcher++ @category_matcher.match(data[:mcc])&.id+ end++ # The user's own note on the transaction, if any.+ def notes+ data[:comment].presence+ end++ # Find or create the merchant for this transaction's description, or nil.+ def merchant+ merchant_name = data[:description].to_s.strip.presence+ return nil unless merchant_name++ provider_merchant_id = "monobank_merchant_#{Digest::MD5.hexdigest(merchant_name.downcase)}"++ @merchant ||= import_adapter.find_or_create_merchant(+ provider_merchant_id: provider_merchant_id,+ name: merchant_name,+ source: "monobank"+ )+ rescue ActiveRecord::RecordInvalid => e+ Rails.logger.error "MonobankEntry::Processor - Failed to create merchant '#{merchant_name}': #{e.message}"+ nil+ end++ # Monobank reports `amount` in the account currency's minor units, using banking+ # convention: negative is money out, positive is money in. Sure stores expenses as+ # positive and income as negative, so the sign is flipped.+ def amount+ -(minor_units(data[:amount]) / account_minor_unit_divisor)+ end++ # Entries are recorded in the account currency, which is what `amount` is expressed+ # in. Monobank's `currencyCode` on a statement item is documented as the *account*+ # currency ("Код валюти рахунку"), so it is preferred here and the stored account+ # currency is the fallback.+ def currency+ parse_currency(alpha_currency_code(data[:currencyCode])) ||+ parse_currency(monobank_account.currency) ||+ account&.currency ||+ "UAH"+ end++ # Settlement/authorization timestamp as a Date, in the family's zone.+ def date+ value = data[:time]+ raise ArgumentError, "Invalid date format" if value.blank?++ case value+ when Integer, Float+ Time.at(value).in_time_zone(account&.family&.timezone).to_date+ when String+ parse_string_date(value)+ when Time, DateTime+ value.in_time_zone(account&.family&.timezone).to_date+ when Date+ value+ else+ Rails.logger.error("Monobank transaction has no usable date value")+ raise ArgumentError, "Invalid date format"+ end+ rescue ArgumentError, TypeError+ Rails.logger.error("Failed to parse Monobank transaction date")+ raise ArgumentError, "Unable to parse transaction date"+ end++ # Monobank sends Unix seconds; a string is tolerated in case a caller (a webhook+ # relay, a fixture) hands the epoch over as text.+ def parse_string_date(value)+ return Time.at(Integer(value)).in_time_zone(account&.family&.timezone).to_date if value.match?(/\A-?\d+\z/)++ Time.parse(value).in_time_zone(account&.family&.timezone).to_date+ end++ # Provider metadata persisted on Transaction#extra.+ #+ # `pending` is the flag Sure's pending scopes read (Transaction::PENDING_PROVIDERS).+ # `balance_after` is Monobank's running account balance at the time of the+ # transaction, which is useful when reconciling a drifted balance by hand.+ def extra_metadata+ {+ "monobank" => {+ "pending" => pending?,+ "mcc" => data[:mcc],+ "original_mcc" => data[:originalMcc],+ "cashback_amount" => major_amount(data[:cashbackAmount]),+ "commission_amount" => major_amount(data[:commissionRate]),+ "balance_after" => major_amount(data[:balance]),+ "operation_amount" => foreign_operation_amount,+ "counter_name" => data[:counterName],+ "counter_iban" => data[:counterIban],+ "counter_edrpou" => data[:counterEdrpou],+ "receipt_id" => data[:receiptId],+ "invoice_id" => data[:invoiceId]+ }.compact+ }+ end++ # Whether this transaction is still an unsettled hold on Monobank.+ def pending?+ self.class.pending?(data)+ end++ # Monobank's `operationAmount` is the amount in the currency the transaction was+ # actually made in, but the statement never reports *which* currency that was — only+ # the account currency is given. So an FX purchase can be detected (the two amounts+ # differ) without being described: the raw operation amount is recorded for+ # reference and Sure's fx_from/fx_amount convention is deliberately left unset+ # rather than filled in with a guessed currency.+ def foreign_operation_amount+ operation_amount = data[:operationAmount]+ return nil if operation_amount.blank?+ return nil if operation_amount.to_s == data[:amount].to_s++ operation_amount+ end++ # Minor units of the account currency per major unit (100 for UAH).+ def account_minor_unit_divisor+ @account_minor_unit_divisor ||= BigDecimal(minor_unit_divisor(monobank_account.currency).to_s)+ end++ # Parse an integer minor-unit value into a BigDecimal.+ def minor_units(value)+ return BigDecimal("0") if value.blank?++ BigDecimal(value.to_s)+ rescue ArgumentError+ Rails.logger.error "Failed to parse Monobank transaction amount"+ raise ArgumentError, "Invalid transaction amount"+ end++ # Convert a minor-unit value into a plain decimal string in major units, or nil when+ # absent. Stored as a string rather than a BigDecimal because BigDecimal serializes+ # into JSON in engineering notation ("0.1005e4"), which is unreadable in the+ # transaction's extra payload.+ def major_amount(value)+ return nil if value.blank?++ (minor_units(value) / account_minor_unit_divisor).to_s("F")+ rescue ArgumentError+ nil+ end++ # CurrencyNormalizable hook: warn when a Monobank currency code is unrecognized.+ def log_invalid_currency(currency_value)+ Rails.logger.warn("Invalid currency code '#{currency_value}' in Monobank transaction #{external_id}, falling back to account currency")+ end+enddiff --git a/app/models/monobank_item.rb b/app/models/monobank_item.rbnew file mode 100644index 0000000000..0cf3ac0e64--- /dev/null+++ b/app/models/monobank_item.rb@@ -0,0 +1,222 @@+class MonobankItem < ApplicationRecord+ include Syncable, Provided, Unlinking, Encryptable++ enum :status, { good: "good", requires_update: "requires_update" }, default: :good++ if encryption_ready?+ encrypts :access_token, deterministic: true+ encrypts :raw_payload+ encrypts :raw_institution_payload+ end++ belongs_to :family+ has_one_attached :logo, dependent: :purge_later+ has_many :monobank_accounts, dependent: :destroy+ has_many :accounts, through: :monobank_accounts++ validates :name, presence: true+ validates :access_token, presence: true, on: :create++ # Monobank is a single institution, so unlike an aggregator its metadata is known up+ # front instead of being discovered per connection. Applied on the model so both the+ # settings panel and Family#create_monobank_item! get it.+ before_validation :apply_institution_defaults, on: :create++ scope :active, -> { where(scheduled_for_deletion: false) }+ scope :syncable, -> { active }+ scope :ordered, -> { order(created_at: :desc) }+ scope :needs_update, -> { where(status: :requires_update) }++ # Mark the item for deletion and enqueue the background destroy job.+ def destroy_later+ update!(scheduled_for_deletion: true)+ DestroyJob.perform_later(self)+ end++ # Run the importer to fetch the latest accounts/transactions from Monobank.+ def import_latest_monobank_data+ provider = monobank_provider+ unless provider+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "Cannot import: Monobank provider is not configured",+ source: self.class.name,+ provider_key: "monobank",+ family: family,+ metadata: { monobank_item_id: id }+ )+ raise StandardError.new("Monobank provider is not configured")+ end++ MonobankItem::Importer.new(self, monobank_provider: provider).import+ rescue => e+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "Failed to import data",+ source: self.class.name,+ provider_key: "monobank",+ family: family,+ metadata: { monobank_item_id: id, error_class: e.class.name, error_message: e.message }+ )+ raise+ end++ # Process each linked, visible Monobank account, returning a per-account result array.+ def process_accounts+ return [] if monobank_accounts.empty?++ monobank_accounts.joins(:account).merge(Account.visible).map do |monobank_account|+ result = MonobankAccount::Processor.new(monobank_account).process+ if result.is_a?(Hash) && result.with_indifferent_access[:success] == false+ { monobank_account_id: monobank_account.id, success: false, error: I18n.t("monobank_item.errors.account_processing_failed") }+ else+ { monobank_account_id: monobank_account.id, success: true, result: result }+ end+ rescue => e+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "Failed to process account",+ source: self.class.name,+ provider_key: "monobank",+ family: family,+ account_provider: monobank_account.account_provider,+ metadata: { monobank_item_id: id, monobank_account_id: monobank_account.id, error_class: e.class.name, error_message: e.message }+ )+ { monobank_account_id: monobank_account.id, success: false, error: I18n.t("monobank_item.errors.account_processing_failed") }+ end+ end++ # Enqueue a balance sync for each visible linked account, returning per-account results.+ def schedule_account_syncs(parent_sync: nil, window_start_date: nil, window_end_date: nil)+ return [] if accounts.empty?++ accounts.visible.map do |account|+ account.sync_later(+ parent_sync: parent_sync,+ window_start_date: window_start_date,+ window_end_date: window_end_date+ )+ { account_id: account.id, success: true }+ rescue => e+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "Failed to schedule sync for account",+ source: self.class.name,+ provider_key: "monobank",+ family: family,+ account: account,+ metadata: { monobank_item_id: id, account_id: account.id, error_class: e.class.name, error_message: e.message }+ )+ { account_id: account.id, success: false, error: I18n.t("monobank_item.errors.account_sync_schedule_failed") }+ end+ end++ # Persist the latest client-info payload for this item.+ #+ # The client's personal name is dropped before storing: it is never used for syncing+ # or display, and raw_payload is only encrypted at rest when the deployment has+ # ActiveRecord encryption configured. The Monobank client id is kept as the+ # institution id so support can correlate a connection without holding a name.+ def upsert_monobank_snapshot!(client_info_snapshot)+ snapshot = client_info_snapshot.to_h.with_indifferent_access.except(:name)++ assign_attributes(+ institution_id: snapshot[:clientId].presence || institution_id,+ raw_payload: snapshot+ )+ save!+ end++ # True once at least one Monobank account has been linked to a Sure account.+ def has_completed_initial_setup?+ accounts.any?+ end++ # Human-readable summary of linked vs. unlinked account counts.+ def sync_status_summary+ total_accounts = total_accounts_count+ linked_count = linked_accounts_count+ unlinked_count = unlinked_accounts_count++ if total_accounts.zero?+ I18n.t("monobank_item.sync_status.no_accounts")+ elsif unlinked_count.zero?+ I18n.t("monobank_item.sync_status.all_synced", count: linked_count)+ else+ I18n.t("monobank_item.sync_status.partial", linked: linked_count, unlinked: unlinked_count)+ end+ end++ # Number of Monobank accounts linked to a Sure account.+ def linked_accounts_count+ account_counts[:linked]+ end++ # Number of unlinked Monobank accounts still awaiting setup.+ def unlinked_accounts_count+ account_counts[:unlinked]+ end++ # Total number of Monobank accounts under this item.+ def total_accounts_count+ account_counts[:total]+ end++ # Best available display name for the connected institution.+ def institution_display_name+ institution_name.presence || institution_domain.presence || name+ end++ # Distinct institution metadata across this item's accounts.+ def connected_institutions+ monobank_accounts.includes(:account)+ .where.not(institution_metadata: nil)+ .map(&:institution_metadata)+ .uniq { |inst| inst["name"] || inst["domain"] }+ end++ # Human-readable summary of connected institutions (none/one/count).+ def institution_summary+ institutions = connected_institutions+ case institutions.count+ when 0+ I18n.t("monobank_item.institution_summary.none")+ when 1+ institutions.first["name"].presence || I18n.t("monobank_item.institution_summary.one")+ else+ I18n.t("monobank_item.institution_summary.count", count: institutions.count)+ end+ end++ # True when an access token is present and the item can call the Monobank API.+ def credentials_configured?+ access_token.present?+ end++ private++ def apply_institution_defaults+ self.institution_name ||= MonobankAccount::INSTITUTION_NAME+ self.institution_domain ||= MonobankAccount::INSTITUTION_DOMAIN+ self.institution_url ||= "https://#{MonobankAccount::INSTITUTION_DOMAIN}"+ end++ # Single query for all three account counts, reused across sync_status_summary+ # and the settings partial to avoid 3+ separate COUNT queries per rendered item.+ def account_counts+ @account_counts ||= begin+ rows = monobank_accounts+ .left_joins(:account_provider)+ .pluck(Arel.sql("account_providers.id IS NOT NULL"), :ignored)++ linked = rows.count { |has_provider, _ignored| has_provider }+ unlinked = rows.count { |has_provider, ignored| !has_provider && !ignored }++ { linked: linked, unlinked: unlinked, total: rows.size }+ end+ end+enddiff --git a/app/models/monobank_item/importer.rb b/app/models/monobank_item/importer.rbnew file mode 100644index 0000000000..c98a06998a--- /dev/null+++ b/app/models/monobank_item/importer.rb@@ -0,0 +1,556 @@+# Imports Monobank cards, jars and statement history for a single MonobankItem.+#+# Monobank's personal API is heavily rate limited (one request per minute, per endpoint)+# and caps a statement request at 31 days, which drives the whole design here:+#+# * client-info is fetched once per sync and reused for every account snapshot.+# * Each linked account gets a *forward* statement window (new activity since the last+# sync, always re-covering the last few days so unsettled holds stay visible) and,+# when budget remains, one *backward* window that walks older history towards the+# configured start date across successive syncs.+# * The number of statement requests per sync is capped so a family with many accounts+# cannot turn one sync into an hour of throttled sleeping.+class MonobankItem::Importer+ attr_reader :monobank_item, :monobank_provider++ # Build an importer for the given +monobank_item+ using the supplied provider client.+ def initialize(monobank_item, monobank_provider:)+ @monobank_item = monobank_item+ @monobank_provider = monobank_provider+ @statement_requests_remaining = self.class.max_statement_requests_per_sync+ end++ # Maximum statement requests one sync may spend, across all of the item's accounts.+ def self.max_statement_requests_per_sync+ Rails.configuration.x.monobank.max_statement_requests_per_sync+ end++ # Run the full import (accounts then statements) and return a result hash of success+ # flag and per-entity counts. On a failed client-info fetch, returns a +failed_result++ # with the same shape and zeroed counts; on a throttled one, a +throttled_result+ that+ # defers the work to the next sync.+ def import+ Rails.logger.info "MonobankItem::Importer - Starting import for item #{monobank_item.id}"++ client_info = fetch_client_info+ unless client_info+ return throttled_result if @client_info_throttled+ return failed_result("Failed to fetch client info")+ end++ monobank_item.upsert_monobank_snapshot!(client_info)++ accounts_data = monobank_provider.get_accounts(client_info: client_info)+ account_stats = import_accounts(accounts_data)+ transaction_stats = import_transactions++ Rails.logger.info(+ "MonobankItem::Importer - Completed import for item #{monobank_item.id}: " \+ "#{account_stats[:updated]} accounts updated, #{account_stats[:created]} new accounts discovered, " \+ "#{transaction_stats[:imported]} transactions, #{transaction_stats[:skipped]} accounts skipped"+ )++ {+ success: account_stats[:failed].zero? && transaction_stats[:failed].zero?,+ accounts_updated: account_stats[:updated],+ accounts_created: account_stats[:created],+ accounts_failed: account_stats[:failed],+ transactions_imported: transaction_stats[:imported],+ transactions_failed: transaction_stats[:failed],+ accounts_skipped: transaction_stats[:skipped]+ }+ end++ private++ attr_reader :statement_requests_remaining++ # Fetch the client profile (with cards and jars), returning nil on any provider or+ # parse error, which is logged and captured for support. A throttle is flagged+ # separately so +import+ can defer the sync instead of failing it.+ def fetch_client_info+ client_info = monobank_provider.get_client_info++ if Rails.configuration.x.monobank.debug_raw && Rails.env.local?+ Rails.logger.debug "Monobank raw client-info response: #{client_info.to_json}"+ end++ client_info+ rescue Provider::Monobank::RateLimitError => e+ Rails.logger.warn "MonobankItem::Importer - Monobank rate limit hit while fetching client info"+ capture_sync_error("Rate limited while fetching client info", e, level: "warn")+ @client_info_throttled = true+ nil+ rescue Provider::Monobank::Error => e+ mark_requires_update! if e.failure_code.in?([ :unauthorized, :access_forbidden ])+ Rails.logger.error "MonobankItem::Importer - Monobank API error: #{e.failure_code}"+ capture_sync_error("Failed to fetch client info", e, error_type: e.failure_code)+ nil+ rescue JSON::ParserError => e+ Rails.logger.error "MonobankItem::Importer - Failed to parse Monobank API response: #{e.class}"+ capture_sync_error("Failed to parse Monobank client info response", e)+ nil+ rescue => e+ Rails.logger.error "MonobankItem::Importer - Unexpected error fetching client info: #{e.class}"+ Rails.logger.error e.backtrace.join("\n")+ capture_sync_error("Unexpected error fetching client info", e)+ nil+ end++ # Upsert snapshots for linked accounts and record newly discovered ones, returning a+ # stats hash of +updated+, +created+ and +failed+ counts.+ def import_accounts(accounts_data)+ stats = { updated: 0, created: 0, failed: 0 }+ accounts = Array(accounts_data)+ linked_account_ids = monobank_item.monobank_accounts.joins(:account_provider).pluck(:account_id).map(&:to_s)+ all_existing_ids = monobank_item.monobank_accounts.pluck(:account_id).map(&:to_s)++ accounts.each do |account_data|+ account = account_data.with_indifferent_access+ account_id = account[:id].presence+ next if account_id.blank?++ if linked_account_ids.include?(account_id.to_s)+ import_account(account)+ stats[:updated] += 1+ elsif !all_existing_ids.include?(account_id.to_s)+ monobank_account = monobank_item.monobank_accounts.build(account_id: account_id.to_s)+ monobank_account.upsert_monobank_snapshot!(account)+ stats[:created] += 1+ end+ rescue => e+ stats[:failed] += 1+ Rails.logger.error "MonobankItem::Importer - Failed to import account #{account_id}: #{e.class}"+ capture_sync_error(+ "Failed to import Monobank account",+ e,+ monobank_account: monobank_item.monobank_accounts.find_by(account_id: account_id.to_s),+ extra_metadata: { provider_account_id: account_id.to_s }+ )+ end++ stats+ end++ # Upsert the snapshot for a single already-linked Monobank account.+ def import_account(account_data)+ account = account_data.with_indifferent_access+ monobank_account = monobank_item.monobank_accounts.find_by(account_id: account[:id].to_s)+ return unless monobank_account++ monobank_account.upsert_monobank_snapshot!(account)+ end++ # Fetch and store statements for every visible linked account, returning a stats+ # hash of +imported+, +failed+ and +skipped+ counts. An account skipped because the+ # request budget ran out (or because Monobank throttled us) is not a failure: the+ # next sync picks it up.+ def import_transactions+ stats = { imported: 0, failed: 0, skipped: 0 }++ # Least-recently-covered accounts first, so a budget too small for every account+ # still rotates fairly instead of starving the same ones every sync.+ accounts = monobank_item.monobank_accounts+ .joins(:account).merge(Account.visible)+ .order(Arel.sql("statement_synced_through ASC NULLS FIRST"))++ accounts.each do |monobank_account|+ if statement_requests_remaining <= 0+ stats[:skipped] += 1+ Rails.logger.info(+ "MonobankItem::Importer - Statement request budget exhausted, deferring account " \+ "#{monobank_account.id} to the next sync"+ )+ next+ end++ result = fetch_and_store_transactions(monobank_account)+ if result[:success]+ stats[:imported] += result[:transactions_count]+ elsif result[:skipped]+ stats[:skipped] += 1+ else+ stats[:failed] += 1+ end+ rescue => e+ stats[:failed] += 1+ Rails.logger.error "MonobankItem::Importer - Failed to fetch/store statement for Monobank account #{monobank_account.id}: #{e.class}"+ # fetch_window captures its own provider errors; what lands here instead is a+ # persistence failure (an invalid snapshot, a cursor that will not save), which+ # otherwise showed up only as an incremented failure count.+ capture_sync_error(+ "Failed to fetch or store a Monobank statement",+ e,+ monobank_account: monobank_account+ )+ end++ stats+ end++ # Fetch the forward window (and, when budget allows, one backward history window)+ # for +monobank_account+ and persist the results.+ def fetch_and_store_transactions(monobank_account)+ fetched = []++ forward = fetch_forward_window(monobank_account)+ return forward if forward[:error] || forward[:skipped]++ fetched.concat(forward[:transactions])++ backward = fetch_history_window(monobank_account)+ fetched.concat(backward[:transactions]) if backward[:transactions]++ # Persist before propagating a backward failure: the forward window is already in+ # hand, and dropping it would leave the account further behind next sync for no+ # gain. The forward cursor is only advanced by what was actually covered.+ store_transactions(monobank_account, fresh_transactions: fetched, pending_covered_from: forward[:covered_from])+ monobank_account.save! if monobank_account.changed?++ return backward.merge(transactions_count: fetched.count) if backward[:error]++ { success: true, transactions_count: fetched.count }+ end++ # New activity since the last covered timestamp. The window always re-covers the+ # last few days (pending_lookback_days), and any older hold still on file, so a hold+ # that is still unsettled stays in the payload — pending entries are pruned when+ # they drop out of it.+ def fetch_forward_window(monobank_account)+ now = Time.current+ lookback_start = now - Rails.configuration.x.monobank.pending_lookback_days.days++ requested_from = if monobank_account.statement_synced_through.present?+ [ monobank_account.statement_synced_through, lookback_start, oldest_stored_hold_time(monobank_account) ].compact.min+ else+ initial_history_start(monobank_account)+ end+ from = [ requested_from, now - Provider::Monobank::MAX_STATEMENT_WINDOW ].max++ result = fetch_window(monobank_account, from: from, to: now, direction: :forward)+ return result unless result[:success]++ transactions = result[:transactions]+ previously_covered_through = monobank_account.statement_synced_through+ truncated = truncated?(transactions)++ # What the response actually accounts for. A response at the item cap is missing+ # the oldest part of the window, and Monobank returns a statement newest-first, so+ # only [oldest_received, now] arrived.+ covered_from = if truncated+ capture_truncated_window(monobank_account, from: from, to: now)+ oldest_transaction_time(transactions) || from+ else+ from+ end++ monobank_account.statement_synced_through = now+ monobank_account.history_synced_from = if truncated+ # Coverage is still contiguous with what was already stored as long as the+ # previous coverage reached the oldest record received; if it did not, the gap+ # below it has to be re-walked, which is what moving the history cursor up to+ # that record does.+ if previously_covered_through.present? && previously_covered_through >= covered_from+ monobank_account.history_synced_from+ else+ covered_from+ end+ elsif previously_covered_through.present? && from > previously_covered_through+ # The requested window was wider than Monobank's 31-day cap, so the interval+ # between the old cursor and +from+ was never asked for. Hand it to the backward+ # walk instead of letting both cursors report it as covered; store_transactions+ # dedupes by canonical id, so re-fetching what is already stored is harmless.+ from+ else+ [ monobank_account.history_synced_from, from ].compact.min+ end++ result.merge(covered_from: covered_from)+ end++ # One step of the backward history walk: fetch the 31 days below the oldest date+ # covered so far, until the configured start date is reached. Returns an empty+ # result when there is nothing left to backfill or no request budget for it.+ def fetch_history_window(monobank_account)+ return { transactions: [] } if statement_requests_remaining <= 0++ target_start = initial_history_start(monobank_account)+ covered_from = monobank_account.history_synced_from+ return { transactions: [] } if covered_from.blank? || covered_from <= target_start++ to = covered_from+ from = [ target_start, to - Provider::Monobank::MAX_STATEMENT_WINDOW ].max+ return { transactions: [] } if from >= to++ result = fetch_window(monobank_account, from: from, to: to, direction: :backward)+ # A throttled backward walk is a soft skip, not a failure: the forward window+ # still landed and the backfill simply resumes next sync, exactly as it does when+ # the request budget runs out. A hard failure (auth, parse, provider error) has to+ # reach the caller instead, or the sync reports success while silently never+ # having fetched the configured history.+ return { transactions: [] } if result[:skipped]+ return result unless result[:success]++ transactions = result[:transactions]+ monobank_account.history_synced_from = if truncated?(transactions)+ oldest_transaction_time(transactions) || from+ else+ from+ end++ result+ end++ # Perform a single statement request, spending one unit of the request budget.+ # Provider errors are classified: a throttle is a soft skip, an auth failure marks+ # the connection as needing attention, anything else is a hard failure.+ def fetch_window(monobank_account, from:, to:, direction:)+ @statement_requests_remaining -= 1++ Rails.logger.info(+ "MonobankItem::Importer - Fetching #{direction} statement for Monobank account " \+ "#{monobank_account.id} from #{from.iso8601} to #{to.iso8601}"+ )++ transactions = monobank_provider.get_statement(+ account_id: monobank_account.account_id,+ from: from,+ to: to+ )++ if Rails.configuration.x.monobank.debug_raw && Rails.env.local?+ Rails.logger.debug "Monobank raw statement response: #{transactions.to_json}"+ end++ { success: true, transactions: Array(transactions) }+ rescue Provider::Monobank::RateLimitError => e+ Rails.logger.warn "MonobankItem::Importer - Monobank rate limit hit for account #{monobank_account.id}"+ capture_sync_error("Rate limited while fetching statement", e, monobank_account: monobank_account, level: "warn")+ { success: false, skipped: true, transactions_count: 0 }+ rescue Provider::Monobank::Error => e+ mark_requires_update!(monobank_account: monobank_account) if e.failure_code.in?([ :unauthorized, :access_forbidden ])+ Rails.logger.error "MonobankItem::Importer - Monobank API error for account #{monobank_account.id}: #{e.failure_code}"+ capture_sync_error("Failed to fetch statement", e, monobank_account: monobank_account, error_type: e.failure_code)+ { success: false, error: I18n.t("monobank_item.errors.transactions_failed"), transactions_count: 0 }+ rescue JSON::ParserError => e+ Rails.logger.error "MonobankItem::Importer - Failed to parse statement response for account #{monobank_account.id}: #{e.class}"+ capture_sync_error("Failed to parse Monobank statement response", e, monobank_account: monobank_account)+ { success: false, error: "Failed to parse response", transactions_count: 0 }+ rescue => e+ Rails.logger.error "MonobankItem::Importer - Unexpected error fetching statement for account #{monobank_account.id}: #{e.class}"+ Rails.logger.error e.backtrace.join("\n")+ capture_sync_error("Unexpected error fetching statement", e, monobank_account: monobank_account)+ { success: false, error: I18n.t("monobank_item.errors.transactions_failed"), transactions_count: 0 }+ end++ # Monobank returns settled and held transactions from the same endpoint. Settled+ # history accumulates; a held transaction is dropped once the statement that covered+ # it stops reporting it, so a hold that settled (Monobank may issue the settled+ # record under a different id) or was cancelled leaves storage and the transactions+ # processor retires the pending entry it created. A hold below what the response+ # actually covered is kept: see #stale_pending?.+ # Note on growth: like the other providers here, settled history accumulates in the+ # account's raw_transactions_payload and is re-processed in full on every sync. That+ # is fine for the default 31-day window; a connection configured to reach back years+ # will make each sync progressively heavier.+ def store_transactions(monobank_account, fresh_transactions:, pending_covered_from: nil)+ fresh_transactions = fresh_transactions.reject { |tx| MonobankEntry::Processor.pending?(tx) } unless include_pending?++ existing = monobank_account.raw_transactions_payload.to_a+ retained = existing.reject { |tx| stale_pending?(tx, covered_from: pending_covered_from) }++ by_id = {}+ retained.each do |tx|+ key = transaction_key(tx)+ by_id[key] = tx if key.present?+ end+ fresh_transactions.each do |tx|+ next unless tx.is_a?(Hash)++ key = transaction_key(tx)+ by_id[key] = tx if key.present?+ end++ final_transactions = by_id.values++ if final_transactions != existing+ Rails.logger.info(+ "MonobankItem::Importer - Storing #{final_transactions.count} transactions " \+ "(#{existing.count} existing) for account #{monobank_account.account_id}"+ )+ monobank_account.upsert_monobank_transactions_snapshot!(final_transactions)+ else+ Rails.logger.info "MonobankItem::Importer - No transaction changes for account #{monobank_account.account_id}"+ end+ end++ # Dedup key for a stored transaction: the canonical external id, so an id-less+ # record still collapses onto its content hash instead of duplicating.+ def transaction_key(transaction)+ return nil unless transaction.is_a?(Hash)++ MonobankEntry::Processor.canonical_external_id(transaction)+ end++ # Whether held (pending) transactions are imported at all.+ def include_pending?+ Rails.configuration.x.monobank.include_pending+ end++ # A response that hit Monobank's per-response item cap is assumed to cover only part+ # of the requested window.+ def truncated?(transactions)+ transactions.size >= Provider::Monobank::MAX_STATEMENT_ITEMS+ end++ # Whether a stored hold the latest statement no longer reports has really gone away.+ # Only a hold the response actually accounted for can be stale (RedbarkItem::Importer+ # #merge_transactions pairs the same two checks): below that point Monobank was never+ # asked, and dropping the hold would delete a pre-authorization that is still+ # blocking funds — a hotel or car hire hold outlives the pending lookback easily.+ def stale_pending?(transaction, covered_from:)+ return false unless transaction.is_a?(Hash)+ return false unless MonobankEntry::Processor.pending?(transaction)+ return true if covered_from.blank?++ time = transaction_time(transaction)+ # Undated, or covered by the statement just fetched and absent from it: the hold+ # settled or was cancelled.+ return true if time.blank? || time >= covered_from++ # Older than one statement window, so Monobank cannot be asked about it again.+ # Keeping it would leave a pending entry that can never clear.+ time < Time.current - Provider::Monobank::MAX_STATEMENT_WINDOW+ end++ # Timestamp of the oldest hold still on file. A hold can stay unsettled for longer+ # than the lookback (hotels, car hire, fuel), so the forward window reaches back to+ # it and keeps asking Monobank whether it has settled or been cancelled.+ def oldest_stored_hold_time(monobank_account)+ return nil unless include_pending?++ holds = monobank_account.raw_transactions_payload.to_a.select do |transaction|+ transaction.is_a?(Hash) && MonobankEntry::Processor.pending?(transaction)+ end++ transaction_times(holds).min+ end++ # Timestamp of the oldest record in a response, used to work out how much of a+ # truncated window actually arrived.+ def oldest_transaction_time(transactions)+ transaction_times(transactions).min+ end++ def transaction_times(transactions)+ transactions.filter_map { |transaction| transaction_time(transaction) }+ end++ # When Monobank says a single record happened, or nil when it omitted the field.+ def transaction_time(transaction)+ return nil unless transaction.is_a?(Hash)++ value = transaction.with_indifferent_access[:time]+ return nil if value.blank?++ Time.at(value.to_i)+ end++ # The timestamp history should reach back to: an explicit per-account or+ # per-connection start date, else the configured default window. A timestamp rather+ # than a date, because the cursors record exactly what a window covered.+ def initial_history_start(monobank_account)+ start_date = monobank_account.sync_start_date.presence || monobank_item.sync_start_date.presence+ # in_time_zone, not to_time: to_time reads the date in the server process's own+ # zone, which would move the window whenever TZ differs between web and worker.+ return start_date.in_time_zone if start_date++ Rails.configuration.x.monobank.initial_history_days.days.ago+ end++ # Record a note (not an error) when a statement window came back full, since it+ # explains why history is arriving in stages.+ def capture_truncated_window(monobank_account, from:, to:)+ DebugLogEntry.capture(+ category: "provider_sync",+ level: "info",+ message: "Monobank statement window truncated at the response item cap",+ source: self.class.name,+ provider_key: "monobank",+ family: monobank_item.family,+ account_provider: monobank_account.account_provider,+ metadata: {+ monobank_item_id: monobank_item.id,+ monobank_account_id: monobank_account.id,+ window_from: from.iso8601,+ window_to: to.iso8601,+ item_cap: Provider::Monobank::MAX_STATEMENT_ITEMS+ }+ )+ end++ # Record a provider sync problem as a DebugLogEntry with structured metadata for+ # support, attaching family and account provider when available.+ def capture_sync_error(message, error, monobank_account: nil, error_type: nil, level: "error", extra_metadata: {})+ metadata = { monobank_item_id: monobank_item.id, error_class: error.class.name, error_message: error.message }+ metadata[:monobank_account_id] = monobank_account.id if monobank_account+ metadata[:error_type] = error_type if error_type+ metadata.merge!(extra_metadata)++ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: level,+ message: message,+ source: self.class.name,+ provider_key: "monobank",+ family: monobank_item.family,+ account_provider: monobank_account&.account_provider,+ metadata: metadata+ )+ end++ # Flag the item as requiring re-authorization, swallowing update errors. A failure+ # here means the connection keeps showing as healthy after its token was rejected,+ # so it is recorded where support can find it rather than only in the app log.+ def mark_requires_update!(monobank_account: nil)+ monobank_item.update!(status: :requires_update)+ rescue => e+ Rails.logger.error "MonobankItem::Importer - Failed to update item status: #{e.class}"+ capture_sync_error(+ "Failed to flag connection as requiring re-authorization",+ e,+ monobank_account: monobank_account+ )+ end++ # Build a skip result mirroring +import+'s shape. Monobank throttles client-info to+ # one request per minute and the timer is not shared across processes, so a manual+ # sync landing in the same minute as a scheduled one (or as a setup screen) collides+ # legitimately. Like a throttled statement that is a skip, not a broken connection:+ # nothing was fetched, the connection stays healthy, the next sync picks it up.+ def throttled_result+ {+ success: true,+ accounts_updated: 0,+ accounts_created: 0,+ accounts_failed: 0,+ transactions_imported: 0,+ transactions_failed: 0,+ accounts_skipped: monobank_item.monobank_accounts.joins(:account).merge(Account.visible).count+ }+ end++ # Build a failure result mirroring +import+'s shape with zeroed counts.+ def failed_result(error)+ {+ success: false,+ error: error,+ accounts_updated: 0,+ accounts_created: 0,+ accounts_failed: 0,+ transactions_imported: 0,+ transactions_failed: 0,+ accounts_skipped: 0+ }+ end+enddiff --git a/app/models/monobank_item/provided.rb b/app/models/monobank_item/provided.rbnew file mode 100644index 0000000000..6e0652204f--- /dev/null+++ b/app/models/monobank_item/provided.rb@@ -0,0 +1,15 @@+module MonobankItem::Provided+ extend ActiveSupport::Concern++ # Build a Monobank API client from this item's token, or nil if unconfigured.+ def monobank_provider+ return nil unless credentials_configured?++ Provider::Monobank.new(access_token)+ end++ # The syncer responsible for importing and processing this item's data.+ def syncer+ MonobankItem::Syncer.new(self)+ end+enddiff --git a/app/models/monobank_item/sync_complete_event.rb b/app/models/monobank_item/sync_complete_event.rbnew file mode 100644index 0000000000..660f33f1bd--- /dev/null+++ b/app/models/monobank_item/sync_complete_event.rb@@ -0,0 +1,22 @@+class MonobankItem::SyncCompleteEvent+ attr_reader :monobank_item++ # Build the event for the given +monobank_item+.+ def initialize(monobank_item)+ @monobank_item = monobank_item+ end++ # Broadcast sync-complete Turbo updates for the item, its accounts, and family.+ def broadcast+ monobank_item.accounts.each(&:broadcast_sync_complete)++ monobank_item.broadcast_replace_to(+ monobank_item.family,+ target: "monobank_item_#{monobank_item.id}",+ partial: "monobank_items/monobank_item",+ locals: { monobank_item: monobank_item }+ )++ monobank_item.family.broadcast_sync_complete+ end+enddiff --git a/app/models/monobank_item/syncer.rb b/app/models/monobank_item/syncer.rbnew file mode 100644index 0000000000..237118cc66--- /dev/null+++ b/app/models/monobank_item/syncer.rb@@ -0,0 +1,141 @@+class MonobankItem::Syncer+ include SyncStats::Collector++ SafeSyncError = Class.new(StandardError)++ # Error carrying the structured per-stage sync errors for health reporting.+ class SyncError < StandardError+ attr_reader :sync_errors++ # Build the error with a +message+ and the collected +sync_errors+.+ def initialize(message, sync_errors:)+ super(message)+ @sync_errors = sync_errors+ end+ end++ attr_reader :monobank_item++ # Build a syncer for the given +monobank_item+.+ def initialize(monobank_item)+ @monobank_item = monobank_item+ end++ # Run the full sync: import, account setup detection, transaction processing,+ # balance sync scheduling, and stats/health collection. Raises on failures.+ def perform_sync(sync)+ sync.update!(status_text: I18n.t("monobank_item.sync.status.importing")) if sync.respond_to?(:status_text)+ import_result = monobank_item.import_latest_monobank_data+ raise_if_failed_result!(import_result, stage: "Monobank import")++ sync.update!(status_text: I18n.t("monobank_item.sync.status.checking_setup")) if sync.respond_to?(:status_text)+ collect_setup_stats(sync, provider_accounts: monobank_item.monobank_accounts)++ linked_accounts = monobank_item.monobank_accounts.joins(:account_provider)+ unlinked_accounts = monobank_item.monobank_accounts.needs_setup++ if unlinked_accounts.any?+ monobank_item.update!(pending_account_setup: true)+ sync.update!(status_text: I18n.t("monobank_item.sync.status.needs_setup", count: unlinked_accounts.count)) if sync.respond_to?(:status_text)+ else+ monobank_item.update!(pending_account_setup: false)+ end++ if linked_accounts.any?+ sync.update!(status_text: I18n.t("monobank_item.sync.status.processing")) if sync.respond_to?(:status_text)+ mark_import_started(sync)+ process_results = monobank_item.process_accounts+ raise_if_failed_results!(process_results, stage: "Monobank account processing")++ sync.update!(status_text: I18n.t("monobank_item.sync.status.calculating")) if sync.respond_to?(:status_text)+ schedule_results = monobank_item.schedule_account_syncs(+ parent_sync: sync,+ window_start_date: sync.window_start_date,+ window_end_date: sync.window_end_date+ )+ raise_if_failed_results!(schedule_results, stage: "Monobank account sync scheduling")++ account_ids = linked_accounts.includes(:account_provider).filter_map { |ua| ua.current_account&.id }+ collect_transaction_stats(sync, account_ids: account_ids, source: "monobank")+ else+ Rails.logger.info "MonobankItem::Syncer - No linked accounts to process"+ end++ collect_health_stats(sync, errors: nil)+ rescue SyncError => e+ collect_health_stats(sync, errors: e.sync_errors)+ raise+ rescue => e+ safe_message = I18n.t("monobank_item.errors.sync_failed")+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "Unexpected sync error",+ source: self.class.name,+ provider_key: "monobank",+ family: monobank_item.family,+ metadata: { monobank_item_id: monobank_item.id, error_class: e.class.name, error_message: e.message }+ )+ collect_health_stats(sync, errors: [ { message: safe_message, category: "sync_error" } ])+ raise SafeSyncError.new(safe_message), cause: nil+ end++ # Post-sync hook (no work required for Monobank).+ def perform_post_sync+ # no-op+ end++ private++ # Raise a SyncError if a single result hash indicates failure.+ def raise_if_failed_result!(result, stage:)+ return unless failed_result?(result)++ errors = errors_from_result(result, stage: stage)+ raise SyncError.new(error_message(stage, errors), sync_errors: errors)+ end++ # Raise a SyncError if any result in the collection indicates failure.+ def raise_if_failed_results!(results, stage:)+ errors = Array(results).filter_map do |result|+ next unless failed_result?(result)++ errors_from_result(result, stage: stage).first+ end++ return if errors.empty?++ raise SyncError.new(error_message(stage, errors), sync_errors: errors)+ end++ # True when +result+ is a hash explicitly flagged success: false.+ def failed_result?(result)+ result.is_a?(Hash) && result.with_indifferent_access[:success] == false+ end++ # Normalize a failed result into an array of { message:, category: } errors.+ def errors_from_result(result, stage:)+ data = result.with_indifferent_access+ messages = []+ messages << data[:error] if data[:error].present?+ messages << "#{data[:accounts_failed]} accounts failed" if data[:accounts_failed].to_i.positive?+ messages << "#{data[:transactions_failed]} transactions failed" if data[:transactions_failed].to_i.positive?+ messages.concat(Array(data[:errors]).map { |error| error_message_value(error) }.compact)+ messages << "#{stage} failed" if messages.empty?++ messages.map { |message| { message: "#{stage}: #{message}", category: "sync_error" } }+ end++ # Join the error messages into a single stage summary string.+ def error_message(stage, errors)+ messages = errors.map { |error| error[:message] || error["message"] }.compact+ messages.presence&.join(", ") || "#{stage} failed"+ end++ # Extract a human-readable message from a heterogeneous error value.+ def error_message_value(error)+ return error[:message].presence || error["message"].presence || error[:error].presence || error["error"].presence if error.is_a?(Hash)++ error.to_s.presence+ end+enddiff --git a/app/models/monobank_item/unlinking.rb b/app/models/monobank_item/unlinking.rbnew file mode 100644index 0000000000..b48ddebf5e--- /dev/null+++ b/app/models/monobank_item/unlinking.rb@@ -0,0 +1,54 @@+module MonobankItem::Unlinking+ extend ActiveSupport::Concern++ # Unlink every Monobank account from its Sure account, detaching holdings and+ # destroying the AccountProvider links. With +dry_run+, only reports what+ # would be unlinked. Returns a per-account result array (with :error on failure).+ def unlink_all!(dry_run: false)+ results = []++ monobank_accounts.find_each do |provider_account|+ links = AccountProvider.joins(:account)+ .where(provider: provider_account, accounts: { family_id: family_id })+ .to_a+ link_ids = links.map(&:id)+ result = {+ provider_account_id: provider_account.id,+ name: provider_account.name,+ provider_link_ids: link_ids+ }+ results << result++ next if dry_run++ begin+ ActiveRecord::Base.transaction do+ links.each do |link|+ Holding.where(account_id: link.account_id, account_provider_id: link.id).update_all(account_provider_id: nil)+ link.destroy!+ end+ end+ rescue StandardError => e+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "warn",+ message: "Failed to fully unlink provider account",+ source: self.class.name,+ provider_key: "monobank",+ family: family,+ account_provider: links.first,+ metadata: {+ monobank_item_id: id,+ monobank_account_id: provider_account.id,+ link_ids: link_ids,+ error_class: e.class.name,+ error_message: e.message+ }+ )+ result[:error] = e.message+ end+ end++ results+ end+enddiff --git a/app/models/provider/metadata.rb b/app/models/provider/metadata.rbindex 9289a09c9e..9184c278b5 100644--- a/app/models/provider/metadata.rb+++ b/app/models/provider/metadata.rb@@ -5,6 +5,7 @@ class Providersimplefin: { region: "US", kinds: %w[Bank Investment], maturity: :stable, logo_text: "SF", logo_bg: "bg-blue-600" },lunchflow: { region: "Global", kinds: %w[Bank], maturity: :stable, logo_text: "LF", logo_bg: "bg-orange-500" },up: { region: "AU", kinds: %w[Bank], maturity: :beta, logo_text: "UP", logo_bg: "bg-orange-600" },+ monobank: { region: "UA", kinds: %w[Bank], maturity: :alpha, logo_text: "MB", logo_bg: "bg-primary" },enable_banking: { region: "EU", kinds: %w[Bank], maturity: :beta, logo_text: "EB", logo_bg: "bg-purple-600" },coinstats: { region: "Global", kinds: %w[Crypto], maturity: :beta, logo_text: "CS", logo_bg: "bg-pink-600" },wise: { region: "Global", kinds: %w[Bank], maturity: :beta, logo_text: "WI", logo_bg: "bg-green-500" },diff --git a/app/models/provider/monobank.rb b/app/models/provider/monobank.rbnew file mode 100644index 0000000000..00ee6026fb--- /dev/null+++ b/app/models/provider/monobank.rb@@ -0,0 +1,336 @@+# API client for Monobank's personal (client) API — https://api.monobank.ua/docs.+#+# The personal API is deliberately small: one call returns the client's cards and jars,+# another returns a statement window for a single account. Both are documented as+# "не частіше ніж 1 раз у 60 секунд", per function, which shapes every caller: requests+# are throttled per endpoint (see #throttle_request) and a statement window may not+# exceed 31 days + 1 hour.+#+# Note on scope: Monobank's terms limit this token to personal use, so credentials are+# per-family (the user brings their own token from https://api.monobank.ua/) rather than+# a site-wide integration.+class Provider::Monobank < Provider+ include HTTParty+ include Provider::RateLimitable+ extend SslConfigurable++ # Subclass so errors caught in this provider are raised as Provider::Monobank::Error+ Error = Class.new(Provider::Error)+ class RateLimitError < Error; end++ DEFAULT_BASE_URL = "https://api.monobank.ua".freeze+ ALLOWED_HOST = URI.parse(DEFAULT_BASE_URL).host.freeze++ PROVIDER_ENV_PREFIX = "MONOBANK".freeze+ # Documented throttle for the personal endpoints: one request per minute, per function.+ MIN_REQUEST_INTERVAL = 60.0++ # Documented cap on a single statement request: 31 days + 1 hour.+ MAX_STATEMENT_WINDOW = 2_682_000++ # Undocumented but well-established cap on how many transactions one statement+ # response carries. Callers treat a full page as "possibly truncated" and continue+ # from the newest/oldest transaction they actually received rather than assuming the+ # whole window was covered.+ MAX_STATEMENT_ITEMS = 500++ headers "User-Agent" => "Sure Finance Monobank Client (https://github.com/we-promise/sure)"+ default_options.merge!({ timeout: 120 }.merge(httparty_ssl_options))++ attr_reader :access_token++ # Build a client with the family's Monobank personal token. Raises if blank.+ def initialize(access_token)+ @access_token = access_token.to_s.strip++ if @access_token.blank?+ raise Error.new("Monobank access token is required", failure_code: :configuration_error)+ end+ end++ # GET /personal/client-info — the client's profile plus every card and jar.+ # Doubles as the token check: an invalid token fails here with :unauthorized.+ def get_client_info+ payload = get("/personal/client-info", bucket: :client_info)++ unless payload.is_a?(Hash)+ raise Error.new("Unexpected Monobank client-info response", failure_code: :parse_error)+ end++ payload.with_indifferent_access+ end++ # Flattened account list built from client-info. Cards and jars are returned in one+ # array, each tagged with `kind` ("card" or "jar") so callers do not have to know+ # which half of the payload an account came from. Monobank's own field names are+ # preserved; only `kind` is added.+ #+ # @param client_info [Hash, nil] a previously fetched client-info payload, so a caller+ # that already paid the rate-limited request can reuse it+ def get_accounts(client_info: nil)+ payload = (client_info || get_client_info).with_indifferent_access++ cards = Array(payload[:accounts]).filter_map { |account| flatten_account(account, kind: "card") }+ jars = Array(payload[:jars]).filter_map { |jar| flatten_account(jar, kind: "jar") }++ cards + jars+ end++ # GET /personal/statement/{account}/{from}/{to} — transactions for one account or jar.+ # Both settled and held (pending) transactions are returned; callers derive pending+ # status from the `hold` field.+ #+ # @param account_id [String] Monobank account/jar id, or "0" for the default account+ # @param from [Time, Date, Integer] window start+ # @param to [Time, Date, Integer, nil] window end (defaults to now)+ # @raise [Error] when the requested window exceeds Monobank's 31-day cap, or when the+ # response body is not the documented JSON array+ def get_statement(account_id:, from:, to: nil)+ from_unix = to_unix(from)+ to_unix_value = to.present? ? to_unix(to) : Time.current.to_i++ if to_unix_value < from_unix+ raise Error.new("Monobank statement window ends before it starts", failure_code: :bad_request)+ end++ if (to_unix_value - from_unix) > MAX_STATEMENT_WINDOW+ raise Error.new(+ "Monobank statement window exceeds the 31 day maximum",+ failure_code: :window_too_large+ )+ end++ path = "/personal/statement/#{ERB::Util.url_encode(account_id.to_s)}/#{from_unix}/#{to_unix_value}"+ transactions = get(path, bucket: :statement)++ # A statement is always a JSON array. Anything else (a 204, an empty body, an error+ # object) would otherwise read as "no activity in this window", and the caller would+ # record the window as permanently covered. Failing here leaves the cursors alone so+ # the window is walked again on the next sync.+ unless transactions.is_a?(Array)+ raise Error.new("Unexpected Monobank statement response", failure_code: :parse_error)+ end++ transactions.filter_map do |transaction|+ next unless transaction.is_a?(Hash)++ transaction.with_indifferent_access.merge(account_id: account_id.to_s)+ end+ end++ private++ RETRYABLE_ERRORS = [+ SocketError,+ Net::OpenTimeout,+ Net::ReadTimeout,+ Errno::ECONNRESET,+ Errno::ECONNREFUSED,+ Errno::ETIMEDOUT,+ EOFError+ ].freeze++ MAX_RETRIES = 3+ INITIAL_RETRY_DELAY = 2++ # Issues a throttled GET against the personal API. `bucket` names the rate-limit+ # bucket (see #throttle_request).+ def get(path, bucket:, query: nil)+ operation = "GET #{path}"++ with_retries(operation) do+ throttle_request(bucket)+ response = self.class.get(resolve_url(path), headers: auth_headers, query: query)+ handle_response(response, operation: operation)+ end+ end++ # Monobank documents its throttle per function, so client-info and statement each+ # get their own timer. Overrides Provider::RateLimitable's single-timer version+ # while still taking the interval (and its MONOBANK_MIN_REQUEST_INTERVAL override)+ # from the concern — a shared timer would add a needless minute to every sync.+ #+ # The timer lives on the instance: one client is built per sync, which is where+ # consecutive calls actually happen. Two syncs racing across processes can still+ # collide, and that surfaces as a :rate_limited error the importer treats as a+ # soft failure rather than a broken connection.+ def throttle_request(bucket = :default)+ @last_request_at ||= {}++ elapsed = Time.current - (@last_request_at[bucket] || Time.at(0))+ sleep_time = min_request_interval - elapsed+ sleep(sleep_time) if sleep_time > 0++ @last_request_at[bucket] = Time.current+ end++ # Normalizes a card or jar resource. Cards carry no display name of their own, so+ # naming is left to MonobankAccount (which localizes the card type); only the id,+ # `kind` tag and a jar's title are guaranteed here.+ def flatten_account(resource, kind:)+ return nil unless resource.is_a?(Hash)++ data = resource.with_indifferent_access+ return nil if data[:id].blank?++ data.merge(kind: kind)+ end++ # Resolves a relative path against the base URL, refusing to send the token+ # anywhere but Monobank's HTTPS host.+ def resolve_url(path)+ value = path.to_s+ return "#{DEFAULT_BASE_URL}#{value.start_with?('/') ? value : "/#{value}"}" unless value.start_with?("http")++ uri = URI.parse(value)+ unless uri.scheme == "https" && uri.host == ALLOWED_HOST+ raise Error.new("Refusing to send credentials to untrusted host: #{uri.host.inspect}", failure_code: :invalid_url)+ end++ value+ rescue URI::InvalidURIError+ raise Error.new("Invalid Monobank API URL", failure_code: :invalid_url)+ end++ # Monobank authenticates with a personal token in X-Token (not a bearer header).+ def auth_headers+ {+ "X-Token" => access_token,+ "Accept" => "application/json"+ }+ end++ # Converts a Time/Date/epoch into Unix seconds. A bare Date is read as UTC midnight+ # rather than in the server's zone, which would shift the window by the offset.+ def to_unix(value)+ # instance_of?, not is_a?: DateTime is a subclass of Date but only Date needs the+ # UTC-midnight reading, and DateTime#to_time takes no form argument.+ return value.to_time(:utc).to_i if value.instance_of?(Date)++ case value+ when Integer then value+ when Float then value.to_i+ when Time, DateTime then value.to_time.to_i+ when String then Time.parse(value).to_i+ else+ raise Error.new("Unsupported Monobank statement timestamp", failure_code: :bad_request)+ end+ rescue ArgumentError, TypeError+ raise Error.new("Unsupported Monobank statement timestamp", failure_code: :bad_request)+ end++ # Runs the block, retrying transient network errors with exponential backoff.+ def with_retries(operation_name, max_retries: MAX_RETRIES)+ retries = 0++ begin+ yield+ rescue *RETRYABLE_ERRORS => e+ retries += 1+ if retries <= max_retries+ delay = calculate_retry_delay(retries)+ capture_request_error(+ category: "provider_sync",+ level: "warn",+ message: "Monobank API request will be retried",+ operation: operation_name,+ metadata: {+ error_class: e.class.name,+ retry_attempt: retries,+ retry_limit: max_retries,+ retry_delay: delay.round(2)+ }+ )+ # Kept alongside the debug entry, as Provider::Lunchflow does: a retry that+ # then succeeds is local noise an operator will not go looking for, but it is+ # what you want in the terminal during `bin/dev`.+ Rails.logger.warn(+ "Monobank API: #{operation_name} failed (attempt #{retries}/#{max_retries}): " \+ "#{e.class}. Retrying in #{delay.round(2)}s..."+ )+ sleep(delay)+ retry+ end++ capture_request_error(+ level: "error",+ message: "Monobank API request failed after retries",+ operation: operation_name,+ metadata: { error_class: e.class.name, retry_limit: max_retries }+ )+ raise Error.new("Network error after #{max_retries} retries: #{e.message}", failure_code: :network_error)+ end+ end++ # Exponential backoff delay (with jitter), capped at 30 seconds.+ def calculate_retry_delay(retry_count)+ base_delay = INITIAL_RETRY_DELAY * (2 ** (retry_count - 1))+ jitter = base_delay * rand * 0.25+ [ base_delay + jitter, 30 ].min+ end++ # Maps an HTTP response to parsed data or a typed error by status code.+ def handle_response(response, operation: nil)+ case response.code+ when 200, 201+ parse_response_body(response, operation: operation)+ when 204+ {}+ when 400+ raise Error.new("Bad request to Monobank API (status=#{response.code})", failure_code: :bad_request)+ when 401+ raise Error.new("Invalid Monobank access token", failure_code: :unauthorized)+ when 403+ raise Error.new("Monobank access forbidden - check token permissions", failure_code: :access_forbidden)+ when 404+ raise Error.new("Monobank resource not found", failure_code: :not_found)+ when 429+ raise RateLimitError.new(+ "Monobank rate limit exceeded (one request per minute per endpoint)",+ failure_code: :rate_limited+ )+ when 500..599+ raise Error.new("Monobank server error (#{response.code}). Please try again later.", failure_code: :server_error)+ else+ capture_request_error(+ level: "error",+ message: "Monobank API returned an unexpected response status",+ operation: operation,+ metadata: { status: response.code }+ )+ raise Error.new("Failed to fetch Monobank data", failure_code: :fetch_failed)+ end+ end++ # Parses a JSON response body, raising a typed error on malformed JSON.+ def parse_response_body(response, operation: nil)+ return {} if response.body.blank?++ JSON.parse(response.body)+ rescue JSON::ParserError+ capture_request_error(+ level: "error",+ message: "Monobank API response could not be parsed",+ operation: operation,+ metadata: { status: response.code, body_bytes: response.body.bytesize }+ )+ raise Error.new("Failed to parse Monobank API response", failure_code: :parse_error)+ end++ # Transport-level diagnostics for /settings/debug. The client is built from a token+ # alone, so it has no family or account_provider to attach — MonobankItem::Importer+ # catches the typed error these paths raise and records the same failure against the+ # connection. What only exists here is the transport detail (status, retry attempt),+ # which never reaches that layer, so it is captured here rather than left in the+ # application log. The body is never included: it carries statement PII.+ def capture_request_error(level:, message:, operation:, category: "provider_sync_error", metadata: {})+ DebugLogEntry.capture(+ category: category,+ level: level,+ message: message,+ source: self.class.name,+ provider_key: "monobank",+ metadata: metadata.merge(operation: operation).compact+ )+ end+enddiff --git a/app/models/provider/monobank_adapter.rb b/app/models/provider/monobank_adapter.rbnew file mode 100644index 0000000000..ac71850582--- /dev/null+++ b/app/models/provider/monobank_adapter.rb@@ -0,0 +1,113 @@+class Provider::MonobankAdapter < Provider::Base+ include Provider::Syncable+ include Provider::InstitutionMetadata++ Provider::Factory.register("MonobankAccount", self)++ # Sure accountable types that can be created from Monobank accounts. Everything the+ # personal API exposes — cards and jars alike — is a cash account (see+ # MonobankAccount::MONOBANK_ACCOUNT_TYPE_MAP).+ def self.supported_account_types+ %w[Depository]+ end++ # Connection config hashes for each of the family's configured Monobank items.+ def self.connection_configs(family:)+ return [] unless family.can_connect_monobank?++ family.monobank_items.active.ordered.select(&:credentials_configured?).map do |monobank_item|+ connection_config_for(monobank_item)+ end+ end++ # Build a Monobank API client for the resolved item, or nil if none is usable.+ def self.build_provider(family: nil, monobank_item_id: nil)+ return nil unless family.present?++ monobank_item = resolve_monobank_item(family, monobank_item_id)+ return nil unless monobank_item&.credentials_configured?++ Provider::Monobank.new(monobank_item.access_token)+ end++ # Build the settings connection-config hash for a single Monobank item.+ def self.connection_config_for(monobank_item)+ path_params = ->(extra = {}) { extra.merge(monobank_item_id: monobank_item.id) }++ {+ key: "monobank_#{monobank_item.id}",+ name: monobank_item.name.presence || I18n.t("providers.monobank.name"),+ description: I18n.t("providers.monobank.description"),+ can_connect: true,+ new_account_path: ->(accountable_type, return_to) {+ Rails.application.routes.url_helpers.select_accounts_monobank_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_monobank_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+ "monobank"+ end++ # Route to trigger a manual sync for this provider account's item.+ def sync_path+ Rails.application.routes.url_helpers.sync_monobank_item_path(item)+ end++ # The MonobankItem backing this provider account.+ def item+ provider_account.monobank_item+ end++ # Monobank 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 Monobank item: the requested one, else the first configured.+ def self.resolve_monobank_item(family, monobank_item_id)+ if monobank_item_id.present?+ item = family.monobank_items.active.find_by(id: monobank_item_id)+ return item if item&.credentials_configured?++ return nil+ end++ family.monobank_items.active.ordered.find(&:credentials_configured?)+ end+ private_class_method :resolve_monobank_item+enddiff --git a/app/models/provider_connection_status.rb b/app/models/provider_connection_status.rbindex a90946b86f..d3ee614b08 100644--- a/app/models/provider_connection_status.rb+++ b/app/models/provider_connection_status.rb@@ -4,6 +4,7 @@ class ProviderConnectionStatusPROVIDERS = [{ key: "akahu", type: "AkahuItem", association: :akahu_items, accounts: :akahu_accounts },{ key: "up", type: "UpItem", association: :up_items, accounts: :up_accounts },+ { key: "monobank", type: "MonobankItem", association: :monobank_items, accounts: :monobank_accounts },{ key: "plaid", type: "PlaidItem", association: :plaid_items, accounts: :plaid_accounts },{ key: "simplefin", type: "SimplefinItem", association: :simplefin_items, accounts: :simplefin_accounts },{ key: "lunchflow", type: "LunchflowItem", association: :lunchflow_items, accounts: :lunchflow_accounts },diff --git a/app/models/provider_merchant.rb b/app/models/provider_merchant.rbindex be22bd7786..8e24566129 100644--- a/app/models/provider_merchant.rb+++ b/app/models/provider_merchant.rb@@ -1,5 +1,5 @@class ProviderMerchant < Merchant- enum :source, { plaid: "plaid", simplefin: "simplefin", lunchflow: "lunchflow", akahu: "akahu", up: "up", synth: "synth", ai: "ai", enable_banking: "enable_banking", coinstats: "coinstats", mercury: "mercury", brex: "brex", indexa_capital: "indexa_capital", sophtron: "sophtron", questrade: "questrade", redbark: "redbark" }+ enum :source, { plaid: "plaid", simplefin: "simplefin", lunchflow: "lunchflow", akahu: "akahu", up: "up", monobank: "monobank", synth: "synth", ai: "ai", enable_banking: "enable_banking", coinstats: "coinstats", mercury: "mercury", brex: "brex", indexa_capital: "indexa_capital", sophtron: "sophtron", questrade: "questrade", redbark: "redbark" }validates :name, uniqueness: { scope: [ :source ] }validates :source, presence: truediff --git a/app/models/transaction.rb b/app/models/transaction.rbindex 8f7a6e0f4f..532121a541 100644--- a/app/models/transaction.rb+++ b/app/models/transaction.rb@@ -112,7 +112,7 @@ class Transaction < ApplicationRecordINTERNAL_MOVEMENT_LABELS = [ "Transfer", "Sweep In", "Sweep Out", "Exchange" ].freeze# Providers that support pending transaction flags- PENDING_PROVIDERS = %w[simplefin plaid lunchflow enable_banking akahu up mercury redbark].freeze+ PENDING_PROVIDERS = %w[simplefin plaid lunchflow enable_banking akahu up monobank mercury redbark].freeze# Pre-computed SQL fragment for subqueries that check if a transaction (aliased as "t") is pending.# Stored as a constant so static analysis can verify it contains no user input.diff --git a/app/views/accounts/index.html.erb b/app/views/accounts/index.html.erbindex b282d8e5a8..cd1d97bcfb 100644--- a/app/views/accounts/index.html.erb+++ b/app/views/accounts/index.html.erb@@ -10,7 +10,7 @@) %><% end %>-<% if @manual_accounts.empty? && @plaid_items.empty? && @simplefin_items.empty? && @lunchflow_items.empty? && @redbark_items.empty? && @akahu_items.empty? && @up_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? && @questrade_items.empty? && @wise_items.empty? && @onchain_wallet_items.empty? && @trade_republic_items.empty? %>+<% 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? && @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? && @questrade_items.empty? && @wise_items.empty? && @onchain_wallet_items.empty? && @trade_republic_items.empty? %><%= render "empty" %><% else %><div class="space-y-2">@@ -38,6 +38,10 @@<%= render @up_items.sort_by(&:created_at) %><% end %>+ <% if @monobank_items.any? %>+ <%= render @monobank_items.sort_by(&:created_at) %>+ <% end %>+<% if @enable_banking_items.any? %><%= render @enable_banking_items.sort_by(&:created_at) %><% end %>diff --git a/app/views/monobank_items/_monobank_item.html.erb b/app/views/monobank_items/_monobank_item.html.erbnew file mode 100644index 0000000000..85ba32c1e1--- /dev/null+++ b/app/views/monobank_items/_monobank_item.html.erb@@ -0,0 +1,114 @@+<%# locals: (monobank_item:) %>++<%= tag.div id: dom_id(monobank_item) do %>+ <%= render DS::Disclosure.new(variant: :card, open: true) do |disclosure| %>+ <% disclosure.with_summary_content do %>+ <div class="flex items-center justify-between gap-2 w-full">+ <div class="flex items-center gap-2">+ <%= icon "chevron-right", class: "group-open:rotate-90 motion-safe:transition-transform motion-safe:duration-150" %>++ <div class="flex items-center justify-center h-8 w-8 bg-surface rounded-full">+ <p class="text-primary text-xs font-medium"><%= monobank_item.name.to_s.first.to_s.upcase %></p>+ </div>++ <div class="pl-1 text-sm">+ <div class="flex items-center gap-2">+ <%= tag.p monobank_item.name, class: "font-medium text-primary" %>+ <% if monobank_item.scheduled_for_deletion? %>+ <p class="text-destructive text-sm animate-pulse"><%= t(".deletion_in_progress") %></p>+ <% end %>+ </div>++ <% if monobank_item.accounts.any? %>+ <p class="text-xs text-secondary"><%= monobank_item.institution_summary %></p>+ <% end %>++ <% if monobank_item.syncing? %>+ <div class="text-secondary flex items-center gap-1">+ <%= icon "loader", size: "sm", class: "animate-spin" %>+ <%= tag.span t(".syncing") %>+ </div>+ <% elsif monobank_item.sync_error.present? %>+ <div class="text-secondary flex items-center gap-1">+ <%= render DS::Tooltip.new(text: monobank_item.sync_error, icon: "alert-circle", size: "sm", color: "destructive", as: :span) %>+ <%= tag.span t(".error"), class: "text-destructive" %>+ </div>+ <% else %>+ <p class="text-secondary">+ <% if monobank_item.last_synced_at %>+ <%= t(".status_with_summary", timestamp: time_ago_in_words(monobank_item.last_synced_at), summary: monobank_item.sync_status_summary) %>+ <% else %>+ <%= t(".status_never") %>+ <% end %>+ </p>+ <% end %>+ </div>+ </div>++ <% if Current.user&.admin? %>+ <div class="flex items-center gap-2">+ <%= render DS::Menu.new do |menu| %>+ <% menu.with_item(+ variant: "button",+ text: t(".delete"),+ icon: "trash-2",+ href: monobank_item_path(monobank_item),+ method: :delete,+ confirm: CustomConfirm.for_resource_deletion(monobank_item.name, high_severity: true)+ ) %>+ <% end %>+ </div>+ <% end %>+ </div>+ <% end %>++ <% unless monobank_item.scheduled_for_deletion? %>+ <div class="space-y-4 mt-4">+ <% if monobank_item.accounts.any? %>+ <%= render "accounts/index/account_groups", accounts: monobank_item.accounts %>+ <% end %>++ <% stats = if defined?(@monobank_sync_stats_map) && @monobank_sync_stats_map+ @monobank_sync_stats_map[monobank_item.id] || {}+ else+ monobank_item.syncs.ordered.first&.sync_stats || {}+ end %>+ <%= render ProviderSyncSummary.new(+ stats: stats,+ provider_item: monobank_item,+ institutions_count: monobank_item.connected_institutions.size+ ) %>++ <% unlinked_count = monobank_item.unlinked_accounts_count %>+ <% linked_count = monobank_item.linked_accounts_count %>+ <% total_count = monobank_item.total_accounts_count %>++ <% if unlinked_count > 0 %>+ <div class="p-4 flex flex-col gap-3 items-center justify-center">+ <p class="text-primary font-medium text-sm"><%= t(".setup_needed") %></p>+ <p class="text-secondary text-sm"><%= t(".setup_description", linked: linked_count, total: total_count) %></p>+ <%= render DS::Link.new(+ text: t(".setup_action"),+ icon: "settings",+ variant: "primary",+ href: setup_accounts_monobank_item_path(monobank_item),+ frame: :modal+ ) %>+ </div>+ <% elsif monobank_item.accounts.empty? && total_count == 0 %>+ <div class="p-4 flex flex-col gap-3 items-center justify-center">+ <p class="text-primary font-medium text-sm"><%= t(".no_accounts_title") %></p>+ <p class="text-secondary text-sm"><%= t(".no_accounts_description") %></p>+ <%= render DS::Link.new(+ text: t(".setup_action"),+ icon: "settings",+ variant: "primary",+ href: setup_accounts_monobank_item_path(monobank_item),+ frame: :modal+ ) %>+ </div>+ <% end %>+ </div>+ <% end %>+ <% end %>+<% end %>diff --git a/app/views/monobank_items/select_accounts.html.erb b/app/views/monobank_items/select_accounts.html.erbnew file mode 100644index 0000000000..18cc54331b--- /dev/null+++ b/app/views/monobank_items/select_accounts.html.erb@@ -0,0 +1,54 @@+<%= turbo_frame_tag "modal" do %>+ <%= render DS::Dialog.new do |dialog| %>+ <% dialog.with_header(title: t(".title")) %>++ <% dialog.with_body do %>+ <div class="space-y-4">+ <%# A refresh failure is a notice, not a dead end: the accounts stored by the %>+ <%# last sync are still linkable. %>+ <% if @api_error.present? %>+ <%= render DS::Alert.new(message: @api_error, variant: :warning) %>+ <% end %>++ <% if @monobank_accounts.empty? %>+ <p class="text-sm text-secondary"><%= t(".no_accounts_found") %></p>+ <% else %>+ <p class="text-sm text-secondary"><%= t(".description") %></p>++ <%= form_with url: link_accounts_monobank_items_path,+ method: :post,+ data: { turbo_frame: "_top" },+ class: "space-y-4" do %>+ <%= hidden_field_tag :monobank_item_id, @monobank_item.id %>+ <%= hidden_field_tag :accountable_type, @accountable_type %>+ <%= hidden_field_tag :return_to, @return_to %>++ <div class="space-y-2">+ <% @monobank_accounts.each do |monobank_account| %>+ <label class="flex items-start gap-3 p-3 border border-primary rounded-lg hover:bg-surface cursor-pointer transition-colors">+ <%= check_box_tag "account_ids[]", monobank_account.id, false, class: "mt-1" %>+ <div class="flex-1">+ <div class="font-medium text-sm text-primary"><%= monobank_account.name %></div>+ <div class="text-xs text-secondary mt-1">+ <%= [monobank_account.type_label, monobank_account.currency].compact_blank.join(" · ") %>+ </div>+ </div>+ </label>+ <% end %>+ </div>++ <div class="flex gap-2 justify-end pt-4">+ <%= render DS::Link.new(+ text: t(".cancel"),+ href: @return_to || accounts_path,+ variant: :secondary,+ data: { turbo_frame: "_top", action: "DS--dialog#close" }+ ) %>+ <%= render DS::Button.new(text: t(".link_accounts"), type: "submit") %>+ </div>+ <% end %>+ <% end %>+ </div>+ <% end %>+ <% end %>+<% end %>diff --git a/app/views/monobank_items/select_existing_account.html.erb b/app/views/monobank_items/select_existing_account.html.erbnew file mode 100644index 0000000000..f4bdff1879--- /dev/null+++ b/app/views/monobank_items/select_existing_account.html.erb@@ -0,0 +1,54 @@+<%= turbo_frame_tag "modal" do %>+ <%= render DS::Dialog.new do |dialog| %>+ <% dialog.with_header(title: t(".title", account_name: @account.name)) %>++ <% dialog.with_body do %>+ <div class="space-y-4">+ <%# A refresh failure is a notice, not a dead end: the accounts stored by the %>+ <%# last sync are still linkable. %>+ <% if @api_error.present? %>+ <%= render DS::Alert.new(message: @api_error, variant: :warning) %>+ <% end %>++ <% if @monobank_accounts.empty? %>+ <p class="text-sm text-secondary"><%= t(".no_accounts_found") %></p>+ <% else %>+ <p class="text-sm text-secondary"><%= t(".description") %></p>++ <%= form_with url: link_existing_account_monobank_items_path,+ method: :post,+ data: { turbo_frame: "_top" },+ class: "space-y-4" do %>+ <%= hidden_field_tag :monobank_item_id, @monobank_item.id %>+ <%= hidden_field_tag :account_id, @account.id %>+ <%= hidden_field_tag :return_to, @return_to %>++ <div class="space-y-2">+ <% @monobank_accounts.each do |monobank_account| %>+ <label class="flex items-start gap-3 p-3 border border-primary rounded-lg hover:bg-surface cursor-pointer transition-colors">+ <%= radio_button_tag "monobank_account_id", monobank_account.id, false, class: "mt-1", required: true %>+ <div class="flex-1">+ <div class="font-medium text-sm text-primary"><%= monobank_account.name %></div>+ <div class="text-xs text-secondary mt-1">+ <%= [monobank_account.type_label, monobank_account.currency].compact_blank.join(" · ") %>+ </div>+ </div>+ </label>+ <% end %>+ </div>++ <div class="flex gap-2 justify-end pt-4">+ <%= render DS::Link.new(+ text: t(".cancel"),+ href: @return_to || accounts_path,+ variant: :secondary,+ data: { turbo_frame: "_top", action: "DS--dialog#close" }+ ) %>+ <%= render DS::Button.new(text: t(".link_account"), type: "submit") %>+ </div>+ <% end %>+ <% end %>+ </div>+ <% end %>+ <% end %>+<% end %>diff --git a/app/views/monobank_items/setup_accounts.html.erb b/app/views/monobank_items/setup_accounts.html.erbnew file mode 100644index 0000000000..2bcf93f8ed--- /dev/null+++ b/app/views/monobank_items/setup_accounts.html.erb@@ -0,0 +1,73 @@+<% content_for :title, t(".title") %>++<%= render DS::Dialog.new do |dialog| %>+ <% dialog.with_header(title: t(".title")) do %>+ <div class="flex items-center gap-2">+ <%= icon "landmark", class: "text-primary" %>+ <span class="text-primary"><%= t(".subtitle") %></span>+ </div>+ <% end %>++ <% dialog.with_body do %>+ <%= form_with url: complete_account_setup_monobank_item_path(@monobank_item),+ method: :post,+ local: true,+ data: { turbo_frame: "_top" },+ class: "space-y-6" do %>+ <div class="space-y-4">+ <%# A refresh failure (Monobank allows one request per minute) must not hide the %>+ <%# accounts the last sync already stored: the notice is informational and setup %>+ <%# carries on with what is on file. %>+ <% if @api_error.present? %>+ <%= render DS::Alert.new(message: @api_error, variant: :warning) %>+ <% end %>++ <% if @monobank_accounts.empty? %>+ <div class="p-8 flex flex-col gap-3 items-center justify-center text-center">+ <%= icon "check-circle", size: "lg", class: "text-success" %>+ <p class="text-primary font-medium"><%= t(".no_accounts_to_setup") %></p>+ <p class="text-secondary text-sm"><%= t(".all_accounts_linked") %></p>+ </div>+ <% else %>+ <div class="bg-surface border border-primary p-4 rounded-lg">+ <p class="text-sm text-primary"><strong><%= t(".choose_account_type") %></strong></p>+ <p class="text-xs text-secondary mt-1"><%= t(".choose_account_type_description") %></p>+ </div>++ <% @monobank_accounts.each do |monobank_account| %>+ <div class="border border-primary rounded-lg p-4">+ <div class="mb-3">+ <h3 class="font-medium text-primary"><%= monobank_account.name %></h3>+ <p class="text-xs text-secondary">+ <%= [monobank_account.type_label, monobank_account.currency].compact_blank.join(" · ") %>+ </p>+ </div>++ <%= label_tag "account_types[#{monobank_account.id}]", t(".account_type_label"),+ class: "block text-sm font-medium text-primary mb-2" %>+ <%= select_tag "account_types[#{monobank_account.id}]",+ options_for_select(@account_type_options, @monobank_account_type_suggestions.fetch(monobank_account.id, "skip")),+ class: "appearance-none bg-container border border-primary rounded-md px-3 py-2 text-sm leading-6 text-primary focus:border-primary focus:ring-1 focus:ring-primary focus:outline-none w-full" %>+ </div>+ <% end %>+ <% end %>+ </div>++ <div class="flex gap-3">+ <%= render DS::Button.new(+ text: t(".create_accounts"),+ variant: "primary",+ icon: "plus",+ type: "submit",+ class: "flex-1",+ disabled: @monobank_accounts.empty?+ ) %>+ <%= render DS::Link.new(+ text: t(".cancel"),+ variant: "secondary",+ href: accounts_path+ ) %>+ </div>+ <% end %>+ <% end %>+<% end %>diff --git a/app/views/settings/providers/_monobank_panel.html.erb b/app/views/settings/providers/_monobank_panel.html.erbnew file mode 100644index 0000000000..768cfaa782--- /dev/null+++ b/app/views/settings/providers/_monobank_panel.html.erb@@ -0,0 +1,125 @@+<div id="monobank-providers-panel" class="space-y-4">+ <% active_items = local_assigns[:monobank_items] || @monobank_items || Current.family.monobank_items.active.ordered %>++ <%= render "settings/providers/setup_steps",+ steps: [+ t("settings.providers.monobank_panel.step_1_html", link: link_to(t("providers.monobank.name"), "https://api.monobank.ua", target: "_blank", rel: "noopener noreferrer", class: "text-primary font-medium underline")),+ t("settings.providers.monobank_panel.step_2"),+ t("settings.providers.monobank_panel.step_3")+ ] %>++ <%= render DS::Alert.new(message: t("monobank_items.provider_panel.rate_limit_notice"), variant: :info) %>++ <% error_msg = local_assigns[:error_message] || @error_message %>+ <% if error_msg.present? %>+ <%= render DS::Alert.new(message: error_msg, variant: :error) %>+ <% end %>++ <% if active_items.any? %>+ <div class="space-y-3">+ <% active_items.each do |item| %>+ <%= render DS::Disclosure.new(variant: :card) do |disclosure| %>+ <% disclosure.with_summary_content do %>+ <div class="flex items-center justify-between gap-2 w-full">+ <div class="flex items-center gap-3">+ <div class="flex items-center justify-center h-8 w-8 bg-surface rounded-full">+ <p class="text-primary text-xs font-medium"><%= item.name.to_s.first.to_s.upcase %></p>+ </div>+ <div>+ <p class="font-medium text-primary"><%= item.name %></p>+ <p class="text-xs text-secondary"><%= item.sync_status_summary %></p>+ </div>+ </div>+ </div>+ <% end %>++ <div class="mt-4 space-y-4">+ <div class="flex items-center gap-2">+ <%= render DS::Button.new(+ text: t("monobank_items.provider_panel.sync"),+ icon: "refresh-cw",+ variant: :outline,+ size: :sm,+ href: sync_monobank_item_path(item),+ method: :post,+ disabled: item.syncing?+ ) %>+ <%= render DS::Button.new(+ text: t("monobank_items.provider_panel.disconnect"),+ icon: "trash-2",+ variant: :outline_destructive,+ size: :sm,+ href: monobank_item_path(item),+ method: :delete,+ data: { turbo_confirm: t("monobank_items.provider_panel.disconnect_confirm", name: item.name) }+ ) %>+ </div>++ <%= styled_form_with model: item,+ url: monobank_item_path(item),+ scope: :monobank_item,+ method: :patch,+ data: { turbo: true },+ class: "space-y-3" do |form| %>+ <%= form.text_field :name,+ label: t("monobank_items.provider_panel.connection_name_label"),+ placeholder: t("monobank_items.provider_panel.connection_name_placeholder") %>++ <%= form.text_field :access_token,+ label: t("monobank_items.provider_panel.access_token_label"),+ placeholder: t("monobank_items.provider_panel.keep_access_token_placeholder"),+ type: :password,+ value: nil %>++ <div class="flex flex-wrap justify-end gap-2">+ <%= render DS::Link.new(+ text: t("monobank_items.provider_panel.setup_accounts"),+ icon: "settings",+ variant: "secondary",+ href: setup_accounts_monobank_item_path(item),+ frame: :modal+ ) %>+ <%= render DS::Button.new(+ text: t("monobank_items.provider_panel.update_connection"),+ type: "submit"+ ) %>+ </div>+ <% end %>+ </div>+ <% end %>+ <% end %>+ </div>+ <% end %>++ <% monobank_item = Current.family.monobank_items.build(name: t("monobank_items.provider_panel.default_connection_name")) %>+ <% if active_items.any? %>+ <h3 class="flex items-center gap-2 text-sm font-medium text-primary mt-4">+ <%= icon "plus", size: "sm" %>+ <%= t("monobank_items.provider_panel.add_connection") %>+ </h3>+ <% end %>++ <%= styled_form_with model: monobank_item,+ url: monobank_items_path,+ scope: :monobank_item,+ method: :post,+ data: { turbo: true },+ class: "space-y-3" do |form| %>+ <%= form.text_field :name,+ label: t("monobank_items.provider_panel.connection_name_label"),+ placeholder: t("monobank_items.provider_panel.connection_name_placeholder") %>++ <%= form.text_field :access_token,+ label: t("monobank_items.provider_panel.access_token_label"),+ placeholder: t("monobank_items.provider_panel.access_token_placeholder"),+ type: :password,+ value: nil %>++ <div class="flex justify-end">+ <%= render DS::Button.new(+ text: t("monobank_items.provider_panel.add_connection"),+ type: "submit"+ ) %>+ </div>+ <% end %>+</div>diff --git a/config/initializers/monobank.rb b/config/initializers/monobank.rbnew file mode 100644index 0000000000..511d2329ce--- /dev/null+++ b/config/initializers/monobank.rb@@ -0,0 +1,36 @@+# Monobank integration runtime configuration.+#+# Monobank's personal API allows one request per minute per endpoint and caps a single+# statement request at 31 days, so these settings exist to bound how much work one sync+# may do rather than to tune performance.+Rails.application.configure do+ # Whether held (unsettled) transactions are imported and shown with a "Pending" badge.+ # Default: true. Set MONOBANK_INCLUDE_PENDING=0 to import only settled transactions.+ config.x.monobank.include_pending = !ENV["MONOBANK_INCLUDE_PENDING"].to_s.strip.downcase.in?(%w[0 false no])++ # How many statement requests one sync may spend across all of the connection's+ # accounts. Each request costs roughly a minute of throttled waiting, so the default+ # keeps a sync to a few minutes; accounts that do not fit in the budget are picked up+ # by the next sync (least-recently-covered first).+ config.x.monobank.max_statement_requests_per_sync =+ ENV.fetch("MONOBANK_MAX_STATEMENT_REQUESTS_PER_SYNC", 4).to_i.clamp(1, 60)++ # How far back every sync re-reads the statement, regardless of when the last sync+ # ran. Holds have to stay visible in the payload to avoid being pruned as stale, and+ # Monobank may also settle a transaction under a different id than the hold it+ # replaces, so a few days of overlap keeps pending entries accurate.+ config.x.monobank.pending_lookback_days =+ ENV.fetch("MONOBANK_PENDING_LOOKBACK_DAYS", 3).to_i.clamp(1, 31)++ # How much history a brand-new connection reaches for when no explicit start date is+ # set. Anything beyond one statement window is backfilled across later syncs.+ config.x.monobank.initial_history_days =+ ENV.fetch("MONOBANK_INITIAL_HISTORY_DAYS", 31).to_i.clamp(1, 3650)++ # Debug logging for raw Monobank API responses.+ # DEVELOPMENT-ONLY: the raw dump contains PII (merchant names, counterparty names and+ # IBANs, amounts, account ids) and is gated to local environments so it never fires in+ # managed/production.+ # Default: false (only log summary info)+ config.x.monobank.debug_raw = ENV["MONOBANK_DEBUG_RAW"].to_s.strip.downcase.in?(%w[1 true yes])+enddiff --git a/config/locales/breadcrumbs/en.yml b/config/locales/breadcrumbs/en.ymlindex 72ba7d7551..97710dfc00 100644--- a/config/locales/breadcrumbs/en.yml+++ b/config/locales/breadcrumbs/en.yml@@ -53,6 +53,7 @@ en:mercury_items: Mercurymessages: Messagesmfa: Two-factor authentication+ monobank_items: monobankoidc_accounts: SSO accountsonboardings: Onboardingother_assets: Other assetsdiff --git a/config/locales/views/monobank_items/en.yml b/config/locales/views/monobank_items/en.ymlnew file mode 100644index 0000000000..5a2271167a--- /dev/null+++ b/config/locales/views/monobank_items/en.yml@@ -0,0 +1,134 @@+---+en:+ providers:+ monobank:+ name: Monobank+ description: Connect Ukrainian Monobank cards and jars with a personal API token+ family:+ monobank:+ create_monobank_item:+ default_name: Monobank Connection+ monobank_account:+ jar_fallback: Monobank jar+ card_types:+ black: Black card+ white: White card+ platinum: Platinum card+ iron: Iron card+ yellow: Yellow card+ eaid: eAid card+ fop: Business account+ jar: Jar+ unknown: Monobank card+ monobank_item:+ errors:+ account_processing_failed: Could not sync Monobank account+ account_sync_schedule_failed: Could not schedule Monobank account sync+ transactions_failed: Could not fetch Monobank statement+ sync_failed: Could not sync Monobank connection+ sync:+ status:+ importing: Importing accounts from Monobank...+ checking_setup: Checking account configuration...+ needs_setup:+ one: 1 account needs setup...+ other: "%{count} accounts need setup..."+ processing: Processing transactions...+ calculating: Calculating balances...+ sync_status:+ no_accounts: No accounts found+ all_synced:+ one: 1 account synced+ other: "%{count} accounts synced"+ partial: "%{linked} synced, %{unlinked} need setup"+ institution_summary:+ none: No institutions connected+ one: 1 institution+ count:+ one: 1 institution+ other: "%{count} institutions"+ monobank_items:+ provider_panel:+ default_connection_name: Monobank Connection+ add_connection: Add Monobank connection+ update_connection: Update connection+ connection_name_label: Connection name+ connection_name_placeholder: My Monobank+ access_token_label: Personal API token+ access_token_placeholder: Paste your Monobank personal token+ keep_access_token_placeholder: Leave blank to keep the existing token+ setup_accounts: Setup accounts+ syncing: Syncing...+ sync: Sync+ disconnect: Disconnect+ disconnect_confirm: "Are you sure you want to disconnect %{name}?"+ rate_limit_notice: Monobank allows one request per minute, so a sync fetches a few accounts at a time and older history arrives over several syncs.+ create:+ success: Monobank connection saved.+ update:+ success: Monobank connection updated.+ destroy:+ success: Scheduled Monobank connection for deletion.+ unlink_failed: Could not disconnect Monobank connection+ select_accounts:+ title: Link Monobank accounts+ description: Choose the Monobank cards or jars to add.+ no_accounts_found: No unlinked Monobank accounts were found.+ no_credentials_configured: Configure Monobank in provider settings first.+ cancel: Cancel+ link_accounts: Link accounts+ link_accounts:+ success:+ one: Linked 1 Monobank account.+ other: "Linked %{count} Monobank accounts."+ no_accounts_selected: Select at least one account.+ no_credentials_configured: Configure Monobank in provider settings first.+ unsupported_account_type: Monobank does not support that account type.+ link_failed: No accounts were linked.+ select_existing_account:+ title: "Link Monobank account to %{account_name}"+ description: Choose an unlinked Monobank account to connect to this account.+ no_accounts_found: No unlinked Monobank accounts were found.+ no_credentials_configured: Configure Monobank in provider settings first.+ account_already_linked: This account is already linked to a provider.+ cancel: Cancel+ link_account: Link account+ link_existing_account:+ success: "Linked Monobank account to %{account_name}."+ account_already_linked: This account is already linked to a provider.+ monobank_account_already_linked: This Monobank account is already linked.+ no_account_selected: Select a Monobank account to link.+ setup_accounts:+ title: Link Monobank Accounts+ subtitle: Choose how each Monobank card or jar should appear in Sure.+ no_credentials: Configure Monobank credentials first.+ api_error: Could not refresh accounts from Monobank, so the accounts saved by the last sync are shown instead.+ no_accounts_to_setup: No accounts to set up+ all_accounts_linked: All Monobank accounts are already linked.+ choose_account_type: Choose an account type+ choose_account_type_description: Skip accounts you do not want to track.+ account_type_label: Account type+ account_types:+ skip: Skip+ depository: Cash+ create_accounts: Create accounts+ cancel: Cancel+ complete_account_setup:+ success:+ one: Created 1 Monobank account.+ other: "Created %{count} Monobank accounts."+ all_skipped: No Monobank accounts were created.+ no_accounts: No Monobank accounts were selected.+ creation_failed: Could not create Monobank accounts.+ monobank_item:+ deletion_in_progress: Deletion in progress+ syncing: Syncing+ error: Error+ status_with_summary: "Synced %{timestamp} ago · %{summary}"+ status_never: Never synced+ delete: Delete+ setup_needed: Account setup needed+ setup_description: "%{linked} of %{total} accounts linked."+ setup_action: Setup accounts+ no_accounts_title: No accounts imported yet+ no_accounts_description: Fetch Monobank accounts and choose which ones to link.diff --git a/config/locales/views/monobank_items/uk.yml b/config/locales/views/monobank_items/uk.ymlnew file mode 100644index 0000000000..846373f6d8--- /dev/null+++ b/config/locales/views/monobank_items/uk.yml@@ -0,0 +1,144 @@+---+uk:+ providers:+ monobank:+ name: Monobank+ description: Підключення карток і банок monobank за персональним токеном API+ family:+ monobank:+ create_monobank_item:+ default_name: Підключення Monobank+ monobank_account:+ jar_fallback: Банка Monobank+ card_types:+ black: Чорна картка+ white: Біла картка+ platinum: Платинова картка+ iron: Картка Iron+ yellow: Жовта картка+ eaid: Картка єПідтримка+ fop: Рахунок ФОП+ jar: Банка+ unknown: Картка Monobank+ monobank_item:+ errors:+ account_processing_failed: Не вдалося синхронізувати рахунок Monobank+ account_sync_schedule_failed: Не вдалося запланувати синхронізацію рахунку Monobank+ transactions_failed: Не вдалося отримати виписку Monobank+ sync_failed: Не вдалося синхронізувати підключення Monobank+ sync:+ status:+ importing: Імпортуємо рахунки з monobank...+ checking_setup: Перевіряємо налаштування рахунків...+ needs_setup:+ one: 1 рахунок потребує налаштування...+ few: "%{count} рахунки потребують налаштування..."+ many: "%{count} рахунків потребують налаштування..."+ other: "%{count} рахунків потребують налаштування..."+ processing: Обробляємо транзакції...+ calculating: Обчислюємо баланси...+ sync_status:+ no_accounts: Рахунків не знайдено+ all_synced:+ one: Синхронізовано 1 рахунок+ few: "Синхронізовано %{count} рахунки"+ many: "Синхронізовано %{count} рахунків"+ other: "Синхронізовано %{count} рахунку"+ partial: "%{linked} синхронізовано, %{unlinked} потребують налаштування"+ institution_summary:+ none: Установи не підключені+ one: 1 установа+ count:+ one: 1 установа+ few: "%{count} установи"+ many: "%{count} установ"+ other: "%{count} установи"+ monobank_items:+ provider_panel:+ default_connection_name: Підключення Monobank+ add_connection: Додати підключення Monobank+ update_connection: Оновити підключення+ connection_name_label: Назва підключення+ connection_name_placeholder: Мій Monobank+ access_token_label: Персональний токен API+ access_token_placeholder: Вставте персональний токен Monobank+ keep_access_token_placeholder: Залиште порожнім, щоб зберегти наявний токен+ setup_accounts: Налаштувати рахунки+ syncing: Синхронізація...+ sync: Синхронізувати+ disconnect: Відключити+ disconnect_confirm: "Ви впевнені, що хочете відключити %{name}?"+ rate_limit_notice: Monobank дозволяє один запит на хвилину, тому одна синхронізація опрацьовує кілька рахунків, а давніша історія завантажується за кілька синхронізацій.+ create:+ success: Підключення Monobank збережено.+ update:+ success: Підключення Monobank оновлено.+ destroy:+ success: Підключення Monobank заплановано на видалення.+ unlink_failed: Не вдалося відключити підключення Monobank+ select_accounts:+ title: Підключити рахунки Monobank+ description: Виберіть картки або банки Monobank, які потрібно додати.+ no_accounts_found: Непідключених рахунків Monobank не знайдено.+ no_credentials_configured: Спершу налаштуйте Monobank у налаштуваннях провайдерів.+ cancel: Скасувати+ link_accounts: Підключити рахунки+ link_accounts:+ success:+ one: Підключено 1 рахунок Monobank.+ few: "Підключено %{count} рахунки Monobank."+ many: "Підключено %{count} рахунків Monobank."+ other: "Підключено %{count} рахунку Monobank."+ no_accounts_selected: Виберіть щонайменше один рахунок.+ no_credentials_configured: Спершу налаштуйте Monobank у налаштуваннях провайдерів.+ unsupported_account_type: Monobank не підтримує цей тип рахунку.+ link_failed: Жодного рахунку не підключено.+ select_existing_account:+ title: "Підключити рахунок Monobank до %{account_name}"+ description: Виберіть непідключений рахунок Monobank для цього рахунку.+ no_accounts_found: Непідключених рахунків Monobank не знайдено.+ no_credentials_configured: Спершу налаштуйте Monobank у налаштуваннях провайдерів.+ account_already_linked: Цей рахунок уже підключено до провайдера.+ cancel: Скасувати+ link_account: Підключити рахунок+ link_existing_account:+ success: "Рахунок Monobank підключено до %{account_name}."+ account_already_linked: Цей рахунок уже підключено до провайдера.+ monobank_account_already_linked: Цей рахунок Monobank уже підключено.+ no_account_selected: Виберіть рахунок Monobank для підключення.+ setup_accounts:+ title: Підключення рахунків Monobank+ subtitle: Виберіть, як кожна картка або банка Monobank має відображатися у Sure.+ no_credentials: Спершу налаштуйте доступ до Monobank.+ api_error: Не вдалося оновити рахунки з Monobank, тому показані рахунки, збережені під час останньої синхронізації.+ no_accounts_to_setup: Немає рахунків для налаштування+ all_accounts_linked: Усі рахунки Monobank уже підключені.+ choose_account_type: Виберіть тип рахунку+ choose_account_type_description: Пропустіть рахунки, які не потрібно відслідковувати.+ account_type_label: Тип рахунку+ account_types:+ skip: Пропустити+ depository: Готівка+ create_accounts: Створити рахунки+ cancel: Скасувати+ complete_account_setup:+ success:+ one: Створено 1 рахунок Monobank.+ few: "Створено %{count} рахунки Monobank."+ many: "Створено %{count} рахунків Monobank."+ other: "Створено %{count} рахунку Monobank."+ all_skipped: Рахунків Monobank не створено.+ no_accounts: Рахунки Monobank не вибрано.+ creation_failed: Не вдалося створити рахунки Monobank.+ monobank_item:+ deletion_in_progress: Видалення виконується+ syncing: Синхронізація+ error: Помилка+ status_with_summary: "Синхронізовано %{timestamp} тому · %{summary}"+ status_never: Ніколи не синхронізувалося+ delete: Видалити+ setup_needed: Потрібно налаштувати рахунки+ setup_description: "Підключено %{linked} з %{total} рахунків."+ setup_action: Налаштувати рахунки+ no_accounts_title: Рахунки ще не імпортовано+ no_accounts_description: Отримайте рахунки Monobank і виберіть, які підключити.diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.ymlindex 8af78d8410..7fac7163d8 100644--- a/config/locales/views/settings/en.yml+++ b/config/locales/views/settings/en.yml@@ -419,6 +419,7 @@ en:simplefin: Connect US bank accounts via the open SimpleFIN protocol.lunchflow: Connect 20k+ banks from 40+ countries (UK, EU, USA and more!)redbark: Sync Australian bank accounts via Redbark open banking.+ monobank: Sync Ukrainian monobank cards and jars with a personal API token.enable_banking: Sync European bank accounts via PSD2 open banking.coinstats: Track your entire crypto portfolio across wallets and exchanges.wise: Sync your Wise multi-currency balances and international transfers automatically.@@ -572,6 +573,10 @@ en:step_1_html: "Go to %{link} and generate a personal access token."step_2: "Copy your personal access token."step_3: "Paste the token below, save, then link your synced accounts."+ monobank_panel:+ step_1_html: "Go to %{link}, sign in with the monobank app and generate a personal token."+ step_2: "Copy the token — it is shown only once."+ step_3: "Paste the token below, save, then link the cards and jars you want to track."simplefin_panel:step_1_html: "Go to %{link} for a one-time setup token."step_2: "Paste the token below and connect."diff --git a/config/locales/views/settings/uk.yml b/config/locales/views/settings/uk.ymlindex ef51f5f968..3c8eadb7ce 100644--- a/config/locales/views/settings/uk.yml+++ b/config/locales/views/settings/uk.yml@@ -396,6 +396,7 @@ uk:akahu: Синхронізуйте фінансові установи Нової Зеландії через Akahu.simplefin: Підключайте банківські рахунки США за допомогою відкритого протоколу SimpleFIN.lunchflow: Підключайте 20 тис.+ банків з 40+ країн (Великобританія, ЄС, США та інші!)+ monobank: Синхронізуйте картки та банки monobank за персональним токеном API.enable_banking: Синхронізуйте європейські банківські рахунки через PSD2 open banking.coinstats: Відстежуйте весь свій криптовалютний портфель у гаманцях та на біржах.wise: Автоматично синхронізуйте свої мультивалютні баланси Wise та міжнародні перекази.@@ -531,6 +532,10 @@ uk:step_1_html: "Перейдіть до %{link} і згенеруйте особистий токен доступу."step_2: "Скопіюйте свій особистий токен доступу."step_3: "Вставте токен нижче, збережіть, а потім пов'яжіть свої синхронізовані облікові записи."+ monobank_panel:+ step_1_html: "Перейдіть до %{link}, увійдіть через застосунок monobank і згенеруйте персональний токен."+ step_2: "Скопіюйте токен — він показується лише один раз."+ step_3: "Вставте токен нижче, збережіть, а потім підключіть картки та банки, які потрібно відслідковувати."simplefin_panel:step_1_html: "Перейдіть до %{link} для отримання одноразового токена налаштування."step_2: "Вставте токен нижче та підключіться."diff --git a/config/routes.rb b/config/routes.rbindex 5c312077d6..e4ff981970 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -875,6 +875,22 @@ Rails.application.routes.draw doendend+ resources :monobank_items, only: %i[create update destroy] do+ collection do+ get :preload_accounts+ get :select_accounts+ post :link_accounts+ get :select_existing_account+ post :link_existing_account+ end++ member do+ post :sync+ get :setup_accounts+ post :complete_account_setup+ end+ end+resources :sophtron_items, only: %i[index new create show edit update destroy] docollection doget :preload_accountsdiff --git a/db/migrate/20260904120000_create_monobank_items_and_accounts.rb b/db/migrate/20260904120000_create_monobank_items_and_accounts.rbnew file mode 100644index 0000000000..df2d5d2ffe--- /dev/null+++ b/db/migrate/20260904120000_create_monobank_items_and_accounts.rb@@ -0,0 +1,60 @@+class CreateMonobankItemsAndAccounts < ActiveRecord::Migration[7.2]+ def change+ create_table :monobank_items, id: :uuid do |t|+ t.references :family, null: false, foreign_key: true, type: :uuid+ t.string :name+ t.string :institution_id+ t.string :institution_name+ t.string :institution_domain+ t.string :institution_url+ t.string :institution_color+ t.string :status, default: "good", null: false+ t.boolean :scheduled_for_deletion, default: false, null: false+ t.boolean :pending_account_setup, default: false, null: false+ t.date :sync_start_date+ t.jsonb :raw_payload+ t.jsonb :raw_institution_payload+ t.text :access_token+ t.timestamps+ end++ add_index :monobank_items, :status++ create_table :monobank_accounts, id: :uuid do |t|+ t.references :monobank_item, null: false, foreign_key: true, type: :uuid+ t.string :name, null: false+ t.string :account_id+ t.string :currency, null: false+ t.decimal :current_balance, precision: 19, scale: 4+ t.decimal :credit_limit, precision: 19, scale: 4+ t.string :account_status+ t.string :account_type+ t.string :account_kind+ t.string :masked_pan+ t.string :iban+ t.string :provider+ t.boolean :ignored, default: false, null: false+ t.jsonb :institution_metadata+ t.jsonb :raw_payload+ t.jsonb :raw_transactions_payload+ t.date :sync_start_date+ # Statement backfill cursors. Monobank caps one statement request at 31 days and+ # throttles to one call per minute, so history is walked backwards across syncs+ # (history_synced_from) while new activity is fetched forward from the last+ # covered timestamp (statement_synced_through). Both are timestamps, not dates: a+ # window is requested in Unix seconds and rarely lands on midnight, so recording+ # only the date would claim a partially covered day as complete.+ t.datetime :history_synced_from+ t.datetime :statement_synced_through++ t.timestamps+ end++ add_index :monobank_accounts, :account_id+ add_index :monobank_accounts,+ [ :monobank_item_id, :account_id ],+ unique: true,+ where: "account_id IS NOT NULL",+ name: "index_monobank_accounts_on_item_and_account_id"+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 241769b765..5b48a9ef3a 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -1447,6 +1447,54 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_04_201444) dot.index ["user_id"], name: "index_mobile_devices_on_user_id"end+ create_table "monobank_accounts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|+ t.string "account_id"+ t.string "account_kind"+ t.string "account_status"+ t.string "account_type"+ t.datetime "created_at", null: false+ t.decimal "credit_limit", precision: 19, scale: 4+ t.string "currency", null: false+ t.decimal "current_balance", precision: 19, scale: 4+ t.datetime "history_synced_from"+ t.string "iban"+ t.boolean "ignored", default: false, null: false+ t.jsonb "institution_metadata"+ t.string "masked_pan"+ t.uuid "monobank_item_id", null: false+ t.string "name", null: false+ t.string "provider"+ t.jsonb "raw_payload"+ t.jsonb "raw_transactions_payload"+ t.datetime "statement_synced_through"+ t.date "sync_start_date"+ t.datetime "updated_at", null: false+ t.index ["account_id"], name: "index_monobank_accounts_on_account_id"+ t.index ["monobank_item_id", "account_id"], name: "index_monobank_accounts_on_item_and_account_id", unique: true, where: "(account_id IS NOT NULL)"+ t.index ["monobank_item_id"], name: "index_monobank_accounts_on_monobank_item_id"+ end++ create_table "monobank_items", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|+ t.text "access_token"+ t.datetime "created_at", null: false+ t.uuid "family_id", null: false+ t.string "institution_color"+ t.string "institution_domain"+ t.string "institution_id"+ t.string "institution_name"+ t.string "institution_url"+ t.string "name"+ t.boolean "pending_account_setup", default: false, null: false+ t.jsonb "raw_institution_payload"+ t.jsonb "raw_payload"+ t.boolean "scheduled_for_deletion", default: false, null: false+ t.string "status", default: "good", null: false+ t.date "sync_start_date"+ t.datetime "updated_at", null: false+ t.index ["family_id"], name: "index_monobank_items_on_family_id"+ t.index ["status"], name: "index_monobank_items_on_status"+ end+create_table "notification_deliveries", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|t.datetime "created_at", null: falset.uuid "rule_id", null: false@@ -2669,6 +2717,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_04_201444) doadd_foreign_key "mercury_items", "families"add_foreign_key "messages", "chats"add_foreign_key "mobile_devices", "users"+ add_foreign_key "monobank_accounts", "monobank_items"+ add_foreign_key "monobank_items", "families"add_foreign_key "notification_deliveries", "rules", on_delete: :cascadeadd_foreign_key "notification_deliveries", "transactions", on_delete: :cascadeadd_foreign_key "oauth_access_grants", "oauth_applications", column: "application_id"diff --git a/docs/hosting/monobank.md b/docs/hosting/monobank.mdnew file mode 100644index 0000000000..d1eae5d03a--- /dev/null+++ b/docs/hosting/monobank.md@@ -0,0 +1,116 @@+# Setting Up monobank (Ukraine)++[monobank](https://monobank.ua) exposes a personal API that returns your own cards, jars+and statements. You bring your own token, so Sure talks to monobank directly on your+behalf — no third-party aggregator sits in between.++> [!NOTE]+> This integration uses monobank's **personal** API. Its documentation states that a+> service which stores other people's data on its own servers must use the corporate+> (service provider) API instead, and that programs used by clients personally — where+> the data never passes through the developer's nodes — do not. A self-hosted Sure+> instance is the latter. If you run Sure as a hosted service for other people, read+> [monobank's API terms](https://api.monobank.ua/docs/index.html) first.++> [!NOTE]+> The personal API is not available to clients under 16. Data for a child's accounts is+> available from the parent's account.++## 1. Get Your Personal Token++1. Go to [api.monobank.ua](https://api.monobank.ua/).+2. Sign in by scanning the QR code with the monobank app.+3. Generate a personal token and copy it. **It is shown only once.**++The token is scoped to your own data: it can list your accounts, read statements, and+register a statement webhook (`POST /personal/webhook`). It cannot move money.++## 2. Add monobank to Sure++1. In Sure, go to **Settings > Providers** and find the **monobank** panel.+2. Paste your token and save.+3. Your cards and jars appear for setup. Link each one to an existing Sure account or+ create a new account from it, and skip anything you don't want to track.++Cards become cash accounts; jars become savings accounts. A card's balance is stored as+your own funds — monobank reports the credit limit inside the balance, and Sure+subtracts it.++## 3. Syncing++monobank's rate limit shapes how syncing works. Each personal endpoint accepts **one+request per minute**, and a single statement request may cover at most **31 days**. So:++- Every sync fetches your account list once, then reads statements account by account.+- A sync spends a fixed budget of statement requests (4 by default). Accounts that don't+ fit are picked up by the next sync, least-recently-synced first.+- History older than one statement window is backfilled over successive syncs, walking+ backwards 31 days at a time until it reaches the start date.+- Each sync also re-reads the last few days, and any older hold that is still+ unsettled, so pending transactions stay accurate.++Because of the throttle, a sync sleeps between requests: with four accounts, expect it+to take a few minutes. Transactions are deduplicated by their monobank id, so+re-syncing never creates duplicates.++### Pending transactions++Held (unsettled) authorizations are imported and marked **Pending**. When a hold+settles, monobank may issue the settled record under a different id, so the settled+record is matched to the pending entry by amount and date, and inherits it.++A hold that simply disappears from the statement — cancelled rather than settled — has+its pending entry removed. Two things are never removed:++- A hold the statement request did not actually reach, so it stays visible while the+ funds are still blocked. Pre-authorizations for hotels, car hire and fuel routinely+ outlive the few days a sync re-reads by default.+- An entry you have taken over yourself (excluded, edited, or split). It only loses its+ pending badge, so your edits, splits and transfers survive.++To import only settled transactions:++```+MONOBANK_INCLUDE_PENDING=0+```++### Categories++monobank does not categorise transactions; it reports the merchant's MCC. Sure maps the+codes with a clear equivalent (groceries, restaurants, fuel, pharmacies, …) onto your+existing categories, matching them by the name in your own language. Codes without an+honest equivalent — cash withdrawals, transfers, gambling — are left uncategorised for+your own rules to handle.++### Configuration++| Variable | Default | Purpose |+| --- | --- | --- |+| `MONOBANK_INCLUDE_PENDING` | `1` | Import held transactions and badge them as pending. |+| `MONOBANK_MAX_STATEMENT_REQUESTS_PER_SYNC` | `4` | Statement requests one sync may spend. Each costs about a minute. |+| `MONOBANK_PENDING_LOOKBACK_DAYS` | `3` | Minimum period every sync re-reads. A hold older than this extends the window on its own. |+| `MONOBANK_INITIAL_HISTORY_DAYS` | `31` | History a new connection reaches for when no start date is set. |+| `MONOBANK_MIN_REQUEST_INTERVAL` | `60` | Seconds enforced between requests to the same endpoint. |+| `MONOBANK_DEBUG_RAW` | unset | Log raw API payloads. Development only — the dump contains personal data. |++## Troubleshooting++**Connection requires update**+The token was revoked or is invalid. Generate a new one at+[api.monobank.ua](https://api.monobank.ua/) and update it in the provider panel.++**A sync says accounts were skipped**+Either the statement request budget ran out for this run, or monobank throttled the+request — one request per minute per endpoint, so a manual sync started right after a+scheduled one collides. All of these are normal and leave the connection healthy: the+next sync continues where this one stopped. Raise+`MONOBANK_MAX_STATEMENT_REQUESTS_PER_SYNC` if you would rather trade a longer sync for+fewer runs.++**Older transactions are missing**+History arrives in 31-day steps, one step per sync. Set a start date on the connection+to bound how far back it goes, then let it run.++**Sync errors**+Provider sync failures and notes are captured in Sure's debug log (super admin:+**Settings > Debug**), filtered by the `monobank` provider key.diff --git a/docs/llm-guides/providers.md b/docs/llm-guides/providers.mdindex aaed306f59..52b46dcef4 100644--- a/docs/llm-guides/providers.md+++ b/docs/llm-guides/providers.md@@ -33,6 +33,7 @@ metadata produces no badge; manual/CSV imports have no pending concept.| SimpleFIN | [`SimplefinEntry::Processor.pending?`](../../app/models/simplefin_entry/processor.rb) accepts an explicitly truthy `pending` flag, or `posted` equal to numeric `0` or string `"0"` with a present, positive `transacted_at` timestamp. A blank/missing `posted` value does **not** imply pending. Writes `extra["simplefin"]["pending"]` as true or false so a posted update clears stale pending metadata. || Plaid | [`PlaidEntry::Processor`](../../app/models/plaid_entry/processor.rb) stores bank/credit transaction `pending` and `pending_transaction_id` under `extra["plaid"]`; the linking ID supports pending-to-posted reconciliation. The investment transaction processor does not store pending metadata. || Lunchflow | [`LunchflowEntry::Processor`](../../app/models/lunchflow_entry/processor.rb) stores the boolean-cast `isPending` value under `extra["lunchflow"]["pending"]` when the upstream key is present. |+| Monobank | [`MonobankEntry::Processor`](../../app/models/monobank_entry/processor.rb) treats a `hold: true` statement item as pending and writes `extra["monobank"]["pending"]`. Monobank may settle a hold under a *different* id, so the settled record reconciles onto the pending entry through [`Account::ProviderImportAdapter`](../../app/models/account/provider_import_adapter.rb)'s amount/date lookup. A hold that simply disappears is pruned, but only when the statement request actually covered its date range, and never when the entry is `protected_from_sync?` — those only lose the pending flag. No FX metadata: the statement reports `operationAmount` without the operation currency, so `operation_amount` is stored raw and `fx_from`/`fx_amount` are left unset. |SimpleFIN additionally stores `extra["simplefin"]["fx_from"]` when transaction andaccount currencies differ, and `fx_date` from the transacted date with posted-date@@ -67,6 +68,15 @@ Pending inclusion is provider- and layer-specific:that configuration as `include_pending:`. A direct [provider call](../../app/models/provider/lunchflow.rb)defaults the argument to false and adds `include_pending=true` only when enabled;it does not consult the shared SimpleFIN/Plaid setting.+- **Monobank:** the [initializer](../../config/initializers/monobank.rb) defaults+ `config.x.monobank.include_pending` to true; `MONOBANK_INCLUDE_PENDING=0` imports+ only settled transactions. The same initializer bounds a sync against Monobank's+ one-request-per-minute limit and 31-day statement window+ (`max_statement_requests_per_sync`, `pending_lookback_days`,+ `initial_history_days`); read [the hosting guide](../hosting/monobank.md) before+ changing the [importer](../../app/models/monobank_item/importer.rb)'s request+ budgeting, and keep the pending lookback wide enough that live holds stay in the+ payload instead of being pruned as stale.## Raw payload debugging@@ -80,3 +90,8 @@ but its [importer](../../app/models/up_item/importer.rb) logs raw transactions owhen `Rails.env.local?` is also true. The dump contains PII: preserve this local-onlyguard and do not enable raw Up dumps in managed/production. This guard is specificto Up; the SimpleFIN and Lunchflow flags do not provide the same environment gate.++`MONOBANK_DEBUG_RAW=1` behaves like the Up flag: its+[importer](../../app/models/monobank_item/importer.rb) dumps raw payloads only when+`Rails.env.local?` is also true, because the dump contains PII (merchant and+counterparty names, IBANs, amounts, account ids). Preserve that local-only guard.diff --git a/docs/onboarding/guide.md b/docs/onboarding/guide.mdindex 930ab993f6..60dda72f2f 100644--- a/docs/onboarding/guide.md+++ b/docs/onboarding/guide.md@@ -37,6 +37,7 @@ When you arrive at the main dashboard, showing **No accounts yet**, you're all s> If you'd like to use an integration with a data provider instead, see:>> - [**Lunch Flow**](https://www.lunchflow.app/)+> - [**monobank**](/docs/hosting/monobank.md) (Ukrainian cards and jars)> - [**Plaid**](/docs/hosting/plaid.md)> - [**Redbark**](/docs/hosting/redbark.md) (Australian banks)> - [**SimpleFIN**](https://beta-bridge.simplefin.org/)diff --git a/test/controllers/monobank_items_controller_test.rb b/test/controllers/monobank_items_controller_test.rbnew file mode 100644index 0000000000..5538b270fb--- /dev/null+++ b/test/controllers/monobank_items_controller_test.rb@@ -0,0 +1,173 @@+require "test_helper"++class MonobankItemsControllerTest < ActionDispatch::IntegrationTest+ setup do+ ensure_tailwind_build+ sign_in users(:family_admin)+ SyncJob.stubs(:perform_later)++ @family = families(:dylan_family)+ @monobank_item = MonobankItem.create!(+ family: @family,+ name: "Main Monobank",+ access_token: "monobank-personal-token"+ )+ @monobank_account = @monobank_item.monobank_accounts.create!(+ name: "Black card ·1234",+ account_id: "acc_1",+ currency: "UAH",+ account_kind: "card",+ account_type: "black"+ )+ end++ test "create saves the connection and starts a sync" do+ # The setup-wide stub allows zero calls, so the enqueue is asserted explicitly here:+ # a regression that stops kicking off the first sync would otherwise pass.+ SyncJob.expects(:perform_later).with { |sync| sync.syncable.is_a?(MonobankItem) }.once++ assert_difference "MonobankItem.count", 1 do+ post monobank_items_url, params: {+ monobank_item: { name: "Second Monobank", access_token: "another-token" }+ }+ end++ assert_redirected_to settings_providers_path++ created = MonobankItem.order(:created_at).last+ assert_equal "another-token", created.access_token+ assert_equal 1, created.syncs.count+ end++ test "update keeps the existing token when the field is left blank" do+ patch monobank_item_url(@monobank_item), params: {+ monobank_item: { name: "Renamed", access_token: "" }+ }++ @monobank_item.reload+ assert_equal "Renamed", @monobank_item.name+ assert_equal "monobank-personal-token", @monobank_item.access_token+ end++ test "setup_accounts renders the pending accounts with a preselected type" do+ MonobankItemsController.any_instance.stubs(:fetch_monobank_accounts_from_api).returns(nil)++ get setup_accounts_monobank_item_url(@monobank_item)+ assert_response :success++ select = css_select("select[name='account_types[#{@monobank_account.id}]']").first+ assert select, "expected scoped account_types[#{@monobank_account.id}] select"+ selected_option = css_select("select[name='account_types[#{@monobank_account.id}]'] option[selected='selected']").first+ assert_equal "Depository", selected_option["value"]+ end++ test "complete_account_setup creates a savings account for a jar" do+ jar = @monobank_item.monobank_accounts.create!(+ name: "На тепловізор", account_id: "jar_1", currency: "UAH", account_kind: "jar", account_type: "jar"+ )++ assert_difference [ "Account.count", "AccountProvider.count" ], 1 do+ post complete_account_setup_monobank_item_url(@monobank_item), params: {+ account_types: { jar.id.to_s => "Depository", @monobank_account.id.to_s => "skip" }+ }+ end++ assert_redirected_to accounts_path+ created_account = jar.reload.current_account+ assert_equal "Depository", created_account.accountable_type+ assert_equal "savings", created_account.accountable.subtype+ assert @monobank_account.reload.ignored?, "a skipped account stops resurfacing as needing setup"+ end++ # Monobank allows one client-info request per minute, so the very first setup screen+ # regularly collides with the sync that just ran. The screen must still offer the+ # accounts already on file instead of blocking on a refresh failure.+ test "setup_accounts still offers the stored accounts when the refresh fails" do+ MonobankItemsController.any_instance+ .stubs(:fetch_monobank_accounts_from_api)+ .returns(I18n.t("monobank_items.setup_accounts.api_error"))++ get setup_accounts_monobank_item_url(@monobank_item)++ assert_response :success+ assert_select "select[name='account_types[#{@monobank_account.id}]']", 1+ assert_select "button[type=submit][disabled]", false, "the refresh failure must not block setup"+ assert_select "body", text: /#{Regexp.escape(I18n.t("monobank_items.setup_accounts.api_error"))}/+ end++ test "select_accounts still offers the stored accounts when the refresh fails" do+ MonobankItemsController.any_instance+ .stubs(:fetch_monobank_accounts_from_api)+ .returns(I18n.t("monobank_items.setup_accounts.api_error"))++ get select_accounts_monobank_items_url, params: {+ monobank_item_id: @monobank_item.id, accountable_type: "Depository"+ }++ assert_response :success+ assert_select "input[name='account_ids[]'][value=?]", @monobank_account.id+ end++ test "select_accounts renders the unlinked accounts" do+ MonobankItemsController.any_instance.stubs(:fetch_monobank_accounts_from_api).returns(nil)++ get select_accounts_monobank_items_url, params: {+ monobank_item_id: @monobank_item.id, accountable_type: "Depository"+ }++ assert_response :success+ assert_select "input[name='account_ids[]'][value=?]", @monobank_account.id+ end++ test "select_accounts rejects unsafe return paths" do+ MonobankItemsController.any_instance.stubs(:fetch_monobank_accounts_from_api).returns(nil)++ unsafe_return_paths.each do |return_to|+ get select_accounts_monobank_items_url, params: {+ monobank_item_id: @monobank_item.id,+ accountable_type: "Depository",+ return_to: return_to+ }++ assert_response :success+ assert_select %(input[name="return_to"]) do |fields|+ assert fields.first["value"].blank?, "expected #{return_to.inspect} to be rejected"+ end+ end+ end++ test "sync enqueues a sync for the connection" do+ SyncJob.expects(:perform_later).with { |sync| sync.syncable == @monobank_item }.once++ post sync_monobank_item_url(@monobank_item)++ assert_redirected_to accounts_path+ end++ test "destroy schedules the connection for deletion" do+ DestroyJob.expects(:perform_later).with(@monobank_item).once++ delete monobank_item_url(@monobank_item)++ assert_redirected_to settings_providers_path+ assert @monobank_item.reload.scheduled_for_deletion?+ end++ private++ def unsafe_return_paths+ [+ "https://evil.example/accounts",+ "http://evil.example/accounts",+ "//evil.example/accounts",+ "\\evil.example/accounts",+ "/\\evil.example/accounts",+ "/%2fevil.example/accounts",+ "/%2Fevil.example/accounts",+ "/%5cevil.example/accounts",+ "/%5Cevil.example/accounts",+ "/\naccounts",+ "/ accounts"+ ]+ end+enddiff --git a/test/controllers/settings/providers_controller_test.rb b/test/controllers/settings/providers_controller_test.rbindex e40f834276..e23052cea1 100644--- a/test/controllers/settings/providers_controller_test.rb+++ b/test/controllers/settings/providers_controller_test.rb@@ -33,6 +33,23 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTestendend+ # A panel missing from family_panel_items reports :ok forever, however badly its+ # connection is doing: compute_provider_sync_health skips any key whose items are+ # absent, so no error badge ever reaches the page.+ test "a failed monobank sync surfaces as an error on the providers page" do+ monobank_items(:one).syncs.create!(status: :failed)++ get settings_providers_url+ assert_response :success++ health = @controller.view_assigns["provider_sync_health"]["monobank"]+ assert health.present?, "monobank is missing from the computed sync health"+ assert health[:error], "monobank sync health should report an error"++ needs_attention = @controller.view_assigns["needs_attention"]+ assert_includes needs_attention.map { |entry| entry[:provider_key] }, "monobank"+ end+test "shows configured Brex connections in bank sync settings" doget settings_providers_urldiff --git a/test/encryption_verification_test.rb b/test/encryption_verification_test.rbindex c574274372..0b4f6059e7 100644--- a/test/encryption_verification_test.rb+++ b/test/encryption_verification_test.rb@@ -320,6 +320,46 @@ class EncryptionVerificationTest < ActiveSupport::TestCaseaccount.update!(raw_payload: original_payload)end+ test "monobank item credentials and payloads are encrypted" do+ skip "No monobank items in fixtures" unless MonobankItem.any?++ item = MonobankItem.first+ item.update!(access_token: "mono-token-plaintext-probe", raw_payload: { test: "data" })+ item.reload++ # The accessor round-trips...+ assert_equal "mono-token-plaintext-probe", item.access_token+ assert_equal({ "test" => "data" }, item.raw_payload)++ # ...but the column must not hold the value verbatim. Without this the assertions+ # above pass just as happily against plaintext columns.+ assert_column_not_plaintext(MonobankItem, item.id, :access_token, "mono-token-plaintext-probe")+ assert_column_not_plaintext(MonobankItem, item.id, :raw_payload, "test")+ end++ test "monobank account payloads and identifiers are encrypted" do+ skip "No monobank accounts in fixtures" unless MonobankAccount.any?++ account = MonobankAccount.first+ account.update!(+ raw_payload: { account_test: "value" },+ raw_transactions_payload: [ { id: "tx_probe" } ],+ masked_pan: "537541******9999",+ iban: "UA-TEST-IBAN-ENCRYPTION-PROBE"+ )+ account.reload++ assert_equal({ "account_test" => "value" }, account.raw_payload)+ assert_equal "537541******9999", account.masked_pan+ assert_equal "UA-TEST-IBAN-ENCRYPTION-PROBE", account.iban++ # A partial card number and an IBAN are exactly the fields worth proving opaque.+ assert_column_not_plaintext(MonobankAccount, account.id, :masked_pan, "537541******9999")+ assert_column_not_plaintext(MonobankAccount, account.id, :iban, "UA-TEST-IBAN-ENCRYPTION-PROBE")+ assert_column_not_plaintext(MonobankAccount, account.id, :raw_payload, "account_test")+ assert_column_not_plaintext(MonobankAccount, account.id, :raw_transactions_payload, "tx_probe")+ end+# ============================================================================# DATABASE VERIFICATION TESTS# ============================================================================@@ -344,4 +384,19 @@ class EncryptionVerificationTest < ActiveSupport::TestCaseuser.destroyend++ private++ # Reads +column+ straight from the database, bypassing the model, and asserts the+ # stored bytes do not contain +value+. An accessor round-trip alone cannot tell+ # encryption from plaintext; this can.+ def assert_column_not_plaintext(model, id, column, value)+ raw = ActiveRecord::Base.connection.select_value(+ model.where(id: id).select(column).to_sql+ )++ assert raw.present?, "expected #{model}##{column} to be stored"+ assert_not_includes raw.to_s, value,+ "#{model}##{column} should be encrypted at rest, but the raw column contains #{value.inspect}"+ endenddiff --git a/test/fixtures/monobank_accounts.yml b/test/fixtures/monobank_accounts.ymlnew file mode 100644index 0000000000..d681df8572--- /dev/null+++ b/test/fixtures/monobank_accounts.yml@@ -0,0 +1,10 @@+black_card:+ monobank_item: one+ account_id: "mono_acc_black_1"+ name: "Black card"+ currency: UAH+ current_balance: 1500.00+ account_kind: "card"+ account_type: "black"+ masked_pan: "537541******1234"+ iban: "UA-TEST-IBAN-FIXTURE"diff --git a/test/fixtures/monobank_items.yml b/test/fixtures/monobank_items.ymlnew file mode 100644index 0000000000..24b13028f3--- /dev/null+++ b/test/fixtures/monobank_items.yml@@ -0,0 +1,9 @@+one:+ family: dylan_family++ name: "Test Monobank Connection"+ access_token: "monobank-test-access-token"+ institution_id: "monobank"+ institution_name: "Monobank"+ institution_domain: "monobank.ua"+ status: gooddiff --git a/test/models/account/provider_import_adapter_test.rb b/test/models/account/provider_import_adapter_test.rbindex 6927ad30af..8b70fccba5 100644--- a/test/models/account/provider_import_adapter_test.rb+++ b/test/models/account/provider_import_adapter_test.rb@@ -1251,6 +1251,32 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCaseendend+ # Every provider in Transaction::PENDING_PROVIDERS must be reconcilable, not just the+ # ones the lookup happened to spell out.+ test "find_pending_transaction covers every pending-capable provider" do+ Transaction::PENDING_PROVIDERS.each_with_index do |provider, index|+ amount = 10.00 + index+ pending = @adapter.import_transaction(+ external_id: "#{provider}_pending_#{index}",+ amount: amount,+ currency: "USD",+ date: Date.today - 1.day,+ name: "Pending #{provider}",+ source: provider,+ extra: { provider => { "pending" => true } }+ )++ result = @adapter.find_pending_transaction(+ date: Date.today,+ amount: amount,+ currency: "USD",+ source: provider+ )++ assert_equal pending.id, result&.id, "#{provider} pending transactions must be findable"+ end+ end+test "find_pending_transaction returns nil when no pending transactions exist" do# Create a non-pending transaction@adapter.import_transaction(diff --git a/test/models/monobank_account/transactions/category_matcher_test.rb b/test/models/monobank_account/transactions/category_matcher_test.rbnew file mode 100644index 0000000000..cfc1056539--- /dev/null+++ b/test/models/monobank_account/transactions/category_matcher_test.rb@@ -0,0 +1,59 @@+require "test_helper"++class MonobankAccount::Transactions::CategoryMatcherTest < ActiveSupport::TestCase+ Category = Struct.new(:id, :name)++ test "matches an MCC onto the equivalent English default category" do+ matcher = build_matcher([ "Groceries", "Food & Drink", "Transportation" ])++ assert_equal "Groceries", matcher.match(5411)&.name+ assert_equal "Food & Drink", matcher.match(5812)&.name+ assert_equal "Transportation", matcher.match(5541)&.name+ end++ test "matches ranges as well as single codes" do+ matcher = build_matcher([ "Travel" ])++ assert_equal "Travel", matcher.match(3005)&.name, "airline MCCs are a range"+ assert_equal "Travel", matcher.match(7011)&.name, "hotels are a single code"+ end++ test "returns nil for MCCs with no confident mapping" do+ matcher = build_matcher([ "Groceries", "Shopping", "Fees" ])++ assert_nil matcher.match(6011), "ATM withdrawal is money movement, not spending"+ assert_nil matcher.match(4829), "money transfer is money movement"+ assert_nil matcher.match(7995), "gambling has no honest default category"+ assert_nil matcher.match(nil)+ assert_nil matcher.match("")+ end++ test "returns nil when the family has no equivalent category" do+ matcher = build_matcher([ "Shopping" ])++ assert_nil matcher.match(5411)+ end++ # A Ukrainian family's categories are named in Ukrainian, which is the whole reason+ # this matcher resolves the default category name in the family's own locale.+ test "matches localized default category names" do+ localized = I18n.t("models.category.defaults.groceries", locale: :uk)+ matcher = build_matcher([ localized ], locale: "uk")++ assert_equal localized, matcher.match(5411)&.name+ end++ test "ignores case, punctuation and the and conjunction" do+ matcher = build_matcher([ "gifts and donations" ])++ assert_equal "gifts and donations", matcher.match(8398)&.name+ end++ private++ def build_matcher(names, locale: nil)+ categories = names.each_with_index.map { |name, index| Category.new(index + 1, name) }++ MonobankAccount::Transactions::CategoryMatcher.new(categories, locale: locale)+ end+enddiff --git a/test/models/monobank_account/transactions/processor_test.rb b/test/models/monobank_account/transactions/processor_test.rbnew file mode 100644index 0000000000..d3924bb72a--- /dev/null+++ b/test/models/monobank_account/transactions/processor_test.rb@@ -0,0 +1,142 @@+require "test_helper"++class MonobankAccount::Transactions::ProcessorTest < ActiveSupport::TestCase+ MIDDAY_UNIX = 1_767_960_000++ setup do+ @family = families(:empty)+ @family.update!(timezone: "Europe/Kyiv")+ @monobank_item = MonobankItem.create!(family: @family, name: "Monobank", access_token: "tok")+ @monobank_account = MonobankAccount.create!(+ monobank_item: @monobank_item, name: "Black card", account_id: "acc_1", currency: "UAH"+ )+ @account = Account.create!(+ family: @family, name: "Card",+ accountable: Depository.new(subtype: "checking"), balance: 100, currency: "UAH"+ )+ AccountProvider.create!(account: @account, provider: @monobank_account)+ end++ # Importing must not create categories as a side effect: a family that has none+ # (deliberately cleared, or pre-onboarding) keeps none, and transactions stay+ # uncategorised until the user sets up categories themselves.+ test "does not bootstrap default categories during import" do+ assert_equal 0, @family.categories.count, "family starts with no categories"++ @monobank_account.update!(raw_transactions_payload: [ transaction(id: "tx_1", mcc: 5411) ])++ result = MonobankAccount::Transactions::Processor.new(@monobank_account).process++ assert result[:success]+ assert_equal 0, @family.categories.reload.count, "import must not create categories"++ entry = @account.entries.find_by(external_id: "monobank_tx_1")+ assert_not_nil entry, "the transaction was still imported"+ assert_nil entry.transaction.category_id, "stays uncategorised when the family has no categories"+ end++ test "applies the category matched from the transaction MCC" do+ @family.categories.bootstrap!++ @monobank_account.update!(raw_transactions_payload: [ transaction(id: "tx_2", mcc: 5411) ])++ MonobankAccount::Transactions::Processor.new(@monobank_account).process++ entry = @account.entries.find_by(external_id: "monobank_tx_2")+ assert_equal "Groceries", entry.transaction.category&.name+ end++ test "leaves transactions with an unmapped MCC uncategorised" do+ @family.categories.bootstrap!++ # 6011 is an ATM cash withdrawal: money movement, deliberately unmapped.+ @monobank_account.update!(raw_transactions_payload: [ transaction(id: "tx_3", mcc: 6011) ])++ MonobankAccount::Transactions::Processor.new(@monobank_account).process++ entry = @account.entries.find_by(external_id: "monobank_tx_3")+ assert_nil entry.transaction.category_id+ end++ # Monobank may issue the settled record under a different id than the hold it+ # replaces, so reconciliation has to match them up on amount and date instead. The+ # user's own category and notes live on the pending entry and must survive.+ test "reconciles a hold that settles under a different id" do+ @monobank_account.update!(raw_transactions_payload: [ transaction(id: "tx_hold", hold: true) ])+ MonobankAccount::Transactions::Processor.new(@monobank_account).process++ assert_equal 1, pending_entries.count++ @monobank_account.update!(raw_transactions_payload: [ transaction(id: "tx_settled", hold: false) ])+ MonobankAccount::Transactions::Processor.new(@monobank_account).process++ settled = @account.entries.find_by(external_id: "monobank_tx_settled")+ assert_not_nil settled+ assert_equal [ "monobank_tx_hold" ], settled.transaction.extra["auto_claimed_pending_ids"],+ "the settled record must claim the hold instead of duplicating it"+ assert_empty pending_entries+ assert_equal 1, @account.entries.count, "no orphaned pending entry is left behind"+ end++ test "prunes a hold that was cancelled rather than settled" do+ @monobank_account.update!(raw_transactions_payload: [ transaction(id: "tx_hold", hold: true) ])+ MonobankAccount::Transactions::Processor.new(@monobank_account).process++ assert_equal 1, pending_entries.count++ # Nothing settled: the hold simply dropped out of the statement.+ @monobank_account.update!(raw_transactions_payload: [ unrelated_transaction ])+ result = MonobankAccount::Transactions::Processor.new(@monobank_account).process++ assert_equal 1, result[:pruned_pending]+ assert_empty pending_entries+ end++ # Destroying an entry the user has taken over would take its splits (child entries)+ # and any transfer it belongs to with it, so a stale hold only loses its pending flag.+ test "keeps user-owned pending entries and clears their pending flag instead" do+ @monobank_account.update!(raw_transactions_payload: [ transaction(id: "tx_hold", hold: true) ])+ MonobankAccount::Transactions::Processor.new(@monobank_account).process++ entry = @account.entries.find_by(external_id: "monobank_tx_hold")+ entry.update!(excluded: true)+ entry.mark_user_modified!++ @monobank_account.update!(raw_transactions_payload: [ unrelated_transaction ])+ result = MonobankAccount::Transactions::Processor.new(@monobank_account).process++ assert_equal 0, result[:pruned_pending]+ assert_equal 1, result[:protected_pending]+ assert Entry.exists?(entry.id), "a user-owned entry must never be hard-deleted by the prune"+ assert_empty pending_entries, "it is no longer held, so the pending flag is gone"+ end++ private++ def transaction(id:, mcc: 5411, hold: false, amount: -4_000)+ {+ "id" => id,+ "account_id" => "acc_1",+ "time" => MIDDAY_UNIX,+ "description" => "Сільпо",+ "mcc" => mcc,+ "hold" => hold,+ "amount" => amount,+ "operationAmount" => amount,+ "currencyCode" => 980+ }+ end++ # A record that cannot be mistaken for the settled half of the hold above: neither+ # the amount nor the description matches, so no reconciliation claims it.+ def unrelated_transaction+ transaction(id: "tx_other", amount: -12_345).merge("description" => "Нова пошта")+ end++ def pending_entries+ @account.entries+ .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'")+ .where(source: "monobank")+ .where("(transactions.extra -> 'monobank' ->> 'pending')::boolean = true")+ end+enddiff --git a/test/models/monobank_account_test.rb b/test/models/monobank_account_test.rbnew file mode 100644index 0000000000..5951118ef5--- /dev/null+++ b/test/models/monobank_account_test.rb@@ -0,0 +1,98 @@+require "test_helper"++class MonobankAccountTest < ActiveSupport::TestCase+ setup do+ @family = families(:empty)+ @monobank_item = MonobankItem.create!(family: @family, name: "Test Monobank", access_token: "mono-token")+ end++ test "needs_setup excludes linked and ignored accounts" do+ unlinked = MonobankAccount.create!(monobank_item: @monobank_item, name: "Unlinked", account_id: "acc_unlinked", currency: "UAH")+ ignored = MonobankAccount.create!(monobank_item: @monobank_item, name: "Skipped", account_id: "acc_ignored", currency: "UAH", ignored: true)++ linked = MonobankAccount.create!(monobank_item: @monobank_item, name: "Linked", account_id: "acc_linked", currency: "UAH")+ account = Account.create!(family: @family, name: "Linked", accountable: Depository.new(subtype: "checking"), balance: 0, currency: "UAH")+ AccountProvider.create!(account: account, provider: linked)++ needs_setup = @monobank_item.monobank_accounts.needs_setup++ assert_includes needs_setup, unlinked+ assert_not_includes needs_setup, ignored+ assert_not_includes needs_setup, linked+ assert_equal 1, @monobank_item.unlinked_accounts_count+ end++ # Monobank reports a card's balance *including* its credit limit, so own funds are+ # balance - creditLimit, and both arrive in minor units.+ test "card snapshot subtracts the credit limit and converts minor units" do+ monobank_account = MonobankAccount.new(monobank_item: @monobank_item, account_id: "acc_black")++ monobank_account.upsert_monobank_snapshot!(+ {+ "id" => "acc_black",+ "kind" => "card",+ "type" => "black",+ "balance" => 150_00,+ "creditLimit" => 100_00,+ "currencyCode" => 980,+ "maskedPan" => [ "537541******1234" ],+ "iban" => "UA-TEST-IBAN-SNAPSHOT"+ }+ )++ assert_equal BigDecimal("50"), monobank_account.current_balance+ assert_equal BigDecimal("100"), monobank_account.credit_limit+ assert_equal "UAH", monobank_account.currency+ assert_equal "black", monobank_account.account_type+ assert_equal "card", monobank_account.account_kind+ assert_equal "537541******1234", monobank_account.masked_pan+ assert_equal "Depository", monobank_account.suggested_account_type+ assert_equal "checking", monobank_account.suggested_subtype+ end++ test "card name combines the localized product name with the last four digits" do+ monobank_account = MonobankAccount.new(monobank_item: @monobank_item, account_id: "acc_white")++ monobank_account.upsert_monobank_snapshot!(+ { "id" => "acc_white", "kind" => "card", "type" => "white", "balance" => 0, "currencyCode" => 980, "maskedPan" => [ "444111******9876" ] }+ )++ assert_equal "White card ·9876", monobank_account.name+ end++ test "unknown card types still produce a name and no type suggestion" do+ monobank_account = MonobankAccount.new(monobank_item: @monobank_item, account_id: "acc_new")++ monobank_account.upsert_monobank_snapshot!(+ { "id" => "acc_new", "kind" => "card", "type" => "titanium", "balance" => 0, "currencyCode" => 980 }+ )++ assert_equal "Monobank card", monobank_account.name+ assert_nil monobank_account.suggested_account_type+ end++ test "jar snapshot uses its title and maps to savings" do+ monobank_account = MonobankAccount.new(monobank_item: @monobank_item, account_id: "jar_1")++ monobank_account.upsert_monobank_snapshot!(+ { "id" => "jar_1", "kind" => "jar", "title" => "На тепловізор", "balance" => 10_000_00, "currencyCode" => 980, "goal" => 100_000_00 }+ )++ assert_equal "На тепловізор", monobank_account.name+ assert monobank_account.jar?+ assert_equal "jar", monobank_account.account_type+ assert_equal BigDecimal("10000"), monobank_account.current_balance+ assert_equal "savings", monobank_account.suggested_subtype+ end++ test "non-UAH accounts resolve their currency from the ISO numeric code" do+ monobank_account = MonobankAccount.new(monobank_item: @monobank_item, account_id: "acc_usd")++ monobank_account.upsert_monobank_snapshot!(+ { "id" => "acc_usd", "kind" => "card", "type" => "black", "balance" => 5_00, "currencyCode" => 840 }+ )++ assert_equal "USD", monobank_account.currency+ assert_equal BigDecimal("5"), monobank_account.current_balance+ end+enddiff --git a/test/models/monobank_entry/processor_test.rb b/test/models/monobank_entry/processor_test.rbnew file mode 100644index 0000000000..b91b8add35--- /dev/null+++ b/test/models/monobank_entry/processor_test.rb@@ -0,0 +1,140 @@+require "test_helper"++class MonobankEntry::ProcessorTest < ActiveSupport::TestCase+ # 2026-01-09 12:00:00 UTC — mid-day so the date does not depend on the family zone.+ MIDDAY_UNIX = 1_767_960_000++ setup do+ @family = families(:empty)+ @family.update!(timezone: "Europe/Kyiv")+ @monobank_item = MonobankItem.create!(family: @family, name: "Test Monobank", access_token: "mono-token")+ @monobank_account = MonobankAccount.create!(+ monobank_item: @monobank_item,+ name: "Black card ·1234",+ account_id: "acc_1",+ currency: "UAH"+ )+ @account = Account.create!(+ family: @family,+ name: "Card",+ accountable: Depository.new(subtype: "checking"),+ balance: 1000,+ currency: "UAH"+ )++ AccountProvider.create!(account: @account, provider: @monobank_account)+ end++ test "imports a settled transaction with minor-unit and sign conversion" do+ entry = process(+ id: "tx_123",+ time: MIDDAY_UNIX,+ description: "Coffee Shop",+ mcc: 5812,+ originalMcc: 5812,+ hold: false,+ amount: -12_500,+ operationAmount: -12_500,+ currencyCode: 980,+ commissionRate: 0,+ cashbackAmount: 1_900,+ balance: 100_500_00,+ comment: "За каву",+ receiptId: "XXXX-XXXX-XXXX-XXXX"+ )++ assert_equal "monobank_tx_123", entry.external_id+ assert_equal "monobank", entry.source+ # Monobank reports -12500 kopiykas out; Sure stores an expense as positive 125.00.+ assert_equal BigDecimal("125"), entry.amount+ assert_equal "UAH", entry.currency+ assert_equal Date.new(2026, 1, 9), entry.date+ assert_equal "Coffee Shop", entry.name+ assert_equal "За каву", entry.notes+ assert_equal "Coffee Shop", entry.entryable.merchant.name++ extra = entry.entryable.extra["monobank"]+ assert_equal false, extra["pending"]+ assert_equal 5812, extra["mcc"]+ assert_equal "100500.0", extra["balance_after"].to_s+ assert_equal "19.0", extra["cashback_amount"].to_s+ assert_nil extra["operation_amount"], "no FX metadata when the amounts agree"+ end++ test "income keeps the inverted sign" do+ entry = process(id: "tx_in", time: MIDDAY_UNIX, description: "Зарплата", amount: 25_000_00, operationAmount: 25_000_00, currencyCode: 980, hold: false)++ assert_equal BigDecimal("-25000"), entry.amount+ end++ test "marks held transactions as pending" do+ entry = process(id: "tx_hold", time: MIDDAY_UNIX, description: "Pending auth", amount: -800, operationAmount: -800, currencyCode: 980, hold: true)++ assert entry.entryable.pending?+ assert_equal true, entry.entryable.extra.dig("monobank", "pending")+ end++ # The operation currency is not reported by Monobank, so only the raw operation amount+ # is recorded — fx_from/fx_amount are deliberately left unset.+ test "records the operation amount for a foreign-currency purchase" do+ entry = process(id: "tx_fx", time: MIDDAY_UNIX, description: "Steam", amount: -41_500, operationAmount: -1_000, currencyCode: 980, hold: false)++ extra = entry.entryable.extra["monobank"]+ assert_equal(-1_000, extra["operation_amount"])+ assert_nil extra["fx_from"]+ end++ test "stores counterparty details for business account transfers" do+ entry = process(+ id: "tx_fop",+ time: MIDDAY_UNIX,+ description: "ТОВ «ВОРОНА»",+ amount: 500_00,+ operationAmount: 500_00,+ currencyCode: 980,+ hold: false,+ counterEdrpou: "3096889974",+ counterIban: "UA-TEST-IBAN-COUNTERPARTY",+ counterName: "ТОВ «ВОРОНА»"+ )++ extra = entry.entryable.extra["monobank"]+ assert_equal "3096889974", extra["counter_edrpou"]+ assert_equal "UA-TEST-IBAN-COUNTERPARTY", extra["counter_iban"]+ end++ test "non-UAH accounts convert using their own minor units" do+ @monobank_account.update!(currency: "USD")+ @account.update!(currency: "USD")++ entry = process(id: "tx_usd", time: MIDDAY_UNIX, description: "Hosting", amount: -1_050, operationAmount: -1_050, currencyCode: 840, hold: false)++ assert_equal BigDecimal("10.5"), entry.amount+ assert_equal "USD", entry.currency+ end++ test "raises when the transaction has no timestamp" do+ assert_raises ArgumentError do+ process(id: "tx_no_time", description: "Broken", amount: -100, currencyCode: 980, hold: false)+ end+ end++ test "id-less transactions fall back to a content hash so they still deduplicate" do+ data = { "account_id" => "acc_1", "time" => MIDDAY_UNIX, "amount" => -100, "description" => "No id" }++ first = MonobankEntry::Processor.canonical_external_id(data)+ second = MonobankEntry::Processor.canonical_external_id(data.dup)++ assert_equal first, second+ assert first.start_with?("monobank_pending_")+ end++ private++ def process(**transaction_data)+ MonobankEntry::Processor.new(+ transaction_data.deep_stringify_keys,+ monobank_account: @monobank_account+ ).process+ end+enddiff --git a/test/models/monobank_item/importer_test.rb b/test/models/monobank_item/importer_test.rbnew file mode 100644index 0000000000..331506d633--- /dev/null+++ b/test/models/monobank_item/importer_test.rb@@ -0,0 +1,492 @@+require "test_helper"++class MonobankItem::ImporterTest < ActiveSupport::TestCase+ MIDDAY_UNIX = 1_767_960_000++ class FakeMonobankProvider+ attr_reader :statement_calls, :client_info_calls++ def initialize(accounts: nil, jars: nil, statements: nil, statement_error: nil, statement_error_after: 0)+ @statement_calls = []+ @client_info_calls = 0+ @accounts = accounts+ @jars = jars+ @statements = statements+ @statement_error = statement_error+ # Lets a test fail only the backward window: the first N statement requests+ # succeed, everything after that raises.+ @statement_error_after = statement_error_after+ end++ def get_client_info+ @client_info_calls += 1++ {+ "clientId" => "client_1",+ "name" => "Іван Мазепа",+ "accounts" => @accounts || [ default_account ],+ "jars" => @jars || []+ }.with_indifferent_access+ end++ # Mirrors Provider::Monobank#get_accounts: cards and jars in one list, tagged by kind.+ def get_accounts(client_info: nil)+ payload = (client_info || get_client_info).with_indifferent_access++ Array(payload[:accounts]).map { |a| a.merge(kind: "card") } ++ Array(payload[:jars]).map { |j| j.merge(kind: "jar") }+ end++ def get_statement(account_id:, from:, to: nil)+ @statement_calls << { account_id: account_id, from: from, to: to }+ raise @statement_error if @statement_error && @statement_calls.count > @statement_error_after++ @statements || [ settled_transaction ]+ end++ private++ def default_account+ {+ "id" => "acc_1",+ "type" => "black",+ "balance" => 150_00,+ "creditLimit" => 100_00,+ "currencyCode" => 980,+ "maskedPan" => [ "537541******1234" ]+ }+ end++ def settled_transaction+ {+ "id" => "tx_1",+ "time" => MIDDAY_UNIX,+ "description" => "Сільпо",+ "mcc" => 5411,+ "hold" => false,+ "amount" => -4_000,+ "operationAmount" => -4_000,+ "currencyCode" => 980+ }+ end+ end++ setup do+ @family = families(:empty)+ @family.update!(timezone: "Europe/Kyiv")+ @monobank_item = MonobankItem.create!(family: @family, name: "Test Monobank", access_token: "mono-token")+ @monobank_account = MonobankAccount.create!(+ monobank_item: @monobank_item,+ name: "Old name",+ account_id: "acc_1",+ currency: "UAH"+ )+ @account = Account.create!(+ family: @family,+ name: "Card",+ accountable: Depository.new(subtype: "checking"),+ balance: 0,+ currency: "UAH"+ )+ AccountProvider.create!(account: @account, provider: @monobank_account)+ end++ test "imports the account snapshot and stores the statement" do+ provider = FakeMonobankProvider.new++ result = MonobankItem::Importer.new(@monobank_item, monobank_provider: provider).import++ assert result[:success]+ assert_equal 1, result[:accounts_updated]+ assert_equal 1, result[:transactions_imported]+ assert_equal 1, provider.client_info_calls, "client-info is fetched once per sync"++ @monobank_account.reload+ assert_equal "Black card ·1234", @monobank_account.name+ assert_equal BigDecimal("50"), @monobank_account.current_balance+ assert_equal [ "tx_1" ], @monobank_account.raw_transactions_payload.map { |tx| tx["id"] }+ assert_not_nil @monobank_account.statement_synced_through+ assert_not_nil @monobank_account.history_synced_from+ end++ test "does not persist the client's personal name" do+ MonobankItem::Importer.new(@monobank_item, monobank_provider: FakeMonobankProvider.new).import++ @monobank_item.reload+ assert_equal "client_1", @monobank_item.institution_id+ assert_nil @monobank_item.raw_payload["name"]+ end++ test "discovers jars as unlinked accounts awaiting setup" do+ provider = FakeMonobankProvider.new(+ jars: [ { "id" => "jar_1", "title" => "На тепловізор", "balance" => 5_000_00, "currencyCode" => 980, "goal" => 10_000_00 } ]+ )++ result = MonobankItem::Importer.new(@monobank_item, monobank_provider: provider).import++ assert_equal 1, result[:accounts_created]+ jar = @monobank_item.monobank_accounts.find_by(account_id: "jar_1")+ assert jar.jar?+ assert_includes @monobank_item.monobank_accounts.needs_setup, jar+ end++ # The forward window must always re-read the last few days so an unsettled hold stays+ # in the payload instead of being pruned as stale.+ test "forward window always re-covers the pending lookback period" do+ @monobank_account.update!(statement_synced_through: Time.current)+ provider = FakeMonobankProvider.new++ MonobankItem::Importer.new(@monobank_item, monobank_provider: provider).import++ call = provider.statement_calls.first+ lookback_days = Rails.configuration.x.monobank.pending_lookback_days+ assert_in_delta lookback_days, (Time.current - call[:from]) / 1.day, 0.1+ end++ test "walks older history backwards one window at a time" do+ @monobank_item.update!(sync_start_date: 120.days.ago.to_date)+ @monobank_account.update!(+ statement_synced_through: Time.current,+ history_synced_from: 60.days.ago.to_date+ )+ provider = FakeMonobankProvider.new++ MonobankItem::Importer.new(@monobank_item, monobank_provider: provider).import++ assert_equal 2, provider.statement_calls.count, "one forward window plus one history window"++ history_call = provider.statement_calls.last+ assert_equal 60.days.ago.to_date.in_time_zone, history_call[:to]+ assert_equal 60.days.ago.to_date.in_time_zone - Provider::Monobank::MAX_STATEMENT_WINDOW, history_call[:from]++ # The cursor records exactly what was requested, to the second: rounding it down to+ # a date would claim the untouched first 23 hours of that day as covered.+ @monobank_account.reload+ assert_equal history_call[:from], @monobank_account.history_synced_from+ end++ # Each backward step starts where the previous one stopped. Monobank's window is 31+ # days *plus an hour*, so a step rarely lands on midnight; a day-granular cursor left+ # a 23-hour hole at every boundary.+ test "consecutive history windows are contiguous" do+ @monobank_item.update!(sync_start_date: 200.days.ago.to_date)+ @monobank_account.update!(+ statement_synced_through: Time.current,+ history_synced_from: 60.days.ago.to_date+ )++ first = FakeMonobankProvider.new+ MonobankItem::Importer.new(@monobank_item, monobank_provider: first).import++ second = FakeMonobankProvider.new+ MonobankItem::Importer.new(@monobank_item, monobank_provider: second).import++ assert_equal first.statement_calls.last[:from], second.statement_calls.last[:to],+ "the second window must resume exactly where the first one stopped"+ end++ # A window wider than Monobank's 31-day cap gets clamped, so the interval between the+ # old cursor and the clamped start is never requested. It has to be handed to the+ # backward walk instead of being reported as covered by both cursors.+ test "a clamped forward window hands the skipped interval to the history walk" do+ MonobankItem::Importer.stubs(:max_statement_requests_per_sync).returns(1)+ @monobank_item.update!(sync_start_date: 200.days.ago.to_date)+ @monobank_account.update!(+ statement_synced_through: 40.days.ago,+ history_synced_from: 200.days.ago.to_date+ )+ provider = FakeMonobankProvider.new++ MonobankItem::Importer.new(@monobank_item, monobank_provider: provider).import++ requested_from = provider.statement_calls.first[:from]+ assert_operator requested_from, :>, 40.days.ago, "the window was clamped to the 31 day cap"++ @monobank_account.reload+ assert_equal requested_from.floor(6), @monobank_account.history_synced_from,+ "the interval the clamp skipped has to be re-walked from below"+ end++ test "stops backfilling once the configured start date is reached" do+ @monobank_item.update!(sync_start_date: 45.days.ago.to_date)+ @monobank_account.update!(+ statement_synced_through: Time.current,+ history_synced_from: 45.days.ago.to_date+ )+ provider = FakeMonobankProvider.new++ MonobankItem::Importer.new(@monobank_item, monobank_provider: provider).import++ assert_equal 1, provider.statement_calls.count, "history is already covered"+ end++ # Each statement request costs a minute of throttled waiting, so a sync spends a fixed+ # budget and leaves the rest for the next run.+ test "defers accounts that do not fit in the statement request budget" do+ second_account = MonobankAccount.create!(+ monobank_item: @monobank_item, name: "Second", account_id: "acc_2", currency: "UAH"+ )+ other = Account.create!(+ family: @family, name: "Second card",+ accountable: Depository.new(subtype: "checking"), balance: 0, currency: "UAH"+ )+ AccountProvider.create!(account: other, provider: second_account)++ MonobankItem::Importer.stubs(:max_statement_requests_per_sync).returns(1)+ provider = FakeMonobankProvider.new(+ accounts: [+ { "id" => "acc_1", "type" => "black", "balance" => 0, "currencyCode" => 980 },+ { "id" => "acc_2", "type" => "white", "balance" => 0, "currencyCode" => 980 }+ ]+ )++ result = MonobankItem::Importer.new(@monobank_item, monobank_provider: provider).import++ assert_equal 1, provider.statement_calls.count+ assert_equal 1, result[:accounts_skipped]+ assert result[:success], "a deferred account is not a failure"+ end++ # A statement response that hits Monobank's per-response item cap only covers part of+ # the window. Coverage that is still contiguous with what was already stored must not+ # throw away backfill progress.+ test "a truncated window keeps existing backfill progress when coverage stays contiguous" do+ MonobankItem::Importer.stubs(:max_statement_requests_per_sync).returns(1)+ @monobank_account.update!(+ statement_synced_through: 1.day.ago,+ history_synced_from: 100.days.ago.to_date+ )+ provider = FakeMonobankProvider.new(statements: full_page(oldest: 2.days.ago))++ MonobankItem::Importer.new(@monobank_item, monobank_provider: provider).import++ @monobank_account.reload+ assert_equal 100.days.ago.to_date.in_time_zone, @monobank_account.history_synced_from+ end++ test "a truncated window moves the history cursor up when it leaves a gap" do+ MonobankItem::Importer.stubs(:max_statement_requests_per_sync).returns(1)+ # Bound once: evaluating 10.days.ago separately for the fixture and the assertion+ # races the wall clock and disagrees by a second whenever the two calls straddle a+ # second boundary.+ oldest = 10.days.ago+ @monobank_item.update!(sync_start_date: 31.days.ago.to_date)+ provider = FakeMonobankProvider.new(statements: full_page(oldest: oldest))++ MonobankItem::Importer.new(@monobank_item, monobank_provider: provider).import++ @monobank_account.reload+ assert_equal Time.at(oldest.to_i), @monobank_account.history_synced_from,+ "the gap below the oldest record received has to be re-walked, from its exact time"+ end++ test "treats a rate limit as a skip rather than a failure" do+ provider = FakeMonobankProvider.new(+ statement_error: Provider::Monobank::RateLimitError.new("throttled", failure_code: :rate_limited)+ )++ result = MonobankItem::Importer.new(@monobank_item, monobank_provider: provider).import++ assert result[:success]+ assert_equal 1, result[:accounts_skipped]+ assert_equal 0, result[:transactions_failed]+ @monobank_item.reload+ assert @monobank_item.good?, "throttling must not mark the connection as needing attention"+ end++ # fetch_window captures provider errors itself. What lands in the outer rescue is a+ # persistence failure, which used to increment a counter and leave nothing an operator+ # could find in /settings/debug.+ test "a failure while storing a statement is captured in the debug log" do+ provider = FakeMonobankProvider.new+ MonobankItem::Importer.any_instance.stubs(:store_transactions).raises(StandardError, "cursor would not save")++ result = nil+ assert_difference "DebugLogEntry.count", 1 do+ result = MonobankItem::Importer.new(@monobank_item, monobank_provider: provider).import+ end++ assert_equal 1, result[:transactions_failed]++ entry = DebugLogEntry.order(:created_at).last+ assert_equal "monobank", entry.provider_key+ assert_equal @family, entry.family+ assert_equal @monobank_account.account_provider, entry.account_provider+ assert_equal "StandardError", entry.metadata["error_class"]+ end++ # An unauthorized response flips the connection to requires_update. If that update+ # fails, the connection keeps rendering as healthy, so the failure must reach+ # /settings/debug rather than only the application log.+ test "a failure while flagging the connection for re-authorization is captured in the debug log" do+ importer = MonobankItem::Importer.new(@monobank_item, monobank_provider: FakeMonobankProvider.new)+ @monobank_item.stubs(:update!).raises(ActiveRecord::RecordInvalid)++ assert_difference "DebugLogEntry.count", 1 do+ assert_nothing_raised { importer.send(:mark_requires_update!) }+ end++ entry = DebugLogEntry.order(:created_at).last+ assert_equal "monobank", entry.provider_key+ assert_equal @family, entry.family+ assert_equal "ActiveRecord::RecordInvalid", entry.metadata["error_class"]+ end++ test "a hard failure on the history window is reported rather than swallowed" do+ MonobankItem::Importer.stubs(:max_statement_requests_per_sync).returns(2)+ @monobank_item.update!(sync_start_date: 90.days.ago.to_date)+ @monobank_account.update!(history_synced_from: 40.days.ago)+ provider = FakeMonobankProvider.new(+ statement_error: Provider::Monobank::Error.new("boom", failure_code: :server_error),+ statement_error_after: 1+ )++ result = MonobankItem::Importer.new(@monobank_item, monobank_provider: provider).import++ assert_equal 2, provider.statement_calls.count, "the backward window must still be attempted"+ assert_equal 1, result[:transactions_failed],+ "configured history was not fetched, so the sync cannot report success"+ assert_equal 0, result[:accounts_skipped], "a server error is not a soft skip"+ end++ test "a hard failure on the history window still persists the forward window" do+ MonobankItem::Importer.stubs(:max_statement_requests_per_sync).returns(2)+ @monobank_item.update!(sync_start_date: 90.days.ago.to_date)+ @monobank_account.update!(history_synced_from: 40.days.ago)+ provider = FakeMonobankProvider.new(+ statement_error: Provider::Monobank::Error.new("boom", failure_code: :server_error),+ statement_error_after: 1+ )++ MonobankItem::Importer.new(@monobank_item, monobank_provider: provider).import++ @monobank_account.reload+ assert @monobank_account.raw_transactions_payload.present?,+ "new activity already in hand must not be thrown away because the backfill failed"+ end++ test "a rate limit on the history window stays a success" do+ MonobankItem::Importer.stubs(:max_statement_requests_per_sync).returns(2)+ @monobank_item.update!(sync_start_date: 90.days.ago.to_date)+ @monobank_account.update!(history_synced_from: 40.days.ago)+ provider = FakeMonobankProvider.new(+ statement_error: Provider::Monobank::RateLimitError.new("throttled", failure_code: :rate_limited),+ statement_error_after: 1+ )++ result = MonobankItem::Importer.new(@monobank_item, monobank_provider: provider).import++ assert result[:success], "the backfill just resumes next sync, exactly as on budget exhaustion"+ assert_equal 0, result[:transactions_failed]+ end++ test "marks the connection as requiring update when the token is rejected" do+ provider = FakeMonobankProvider.new+ provider.stubs(:get_client_info).raises(+ Provider::Monobank::Error.new("Invalid Monobank access token", failure_code: :unauthorized)+ )++ result = MonobankItem::Importer.new(@monobank_item, monobank_provider: provider).import++ assert_not result[:success]+ assert @monobank_item.reload.requires_update?+ end++ test "keeps settled history but drops holds that disappear from the latest window" do+ hold = { "id" => "tx_hold", "time" => MIDDAY_UNIX, "description" => "Hold", "hold" => true, "amount" => -800, "operationAmount" => -800, "currencyCode" => 980 }+ settled = { "id" => "tx_settled", "time" => MIDDAY_UNIX, "description" => "Settled", "hold" => false, "amount" => -800, "operationAmount" => -800, "currencyCode" => 980 }++ MonobankItem::Importer.new(@monobank_item, monobank_provider: FakeMonobankProvider.new(statements: [ hold ])).import+ assert_equal [ "tx_hold" ], @monobank_account.reload.raw_transactions_payload.map { |tx| tx["id"] }++ MonobankItem::Importer.new(@monobank_item, monobank_provider: FakeMonobankProvider.new(statements: [ settled ])).import++ stored_ids = @monobank_account.reload.raw_transactions_payload.map { |tx| tx["id"] }+ assert_equal [ "tx_settled" ], stored_ids, "the hold is gone, the settled record remains"+ end++ # A pre-authorization (hotel, car hire, fuel) can stay held for longer than the+ # pending lookback, so the window has to keep reaching back to it. Otherwise the hold+ # simply leaves the payload and its entry is pruned while the funds are still blocked.+ test "the forward window reaches back to the oldest hold still on file" do+ hold = held_transaction(id: "tx_hotel", at: 7.days.ago)+ @monobank_account.update!(+ raw_transactions_payload: [ hold ],+ statement_synced_through: 1.hour.ago,+ history_synced_from: 31.days.ago.to_date+ )+ # Monobank still reports the hold, because it is still unsettled.+ provider = FakeMonobankProvider.new(statements: [ hold ])++ MonobankItem::Importer.new(@monobank_item, monobank_provider: provider).import++ assert_operator provider.statement_calls.first[:from], :<=, Time.at(hold["time"]),+ "the forward window must cover the oldest hold still stored"+ assert_equal [ "tx_hotel" ], @monobank_account.reload.raw_transactions_payload.map { |tx| tx["id"] }+ end++ # A response at the item cap only accounts for its newest part, so a hold below that+ # point was not reported on because Monobank was never asked, not because it settled.+ test "keeps a hold the truncated response never reached" do+ hold = held_transaction(id: "tx_hotel", at: 5.days.ago)+ @monobank_account.update!(+ raw_transactions_payload: [ hold ],+ statement_synced_through: 1.hour.ago,+ history_synced_from: 31.days.ago.to_date+ )+ MonobankItem::Importer.stubs(:max_statement_requests_per_sync).returns(1)+ provider = FakeMonobankProvider.new(statements: full_page(oldest: 1.day.ago))++ MonobankItem::Importer.new(@monobank_item, monobank_provider: provider).import++ stored_ids = @monobank_account.reload.raw_transactions_payload.map { |tx| tx["id"] }+ assert_includes stored_ids, "tx_hotel", "the hold is still blocking funds upstream"+ end++ # Monobank throttles client-info to one request per minute and the timer is per client+ # instance, so a manual sync landing in the same minute as a scheduled one collides+ # legitimately. That is a deferral, not a broken connection.+ test "treats a throttled client-info as a skip rather than a failure" do+ provider = FakeMonobankProvider.new+ provider.stubs(:get_client_info).raises(+ Provider::Monobank::RateLimitError.new("throttled", failure_code: :rate_limited)+ )++ result = MonobankItem::Importer.new(@monobank_item, monobank_provider: provider).import++ assert result[:success], "throttling must not fail the sync"+ assert_equal 1, result[:accounts_skipped]+ assert_equal 0, result[:accounts_failed]+ assert @monobank_item.reload.good?, "throttling must not mark the connection as needing attention"+ end++ private++ # An unsettled authorization at +at+.+ def held_transaction(id:, at:)+ {+ "id" => id,+ "time" => at.to_i,+ "description" => "Hotel",+ "hold" => true,+ "amount" => -50_000,+ "operationAmount" => -50_000,+ "currencyCode" => 980+ }+ end++ # A response at Monobank's per-response item cap, oldest record at +oldest+.+ def full_page(oldest:)+ Array.new(Provider::Monobank::MAX_STATEMENT_ITEMS) do |index|+ {+ "id" => "tx_page_#{index}",+ "time" => (oldest + index.minutes).to_i,+ "description" => "Purchase #{index}",+ "hold" => false,+ "amount" => -100,+ "operationAmount" => -100,+ "currencyCode" => 980+ }+ end+ end+enddiff --git a/test/models/provider/monobank_test.rb b/test/models/provider/monobank_test.rbnew file mode 100644index 0000000000..db8434aabc--- /dev/null+++ b/test/models/provider/monobank_test.rb@@ -0,0 +1,109 @@+require "test_helper"++class Provider::MonobankTest < ActiveSupport::TestCase+ FakeResponse = Struct.new(:code, :body, :message, keyword_init: true)++ test "sends the personal token in X-Token and returns the statement window" do+ requests = []+ response = FakeResponse.new(+ code: 200,+ message: "OK",+ body: [ { id: "tx_1", time: 1_767_960_000, hold: false, amount: -4_000 } ].to_json+ )++ Provider::Monobank.stub(:get, ->(url, headers:, query: nil) {+ requests << { url: url, headers: headers }+ response+ }) do+ transactions = Provider::Monobank.new("mono-token").get_statement(+ account_id: "acc_1",+ from: Time.at(1_767_800_000),+ to: Time.at(1_767_960_000)+ )++ assert_equal [ "tx_1" ], transactions.map { |tx| tx[:id] }+ assert_equal [ "acc_1" ], transactions.map { |tx| tx[:account_id] }+ end++ assert_equal 1, requests.size+ assert_equal "https://api.monobank.ua/personal/statement/acc_1/1767800000/1767960000", requests.first[:url]+ assert_equal "mono-token", requests.first[:headers]["X-Token"]+ end++ # A statement is documented as a JSON array. A 204, an empty body or an error object+ # must not read as "no activity": the caller would record the window as permanently+ # covered and never ask again.+ test "rejects a statement response that is not an array" do+ [ "", "{\"errorDescription\":\"too many requests\"}" ].each do |body|+ Provider::Monobank.stub(:get, ->(_url, headers:, query: nil) {+ FakeResponse.new(code: 200, message: "OK", body: body)+ }) do+ error = assert_raises(Provider::Monobank::Error) do+ Provider::Monobank.new("mono-token").get_statement(+ account_id: "acc_1",+ from: Time.at(1_767_800_000),+ to: Time.at(1_767_960_000)+ )+ end++ assert_equal :parse_error, error.failure_code+ end+ end+ end++ # Transport failures are the ones the importer never sees in detail: it catches a+ # typed error and records the connection, but the HTTP status and the fact that the+ # body was unparseable only exist inside the client.+ test "records an unexpected response status in the debug log" do+ Provider::Monobank.stub(:get, ->(_url, headers:, query: nil) {+ FakeResponse.new(code: 418, message: "I'm a teapot", body: "")+ }) do+ assert_difference "DebugLogEntry.count", 1 do+ error = assert_raises(Provider::Monobank::Error) do+ Provider::Monobank.new("mono-token").get_client_info+ end++ assert_equal :fetch_failed, error.failure_code+ end+ end++ entry = DebugLogEntry.order(:created_at).last+ assert_equal "monobank", entry.provider_key+ assert_equal "error", entry.level+ assert_equal 418, entry.metadata["status"]+ assert_equal "GET /personal/client-info", entry.metadata["operation"]+ end++ test "records an unparseable response body in the debug log without the body itself" do+ body = "<html>not json</html>"++ Provider::Monobank.stub(:get, ->(_url, headers:, query: nil) {+ FakeResponse.new(code: 200, message: "OK", body: body)+ }) do+ assert_difference "DebugLogEntry.count", 1 do+ error = assert_raises(Provider::Monobank::Error) do+ Provider::Monobank.new("mono-token").get_client_info+ end++ assert_equal :parse_error, error.failure_code+ end+ end++ entry = DebugLogEntry.order(:created_at).last+ assert_equal "monobank", entry.provider_key+ assert_equal body.bytesize, entry.metadata["body_bytes"]+ refute_includes entry.metadata.to_s, "not json"+ end++ test "refuses a window wider than Monobank's cap" do+ error = assert_raises(Provider::Monobank::Error) do+ Provider::Monobank.new("mono-token").get_statement(+ account_id: "acc_1",+ from: 40.days.ago,+ to: Time.current+ )+ end++ assert_equal :window_too_large, error.failure_code+ end+end