Class: Workarea::Reports::ReviewsByProduct

Inherits:
Object
  • Object
show all
Includes:
Report
Defined in:
app/queries/workarea/reports/reviews_by_product.rb

Instance Method Summary collapse

Instance Method Details

#aggregationObject



9
10
11
# File 'app/queries/workarea/reports/reviews_by_product.rb', line 9

def aggregation
  [filter_results, project_used_fields, group_by_product, project_averages]
end

#filter_resultsObject



13
14
15
16
17
18
19
20
# File 'app/queries/workarea/reports/reviews_by_product.rb', line 13

def filter_results
  {
    '$match' => {
      'created_at' => { '$gte' => starts_at, '$lte' => ends_at },
      **approval_query
    }
  }
end

#group_by_productObject



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'app/queries/workarea/reports/reviews_by_product.rb', line 32

def group_by_product
  {
    '$group' => {
      '_id' => '$product_id',
      'reviews' => { '$sum' => 1 },
      'verified' => { '$sum' => { '$cond' => { 'if' => '$verified', 'then' => 1, 'else' => 0 } } },
      'rating_tally' => { '$sum' => '$rating' },
      'rated_5' => { '$sum' => { '$cond' => { 'if' => { '$eq' => ['$rating', 5] }, 'then' => 1, 'else' => 0 } } },
      'rated_4' => { '$sum' => { '$cond' => { 'if' => { '$eq' => ['$rating', 4] }, 'then' => 1, 'else' => 0 } } },
      'rated_3' => { '$sum' => { '$cond' => { 'if' => { '$eq' => ['$rating', 3] }, 'then' => 1, 'else' => 0 } } },
      'rated_2' => { '$sum' => { '$cond' => { 'if' => { '$eq' => ['$rating', 2] }, 'then' => 1, 'else' => 0 } } },
      'rated_1' => { '$sum' => { '$cond' => { 'if' => { '$eq' => ['$rating', 1] }, 'then' => 1, 'else' => 0 } } }
    }
  }
end

#project_averagesObject



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/queries/workarea/reports/reviews_by_product.rb', line 48

def project_averages
  {
    '$project' => {
      'product_id' => 1,
      'reviews' => 1,
      'verified' => 1,
      'average_rating' => { '$divide' => ['$rating_tally', '$reviews'] },
      'weighted_average_rating' => {
        '$divide' => [
          {
            '$sum' => [
              { '$multiply' => [{ '$sum' => [2, '$rated_5'] }, 5] },
              { '$multiply' => [{ '$sum' => [2, '$rated_4'] }, 4] },
              { '$multiply' => [{ '$sum' => [2, '$rated_3'] }, 3] },
              { '$multiply' => [{ '$sum' => [2, '$rated_2'] }, 2] },
              { '$multiply' => [{ '$sum' => [2, '$rated_1'] }, 1] }
            ]
          },
          { '$sum' => [10, '$rated_5', '$rated_4', '$rated_3', '$rated_2', '$rated_1'] }
        ]
      }
    }
  }
end

#project_used_fieldsObject



22
23
24
25
26
27
28
29
30
# File 'app/queries/workarea/reports/reviews_by_product.rb', line 22

def project_used_fields
  {
    '$project' => {
      'product_id' => 1,
      'rating' => 1,
      'verified' => 1
    }
  }
end