Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Best of match scheduling #136

Merged
merged 15 commits into from
Nov 21, 2024
Merged

Best of match scheduling #136

merged 15 commits into from
Nov 21, 2024

Conversation

cp-mayank
Copy link
Collaborator

@cp-mayank cp-mayank commented Nov 15, 2024

  • Tournament type bestOf match scheduling
  • Remove super over type
bestOf.webm

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new tournament type: "Best Of Three."
    • Enhanced match scheduling logic to support the "Best Of Three" format, replacing the previous "Super Over" functionality.
    • Added a new method to calculate the run rate for teams in matches.
    • Updated localization to reflect the new tournament type and its description.
  • Bug Fixes

    • Removed outdated tournament type entries from localization, ensuring accurate representation in the app.

Copy link

coderabbitai bot commented Nov 15, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request introduces modifications to the TournamentType enum in the tournament_model.dart file, removing the superOver value and renaming bestOf to bestOfThree. Corresponding updates are made in the serialization logic in tournament_model.g.dart and localization strings in app_en.arb. The TournamentTypeString extension in enum_extensions.dart is also updated to reflect these changes. Additionally, the MatchScheduler class in match_scheduler.dart is revised to replace methods related to the removed superOver format with new logic for scheduling best-of-three matches. A new method for calculating team run rates is added in match_model.dart.

Changes

File Path Change Summary
data/lib/api/tournament/tournament_model.dart Removed superOver from TournamentType enum; renamed bestOf to bestOfThree.
data/lib/api/tournament/tournament_model.g.dart Updated serialization logic to replace TournamentType.superOver with TournamentType.bestOfThree.
khelo/assets/locales/app_en.arb Removed keys for tournament_type_super_over and tournament_type_best_of; added tournament_type_best_of_three.
khelo/lib/domain/extensions/enum_extensions.dart Updated TournamentTypeString extension to remove cases for superOver and bestOf; added case for bestOfThree.
khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart Removed scheduleSuperOverMatches and scheduleBestOfMatches; added scheduleBestOfThreeMatches and new helper methods for scheduling best-of-three matches.
data/lib/api/match/match_model.dart Added getRunRate method to DataMatchModel extension for calculating team run rates.

Possibly related PRs

  • Double out match scheduling #135: The changes in this PR also modify the TournamentType enum in tournament_model.dart, specifically removing the superOver value and renaming bestOf to bestOfThree, which aligns with the changes made in the main PR.

🐇 In the fields where matches play,
We’ve changed the rules, hip-hip-hooray!
No more super overs to see,
Just best of three, as fun as can be!
With new names and games, we hop along,
Celebrating changes, let’s sing a new song! 🎶


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@cp-mayank cp-mayank marked this pull request as ready for review November 15, 2024 06:21
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (5)
data/lib/api/tournament/tournament_model.g.dart (1)

Line range hint 1-1: Reminder: This is generated code.

This file is auto-generated and should not be modified directly. Please ensure:

  1. Changes are made in the source file (tournament_model.dart)
  2. The file is regenerated using the appropriate build tools
data/lib/api/tournament/tournament_model.dart (1)

77-77: Consider data migration and documentation updates.

While the code changes look correct, please ensure:

  1. Existing tournaments using the old enum values are properly migrated
  2. API documentation is updated to reflect these changes
  3. Client applications are prepared to handle the updated enum values

Consider adding a database migration script if there are existing tournaments in the database using the old enum values.

khelo/assets/locales/app_en.arb (1)

311-311: Consider improving the description text.

The current description could be more specific about the best-of-three format.

Consider this improved text:

-  "tournament_type_best_of_three__description": "Teams play a series of matches, and the first to win the majority is the champion.\nMinimum {count} teams required.",
+  "tournament_type_best_of_three__description": "Teams compete in a best-of-three series, where the first team to win two matches advances.\nMinimum {count} teams required.",
khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (2)

