Class: Sitemap::SitemapGenerator

Inherits:
BaseService
  • Object
show all
Defined in:
app/services/sitemap/sitemap_generator.rb

Overview

Operation to set a new source on invoices and related order and opportunity

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ SitemapGenerator

Returns a new instance of SitemapGenerator.



5
6
7
8
9
10
11
# File 'app/services/sitemap/sitemap_generator.rb', line 5

def initialize(options = {})
  require 'activerecord-import/base'
  require 'activerecord-import/active_record/adapters/postgresql_adapter'
  @url_builder_options = options[:url_builder_options] || {}
  @url_builder_options.reverse_merge!({ default_host: WEB_HOSTNAME_WITHOUT_PORT, default_port: APP_PORT_NUMBER, default_scheme: 'https' })
  super
end

Instance Attribute Details

#cleaned_tableObject (readonly)

Returns the value of attribute cleaned_table.



3
4
5
# File 'app/services/sitemap/sitemap_generator.rb', line 3

def cleaned_table
  @cleaned_table
end

Instance Method Details

#contact_form_pathsObject



178
179
180
181
182
183
# File 'app/services/sitemap/sitemap_generator.rb', line 178

def contact_form_paths
  Dir[Rails.root.join('app/views/contact_forms/*.html.erb')]
    .map { |f| File.basename(f, '.html.erb') }
    .reject { |name| name.start_with?('_') || name.end_with?('_thank_you') }
    .map { |name| "/contact/#{name.dasherize}" }
end

#generate_authors(ub, locale, params: {}) ⇒ Object



739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
# File 'app/services/sitemap/sitemap_generator.rb', line 739

def generate_authors(ub, locale, params: {})
  category = 'author'
  site_maps = []

  authors = EmployeeRecord.with_author_page
  last_mod = Post.published.maximum(:updated_at) || Date.current

  site_maps << {
    category: category,
    path: '/authors',
    last_mod: last_mod
  }

  author_party_ids = authors.map(&:party_id).compact
  latest_post_by_author = Post.published
                              .where(original_author_id: author_party_ids)
                              .group(:original_author_id)
                              .maximum(:updated_at)

  authors.each do |er|
    next if er.slug.blank?

    site_maps << {
      category: category,
      path: "/authors/#{er.slug}",
      last_mod: latest_post_by_author[er.party_id] || er.updated_at,
      resource_type: 'EmployeeRecord',
      resource_id: er.id,
      change_frequency: 'monthly'
    }
  end

  upsert_site_maps(locale, category, site_maps)
end

#generate_floor_plans(ub, locale, params: {}) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'app/services/sitemap/sitemap_generator.rb', line 65

def generate_floor_plans(ub, locale, params: {})
  category = 'floor_plan'
  site_maps = []
  # Index page
  site_maps << {
    category: category,
    path: '/floor-plans',
    last_mod: FloorPlanDisplay.maximum(:updated_at) || Date.current
  }

  # Individual floor plan displays
  FloorPlanDisplay.published.find_each do |fpd|
    # Extract path from route helper, stripping locale
    full_path = Rails.application.routes.url_helpers.www_floor_plan_display_path(fpd, locale: locale)
    path = SiteMap.extract_path_from_url(full_path)
    site_maps << {
      category: category,
      path: path,
      last_mod: fpd.updated_at,
      resource_type: 'FloorPlanDisplay',
      resource_id: fpd.id
    }
  end

  # Room-type listing pages that have content
  present_room_type_ids = FloorPlanDisplay.published.pluck(:room_types).flatten.compact.uniq.map(&:to_i)
  RoomType.where(id: present_room_type_ids).find_each do |rt|
    slug = rt.seo_key.presence || rt.name.parameterize
    site_maps << {
      category: category,
      path: "/floor-plans/#{slug}",
      last_mod: FloorPlanDisplay.published.where('room_types && ARRAY[?]::varchar[]', [rt.id.to_s]).maximum(:updated_at) || Date.current
    }
  end

  upsert_site_maps(locale, category, site_maps)
