Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
16.8 KB
Raw Blame
class RuleImport < Import
  def import!
    transaction do
      @rules_with_stored_email_action = Rule.ids_with_stored_email_notification_action(family.rules)
      rows.each do |row|
        create_or_update_rule_from_row(row)
      end
    end
  end

  # Rules hang off the family, not the import — see
  # Import#committed_by_named_records?. Nameless rows build unconditionally and
  # carry no stable key, so a file of only nameless rows has no commit signal.
  def data_committed?
    committed_by_named_records?(family.rules)
  end

  def column_keys
    %i[name resource_type active effective_date conditions actions rule_group]
  end

  def required_column_keys
    %i[resource_type conditions actions]
  end

  def mapping_steps
    []
  end

  def dry_run
    { rules: rows_count }
  end

  def csv_template
    csv_string = CSV.generate do |csv|
      csv << %w[name resource_type* active effective_date conditions* actions* group]

      csv << [
        "Categorize groceries",
        "transaction",
        "true",
        "2024-01-01",
        '[{"condition_type":"transaction_name","operator":"like","value":"grocery"}]',
        '[{"action_type":"set_transaction_category","value":"Groceries"}]',
        "Shopping"
      ]

      csv << [
        "Auto-categorize transactions",
        "transaction",
        "true",
        "",
        '[{"condition_type":"transaction_name","operator":"like","value":"amazon"}]',
        '[{"action_type":"auto_categorize"}]',
        ""
      ]

      csv << [
        "Split shared rent",
        "transaction",
        "true",
        "",
        '[{"condition_type":"transaction_name","operator":"like","value":"rent"}]',
        '[{"action_type":"split_transaction","value":{"splits":[{"type":"percentage","name":"My share","share":"50","category":"Rent"},{"type":"percentage","name":"Partner share","share":"50","category":"Rent","tags":["Shared"]}]}}]',
        ""
      ]
    end

    CSV.parse(csv_string, headers: true)
  end

  def generate_rows_from_csv
    rows.destroy_all

    header_size = header_row_size
    csv_rows.each.with_index(1) do |row, index|
      normalized_row = normalize_rule_row(row, header_size: header_size)

      rows.create!(
        source_row_number: index,
        name: normalized_rule_text(normalized_row[:name], attribute: :name),
        resource_type: normalized_rule_text(normalized_row[:resource_type], attribute: :resource_type),
        active: parse_boolean(normalized_row[:active]),
        effective_date: normalized_row[:effective_date].to_s.strip,
        conditions: normalized_row[:conditions].to_s.strip,
        actions: normalized_row[:actions].to_s.strip,
        rule_group: normalized_row[:rule_group] && normalized_rule_text(normalized_row[:rule_group], attribute: :rule_group),
        currency: default_currency
      )
    end
  end

  def parsed_csv
    @parsed_csv ||= Import.parse_csv_str(raw_file_str, col_sep: col_sep)
  end

  private

    # The optional group column is read by its header and left out of the
    # positional fields, which re-assemble conditions and actions from
    # everything after the fourth column.
    def normalize_rule_row(row, header_size: row.headers.compact.size)
      fields = row.fields.dup
      headers = row.headers
      group_index = headers.index { |header| header.to_s.strip.delete_suffix("*") == "group" }
      # Counted from the end of the header row, so a row whose JSON was split
      # into extra fields (CSV pads headers with nil for those) still gives up
      # the right one.
      group = fields.delete_at(group_index - header_size) if group_index
      name, resource_type, active, effective_date = fields[0..3]
      conditions, actions = extract_conditions_and_actions(fields[4..])

      {
        name: row["name"].presence || name,
        resource_type: row["resource_type"].presence || resource_type,
        active: row["active"].presence || active,
        effective_date: row["effective_date"].presence || effective_date,
        conditions: conditions,
        actions: actions,
        rule_group: group_index ? group.to_s : nil
      }
    end

    # The number of cells in the header row, blank ones included. A row's
    # headers cannot tell a blank header cell from the nil CSV pads in for a
    # row with more fields than the header.
    def header_row_size
      header = CSV.parse_line(Import.normalize_line_endings(raw_file_str).strip, col_sep: col_sep, liberal_parsing: true)
      header ? header.size : 0
    end

    def normalized_rule_text(value, attribute:)
      text = value.to_s
      reject_invalid_text!(text, label: Rule.human_attribute_name(attribute))

      text.strip
    end

    def reject_invalid_text!(value, label:, acceptable: DatabaseTextValidator.acceptable?(value))
      return if acceptable

      errors.add(:base, :invalid, message: "#{label} #{I18n.t("errors.messages.invalid")}")
      raise ActiveRecord::RecordInvalid.new(self)
    end

    def extract_conditions_and_actions(fragments)
      pieces = Array(fragments).compact
      return [ "", "" ] if pieces.empty?

      combined = pieces.join(col_sep)

      # If the CSV was split incorrectly because of unescaped quotes in the JSON
      # payload, re-assemble the last two logical columns by splitting on the
      # boundary between the two JSON arrays: ...]","[...
      parts = combined.split(/(?<=\])"\s*,\s*"(?=\[)/, 2)
      parts = [ pieces[0], pieces[1] ] if parts.length < 2

      parts.map do |part|
        next "" unless part

        # Remove any stray leading/trailing quotes left from CSV parsing
        part.to_s.strip.gsub(/\A"+|"+\z/, "")
      end
    end

    def create_or_update_rule_from_row(row)
      rule_name = normalized_rule_text(row.name, attribute: :name).presence
      resource_type = normalized_rule_text(row.resource_type, attribute: :resource_type)

      # Validate resource type
      unless resource_type == "transaction"
        errors.add(:base, :unsupported_resource_type, resource_type: resource_type)
        raise ActiveRecord::RecordInvalid.new(self)
      end

      # Parse conditions and actions from JSON
      begin
        conditions_data = parse_json_safely(row.conditions, "conditions")
        actions_data = parse_json_safely(row.actions, "actions")
      rescue JSON::ParserError => e
        errors.add(:base, :invalid_json, message: e.message)
        raise ActiveRecord::RecordInvalid.new(self)
      end

      # Validate we have at least one action
      if actions_data.empty?
        errors.add(:base, :min_actions)
        raise ActiveRecord::RecordInvalid.new(self)
      end

      # Find or create rule
      rule = if rule_name.present?
        family.rules.find_or_initialize_by(name: rule_name, resource_type: resource_type)
      else
        family.rules.build(resource_type: resource_type)
      end

      rule.active = row.active || false
      rule.effective_date = parse_date(row.effective_date)
      # A file without the group column leaves the rule's group as it is.
      rule.rule_group = find_or_create_rule_group(row.rule_group) unless row.rule_group.nil?

      # An email action replacing the rule's own keeps the baseline it recorded
      # (see Rule::Action#keep_notification_baseline), as stored before this
      # import: not one an earlier row of it wrote.
      had_email_action = rule.persisted? && @rules_with_stored_email_action.include?(rule.id)

      # Clear existing conditions and actions. The conditions are marked rather
      # than destroyed now, so the rule's save removes them and sees its
      # conditions change (Rule re-seeds an email rule's baseline then).
      rule.conditions.each(&:mark_for_destruction)
      rule.actions.destroy_all

      # Create conditions
      conditions_data.each do |condition_data|
        build_condition(rule, condition_data)
      end

      # Create actions
      actions_data.each do |action_data|
        build_action(rule, action_data).keep_notification_baseline = had_email_action
      end

      rule.save!
    end

    def find_or_create_rule_group(name)
      name = name.strip
      return if name.empty?

      family.rule_groups.find_or_create_named!(name)
    end

    def build_condition(rule, condition_data, parent: nil)
      condition_type = condition_data["condition_type"]
      operator = condition_data["operator"]
      value = resolve_import_condition_value(condition_data)

      condition = if parent
        parent.sub_conditions.build(
          condition_type: condition_type,
          operator: operator,
          value: value
        )
      else
        rule.conditions.build(
          condition_type: condition_type,
          operator: operator,
          value: value
        )
      end

      # Handle compound conditions with sub_conditions
      if condition_data["sub_conditions"].present?
        condition_data["sub_conditions"].each do |sub_condition_data|
          build_condition(rule, sub_condition_data, parent: condition)
        end
      end

      condition
    end

    def build_action(rule, action_data)
      action_type = action_data["action_type"]
      value = resolve_import_action_value(action_data)

      rule.actions.build(
        action_type: action_type,
        value: value
      )
    end

    def resolve_import_condition_value(condition_data)
      condition_type = condition_data["condition_type"]
      value = condition_data["value"]
      reject_invalid_text!(value, label: Rule::Condition.human_attribute_name(:value))

      return value unless value.present?

      # Map category names to UUIDs
      if condition_type == "transaction_category"
        return find_or_create_category(value).id
      end

      # Map merchant names to UUIDs
      if condition_type == "transaction_merchant"
        return find_or_create_merchant(value).id
      end

      # Map tag names to UUIDs
      if condition_type == "transaction_tag"
        return find_or_create_tag(value).id
      end

      value
    end

    def resolve_import_action_value(action_data)
      action_type = action_data["action_type"]
      value = action_data["value"]
      reject_invalid_text!(value, label: Rule::Action.human_attribute_name(:value))

      return value unless value.present?

      return resolve_import_split_value(value) if action_type == "split_transaction"

      # Map category names to UUIDs
      if action_type == "set_transaction_category"
        return find_or_create_category(value).id
      end

      # Map merchant names to UUIDs
      if action_type == "set_transaction_merchant"
        return find_or_create_merchant(value).id
      end

      # Map tag names to UUIDs. `value` may be a comma-separated list of tag
      # names for multi-tag actions (see Rule::Action#value=), so each name
      # is resolved independently rather than treating the whole string as
      # a single tag name.
      if action_type == "set_transaction_tags"
        return resolve_import_multi_tag_value(value)
      end

      value
    end

    def resolve_import_multi_tag_value(value)
      names = Rule::Action.decode_multi_value_names(value).map(&:strip).reject(&:blank?)
      return value if names.empty?

      names.map { |name| find_or_create_tag(name).id }.join(",")
    end

    # Names resolve like the other actions; a raw id is kept only if it belongs to the family.
    def resolve_import_split_value(value)
      reject_invalid_text!(value, label: Rule::Action.human_attribute_name(:value),
                                  acceptable: Rule::ActionExecutor::SplitTransaction.acceptable_text?(value))

      Rule::ActionExecutor::SplitTransaction.localize_value(value) do |kind, name: nil, id: nil|
        next (id if family_record_ids(kind.to_s.pluralize.to_sym).include?(id)) unless name

        case kind
        when :category then find_or_create_category(name).id
        # A split child is set like a manual split, which only offers the
        # family's own merchants.
        when :merchant then find_or_create_family_merchant(name).id
        when :tag then find_or_create_tag(name).id
        end
      end
    end

    def family_record_ids(relation)
      @family_record_ids ||= {}
      @family_record_ids[relation] ||= family.public_send(relation).pluck(:id).to_set
    end

    # Preloaded once per import and extended in place on cache-miss, so a
    # category/merchant/tag created for an earlier row is immediately visible
    # to a later row referencing the same name, instead of one query per
    # condition/action across every row in the file.
    def categories_by_name
      @categories_by_name ||= family.categories.index_by(&:name)
    end

    def family_merchants_by_name
      @family_merchants_by_name ||= family.merchants.index_by(&:name)
    end

    # An exported rule may name a provider merchant (see Family::DataExporter);
    # reuse it while it is still on the family's transactions, so the rule
    # keeps matching them. A name shared by several provider merchants is
    # ambiguous and left out.
    def provider_merchants_by_name
      @provider_merchants_by_name ||= ProviderMerchant.where(id: family.transactions.select(:merchant_id))
        .group_by(&:name)
        .filter_map { |name, merchants| [ name, merchants.first ] if merchants.one? }
        .to_h
    end

    def tags_by_name
      @tags_by_name ||= family.tags.index_by(&:name)
    end

    def find_or_create_category(name)
      categories_by_name[name] ||= family.categories.create!(
        name: name,
        color: Category::UNCATEGORIZED_COLOR,
        lucide_icon: "shapes"
      )
    end

    # The family's own merchant wins on a name clash.
    def find_or_create_merchant(name)
      family_merchants_by_name[name] || provider_merchants_by_name[name] || find_or_create_family_merchant(name)
    end

    def find_or_create_family_merchant(name)
      family_merchants_by_name[name] ||= family.merchants.create!(name: name)
    end

    def find_or_create_tag(name)
      tags_by_name[name] ||= family.tags.create!(name: name)
    end

    def parse_boolean(value)
      return true if value.to_s.downcase.in?(%w[true 1 yes y])
      return false if value.to_s.downcase.in?(%w[false 0 no n])
      false
    end

    def parse_date(value)
      return nil if value.blank?
      Date.parse(value.to_s)
    rescue ArgumentError
      nil
    end

    def parse_json_safely(json_string, field_name)
      return [] if json_string.blank?

      cleaned = json_string.to_s.strip

      # Most API-created rows already store valid JSON. Parse them as-is before
      # falling back to the legacy cleanup path for older malformed payloads.
      parse_json_payload(cleaned, normalize_legacy_strings: false)
    rescue JSON::ParserError
      # Clean up the JSON string - remove extra escaping that might come from CSV parsing

      # Remove surrounding quotes if present (both single and double)
      cleaned = cleaned.gsub(/\A["']+|["']+\z/, "")

      # Handle multiple levels of escaping iteratively
      # Keep unescaping until no more changes occur
      loop do
        previous = cleaned.dup

        # Unescape quotes - handle patterns like \" or \\\" or \\\\\" etc.
        # Replace any number of backslashes followed by a quote with just a quote
        cleaned = cleaned.gsub(/\\+"/, '"')
        cleaned = cleaned.gsub(/\\+'/, "'")

        # Unescape backslashes (\\\\ becomes \)
        cleaned = cleaned.gsub(/\\\\/, "\\")

        break if cleaned == previous
      end

      # Handle unicode escapes like \u003e (but only if not over-escaped)
      # Try to find and decode unicode escapes
      cleaned = cleaned.gsub(/\\u([0-9a-fA-F]{4})/i) do |match|
        code_point = $1.to_i(16)
        [ code_point ].pack("U")
      rescue
        match # If decoding fails, keep the original
      end

      # Try parsing
      parse_json_payload(cleaned, normalize_legacy_strings: true)
    rescue JSON::ParserError => e
      raise JSON::ParserError.new("Invalid JSON in #{field_name}: #{e.message}. Raw value: #{json_string.inspect}")
    end

    def parse_json_payload(payload, normalize_legacy_strings:)
      parsed = JSON.parse(payload)
      parsed = JSON.parse(parsed) if wrapped_json_payload?(parsed)

      normalize_json_values(parsed, normalize_legacy_strings:)
    end

    def wrapped_json_payload?(value)
      return false unless value.is_a?(String)

      stripped_value = value.strip
      stripped_value.start_with?("[", "{")
    end

    def normalize_json_values(value, normalize_legacy_strings:)
      case value
      when Array
        value.map { |item| normalize_json_values(item, normalize_legacy_strings:) }
      when Hash
        value.transform_values { |item| normalize_json_values(item, normalize_legacy_strings:) }
      when String
        normalized = value
          .gsub(/\\u([0-9a-fA-F]{4})/i) { [ $1.to_i(16) ].pack("U") }
          .gsub('\\"', '"')

        if normalize_legacy_strings
          normalized = normalized
            .gsub("\\n", "\n")
            .gsub("\\r", "\r")
            .gsub("\\t", "\t")
        end

        normalized
      else
        value
      end
    end
end