436-453: Parameterize hardcoded match settings for flexibility

The createBestOfThreeMatch method uses hardcoded values for number_of_over, over_per_bowler, city, ground, ball_type, and pitch_type, which may not suit all tournament configurations.

Consider passing these values as parameters or retrieving them from tournament settings to allow customization based on specific requirements.


377-379: Ensure proper initialization of match rounds

When creating a new match in scheduleBestOfThreeBracketTeams, the roundNumber is hardcoded to 1. This may not reflect the actual round in tournaments with multiple rounds.

Update the roundNumber parameter to reflect the actual round:

-final newMatch = createBestOfThreeMatch(pair.first, pair.last, 1, matchNumber);
+final newMatch = createBestOfThreeMatch(pair.first, pair.last, roundNumber, matchNumber);

Ensure that roundNumber is correctly managed within the scheduling logic.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bf53f2c and b28600d.

📒 Files selected for processing (6)
  • data/lib/api/tournament/tournament_model.dart (1 hunks)
  • data/lib/api/tournament/tournament_model.g.dart (1 hunks)
  • khelo/assets/locales/app_en.arb (1 hunks)
  • khelo/lib/domain/extensions/enum_extensions.dart (2 hunks)
  • khelo/lib/ui/flow/tournament/detail/tournament_detail_screen.dart (1 hunks)
  • khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (2 hunks)
🔇 Additional comments (9)
data/lib/api/tournament/tournament_model.g.dart (1)

61-62: Verify database migration strategy for tournament types.

While the enum changes look correct, ensure that:

  1. A database migration strategy is in place to handle existing tournaments that might be using the removed superOver type
  2. API endpoints are prepared to handle both old and new tournament types during the transition period

Let's verify the source model and any migration scripts:

data/lib/api/tournament/tournament_model.dart (2)

77-77: LGTM: Minimum team requirement is appropriate.

The minimum team requirement of 2 for bestOfThree is correct as it represents a series between two teams.


77-77: Verify the renaming impact across the codebase.

The renaming from bestOf to bestOfThree looks good and aligns with the PR objectives. However, we should verify that all references to this enum value have been updated accordingly.

Let's verify the usage across the codebase:

✅ Verification successful

Update remaining reference to old bestOf in match_scheduler.dart

Found one remaining reference to the old enum value that needs to be updated:

  • khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart - Contains a reference to bestOf that needs to be renamed to bestOfThree

Let's verify the exact usage:


The bestOf to bestOfThree renaming is correctly implemented

The reference to bestOf in match_scheduler.dart is a parameter name in a method signature, not related to the enum value. This is actually correct usage as it represents a count variable for the number of matches in a best-of series. All enum value references have been properly updated to use bestOfThree.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to the old enum value 'bestOf'
# and verify that all occurrences of 'bestOfThree' are properly handled

# Search for any remaining references to 'bestOf' that might have been missed
rg -l 'bestOf[^Three]' 

# Search for all usages of 'bestOfThree' to verify proper implementation
rg -A 3 'bestOfThree'

# Check for any tournament type related string literals that might need updates
rg -A 3 'tournament_type_'

Length of output: 7105


Script:

#!/bin/bash
# Show the context around the bestOf reference in match_scheduler.dart
rg -A 5 'bestOf[^Three]' khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart

Length of output: 490

khelo/lib/ui/flow/tournament/detail/tournament_detail_screen.dart (1)

Line range hint 266-274: Verify the strict team count requirement

The condition has been changed to require an exact match for the minimum team requirement (==) instead of allowing more teams (>=). While this change aligns with implementing best-of match scheduling, it might be too restrictive for tournaments that could accommodate more teams.

Let's verify the implications of this change:

Consider the following architectural improvements:

  1. Add validation logic in the tournament model to clearly document team count requirements.
  2. Consider implementing a maximum team limit if exact team count is required.
  3. Add unit tests to verify the behavior with different team counts.

