diff --git a/lib/bad_list_deleter.rb b/lib/bad_list_deleter.rb new file mode 100644 index 000000000..8af299017 --- /dev/null +++ b/lib/bad_list_deleter.rb @@ -0,0 +1,56 @@ +class BadListDeleter + VALID_PREFIXES = %w[ + topic + organisations + government/people + government/ministers + government/topical-events + service-manual + service-manual/service-standard + ].freeze + + attr_reader :prefix + + def initialize(prefix) + @prefix = prefix + end + + def process_all_lists + message = "Bad list deletion not possible for the provided prefix" + raise message unless valid_prefix? + + bad_lists.each do |bad_list| + if bad_list.subscriptions.active.any? + next + end + + bad_list.destroy! + end + end + + def bad_lists + subscriber_lists - valid_links_based_lists?(subscriber_lists) + end + +private + + def valid_prefix? + VALID_PREFIXES.include?(prefix) + end + + def subscriber_lists + @subscriber_lists ||= SubscriberList.where("url LIKE ?", "%/#{prefix}/%") + end + + def valid_links_based_lists?(lists) + lists.select { |list| valid_links_based_list?(list) } + end + + def valid_links_based_list?(list) + list.content_id.nil? && has_links_or_tags(list) + end + + def has_links_or_tags(list) + list.links.present? || list.tags.present? + end +end diff --git a/lib/tasks/data_cleanup.rake b/lib/tasks/data_cleanup.rake new file mode 100644 index 000000000..2ff18d047 --- /dev/null +++ b/lib/tasks/data_cleanup.rake @@ -0,0 +1,12 @@ +desc "Update one of the tags in a subscriber list" +task delete_bad_lists: :environment do |_t, _args| + BadListDeleter::VALID_PREFIXES.each do |prefix| + deleter = BadListDeleter.new(prefix) + + bad_lists = deleter.bad_lists + subscriptions_sum = bad_lists.sum { |l| l.subscriptions.ended.count } + puts "Prefix: #{prefix} attempting to delete #{bad_lists.count} lists and #{subscriptions_sum} subscriptions" + deleter.process_all_lists + puts " - #{deleter.bad_lists.count} could not be deleted" if deleter.bad_lists.any? + end +end