Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
38.1 KB
Raw Blame
require "test_helper"

class RuleImportTest < ActiveSupport::TestCase
  include ActiveJob::TestHelper

  setup do
    @family = families(:dylan_family)
    @category = @family.categories.create!(
      name: "Groceries",
      color: "#407706",
      lucide_icon: "shopping-basket"
    )
    @csv = <<~CSV
      name,resource_type,active,effective_date,conditions,actions
      "Categorize groceries","transaction",true,2024-01-01,"[{\"condition_type\":\"transaction_name\",\"operator\":\"like\",\"value\":\"grocery\"}]","[{\"action_type\":\"set_transaction_category\",\"value\":\"Groceries\"}]"
      "Auto-categorize transactions","transaction",false,,"[{\"condition_type\":\"transaction_amount\",\"operator\":\">\",\"value\":\"100\"}]","[{\"action_type\":\"auto_categorize\"}]"
    CSV
  end

  test "imports rules from CSV" do
    import = @family.imports.create!(type: "RuleImport", raw_file_str: @csv, col_sep: ",")
    import.generate_rows_from_csv
    assert_equal 2, import.rows.count

    assert_difference -> { Rule.where(family: @family).count }, 2 do
      import.send(:import!)
    end

    grocery_rule = Rule.find_by!(family: @family, name: "Categorize groceries")
    auto_rule = Rule.find_by!(family: @family, name: "Auto-categorize transactions")

    assert_equal "transaction", grocery_rule.resource_type
    assert grocery_rule.active
    assert_equal Date.parse("2024-01-01"), grocery_rule.effective_date
    assert_equal 1, grocery_rule.conditions.count
    assert_equal 1, grocery_rule.actions.count

    assert_equal "transaction", auto_rule.resource_type
    assert_not auto_rule.active
    assert_nil auto_rule.effective_date
    assert_equal 1, auto_rule.conditions.count
    assert_equal 1, auto_rule.actions.count
  end

  test "reuses a provider merchant on the family's transactions instead of creating a family merchant" do
    provider_merchant = ProviderMerchant.create!(name: "Synced Coffee", source: "plaid")
    account = @family.accounts.first
    account.entries.create!(name: "Coffee", date: Date.current, amount: 4, currency: "USD", entryable: Transaction.new(merchant: provider_merchant))
    csv = <<~CSV
      name,resource_type,active,effective_date,conditions,actions
      "Coffee","transaction",true,,"[{\"condition_type\":\"transaction_merchant\",\"operator\":\"=\",\"value\":\"Synced Coffee\"}]","[{\"action_type\":\"set_transaction_merchant\",\"value\":\"Synced Coffee\"}]"
    CSV
    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv

    assert_no_difference -> { @family.merchants.count } do
      import.send(:import!)
    end

    rule = Rule.find_by!(family: @family, name: "Coffee")
    assert_equal provider_merchant.id, rule.conditions.first.value
    assert_equal provider_merchant.id, rule.actions.first.value
  end

  test "creates a family merchant for a provider merchant name that is ambiguous or used in a split" do
    account = @family.accounts.first
    [ [ "Shared Name", "plaid" ], [ "Shared Name", "simplefin" ], [ "Split Shop", "plaid" ] ].each do |name, source|
      merchant = ProviderMerchant.create!(name: name, source: source)
      account.entries.create!(name: name, date: Date.current, amount: 4, currency: "USD", entryable: Transaction.new(merchant: merchant))
    end
    split = { splits: [ { type: "percentage", name: "Shop", share: "60", merchant: "Split Shop" }, { type: "percentage", name: "Rest", share: "40" } ] }.to_json
    csv = CSV.generate do |rows|
      rows << %w[name resource_type active effective_date conditions actions]
      rows << [ "Ambiguous", "transaction", "true", "", '[{"condition_type":"transaction_name","operator":"like","value":"x"}]', '[{"action_type":"set_transaction_merchant","value":"Shared Name"}]' ]
      rows << [ "Split", "transaction", "true", "", '[{"condition_type":"transaction_name","operator":"like","value":"y"}]', [ { action_type: "split_transaction", value: JSON.parse(split) } ].to_json ]
    end
    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv
    import.send(:import!)

    assert_equal @family.merchants.find_by!(name: "Shared Name").id, Rule.find_by!(family: @family, name: "Ambiguous").actions.sole.value
    split_merchant_id = JSON.parse(Rule.find_by!(family: @family, name: "Split").actions.sole.value)["splits"].first["merchant_id"]
    assert_equal @family.merchants.find_by!(name: "Split Shop").id, split_merchant_id
  end

  test "imports rule conditions correctly" do
    import = @family.imports.create!(type: "RuleImport", raw_file_str: @csv, col_sep: ",")
    import.generate_rows_from_csv
    import.send(:import!)

    grocery_rule = Rule.find_by!(family: @family, name: "Categorize groceries")
    condition = grocery_rule.conditions.first

    assert_equal "transaction_name", condition.condition_type
    assert_equal "like", condition.operator
    assert_equal "grocery", condition.value
  end

  test "imports rule actions correctly and maps category names to IDs" do
    import = @family.imports.create!(type: "RuleImport", raw_file_str: @csv, col_sep: ",")
    import.generate_rows_from_csv
    import.send(:import!)

    grocery_rule = Rule.find_by!(family: @family, name: "Categorize groceries")
    action = grocery_rule.actions.first

    assert_equal "set_transaction_category", action.action_type
    assert_equal @category.id, action.value
  end

  test "imports compound conditions with sub-conditions" do
    csv = <<~CSV
      name,resource_type,active,effective_date,conditions,actions
      "Complex rule","transaction",true,,"[{\"condition_type\":\"compound\",\"operator\":\"or\",\"sub_conditions\":[{\"condition_type\":\"transaction_name\",\"operator\":\"like\",\"value\":\"walmart\"},{\"condition_type\":\"transaction_name\",\"operator\":\"like\",\"value\":\"target\"}]}]","[{\"action_type\":\"set_transaction_category\",\"value\":\"Groceries\"}]"
    CSV

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv
    import.send(:import!)

    rule = Rule.find_by!(family: @family, name: "Complex rule")
    assert_equal 1, rule.conditions.count

    compound_condition = rule.conditions.first
    assert compound_condition.compound?
    assert_equal "or", compound_condition.operator
    assert_equal 2, compound_condition.sub_conditions.count

    sub_condition_1 = compound_condition.sub_conditions.first
    assert_equal "transaction_name", sub_condition_1.condition_type
    assert_equal "like", sub_condition_1.operator
    assert_equal "walmart", sub_condition_1.value

    sub_condition_2 = compound_condition.sub_conditions.last
    assert_equal "transaction_name", sub_condition_2.condition_type
    assert_equal "like", sub_condition_2.operator
    assert_equal "target", sub_condition_2.value
  end

  test "creates missing categories when importing actions" do
    csv = <<~CSV
      name,resource_type,active,effective_date,conditions,actions
      "New category rule","transaction",true,,"[{\"condition_type\":\"transaction_name\",\"operator\":\"like\",\"value\":\"coffee\"}]","[{\"action_type\":\"set_transaction_category\",\"value\":\"Coffee Shops\"}]"
    CSV

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv

    assert_difference -> { Category.where(family: @family).count }, 1 do
      import.send(:import!)
    end

    new_category = Category.find_by!(family: @family, name: "Coffee Shops")
    assert_equal Category::UNCATEGORIZED_COLOR, new_category.color

    rule = Rule.find_by!(family: @family, name: "New category rule")
    action = rule.actions.first
    assert_equal new_category.id, action.value
  end

  test "creates missing tags when importing actions" do
    csv = <<~CSV
      name,resource_type,active,effective_date,conditions,actions
      "New tag rule","transaction",true,,"[{\"condition_type\":\"transaction_name\",\"operator\":\"like\",\"value\":\"coffee\"}]","[{\"action_type\":\"set_transaction_tags\",\"value\":\"Coffee Tag\"}]"
    CSV

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv

    assert_difference -> { Tag.where(family: @family).count }, 1 do
      import.send(:import!)
    end

    new_tag = Tag.find_by!(family: @family, name: "Coffee Tag")

    rule = Rule.find_by!(family: @family, name: "New tag rule")
    action = rule.actions.first
    assert_equal "set_transaction_tags", action.action_type
    assert_equal new_tag.id, action.value
  end

  test "reuses existing tags when importing actions" do
    existing_tag = @family.tags.create!(name: "Existing Tag")

    csv = <<~CSV
      name,resource_type,active,effective_date,conditions,actions
      "Tag rule","transaction",true,,"[{\"condition_type\":\"transaction_name\",\"operator\":\"like\",\"value\":\"test\"}]","[{\"action_type\":\"set_transaction_tags\",\"value\":\"Existing Tag\"}]"
    CSV

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv

    assert_no_difference -> { Tag.where(family: @family).count } do
      import.send(:import!)
    end

    rule = Rule.find_by!(family: @family, name: "Tag rule")
    action = rule.actions.first
    assert_equal "set_transaction_tags", action.action_type
    assert_equal existing_tag.id, action.value
  end

  test "imports multi-tag actions, reusing existing tags and creating missing ones" do
    existing_tag = @family.tags.create!(name: "Existing Tag")

    csv = <<~CSV
      name,resource_type,active,effective_date,conditions,actions
      "Multi tag rule","transaction",true,,"[{\"condition_type\":\"transaction_name\",\"operator\":\"like\",\"value\":\"test\"}]","[{\"action_type\":\"set_transaction_tags\",\"value\":\"Existing Tag,New Tag\"}]"
    CSV

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv

    assert_difference -> { Tag.where(family: @family).count }, 1 do
      import.send(:import!)
    end

    new_tag = Tag.find_by!(family: @family, name: "New Tag")

    rule = Rule.find_by!(family: @family, name: "Multi tag rule")
    action = rule.actions.first
    assert_equal "set_transaction_tags", action.action_type
    assert_equal [ existing_tag.id, new_tag.id ], action.value.split(",")
  end

  test "imports a multi-tag action preserving a tag name that contains a comma" do
    existing_tag = @family.tags.create!(name: "Existing Tag")

    actions_json = [
      {
        action_type: "set_transaction_tags",
        value: CSV.generate_line([ "Existing Tag", "Food, Dining" ], row_sep: "")
      }
    ].to_json
    conditions_json = [
      { condition_type: "transaction_name", operator: "like", value: "test" }
    ].to_json

    csv = CSV.generate do |csv_out|
      csv_out << %w[name resource_type active effective_date conditions actions]
      csv_out << [ "Comma tag rule", "transaction", true, nil, conditions_json, actions_json ]
    end

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv

    assert_difference -> { Tag.where(family: @family).count }, 1 do
      import.send(:import!)
    end

    comma_tag = Tag.find_by!(family: @family, name: "Food, Dining")

    rule = Rule.find_by!(family: @family, name: "Comma tag rule")
    action = rule.actions.first
    assert_equal "set_transaction_tags", action.action_type
    assert_equal [ existing_tag.id, comma_tag.id ], action.value.split(",")
  end

  test "imports a split action by mapping row category, merchant and tag names to ids" do
    actions = [
      {
        action_type: "split_transaction",
        value: {
          splits: [
            { type: "percentage", name: "Food", share: "70", category: "Groceries", merchant: "Corner Shop", tags: [ "Shared" ] },
            { type: "percentage", name: "Other", share: "30", category_id: categories(:food_and_drink).id }
          ]
        }
      }
    ].to_json
    csv = CSV.generate do |rows|
      rows << %w[name resource_type active effective_date conditions actions]
      rows << [ "Split groceries", "transaction", "true", "", '[{"condition_type":"transaction_name","operator":"like","value":"market"}]', actions ]
    end

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv
    import.send(:import!)

    food, other = JSON.parse(Rule.find_by!(family: @family, name: "Split groceries").actions.sole.value)["splits"]
    assert_equal @category.id, food["category_id"]
    assert_equal @family.merchants.find_by!(name: "Corner Shop").id, food["merchant_id"]
    assert_equal [ Tag.find_by!(family: @family, name: "Shared").id ], food["tag_ids"]
    # A raw id that belongs to the importing family is kept as is
    assert_equal categories(:food_and_drink).id, other["category_id"]
  end

  test "csv template rows import, including the split example" do
    import = @family.imports.create!(type: "RuleImport", raw_file_str: RuleImport.new.csv_template.to_csv, col_sep: ",")
    import.generate_rows_from_csv
    import.send(:import!)

    splits = JSON.parse(Rule.find_by!(family: @family, name: "Split shared rent").actions.sole.value)["splits"]
    rent = @family.categories.find_by!(name: "Rent")
    assert_equal [ rent.id, rent.id ], splits.map { |split| split["category_id"] }
    assert_equal [ @family.tags.find_by!(name: "Shared").id ], splits.last["tag_ids"]
  end

  test "imports transaction_tag condition and maps tag name to id" do
    existing_tag = @family.tags.create!(name: "Existing Tag")

    csv = <<~CSV
      name,resource_type,active,effective_date,conditions,actions
      "Tag condition rule","transaction",true,,"[{\"condition_type\":\"transaction_tag\",\"operator\":\"=\",\"value\":\"Existing Tag\"}]","[{\"action_type\":\"auto_categorize\"}]"
    CSV

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv

    assert_no_difference -> { Tag.where(family: @family).count } do
      import.send(:import!)
    end

    rule = Rule.find_by!(family: @family, name: "Tag condition rule")
    condition = rule.conditions.first
    assert_equal "transaction_tag", condition.condition_type
    assert_equal existing_tag.id, condition.value
  end

  test "creates a missing tag referenced by a transaction_tag condition" do
    csv = <<~CSV
      name,resource_type,active,effective_date,conditions,actions
      "New tag condition rule","transaction",true,,"[{\"condition_type\":\"transaction_tag\",\"operator\":\"=\",\"value\":\"Brand New Tag\"}]","[{\"action_type\":\"auto_categorize\"}]"
    CSV

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv

    assert_difference -> { Tag.where(family: @family).count }, 1 do
      import.send(:import!)
    end

    new_tag = Tag.find_by!(family: @family, name: "Brand New Tag")
    rule = Rule.find_by!(family: @family, name: "New tag condition rule")
    assert_equal new_tag.id, rule.conditions.first.value
  end

  test "reuses a category created for an earlier row within the same import" do
    csv = <<~CSV
      name,resource_type,active,effective_date,conditions,actions
      "First coffee rule","transaction",true,,"[{\"condition_type\":\"transaction_name\",\"operator\":\"like\",\"value\":\"coffee\"}]","[{\"action_type\":\"set_transaction_category\",\"value\":\"Coffee Shops\"}]"
      "Second coffee rule","transaction",true,,"[{\"condition_type\":\"transaction_name\",\"operator\":\"like\",\"value\":\"latte\"}]","[{\"action_type\":\"set_transaction_category\",\"value\":\"Coffee Shops\"}]"
    CSV

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv

    assert_difference -> { Category.where(family: @family).count }, 1 do
      import.send(:import!)
    end

    category = Category.find_by!(family: @family, name: "Coffee Shops")
    first_rule = Rule.find_by!(family: @family, name: "First coffee rule")
    second_rule = Rule.find_by!(family: @family, name: "Second coffee rule")
    assert_equal category.id, first_rule.actions.first.value
    assert_equal category.id, second_rule.actions.first.value
  end

  test "updates existing rule when re-importing with same name" do
    # First import
    import1 = @family.imports.create!(type: "RuleImport", raw_file_str: @csv, col_sep: ",")
    import1.generate_rows_from_csv
    import1.send(:import!)

    original_rule = Rule.find_by!(family: @family, name: "Categorize groceries")
    assert original_rule.active

    # Second import with updated rule
    csv2 = <<~CSV
      name,resource_type,active,effective_date,conditions,actions
      "Categorize groceries","transaction",false,2024-02-01,"[{\"condition_type\":\"transaction_name\",\"operator\":\"like\",\"value\":\"market\"}]","[{\"action_type\":\"auto_categorize\"}]"
    CSV

    import2 = @family.imports.create!(type: "RuleImport", raw_file_str: csv2, col_sep: ",")
    import2.generate_rows_from_csv

    assert_no_difference -> { Rule.where(family: @family).count } do
      import2.send(:import!)
    end

    updated_rule = Rule.find_by!(family: @family, name: "Categorize groceries")
    assert_equal original_rule.id, updated_rule.id
    assert_not updated_rule.active
    assert_equal Date.parse("2024-02-01"), updated_rule.effective_date

    # Verify old conditions/actions are replaced
    condition = updated_rule.conditions.first
    assert_equal "market", condition.value

    action = updated_rule.actions.first
    assert_equal "auto_categorize", action.action_type
  end

  test "re-importing an email rule with wider conditions does not email existing matches" do
    account = @family.accounts.create!(name: "Baseline test", balance: 1000, currency: "USD", accountable: Depository.new)
    Entry.create!(account: account, name: "Coffee shop", date: 90.days.ago.to_date, amount: 10, currency: "USD", entryable: Transaction.new)
    tea = Entry.create!(account: account, name: "Tea house", date: 60.days.ago.to_date, amount: 20, currency: "USD", entryable: Transaction.new).transaction

    rule = @family.rules.create!(
      name: "Coffee alerts",
      resource_type: "transaction",
      active: true,
      conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: "coffee" } ],
      actions_attributes: [ { action_type: "send_email_notification" } ]
    )
    # Rule::Action's create-time seed does not run today (its after_update_commit
    # names the same method and replaces it), so take that baseline here.
    rule.actions.first.send(:seed_notification_baseline)

    csv = <<~CSV
      name,resource_type,active,effective_date,conditions,actions
      "Coffee alerts","transaction",true,,"[{\"condition_type\":\"transaction_name\",\"operator\":\"like\",\"value\":\"house\"}]","[{\"action_type\":\"send_email_notification\"}]"
    CSV
    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv
    import.send(:import!)

    assert_no_enqueued_jobs only: RuleEmailNotificationJob do
      RuleJob.perform_now(Rule.find(rule.id))
    end
    assert_includes NotificationDelivery.where(rule: rule).pluck(:transaction_id), tea.id
  end

  # Review of we-promise/sure#4150 (Codex, P1). The import clears the rule's
  # conditions with destroy_all before it saves, so a row with no conditions left
  # nothing for the rule to see changing, and a rule with no conditions matches
  # every transaction.
  test "re-importing an email rule with no conditions does not email existing matches" do
    account = @family.accounts.create!(name: "Baseline test", balance: 1000, currency: "USD", accountable: Depository.new)
    Entry.create!(account: account, name: "Coffee shop", date: 90.days.ago.to_date, amount: 10, currency: "USD", entryable: Transaction.new)
    tea = Entry.create!(account: account, name: "Tea house", date: 60.days.ago.to_date, amount: 20, currency: "USD", entryable: Transaction.new).transaction

    rule = @family.rules.create!(
      name: "Coffee alerts",
      resource_type: "transaction",
      active: true,
      conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: "coffee" } ],
      actions_attributes: [ { action_type: "send_email_notification" } ]
    )
    rule.actions.first.send(:seed_notification_baseline)
    assert_not_includes NotificationDelivery.where(rule: rule).pluck(:transaction_id), tea.id, "precondition: Tea house is outside the baseline"

    csv = <<~CSV
      name,resource_type,active,effective_date,conditions,actions
      "Coffee alerts","transaction",true,,"[]","[{\"action_type\":\"send_email_notification\"}]"
    CSV
    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv
    import.send(:import!)
    assert_empty rule.reload.conditions, "precondition: the import left the rule with no conditions"

    assert_no_enqueued_jobs only: RuleEmailNotificationJob do
      RuleJob.perform_now(Rule.find(rule.id))
    end
    assert_includes NotificationDelivery.where(rule: rule).pluck(:transaction_id), tea.id
  end

  # Review of we-promise/sure#4150 (CodeRabbit). The import replaces every
  # condition, so each one reads as changing even when the row holds the same
  # criteria. Re-seeding then would record a match still waiting for the next run
  # as delivered, and it would never be emailed.
  test "re-importing an email rule with identical conditions still emails a pending match" do
    rule, coffee_bar = email_rule_with_pending_match(conditions: [ { condition_type: "transaction_name", operator: "like", value: "coffee" } ])

    assert_no_difference -> { NotificationDelivery.where(rule: rule).count } do
      import_rule_rows(rule.name, [ { condition_type: "transaction_name", operator: "like", value: "coffee" } ])
    end

    assert_equal [ coffee_bar.id ], emailed_transaction_ids(rule)
  end

  test "re-importing an email rule's conditions in a different order still emails a pending match" do
    rule, coffee_bar = email_rule_with_pending_match(conditions: [
      { condition_type: "transaction_name", operator: "like", value: "coffee" },
      { condition_type: "transaction_name", operator: "like", value: "bar" }
    ])

    assert_no_difference -> { NotificationDelivery.where(rule: rule).count } do
      import_rule_rows(rule.name, [
        { condition_type: "transaction_name", operator: "like", value: "bar" },
        { condition_type: "transaction_name", operator: "like", value: "coffee" }
      ])
    end

    assert_equal [ coffee_bar.id ], emailed_transaction_ids(rule)
  end

  test "re-importing a valueless condition with a blank value still emails a pending match" do
    rule, coffee_bar = email_rule_with_pending_match(conditions: [
      { condition_type: "transaction_name", operator: "like", value: "coffee" },
      { condition_type: "transaction_notes", operator: "is_null", value: nil }
    ])
    assert_nil rule.conditions.find_by!(condition_type: "transaction_notes").value

    assert_no_difference -> { NotificationDelivery.where(rule: rule).count } do
      import_rule_rows(rule.name, [
        { condition_type: "transaction_name", operator: "like", value: "coffee" },
        { condition_type: "transaction_notes", operator: "is_null", value: "" }
      ])
    end
    assert_equal "", rule.reload.conditions.find_by!(condition_type: "transaction_notes").value, "precondition: the import stored the blank value"

    assert_equal [ coffee_bar.id ], emailed_transaction_ids(rule)
  end

  test "validates resource_type" do
    csv = <<~CSV
      name,resource_type,active,effective_date,conditions,actions
      "Invalid rule","invalid_type",true,,"[{\"condition_type\":\"transaction_name\",\"operator\":\"like\",\"value\":\"test\"}]","[{\"action_type\":\"auto_categorize\"}]"
    CSV

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv

    assert_raises ActiveRecord::RecordInvalid do
      import.send(:import!)
    end
  end

  test "validates at least one action exists" do
    csv = <<~CSV
      name,resource_type,active,effective_date,conditions,actions
      "No actions rule","transaction",true,,"[{\"condition_type\":\"transaction_name\",\"operator\":\"like\",\"value\":\"test\"}]","[]"
    CSV

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv

    assert_raises ActiveRecord::RecordInvalid do
      import.send(:import!)
    end
  end

  test "handles invalid JSON in conditions or actions" do
    csv = <<~CSV
      name,resource_type,active,effective_date,conditions,actions
      "Bad JSON rule","transaction",true,,"invalid json","[{\"action_type\":\"auto_categorize\"}]"
    CSV

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv

    assert_raises ActiveRecord::RecordInvalid do
      import.send(:import!)
    end
  end

  test "reports a validation error for a null byte in an imported condition" do
    csv = CSV.generate do |rows|
      rows << %w[name resource_type active effective_date conditions actions]
      rows << [
        "Invalid condition rule",
        "transaction",
        true,
        nil,
        [ { condition_type: "transaction_name", operator: "like", value: "bad\0value" } ].to_json,
        [ { action_type: "exclude_transaction" } ].to_json
      ]
    end

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv

    error = assert_raises(ActiveRecord::RecordInvalid) { import.send(:import!) }
    assert_match(/value is invalid/i, error.message)
    assert_nil @family.rules.find_by(name: "Invalid condition rule")
  end

  test "reports a validation error for a null byte inside a split action" do
    split = { splits: [
      { type: "percentage", name: "A", share: "50", category: "Bad\0Category" },
      { type: "percentage", name: "B", share: "50" }
    ] }
    category_count = @family.categories.count

    # As an object and as a JSON string (where the NUL byte is escaped in the raw text).
    [ split, split.to_json ].each do |value|
      csv = CSV.generate do |rows|
        rows << %w[name resource_type active effective_date conditions actions]
        rows << [
          "Invalid split rule", "transaction", true, nil,
          [ { condition_type: "transaction_name", operator: "like", value: "rent" } ].to_json,
          [ { action_type: "split_transaction", value: value } ].to_json
        ]
      end

      import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
      import.generate_rows_from_csv

      error = assert_raises(ActiveRecord::RecordInvalid, value.class.name) { import.send(:import!) }
      assert_match(/value is invalid/i, error.message)
      assert_nil @family.rules.find_by(name: "Invalid split rule")
      assert_equal category_count, @family.categories.count
    end
  end

  test "rejects an imported name with a trailing null byte" do
    import = @family.imports.create!(type: "RuleImport", raw_file_str: @csv, col_sep: ",")
    import.generate_rows_from_csv
    row = import.rows.first
    row.name = "Invalid name\0"

    error = assert_raises(ActiveRecord::RecordInvalid) do
      import.send(:create_or_update_rule_from_row, row)
    end

    assert_match(/Name is invalid/, error.message)
    assert_nil @family.rules.find_by(name: "Invalid name")
  end

  test "rejects an imported resource type with a trailing null byte" do
    import = @family.imports.create!(type: "RuleImport", raw_file_str: @csv, col_sep: ",")
    import.generate_rows_from_csv
    row = import.rows.first
    row.resource_type = "transaction\0"

    error = assert_raises(ActiveRecord::RecordInvalid) do
      import.send(:create_or_update_rule_from_row, row)
    end

    assert_match(/Resource type is invalid/, error.message)
  end

  test "rejects null bytes in imported references before looking them up" do
    import = @family.imports.create!(type: "RuleImport", raw_file_str: @csv, col_sep: ",")
    counts = [ @family.categories.count, @family.merchants.count, @family.tags.count ]

    {
      resolve_import_condition_value: [ "transaction_category", "transaction_merchant", "transaction_tag" ],
      resolve_import_action_value: [ "set_transaction_category", "set_transaction_merchant", "set_transaction_tags" ]
    }.each do |resolver, types|
      type_key = resolver == :resolve_import_condition_value ? "condition_type" : "action_type"

      types.each do |type|
        error = assert_raises(ActiveRecord::RecordInvalid, type) do
          import.send(resolver, { type_key => type, "value" => "Bad\0reference" })
        end
        assert_match(/Value is invalid/, error.message)
      end
    end

    assert_equal counts, [ @family.categories.count, @family.merchants.count, @family.tags.count ]
  end

  test "rejects null bytes in imported operator and action type" do
    [
      [ "like\0", "exclude_transaction" ],
      [ "like", "exclude_transaction\0" ]
    ].each do |operator, action_type|
      csv = CSV.generate do |rows|
        rows << %w[name resource_type active effective_date conditions actions]
        rows << [
          "Invalid metadata rule", "transaction", true, nil,
          [ { condition_type: "transaction_name", operator: operator, value: "coffee" } ].to_json,
          [ { action_type: action_type } ].to_json
        ]
      end

      import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
      import.generate_rows_from_csv

      error = assert_raises(ActiveRecord::RecordInvalid) { import.send(:import!) }
      assert_match(/is invalid/, error.message)
      assert_nil @family.rules.find_by(name: "Invalid metadata rule")
    end
  end

  test "rejects an unknown imported action type" do
    csv = CSV.generate do |rows|
      rows << %w[name resource_type active effective_date conditions actions]
      rows << [
        "Unknown action rule", "transaction", true, nil,
        [ { condition_type: "transaction_name", operator: "like", value: "coffee" } ].to_json,
        [ { action_type: "garbage" } ].to_json
      ]
    end

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv

    error = assert_raises(ActiveRecord::RecordInvalid) { import.send(:import!) }
    assert_match(/is not included in the list/, error.message)
    assert_nil @family.rules.find_by(name: "Unknown action rule")
  end

  test "imports valid JSON conditions whose values contain escaped quotes" do
    csv = CSV.generate do |out|
      out << %w[name resource_type active effective_date conditions actions]
      out << [
        "Quoted value rule",
        "transaction",
        true,
        "",
        [ { condition_type: "transaction_name", operator: "=", value: "ני\\u0022ע-קניה" } ].to_json,
        [ { action_type: "set_transaction_name", value: "Quoted transfer" } ].to_json
      ]
    end

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv

    assert_nothing_raised do
      import.send(:import!)
    end

    rule = Rule.find_by!(family: @family, name: "Quoted value rule")
    condition = rule.conditions.first
    assert_equal "ני\"ע-קניה", condition.value
  end

  test "imports the group column and reuses existing groups" do
    existing = @family.rule_groups.create!(name: "Food")
    csv = CSV.generate do |out|
      out << %w[name resource_type active effective_date conditions actions group]
      out << [ "Grocery rule", "transaction", true, "", [ { condition_type: "transaction_name", operator: "like", value: "grocery" } ].to_json, [ { action_type: "set_transaction_category", value: "Groceries" } ].to_json, "Food" ]
      out << [ "Rent rule", "transaction", true, "", [ { condition_type: "transaction_name", operator: "like", value: "rent" } ].to_json, [ { action_type: "exclude_transaction" } ].to_json, "Housing" ]
      out << [ "Loose rule", "transaction", true, "", [ { condition_type: "transaction_name", operator: "like", value: "misc" } ].to_json, [ { action_type: "exclude_transaction" } ].to_json, "" ]
    end

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv

    assert_difference -> { @family.rule_groups.count }, 1 do
      import.send(:import!)
    end

    assert_equal existing, @family.rules.find_by!(name: "Grocery rule").rule_group
    assert_equal "Housing", @family.rules.find_by!(name: "Rent rule").rule_group.name
    assert_nil @family.rules.find_by!(name: "Loose rule").rule_group
    assert_equal [ { condition_type: "transaction_name", operator: "like", value: "rent" }.stringify_keys ],
      @family.rules.find_by!(name: "Rent rule").conditions.map { |condition| condition.slice(:condition_type, :operator, :value) }
  end

  test "reads the group of a row whose JSON was split into extra fields" do
    headers = %w[name resource_type active effective_date conditions actions group]
    # CSV pads the headers with nil for fields beyond the named columns.
    row = CSV::Row.new(headers + [ nil ], [ "Split rule", "transaction", "true", nil, '[{"a":1}', '{"b":2}]', "[]", "Food" ])

    normalized = RuleImport.new.send(:normalize_rule_row, row)

    assert_equal "Food", normalized[:rule_group]
    assert_equal "Split rule", normalized[:name]
  end

  test "reads the group when the header row has a blank cell" do
    conditions = [ { condition_type: "transaction_name", operator: "like", value: "rent" } ].to_json
    actions = [ { action_type: "exclude_transaction" } ].to_json
    csv = "name,resource_type,active,effective_date,conditions,actions,group,\n" +
      CSV.generate_line([ "Rent rule", "transaction", "true", "", conditions, actions, "Housing" ])

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv
    import.send(:import!)

    assert_equal "Housing", @family.rules.find_by!(name: "Rent rule").rule_group&.name
  end

  test "a file without the group column keeps the group of an updated rule" do
    group = @family.rule_groups.create!(name: "Food")
    @family.rules.create!(name: "Categorize groceries", resource_type: "transaction", rule_group: group,
      actions: [ Rule::Action.new(action_type: "exclude_transaction") ])

    import = @family.imports.create!(type: "RuleImport", raw_file_str: @csv, col_sep: ",")
    import.generate_rows_from_csv
    import.send(:import!)

    assert_equal group, @family.rules.find_by!(name: "Categorize groceries").rule_group
  end

  test "imports wrapped JSON payloads from legacy rows" do
    wrapped_conditions = [ { condition_type: "transaction_name", operator: "like", value: "legacy grocery" } ].to_json.to_json
    wrapped_actions = [ { action_type: "set_transaction_category", value: "Groceries" } ].to_json.to_json

    csv = CSV.generate do |out|
      out << %w[name resource_type active effective_date conditions actions]
      out << [
        "Wrapped payload rule",
        "transaction",
        true,
        "",
        wrapped_conditions,
        wrapped_actions
      ]
    end

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv

    assert_nothing_raised do
      import.send(:import!)
    end

    rule = Rule.find_by!(family: @family, name: "Wrapped payload rule")
    condition = rule.conditions.first
    action = rule.actions.first

    assert_equal "legacy grocery", condition.value
    assert_equal @category.id, action.value
  end

  test "preserves literal backslash sequences in valid JSON values" do
    csv = CSV.generate do |out|
      out << %w[name resource_type active effective_date conditions actions]
      out << [
        "Literal backslash rule",
        "transaction",
        true,
        "",
        [ { condition_type: "transaction_name", operator: "=", value: 'C:\new\test' } ].to_json,
        [ { action_type: "set_transaction_name", value: "Path rule" } ].to_json
      ]
    end

    import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv
    import.send(:import!)

    rule = Rule.find_by!(family: @family, name: "Literal backslash rule")
    condition = rule.conditions.first

    assert_equal 'C:\new\test', condition.value
  end

  private
    # An email rule with its baseline taken, plus a later Coffee bar transaction
    # the rule has not run against yet.
    def email_rule_with_pending_match(conditions:)
      account = @family.accounts.create!(name: "Baseline test", balance: 1000, currency: "USD", accountable: Depository.new)
      Entry.create!(account: account, name: "Coffee shop", date: 90.days.ago.to_date, amount: 10, currency: "USD", entryable: Transaction.new)
      rule = @family.rules.create!(
        name: "Coffee alerts",
        resource_type: "transaction",
        active: true,
        conditions_attributes: conditions,
        actions_attributes: [ { action_type: "send_email_notification" } ]
      )
      rule.actions.first.send(:seed_notification_baseline)
      coffee_bar = Entry.create!(account: account, name: "Coffee bar", date: Date.current, amount: 5, currency: "USD", entryable: Transaction.new).transaction
      assert_not_includes NotificationDelivery.where(rule: rule).pluck(:transaction_id), coffee_bar.id, "precondition: Coffee bar is outside the baseline"

      [ Rule.find(rule.id), coffee_bar ]
    end

    def import_rule_rows(name, conditions)
      csv = CSV.generate do |rows|
        rows << %w[name resource_type active effective_date conditions actions]
        rows << [ name, "transaction", "true", nil, conditions.to_json, [ { action_type: "send_email_notification" } ].to_json ]
      end
      import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
      import.generate_rows_from_csv
      import.send(:import!)
    end

    # The transaction ids a RuleJob run enqueues for emailing, for this rule only.
    def emailed_transaction_ids(rule)
      before = enqueued_jobs.size
      RuleJob.perform_now(Rule.find(rule.id))
      enqueued_jobs.drop(before)
        .select { |job| job[:job] == RuleEmailNotificationJob }
        .map { |job| ActiveJob::Arguments.deserialize(job[:args]) }
        .select { |rule_id, _| rule_id == rule.id }
        .flat_map(&:second)
        .sort
    end
end