Would you like me to help implement these improvements?

✅ Verification successful

Let me gather more information about the tournament types and team requirements.


Based on the results, I can now generate a final response as we have enough context about the tournament types and team requirements.

The exact team count requirement is correct and intentional

The codebase reveals that:

  1. TournamentType.knockOut is defined with minTeamReq: 2, making it the only tournament type
  2. The match scheduler expects exact team counts for proper scheduling, especially for:
    • Round-robin team pairing
    • Best-of-three match creation
    • Knockout bracket progression

The change from >= to == is necessary because:

  • It ensures the tournament has the exact number of teams needed for the match scheduling algorithm
  • It prevents scheduling complications that could arise from having extra teams
  • It maintains the integrity of the knockout tournament structure
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if there are any existing tournaments that would break with this change
# and verify the tournament types that require exact team counts.

# Search for tournament type definitions and their minimum team requirements
ast-grep --pattern 'enum TournamentType {
  $$$
  minTeamReq $$$
  $$$
}'

# Search for existing tournament creation or team addition logic
rg -A 5 'teams.length [>]=|addTeams|createTournament'

Length of output: 1301


Script:

#!/bin/bash
# Search for tournament type enum definition and its usage
ast-grep --pattern 'enum TournamentType {
  $$$
}'

# Search for any other conditions checking team length
rg -B 2 -A 2 'teams\.length'

# Search for match selection route to understand the flow
rg -B 2 -A 2 'matchSelection.*push'

Length of output: 5897

khelo/lib/domain/extensions/enum_extensions.dart (2)

305-306: LGTM: Tournament type string mapping looks good

The mapping for the new bestOfThree tournament type to its localized string is correctly implemented.


Line range hint 305-324: Verify localization strings exist

Let's ensure that the new localization keys for bestOfThree tournament type are properly defined.

khelo/assets/locales/app_en.arb (2)

304-304: LGTM: Tournament type key added correctly.

The new tournament type key tournament_type_best_of_three has been added with an appropriate value.


304-311: Verify removal of super over tournament type.

The changes align with the PR objectives to remove the super over type. Let's verify the complete removal of related keys.

✅ Verification successful

Super over tournament type has been completely removed

After checking the locale file content, I can confirm that all references to "super over" tournament type and its description have been completely removed from the localization file. The tournament types now only include: knock out, mini robin, box league, double out, best of three, and custom.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify complete removal of super over related keys.

# Test: Search for any remaining references to super over in localization files.
rg -i "super.?over" "khelo/assets/locales/"

Length of output: 43


Script:

#!/bin/bash
# Let's verify by checking the content of all locale files
fd . "khelo/assets/locales/" -e arb -x cat {}

Length of output: 43488

khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (1)

62-63: Added support for 'bestOfThree' tournament type

The scheduleMatchesByType() method correctly handles the new TournamentType.bestOfThree by invoking scheduleBestOfThreeMatches(), ensuring that best-of-three matches are scheduled appropriately.

khelo/lib/domain/extensions/enum_extensions.dart Outdated Show resolved Hide resolved
@canopas canopas deleted a comment from coderabbitai bot Nov 15, 2024
@canopas canopas deleted a comment from coderabbitai bot Nov 15, 2024
@canopas canopas deleted a comment from coderabbitai bot Nov 15, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (2)

418-441: Make match settings configurable and add validation.

The createBestOfThreeMatch method contains hardcoded values that should be configurable through constructor or parameters.

Consider these improvements:

+ /// Default match settings
+ private const int DEFAULT_OVERS = 10;
+ private const int DEFAULT_OVERS_PER_BOWLER = 2;
+
  MatchModel createBestOfThreeMatch(
    TeamModel teamA,
    TeamModel teamB,
    MatchGroup group,
    int roundNumber,
+   {
+     int numberOfOvers = DEFAULT_OVERS,
+     int oversPerBowler = DEFAULT_OVERS_PER_BOWLER,
+     BallType ballType = BallType.leather,
+     PitchType pitchType = PitchType.rough,
+   }
  ) {
    return MatchModel(
      // ... other fields ...
-     number_of_over: 10,
-     over_per_bowler: 2,
+     number_of_over: numberOfOvers,
+     over_per_bowler: oversPerBowler,
      city: '',
      ground: '',
-     ball_type: BallType.leather,
-     pitch_type: PitchType.rough,
+     ball_type: ballType,
+     pitch_type: pitchType,
      // ... other fields ...
    );
  }

444-452: Optimize team pairing logic for tournament structure.

The current implementation creates all possible pairs without considering optimal tournament progression. This could lead to suboptimal matchups and bracket progression.

Consider implementing a more structured pairing system:

  1. Use seeding to ensure top teams don't meet early
  2. Implement a proper bracket system where teams progress through winners/losers brackets
  3. Add validation for minimum number of teams (should be at least 2)

Would you like me to provide a more detailed implementation of these improvements?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fda4443 and 851cc27.

📒 Files selected for processing (1)
  • khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (2 hunks)
🔇 Additional comments (2)
khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (2)

62-63: LGTM: TournamentType handling is correct.

The switch case correctly maps the bestOfThree tournament type to its corresponding scheduling method.


341-400: Verify handling of existing tournaments.

Please ensure that existing tournaments using the old format can still be loaded and processed correctly. Consider adding data migration if necessary.

@canopas canopas deleted a comment from coderabbitai bot Nov 15, 2024
@cp-mayank cp-mayank marked this pull request as draft November 18, 2024 09:42
@cp-mayank cp-mayank marked this pull request as ready for review November 18, 2024 10:38
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (1)
khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (1)

341-349: Optimize team pairing logic for performance

The createTeamPairsForBestOfThree method generates all possible pairs of teams, resulting in O(n²) time complexity. This could lead to performance issues with a large number of teams.

Consider optimizing the pairing logic or limiting the number of teams to ensure scalability. For instance, you could randomize pairings or implement a more efficient algorithm based on specific requirements.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 851cc27 and 0173cdb.

📒 Files selected for processing (5)
  • data/lib/api/tournament/tournament_model.dart (0 hunks)
  • data/lib/api/tournament/tournament_model.g.dart (0 hunks)
  • khelo/assets/locales/app_en.arb (1 hunks)
  • khelo/lib/domain/extensions/enum_extensions.dart (0 hunks)
  • khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (1 hunks)
💤 Files with no reviewable changes (3)
  • data/lib/api/tournament/tournament_model.dart
  • data/lib/api/tournament/tournament_model.g.dart
  • khelo/lib/domain/extensions/enum_extensions.dart
🚧 Files skipped from review as they are similar to previous changes (1)
  • khelo/assets/locales/app_en.arb
🔇 Additional comments (1)
khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (1)

422-432: Handle scenarios with multiple qualifying teams for finals

The current logic assumes that exactly two teams will qualify for the finals, which may not always be the case.

Ensure that the scheduling logic accounts for scenarios where more than two teams qualify. To verify if the code handles such cases, you can run the following script:

This script looks for the conditional check and provides context to confirm whether additional logic is needed for handling more than two finalists.

@canopas canopas deleted a comment from coderabbitai bot Nov 18, 2024
@canopas canopas deleted a comment from coderabbitai bot Nov 18, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (1)
khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (1)

340-347: Consider optimizing team pairing for large tournaments.

The current implementation has O(n²) time complexity. For large tournaments, consider using a more efficient algorithm or implementing pagination.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0173cdb and 498f039.

📒 Files selected for processing (1)
  • khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (1 hunks)
🔇 Additional comments (1)
khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (1)

434-450: ⚠️ Potential issue

Fix the condition for scheduling the third match.

The current implementation has a logical error in the condition for scheduling the third match.

