Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(generators): stop provider:family emitting a broken migration and invalid enum (#3047)

markhaines5a0723bb84c8
diff --git a/lib/generators/provider/family/family_generator.rb b/lib/generators/provider/family/family_generator.rb
index e0d5b77550..2162b2f531 100644
--- a/lib/generators/provider/family/family_generator.rb
+++ b/lib/generators/provider/family/family_generator.rb
@@ -30,6 +30,28 @@ require "rails/generators/active_record"
class Provider::FamilyGenerator < Rails::Generators::NamedBase
include Rails::Generators::Migration
+ # Columns the migration template already defines on the items table. A provider whose
+ # API happens to use one of these names (institution_id is the obvious one) would
+ # otherwise emit a duplicate t.string and abort db:migrate with
+ # "you can't define an already defined column".
+ #
+ # Declaring one is rejected rather than silently dropped. parsed_fields feeds eight
+ # other templates (model validations and encryption, panel form inputs, controller
+ # params, locale strings, adapter, SDK), so filtering it out of the migration alone
+ # would leave the field generating a form input and a validation with no column of the
+ # declared type behind it: `institution_id:integer` would render a numeric input over
+ # the built-in string column. Rejecting keeps the generated code self-consistent.
+ #
+ # family_id is listed, family is NOT: the template writes `t.references :family`, which
+ # creates the family_id column, so a field literally named family is not a collision.
+ RESERVED_ITEM_COLUMNS = %w[
+ family_id name
+ institution_id institution_name institution_domain institution_url institution_color
+ status scheduled_for_deletion pending_account_setup
+ sync_start_date raw_payload raw_institution_payload
+ created_at updated_at id
+ ].freeze
+
source_root File.expand_path("templates", __dir__)
argument :fields, type: :array, default: [], banner: "field:type[:secret] field:type[:secret]"
@@ -48,6 +70,15 @@ class Provider::FamilyGenerator < Rails::Generators::NamedBase
say "Warning: No fields specified. You'll need to add them manually later.", :yellow
end
+ reserved = parsed_fields.map { |f| f[:name] } & RESERVED_ITEM_COLUMNS
+ if reserved.any?
+ raise Thor::Error,
+ "#{reserved.join(', ')} #{reserved.one? ? 'is' : 'are'} already provided by the " \
+ "items table. Remove #{reserved.one? ? 'it' : 'them'} from the command: the " \
+ "standard column serves the same purpose, and redeclaring would abort db:migrate " \
+ "with \"you can't define an already defined column\"."
+ end
+
# Validate field types
parsed_fields.each do |field|
unless %w[text string integer boolean].include?(field[:type])
@@ -613,6 +644,48 @@ class Provider::FamilyGenerator < Rails::Generators::NamedBase
ActiveRecord::Generators::Base.next_migration_number(dirname)
end
+ # Appends `name` as the final entry of the `enum :source, { ... }` hash in `content`.
+ # Returns the updated source, or nil when no such hash is present.
+ #
+ # Pure string transformation, extracted from the generator so the comma and
+ # indentation handling can be tested directly. Both are easy to get wrong and fail as
+ # a SyntaxError in an unrelated file rather than anything pointing back here:
+ #
+ # - appending before the closing brace of a MULTI-LINE hash puts the entry on its own
+ # line after Ruby has already ended the expression
+ # - a hash written with a TRAILING COMMA already supplies the separator, so adding
+ # another yields `redbark: "redbark",,`
+ # - an EMPTY hash needs no separator, so adding one yields `{, gocardless: "..."}`
+ def self.append_source_enum_entry(content, name)
+ match = content.match(/(enum :source, \{)([^}]*)(\})/m)
+ return nil unless match
+
+ prefix, body, suffix = match[1], match[2], match[3]
+
+ trailing = body[/\s*\z/] || ""
+ core = body[0...(body.length - trailing.length)]
+ entry = "#{name}: \"#{name}\""
+
+ # A hash written with a trailing comma already supplies the separator, and an empty
+ # hash needs none at all. Emitting one regardless yields `redbark: "redbark",,` or
+ # `{, gocardless: "gocardless"}`: the same class of syntax error this method exists
+ # to prevent.
+ separator = (core.empty? || core.end_with?(",")) ? "" : ","
+
+ new_body =
+ if trailing.include?("\n")
+ # Multi-line: indent to match the last entry, not the closing brace.
+ indent = core[/\n([ \t]*)[^\n]*\z/, 1] || " "
+ "#{core}#{separator}\n#{indent}#{entry}#{trailing}"
+ else
+ "#{core}#{separator} #{entry}#{trailing}"
+ end
+
+ # Block form: a string replacement would interpret any backslash sequence in the
+ # captured hash body as a backreference.
+ content.sub(/(enum :source, \{)([^}]*)(\})/m) { prefix + new_body + suffix }
+ end
+
private
def update_source_enum(model_path)
@@ -627,15 +700,10 @@ class Provider::FamilyGenerator < Rails::Generators::NamedBase
return
end
- # Find the enum :source line and add the new provider
- # Pattern: enum :source, { key: "value", ... }
- if content =~ /(enum :source, \{[^}]+)(})/
- # Insert the new provider before the closing brace
- updated_content = content.sub(
- /(enum :source, \{[^}]+)(})/,
- "\\1, #{file_name}: \"#{file_name}\"\\2"
- )
- write_file(model_path, updated_content)
+ updated = self.class.append_source_enum_entry(content, file_name)
+
+ if updated
+ write_file(model_path, updated)
say "Added #{file_name} to #{model_name} source enum", :green
else
say "Could not find source enum in #{model_name}", :yellow
@@ -811,6 +879,7 @@ class Provider::FamilyGenerator < Rails::Generators::NamedBase
options[:type] == "investment"
end
+
def parsed_fields
@parsed_fields ||= fields.map do |field_def|
# Handle default values with colons (like URLs) by extracting them first
diff --git a/lib/generators/provider/family/templates/item_model.rb.tt b/lib/generators/provider/family/templates/item_model.rb.tt
index 9d4a8e4377..015814ed7e 100644
--- a/lib/generators/provider/family/templates/item_model.rb.tt
+++ b/lib/generators/provider/family/templates/item_model.rb.tt
@@ -35,6 +35,10 @@ class <%= class_name %>Item < ApplicationRecord
scope :active, -> { where(scheduled_for_deletion: false) }
scope :ordered, -> { order(created_at: :desc) }
scope :needs_update, -> { where(status: :requires_update) }
+ # Family::Syncer discovers provider items reflectively and calls `syncable` on every
+ # `*_items` association whose model includes Syncable. Omitting this scope breaks the
+ # whole nightly family sync, not just this provider.
+ scope :syncable, -> { active }
def syncer
<%= class_name %>Item::Syncer.new(self)
diff --git a/lib/generators/provider/family/templates/locale.en.yml.tt b/lib/generators/provider/family/templates/locale.en.yml.tt
index 155c93c181..d15eb4eda5 100644
--- a/lib/generators/provider/family/templates/locale.en.yml.tt
+++ b/lib/generators/provider/family/templates/locale.en.yml.tt
@@ -5,14 +5,14 @@ en:
sync_status:
no_accounts: "No accounts found"
synced:
- one: "%%{count} account synced"
- other: "%%{count} accounts synced"
- synced_with_setup: "%%{linked} synced, %%{unlinked} need setup"
+ one: "%{count} account synced"
+ other: "%{count} accounts synced"
+ synced_with_setup: "%{linked} synced, %{unlinked} need setup"
institution_summary:
none: "No institutions connected"
count:
- one: "%%{count} institution"
- other: "%%{count} institutions"
+ one: "%{count} institution"
+ other: "%{count} institutions"
errors:
provider_not_configured: "<%= class_name %> provider is not configured"
@@ -28,7 +28,7 @@ en:
calculating: "Calculating balances..."
importing_data: "Importing account data..."
checking_setup: "Checking account configuration..."
- needs_setup: "%%{count} accounts need setup..."
+ needs_setup: "%{count} accounts need setup..."
success: "Sync started"
# Panel (settings view)
@@ -40,10 +40,10 @@ en:
field_descriptions: "Field descriptions:"
optional: "(Optional)"
required: "(required)"
- optional_with_default: "(optional, defaults to %%{default_value})"
+ optional_with_default: "(optional, defaults to %{default_value})"
save_button: "Save Configuration"
update_button: "Update Configuration"
- status_configured_html: "Configured and ready to use. Visit the <a href=\"%%{accounts_path}\" class=\"link\">Accounts</a> tab to manage and set up accounts."
+ status_configured_html: "Configured and ready to use. Visit the <a href=\"%{accounts_path}\" class=\"link\">Accounts</a> tab to manage and set up accounts."
status_not_configured: "Not configured"
fields:
<% parsed_fields.each do |field| -%>
@@ -72,20 +72,20 @@ en:
# Account linking
link_accounts:
all_already_linked:
- one: "The selected account (%%{names}) is already linked"
- other: "All %%{count} selected accounts are already linked: %%{names}"
- api_error: "API error: %%{message}"
+ one: "The selected account (%{names}) is already linked"
+ other: "All %{count} selected accounts are already linked: %{names}"
+ api_error: "API error: %{message}"
invalid_account_names:
one: "Cannot link account with blank name"
- other: "Cannot link %%{count} accounts with blank names"
+ other: "Cannot link %{count} accounts with blank names"
link_failed: "Failed to link accounts"
no_accounts_selected: "Please select at least one account"
no_api_key: "<%= class_name %> API key not found. Please configure it in Provider Settings."
- partial_invalid: "Successfully linked %%{created_count} account(s), %%{already_linked_count} were already linked, %%{invalid_count} account(s) had invalid names"
- partial_success: "Successfully linked %%{created_count} account(s). %%{already_linked_count} account(s) were already linked: %%{already_linked_names}"
+ partial_invalid: "Successfully linked %{created_count} account(s), %{already_linked_count} were already linked, %{invalid_count} account(s) had invalid names"
+ partial_success: "Successfully linked %{created_count} account(s). %{already_linked_count} account(s) were already linked: %{already_linked_names}"
success:
- one: "Successfully linked %%{count} account"
- other: "Successfully linked %%{count} accounts"
+ one: "Successfully linked %{count} account"
+ other: "Successfully linked %{count} accounts"
# Provider item display (used in _item partial)
<%= file_name %>_item:
@@ -94,18 +94,18 @@ en:
deletion_in_progress: "deletion in progress..."
error: "Error"
more_accounts_available:
- one: "%%{count} more account available"
- other: "%%{count} more accounts available"
+ one: "%{count} more account available"
+ other: "%{count} more accounts available"
no_accounts_description: "This connection has no linked accounts yet."
no_accounts_title: "No accounts"
provider_name: "<%= class_name %>"
requires_update: "Connection needs update"
setup_action: "Set Up New Accounts"
- setup_description: "%%{linked} of %%{total} accounts linked. Choose account types for your newly imported <%= class_name %> accounts."
+ setup_description: "%{linked} of %{total} accounts linked. Choose account types for your newly imported <%= class_name %> accounts."
setup_needed: "New accounts ready to set up"
- status: "Synced %%{timestamp} ago"
+ status: "Synced %{timestamp} ago"
status_never: "Never synced"
- status_with_summary: "Last synced %%{timestamp} ago - %%{summary}"
+ status_with_summary: "Last synced %{timestamp} ago - %{summary}"
syncing: "Syncing..."
total: "Total"
unlinked: "Unlinked"
@@ -114,10 +114,10 @@ en:
# Select accounts view
select_accounts:
accounts_selected: "accounts selected"
- api_error: "API error: %%{message}"
+ api_error: "API error: %{message}"
cancel: "Cancel"
configure_name_in_provider: "Cannot import - please configure account name in <%= class_name %>"
- description: "Select the accounts you want to link to your %%{product_name} account."
+ description: "Select the accounts you want to link to your %{product_name} account."
link_accounts: "Link selected accounts"
no_accounts_found: "No accounts found. Please check your API key configuration."
no_api_key: "<%= class_name %> API key is not configured. Please configure it in Settings."
@@ -129,7 +129,7 @@ en:
select_existing_account:
account_already_linked: "This account is already linked to a provider"
all_accounts_already_linked: "All <%= class_name %> accounts are already linked"
- api_error: "API error: %%{message}"
+ api_error: "API error: %{message}"
balance_label: "Balance:"
cancel: "Cancel"
cancel_button: "Cancel"
@@ -148,27 +148,27 @@ en:
no_name_placeholder: "(No name)"
settings_link: "Go to Provider Settings"
subtitle: "Choose a <%= class_name %> account"
- title: "Link %%{account_name} with <%= class_name %>"
+ title: "Link %{account_name} with <%= class_name %>"
# Link existing account
link_existing_account:
account_already_linked: "This account is already linked to a provider"
- api_error: "API error: %%{message}"
+ api_error: "API error: %{message}"
invalid_account_name: "Cannot link account with blank name"
provider_account_already_linked: "This <%= class_name %> account is already linked to another account"
provider_account_not_found: "<%= class_name %> account not found"
missing_parameters: "Missing required parameters"
no_api_key: "<%= class_name %> API key not found. Please configure it in Provider Settings."
- success: "Successfully linked %%{account_name} with <%= class_name %>"
+ success: "Successfully linked %{account_name} with <%= class_name %>"
# Setup accounts wizard
setup_accounts:
account_type_label: "Account Type:"
accounts_count:
- one: "%%{count} account available"
- other: "%%{count} accounts available"
+ one: "%{count} account available"
+ other: "%{count} accounts available"
all_accounts_linked: "All your <%= class_name %> accounts have already been set up."
- api_error: "API error: %%{message}"
+ api_error: "API error: %{message}"
creating: "Creating accounts..."
fetch_failed: "Failed to Fetch Accounts"
import_selected: "Import selected accounts"
@@ -249,9 +249,9 @@ en:
# Complete account setup
complete_account_setup:
all_skipped: "All accounts were skipped. No accounts were created."
- creation_failed: "Failed to create accounts: %%{error}"
+ creation_failed: "Failed to create accounts: %{error}"
no_accounts: "No accounts to set up."
- success: "Successfully created %%{count} account(s)."
+ success: "Successfully created %{count} account(s)."
# Preload accounts
preload_accounts:
diff --git a/test/lib/generators/provider/family_generator_test.rb b/test/lib/generators/provider/family_generator_test.rb
new file mode 100644
index 0000000000..0619bf15da
--- /dev/null
+++ b/test/lib/generators/provider/family_generator_test.rb
@@ -0,0 +1,105 @@
+require "test_helper"
+require "generators/provider/family/family_generator"
+
+# Covers the source-enum insertion, which historically emitted invalid Ruby. The failure
+# mode is nasty: the generator reports success, and the damage surfaces later as a
+# SyntaxError in data_enrichment.rb with nothing pointing back at the generator. So each
+# case asserts the result actually PARSES, not just that it looks right.
+class Provider::FamilyGeneratorTest < ActiveSupport::TestCase
+ def append(content)
+ Provider::FamilyGenerator.append_source_enum_entry(content, "gocardless")
+ end
+
+ def assert_parses(source)
+ RubyVM::AbstractSyntaxTree.parse(source)
+ rescue SyntaxError => e
+ flunk "generated invalid Ruby: #{e.message}\n\n#{source}"
+ end
+
+ test "appends to a single-line enum" do
+ result = append(<<~RUBY)
+ class ProviderMerchant < Merchant
+ enum :source, { plaid: "plaid", redbark: "redbark" }
+ end
+ RUBY
+
+ assert_parses result
+ assert_includes result, 'redbark: "redbark", gocardless: "gocardless" }'
+ end
+
+ test "appends to a multiline enum without putting the entry after the expression ends" do
+ result = append(<<~RUBY)
+ class DataEnrichment < ApplicationRecord
+ enum :source, {
+ plaid: "plaid",
+ redbark: "redbark"
+ }
+ end
+ RUBY
+
+ assert_parses result
+ # The comma must attach to the previous entry, and the new entry take its indentation.
+ assert_includes result, %( redbark: "redbark",\n gocardless: "gocardless"\n)
+ end
+
+ test "does not double the comma on a single-line enum with a trailing comma" do
+ result = append('enum :source, { plaid: "plaid", redbark: "redbark", }')
+
+ assert_parses "x = #{result}"
+ assert_not_includes result, ",,"
+ end
+
+ test "does not double the comma on a multiline enum with a trailing comma" do
+ result = append(<<~RUBY)
+ class DataEnrichment < ApplicationRecord
+ enum :source, {
+ plaid: "plaid",
+ redbark: "redbark",
+ }
+ end
+ RUBY
+
+ assert_parses result
+ assert_not_includes result, ",,"
+ assert_includes result, 'gocardless: "gocardless"'
+ end
+
+ test "does not emit a leading comma into an empty single-line enum" do
+ result = append("enum :source, {}")
+
+ assert_parses "x = #{result}"
+ assert_not_includes result, "{,"
+ assert_includes result, 'gocardless: "gocardless"'
+ end
+
+ test "does not emit a leading comma into an empty multiline enum" do
+ result = append(<<~RUBY)
+ class DataEnrichment < ApplicationRecord
+ enum :source, {
+ }
+ end
+ RUBY
+
+ assert_parses result
+ assert_not_includes result, "{,"
+ assert_includes result, 'gocardless: "gocardless"'
+ end
+
+ test "returns nil when there is no source enum to update" do
+ assert_nil append("class Foo < ApplicationRecord\nend\n")
+ end
+
+ test "preserves backslashes in the hash body rather than treating them as backreferences" do
+ result = append(%(enum :source, { plaid: "pl\\\\aid" }))
+
+ assert_includes result, "pl\\\\aid"
+ end
+
+ test "reserved item columns exclude family but include family_id" do
+ # family is created by t.references :family as family_id, so a field named family is
+ # not a collision and must not be rejected.
+ assert_not_includes Provider::FamilyGenerator::RESERVED_ITEM_COLUMNS, "family"
+ assert_includes Provider::FamilyGenerator::RESERVED_ITEM_COLUMNS, "family_id"
+ assert_includes Provider::FamilyGenerator::RESERVED_ITEM_COLUMNS, "institution_id"
+ end
+end