|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module ProductTaxonomy |
| 4 | + class AddReturnReasonsToCategoriesCommand < Command |
| 5 | + def initialize(options) |
| 6 | + super |
| 7 | + load_taxonomy |
| 8 | + @return_reason_friendly_ids = options[:return_reason_friendly_ids] |
| 9 | + @category_ids = options[:category_ids] |
| 10 | + @include_descendants = options[:include_descendants] |
| 11 | + end |
| 12 | + |
| 13 | + def execute |
| 14 | + add_return_reasons_to_categories! |
| 15 | + update_data_files! |
| 16 | + end |
| 17 | + |
| 18 | + private |
| 19 | + |
| 20 | + def add_return_reasons_to_categories! |
| 21 | + @return_reasons = return_reason_friendly_ids.map { |friendly_id| ReturnReason.find_by!(friendly_id:) } |
| 22 | + @categories = category_ids.map { |id| Category.find_by!(id:) } |
| 23 | + @categories = @categories.flat_map(&:descendants_and_self) if @include_descendants |
| 24 | + |
| 25 | + @categories.each do |category| |
| 26 | + @return_reasons.each do |return_reason| |
| 27 | + if category.return_reasons.include?(return_reason) |
| 28 | + logger.info("Category `#{category.name}` already has return reason `#{return_reason.friendly_id}` - skipping") |
| 29 | + else |
| 30 | + category.return_reasons << return_reason |
| 31 | + end |
| 32 | + end |
| 33 | + |
| 34 | + sort_return_reasons!(category) |
| 35 | + end |
| 36 | + |
| 37 | + logger.info("Added #{@return_reasons.size} return reason(s) to #{@categories.size} categories") |
| 38 | + end |
| 39 | + |
| 40 | + def sort_return_reasons!(category) |
| 41 | + special_reasons = category.return_reasons.select { |r| ['unknown', 'other'].include?(r.friendly_id) } |
| 42 | + regular_reasons = category.return_reasons.reject { |r| ['unknown', 'other'].include?(r.friendly_id) } |
| 43 | + |
| 44 | + regular_reasons.sort_by!(&:name) |
| 45 | + |
| 46 | + sorted_reasons = regular_reasons.dup |
| 47 | + sorted_reasons << special_reasons.find { |r| r.friendly_id == 'unknown' } if special_reasons.any? { |r| r.friendly_id == 'unknown' } |
| 48 | + sorted_reasons << special_reasons.find { |r| r.friendly_id == 'other' } if special_reasons.any? { |r| r.friendly_id == 'other' } |
| 49 | + |
| 50 | + category.instance_variable_set(:@return_reasons, sorted_reasons) |
| 51 | + end |
| 52 | + |
| 53 | + def update_data_files! |
| 54 | + roots = @categories.map(&:root).uniq.map(&:id) |
| 55 | + DumpCategoriesCommand.new(verticals: roots).execute |
| 56 | + SyncEnLocalizationsCommand.new(targets: "categories").execute |
| 57 | + GenerateDocsCommand.new({}).execute |
| 58 | + end |
| 59 | + |
| 60 | + def return_reason_friendly_ids |
| 61 | + @return_reason_friendly_ids.split(",").map(&:strip) |
| 62 | + end |
| 63 | + |
| 64 | + def category_ids |
| 65 | + @category_ids.split(",").map(&:strip) |
| 66 | + end |
| 67 | + end |
| 68 | +end |
| 69 | + |
| 70 | + |
| 71 | + |
0 commit comments