-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Expand file tree
/
Copy pathanalytics_service.rb
More file actions
332 lines (285 loc) · 13.1 KB
/
analytics_service.rb
File metadata and controls
332 lines (285 loc) · 13.1 KB
1
2
3
4
5
6
7
8
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
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
102
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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
230
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
280
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
class AnalyticsService
DEFAULT_REACTION_TOTALS = {
total: 0, like: 0, readinglist: 0, unicorn: 0,
exploding_head: 0, raised_hands: 0, fire: 0, unique_reactors: 0
}.freeze
def initialize(user_or_org, start_date: "", end_date: "", article_id: nil)
@user_or_org = user_or_org
@article_id = article_id
@start_date = Time.zone.parse(start_date.to_s)&.beginning_of_day
@end_date = Time.zone.parse(end_date.to_s)&.end_of_day || Time.current.end_of_day
load_data
end
# Computes total counts for comments, reactions, follows and page views
def totals
{
comments: { total: comment_data.size },
follows: { total: follow_data.size },
reactions: calculate_reactions_totals,
page_views: calculate_page_views_totals
}
end
# Computes counts for comments, reactions, follows and page views per each day
def grouped_by_day
return {} unless start_date && end_date
# cache all stats in the date range for the requested user or organization
cache_key = "analytics-for-dates-#{start_date}-#{end_date}-#{user_or_org.class.name}-#{user_or_org.id}"
cache_key = "#{cache_key}-article-#{article_id}" if article_id
Rails.cache.fetch(cache_key, expires_in: 7.days) do
# 1. calculate all stats using group queries at once
comments_stats_per_day = calculate_comments_stats_per_day(comment_data)
follows_stats_per_day = calculate_follows_stats_per_day(follow_data)
reactions_stats_per_day = calculate_reactions_stats_per_day(reaction_data)
page_views_stats_per_day = calculate_page_views_stats_per_day(page_view_data)
# 2. build the final hash, one per each day
stats = {}
(start_date.to_date..end_date.to_date).each do |date|
stats[date.iso8601] = stats_per_day(
date,
comments_stats: comments_stats_per_day,
follows_stats: follows_stats_per_day,
reactions_stats: reactions_stats_per_day,
page_views_stats: page_views_stats_per_day,
)
end
stats
end
end
# Returns the list of referrers
def referrers(top: 20)
# count_all is the name of the field autogenerated by Rails with COUNT(*)
counts = page_view_data
.group(:domain)
.order(Arel.sql("sum_counts_for_number_of_views DESC"))
.limit(top)
.sum("counts_for_number_of_views")
# we transform this in a list of hashes in case we need to add more keys
domains = counts.map { |domain, count| { domain: domain, count: count } }
{ domains: domains }
end
# Returns top contributors who engaged with the user/org's articles
# via reactions (excl. bookmarks) and comments, excluding self-interactions.
# Comments are weighted 6x, reactions 1x.
def top_contributors(limit: 20)
return [] unless article_data.exists?
# Use subqueries to avoid loading all IDs into memory for large datasets
article_ids_subquery = article_data.select(:id)
# Determine author IDs to exclude self-interactions
author_ids = article_data.distinct.pluck(:user_id)
# Reactions (excl readinglist/self) → weight 1
reactions_sql = Reaction.for_analytics
.where(reactable_id: article_ids_subquery, reactable_type: "Article")
.where.not(category: "readinglist")
.where.not(user_id: author_ids)
reactions_sql = reactions_sql.where(created_at: start_date..end_date) if start_date && end_date
reactions_query = reactions_sql
.select("user_id, COUNT(*) AS reactions_count, 0 AS comments_count, COUNT(*) AS score")
.group(:user_id)
# Comments (excl self, score > 0) → weight 6
# Comments carry more weight than reactions because they require
# significantly more effort and drive meaningful discussion.
comments_sql = Comment
.where(commentable_id: article_ids_subquery, commentable_type: "Article")
.where("score > 0")
.where.not(user_id: author_ids)
comments_sql = comments_sql.where(created_at: start_date..end_date) if start_date && end_date
comments_query = comments_sql
.select("user_id, 0 AS reactions_count, COUNT(*) AS comments_count, COUNT(*) * 6 AS score")
.group(:user_id)
# UNION and aggregate
union_sql = "(" \
"#{reactions_query.to_sql}" \
" UNION ALL " \
"#{comments_query.to_sql}" \
")"
rows = ActiveRecord::Base.connection.select_all(
"SELECT user_id, SUM(reactions_count)::int AS reactions_count, " \
"SUM(comments_count)::int AS comments_count, SUM(score)::int AS score " \
"FROM #{union_sql} AS combined " \
"GROUP BY user_id ORDER BY score DESC, user_id ASC LIMIT #{limit.to_i}",
)
user_ids = rows.map { |r| r["user_id"] }
users_by_id = User.where(id: user_ids).index_by(&:id)
rows.filter_map do |row|
user = users_by_id[row["user_id"]]
next unless user
{
user_id: user.id,
username: user.username,
name: user.name,
profile_image: user.profile_image_90,
reactions_count: row["reactions_count"],
comments_count: row["comments_count"],
score: row["score"]
}
end
end
# Returns what percentage of followers engaged (reacted or commented)
# with the user/org's articles in the given period.
def follower_engagement
follower_scope = Follow
.where(followable_type: user_or_org.class.name, followable_id: user_or_org.id)
.where(blocked: false)
total_followers = follower_scope.count
return { total_followers: 0, engaged_followers: 0, ratio: 0.0 } if total_followers.zero?
return { total_followers: total_followers, engaged_followers: 0, ratio: 0.0 } unless article_data.exists?
follower_ids_subquery = follower_scope.select(:follower_id)
article_ids_subquery = article_data.select(:id)
# Followers who reacted (excl readinglist)
reacting_scope = Reaction.for_analytics
.where(reactable_id: article_ids_subquery, reactable_type: "Article")
.where.not(category: "readinglist")
.where(user_id: follower_ids_subquery)
reacting_scope = reacting_scope.where(created_at: start_date..end_date) if start_date && end_date
# Followers who commented (score > 0)
commenting_scope = Comment
.where(commentable_id: article_ids_subquery, commentable_type: "Article")
.where("score > 0")
.where(user_id: follower_ids_subquery)
commenting_scope = commenting_scope.where(created_at: start_date..end_date) if start_date && end_date
engaged_count = ActiveRecord::Base.connection.select_value(
"SELECT COUNT(DISTINCT user_id) FROM (" \
"#{reacting_scope.select(:user_id).to_sql} UNION ALL #{commenting_scope.select(:user_id).to_sql}" \
") AS engaged",
).to_i
{
total_followers: total_followers,
engaged_followers: engaged_count,
ratio: (engaged_count.to_f / total_followers * 100).round(1)
}
end
private
attr_reader(
:user_or_org, :article_id, :start_date, :end_date,
:article_data, :reaction_data, :comment_data, :follow_data, :page_view_data
)
def load_data
@article_data = Article.published.from_subforem.where("#{user_or_org.class.name.downcase}_id" => user_or_org.id)
if @article_id
@article_data = @article_data.where(id: @article_id)
# check article_id is published and belongs to the user/org
raise ArgumentError, I18n.t("services.analytics_service.no_stats") unless @article_data.exists?
article_ids = [@article_id]
else
article_ids = @article_data.ids
end
# prepare relations for metrics
@comment_data = Comment
.where(commentable_id: article_ids, commentable_type: "Article")
.where("score > 0")
@follow_data = Follow
.where(followable_type: user_or_org.class.name, followable_id: user_or_org.id)
@reaction_data = Reaction.for_analytics
.where(reactable_id: article_ids, reactable_type: "Article")
@page_view_data = PageView.where(article_id: article_ids)
# filter data by date if needed
return unless start_date && end_date
@comment_data = @comment_data.where(created_at: @start_date..@end_date)
@reaction_data = @reaction_data.where(created_at: @start_date..@end_date)
@page_view_data = @page_view_data.where(created_at: @start_date..@end_date)
end
def calculate_reactions_totals
# NOTE: the order of the keys needs to be the same as the one of the counts
keys = %i[total like readinglist unicorn exploding_head raised_hands fire unique_reactors]
counts = reaction_data.pick(
Arel.sql("COUNT(*)"),
Arel.sql("COUNT(*) FILTER (WHERE category = 'like')"),
Arel.sql("COUNT(*) FILTER (WHERE category = 'readinglist')"),
Arel.sql("COUNT(*) FILTER (WHERE category = 'unicorn')"),
Arel.sql("COUNT(*) FILTER (WHERE category = 'exploding_head')"),
Arel.sql("COUNT(*) FILTER (WHERE category = 'raised_hands')"),
Arel.sql("COUNT(*) FILTER (WHERE category = 'fire')"),
Arel.sql("COUNT(DISTINCT user_id)"),
)
if counts
# this transforms the counts, eg. [1, 0, 1, 0, ...]
# in a hash, eg. {total: 1, like: 0, readinglist: 1, unicorn: 0, ...}
keys.zip(counts).to_h
else
DEFAULT_REACTION_TOTALS
end
end
def calculate_page_views_totals
total_views = article_data.sum(:page_views_count)
logged_in_page_view_data = page_view_data.where.not(user_id: nil)
average = logged_in_page_view_data.pick(Arel.sql("AVG(time_tracked_in_seconds)"))
average_read_time_in_seconds = (average || 0).round # average is a BigDecimal
{
total: total_views,
average_read_time_in_seconds: average_read_time_in_seconds,
total_read_time_in_seconds: average_read_time_in_seconds * total_views
}
end
def calculate_comments_stats_per_day(comment_data)
# AR returns a hash with date => count, we transform it using ISO dates for convenience
comment_data.group("DATE(created_at)").count.transform_keys(&:iso8601)
end
def calculate_follows_stats_per_day(follow_data)
# AR returns a hash with date => count, we transform it using ISO dates for convenience
follow_data.group("DATE(created_at)").count.transform_keys(&:iso8601)
end
def calculate_reactions_stats_per_day(reaction_data)
# we issue one single query that contains all requested aggregates
# and that groups them by date
reactions = reaction_data.select(
Arel.sql("DATE(created_at)").as("date"),
Arel.sql("COUNT(*)").as("total"),
Arel.sql("COUNT(*) FILTER (WHERE category = 'like')").as("like"),
Arel.sql("COUNT(*) FILTER (WHERE category = 'readinglist')").as("readinglist"),
Arel.sql("COUNT(*) FILTER (WHERE category = 'unicorn')").as("unicorn"),
Arel.sql("COUNT(*) FILTER (WHERE category = 'exploding_head')").as("exploding_head"),
Arel.sql("COUNT(*) FILTER (WHERE category = 'raised_hands')").as("raised_hands"),
Arel.sql("COUNT(*) FILTER (WHERE category = 'fire')").as("fire"),
Arel.sql("COUNT(DISTINCT user_id)").as("unique_reactors"),
).group("DATE(created_at)")
# this transforms the collection of pseudo Reaction objects previously selected
# in a hash with all reaction category counts plus unique reactors
reactions.each_with_object({}) do |reaction, hash|
hash[reaction.date.iso8601] = {
total: reaction.total,
like: reaction.like,
readinglist: reaction.readinglist,
unicorn: reaction.unicorn,
exploding_head: reaction.exploding_head,
raised_hands: reaction.raised_hands,
fire: reaction.fire,
unique_reactors: reaction.unique_reactors
}
end
end
def calculate_page_views_stats_per_day(page_view_data)
# we issue one single query that contains all requested aggregates
# and that groups them by date
page_views = page_view_data.select(
Arel.sql("DATE(created_at)").as("date"),
Arel.sql("SUM(counts_for_number_of_views)").as("total"),
# count the average only for logged in users
Arel.sql("AVG(time_tracked_in_seconds) FILTER (WHERE user_id IS NOT NULL)").as("average"),
).group("DATE(created_at)")
# this transforms the collection of pseudo PageView objects previously selected
# in a hash, eg. {total: 2, average_read_time_in_seconds: 10, total_read_time_in_seconds: 20}
page_views.each_with_object({}) do |page_view, hash|
average = (page_view.average || 0).round # average is a BigDecimal
hash[page_view.date.iso8601] = {
total: page_view.total,
average_read_time_in_seconds: average,
total_read_time_in_seconds: page_view.total * average
}
end
end
def stats_per_day(date, comments_stats:, follows_stats:, reactions_stats:, page_views_stats:)
# we need these defaults because SQL doesn't return any data for dates that don't have any
default_reactions_stats = {
total: 0, like: 0, readinglist: 0, unicorn: 0,
exploding_head: 0, raised_hands: 0, fire: 0, unique_reactors: 0
}
default_page_views_stats = { total: 0, average_read_time_in_seconds: 0, total_read_time_in_seconds: 0 }
iso_date = date.iso8601
{
comments: { total: comments_stats[iso_date] || 0 },
follows: { total: follows_stats[iso_date] || 0 },
reactions: reactions_stats[iso_date] || default_reactions_stats,
page_views: page_views_stats[iso_date] || default_page_views_stats
}
end
end