end

#generate_for_locale(locale, categories: nil, params: {}) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'app/services/sitemap/sitemap_generator.rb', line 37

def generate_for_locale(locale, categories: nil, params: {})
  page_count = 0
  I18n.with_locale(locale) do
    url_builder_options = { default_locale: locale }.merge(@url_builder_options)
    puts "url builder options: #{url_builder_options.inspect}"
    ub = Web::UrlBuilder.new(**url_builder_options)
    page_count += generate_pages(ub, locale, params:) if categories.blank? || categories.include?('static_page')
    page_count += generate_forms(ub, locale, params:) if categories.blank? || categories.include?('form')
    if categories.blank? || categories.include?('product')
      res = generate_products(ub, locale, params:)
      page_count += res[:count]
    end
    page_count += generate_floor_plans(ub, locale, params:) if categories.blank? || categories.include?('floor_plan')
    # page_count += generate_product_lines(ub, locale, params:) if categories.blank? || categories.include?('product_line')
    page_count += generate_posts(ub, locale, params:) if categories.blank? || categories.include?('post')
    page_count += (ub, locale, params:) if categories.blank? || categories.include?('post_tag')
    page_count += generate_tech_articles(ub, locale, params:) if categories.blank? || categories.include?('tech_article')
    page_count += generate_support_pages(ub, locale, params:) if categories.blank? || categories.include?('support')
    page_count += generate_publications(ub, locale, params:) if categories.blank? || categories.include?('publication')
    page_count += generate_videos(ub, locale, params:) if categories.blank? || categories.include?('video')
    page_count += generate_showcases(ub, locale, params:) if categories.blank? || categories.include?('showcase')

    page_count += generate_towel_warmer_filters(ub, locale, params:) if categories.blank? || categories.include?('towel_warmer_filter')
    page_count += generate_authors(ub, locale, params:) if categories.blank? || categories.include?('author')
  end
  page_count
end

#generate_forms(ub, locale, params: {}) ⇒ Object



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'app/services/sitemap/sitemap_generator.rb', line 161

def generate_forms(ub, locale, params: {})
  site_maps = []
  category = 'form'

  # Public form pages
  ['/contact', '/floor-heating/quote-builder', '/snow-melting/quote-builder'].each do |form_path|
    site_maps << { category: category, path: form_path, last_mod: 1.week.ago }
  end

  # Dynamic contact form pages (hidden from public XML sitemap but tracked for link validation)
  contact_form_paths.each do |form_path|
    site_maps << { category: category, path: form_path, last_mod: 1.week.ago, hide: true }
  end

  upsert_site_maps(locale, category, site_maps)
end

#generate_pages(ub, locale, params: {}) ⇒ Object



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'app/services/sitemap/sitemap_generator.rb', line 141

def generate_pages(ub, locale, params: {})
  site_maps = []
  category = 'static_page'
  pages = PagesController.page_ids.uniq
  pages = pages.reject { |page_id| page_id.starts_with?('h/') }
  pages.each do |page|
    p1 = Rails.root.join('app', 'views', 'pages', "#{page}.html.erb")
    p2 = Rails.root.join('app', 'views', 'pages', "#{page}.#{locale}.html.erb")
    next unless file_path = [p2, p1].detect { |f| File.exist?(f) }

    page_path = page == 'home' ? '/' : "/#{page}"
    site_maps << {
      category: category,
      path: page_path,
      last_mod: File.mtime(file_path)
    }
  end
  upsert_site_maps(locale, category, site_maps)
end

#generate_post_tags(ub, locale, params: {}) ⇒ Object



331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'app/services/sitemap/sitemap_generator.rb', line 331

