2019-12-18 09:49:57 -06:00
|
|
|
# typed: true
|
2013-03-02 08:11:15 -05:00
|
|
|
# Get action count for the top n contexts (default: all)
|
|
|
|
# If initialized with :running => true, then only active
|
2013-03-01 23:29:54 -05:00
|
|
|
# and visible contexts will be included.
|
|
|
|
module Stats
|
|
|
|
class TopContextsQuery
|
|
|
|
|
2013-03-02 07:54:13 -05:00
|
|
|
attr_reader :user, :running, :limit
|
|
|
|
def initialize(user, options = {})
|
2013-03-01 23:29:54 -05:00
|
|
|
@user = user
|
2013-03-02 07:54:13 -05:00
|
|
|
@running = options.fetch(:running) { false }
|
|
|
|
@limit = options.fetch(:limit) { false }
|
2013-03-01 23:29:54 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def result
|
|
|
|
user.contexts.find_by_sql([sql, user.id])
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def sql
|
|
|
|
query = "SELECT c.id AS id, c.name AS name, count(c.id) AS total "
|
|
|
|
query << "FROM contexts c, todos t "
|
|
|
|
query << "WHERE t.context_id=c.id "
|
|
|
|
query << "AND t.user_id = ? "
|
|
|
|
if running
|
|
|
|
query << "AND t.completed_at IS NULL "
|
|
|
|
query << "AND NOT c.state='hidden' "
|
|
|
|
end
|
|
|
|
query << "GROUP BY c.id, c.name "
|
|
|
|
query << "ORDER BY total DESC "
|
2013-03-02 07:54:13 -05:00
|
|
|
if limit
|
|
|
|
query << "LIMIT #{limit}"
|
|
|
|
end
|
|
|
|
query
|
2013-03-01 23:29:54 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|