1<?php
2
3// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
4// See the LICENCE file in the repository root for full licence text.
5
6namespace App\Models;
7
8use DB;
9
10/**
11 * @property Country $country
12 * @property string $country_code
13 * @property \Carbon\Carbon|null $created_at
14 * @property int $display
15 * @property int $id
16 * @property int $mode
17 * @property int $performance
18 * @property int $play_count
19 * @property int $ranked_score
20 * @property \Carbon\Carbon|null $updated_at
21 * @property int $user_count
22 */
23class CountryStatistics extends Model
24{
25 public function country()
26 {
27 return $this->belongsTo(Country::class, 'country_code', 'acronym');
28 }
29
30 public static function recalculate($countryAcronym, $modeInt)
31 {
32 $statisticsQuery = UserStatistics\Model::getClass(Beatmap::modeStr($modeInt))
33 ::where('country_acronym', $countryAcronym)
34 ->where('rank_score', '>', 0)
35 ->whereHas('user', fn ($userQuery) => $userQuery->default());
36
37 $stats = $statisticsQuery
38 ->select(DB::raw('sum(ranked_score) AS ranked_score, sum(playcount) AS playcount, count(*) AS usercount'))
39 ->first();
40
41 $conds = [
42 'country_code' => $countryAcronym,
43 'mode' => $modeInt,
44 ];
45
46 if ($stats->ranked_score > 0) {
47 $userPerformances = $statisticsQuery->clone()
48 ->select('rank_score')
49 ->orderBy('rank_score', 'desc')
50 ->limit($GLOBALS['cfg']['osu']['rankings']['country_performance_user_count'])
51 ->get();
52
53 $totalPerformance = 0;
54 $factor = 1.0;
55
56 foreach ($userPerformances as $userPerformance) {
57 $totalPerformance += $userPerformance->rank_score * $factor;
58 $factor *= $GLOBALS['cfg']['osu']['rankings']['country_performance_weighting_factor'];
59 }
60
61 self::updateOrCreate($conds, [
62 'ranked_score' => $stats->ranked_score,
63 'play_count' => $stats->playcount,
64 'user_count' => $stats->usercount,
65 'performance' => $totalPerformance,
66 ]);
67 } else {
68 self::where($conds)->delete();
69 }
70 }
71}