From b8e7ee31aabe1ad025bae3117a459a7e67d27df8 Mon Sep 17 00:00:00 2001 From: Mayank Variya Date: Fri, 29 Nov 2024 10:13:02 +0530 Subject: [PATCH] Record team stats --- data/lib/api/match/match_model.dart | 165 ++--- data/lib/api/match/match_model.freezed.dart | 486 --------------- data/lib/api/team/team_model.dart | 44 ++ data/lib/api/team/team_model.freezed.dart | 584 +++++++++++++++++- data/lib/api/team/team_model.g.dart | 44 ++ data/lib/service/team/team_service.dart | 60 +- data/lib/service/user/user_service.dart | 5 - .../utils/constant/firestore_constant.dart | 2 + .../score_board/score_board_view_model.dart | 25 +- .../components/primer_progress_bar.dart | 2 +- .../components/team_detail_stat_content.dart | 7 +- .../team/detail/team_detail_view_model.dart | 11 - .../team_detail_view_model.freezed.dart | 50 +- .../tournament_detail_points_table_tab.dart | 6 +- .../detail/tournament_detail_view_model.dart | 6 +- 15 files changed, 805 insertions(+), 692 deletions(-) diff --git a/data/lib/api/match/match_model.dart b/data/lib/api/match/match_model.dart index b9e790c0..a361b6b2 100644 --- a/data/lib/api/match/match_model.dart +++ b/data/lib/api/match/match_model.dart @@ -346,128 +346,71 @@ enum MatchGroup { const MatchGroup(this.value); } -@freezed -class TeamMatchStatus with _$TeamMatchStatus { - const factory TeamMatchStatus({ - @Default(0) int win, - @Default(0) int tie, - @Default(0) int lost, - }) = _TeamMatchStatus; -} - -@freezed -class TeamStat with _$TeamStat { - const factory TeamStat({ - @Default(0) int played, - @Default(TeamMatchStatus()) TeamMatchStatus status, - @Default(0) int runs, - @Default(0) int wickets, - @Default(0.0) double batting_average, - @Default(0.0) double bowling_average, - @Default(0) int highest_runs, - @Default(0) int lowest_runs, - @Default(0.0) double run_rate, - }) = _TeamStat; -} - -extension TeamStatExtension on List { - TeamStat teamStat(String teamId) { - if (isEmpty) return const TeamStat(); - - var runs = 0; - var wickets = 0; - var battingAverageTotal = 0.0; - var bowlingAverageTotal = 0.0; - var highestRuns = 0; - var lowestRuns = double.maxFinite.toInt(); +extension SingleMatchTeamStatExtension on MatchModel { + TeamStat updateTeamStat(String teamId, TeamStat currentStat) { + final team = _getTeam(teamId); + final opponentTeam = _getOpponentTeam(teamId); - for (final match in this) { - final team = _getTeam(match, teamId); - final opponentTeam = _getOpponentTeam(match, teamId); + final matchRuns = team.run; + final matchWickets = team.wicket; + final battingAverage = + opponentTeam.wicket > 0 ? matchRuns / opponentTeam.wicket : 0.0; + final bowlingAverage = + matchWickets > 0 ? opponentTeam.run / matchWickets : 0.0; - runs += team.run; - wickets += team.wicket; + final result = _matchResult(teamId, team.run, opponentTeam.run); - battingAverageTotal += - opponentTeam.wicket > 0 ? team.run / opponentTeam.wicket : 0; - if (team.wicket > 0) { - bowlingAverageTotal += opponentTeam.run / team.wicket; - } + final totalOvers = currentStat.run_rate > 0 + ? _computeOvers(currentStat.runs, currentStat.run_rate) + : 0.0; - if (team.run > highestRuns) highestRuns = team.run; - if (team.run < lowestRuns) lowestRuns = team.run; - } - - final bowlingAverage = length > 0.0 ? bowlingAverageTotal / length : 0.0; + final matchOvers = team.over; + final updatedOvers = totalOvers + matchOvers; return TeamStat( - played: length, - status: _teamMatchStatus(teamId), - run_rate: _runRate(teamId, runs), - runs: runs, - wickets: wickets, - batting_average: battingAverageTotal, - bowling_average: bowlingAverage, - highest_runs: highestRuns, - lowest_runs: lowestRuns == double.maxFinite.toInt() ? 0 : lowestRuns, - ); - } - - TeamMatchStatus _teamMatchStatus(String teamId) { - return fold( - const TeamMatchStatus(), - (status, match) { - final firstTeam = match.teams.firstWhere( - (team) => - team.team.id == - (match.toss_decision == TossDecision.bat - ? match.toss_winner_id - : match.teams - .firstWhere( - (team) => team.team.id != match.toss_winner_id, - ) - .team - .id), - ); - - final secondTeam = - match.teams.firstWhere((team) => team.team.id != firstTeam.team.id); - - if (firstTeam.run == secondTeam.run) { - return TeamMatchStatus( - win: status.win, - lost: status.lost, - tie: status.tie + 1, - ); - } else if ((firstTeam.run > secondTeam.run && - firstTeam.team.id == teamId) || - (firstTeam.run < secondTeam.run && secondTeam.team.id == teamId)) { - return TeamMatchStatus( - win: status.win + 1, - lost: status.lost, - tie: status.tie, - ); - } else { - return TeamMatchStatus( - win: status.win, - lost: status.lost + 1, - tie: status.tie, - ); - } - }, + played: currentStat.played + 1, + status: TeamMatchStatus( + win: currentStat.status.win + result.win, + lost: currentStat.status.lost + result.lost, + tie: currentStat.status.tie + result.tie, + ), + run_rate: updatedOvers > 0 + ? (currentStat.runs + matchRuns) / updatedOvers + : 0.0, + runs: currentStat.runs + matchRuns, + wickets: currentStat.wickets + matchWickets, + batting_average: currentStat.batting_average + battingAverage, + bowling_average: currentStat.played > 0 + ? (currentStat.bowling_average + bowlingAverage) / currentStat.played + : 0.0, + highest_runs: matchRuns > currentStat.highest_runs + ? matchRuns + : currentStat.highest_runs, + lowest_runs: currentStat.lowest_runs == 0 + ? matchRuns + : matchRuns < currentStat.lowest_runs + ? matchRuns + : currentStat.lowest_runs, ); } - MatchTeamModel _getTeam(MatchModel match, String teamId) => - match.teams.firstWhere((team) => team.team.id == teamId); + MatchTeamModel _getTeam(String teamId) => + teams.firstWhere((team) => team.team.id == teamId); - MatchTeamModel _getOpponentTeam(MatchModel match, String teamId) => - match.teams.firstWhere((team) => team.team.id != teamId); + MatchTeamModel _getOpponentTeam(String teamId) => + teams.firstWhere((team) => team.team.id != teamId); - double _runRate(String teamId, int runs) { - final totalOvers = map((match) => _getTeam(match, teamId)) - .fold(0.0, (total, team) => total + team.over); + TeamMatchStatus _matchResult(String teamId, int teamRun, int opponentRun) { + if (teamRun == opponentRun) { + return TeamMatchStatus(tie: 1); + } else if (teamRun > opponentRun) { + return TeamMatchStatus(win: 1); + } else { + return TeamMatchStatus(win: 0); + } + } - return totalOvers > 0 ? runs / totalOvers : 0; + double _computeOvers(int runs, double runRate) { + return runRate > 0 ? runs / runRate : 0.0; } } diff --git a/data/lib/api/match/match_model.freezed.dart b/data/lib/api/match/match_model.freezed.dart index 5e540e68..8d6d91c1 100644 --- a/data/lib/api/match/match_model.freezed.dart +++ b/data/lib/api/match/match_model.freezed.dart @@ -2277,489 +2277,3 @@ abstract class _RevisedTarget implements RevisedTarget { _$$RevisedTargetImplCopyWith<_$RevisedTargetImpl> get copyWith => throw _privateConstructorUsedError; } - -/// @nodoc -mixin _$TeamMatchStatus { - int get win => throw _privateConstructorUsedError; - int get tie => throw _privateConstructorUsedError; - int get lost => throw _privateConstructorUsedError; - - /// Create a copy of TeamMatchStatus - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - $TeamMatchStatusCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $TeamMatchStatusCopyWith<$Res> { - factory $TeamMatchStatusCopyWith( - TeamMatchStatus value, $Res Function(TeamMatchStatus) then) = - _$TeamMatchStatusCopyWithImpl<$Res, TeamMatchStatus>; - @useResult - $Res call({int win, int tie, int lost}); -} - -/// @nodoc -class _$TeamMatchStatusCopyWithImpl<$Res, $Val extends TeamMatchStatus> - implements $TeamMatchStatusCopyWith<$Res> { - _$TeamMatchStatusCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - /// Create a copy of TeamMatchStatus - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? win = null, - Object? tie = null, - Object? lost = null, - }) { - return _then(_value.copyWith( - win: null == win - ? _value.win - : win // ignore: cast_nullable_to_non_nullable - as int, - tie: null == tie - ? _value.tie - : tie // ignore: cast_nullable_to_non_nullable - as int, - lost: null == lost - ? _value.lost - : lost // ignore: cast_nullable_to_non_nullable - as int, - ) as $Val); - } -} - -/// @nodoc -abstract class _$$TeamMatchStatusImplCopyWith<$Res> - implements $TeamMatchStatusCopyWith<$Res> { - factory _$$TeamMatchStatusImplCopyWith(_$TeamMatchStatusImpl value, - $Res Function(_$TeamMatchStatusImpl) then) = - __$$TeamMatchStatusImplCopyWithImpl<$Res>; - @override - @useResult - $Res call({int win, int tie, int lost}); -} - -/// @nodoc -class __$$TeamMatchStatusImplCopyWithImpl<$Res> - extends _$TeamMatchStatusCopyWithImpl<$Res, _$TeamMatchStatusImpl> - implements _$$TeamMatchStatusImplCopyWith<$Res> { - __$$TeamMatchStatusImplCopyWithImpl( - _$TeamMatchStatusImpl _value, $Res Function(_$TeamMatchStatusImpl) _then) - : super(_value, _then); - - /// Create a copy of TeamMatchStatus - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? win = null, - Object? tie = null, - Object? lost = null, - }) { - return _then(_$TeamMatchStatusImpl( - win: null == win - ? _value.win - : win // ignore: cast_nullable_to_non_nullable - as int, - tie: null == tie - ? _value.tie - : tie // ignore: cast_nullable_to_non_nullable - as int, - lost: null == lost - ? _value.lost - : lost // ignore: cast_nullable_to_non_nullable - as int, - )); - } -} - -/// @nodoc - -class _$TeamMatchStatusImpl implements _TeamMatchStatus { - const _$TeamMatchStatusImpl({this.win = 0, this.tie = 0, this.lost = 0}); - - @override - @JsonKey() - final int win; - @override - @JsonKey() - final int tie; - @override - @JsonKey() - final int lost; - - @override - String toString() { - return 'TeamMatchStatus(win: $win, tie: $tie, lost: $lost)'; - } - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$TeamMatchStatusImpl && - (identical(other.win, win) || other.win == win) && - (identical(other.tie, tie) || other.tie == tie) && - (identical(other.lost, lost) || other.lost == lost)); - } - - @override - int get hashCode => Object.hash(runtimeType, win, tie, lost); - - /// Create a copy of TeamMatchStatus - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @override - @pragma('vm:prefer-inline') - _$$TeamMatchStatusImplCopyWith<_$TeamMatchStatusImpl> get copyWith => - __$$TeamMatchStatusImplCopyWithImpl<_$TeamMatchStatusImpl>( - this, _$identity); -} - -abstract class _TeamMatchStatus implements TeamMatchStatus { - const factory _TeamMatchStatus( - {final int win, final int tie, final int lost}) = _$TeamMatchStatusImpl; - - @override - int get win; - @override - int get tie; - @override - int get lost; - - /// Create a copy of TeamMatchStatus - /// with the given fields replaced by the non-null parameter values. - @override - @JsonKey(includeFromJson: false, includeToJson: false) - _$$TeamMatchStatusImplCopyWith<_$TeamMatchStatusImpl> get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -mixin _$TeamStat { - int get played => throw _privateConstructorUsedError; - TeamMatchStatus get status => throw _privateConstructorUsedError; - int get runs => throw _privateConstructorUsedError; - int get wickets => throw _privateConstructorUsedError; - double get batting_average => throw _privateConstructorUsedError; - double get bowling_average => throw _privateConstructorUsedError; - int get highest_runs => throw _privateConstructorUsedError; - int get lowest_runs => throw _privateConstructorUsedError; - double get run_rate => throw _privateConstructorUsedError; - - /// Create a copy of TeamStat - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - $TeamStatCopyWith get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $TeamStatCopyWith<$Res> { - factory $TeamStatCopyWith(TeamStat value, $Res Function(TeamStat) then) = - _$TeamStatCopyWithImpl<$Res, TeamStat>; - @useResult - $Res call( - {int played, - TeamMatchStatus status, - int runs, - int wickets, - double batting_average, - double bowling_average, - int highest_runs, - int lowest_runs, - double run_rate}); - - $TeamMatchStatusCopyWith<$Res> get status; -} - -/// @nodoc -class _$TeamStatCopyWithImpl<$Res, $Val extends TeamStat> - implements $TeamStatCopyWith<$Res> { - _$TeamStatCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; - - /// Create a copy of TeamStat - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? played = null, - Object? status = null, - Object? runs = null, - Object? wickets = null, - Object? batting_average = null, - Object? bowling_average = null, - Object? highest_runs = null, - Object? lowest_runs = null, - Object? run_rate = null, - }) { - return _then(_value.copyWith( - played: null == played - ? _value.played - : played // ignore: cast_nullable_to_non_nullable - as int, - status: null == status - ? _value.status - : status // ignore: cast_nullable_to_non_nullable - as TeamMatchStatus, - runs: null == runs - ? _value.runs - : runs // ignore: cast_nullable_to_non_nullable - as int, - wickets: null == wickets - ? _value.wickets - : wickets // ignore: cast_nullable_to_non_nullable - as int, - batting_average: null == batting_average - ? _value.batting_average - : batting_average // ignore: cast_nullable_to_non_nullable - as double, - bowling_average: null == bowling_average - ? _value.bowling_average - : bowling_average // ignore: cast_nullable_to_non_nullable - as double, - highest_runs: null == highest_runs - ? _value.highest_runs - : highest_runs // ignore: cast_nullable_to_non_nullable - as int, - lowest_runs: null == lowest_runs - ? _value.lowest_runs - : lowest_runs // ignore: cast_nullable_to_non_nullable - as int, - run_rate: null == run_rate - ? _value.run_rate - : run_rate // ignore: cast_nullable_to_non_nullable - as double, - ) as $Val); - } - - /// Create a copy of TeamStat - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $TeamMatchStatusCopyWith<$Res> get status { - return $TeamMatchStatusCopyWith<$Res>(_value.status, (value) { - return _then(_value.copyWith(status: value) as $Val); - }); - } -} - -/// @nodoc -abstract class _$$TeamStatImplCopyWith<$Res> - implements $TeamStatCopyWith<$Res> { - factory _$$TeamStatImplCopyWith( - _$TeamStatImpl value, $Res Function(_$TeamStatImpl) then) = - __$$TeamStatImplCopyWithImpl<$Res>; - @override - @useResult - $Res call( - {int played, - TeamMatchStatus status, - int runs, - int wickets, - double batting_average, - double bowling_average, - int highest_runs, - int lowest_runs, - double run_rate}); - - @override - $TeamMatchStatusCopyWith<$Res> get status; -} - -/// @nodoc -class __$$TeamStatImplCopyWithImpl<$Res> - extends _$TeamStatCopyWithImpl<$Res, _$TeamStatImpl> - implements _$$TeamStatImplCopyWith<$Res> { - __$$TeamStatImplCopyWithImpl( - _$TeamStatImpl _value, $Res Function(_$TeamStatImpl) _then) - : super(_value, _then); - - /// Create a copy of TeamStat - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? played = null, - Object? status = null, - Object? runs = null, - Object? wickets = null, - Object? batting_average = null, - Object? bowling_average = null, - Object? highest_runs = null, - Object? lowest_runs = null, - Object? run_rate = null, - }) { - return _then(_$TeamStatImpl( - played: null == played - ? _value.played - : played // ignore: cast_nullable_to_non_nullable - as int, - status: null == status - ? _value.status - : status // ignore: cast_nullable_to_non_nullable - as TeamMatchStatus, - runs: null == runs - ? _value.runs - : runs // ignore: cast_nullable_to_non_nullable - as int, - wickets: null == wickets - ? _value.wickets - : wickets // ignore: cast_nullable_to_non_nullable - as int, - batting_average: null == batting_average - ? _value.batting_average - : batting_average // ignore: cast_nullable_to_non_nullable - as double, - bowling_average: null == bowling_average - ? _value.bowling_average - : bowling_average // ignore: cast_nullable_to_non_nullable - as double, - highest_runs: null == highest_runs - ? _value.highest_runs - : highest_runs // ignore: cast_nullable_to_non_nullable - as int, - lowest_runs: null == lowest_runs - ? _value.lowest_runs - : lowest_runs // ignore: cast_nullable_to_non_nullable - as int, - run_rate: null == run_rate - ? _value.run_rate - : run_rate // ignore: cast_nullable_to_non_nullable - as double, - )); - } -} - -/// @nodoc - -class _$TeamStatImpl implements _TeamStat { - const _$TeamStatImpl( - {this.played = 0, - this.status = const TeamMatchStatus(), - this.runs = 0, - this.wickets = 0, - this.batting_average = 0.0, - this.bowling_average = 0.0, - this.highest_runs = 0, - this.lowest_runs = 0, - this.run_rate = 0.0}); - - @override - @JsonKey() - final int played; - @override - @JsonKey() - final TeamMatchStatus status; - @override - @JsonKey() - final int runs; - @override - @JsonKey() - final int wickets; - @override - @JsonKey() - final double batting_average; - @override - @JsonKey() - final double bowling_average; - @override - @JsonKey() - final int highest_runs; - @override - @JsonKey() - final int lowest_runs; - @override - @JsonKey() - final double run_rate; - - @override - String toString() { - return 'TeamStat(played: $played, status: $status, runs: $runs, wickets: $wickets, batting_average: $batting_average, bowling_average: $bowling_average, highest_runs: $highest_runs, lowest_runs: $lowest_runs, run_rate: $run_rate)'; - } - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$TeamStatImpl && - (identical(other.played, played) || other.played == played) && - (identical(other.status, status) || other.status == status) && - (identical(other.runs, runs) || other.runs == runs) && - (identical(other.wickets, wickets) || other.wickets == wickets) && - (identical(other.batting_average, batting_average) || - other.batting_average == batting_average) && - (identical(other.bowling_average, bowling_average) || - other.bowling_average == bowling_average) && - (identical(other.highest_runs, highest_runs) || - other.highest_runs == highest_runs) && - (identical(other.lowest_runs, lowest_runs) || - other.lowest_runs == lowest_runs) && - (identical(other.run_rate, run_rate) || - other.run_rate == run_rate)); - } - - @override - int get hashCode => Object.hash(runtimeType, played, status, runs, wickets, - batting_average, bowling_average, highest_runs, lowest_runs, run_rate); - - /// Create a copy of TeamStat - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @override - @pragma('vm:prefer-inline') - _$$TeamStatImplCopyWith<_$TeamStatImpl> get copyWith => - __$$TeamStatImplCopyWithImpl<_$TeamStatImpl>(this, _$identity); -} - -abstract class _TeamStat implements TeamStat { - const factory _TeamStat( - {final int played, - final TeamMatchStatus status, - final int runs, - final int wickets, - final double batting_average, - final double bowling_average, - final int highest_runs, - final int lowest_runs, - final double run_rate}) = _$TeamStatImpl; - - @override - int get played; - @override - TeamMatchStatus get status; - @override - int get runs; - @override - int get wickets; - @override - double get batting_average; - @override - double get bowling_average; - @override - int get highest_runs; - @override - int get lowest_runs; - @override - double get run_rate; - - /// Create a copy of TeamStat - /// with the given fields replaced by the non-null parameter values. - @override - @JsonKey(includeFromJson: false, includeToJson: false) - _$$TeamStatImplCopyWith<_$TeamStatImpl> get copyWith => - throw _privateConstructorUsedError; -} diff --git a/data/lib/api/team/team_model.dart b/data/lib/api/team/team_model.dart index 46778c13..2eca424b 100644 --- a/data/lib/api/team/team_model.dart +++ b/data/lib/api/team/team_model.dart @@ -30,6 +30,9 @@ abstract class TeamModel with _$TeamModel { @JsonKey(name: FireStoreConst.teamPlayers) @Default([]) List players, + @JsonKey(includeToJson: false, includeFromJson: false) + @Default(TeamStat()) + TeamStat stat, }) = _TeamModel; factory TeamModel.fromJson(Map json) => @@ -76,3 +79,44 @@ class TeamPlayer with _$TeamPlayer { factory TeamPlayer.fromJson(Map json) => _$TeamPlayerFromJson(json); } + +@freezed +class TeamStat with _$TeamStat { + @JsonSerializable(anyMap: true, explicitToJson: true) + const factory TeamStat({ + @Default(0) int played, + @Default(TeamMatchStatus()) TeamMatchStatus status, + @Default(0) int runs, + @Default(0) int wickets, + @Default(0.0) double batting_average, + @Default(0.0) double bowling_average, + @Default(0) int highest_runs, + @Default(0) int lowest_runs, + @Default(0.0) double run_rate, + }) = _TeamStat; + + factory TeamStat.fromJson(Map json) => + _$TeamStatFromJson(json); + + factory TeamStat.fromFireStore( + DocumentSnapshot> snapshot, + SnapshotOptions? options, + ) => + TeamStat.fromJson(snapshot.data()!); +} + +@freezed +class TeamMatchStatus with _$TeamMatchStatus { + const factory TeamMatchStatus({ + @Default(0) int win, + @Default(0) int tie, + @Default(0) int lost, + }) = _TeamMatchStatus; + + factory TeamMatchStatus.fromJson(Map json) => + _$TeamMatchStatusFromJson(json); +} + +extension TeamMatchStatusExtension on TeamMatchStatus { + int get matchCount => win + tie + lost; +} diff --git a/data/lib/api/team/team_model.freezed.dart b/data/lib/api/team/team_model.freezed.dart index d303e91e..1ea739ac 100644 --- a/data/lib/api/team/team_model.freezed.dart +++ b/data/lib/api/team/team_model.freezed.dart @@ -34,6 +34,8 @@ mixin _$TeamModel { DateTime? get created_time => throw _privateConstructorUsedError; @JsonKey(name: FireStoreConst.teamPlayers) List get players => throw _privateConstructorUsedError; + @JsonKey(includeToJson: false, includeFromJson: false) + TeamStat get stat => throw _privateConstructorUsedError; /// Serializes this TeamModel to a JSON map. Map toJson() => throw _privateConstructorUsedError; @@ -62,9 +64,11 @@ abstract class $TeamModelCopyWith<$Res> { UserModel created_by_user, DateTime? created_at, @TimeStampJsonConverter() DateTime? created_time, - @JsonKey(name: FireStoreConst.teamPlayers) List players}); + @JsonKey(name: FireStoreConst.teamPlayers) List players, + @JsonKey(includeToJson: false, includeFromJson: false) TeamStat stat}); $UserModelCopyWith<$Res> get created_by_user; + $TeamStatCopyWith<$Res> get stat; } /// @nodoc @@ -93,6 +97,7 @@ class _$TeamModelCopyWithImpl<$Res, $Val extends TeamModel> Object? created_at = freezed, Object? created_time = freezed, Object? players = null, + Object? stat = null, }) { return _then(_value.copyWith( id: null == id @@ -139,6 +144,10 @@ class _$TeamModelCopyWithImpl<$Res, $Val extends TeamModel> ? _value.players : players // ignore: cast_nullable_to_non_nullable as List, + stat: null == stat + ? _value.stat + : stat // ignore: cast_nullable_to_non_nullable + as TeamStat, ) as $Val); } @@ -151,6 +160,16 @@ class _$TeamModelCopyWithImpl<$Res, $Val extends TeamModel> return _then(_value.copyWith(created_by_user: value) as $Val); }); } + + /// Create a copy of TeamModel + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $TeamStatCopyWith<$Res> get stat { + return $TeamStatCopyWith<$Res>(_value.stat, (value) { + return _then(_value.copyWith(stat: value) as $Val); + }); + } } /// @nodoc @@ -173,10 +192,13 @@ abstract class _$$TeamModelImplCopyWith<$Res> UserModel created_by_user, DateTime? created_at, @TimeStampJsonConverter() DateTime? created_time, - @JsonKey(name: FireStoreConst.teamPlayers) List players}); + @JsonKey(name: FireStoreConst.teamPlayers) List players, + @JsonKey(includeToJson: false, includeFromJson: false) TeamStat stat}); @override $UserModelCopyWith<$Res> get created_by_user; + @override + $TeamStatCopyWith<$Res> get stat; } /// @nodoc @@ -203,6 +225,7 @@ class __$$TeamModelImplCopyWithImpl<$Res> Object? created_at = freezed, Object? created_time = freezed, Object? players = null, + Object? stat = null, }) { return _then(_$TeamModelImpl( id: null == id @@ -249,6 +272,10 @@ class __$$TeamModelImplCopyWithImpl<$Res> ? _value._players : players // ignore: cast_nullable_to_non_nullable as List, + stat: null == stat + ? _value.stat + : stat // ignore: cast_nullable_to_non_nullable + as TeamStat, )); } } @@ -270,7 +297,9 @@ class _$TeamModelImpl implements _TeamModel { this.created_at, @TimeStampJsonConverter() this.created_time, @JsonKey(name: FireStoreConst.teamPlayers) - final List players = const []}) + final List players = const [], + @JsonKey(includeToJson: false, includeFromJson: false) + this.stat = const TeamStat()}) : _players = players; factory _$TeamModelImpl.fromJson(Map json) => @@ -307,9 +336,13 @@ class _$TeamModelImpl implements _TeamModel { return EqualUnmodifiableListView(_players); } + @override + @JsonKey(includeToJson: false, includeFromJson: false) + final TeamStat stat; + @override String toString() { - return 'TeamModel(id: $id, name: $name, name_lowercase: $name_lowercase, city: $city, name_initial: $name_initial, profile_img_url: $profile_img_url, created_by: $created_by, created_by_user: $created_by_user, created_at: $created_at, created_time: $created_time, players: $players)'; + return 'TeamModel(id: $id, name: $name, name_lowercase: $name_lowercase, city: $city, name_initial: $name_initial, profile_img_url: $profile_img_url, created_by: $created_by, created_by_user: $created_by_user, created_at: $created_at, created_time: $created_time, players: $players, stat: $stat)'; } @override @@ -334,7 +367,8 @@ class _$TeamModelImpl implements _TeamModel { other.created_at == created_at) && (identical(other.created_time, created_time) || other.created_time == created_time) && - const DeepCollectionEquality().equals(other._players, _players)); + const DeepCollectionEquality().equals(other._players, _players) && + (identical(other.stat, stat) || other.stat == stat)); } @JsonKey(includeFromJson: false, includeToJson: false) @@ -351,7 +385,8 @@ class _$TeamModelImpl implements _TeamModel { created_by_user, created_at, created_time, - const DeepCollectionEquality().hash(_players)); + const DeepCollectionEquality().hash(_players), + stat); /// Create a copy of TeamModel /// with the given fields replaced by the non-null parameter values. @@ -382,8 +417,9 @@ abstract class _TeamModel implements TeamModel { final UserModel created_by_user, final DateTime? created_at, @TimeStampJsonConverter() final DateTime? created_time, - @JsonKey(name: FireStoreConst.teamPlayers) - final List players}) = _$TeamModelImpl; + @JsonKey(name: FireStoreConst.teamPlayers) final List players, + @JsonKey(includeToJson: false, includeFromJson: false) + final TeamStat stat}) = _$TeamModelImpl; factory _TeamModel.fromJson(Map json) = _$TeamModelImpl.fromJson; @@ -413,6 +449,9 @@ abstract class _TeamModel implements TeamModel { @override @JsonKey(name: FireStoreConst.teamPlayers) List get players; + @override + @JsonKey(includeToJson: false, includeFromJson: false) + TeamStat get stat; /// Create a copy of TeamModel /// with the given fields replaced by the non-null parameter values. @@ -636,3 +675,532 @@ abstract class _TeamPlayer implements TeamPlayer { _$$TeamPlayerImplCopyWith<_$TeamPlayerImpl> get copyWith => throw _privateConstructorUsedError; } + +TeamStat _$TeamStatFromJson(Map json) { + return _TeamStat.fromJson(json); +} + +/// @nodoc +mixin _$TeamStat { + int get played => throw _privateConstructorUsedError; + TeamMatchStatus get status => throw _privateConstructorUsedError; + int get runs => throw _privateConstructorUsedError; + int get wickets => throw _privateConstructorUsedError; + double get batting_average => throw _privateConstructorUsedError; + double get bowling_average => throw _privateConstructorUsedError; + int get highest_runs => throw _privateConstructorUsedError; + int get lowest_runs => throw _privateConstructorUsedError; + double get run_rate => throw _privateConstructorUsedError; + + /// Serializes this TeamStat to a JSON map. + Map toJson() => throw _privateConstructorUsedError; + + /// Create a copy of TeamStat + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + $TeamStatCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $TeamStatCopyWith<$Res> { + factory $TeamStatCopyWith(TeamStat value, $Res Function(TeamStat) then) = + _$TeamStatCopyWithImpl<$Res, TeamStat>; + @useResult + $Res call( + {int played, + TeamMatchStatus status, + int runs, + int wickets, + double batting_average, + double bowling_average, + int highest_runs, + int lowest_runs, + double run_rate}); + + $TeamMatchStatusCopyWith<$Res> get status; +} + +/// @nodoc +class _$TeamStatCopyWithImpl<$Res, $Val extends TeamStat> + implements $TeamStatCopyWith<$Res> { + _$TeamStatCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of TeamStat + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? played = null, + Object? status = null, + Object? runs = null, + Object? wickets = null, + Object? batting_average = null, + Object? bowling_average = null, + Object? highest_runs = null, + Object? lowest_runs = null, + Object? run_rate = null, + }) { + return _then(_value.copyWith( + played: null == played + ? _value.played + : played // ignore: cast_nullable_to_non_nullable + as int, + status: null == status + ? _value.status + : status // ignore: cast_nullable_to_non_nullable + as TeamMatchStatus, + runs: null == runs + ? _value.runs + : runs // ignore: cast_nullable_to_non_nullable + as int, + wickets: null == wickets + ? _value.wickets + : wickets // ignore: cast_nullable_to_non_nullable + as int, + batting_average: null == batting_average + ? _value.batting_average + : batting_average // ignore: cast_nullable_to_non_nullable + as double, + bowling_average: null == bowling_average + ? _value.bowling_average + : bowling_average // ignore: cast_nullable_to_non_nullable + as double, + highest_runs: null == highest_runs + ? _value.highest_runs + : highest_runs // ignore: cast_nullable_to_non_nullable + as int, + lowest_runs: null == lowest_runs + ? _value.lowest_runs + : lowest_runs // ignore: cast_nullable_to_non_nullable + as int, + run_rate: null == run_rate + ? _value.run_rate + : run_rate // ignore: cast_nullable_to_non_nullable + as double, + ) as $Val); + } + + /// Create a copy of TeamStat + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $TeamMatchStatusCopyWith<$Res> get status { + return $TeamMatchStatusCopyWith<$Res>(_value.status, (value) { + return _then(_value.copyWith(status: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$TeamStatImplCopyWith<$Res> + implements $TeamStatCopyWith<$Res> { + factory _$$TeamStatImplCopyWith( + _$TeamStatImpl value, $Res Function(_$TeamStatImpl) then) = + __$$TeamStatImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {int played, + TeamMatchStatus status, + int runs, + int wickets, + double batting_average, + double bowling_average, + int highest_runs, + int lowest_runs, + double run_rate}); + + @override + $TeamMatchStatusCopyWith<$Res> get status; +} + +/// @nodoc +class __$$TeamStatImplCopyWithImpl<$Res> + extends _$TeamStatCopyWithImpl<$Res, _$TeamStatImpl> + implements _$$TeamStatImplCopyWith<$Res> { + __$$TeamStatImplCopyWithImpl( + _$TeamStatImpl _value, $Res Function(_$TeamStatImpl) _then) + : super(_value, _then); + + /// Create a copy of TeamStat + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? played = null, + Object? status = null, + Object? runs = null, + Object? wickets = null, + Object? batting_average = null, + Object? bowling_average = null, + Object? highest_runs = null, + Object? lowest_runs = null, + Object? run_rate = null, + }) { + return _then(_$TeamStatImpl( + played: null == played + ? _value.played + : played // ignore: cast_nullable_to_non_nullable + as int, + status: null == status + ? _value.status + : status // ignore: cast_nullable_to_non_nullable + as TeamMatchStatus, + runs: null == runs + ? _value.runs + : runs // ignore: cast_nullable_to_non_nullable + as int, + wickets: null == wickets + ? _value.wickets + : wickets // ignore: cast_nullable_to_non_nullable + as int, + batting_average: null == batting_average + ? _value.batting_average + : batting_average // ignore: cast_nullable_to_non_nullable + as double, + bowling_average: null == bowling_average + ? _value.bowling_average + : bowling_average // ignore: cast_nullable_to_non_nullable + as double, + highest_runs: null == highest_runs + ? _value.highest_runs + : highest_runs // ignore: cast_nullable_to_non_nullable + as int, + lowest_runs: null == lowest_runs + ? _value.lowest_runs + : lowest_runs // ignore: cast_nullable_to_non_nullable + as int, + run_rate: null == run_rate + ? _value.run_rate + : run_rate // ignore: cast_nullable_to_non_nullable + as double, + )); + } +} + +/// @nodoc + +@JsonSerializable(anyMap: true, explicitToJson: true) +class _$TeamStatImpl implements _TeamStat { + const _$TeamStatImpl( + {this.played = 0, + this.status = const TeamMatchStatus(), + this.runs = 0, + this.wickets = 0, + this.batting_average = 0.0, + this.bowling_average = 0.0, + this.highest_runs = 0, + this.lowest_runs = 0, + this.run_rate = 0.0}); + + factory _$TeamStatImpl.fromJson(Map json) => + _$$TeamStatImplFromJson(json); + + @override + @JsonKey() + final int played; + @override + @JsonKey() + final TeamMatchStatus status; + @override + @JsonKey() + final int runs; + @override + @JsonKey() + final int wickets; + @override + @JsonKey() + final double batting_average; + @override + @JsonKey() + final double bowling_average; + @override + @JsonKey() + final int highest_runs; + @override + @JsonKey() + final int lowest_runs; + @override + @JsonKey() + final double run_rate; + + @override + String toString() { + return 'TeamStat(played: $played, status: $status, runs: $runs, wickets: $wickets, batting_average: $batting_average, bowling_average: $bowling_average, highest_runs: $highest_runs, lowest_runs: $lowest_runs, run_rate: $run_rate)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$TeamStatImpl && + (identical(other.played, played) || other.played == played) && + (identical(other.status, status) || other.status == status) && + (identical(other.runs, runs) || other.runs == runs) && + (identical(other.wickets, wickets) || other.wickets == wickets) && + (identical(other.batting_average, batting_average) || + other.batting_average == batting_average) && + (identical(other.bowling_average, bowling_average) || + other.bowling_average == bowling_average) && + (identical(other.highest_runs, highest_runs) || + other.highest_runs == highest_runs) && + (identical(other.lowest_runs, lowest_runs) || + other.lowest_runs == lowest_runs) && + (identical(other.run_rate, run_rate) || + other.run_rate == run_rate)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode => Object.hash(runtimeType, played, status, runs, wickets, + batting_average, bowling_average, highest_runs, lowest_runs, run_rate); + + /// Create a copy of TeamStat + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$TeamStatImplCopyWith<_$TeamStatImpl> get copyWith => + __$$TeamStatImplCopyWithImpl<_$TeamStatImpl>(this, _$identity); + + @override + Map toJson() { + return _$$TeamStatImplToJson( + this, + ); + } +} + +abstract class _TeamStat implements TeamStat { + const factory _TeamStat( + {final int played, + final TeamMatchStatus status, + final int runs, + final int wickets, + final double batting_average, + final double bowling_average, + final int highest_runs, + final int lowest_runs, + final double run_rate}) = _$TeamStatImpl; + + factory _TeamStat.fromJson(Map json) = + _$TeamStatImpl.fromJson; + + @override + int get played; + @override + TeamMatchStatus get status; + @override + int get runs; + @override + int get wickets; + @override + double get batting_average; + @override + double get bowling_average; + @override + int get highest_runs; + @override + int get lowest_runs; + @override + double get run_rate; + + /// Create a copy of TeamStat + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + _$$TeamStatImplCopyWith<_$TeamStatImpl> get copyWith => + throw _privateConstructorUsedError; +} + +TeamMatchStatus _$TeamMatchStatusFromJson(Map json) { + return _TeamMatchStatus.fromJson(json); +} + +/// @nodoc +mixin _$TeamMatchStatus { + int get win => throw _privateConstructorUsedError; + int get tie => throw _privateConstructorUsedError; + int get lost => throw _privateConstructorUsedError; + + /// Serializes this TeamMatchStatus to a JSON map. + Map toJson() => throw _privateConstructorUsedError; + + /// Create a copy of TeamMatchStatus + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + $TeamMatchStatusCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $TeamMatchStatusCopyWith<$Res> { + factory $TeamMatchStatusCopyWith( + TeamMatchStatus value, $Res Function(TeamMatchStatus) then) = + _$TeamMatchStatusCopyWithImpl<$Res, TeamMatchStatus>; + @useResult + $Res call({int win, int tie, int lost}); +} + +/// @nodoc +class _$TeamMatchStatusCopyWithImpl<$Res, $Val extends TeamMatchStatus> + implements $TeamMatchStatusCopyWith<$Res> { + _$TeamMatchStatusCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of TeamMatchStatus + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? win = null, + Object? tie = null, + Object? lost = null, + }) { + return _then(_value.copyWith( + win: null == win + ? _value.win + : win // ignore: cast_nullable_to_non_nullable + as int, + tie: null == tie + ? _value.tie + : tie // ignore: cast_nullable_to_non_nullable + as int, + lost: null == lost + ? _value.lost + : lost // ignore: cast_nullable_to_non_nullable + as int, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$TeamMatchStatusImplCopyWith<$Res> + implements $TeamMatchStatusCopyWith<$Res> { + factory _$$TeamMatchStatusImplCopyWith(_$TeamMatchStatusImpl value, + $Res Function(_$TeamMatchStatusImpl) then) = + __$$TeamMatchStatusImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({int win, int tie, int lost}); +} + +/// @nodoc +class __$$TeamMatchStatusImplCopyWithImpl<$Res> + extends _$TeamMatchStatusCopyWithImpl<$Res, _$TeamMatchStatusImpl> + implements _$$TeamMatchStatusImplCopyWith<$Res> { + __$$TeamMatchStatusImplCopyWithImpl( + _$TeamMatchStatusImpl _value, $Res Function(_$TeamMatchStatusImpl) _then) + : super(_value, _then); + + /// Create a copy of TeamMatchStatus + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? win = null, + Object? tie = null, + Object? lost = null, + }) { + return _then(_$TeamMatchStatusImpl( + win: null == win + ? _value.win + : win // ignore: cast_nullable_to_non_nullable + as int, + tie: null == tie + ? _value.tie + : tie // ignore: cast_nullable_to_non_nullable + as int, + lost: null == lost + ? _value.lost + : lost // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$TeamMatchStatusImpl implements _TeamMatchStatus { + const _$TeamMatchStatusImpl({this.win = 0, this.tie = 0, this.lost = 0}); + + factory _$TeamMatchStatusImpl.fromJson(Map json) => + _$$TeamMatchStatusImplFromJson(json); + + @override + @JsonKey() + final int win; + @override + @JsonKey() + final int tie; + @override + @JsonKey() + final int lost; + + @override + String toString() { + return 'TeamMatchStatus(win: $win, tie: $tie, lost: $lost)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$TeamMatchStatusImpl && + (identical(other.win, win) || other.win == win) && + (identical(other.tie, tie) || other.tie == tie) && + (identical(other.lost, lost) || other.lost == lost)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode => Object.hash(runtimeType, win, tie, lost); + + /// Create a copy of TeamMatchStatus + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$TeamMatchStatusImplCopyWith<_$TeamMatchStatusImpl> get copyWith => + __$$TeamMatchStatusImplCopyWithImpl<_$TeamMatchStatusImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$TeamMatchStatusImplToJson( + this, + ); + } +} + +abstract class _TeamMatchStatus implements TeamMatchStatus { + const factory _TeamMatchStatus( + {final int win, final int tie, final int lost}) = _$TeamMatchStatusImpl; + + factory _TeamMatchStatus.fromJson(Map json) = + _$TeamMatchStatusImpl.fromJson; + + @override + int get win; + @override + int get tie; + @override + int get lost; + + /// Create a copy of TeamMatchStatus + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + _$$TeamMatchStatusImplCopyWith<_$TeamMatchStatusImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/data/lib/api/team/team_model.g.dart b/data/lib/api/team/team_model.g.dart index 6485d6fc..ead14f1b 100644 --- a/data/lib/api/team/team_model.g.dart +++ b/data/lib/api/team/team_model.g.dart @@ -70,3 +70,47 @@ const _$TeamPlayerRoleEnumMap = { TeamPlayerRole.admin: 'admin', TeamPlayerRole.player: 'player', }; + +_$TeamStatImpl _$$TeamStatImplFromJson(Map json) => _$TeamStatImpl( + played: (json['played'] as num?)?.toInt() ?? 0, + status: json['status'] == null + ? const TeamMatchStatus() + : TeamMatchStatus.fromJson( + Map.from(json['status'] as Map)), + runs: (json['runs'] as num?)?.toInt() ?? 0, + wickets: (json['wickets'] as num?)?.toInt() ?? 0, + batting_average: (json['batting_average'] as num?)?.toDouble() ?? 0.0, + bowling_average: (json['bowling_average'] as num?)?.toDouble() ?? 0.0, + highest_runs: (json['highest_runs'] as num?)?.toInt() ?? 0, + lowest_runs: (json['lowest_runs'] as num?)?.toInt() ?? 0, + run_rate: (json['run_rate'] as num?)?.toDouble() ?? 0.0, + ); + +Map _$$TeamStatImplToJson(_$TeamStatImpl instance) => + { + 'played': instance.played, + 'status': instance.status.toJson(), + 'runs': instance.runs, + 'wickets': instance.wickets, + 'batting_average': instance.batting_average, + 'bowling_average': instance.bowling_average, + 'highest_runs': instance.highest_runs, + 'lowest_runs': instance.lowest_runs, + 'run_rate': instance.run_rate, + }; + +_$TeamMatchStatusImpl _$$TeamMatchStatusImplFromJson( + Map json) => + _$TeamMatchStatusImpl( + win: (json['win'] as num?)?.toInt() ?? 0, + tie: (json['tie'] as num?)?.toInt() ?? 0, + lost: (json['lost'] as num?)?.toInt() ?? 0, + ); + +Map _$$TeamMatchStatusImplToJson( + _$TeamMatchStatusImpl instance) => + { + 'win': instance.win, + 'tie': instance.tie, + 'lost': instance.lost, + }; diff --git a/data/lib/service/team/team_service.dart b/data/lib/service/team/team_service.dart index 0d0ad19e..871b68e1 100644 --- a/data/lib/service/team/team_service.dart +++ b/data/lib/service/team/team_service.dart @@ -31,6 +31,15 @@ class TeamService { toFirestore: (TeamModel team, _) => team.toJson(), ); + CollectionReference _teamStatCollection(String teamId) => + _teamsCollection + .doc(teamId) + .collection(FireStoreConst.teamStatCollection) + .withConverter( + fromFirestore: TeamStat.fromFireStore, + toFirestore: (stat, _) => stat.toJson(), + ); + String get generateTeamId => _teamsCollection.doc().id; Future getTeamById(String teamId) async { @@ -45,6 +54,21 @@ class TeamService { } } + Future getUserOwnedTeamsCount(String userId) { + final currentPlayer = TeamPlayer( + id: userId, + role: TeamPlayerRole.admin, + ); + + final filter = Filter.or( + Filter(FireStoreConst.createdBy, isEqualTo: userId), + Filter(FireStoreConst.teamPlayers, arrayContains: currentPlayer.toJson()), + ); + return _teamsCollection.where(filter).count().get().then((snapshot) { + return snapshot.count ?? 0; + }).catchError((error, stack) => throw AppError.fromError(error, stack)); + } + Stream streamTeamById(String teamId) { return _teamsCollection.doc(teamId).snapshots().asyncMap((teamDoc) async { final team = teamDoc.data(); @@ -54,6 +78,15 @@ class TeamService { }).handleError((error, stack) => AppError.fromError(error, stack)); } + Future getTeamStatById(String teamId) { + return _teamStatCollection(teamId) + .doc(FireStoreConst.stat) + .get() + .then((doc) { + return doc.data() ?? TeamStat(); + }).catchError((error, stack) => throw AppError.fromError(error, stack)); + } + Stream> streamUserRelatedTeams(String userId) { final currentPlayer = TeamPlayer(id: userId); @@ -100,21 +133,6 @@ class TeamService { }).handleError((error, stack) => throw AppError.fromError(error, stack)); } - Future getUserOwnedTeamsCount(String userId) { - final currentPlayer = TeamPlayer( - id: userId, - role: TeamPlayerRole.admin, - ); - - final filter = Filter.or( - Filter(FireStoreConst.createdBy, isEqualTo: userId), - Filter(FireStoreConst.teamPlayers, arrayContains: currentPlayer.toJson()), - ); - return _teamsCollection.where(filter).count().get().then((snapshot) { - return snapshot.count ?? 0; - }).catchError((error, stack) => throw AppError.fromError(error, stack)); - } - Future updateTeam(TeamModel team) async { try { final teamRef = _teamsCollection.doc(team.id); @@ -136,6 +154,15 @@ class TeamService { } } + Future updateTeamStat(String teamId, TeamStat stat) async { + try { + final teamRef = _teamStatCollection(teamId).doc(FireStoreConst.stat); + await teamRef.set(stat, SetOptions(merge: true)); + } catch (error, stack) { + throw AppError.fromError(error, stack); + } + } + Future addPlayersToTeam(String teamId, List players) async { try { await _teamsCollection.doc(teamId).update({ @@ -227,6 +254,9 @@ class TeamService { // Helper Method Future fetchDetailsOfTeam(TeamModel team) async { + final stat = await getTeamStatById(team.id); + team = team.copyWith(stat: stat); + final users = await getMemberListFromUserIds( team.players.map((e) => e.id).toList(), ); diff --git a/data/lib/service/user/user_service.dart b/data/lib/service/user/user_service.dart index 79b83701..526254a9 100644 --- a/data/lib/service/user/user_service.dart +++ b/data/lib/service/user/user_service.dart @@ -61,11 +61,6 @@ class UserService { toFirestore: (userStat, _) => userStat.toJson(), ); - Future> migrate() async { - final users = await _userRef.get(); - return users.docs.map((e) => e.data()).toList(); - } - Future clearSession({ required String uid, required String sessionId, diff --git a/data/lib/utils/constant/firestore_constant.dart b/data/lib/utils/constant/firestore_constant.dart index d4805559..73847ce9 100644 --- a/data/lib/utils/constant/firestore_constant.dart +++ b/data/lib/utils/constant/firestore_constant.dart @@ -4,6 +4,7 @@ class FireStoreConst { static const String matchSettingsSubCollection = "match_settings"; static const String settingDocument = "setting"; static const String teamsCollection = "teams"; + static const String teamStatCollection = "team_stat"; static const String inningsCollection = "innings"; static const String ballScoresCollection = "ball_scores"; static const String usersCollection = "users"; @@ -51,6 +52,7 @@ class FireStoreConst { static const String createdBy = "created_by"; static const String nameLowercase = "name_lowercase"; static const String profileImageUrl = "profile_img_url"; + static const String stat = "stat"; // users field const static const String deviceFcmToken = "device_fcm_token"; diff --git a/khelo/lib/ui/flow/score_board/score_board_view_model.dart b/khelo/lib/ui/flow/score_board/score_board_view_model.dart index 18d3bd5f..a28bc6e5 100644 --- a/khelo/lib/ui/flow/score_board/score_board_view_model.dart +++ b/khelo/lib/ui/flow/score_board/score_board_view_model.dart @@ -11,6 +11,7 @@ import 'package:data/extensions/list_extensions.dart'; import 'package:data/service/ball_score/ball_score_service.dart'; import 'package:data/service/innings/inning_service.dart'; import 'package:data/service/match/match_service.dart'; +import 'package:data/service/team/team_service.dart'; import 'package:data/service/user/user_service.dart'; import 'package:data/utils/combine_latest.dart'; import 'package:flutter/material.dart'; @@ -25,6 +26,7 @@ final scoreBoardStateProvider = StateNotifierProvider.autoDispose< ScoreBoardViewNotifier, ScoreBoardViewState>((ref) { return ScoreBoardViewNotifier( ref.read(matchServiceProvider), + ref.read(teamServiceProvider), ref.read(inningServiceProvider), ref.read(userServiceProvider), ref.read(ballScoreServiceProvider), @@ -33,6 +35,7 @@ final scoreBoardStateProvider = StateNotifierProvider.autoDispose< class ScoreBoardViewNotifier extends StateNotifier { final MatchService _matchService; + final TeamService _teamService; final InningsService _inningService; final UserService _userService; final BallScoreService _ballScoreService; @@ -45,6 +48,7 @@ class ScoreBoardViewNotifier extends StateNotifier { ScoreBoardViewNotifier( this._matchService, + this._teamService, this._inningService, this._userService, this._ballScoreService, @@ -772,7 +776,7 @@ class ScoreBoardViewNotifier extends StateNotifier { } } - void _addPlayerStats({bool isMatchComplete = false}) async { + void _updatePlayerStats({bool isMatchComplete = false}) async { try { final userStatType = state.match?.match_type == MatchType.testMatch ? UserStatType.test @@ -800,6 +804,20 @@ class ScoreBoardViewNotifier extends StateNotifier { } } + void _updateTeamStats() async { + try { + final teamIds = state.match?.teams.map((e) => e.team_id).toList() ?? []; + for (final teamId in teamIds) { + final currentStat = await _teamService.getTeamStatById(teamId); + final newStat = + state.match?.updateTeamStat(teamId, currentStat) ?? currentStat; + await _teamService.updateTeamStat(teamId, newStat); + } + } catch (e) { + debugPrint("ScoreBoardViewNotifier: error while adding team stats -> $e"); + } + } + bool _isAllOut() { // yet_to_play == 0 && playing == 1 && (cont_with_inj ? injured == 0 : true) && wicket_count == (cont_with_inj ? total_wicket : total_wicket - injure_count) - 1 final teamId = state.currentInning?.team_id; @@ -1130,7 +1148,7 @@ class ScoreBoardViewNotifier extends StateNotifier { } try { state = state.copyWith(actionError: null, isActionInProgress: true); - _addPlayerStats(); + _updatePlayerStats(); final batsMan = state.batsMans! .map((e) => e.copyWith( performance: e.performance.updateWhere( @@ -1203,7 +1221,8 @@ class ScoreBoardViewNotifier extends StateNotifier { } try { state = state.copyWith(actionError: null, isActionInProgress: true); - _addPlayerStats(isMatchComplete: true); + _updatePlayerStats(isMatchComplete: true); + _updateTeamStats(); List batsMan = []; if (state.batsMans?.isNotEmpty ?? false) { batsMan = state.batsMans! diff --git a/khelo/lib/ui/flow/team/detail/components/primer_progress_bar.dart b/khelo/lib/ui/flow/team/detail/components/primer_progress_bar.dart index 780b2669..4cefa26a 100644 --- a/khelo/lib/ui/flow/team/detail/components/primer_progress_bar.dart +++ b/khelo/lib/ui/flow/team/detail/components/primer_progress_bar.dart @@ -1,4 +1,4 @@ -import 'package:data/api/match/match_model.dart'; +import 'package:data/api/team/team_model.dart'; import 'package:flutter/material.dart'; import 'package:khelo/domain/extensions/context_extensions.dart'; diff --git a/khelo/lib/ui/flow/team/detail/components/team_detail_stat_content.dart b/khelo/lib/ui/flow/team/detail/components/team_detail_stat_content.dart index 252d8376..38818e42 100644 --- a/khelo/lib/ui/flow/team/detail/components/team_detail_stat_content.dart +++ b/khelo/lib/ui/flow/team/detail/components/team_detail_stat_content.dart @@ -1,4 +1,5 @@ import 'package:data/api/match/match_model.dart'; +import 'package:data/api/team/team_model.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; @@ -37,11 +38,11 @@ class TeamDetailStatContent extends ConsumerWidget { children: [ _matchPlayedProgress( context, - state.teamStat.status, - state.teamStat.played, + state.team!.stat.status, + state.team!.stat.played, ), const SizedBox(height: 16), - _teamStatsView(context, state.teamStat), + _teamStatsView(context, state.team!.stat), ], ); } diff --git a/khelo/lib/ui/flow/team/detail/team_detail_view_model.dart b/khelo/lib/ui/flow/team/detail/team_detail_view_model.dart index affed5a0..78b7bdb7 100644 --- a/khelo/lib/ui/flow/team/detail/team_detail_view_model.dart +++ b/khelo/lib/ui/flow/team/detail/team_detail_view_model.dart @@ -42,12 +42,9 @@ class TeamDetailViewNotifier extends StateNotifier { final teamCombiner = combineLatest2(_teamService.streamTeamById(_teamId!), _matchService.streamMatchesByTeamId(_teamId!)); _teamStreamSubscription = teamCombiner.listen((data) { - final teamStat = _calculateTeamStat(_teamId!, data.$2); - state = state.copyWith( team: data.$1, matches: data.$2, - teamStat: teamStat, loading: false, ); }, onError: (e) { @@ -57,13 +54,6 @@ class TeamDetailViewNotifier extends StateNotifier { }); } - TeamStat _calculateTeamStat(String teamId, List matches) { - final finishedMatches = matches - .where((match) => match.match_status == MatchStatus.finish) - .toList(); - return finishedMatches.teamStat(teamId); - } - void onTabChange(int tab) { if (state.selectedTab != tab) { state = state.copyWith(selectedTab: tab); @@ -86,6 +76,5 @@ class TeamDetailState with _$TeamDetailState { List? matches, @Default(0) int selectedTab, @Default(false) bool loading, - @Default(TeamStat()) TeamStat teamStat, }) = _TeamDetailState; } diff --git a/khelo/lib/ui/flow/team/detail/team_detail_view_model.freezed.dart b/khelo/lib/ui/flow/team/detail/team_detail_view_model.freezed.dart index c3a3c39b..d3114e00 100644 --- a/khelo/lib/ui/flow/team/detail/team_detail_view_model.freezed.dart +++ b/khelo/lib/ui/flow/team/detail/team_detail_view_model.freezed.dart @@ -22,7 +22,6 @@ mixin _$TeamDetailState { List? get matches => throw _privateConstructorUsedError; int get selectedTab => throw _privateConstructorUsedError; bool get loading => throw _privateConstructorUsedError; - TeamStat get teamStat => throw _privateConstructorUsedError; /// Create a copy of TeamDetailState /// with the given fields replaced by the non-null parameter values. @@ -43,11 +42,9 @@ abstract class $TeamDetailStateCopyWith<$Res> { String? currentUserId, List? matches, int selectedTab, - bool loading, - TeamStat teamStat}); + bool loading}); $TeamModelCopyWith<$Res>? get team; - $TeamStatCopyWith<$Res> get teamStat; } /// @nodoc @@ -71,7 +68,6 @@ class _$TeamDetailStateCopyWithImpl<$Res, $Val extends TeamDetailState> Object? matches = freezed, Object? selectedTab = null, Object? loading = null, - Object? teamStat = null, }) { return _then(_value.copyWith( error: freezed == error ? _value.error : error, @@ -95,10 +91,6 @@ class _$TeamDetailStateCopyWithImpl<$Res, $Val extends TeamDetailState> ? _value.loading : loading // ignore: cast_nullable_to_non_nullable as bool, - teamStat: null == teamStat - ? _value.teamStat - : teamStat // ignore: cast_nullable_to_non_nullable - as TeamStat, ) as $Val); } @@ -115,16 +107,6 @@ class _$TeamDetailStateCopyWithImpl<$Res, $Val extends TeamDetailState> return _then(_value.copyWith(team: value) as $Val); }); } - - /// Create a copy of TeamDetailState - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $TeamStatCopyWith<$Res> get teamStat { - return $TeamStatCopyWith<$Res>(_value.teamStat, (value) { - return _then(_value.copyWith(teamStat: value) as $Val); - }); - } } /// @nodoc @@ -141,13 +123,10 @@ abstract class _$$TeamDetailStateImplCopyWith<$Res> String? currentUserId, List? matches, int selectedTab, - bool loading, - TeamStat teamStat}); + bool loading}); @override $TeamModelCopyWith<$Res>? get team; - @override - $TeamStatCopyWith<$Res> get teamStat; } /// @nodoc @@ -169,7 +148,6 @@ class __$$TeamDetailStateImplCopyWithImpl<$Res> Object? matches = freezed, Object? selectedTab = null, Object? loading = null, - Object? teamStat = null, }) { return _then(_$TeamDetailStateImpl( error: freezed == error ? _value.error : error, @@ -193,10 +171,6 @@ class __$$TeamDetailStateImplCopyWithImpl<$Res> ? _value.loading : loading // ignore: cast_nullable_to_non_nullable as bool, - teamStat: null == teamStat - ? _value.teamStat - : teamStat // ignore: cast_nullable_to_non_nullable - as TeamStat, )); } } @@ -210,8 +184,7 @@ class _$TeamDetailStateImpl implements _TeamDetailState { this.currentUserId, final List? matches, this.selectedTab = 0, - this.loading = false, - this.teamStat = const TeamStat()}) + this.loading = false}) : _matches = matches; @override @@ -236,13 +209,10 @@ class _$TeamDetailStateImpl implements _TeamDetailState { @override @JsonKey() final bool loading; - @override - @JsonKey() - final TeamStat teamStat; @override String toString() { - return 'TeamDetailState(error: $error, team: $team, currentUserId: $currentUserId, matches: $matches, selectedTab: $selectedTab, loading: $loading, teamStat: $teamStat)'; + return 'TeamDetailState(error: $error, team: $team, currentUserId: $currentUserId, matches: $matches, selectedTab: $selectedTab, loading: $loading)'; } @override @@ -257,9 +227,7 @@ class _$TeamDetailStateImpl implements _TeamDetailState { const DeepCollectionEquality().equals(other._matches, _matches) && (identical(other.selectedTab, selectedTab) || other.selectedTab == selectedTab) && - (identical(other.loading, loading) || other.loading == loading) && - (identical(other.teamStat, teamStat) || - other.teamStat == teamStat)); + (identical(other.loading, loading) || other.loading == loading)); } @override @@ -270,8 +238,7 @@ class _$TeamDetailStateImpl implements _TeamDetailState { currentUserId, const DeepCollectionEquality().hash(_matches), selectedTab, - loading, - teamStat); + loading); /// Create a copy of TeamDetailState /// with the given fields replaced by the non-null parameter values. @@ -290,8 +257,7 @@ abstract class _TeamDetailState implements TeamDetailState { final String? currentUserId, final List? matches, final int selectedTab, - final bool loading, - final TeamStat teamStat}) = _$TeamDetailStateImpl; + final bool loading}) = _$TeamDetailStateImpl; @override Object? get error; @@ -305,8 +271,6 @@ abstract class _TeamDetailState implements TeamDetailState { int get selectedTab; @override bool get loading; - @override - TeamStat get teamStat; /// Create a copy of TeamDetailState /// with the given fields replaced by the non-null parameter values. diff --git a/khelo/lib/ui/flow/tournament/detail/tabs/tournament_detail_points_table_tab.dart b/khelo/lib/ui/flow/tournament/detail/tabs/tournament_detail_points_table_tab.dart index 49c47b6d..7a2937f1 100644 --- a/khelo/lib/ui/flow/tournament/detail/tabs/tournament_detail_points_table_tab.dart +++ b/khelo/lib/ui/flow/tournament/detail/tabs/tournament_detail_points_table_tab.dart @@ -80,16 +80,16 @@ class TournamentDetailPointsTableTab extends ConsumerWidget { _teamProfileDataCell(context, teamPoint.team), _dataCell(context, text: teamPoint.matchCount.toString()), _dataCell(context, - text: teamPoint.stat.status.win.toString()), + text: teamPoint.team.stat.status.win.toString()), _dataCell(context, - text: teamPoint.stat.status.lost.toString()), + text: teamPoint.team.stat.status.lost.toString()), _dataCell( context, text: teamPoint.points.toString(), textColor: context.colorScheme.textPrimary, ), _dataCell(context, - text: teamPoint.stat.run_rate.toStringAsFixed(1)), + text: teamPoint.team.stat.run_rate.toStringAsFixed(1)), ]), ) .toList())); diff --git a/khelo/lib/ui/flow/tournament/detail/tournament_detail_view_model.dart b/khelo/lib/ui/flow/tournament/detail/tournament_detail_view_model.dart index 3296e178..45a133d0 100644 --- a/khelo/lib/ui/flow/tournament/detail/tournament_detail_view_model.dart +++ b/khelo/lib/ui/flow/tournament/detail/tournament_detail_view_model.dart @@ -175,12 +175,12 @@ class TournamentDetailStateViewNotifier final matches = finishedMatches .where((element) => element.team_ids.contains(team.id)) .toList(); - final teamStat = matches.teamStat(team.id); + //final teamStat = matches.teamStat(team.id); //If team has won then add 2 points and tie then add 1 point - final points = teamStat.status.win * 2 + teamStat.status.tie; + final points = team.stat.status.win * 2 + team.stat.status.tie; teamPoints.add(TeamPoint( team: team, - stat: teamStat, + stat: team.stat, points: points, matchCount: matches.length, ));