Class: ScheduleWorkers::GenerateTopPackagesWorker
- Inherits:
-
ApplicationWorker
- Object
- ApplicationWorker
- ScheduleWorkers::GenerateTopPackagesWorker
- Includes:
- ElasticAPM::SpanHelpers
- Defined in:
- app/workers/schedule_workers/generate_top_packages_worker.rb
Overview
typed: ignore frozen_string_literal: true
Instance Method Summary collapse
Methods inherited from ApplicationWorker
Instance Method Details
#perform ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 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 64 65 66 67 68 69 70 71 |
# File 'app/workers/schedule_workers/generate_top_packages_worker.rb', line 9 def perform return unless ENV['CLICKHOUSE_HOST'].present? top_label = CustomLabel.find_by! defined_label: 'top' BUSINESS_LOGGER.set_business_context(worker: self.class.name) BUSINESS_LOGGER.info('Starting top packages calculation using ClickHouse') restaurant_to_be_touched = [] # Calculate top packages for all restaurants using ClickHouse top_packages_by_restaurant = HhClickHouseTopPackage.calculate_for_all_restaurants(days: 30) BUSINESS_LOGGER.info('Top packages calculated', { restaurants_with_top_packages: top_packages_by_restaurant.keys.count, }) # Process each restaurant that has top packages top_packages_by_restaurant.each do |restaurant_id, top_packages| restaurant = ::Restaurant.find_by(id: restaurant_id) next if restaurant.blank? next unless restaurant.active? && (restaurant.expiry_date.nil? || restaurant.expiry_date >= Date.current) # Clear existing custom labels for all packages of this restaurant restaurant.restaurant_packages.update_all custom_label_id: nil # Set top label for rank 1 packages top_packages.each do |package_result| next unless package_result[:rank] == 1 restaurant_package = restaurant.restaurant_packages.find_by( package_id: package_result[:package_id], package_type: package_result[:package_type], ) if restaurant_package.present? restaurant_package.update!(custom_label_id: top_label.id) restaurant_to_be_touched.push(restaurant_package.restaurant_id) BUSINESS_LOGGER.info('Top package labeled', { restaurant_id: restaurant_id, package_id: package_result[:package_id], package_type: package_result[:package_type], quantity_sold: package_result[:quantity_sold], }) end end end # Touch all affected restaurants to invalidate caches ::Restaurant.where(id: restaurant_to_be_touched.uniq).find_each(&:refresh_view_cache_key) BUSINESS_LOGGER.info('Top packages calculation completed', { restaurants_touched: restaurant_to_be_touched.uniq.count, }) rescue StandardError => e BUSINESS_LOGGER.error('Top packages calculation failed', { error: e., backtrace: e.backtrace, }) APMErrorHandler.report(e, context: { worker: self.class.name }) raise end |