def (ub, locale, params: {})
  category = 'post_tag'
  site_maps = []

  tag_rows = Post.published
                 .joins("INNER JOIN taggings ON taggings.taggable_id = articles.id AND taggings.taggable_type = 'Post'")
                 .joins('INNER JOIN tags ON tags.id = taggings.tag_id')
                 .group('tags.name')
                 .pluck('tags.name', Arel.sql('MAX(articles.updated_at)'))

  redirect_keys = TAG_MAP.keys.to_set
  seen_slugs = Set.new

  tag_rows.each do |tag_name, last_mod|
    slug = tag_name.parameterize
    next if seen_slugs.include?(slug)
    next if redirect_keys.include?(slug) || redirect_keys.include?(tag_name.downcase)

    seen_slugs << slug
    site_maps << {
      category: category,
      path: "/posts/#{slug}/tag",
      last_mod: last_mod || Date.current,
      change_frequency: 'weekly',
      priority: 0.4
    }
  end

  upsert_site_maps(locale, category, site_maps)
end

#generate_posts(ub, locale, params: {}) ⇒ Object



281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'app/services/sitemap/sitemap_generator.rb', line 281

def generate_posts(ub, locale, params: {})
  category = 'post'
  site_maps = []

  indexed_posts = Post.published.where.not(published_at: nil)
  last_mod_post = indexed_posts.maximum(:updated_at) || Date.current

  site_maps << {
    category: 'post',
    path: '/posts',
    last_mod: last_mod_post
  }

  indexed_posts.each do |post|
    site_maps << {
      category: 'post',
      path: "/posts/#{post.friendly_id}",
      last_mod: post.updated_at,
      resource_type: 'Article', # This is how STI works apparently
      resource_id: post.id,
      change_frequency: 'monthly'
    }
  end

  upsert_site_maps(locale, category, site_maps)
  site_maps.size
end

#generate_product_lines(ub, locale, params: {}) ⇒ Object

Process product line entry page, uses the product_line_urls discovered
in the product generation process or pulls them dynamically



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'app/services/sitemap/sitemap_generator.rb', line 187

def generate_product_lines(ub, locale, params: {})
  site_maps = []
  category = 'product_line'
  product_line_url_pattern = params[:product_line_url_pattern]
  product_line_urls = params[:product_line_urls] || []
  product_line_ids = params[:product_line_ids] || []

  if product_line_url_pattern.present?
    root_pl = ProductLine.find_by(slug_ltree: LtreePaths.slug_ltree_from_legacy_hyphen_url(product_line_url_pattern.delete_suffix('%')))
    product_line_ids += ProductLine.where(ProductLine[:ltree_path_ids].ltree_descendant(root_pl.ltree_path_ids)).pluck(:id) if root_pl
  end
  # Start with a base scope
  product_lines = ProductLine.available_to_public.where(show_in_sales_portal: true)
  delete_filter = nil

  if product_line_ids.present?
    product_lines = product_lines.where(id: product_line_ids)
    delete_filter = { resource_id: product_line_ids }
  elsif product_line_urls.present?
    # We take the product line urls passed no questions asked
    product_lines = product_lines.where(slug_ltree: product_line_urls)
    delete_filter = { resource_id: product_lines.map(&:id) }
  end

  # We make sure there's product available
  product_lines = product_lines.select { |pl| Www::ProductLinePresenter.new(pl).main_item }
  canonical_paths = ProductLine.canonical_paths_for(product_lines)

  product_lines.each do |product_line|
    pl_path = canonical_paths[product_line.id]
    next if pl_path.blank?

    site_maps << {
      path: ub.process("/#{pl_path}"),
      category: category,
      last_mod: product_line.updated_at,
      resource_type: 'ProductLine',
      resource_id: product_line.id
    }
  end

  upsert_site_maps(locale, category, site_maps, delete_filter: delete_filter)
end

#generate_products(ub, locale, params: {}) ⇒ Object



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'app/services/sitemap/sitemap_generator.rb', line 231

def generate_products(ub, locale, params: {})
  catalog_item_ids = params[:catalog_item_ids]
  product_line_url_pattern = params[:product_line_url_pattern]

  product_line_urls = []
  site_maps = []
  category = 'product'
  Catalog.locale_to_catalog(locale)
  products = ViewProductCatalog.locale_to_catalog(locale)
                               .visible_to_public.where(item_condition: 'new')
                               .where.not(item_primary_product_line_id: nil)
                               .order(:item_sku)
  if catalog_item_ids.present?
    products = products.where(id: catalog_item_ids)
  elsif product_line_url_pattern.present?
    root_pl = ProductLine.find_by(slug_ltree: LtreePaths.slug_ltree_from_legacy_hyphen_url(product_line_url_pattern.delete_suffix('%')))
    if root_pl
      products = products.where(ViewProductCatalog[:primary_pl_path_ids].ltree_descendant(root_pl.ltree_path_ids))
    end
  end

  # Batch-load items and precompute canonical paths to avoid N+1
  item_skus = products.map(&:item_sku)
  items_by_sku = Item.includes(:primary_product_line)
                     .where(sku: item_skus)
                     .index_by(&:sku)
  pl_ids = items_by_sku.values.filter_map(&:primary_product_line_id).uniq
  pl_canonical_paths = ProductLine.canonical_paths_for(ProductLine.where(id: pl_ids).to_a)

  products.each do |p|
    product_line_urls << p.item_primary_product_line_slug_ltree&.to_s

    item = items_by_sku[p.item_sku]
    pl_path = item&.primary_product_line_id ? pl_canonical_paths[item.primary_product_line_id] : nil
    path = "/#{pl_path}/#{p.item_sku}"

    site_maps << {
      category: category,
      path: path,
      last_mod: p.updated_at || p.created_at,
      resource_type: 'CatalogItem',
      resource_id: p.id
    }
  end

  upsert_site_maps(locale, category, site_maps)

  { count: site_maps.size, product_line_urls: product_line_urls.uniq.compact }
end

#generate_publications(ub, locale, params: {}) ⇒ Object



456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# File 'app/services/sitemap/sitemap_generator.rb', line 456

def generate_publications(ub, locale, params: {})
  category = 'publication'
  site_maps = []
  store_id = Store.store_id_for_locale(locale)
  publications = Item.indexable.publications_for_public_in_store(store_id)
                     .where.not(Item.arel_table[:sku].matches('CASE-STUDY-%'))
                     .order(:name)

  site_maps += publications.map do |p|
    {
      category: category,
      path: "/publications/#{p.sku}.pdf",
      last_mod: p.updated_at,
      resource_type: 'Item',
      resource_id: p.id
    }
  end
  upsert_site_maps(locale, category, site_maps)
end

#generate_showcases(ub, locale, params: {}) ⇒ Object

def generate_images(ub, locale)
logger.info "Processing images"
SiteMap.where(locale: locale, category: 'image').delete_all unless cleaned_table
page_count = 1

Image.for_sitemap.find_each do |image|
page_count += 1
SiteMap.create!(locale: locale,
category: 'image',
url: ub.process("#image.image_url(relative:true)"),
resource: image,
last_mod: image.updated_at || image.created_at)
end
logger.info "Processed #page_count image urls"
page_count
end



529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
# File 'app/services/sitemap/sitemap_generator.rb', line 529

def generate_showcases(ub, locale, params: {})
  category = 'showcase'
  site_maps = []
  indexed_showcases = Showcase.published
  last_mod_post = indexed_showcases.maximum(:updated_at) || Date.current

  site_maps << {
    category: category,
    path: '/showcases',
    last_mod: last_mod_post,
    image_properties: nil
  }

  indexed_showcases.select(&:custom_slug).each do |showcase|
    sm = {
      category: category,
      path: "/showcases/#{showcase.custom_slug}",
      last_mod: showcase.updated_at,
      change_frequency: 'monthly',
      resource_type: 'Showcase',
      resource_id: showcase.id
    }

    if showcase.respond_to?(:digital_assets)
      images = showcase.digital_assets.images
      if images.present?
        sm[:image_properties] = images.map do |image|
          {
            loc: image.image_url(relative: true, width: 600).to_s,
            caption: image.seo_title.presence || image.title.presence,
            geo_location: image.location.presence,
            title: image.title.presence
          }.compact
        end
      end
    end
    site_maps << sm
  end

  upsert_site_maps(locale, category, site_maps)
end

#generate_single_post(post) ⇒ Object

Generates a single post sitemap entry (at time of publication for instance)



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'app/services/sitemap/sitemap_generator.rb', line 310

def generate_single_post(post)
  return unless post.published?

  SiteMap.transaction do
    LocaleUtility.service_locales.each do |locale|
      site_map = SiteMap.where(locale: locale.to_s,
                               category: 'post',
                               resource_type: 'Article',
                               resource_id: post.id).first_or_initialize
      path = "/posts/#{post.friendly_id}"
      logger.info "Generating post sitemap for #{post.friendly_id} with path #{path} in #{locale}"

      site_map.update!(
        path: path,
        last_mod: post.updated_at,
        change_frequency: 'monthly'
      )
    end
  end
end

#generate_single_showcase(showcase) ⇒ Object

Generates a single showcase sitemap entry (at time of publication for instance)



572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
# File 'app/services/sitemap/sitemap_generator.rb', line 572

def generate_single_showcase(showcase)
  return unless showcase.respond_to?(:state) ? (showcase.state == 'published') : showcase.published?

  SiteMap.transaction do
    LocaleUtility.service_locales.each do |locale|
      site_map = SiteMap.where(locale: locale.to_s,
                               category: 'showcase',
                               resource_type: 'Showcase',
                               resource_id: showcase.id).first_or_initialize
      path = if showcase.respond_to?(:custom_slug)
               "/showcases/#{showcase.custom_slug}"
             else
               SiteMap.extract_path_from_url(showcase.showcase_link)
             end
      logger.info "Generating showcase sitemap for #{showcase.try(:friendly_id) || showcase.try(:id)} with path #{path} in #{locale}"

      site_map.update!(
        path: path,
        last_mod: showcase.updated_at,
        change_frequency: 'monthly'
      )
    end
  end
end

#generate_support_pages(ub, locale, params: {}) ⇒ Object



386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
# File 'app/services/sitemap/sitemap_generator.rb', line 386

def generate_support_pages(ub, locale, params: {})
  category = 'support'
  site_maps = []
  additional_slug_ltrees = [LtreePaths::PL_FLOOR_HEATING_CONTROL]
  indexed_support_index_ids = ProductLine.main_product_lines.support_portal_sorted.pluck(:id)
  indexed_support_index_ids += ProductLine.where(slug_ltree: additional_slug_ltrees).pluck(:id)

  indexed_support_index_pls = ProductLine.where(id: indexed_support_index_ids.uniq).to_a

  # Collect all product lines (main + descendants) for batch canonical_path computation
  all_descendant_pls = indexed_support_index_pls.flat_map do |mpl|
    mpl.descendants.for_support_portal.reject do |pl|
      pl.all_my_support_items.where.not(sku: 'UDG4-4999').where(visible_for_support: true).size == 1
    end
  end
  all_pls = indexed_support_index_pls + all_descendant_pls
  canonical_paths = ProductLine.canonical_paths_for(all_pls)

  indexed_support_index_pls.each do |mpl|
    pl_path = canonical_paths[mpl.id]
    next if pl_path.blank?

    site_maps << {
      category: category,
      change_frequency: 'monthly',
      priority: 0.7,
      path: "/#{pl_path}/support",
      last_mod: mpl.updated_at || mpl.created_at,
      resource_type: 'ProductLine',
      resource_id: mpl.id
    }
  end

  all_descendant_pls.each do |dpl|
    dpl_path = canonical_paths[dpl.id]
    next if dpl_path.blank?

    site_maps << {
      category: category,
      change_frequency: 'monthly',
      priority: 0.7,
      path: "/#{dpl_path}/support",
      last_mod: dpl.updated_at || dpl.created_at,
      resource_type: 'ProductLine',
      resource_id: dpl.id
    }
  end

  # Batch-load primary product lines for canonical_path computation
  support_items = Item.goods_visible_for_support.includes(:primary_product_line).to_a
  pl_ids = support_items.filter_map(&:primary_product_line_id).uniq
  pl_paths = ProductLine.canonical_paths_for(ProductLine.where(id: pl_ids).to_a)

  support_items.each do |ri|
    pl_path = ri.primary_product_line_id ? pl_paths[ri.primary_product_line_id] : nil
    next if pl_path.blank?

    support_path = "/#{pl_path}/#{ri.sku}/support"
    site_maps << {
      category: category,
      path: support_path,
      change_frequency: 'monthly',
      last_mod: ri.updated_at || ri.created_at,
      resource_type: 'Item',
      resource_id: ri.id
    }
  end
  upsert_site_maps(locale, category, site_maps)
end

#generate_tech_articles(ub, locale, params: {}) ⇒ Object



362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
# File 'app/services/sitemap/sitemap_generator.rb', line 362

def generate_tech_articles(ub, locale, params: {})
  category = 'tech_article'
  site_maps = []
  indexed_articles = ArticleTechnical.published.where.not(published_at: nil)
  last_mod_article = indexed_articles.maximum(:published_at) || Date.current
  site_maps << {
    category: 'tech_article',
    path: '/support',
    last_mod: last_mod_article
  }

  site_maps += indexed_articles.map do |a|
    {
      category: 'tech_article',
      path: "/support/articles/#{a.friendly_id}",
      last_mod: a.published_at,
      resource_type: 'Article',
      change_frequency: 'monthly',
      resource_id: a.id
    }
  end
  upsert_site_maps(locale, category, site_maps)
end

#generate_towel_warmer_filters(ub, locale, params: {}) ⇒ Object

Generate sitemap entries for towel warmer filter pages
Creates entries for SEO-friendly filter URLs like:
/towel-warmer/brushed-gold
/towel-warmer/wall-mounted
/towel-warmer/brushed-gold/wall-mounted



604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
# File 'app/services/sitemap/sitemap_generator.rb', line 604

def generate_towel_warmer_filters(ub, locale, params: {})
  category = 'towel_warmer_filter'
  site_maps = []
  last_mod = ViewProductCatalog.where(ViewProductCatalog[:item_primary_product_line_slug_ltree].ltree_descendant('towel_warmer'))
                                .maximum(:updated_at) || Date.current

  # Single-dimension filter pages (highest priority for SEO)
  # Finishes - high traffic potential (skip individual gold finishes — consolidated into /gold)
  TowelWarmerFilterSlugs::FINISH_SLUGS.each_key do |slug|
    next if %w[brushed-gold polished-gold].include?(slug)

    site_maps << {
      category: category,
      path: "/towel-warmer/#{slug}",
      last_mod: last_mod,
      priority: 0.7,
      change_frequency: 'weekly'
    }
  end

  # Composite finish pages (e.g. /towel-warmer/gold = brushed + polished)
  TowelWarmerFilterSlugs::COMPOSITE_FINISH_SLUGS.each_key do |slug|
    site_maps << {
      category: category,
      path: "/towel-warmer/#{slug}",
      last_mod: last_mod,
      priority: 0.7,
      change_frequency: 'weekly'
    }
  end

  # Mounting types - core navigation
  TowelWarmerFilterSlugs::MOUNTING_SLUGS.each_key do |slug|
    site_maps << {
      category: category,
      path: "/towel-warmer/#{slug}",
      last_mod: last_mod,
      priority: 0.7,
      change_frequency: 'weekly'
    }
  end

  # Connection types
  TowelWarmerFilterSlugs::CONNECTION_SLUGS.each_key do |slug|
    site_maps << {
      category: category,
      path: "/towel-warmer/#{slug}",
      last_mod: last_mod,
      priority: 0.6,
      change_frequency: 'weekly'
    }
  end

  # Bar shapes/styles
  TowelWarmerFilterSlugs::STYLE_SLUGS.each_key do |slug|
    site_maps << {
      category: category,
      path: "/towel-warmer/#{slug}",
      last_mod: last_mod,
      priority: 0.6,
      change_frequency: 'weekly'
    }
  end

  # Size tiers — compact / standard / large (based on physical height)
  # SIZE_SLUGS is a plain array, not a hash
  TowelWarmerFilterSlugs::SIZE_SLUGS.each do |slug|
    site_maps << {
      category: category,
      path: "/towel-warmer/#{slug}",
      last_mod: last_mod,
      priority: 0.7,
      change_frequency: 'weekly'
    }
  end

  # Key two-dimension combinations (finish + mounting)
  # These have high search intent: "brushed gold wall mounted towel warmer"
  # Only include combinations that actually have products — empty pages 301-redirect
  # at runtime (TowelWarmersController) and must not appear in the sitemap.
  non_empty_finish_mounting_paths = towel_warmer_non_empty_finish_mounting_paths
  TowelWarmerFilterSlugs::FINISH_SLUGS.each_key do |finish_slug|
    TowelWarmerFilterSlugs::MOUNTING_SLUGS.each_key do |mounting_slug|
      path = "#{finish_slug}/#{mounting_slug}"
      next unless non_empty_finish_mounting_paths.include?(path)

      site_maps << {
        category: category,
        path: "/towel-warmer/#{path}",
        last_mod: last_mod,
        priority: 0.5,
        change_frequency: 'weekly'
      }
    end
  end

  upsert_site_maps(locale, category, site_maps)
end

#generate_videos(ub, locale, params: {}) ⇒ Object



476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
# File 'app/services/sitemap/sitemap_generator.rb', line 476

def generate_videos(ub, locale, params: {})
  category = 'video'
  site_maps = []
  site_maps << {
    category: category,
    path: '/video-media',
    last_mod: Video.maximum(:updated_at) || Date.current,
    resource_type: nil,
    resource_id: nil
  }

  Video.public_videos.find_each do |video|
    site_maps << {
      category: category,
      path: "/video-media/#{video.slug}",
      last_mod: video.updated_at || video.created_at,
      resource_type: 'DigitalAsset',
      resource_id: video.id,
      image_properties: {
        thumbnail_loc: video.thumbnail_url(width: 1280, height: 720),
        title: video.respond_to?(:title) ? video.title : nil,
        description: video.respond_to?(:meta_description) ? video.meta_description : nil,
        content_loc: "#{CF_STREAM_URL}/#{video.cloudflare_uid}/downloads/default.mp4",
        player_loc: "#{CF_STREAM_URL}/#{video.cloudflare_uid}/iframe?poster=#{URI.encode_www_form_component(video.thumbnail_url(width: 1280, height: 720))}",
        duration: video.duration_in_seconds,
        publication_date: video.respond_to?(:created_at) ? video.created_at : nil,
        family_friendly: true ? 'yes' : 'no',
        requires_subscription: false ? 'yes' : 'no',
        uploader: 'WarmlyYours',
        live: video.category == 'webinar' ? 'yes' : 'no'
      }.compact
    }
  end
  upsert_site_maps(locale, category, site_maps)
end

#process(options = {}) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'app/services/sitemap/sitemap_generator.rb', line 13

def process(options = {})
  locales = options[:locales]&.map(&:to_sym) || LocaleUtility.service_locales
  page_count = 0
  # NOTE: We no longer delete_all at the start. The upsert_site_maps method
  # handles this properly using the 'preserve' flag pattern:
  # 1. New/updated records get preserve=true
  # 2. Obsolete records (preserve=false) are deleted
  # 3. This preserves extracted_content and embedding references
  @cleaned_table = false
  locales.each do |locale|
    page_count += generate_for_locale(locale, categories: options[:categories]&.map(&:to_s), params: options[:params] || {})
  end
  # Publish event so SitemapRegeneratedHandler queues the content extraction crawl.
  # Skip in development to avoid hitting localhost from background threads.
  options[:skip_warmup] = Rails.env.development? if options[:skip_warmup].nil?
  return if options[:skip_warmup]

  event_data = {}
  event_data[:locale]   = options[:locales].first.to_s if options[:locales]&.one?
  event_data[:category] = options[:categories].first   if options[:categories]&.one?
  Rails.configuration.event_store.publish(Events::SitemapRegenerated.new(data: event_data))
  logger.info 'Published Events::SitemapRegenerated — crawler will be queued by handler'
end

#towel_warmer_non_empty_finish_mounting_pathsObject

Returns a Set of "finish_slug/mounting_slug" path strings that have at least
one visible product. Used to skip empty finish+mounting combinations so they
are never included in the sitemap (they 301-redirect at runtime anyway).

A single GROUP BY query covers all 10 combinations in one round-trip.



710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
# File 'app/services/sitemap/sitemap_generator.rb', line 710

def towel_warmer_non_empty_finish_mounting_paths
  rows = ViewProductCatalog
           .visible_to_public
           .where(item_condition: 'new')
           .where(ViewProductCatalog[:primary_pl_path_slugs].ltree_descendant(LtreePaths::PL_TOWEL_WARMER))
           .where(ViewProductCatalog[:pc_path_slugs].ltree_descendant(LtreePaths::PC_TOWEL_WARMERS))
           .excluding_refurbished
           .where.not(item_primary_product_line_slug_ltree: 'towel_warmer.crystal_accessories')
           .group(
             Arel.sql("product_specifications -> 'finish' ->> 'raw'"),
             Arel.sql("product_specifications -> 'mounting_method' ->> 'raw'")
           )
           .count

  slug_set = Set.new
  rows.each do |(finish_val, mounting_val), count|
    next if count.zero?

    finish_slug   = TowelWarmerFilterSlugs::RANSACK_TO_SLUG[finish_val]
    mounting_slug = TowelWarmerFilterSlugs::RANSACK_TO_SLUG[mounting_val] ||
                    TowelWarmerFilterSlugs::MOUNTING_SLUGS.key(mounting_val)
    next unless finish_slug && mounting_slug

    slug_set << "#{finish_slug}/#{mounting_slug}"
  end

  slug_set
end

#upsert_site_maps(locale, category, site_maps, delete_filter: nil) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'app/services/sitemap/sitemap_generator.rb', line 103

def upsert_site_maps(locale, category, site_maps, delete_filter: nil)
  import_res = nil
  SiteMap.transaction do
    # Mark all newly inserted/updated records as active and preserved for this run.
    site_maps = site_maps.map do |h|
      sm = if h.is_a?(Hash)
             SiteMap.new(h)
           else
             h
           end
      sm.locale = locale.to_s
      sm.preserve = true
      sm.state = :active
      sm.change_frequency ||= 'weekly'
      sm.priority ||= 0.5
      sm
    end
    site_maps = site_maps.uniq { |sm| [sm.locale, sm.path] }
    # Include `state` in on_duplicate_key_update so archived URLs auto-reactivate
    # when they reappear in a subsequent run.
    import_res = SiteMap.import site_maps, on_duplicate_key_update: {
      conflict_target: %i[locale path],
      columns: %i[last_mod preserve image_properties resource_id resource_type category state]
    }
    base_scope = SiteMap.where(locale: locale.to_s, category: category)
    base_scope = base_scope.where(delete_filter) if delete_filter.present?
    unless cleaned_table
      # Archive active entries that were not touched in this run (preserve still false).
      # Archiving preserves all child data (seo_page_keywords, data_points, embeddings).
      stale_ids = base_scope.active.where(preserve: false).pluck(:id)
      SiteMap.where(id: stale_ids).update_all(state: 'archived') if stale_ids.any?
    end
    # Reset preserve flag on active entries so they are eligible for archival next run.
    base_scope.active.where(preserve: true).update_all(preserve: false)
  end
  site_maps.size
end