Coverage for dao/match_event_dao.py: 46.85%

184 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 20:17 +0000

1""" 

2Match Event Data Access Object. 

3 

4Handles all database operations related to live match events including: 

5- Goals 

6- Chat messages 

7- Status changes 

8- Cleanup of expired messages 

9""" 

10 

11from datetime import UTC, datetime 

12 

13import structlog 

14 

15from dao.base_dao import BaseDAO 

16 

17logger = structlog.get_logger() 

18 

19 

20class MatchEventDAO(BaseDAO): 

21 """Data access object for match event operations (live match activity stream).""" 

22 

23 def create_event( 

24 self, 

25 match_id: int, 

26 event_type: str, 

27 message: str, 

28 created_by: str | None = None, 

29 created_by_username: str | None = None, 

30 team_id: int | None = None, 

31 player_name: str | None = None, 

32 player_id: int | None = None, 

33 match_minute: int | None = None, 

34 extra_time: int | None = None, 

35 player_out_id: int | None = None, 

36 assist_player_id: int | None = None, 

37 assist_player_name: str | None = None, 

38 client_event_id: str | None = None, 

39 position: str | None = None, 

40 ) -> dict | None: 

41 """Create a new match event. 

42 

43 Args: 

44 match_id: The match this event belongs to 

45 event_type: Type of event ('goal', 'message', 'status_change', 'substitution', 

46 'red_card', 'yellow_card', 'position_change') 

47 message: Event message/description 

48 created_by: UUID of user who created the event 

49 created_by_username: Username of creator (denormalized for display) 

50 team_id: Team ID (for goal/substitution events) 

51 player_name: Player name (for goal events) 

52 player_id: Player ID from roster (for goal events, player coming on for subs) 

53 match_minute: Minute when event occurred (e.g., 22 for 22nd minute) 

54 extra_time: Stoppage/injury time minutes (e.g., 5 for 90+5) 

55 player_out_id: Player ID being substituted off (for substitution events) 

56 assist_player_id: Roster player credited with the assist (goal events) 

57 assist_player_name: Denormalized assister display name 

58 client_event_id: Client-generated UUID; the unique index on this column 

59 makes replayed inserts fail so offline sync is exactly-once 

60 position: Formation position code the player moved to 

61 (position_change events) 

62 

63 Returns: 

64 Created event record or None on error 

65 """ 

66 try: 

67 data = { 

68 "match_id": match_id, 

69 "event_type": event_type, 

70 "message": message, 

71 "created_by": created_by, 

72 "created_by_username": created_by_username, 

73 } 

74 

75 # Add optional fields for goal/substitution events 

76 if team_id is not None: 76 ↛ 77line 76 didn't jump to line 77 because the condition on line 76 was never true

77 data["team_id"] = team_id 

78 if player_name is not None: 78 ↛ 79line 78 didn't jump to line 79 because the condition on line 78 was never true

79 data["player_name"] = player_name 

80 if player_id is not None: 80 ↛ 81line 80 didn't jump to line 81 because the condition on line 80 was never true

81 data["player_id"] = player_id 

82 if match_minute is not None: 82 ↛ 83line 82 didn't jump to line 83 because the condition on line 82 was never true

83 data["match_minute"] = match_minute 

84 if extra_time is not None: 84 ↛ 85line 84 didn't jump to line 85 because the condition on line 84 was never true

85 data["extra_time"] = extra_time 

86 if player_out_id is not None: 86 ↛ 87line 86 didn't jump to line 87 because the condition on line 86 was never true

87 data["player_out_id"] = player_out_id 

88 if assist_player_id is not None: 88 ↛ 89line 88 didn't jump to line 89 because the condition on line 88 was never true

89 data["assist_player_id"] = assist_player_id 

90 if assist_player_name is not None: 90 ↛ 91line 90 didn't jump to line 91 because the condition on line 90 was never true

91 data["assist_player_name"] = assist_player_name 

92 if client_event_id is not None: 92 ↛ 93line 92 didn't jump to line 93 because the condition on line 92 was never true