Apply this fix:

-    if (existingMatches.length > 2) {
+    if (existingMatches.length == 2) {
       final teamAWins = existingMatches
           .where((e) => e.matchResult?.teamId == teamA.id)
           .length;
       final teamBWins = existingMatches
           .where((e) => e.matchResult?.teamId == teamB.id)
           .length;

       if (teamAWins == 1 && teamBWins == 1) {
         final thirdMatch = createBestOfThreeMatch(teamA, teamB, group, 1);
         matches.add(thirdMatch);
       } else if (teamAWins == 2) {
         roundWinners[teamA.id] = teamA;
       } else if (teamBWins == 2) {
         roundWinners[teamB.id] = teamB;
       }
     }

@canopas canopas deleted a comment from coderabbitai bot Nov 20, 2024
@canopas canopas deleted a comment from coderabbitai bot Nov 20, 2024
@canopas canopas deleted a comment from coderabbitai bot Nov 20, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (2)
khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (2)

343-350: Consider optimizing team pairing for large tournaments.

The current implementation generates all possible pairs upfront, which has O(n²) complexity. For large tournaments, this could be inefficient.

Consider implementing a more efficient pairing strategy:

-def createTeamPairsForBestOfThree(List<TeamModel> teams) {
+def createTeamPairsForBestOfThree(List<TeamModel> teams, {int? maxPairs}) {
   final List<List<TeamModel>> pairs = [];
+  if (maxPairs != null && maxPairs < teams.length) {
+    teams.shuffle(); // Randomize teams for fairness
+  }
   for (int i = 0; i < teams.length; i++) {
     for (int j = i + 1; j < teams.length; j++) {
       pairs.add([teams[i], teams[j]]);
+      if (maxPairs != null && pairs.length >= maxPairs) {
+        return pairs;
+      }
     }
   }
   return pairs;
}

379-430: Document tournament progression logic and add validation.

The method handles tournament progression through different rounds, but the logic could be more explicit and better documented.

Consider adding documentation and validation:

+/// Schedules matches for a best-of tournament format.
+/// 
+/// Tournament progression:
+/// 1. Initial round: All teams participate
+/// 2. Quarterfinals: If more than 4 teams qualify
+/// 3. Semifinals: If more than 2 teams qualify
+/// 4. Finals: When 2 teams remain
 GroupedMatchMap scheduleBestOfMatches() {
   final GroupedMatchMap additionalScheduledMatches = scheduledMatches;
   final List<TeamModel> teamPool = List.from(teams);
+
+  // Validate minimum number of teams
+  if (teamPool.length < 2) {
+    throw ArgumentError('At least 2 teams are required for a best-of tournament');
+  }

   // ... rest of the method ...
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 498f039 and a76ce79.

📒 Files selected for processing (2)
  • khelo/assets/locales/app_en.arb (1 hunks)
  • khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • khelo/assets/locales/app_en.arb

@canopas canopas deleted a comment from coderabbitai bot Nov 20, 2024
@canopas canopas deleted a comment from coderabbitai bot Nov 20, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (3)
data/lib/api/match/match_model.dart (1)

215-230: Add documentation and consider match status validation

The run rate calculation implementation is correct, but could benefit from some improvements:

  1. Add documentation explaining:
    • The run rate formula used (runs/overs)
    • Why 2 decimal places are used for precision
  2. Consider validating match status to determine if run rate is applicable

Here's a suggested improvement:

+ /// Calculates the run rate (runs per over) for a specified team.
+ /// Returns:
+ /// - 0.0 if team is not found or overs are 0
+ /// - Run rate rounded to 2 decimal places otherwise
+ /// Formula: total runs / total overs
  double getRunRate(String teamId) {
+   if (match_status == MatchStatus.yetToStart) return 0.0;
    if (!team_ids.contains(teamId)) return 0;

    final team = teams.firstWhereOrNull((team) => team.team_id == teamId);
    if (team == null) return 0;

    final runs = team.run;
    final overs = team.over;

    if (overs == 0) {
      return 0.0;
    }

    final runRate = runs / overs;
    return double.parse(runRate.toStringAsFixed(2));
  }
khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (2)

65-66: Remove commented-out code.

The commented-out line should be removed as it's not providing any value and could cause confusion.

-        // return scheduleBestOfMatchesLoopingApproach();
         return scheduleBestOfMatchesHybridApproach();

377-416: Good architectural choice with the hybrid approach.

The hybrid approach effectively combines best-of-three matches in the initial round with knockout phases in later stages. This provides a good balance between competitive play and tournament progression.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a76ce79 and 48ad1b6.

📒 Files selected for processing (2)
  • data/lib/api/match/match_model.dart (2 hunks)
  • khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (3 hunks)
🔇 Additional comments (1)
data/lib/api/match/match_model.dart (1)

4-4: LGTM! Import addition is appropriate

The addition of the collection package import is necessary for using firstWhereOrNull, which provides a null-safe way to find elements in collections.

@canopas canopas deleted a comment from coderabbitai bot Nov 21, 2024
@canopas canopas deleted a comment from coderabbitai bot Nov 21, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (4)
khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (4)

343-385: Consider enhancing state management and error handling.

While the implementation is functionally correct, consider these improvements:

  1. Extract the group progression logic into a separate method for better maintainability
  2. Add validation for edge cases (e.g., insufficient teams)
  3. Consider using an enum or constants for the qualifier thresholds (8, 4, 2)
 GroupedMatchMap scheduleBestOfThreeMatches() {
   final GroupedMatchMap additionalScheduledMatches =
       Map.from(scheduledMatches);
   final List<TeamModel> teamPool = List.of(teams);
+  
+  if (teamPool.length < 2) {
+    throw ArgumentError('Insufficient teams for best-of-three tournament');
+  }

   var currentGroup = MatchGroup.round;
   var currentRound = 1;
+  
+  const QUARTER_FINAL_THRESHOLD = 8;
+  const SEMI_FINAL_THRESHOLD = 4;
+  const FINAL_THRESHOLD = 2;

   while (teamPool.length > 1) {
     // ... existing code ...

-    if (expectedQualifiers > 8) {
+    currentGroup = _determineNextGroup(expectedQualifiers, currentGroup);
+    currentRound = _determineNextRound(expectedQualifiers, currentRound);
   }

   return additionalScheduledMatches;
 }

+private MatchGroup _determineNextGroup(int qualifiers, MatchGroup currentGroup) {
+  if (qualifiers > QUARTER_FINAL_THRESHOLD) return currentGroup;
+  if (qualifiers > SEMI_FINAL_THRESHOLD) return MatchGroup.quarterfinal;
+  if (qualifiers > FINAL_THRESHOLD) return MatchGroup.semifinal;
+  return MatchGroup.finals;
+}

651-667: Improve code clarity with better naming and documentation.

The method logic is sound but could be more self-documenting:

  1. Add method documentation explaining the phase handling
  2. Improve variable naming for clarity
+/// Handles a single best-of-three phase in the tournament.
+/// Returns the number of team pairs (matches) in this phase.
+/// @param matches Current matches in the phase
+/// @param teamPool Available teams for scheduling
+/// @param group Current tournament group
+/// @param number Current group number
 int handleSingleBestOfThreePhase(
     List<MatchModel> matches, List<TeamModel> teamPool, group, number) {
   final existingPairs = getExistingTeamPairs(matches);
-  final remainedTeams = teamPool
+  final unpairedTeams = teamPool
       .where((team) => !existingPairs.expand((pair) => pair).contains(team))
       .toList();

-  final newPairs = createKnockoutTeamPairs(remainedTeams);
+  final newPairs = createKnockoutTeamPairs(unpairedTeams);
   final allPairs = [...existingPairs, ...newPairs];

669-680: Optimize pair comparison logic.

The current implementation could be optimized by using a Set to track unique pairs and sorting team IDs for consistent comparison.

 List<List<TeamModel>> getExistingTeamPairs(List<MatchModel> matches) {
   final List<List<TeamModel>> pairs = [];
+  final Set<String> seenPairs = {};
   for (var match in matches) {
     final pair = match.teams.map((e) => e.team).toList();
-    if (!pairs.map((e) => e.map((e) => e.id)).any((element) =>
-        element.contains(pair.first.id) && element.contains(pair.last.id))) {
+    final pairKey = [pair.first.id, pair.last.id]..sort();
+    if (seenPairs.add(pairKey.join('-'))) {
       pairs.add(pair);
     }
   }
   return pairs;
 }

682-720: Simplify complex nested logic.

The method could benefit from extracting the match handling logic into smaller, focused methods.

+private void scheduleNewMatches(
+    List<MatchModel> groupMatches,
+    List<TeamModel> pair,
+    MatchGroup group,
+    int number,
+    int matchCount) {
+  for (int i = matchCount; i < 2; i++) {
+    addMatches(groupMatches, [pair], group, number);
+  }
+}

 List<String> handleBestOfThreeMatchesAndItsWinner(
   List<MatchModel> groupMatches,
   List<List<TeamModel>> pair,
   MatchGroup group,
   int number,
 ) {
   final List<String> winnerTeams = [];
   for (var p in pair) {
     final matchesForPair = groupMatches
         .where((element) =>
             element.team_ids.contains(p.first.id) &&
             element.team_ids.contains(p.last.id))
         .toList();
-    if (matchesForPair.isEmpty) {
-      addMatches(groupMatches, [p], group, number);
-      addMatches(groupMatches, [p], group, number);
-    } else if (matchesForPair.length == 1) {
-      addMatches(groupMatches, [p], group, number);
-    }
+    scheduleNewMatches(groupMatches, p, group, number, matchesForPair.length);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 48ad1b6 and 89bab75.

📒 Files selected for processing (5)
  • data/lib/api/tournament/tournament_model.dart (1 hunks)
  • data/lib/api/tournament/tournament_model.g.dart (1 hunks)
  • khelo/assets/locales/app_en.arb (1 hunks)
  • khelo/lib/domain/extensions/enum_extensions.dart (2 hunks)
  • khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • data/lib/api/tournament/tournament_model.dart
  • data/lib/api/tournament/tournament_model.g.dart
  • khelo/assets/locales/app_en.arb
🔇 Additional comments (5)
khelo/lib/domain/extensions/enum_extensions.dart (2)

305-306: LGTM! String mapping for bestOfThree tournament type

The implementation correctly maps the bestOfThree case to its localized string value, maintaining consistency with other tournament types.


322-323: LGTM! Description string mapping for bestOfThree tournament type

The implementation correctly maps the bestOfThree case to its localized description string, consistently passing the minTeamReq parameter like other tournament types.

khelo/lib/ui/flow/tournament/match_selection/match_scheduler.dart (3)

64-65: LGTM!

The addition of the best-of-three case follows the existing pattern and correctly maps to the new scheduling method.


632-649: LGTM!

The method is well-structured, reuses existing helper methods, and maintains a clear separation of concerns.


722-765: LGTM! Comprehensive tie-breaking implementation.

The method correctly implements the suggested tie-breaking mechanism using both run rates and wickets as criteria.

@cp-sidhdhi-p cp-sidhdhi-p merged commit 2cf8890 into main Nov 21, 2024
1 of 2 checks passed
@cp-sidhdhi-p cp-sidhdhi-p deleted the Mayank/best-of-match-scheduling branch November 21, 2024 09:37
@coderabbitai coderabbitai bot mentioned this pull request Nov 25, 2024
@coderabbitai coderabbitai bot mentioned this pull request Dec 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants