-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplayer_statistics_controller.rb
More file actions
274 lines (233 loc) · 9.19 KB
/
Copy pathplayer_statistics_controller.rb
File metadata and controls
274 lines (233 loc) · 9.19 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
class PlayerStatisticsController < ApplicationController
before_action :set_user, except: :create_for_game
def show
@stats = @user.player_statistic || @user.create_player_statistic
matches = Match.where(user: @user).includes(:opponent, :game).order(played_at: :desc).limit(5).to_a
related_ids = matches.flat_map do |m|
s = (m.stats || {}).to_h
[ m.opponent_id, s["partner_id"], *Array(s["opponent_ids"]), *Array(s["team_a_ids"]), *Array(s["team_b_ids"]) ]
end.compact.uniq
names_by_id =
if related_ids.any?
User.where(id: related_ids).map { |u| [ u.id, Telegram::Helpers::UserLookup.display_name(u, fallback: "User ##{u.id}") ] }.to_h
else
{}
end
render partial: "player_statistics/modal", locals: { user: @user, stats: @stats, matches: matches, names_by_id: names_by_id }
end
def create_for_game
game = Game.find(params[:game_id])
allowed = allowed_to_fill_stats?(game)
started = game_started?(game)
if allowed && started
raw = player_statistics_params.to_h
data = {}
hours = raw.delete("hours")
if hours.present?
field = StatisticsPresenter.hours_field_for_game(game)
data[field.to_s] = hours
end
raw.each do |key, value|
if value.present? && StatisticsPresenter.allowed_keys.include?(key.to_s)
data[key.to_s] = value
end
end
saved_any = false
cycle_start = game.respond_to?(:current_cycle_start) ? game.current_cycle_start : nil
entry_scope = PlayerStatisticEntry.where(game: game)
match_scope = Match.where(game_id: game.id)
if cycle_start.present?
entry_scope = entry_scope.where("recorded_at >= ?", cycle_start)
match_scope = match_scope.where("played_at >= ?", cycle_start)
end
first_stats = !entry_scope.exists? && !match_scope.exists?
if data.present?
PlayerStatistics::ApplyEntryToParticipantsService.new(
game: game,
actor: current_user,
data: data,
source: "web",
recorded_at: Time.current
).call
increment_activity_for_game!(game) if first_stats && game.respond_to?(:with_coach?) && game.with_coach?
first_stats = false
saved_any = true
end
# На тренировке счёт не ведут, поэтому матчи из формы туда не попадают.
matches_input = game.training? ? [] : matches_params
unbalanced_matches = 0
matches_input.each do |m|
team_a_ids = sanitize_team_ids(m[:team_a_user_ids], game)
team_b_ids = sanitize_team_ids(m[:team_b_user_ids], game)
team_a_guests = sanitize_guest_names([ m[:team_a_guests], *Array(m[:team_a_guest_names]) ])
team_b_guests = sanitize_guest_names([ m[:team_b_guests], *Array(m[:team_b_guest_names]) ])
winner = m[:winner_team].to_s
score = m[:score].to_s
next if score.blank?
next unless (team_a_ids + team_a_guests).any? && (team_b_ids + team_b_guests).any?
next unless (team_a_ids + team_b_ids).any?
next unless %w[a b draw].include?(winner)
# A match is one against one or two against two — anything else means a
# player was left out of the form, and saving it would bury that in the
# statistics as a lopsided game nobody played.
team_a_size = team_a_ids.size + team_a_guests.size
team_b_size = team_b_ids.size + team_b_guests.size
unless team_a_size == team_b_size && [ 1, 2 ].include?(team_a_size)
unbalanced_matches += 1
next
end
group_id = m[:group_id].to_s.presence
if group_id && sync_match_group(game, group_id, team_a_ids, team_b_ids, team_a_guests, team_b_guests, score, winner)
saved_any = true
else
upsert_matches_for_teams(game, team_a_ids, team_b_ids, team_a_guests, team_b_guests, score, winner, force_new: true)
saved_any = true
end
end
if unbalanced_matches.positive?
redirect_to game_path(game),
notice: (saved_any ? "Statistics saved." : nil),
alert: "A match is 1 vs 1 or 2 vs 2 — #{unbalanced_matches} match(es) were not saved."
elsif saved_any
redirect_to game_path(game), notice: "Statistics saved."
else
redirect_to game_path(game), alert: "No data to save."
end
else
if allowed == false
redirect_to game_path(game), alert: "Not allowed."
else
redirect_to game_path(game), alert: "Statistics can be entered after the game starts."
end
end
end
private
def player_statistics_params
params.fetch(:statistics, ActionController::Parameters.new).permit(
:hours,
:singles_games,
:doubles_games,
:aces,
:double_faults,
:break_points_saved,
:break_points_converted,
:winners,
:unforced_errors,
:net_points_won,
:service_points_won,
:return_points_won,
:return_games_won,
:games_won_total
)
end
def matches_params
raw = params[:matches]
return [] if raw.blank?
list = raw.respond_to?(:values) ? raw.values : raw
list.map do |m|
next nil unless m.respond_to?(:permit)
m.permit(:score, :winner_team, :group_id, :team_a_guests, :team_b_guests, team_a_user_ids: [], team_b_user_ids: [], team_a_guest_names: [], team_b_guest_names: [])
end.compact
end
def set_user
@user = User.find(params[:user_id] || params[:id])
end
def allowed_to_fill_stats?(game)
return false unless current_user
return true if current_user == game.user || (current_user.respond_to?(:admin?) && current_user.admin?)
participations = game.participations
if participations.respond_to?(:approved)
participations.approved.exists?(user_id: current_user.id)
else
participations.exists?(user_id: current_user.id, status: "approved")
end
end
def game_started?(game)
if game.respond_to?(:started_for_ui?)
game.started_for_ui?
elsif game.respond_to?(:starts_at) && game.starts_at.present?
game.starts_at <= Time.current
elsif game.respond_to?(:date) && game.date.present?
game.date <= Date.current
else
true
end
end
def game_participants(game)
users = []
users << game.user if game.respond_to?(:user)
if game.respond_to?(:participations)
users.concat(game.participations.includes(:user).map(&:user))
end
users.compact.uniq { |u| u.id }
end
def sanitize_team_ids(ids, game)
candidate_ids = Array(ids).map(&:to_i).uniq.reject(&:zero?)
return [] if candidate_ids.empty?
User.where(id: candidate_ids).pluck(:id)
end
def sanitize_guest_names(value)
Array(value).join(",").split(",").map { |name| name.strip[0, 50] }.reject(&:blank?).first(2)
end
def sync_match_group(game, group_id, team_a_ids, team_b_ids, team_a_guests, team_b_guests, score, winner)
PlayerStatistics::SyncMatchGroupService.new(
game: game,
actor: current_user,
group_id: group_id,
mode: mode_for_teams(team_a_ids, team_b_ids, team_a_guests, team_b_guests),
team_a_ids: team_a_ids,
team_b_ids: team_b_ids,
team_a_guest_names: team_a_guests,
team_b_guest_names: team_b_guests,
result: winner == "draw" ? :draw : winner.to_sym,
played_at: played_at_for_game(game),
score: score
).call
end
def upsert_matches_for_teams(game, team_a_ids, team_b_ids, team_a_guests, team_b_guests, score, winner, force_new: false)
result = winner == "draw" ? :draw : winner.to_sym
Telegram::Flows::StatsScore::MatchUpserter.call(
game: game,
actor: current_user,
mode: mode_for_teams(team_a_ids, team_b_ids, team_a_guests, team_b_guests),
team_a_ids: team_a_ids,
team_b_ids: team_b_ids,
team_a_guest_names: team_a_guests,
team_b_guest_names: team_b_guests,
result: result,
played_at: played_at_for_game(game),
score: score,
force_new: force_new
)
end
def played_at_for_game(game)
# Use the current occurrence for recurring games so the match lands inside
# current_cycle_start and stays visible/editable in the stats form.
occurrence = game.respond_to?(:start_at_for_ui) ? game.start_at_for_ui : nil
return occurrence if occurrence.present?
if game.respond_to?(:starts_at) && game.starts_at.present?
game.starts_at
elsif game.respond_to?(:date) && game.date.present?
game.date.to_time
else
Time.current
end
end
def mode_for_teams(team_a_ids, team_b_ids, team_a_guests, team_b_guests)
((team_a_ids.size + team_a_guests.size) >= 2 || (team_b_ids.size + team_b_guests.size) >= 2) ? "doubles" : "singles"
end
def increment_activity_for_game!(game)
return unless game.respond_to?(:with_coach?) && game.with_coach?
users = game.participations.includes(:user).map(&:user).compact.uniq { |u| u.id }
return if users.empty?
mode = StatisticsPresenter.hours_field_for_game(game) == :doubles_hours ? :doubles : :singles
training_key = mode == :doubles ? :group_training : :individual_training
users.each do |u|
ps = u.player_statistic || u.create_player_statistic
ps.with_lock do
ps[training_key] = [ ps[training_key].to_i + 1, 0 ].max
ps.save!
end
end
end
end