93 data["client_event_id"] = client_event_id 

94 if position is not None: 94 ↛ 95line 94 didn't jump to line 95 because the condition on line 94 was never true

95 data["position"] = position 

96 

97 response = self.client.table("match_events").insert(data).execute() 

98 

99 if response.data: 99 ↛ 109line 99 didn't jump to line 109 because the condition on line 99 was always true

100 logger.info( 

101 "match_event_created", 

102 match_id=match_id, 

103 event_type=event_type, 

104 event_id=response.data[0].get("id"), 

105 ) 

106 if event_type == "message": 

107 self.ring_chat(match_id) 

108 return response.data[0] 

109 return None 

110 

111 except Exception: 

112 logger.exception( 

113 "Error creating match event", 

114 match_id=match_id, 

115 event_type=event_type, 

116 ) 

117 return None 

118 

119 def get_events( 

120 self, 

121 match_id: int, 

122 limit: int = 50, 

123 before_id: int | None = None, 

124 exclude_messages_by: list[str] | None = None, 

125 ) -> list[dict]: 

126 """Get paginated events for a match. 

127 

128 Args: 

129 match_id: Match to get events for 

130 limit: Maximum number of events to return 

131 before_id: Return events with ID less than this (for pagination) 

132 exclude_messages_by: Drop chat messages by these users — the 

133 viewer's blocked users (SB-1309). Only event_type 'message': 

134 blocking a manager must not hide the goals they record. 

135 

136 Returns: 

137 List of event records, newest first 

138 """ 

139 try: 

140 query = ( 

141 self.client.table("match_events") 

142 .select("*") 

143 .eq("match_id", match_id) 

144 .eq("is_deleted", False) 

145 .order("created_at", desc=True) 

146 .limit(limit) 

147 ) 

148 

149 if before_id is not None: 149 ↛ 150line 149 didn't jump to line 150 because the condition on line 149 was never true

150 query = query.lt("id", before_id) 

151 

152 if exclude_messages_by: 

153 # Keep anything that is not a chat message, and anything with 

154 # no author: NOT (NULL IN (...)) is NULL, so a bare not.in 

155 # would also drop every event nobody authored. 

156 ids = ",".join(exclude_messages_by) 

157 query = query.or_(f"event_type.neq.message,created_by.is.null,created_by.not.in.({ids})") 

158 

159 response = query.execute() 

160 return response.data or [] 

161 

162 except Exception: 

163 logger.exception("Error getting match events", match_id=match_id) 

164 return [] 

165 

166 # Events that move players on or around the pitch. Clients replay these 

167 # over the starting XI to derive who is on the field right now. 

168 PITCH_EVENT_TYPES = ("substitution", "position_change") 

169 

170 def get_pitch_events(self, match_id: int) -> list[dict] | None: 

171 """Get every substitution and position change for a match (SB-1369). 

172 

173 Unlike get_events this is unpaginated and excludes chat, so a chatty 

174 match cannot push early substitutions out of the window clients use 

175 to rebuild the current XI. 

176 

177 Args: 

178 match_id: Match to get events for 

179 

180 Returns: 

181 Non-deleted substitution/position_change events, oldest first 

182 (created_at, then id as tie-breaker). None if the read failed — 

183 unlike get_events, an empty list here is authoritative ("no 

184 changes since kickoff"), so a failure must not masquerade as one. 

185 """ 

186 try: 

187 response = ( 

188 self.client.table("match_events") 

189 .select("*") 

190 .eq("match_id", match_id) 

191 .eq("is_deleted", False) 

192 .in_("event_type", list(self.PITCH_EVENT_TYPES)) 

193 .order("created_at") 

194 .order("id") 

195 .execute() 

196 ) 

197 return response.data or [] 

198 

199 except Exception: 

200 logger.exception("Error getting match pitch events", match_id=match_id) 

201 return None 

202 

203 # Events that change the scoreline or the discipline record: what "what's the 

204 # score?" and "who scored?" are answered from (SB-1584). 

205 KEY_EVENT_TYPES = ("goal", "yellow_card", "red_card") 

206 

207 def get_key_events(self, match_id: int) -> list[dict] | None: 

208 """Get every goal and card for a match, oldest first (SB-1584). 

209 

210 Unpaginated and chat-free, like get_pitch_events, so a chatty match 

211 cannot push early goals out of a window. 

212 

213 Returns: 

214 Non-deleted goal/card events (created_at, then id). None if the read 

215 failed: an empty list means none were recorded. 

216 """ 

217 try: 

218 response = ( 

219 self.client.table("match_events") 

220 .select("*") 

221 .eq("match_id", match_id) 

222 .eq("is_deleted", False) 

223 .in_("event_type", list(self.KEY_EVENT_TYPES)) 

224 .order("created_at") 

225 .order("id") 

226 .execute() 

227 ) 

228 return response.data or [] 

229 

230 except Exception: 

231 logger.exception("Error getting match key events", match_id=match_id) 

232 return None 

233 

234 def get_event_by_id(self, event_id: int) -> dict | None: 

235 """Get a single event by ID. 

236 

237 Args: 

238 event_id: The event ID 

239 

240 Returns: 

241 Event record or None if not found 

242 """ 

243 try: 

244 response = self.client.table("match_events").select("*").eq("id", event_id).limit(1).execute() 

245 if response.data: 

246 return response.data[0] 

247 return None 

248 except Exception: 

249 logger.exception("Error getting match event", event_id=event_id) 

250 return None 

251 

252 def get_event_by_client_id(self, client_event_id: str) -> dict | None: 

253 """Get an event by its client-generated UUID (idempotency replay lookup). 

254 

255 Args: 

256 client_event_id: Client-generated UUID sent with the original request 

257 

258 Returns: 

259 Event record or None if not found 

260 """ 

261 try: 

262 response = ( 

263 self.client.table("match_events") 

264 .select("*") 

265 .eq("client_event_id", client_event_id) 

266 .limit(1) 

267 .execute() 

268 ) 

269 if response.data: 

270 return response.data[0] 

271 return None 

272 except Exception: 

273 logger.exception("Error getting match event by client id", client_event_id=client_event_id) 

274 return None 

275 

276 def soft_delete_event(self, event_id: int, deleted_by: str) -> bool: 

277 """Soft delete an event (for moderation). 

278 

279 Args: 

280 event_id: Event to delete 

281 deleted_by: UUID of user performing deletion 

282 

283 Returns: 

284 True if successful, False otherwise 

285 """ 

286 try: 

287 response = ( 

288 self.client.table("match_events") 

289 .update( 

290 { 

291 "is_deleted": True, 

292 "deleted_by": deleted_by, 

293 "deleted_at": datetime.now(UTC).isoformat(), 

294 } 

295 ) 

296 .eq("id", event_id) 

297 .execute() 

298 ) 

299 

300 if response.data: 300 ↛ 310line 300 didn't jump to line 310 because the condition on line 300 was always true

301 logger.info( 

302 "match_event_deleted", 

303 event_id=event_id, 

304 deleted_by=deleted_by, 

305 ) 

306 row = response.data[0] 

307 if row.get("event_type") == "message" and row.get("match_id") is not None: 

308 self.ring_chat(row["match_id"]) 

309 return True 

310 return False 

311 

312 except Exception: 

313 logger.exception("Error deleting match event", event_id=event_id) 

314 return False 

315 

316 def ring_chat(self, match_id: int) -> None: 

317 """Tell clients this match's chat changed (SB-1329). 

318 

319 Clients cannot read chat rows, so Realtime no longer carries them. Instead 

320 it carries this content-free row, and clients re-read chat through the 

321 API. Best-effort: a missed ring delays chat until the next one or the 

322 client's fallback refresh, which is no reason to fail the post. 

323 """ 

324 try: 

