Sha256: b7321d4645fe34eb73bac5d03f33d1d0d2204d00dd0b44f043f97ee358b159ea

Contents?: true

Size: 1.73 KB

Versions: 13

Compression:

Stored size: 1.73 KB

Contents

module Workarea
  module Insights
    class TrendingProducts < Base
      class << self
        def dashboards
          %w(catalog)
        end

        def generate_monthly!
          results = generate_results.map { |r| r.merge(product_id: r['_id']) }
          create!(results: results) if results.present?
        end

        def generate_results
          Metrics::ProductByWeek
            .collection
            .aggregate([filter_date_range, group_by_product, add_improving_weeks, sort, limit])
            .to_a
        end

        def filter_date_range
          {
            '$match' => {
              'reporting_on' => {
                '$gte' => beginning_of_last_month,
                '$lte' => end_of_last_month
              }
            }
          }
        end

        def group_by_product
          {
            '$group' => {
              '_id' => '$product_id',
              'improving_weeks' => { '$sum' => 1 },
              'revenue_changes' => { '$push' => '$revenue_change' },
              'orders' => { '$sum' => '$orders' }
            }
          }
        end

        def add_improving_weeks
          {
            '$addFields' => {
              'improving_weeks' => {
                '$size' => {
                  '$filter' => {
                    'input' => '$revenue_changes',
                    'as' => 'revenue_change',
                    'cond' => { '$gt' => ['$$revenue_change', 0] }
                  }
                }
              }
            }
          }
        end

        def sort
          { '$sort' => { 'improving_weeks' => -1, 'orders' => -1 } }
        end

        def limit
          { '$limit' => Workarea.config.insights_products_list_max_results }
        end
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
workarea-core-3.4.22 app/models/workarea/insights/trending_products.rb
workarea-core-3.5.0 app/models/workarea/insights/trending_products.rb
workarea-core-3.4.21 app/models/workarea/insights/trending_products.rb
workarea-core-3.5.0.beta.1 app/models/workarea/insights/trending_products.rb
workarea-core-3.4.20 app/models/workarea/insights/trending_products.rb
workarea-core-3.4.19 app/models/workarea/insights/trending_products.rb
workarea-core-3.4.18 app/models/workarea/insights/trending_products.rb
workarea-core-3.4.17 app/models/workarea/insights/trending_products.rb
workarea-core-3.4.16 app/models/workarea/insights/trending_products.rb
workarea-core-3.4.15 app/models/workarea/insights/trending_products.rb
workarea-core-3.4.14 app/models/workarea/insights/trending_products.rb
workarea-core-3.4.13 app/models/workarea/insights/trending_products.rb
workarea-core-3.4.12 app/models/workarea/insights/trending_products.rb