diff --git a/app/repositories/repository_challenge.rb b/app/repositories/repository_challenge.rb index b389bb1..a27786c 100644 --- a/app/repositories/repository_challenge.rb +++ b/app/repositories/repository_challenge.rb @@ -348,11 +348,14 @@ def self.player_best_scores(player_id) } }, { "$unwind": "$entries" }, - { "$match": { "entries.user_id": player_id } }, - { "$sort": { "entries.score": 1 } }, + { "$sort": { "entries.score": 1, "entries.created_at": 1 } }, { "$group": { - "_id": '$_id', + "_id": { + "challenge_id": '$_id', + "user_id": '$entries.user_id' + }, + "user_id": { "$first": '$entries.user_id'}, "title": { "$first": '$title'}, "description": { "$first": '$description'}, "created_at": { "$first": '$created_at'}, @@ -362,7 +365,29 @@ def self.player_best_scores(player_id) "attempts": { "$sum": 1 } }, }, - { "$sort": { "created_at": -1 } }, + { "$sort": { "best_player_score": 1, "created_at": 1 } }, + { + "$group": { + "_id": "$_id.challenge_id", + "items": { "$push": "$$ROOT" }, + } + }, + { "$unwind": { "path": "$items", "includeArrayIndex": "items.position" }}, + { "$match": { "items.user_id": player_id }}, + { "$sort": { "items.created_at": -1 } }, + { + "$project": { + "_id": 1, + "title": "$items.title", + "description": "$items.description", + "created_at": "$items.created_at", + "count_entries": "$items.count_entries", + "best_score": "$items.best_score", + "best_player_score": "$items.best_player_score", + "attempts": "$items.attempts", + "position": { "$add": ["$items.position", 1]} + } + }, ) end diff --git a/app/views/users/show.erb b/app/views/users/show.erb index 47ffe58..932370b 100644 --- a/app/views/users/show.erb +++ b/app/views/users/show.erb @@ -7,6 +7,7 @@ diff --git a/spec/repositories/repository_challenge_spec.rb b/spec/repositories/repository_challenge_spec.rb index 471bb1c..d804456 100644 --- a/spec/repositories/repository_challenge_spec.rb +++ b/spec/repositories/repository_challenge_spec.rb @@ -430,6 +430,7 @@ expect(challenge['best_score']).to eq(10) expect(challenge['best_player_score']).to eq(12) expect(challenge['attempts']).to eq(2) + expect(challenge['position']).to eq(2) end end @@ -459,6 +460,7 @@ expect(challenge['best_score']).to eq(14) expect(challenge['best_player_score']).to eq(14) expect(challenge['attempts']).to eq(1) + expect(challenge['position']).to eq(1) # And challenge1 is next. challenge = result[1] @@ -469,6 +471,7 @@ expect(challenge['best_score']).to eq(10) expect(challenge['best_player_score']).to eq(12) expect(challenge['attempts']).to eq(2) + expect(challenge['position']).to eq(2) end end