325 self.client.table("live_chat_signals").upsert( 

326 {"match_id": match_id, "changed_at": datetime.now(UTC).isoformat()}, 

327 on_conflict="match_id", 

328 ).execute() 

329 except Exception: 

330 logger.warning("live_chat_signal_failed", match_id=match_id, exc_info=True) 

331 

332 def cleanup_expired_messages(self) -> int: 

333 """Delete message events that have expired (older than 10 days). 

334 

335 This method is called by a Celery scheduled task. 

336 Only deletes events where: 

337 - event_type = 'message' 

338 - expires_at is in the past 

339 - is_deleted = false (don't process already deleted) 

340 

341 Returns: 

342 Number of events deleted 

343 """ 

344 try: 

345 now = datetime.now(UTC).isoformat() 

346 

347 # First, get count of expired messages 

348 count_response = ( 

349 self.client.table("match_events") 

350 .select("id", count="exact") 

351 .eq("event_type", "message") 

352 .eq("is_deleted", False) 

353 .lt("expires_at", now) 

354 .execute() 

355 ) 

356 

357 count = count_response.count or 0 

358 if count == 0: 

359 logger.info("match_events_cleanup_none_expired") 

360 return 0 

361 

362 # Delete expired messages 

363 response = ( 

364 self.client.table("match_events") 

365 .delete() 

366 .eq("event_type", "message") 

367 .eq("is_deleted", False) 

368 .lt("expires_at", now) 

369 .execute() 

370 ) 

371 

372 deleted = len(response.data) if response.data else 0 

373 logger.info( 

374 "match_events_cleanup_completed", 

375 deleted_count=deleted, 

376 ) 

377 return deleted 

378 

379 except Exception: 

380 logger.exception("Error cleaning up expired match events") 

381 return 0 

382 

383 def update_event( 

384 self, 

385 event_id: int, 

386 match_minute: int | None = None, 

387 extra_time: int | None = None, 

388 player_name: str | None = None, 

389 player_id: int | None = None, 

390 assist_player_id: int | None = None, 

391 assist_player_name: str | None = None, 

392 clear_assist: bool = False, 

393 ) -> dict | None: 

394 """Update editable fields on a match event. 

395 

396 Only updates fields that are provided (non-None), so `None` means 

397 "leave unchanged" — which is why removing an assist needs its own flag 

398 rather than a null id (SB-432). 

399 

400 Args: 

401 event_id: Event to update 

402 match_minute: New match minute 

403 extra_time: New extra/stoppage time 

404 player_name: New player name 

405 player_id: New player ID 

406 assist_player_id: New assisting player ID 

407 assist_player_name: New assister display name 

408 clear_assist: Drop the assist entirely — both the id and the 

409 denormalized name. Takes precedence over the two assist args. 

410 

411 Returns: 

412 Updated event record or None on error 

413 """ 

414 try: 

415 data = {} 

416 if match_minute is not None: 

417 data["match_minute"] = match_minute 

418 if extra_time is not None: 418 ↛ 419line 418 didn't jump to line 419 because the condition on line 418 was never true

419 data["extra_time"] = extra_time 

420 if player_name is not None: 420 ↛ 421line 420 didn't jump to line 421 because the condition on line 420 was never true

421 data["player_name"] = player_name 

422 if player_id is not None: 422 ↛ 423line 422 didn't jump to line 423 because the condition on line 422 was never true

423 data["player_id"] = player_id 

424 if assist_player_id is not None: 

425 data["assist_player_id"] = assist_player_id 

426 if assist_player_name is not None: 426 ↛ 427line 426 didn't jump to line 427 because the condition on line 426 was never true

427 data["assist_player_name"] = assist_player_name 

428 if clear_assist: 

429 data["assist_player_id"] = None 

430 data["assist_player_name"] = None 

431 

432 if not data: 432 ↛ 433line 432 didn't jump to line 433 because the condition on line 432 was never true

433 return self.get_event_by_id(event_id) 

434 

435 response = ( 

436 self.client.table("match_events") 

437 .update(data) 

438 .eq("id", event_id) 

439 .execute() 

440 ) 

441 

442 if response.data: 442 ↛ 449line 442 didn't jump to line 449 because the condition on line 442 was always true

443 logger.info( 

444 "match_event_updated", 

445 event_id=event_id, 

446 updated_fields=list(data.keys()), 

447 ) 

448 return response.data[0] 

449 return None 

450 

451 except Exception: 

452 logger.exception("Error updating match event", event_id=event_id) 

453 return None 

454 

455 def get_goal_events( 

456 self, 

457 season_id: int | None = None, 

458 age_group_id: int | None = None, 

459 match_type_id: int | None = None, 

460 team_id: int | None = None, 

461 limit: int = 100, 

462 offset: int = 0, 

463 ) -> list[dict]: 

464 """Get goal events across matches with joined match context. 

465 

466 Args: 

467 season_id: Optional filter by season 

468 age_group_id: Optional filter by age group 

469 match_type_id: Optional filter by match type 

470 team_id: Optional filter by team (scoring team) 

471 limit: Maximum results 

472 offset: Pagination offset 

473 

474 Returns: 

475 List of goal events with match context 

476 """ 

477 try: 

478 query = ( 

479 self.client.table("match_events") 

480 .select( 

481 "*, match:matches!inner(" 

482 "id, match_date, home_score, away_score, " 

483 "season_id, age_group_id, match_type_id, " 

484 "home_team:teams!matches_home_team_id_fkey(id, name), " 

485 "away_team:teams!matches_away_team_id_fkey(id, name), " 

486 "season:seasons(id, name), " 

487 "age_group:age_groups(id, name), " 

488 "match_type:match_types(id, name)" 

489 ")" 

490 ) 

491 .eq("event_type", "goal") 

492 .eq("is_deleted", False) 

493 .order("created_at", desc=True) 

494 .range(offset, offset + limit - 1) 

495 ) 

496 

497 if season_id is not None: 

498 query = query.eq("match.season_id", season_id) 

499 if age_group_id is not None: 

500 query = query.eq("match.age_group_id", age_group_id) 

501 if match_type_id is not None: 

502 query = query.eq("match.match_type_id", match_type_id) 

503 if team_id is not None: 

504 query = query.eq("team_id", team_id) 

505 

506 response = query.execute() 

507 return response.data or [] 

508 

509 except Exception: 

510 logger.exception("Error getting goal events") 

511 return [] 

512 

513 def get_card_events_for_matches(self, match_ids: list[int]) -> dict[int, list[dict]]: 

514 """Get card events (red/yellow) for multiple matches in one query. 

515 

516 Args: 

517 match_ids: List of match IDs 

518 

519 Returns: 

520 Dict mapping match_id to list of card event dicts 

521 """ 

522 if not match_ids: 

523 return {} 

524 

525 try: 

526 response = ( 

527 self.client.table("match_events") 

528 .select("match_id, event_type, team_id, player_name") 

529 .in_("match_id", match_ids) 

530 .in_("event_type", ["red_card", "yellow_card"]) 

531 .eq("is_deleted", False) 

532 .execute() 

533 ) 

534 

535 result: dict[int, list[dict]] = {} 

536 for event in response.data or []: 

537 mid = event["match_id"] 

538 if mid not in result: 

539 result[mid] = [] 

540 result[mid].append(event) 

541 return result 

542 

543 except Exception: 

544 logger.exception("Error fetching card events for matches") 

545 return {} 

546 

547 def get_events_count(self, match_id: int) -> int: 

548 """Get total count of active events for a match. 

549 

550 Args: 

551 match_id: Match to count events for 

552 

553 Returns: 

554 Number of active events 

555 """ 

556 try: 

557 response = ( 

558 self.client.table("match_events") 

559 .select("id", count="exact") 

560 .eq("match_id", match_id) 

561 .eq("is_deleted", False) 

562 .execute() 

563 ) 

564 return response.count or 0 

565 except Exception: 

566 logger.exception("Error counting match events", match_id=match_id) 

567 return 0