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

Add match setting in sub collection #116

Merged
merged 4 commits into from
Oct 11, 2024

Conversation

cp-sidhdhi-p
Copy link
Collaborator

@cp-sidhdhi-p cp-sidhdhi-p commented Oct 9, 2024

Add Match setting in database

Simulator.Screen.Recording.-.iPhone.16.-.2024-10-09.at.17.07.50.mp4

Screenshot 2024-10-09 at 5 06 33 PM

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced MatchSetting class for managing match configurations with default options.
    • Added real-time streaming and updating of match settings.
    • Enhanced scoreboard display with improved handling of match options.
  • Bug Fixes

    • Improved handling of match options, including toggling for injured players.
  • Documentation

    • Updated constants for Firestore collections related to match settings.
  • Refactor

    • Streamlined state management and method signatures for clarity and efficiency.

Copy link

coderabbitai bot commented Oct 9, 2024

Walkthrough

This pull request introduces a new class, MatchSetting, in the match_model.dart file, which includes three boolean properties with default values. It also provides methods for JSON serialization and Firestore integration. Additionally, several modifications are made across various files, including updates to the MatchService for handling match settings, new constants for Firestore, and adjustments in UI components to reflect changes in match options. The changes enhance the overall functionality related to match settings and their management.

Changes

File Path Change Summary
data/lib/api/match/match_model.dart Added MatchSetting class with boolean properties and JSON serialization methods. Updated MatchModel for serialization and new property.
data/lib/api/match/match_model.g.dart Added serialization/deserialization functions for MatchSettingImpl.
data/lib/service/match/match_service.dart Added methods for handling match settings in Firestore: _matchSettingDocument, streamMatchSetting, updateMatchSetting.
data/lib/utils/constant/firestore_constant.dart Added constants for Firestore match settings.
khelo/lib/ui/flow/score_board/score_board_screen.dart Added _getDefaultValue method for match option defaults and updated state management for match settings.
khelo/lib/ui/flow/score_board/score_board_view_model.dart Added stream subscription for MatchSetting and updated methods for managing match options and state.

Poem

🐰 In the meadow where matches play,
New settings hop in, brightening the day.
With wheels for runs and dots that gleam,
Our scoreboard dances, a winning dream!
Toggle and stream, let the fun unfold,
In the game of cricket, new tales are told! 🎉


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.

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 (9)
data/lib/utils/constant/firestore_constant.dart (1)

4-5: LGTM! Consider adding a comment for clarity.

The new constants matchSettingSubCollection and settingDocument are well-placed and follow the existing naming conventions. They appear to represent new Firestore subcollections or documents related to match settings.

For improved clarity, consider adding a brief comment above these new constants to explain their purpose, similar to the existing "collection" comment. For example:

  // collection
  static const String matchesCollection = "matches";
+ // match setting subcollection and document
  static const String matchSettingSubCollection = "match_setting";
  static const String settingDocument = "setting";
data/lib/api/match/match_model.dart (1)

67-70: Consider using camelCase for property names.

While the current naming convention (snake_case) might be consistent with the project's conventions, it's worth noting that Dart typically uses camelCase for variable and property names. If this project doesn't have a specific reason for using snake_case, consider refactoring these property names to camelCase for better alignment with Dart conventions:

@Default(true) bool continueWithInjuredPlayer,
@Default(true) bool showWagonWheelForLessRun,
@Default(true) bool showWagonWheelForDotBall,

This suggestion is purely for maintaining consistency with Dart conventions and can be disregarded if the project has established different naming guidelines.

khelo/lib/ui/flow/score_board/components/select_player_sheet.dart (1)

275-276: LGTM with a minor suggestion for improvement.

The refactoring to use onToggleMatchOptionChange instead of onContinueWithInjuredPlayersChange is a good improvement in the design, allowing for more uniform handling of match options.

The added logic to clear injured batsmen when disabling the option is a good safety measure. However, for completeness, consider applying the same logic to batsMan2 as well.

Here's a suggested improvement:

 if (!isEnabled) {
   if (batsMan1?.performance
           .firstWhereOrNull(
               (element) => element.inning_id == state.currentInning?.id)
           ?.status ==
       PlayerStatus.injured) {
     batsMan1 = null;
   }
+  if (batsMan2?.performance
+          .firstWhereOrNull(
+              (element) => element.inning_id == state.currentInning?.id)
+          ?.status ==
+      PlayerStatus.injured) {
+    batsMan2 = null;
+  }
 }

This ensures that both batsMan1 and batsMan2 are cleared if they are injured when the option is disabled.

Also applies to: 277-289

data/lib/service/match/match_service.dart (3)

40-49: LGTM! Consider adding a brief documentation comment.

The _matchSettingDocument method is well-implemented, following Firestore best practices and using a converter for type safety. As a minor suggestion, consider adding a brief documentation comment explaining the purpose and return type of this method for better maintainability.


101-106: LGTM! Consider adding error logging.

The streamMatchSetting method is well-implemented, providing real-time updates and including error handling. To further improve error management, consider adding error logging before throwing the AppError. This can help with debugging and monitoring in production.

Example:

.handleError((error, stack) {
  // Log the error
  print('Error in streamMatchSetting: $error');
  throw AppError.fromError(error, stack);
});

108-112: LGTM! Consider adding input validation.

The updateMatchSetting method is well-implemented, using SetOptions(merge: true) for partial updates and including error handling. To further improve robustness, consider adding input validation for the matchId and settings parameters before performing the update.

Example:

Future<void> updateMatchSetting(String matchId, MatchSetting settings) async {
  if (matchId.isEmpty) {
    throw ArgumentError('matchId cannot be empty');
  }
  // Add any necessary validation for settings
  
  await _matchSettingDocument(matchId)
      .set(settings, SetOptions(merge: true))
      .catchError((error, stack) => throw AppError.fromError(error, stack));
}
khelo/assets/locales/app_en.arb (1)

686-687: LGTM! Consider updating related documentation.

The changes to show a wheel for 1s, 2s, 3s, and dot balls appear to be a good UI improvement. This should make the scoring process more intuitive and visually engaging for users.

Don't forget to update any related documentation or user guides to reflect this new UI feature. This will ensure users are aware of the new wheel interface for these scoring events.

data/lib/api/match/match_model.freezed.dart (1)

987-1178: Good implementation, but consider Dart naming conventions and default values.

The MatchSetting class is well-structured and correctly implements the Freezed package for immutability and JSON serialization. However, there are a couple of points to consider:

  1. The property names use snake_case, which is not typical for Dart. Consider renaming them to camelCase for better consistency with Dart conventions:

    • continue_with_injured_player -> continueWithInjuredPlayer
    • show_wagon_wheel_for_less_run -> showWagonWheelForLessRun
    • show_wagon_wheel_for_dot_ball -> showWagonWheelForDotBall
  2. All boolean properties have a default value of true. Consider if this is the desired default behavior for all settings, or if some should default to false.

Here's a suggested refactor for the class definition:

@freezed
class MatchSetting with _$MatchSetting {
  const factory MatchSetting({
    @Default(false) bool continueWithInjuredPlayer,
    @Default(true) bool showWagonWheelForLessRun,
    @Default(false) bool showWagonWheelForDotBall,
  }) = _MatchSetting;

  factory MatchSetting.fromJson(Map<String, dynamic> json) =>
      _$MatchSettingFromJson(json);
}

This refactor assumes some logical defaults, but please adjust based on your specific requirements.

khelo/lib/ui/flow/score_board/score_board_view_model.dart (1)

Line range hint 1542-1546: Ensure _matchSettingSubscription is properly canceled to avoid memory leaks

The _matchSettingSubscription is not canceled in the _cancelStreamSubscription method or during the disposal of the notifier. This could lead to potential memory leaks or unintended behavior.

Apply this diff to cancel the subscription:

 _cancelStreamSubscription() async {
   await _matchStreamSubscription?.cancel();
   await _ballScoreStreamSubscription?.cancel();
+  await _matchSettingSubscription?.cancel();
   await _matchStreamController.close();
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4d1c0c7 and 2b4ef1c.

📒 Files selected for processing (11)
  • data/lib/api/match/match_model.dart (2 hunks)
  • data/lib/api/match/match_model.freezed.dart (1 hunks)
  • data/lib/api/match/match_model.g.dart (1 hunks)
  • data/lib/service/match/match_service.dart (2 hunks)
  • data/lib/utils/constant/firestore_constant.dart (1 hunks)
  • khelo/assets/locales/app_en.arb (1 hunks)
  • khelo/lib/ui/flow/score_board/components/select_fielding_position_sheet.dart (1 hunks)
  • khelo/lib/ui/flow/score_board/components/select_player_sheet.dart (1 hunks)
  • khelo/lib/ui/flow/score_board/score_board_screen.dart (6 hunks)
  • khelo/lib/ui/flow/score_board/score_board_view_model.dart (10 hunks)
  • khelo/lib/ui/flow/score_board/score_board_view_model.freezed.dart (17 hunks)
🧰 Additional context used
🔇 Additional comments (14)
khelo/lib/ui/flow/score_board/components/select_fielding_position_sheet.dart (3)

94-94: LGTM: Improved clarity in toggle button title

The change from "not show for less run" to "show wheel for less run" (as indicated by the new localization key) improves clarity by using positive phrasing. The use of a localized string is also good for internationalization.


100-100: LGTM: Improved clarity in toggle button title

The change from "not show for dot ball" to "show wheel for dot ball" (as indicated by the new localization key) improves clarity by using positive phrasing. The use of a localized string is also good for internationalization.


94-100: Verify localization changes and consider user impact

The changes to both toggle button titles improve clarity and align with the PR objectives. They contribute to a better user experience by making the options more understandable.

Please ensure that the corresponding changes have been made in the localization files. Run the following script to check for the new localization keys:

Also, consider if these changes might affect user behavior or require updates to user documentation.

data/lib/api/match/match_model.dart (2)

65-81: LGTM: Well-structured MatchSetting class implementation.

The new MatchSetting class is well-implemented with the following positive aspects:

  1. Consistent use of @freezed annotation with other classes in the file.
  2. Clear boolean properties with default values for match configuration.
  3. Proper implementation of factory methods for JSON and Firestore serialization.

Good job on maintaining consistency with the existing codebase structure!


65-81: Verify the usage of MatchSetting class in the codebase.

The newly added MatchSetting class is not referenced or used within this file. To ensure its proper integration and usage:

  1. Verify that this class is being used in other parts of the codebase where match settings are relevant.
  2. Ensure that any existing match creation or update logic is updated to include these new settings.
  3. Check if the UI for creating or editing matches has been updated to allow users to configure these settings.

To help verify the integration, you can run the following script:

This script will help identify where the MatchSetting class is currently used and where it potentially should be integrated.

✅ Verification successful

Usage of MatchSetting class verified across the codebase.

The MatchSetting class is appropriately integrated and utilized in relevant parts of the codebase, including:

  • khelo/lib/ui/flow/score_board/score_board_view_model.dart
  • data/lib/service/match/match_service.dart
  • Generated files such as match_model.g.dart and match_model.freezed.dart
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of MatchSetting class in the codebase

# Search for MatchSetting usage
echo "Searching for MatchSetting usage:"
rg "MatchSetting" --type dart

# Search for potential places where MatchSetting should be used
echo "\nSearching for potential integration points:"
rg "createMatch|updateMatch|editMatch" --type dart

# Search for UI components that might need updating
echo "\nSearching for related UI components:"
rg "MatchForm|MatchSettings" --type dart

Length of output: 9615

data/lib/api/match/match_model.g.dart (1)

151-166: LGTM! Correct implementation of JSON serialization for MatchSettingImpl.

The newly added methods _$$MatchSettingImplFromJson and _$$MatchSettingImplToJson are correctly implemented for the MatchSettingImpl class. They follow the established patterns in the file:

  1. The FromJson method correctly handles default values for all three boolean properties.
  2. The ToJson method properly maps all properties to their corresponding JSON keys.
  3. The naming convention and structure are consistent with other generated code in the file.

This implementation ensures proper serialization and deserialization of the MatchSettingImpl class, maintaining consistency with the rest of the generated code.

data/lib/service/match/match_service.dart (1)

Line range hint 40-112: Overall, excellent additions to the MatchService class.

The new methods (_matchSettingDocument, streamMatchSetting, and updateMatchSetting) are well-implemented and integrate seamlessly with the existing MatchService class. They enhance the class's capabilities by providing functionality for managing match settings, including real-time updates and Firestore integration.

The consistent use of error handling and Firestore best practices across these new methods aligns well with the existing codebase. These additions will likely improve the overall functionality and maintainability of the match management system.

data/lib/api/match/match_model.freezed.dart (2)

Line range hint 1-986: Well-structured models using Freezed

The existing code in this file demonstrates a consistent and well-structured approach to defining data models using the Freezed package. The models (MatchModel, MatchTeamModel, MatchPlayer, etc.) are clearly defined with appropriate properties and serialization methods.

The use of Freezed for generating immutable classes, copyWith methods, and JSON serialization is a good practice that enhances code reliability and reduces boilerplate.

Also applies to: 1179-1947


Line range hint 1-1947: Overall good structure with minor improvements needed for the new class

This file demonstrates a well-organized approach to defining data models using the Freezed package. The addition of the MatchSetting class maintains consistency with the existing structure. However, minor adjustments to the new class, such as adopting Dart naming conventions and reconsidering default values, would further improve the overall quality of the code.

The existing models are well-defined and utilize Freezed effectively for immutability and serialization. This approach reduces boilerplate and enhances code reliability.

khelo/lib/ui/flow/score_board/score_board_screen.dart (2)

118-123: Code is well-structured and improves clarity

Using _getDefaultValue(state, option) enhances readability and centralizes the logic for determining default values for match options. This is a good practice.


131-142: Solid implementation for determining default match option values

The _getDefaultValue method effectively handles the default values for different MatchOption cases. This improves code maintainability by centralizing the logic.

khelo/lib/ui/flow/score_board/score_board_view_model.freezed.dart (1)

63-63: 'matchSetting' property added and correctly integrated into state management

The matchSetting property of type MatchSetting has been added to ScoreBoardViewState. It is properly integrated throughout the state management, including the copyWith methods, equality checks (operator ==), hashCode, and toString methods. This ensures that any state updates will accurately reflect changes to the matchSetting property.

Also applies to: 123-138, 192-346, 451-460, 508-735, 812-1139

khelo/lib/ui/flow/score_board/score_board_view_model.dart (2)

55-64: Initialization of _loadMatchSetting() method is appropriate

The _loadMatchSetting() method correctly checks for a null matchId, cancels any existing subscription, and sets up a new subscription to streamMatchSetting. Error handling with debugPrint provides useful logging without interrupting the app flow.


1502-1514: Asynchronous operation in onFieldingPositionSelected is correctly handled

The onFieldingPositionSelected method appropriately awaits the asynchronous _updateMatchSetting call before proceeding, ensuring that the state is updated reliably. The parameters for showForLessRun and showForDotBall are correctly used to update the match settings.

khelo/lib/ui/flow/score_board/score_board_screen.dart Outdated Show resolved Hide resolved
khelo/lib/ui/flow/score_board/score_board_view_model.dart Outdated Show resolved Hide resolved
khelo/lib/ui/flow/score_board/score_board_view_model.dart Outdated Show resolved Hide resolved
@canopas canopas deleted a comment from coderabbitai bot Oct 9, 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 (9)
khelo/lib/ui/flow/score_board/score_board_screen.dart (4)

131-142: Well-structured _getDefaultValue method

The new _getDefaultValue method effectively centralizes the logic for retrieving default values based on MatchOption. This improves code organization and makes it easier to manage default values.

Consider adding a // TODO: comment in the default case to remind developers to update this method when new MatchOptions are added in the future. This can help prevent potential bugs from forgetting to handle new options.

  switch (option) {
    case MatchOption.continueWithInjuredPlayer:
      return state.matchSetting.continue_with_injured_player;
    case MatchOption.showForLessRuns:
      return state.matchSetting.show_wagon_wheel_for_less_run;
    case MatchOption.showForDotBall:
      return state.matchSetting.show_wagon_wheel_for_dot_ball;
    default:
+     // TODO: Update this method when new MatchOptions are added
      return false;
  }

341-344: Consistent use of matchSetting in _observeShowSelectFieldingPositionSheet

The refactoring to use the matchSetting property improves consistency with the rest of the codebase. This change enhances maintainability by centralizing the access to match settings.

Note: There's a minor inconsistency in naming between showForLessRun here and showForLessRuns in the _getDefaultValue method. Consider standardizing this naming across the codebase for better clarity.

Also applies to: 351-354


365-367: Consistent use of matchSetting across multiple methods

The refactoring to use the matchSetting property in these methods improves consistency and aligns with the rest of the codebase. This change enhances maintainability by centralizing the access to match settings.

Consider refactoring the repeated code for accessing continue_with_injured_player into a separate method or computed property to reduce duplication. For example:

bool get continueWithInjuredPlayers => ref.read(
    scoreBoardStateProvider.select(
        (value) => value.matchSetting.continue_with_injured_player));

Then you can use this getter in all the methods, simplifying the code and making it easier to maintain.

Also applies to: 382-384, 401-403, 418-420


Line range hint 1-724: Overall improvement in state management and code structure

The changes in this file significantly improve the handling of match options and state management. The introduction of the _getDefaultValue method and the consistent use of the matchSetting property across various methods enhance code readability and maintainability.

These refactorings align well with Flutter best practices for state management and make the codebase more robust and easier to update in the future.

Consider further refactoring to reduce code duplication, particularly in accessing common settings like continue_with_injured_player. This could involve creating getter methods or computed properties for frequently accessed settings.

Overall, these changes represent a positive step towards a more maintainable and consistent codebase.

data/lib/api/user/user_models.freezed.dart (1)

Line range hint 1-852: Overall improvements in JSON handling for data models.

The changes made to both UserModel and ApiSession classes consistently enhance JSON serialization capabilities and provide better control over which properties are included in JSON operations. These modifications will likely improve data handling, especially in API communications and data persistence scenarios.

However, it's important to note that this is a generated file. Any changes should be made to the source file that generates this code, not directly to this file.

Ensure that the source file generating this code (likely named user_models.dart or similar) has been properly updated with the necessary annotations or configurations to produce these changes. This will maintain consistency and prevent loss of changes during code regeneration.

khelo/lib/ui/flow/score_board/score_board_view_model.dart (4)

55-64: LGTM: Well-implemented match setting loading method

The _loadMatchSetting method is well-structured and includes proper null checks, state updates, and error handling. It effectively sets up a subscription to stream match settings and updates the state accordingly.

A minor suggestion for improvement:
Consider using a logging library instead of debugPrint for more robust error logging in production environments.


1227-1243: LGTM: Well-implemented match option toggle method

The onToggleMatchOptionChange method is well-structured and correctly handles different match options. It appropriately updates the MatchSetting based on the provided option and boolean value.

A suggestion for improvement:
Consider using an early return for the default case to make the flow more explicit:

  switch (option) {
    case MatchOption.continueWithInjuredPlayer:
      setting = setting.copyWith(continue_with_injured_player: isTrue);
      break;
    case MatchOption.showForLessRuns:
      setting = setting.copyWith(show_wagon_wheel_for_less_run: isTrue);
      break;
    case MatchOption.showForDotBall:
      setting = setting.copyWith(show_wagon_wheel_for_dot_ball: isTrue);
      break;
    default:
-     return;
+     return; // Early return for unhandled cases
  }
+ _updateMatchSetting(setting);
- _updateMatchSetting(setting);

This change makes it clearer that the method returns early for unhandled cases and only calls _updateMatchSetting when a valid option is processed.


1245-1256: LGTM: Well-implemented match setting update method

The _updateMatchSetting method is well-structured with proper null checks and error handling. It correctly updates both the database and local state to ensure consistency.

A suggestion for improvement:
Consider adding a loading state while the update is in progress:

  Future<void> _updateMatchSetting(MatchSetting setting) async {
    final matchId = this.matchId ?? state.match?.id;
    if (matchId == null) return;
-   state = state.copyWith(actionError: null);
+   state = state.copyWith(actionError: null, isActionInProgress: true);
    try {
      await _matchService.updateMatchSetting(matchId, setting);
-     state = state.copyWith(matchSetting: setting);
+     state = state.copyWith(matchSetting: setting, isActionInProgress: false);
    } catch (e) {
-     state = state.copyWith(actionError: e);
+     state = state.copyWith(actionError: e, isActionInProgress: false);
      debugPrint(
          "ScoreBoardViewNotifier: Error while update match setting -> $e");
    }
  }

This change will provide better feedback to the user during the update process.


1505-1517: LGTM: Updated fielding position selection with match setting update

The changes in the onFieldingPositionSelected method correctly incorporate updating the match settings before handling the ball addition. This ensures that the latest settings are applied when processing the fielding position selection.

A suggestion for improvement:
Consider handling potential errors from _updateMatchSetting:

  Future<void> onFieldingPositionSelected(
    ScoreButton tapped,
    bool isLongTapped,
    FieldingPositionType position,
    bool showForLessRun,
    bool showForDotBall,
  ) async {
    final setting = state.matchSetting.copyWith(
      show_wagon_wheel_for_less_run: showForLessRun,
      show_wagon_wheel_for_dot_ball: showForDotBall,
    );
-   await _updateMatchSetting(setting);
+   try {
+     await _updateMatchSetting(setting);
+   } catch (e) {
+     // Handle error (e.g., show an error message to the user)
+     debugPrint("Error updating match setting: $e");
+     return; // Consider whether to proceed with ball handling if setting update fails
+   }
    state = state.copyWith(position: position);
    _handleAddingBall(tapped, isLongTapped);
  }

This change ensures that any errors during the match setting update are properly handled and logged.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2b4ef1c and b44bd26.

📒 Files selected for processing (8)
  • data/lib/api/ball_score/ball_score_model.freezed.dart (72 hunks)
  • data/lib/api/innings/inning_model.freezed.dart (5 hunks)
  • data/lib/api/match/match_model.freezed.dart (41 hunks)
  • data/lib/api/support/support_models.freezed.dart (11 hunks)
  • data/lib/api/team/team_model.freezed.dart (12 hunks)
  • data/lib/api/user/user_models.freezed.dart (12 hunks)
  • khelo/lib/ui/flow/score_board/score_board_screen.dart (6 hunks)
  • khelo/lib/ui/flow/score_board/score_board_view_model.dart (10 hunks)
🧰 Additional context used
🔇 Additional comments (47)
data/lib/api/innings/inning_model.freezed.dart (6)

32-34: LGTM: Addition of toJson() method

The addition of the toJson() method with its documentation comment is a good practice for JSON serialization. This change enhances the model's functionality by providing a clear way to convert the InningModel to a JSON map.


35-37: LGTM: Improved documentation and JSON key annotation for copyWith

The added documentation for the copyWith method enhances code readability by clearly explaining its purpose. The updated @JsonKey annotation is more explicit about excluding this method from JSON serialization and deserialization, which is appropriate for a utility method like copyWith.


69-70: LGTM: Added documentation for call method

The addition of documentation comments to the call method in the _$InningModelCopyWithImpl class improves code readability. This change is consistent with the documentation added to the copyWith method in the mixin, maintaining a uniform approach to code documentation.


259-259: LGTM: Updated JSON key annotation for hashCode

The @JsonKey annotation for the hashCode getter has been updated to be more explicit about excluding it from JSON serialization and deserialization. This change is consistent with the annotation update for the copyWith method and provides clearer intent in the generated code.


311-314: LGTM: Improved documentation and JSON key annotation for abstract copyWith

The changes to the copyWith getter in the _InningModel abstract class are consistent with earlier updates:

  1. The added documentation enhances code readability by clearly explaining the getter's purpose.
  2. The updated @JsonKey annotation explicitly excludes this getter from JSON serialization and deserialization.

These changes maintain consistency throughout the generated code and improve overall code quality.


Line range hint 1-314: Overall assessment: Improved code quality and consistency

The changes made to this generated file consistently enhance code quality through:

  1. Addition of the toJson() method for JSON serialization.
  2. Improved documentation for copyWith methods and getters.
  3. More explicit @JsonKey annotations for better control over JSON serialization.

These modifications improve code readability, maintainability, and provide clearer intent in the generated code. The changes are consistent throughout the file and align with best practices for Dart and JSON serialization.

data/lib/api/support/support_models.freezed.dart (5)

33-35: LGTM: Addition of toJson method

The addition of the toJson method to the AddSupportCaseRequest class is a good practice. It allows for easy serialization of the object to JSON format, which is often necessary for API communication or data storage.


38-38: Improved JSON serialization control

The update from @JsonKey(ignore: true) to @JsonKey(includeFromJson: false, includeToJson: false) for the copyWith methods is a good change. It provides more explicit control over JSON serialization and deserialization, ensuring that these methods are correctly excluded from both processes.

Also applies to: 252-252, 314-314, 328-328, 483-483, 509-509


36-37: Improved code documentation

The addition of documentation comments for the copyWith methods in both AddSupportCaseRequest and Attachment classes is a great improvement. These comments clearly explain the purpose of the method, enhancing code readability and maintainability.

Also applies to: 70-71, 144-145, 264-265, 311-312, 326-327, 356-357, 410-411, 481-482, 506-507


Line range hint 1-511: Consistent changes across classes

The changes have been consistently applied to both the AddSupportCaseRequest and Attachment classes. This includes the updated @JsonKey annotations and the addition of documentation comments for the copyWith methods. This consistency helps maintain a clean and predictable API structure.


Line range hint 1-511: Overall improvements to generated code

The changes made to this generated file (support_models.freezed.dart) are well-structured and consistent. Key improvements include:

  1. Addition of the toJson method to AddSupportCaseRequest for JSON serialization.
  2. Updated @JsonKey annotations for better control over JSON serialization and deserialization.
  3. Added documentation comments for copyWith methods, enhancing code readability.

These changes improve the overall functionality and maintainability of the code while respecting the constraints of working with generated files. Great job on making these enhancements!

data/lib/api/team/team_model.freezed.dart (6)

36-41: Improved serialization and documentation for TeamModel

The changes in this segment enhance the TeamModel class in several ways:

  1. The new toJson() method facilitates JSON serialization, which is crucial for data persistence and API communication.
  2. The added documentation for the copyWith method improves code readability and maintainability.
  3. The updated @JsonKey annotation provides finer control over JSON serialization, explicitly excluding the copyWith method from both serialization and deserialization processes.

These improvements align with best practices for data modeling and serialization in Dart.


74-75: Enhanced documentation for TeamModelCopyWith

The addition of documentation to the call method of TeamModelCopyWith is a positive change:

  1. It improves code readability and maintainability.
  2. It provides clear information about the purpose and behavior of the copyWith functionality.
  3. This change is consistent with the documentation added to the TeamModel class, maintaining a uniform approach to code documentation.

This improvement contributes to better overall code quality and developer experience.


Line range hint 302-319: Refined JSON handling and documentation in TeamModel implementation

The changes in this segment further enhance the TeamModel implementation:

  1. The updated @JsonKey annotation for hashCode and copyWith ensures these elements are excluded from JSON serialization and deserialization, which is appropriate as they are not part of the data model.
  2. The added documentation for the copyWith getter improves code readability and maintains consistency with earlier documentation changes.

These refinements contribute to a more robust and well-documented data model, which aligns with best practices in Dart development.


392-397: Consistent improvements in TeamPlayer class

The changes to the TeamPlayer class mirror those made to TeamModel, maintaining consistency across the codebase:

  1. The addition of the toJson() method enhances serialization capabilities for TeamPlayer objects.
  2. The new documentation for the copyWith method improves code readability and understanding.
  3. The updated @JsonKey annotation provides precise control over JSON serialization, excluding the copyWith method from both serialization and deserialization.

These consistent improvements across related classes contribute to a more maintainable and well-structured codebase.


Line range hint 487-591: Consistent refinements in TeamPlayer implementation

The changes in the TeamPlayer implementation maintain consistency with the TeamModel improvements:

  1. Added documentation for the call method of TeamPlayerCopyWith enhances code clarity.
  2. Updated @JsonKey annotations for hashCode and copyWith ensure proper JSON handling.
  3. New documentation for the copyWith getter improves code readability.

These consistent refinements across related classes contribute to a more cohesive, maintainable, and well-documented codebase. The uniformity in these changes demonstrates a systematic approach to code improvement.


Line range hint 1-591: Summary: Comprehensive improvements to TeamModel and TeamPlayer

The changes in this file represent a systematic and consistent set of improvements to both the TeamModel and TeamPlayer classes:

  1. Enhanced JSON serialization with new toJson() methods.
  2. Improved documentation for copyWith methods and getters.
  3. Refined @JsonKey annotations for better control over JSON serialization.

These changes collectively contribute to:

  • Improved data persistence and API communication capabilities.
  • Enhanced code readability and maintainability.
  • More precise control over JSON handling.

The consistency of these improvements across related classes demonstrates a thoughtful approach to code refinement, resulting in a more robust and developer-friendly codebase.

khelo/lib/ui/flow/score_board/score_board_screen.dart (1)

118-123: Improved code structure in _moreOptionButton

The refactoring of the defaultEnabled logic into a separate _getDefaultValue method enhances code readability and maintainability. This change makes it easier to update the default values for different match options in the future.

data/lib/api/user/user_models.freezed.dart (4)

40-42: Addition of toJson() method enhances serialization capabilities.

The new toJson() method allows for easy serialization of UserModel instances to JSON format, which is crucial for data persistence and API communication.


45-45: Modification of JSON key annotations improves control over serialization.

The @JsonKey(includeFromJson: false, includeToJson: false) annotation on copyWith, hashCode, and copyWith getter methods ensures these are excluded from JSON serialization and deserialization. This is a good practice as these methods are typically not needed in JSON representations of the model.

Also applies to: 399-399, 420-422, 495-495


517-519: Addition of toJson() method to ApiSession class.

Similar to the UserModel, the new toJson() method in ApiSession allows for easy serialization to JSON format, maintaining consistency across model classes.


522-522: Consistent JSON key annotations applied to ApiSession class.

The @JsonKey(includeFromJson: false, includeToJson: false) annotations have been consistently applied to the copyWith, hashCode, and copyWith getter methods in the ApiSession class, mirroring the changes in UserModel. This ensures uniform behavior across model classes during JSON operations.

Also applies to: 778-778, 793-795, 850-850

khelo/lib/ui/flow/score_board/score_board_view_model.dart (5)

38-38: LGTM: New stream subscription for MatchSetting

The addition of _matchSettingSubscription is a good practice for managing the subscription to match settings. This will allow for proper handling and disposal of the subscription when needed.


52-53: LGTM: Added match setting loading

The addition of _loadMatchSetting() in the setData method is a good way to initialize the match settings when setting up the data. This separation of concerns improves the code organization.


543-544: LGTM: Updated fielding position sheet logic

The changes in the _showFieldingPositionSheet method correctly incorporate the new matchSetting state to determine when to show the fielding position sheet. This update aligns well with the new match setting functionality.


1602-1602: LGTM: Added match setting to ScoreBoardViewState

The addition of the matchSetting field to the ScoreBoardViewState class with a default value is a good practice. It ensures that the state always has a valid MatchSetting object, which aligns well with the new match setting functionality.


Line range hint 1-1702: Overall assessment: Well-implemented match setting functionality

The changes in this file successfully introduce and integrate match setting functionality into the score board view model. The new methods for loading, updating, and using match settings are well-structured and properly integrated with the existing code. The changes maintain consistency with the current coding style and follow good practices for state management and error handling.

Some minor suggestions for improvement have been made, primarily focusing on enhanced error handling and slight adjustments to code structure. These suggestions, if implemented, would further improve the robustness and clarity of the code.

Overall, the changes represent a solid enhancement to the score board functionality, allowing for more flexible and customizable match settings.

data/lib/api/match/match_model.freezed.dart (7)

60-65: LGTM: Improved serialization and immutability for MatchModel

The addition of the toJson() method and the updated copyWith method enhance the MatchModel class. These changes improve serialization capabilities and reinforce the immutability pattern, which are both good practices in Dart.


126-127: LGTM: Improved documentation for MatchModel copyWith method

The added documentation for the copyWith method enhances code readability and maintainability. This is a good practice that helps developers understand the purpose and usage of the method.


1004-1208: LGTM: New MatchSetting class added with proper structure

The new MatchSetting class is well-implemented, following Freezed package conventions for immutability and JSON serialization. This addition enhances the match model by allowing configuration of specific match settings.

However, please verify if the default true values for all boolean properties are intentional and align with the expected default behavior:

continue_with_injured_player = true,
show_wagon_wheel_for_less_run = true,
show_wagon_wheel_for_dot_ball = true

Could you confirm if these default values are correct according to the business requirements?


1226-1231: LGTM: Enhanced MatchTeamModel with improved serialization and immutability

The updates to the toJson() and copyWith methods in the MatchTeamModel class align with the changes made to the MatchModel class. These modifications improve serialization capabilities and reinforce the immutability pattern, which are good practices in Dart.


1550-1555: LGTM: Improved MatchPlayer with better serialization and immutability

The updates to the toJson() and copyWith methods in the MatchPlayer class are consistent with the changes made to other classes in this file. These modifications enhance serialization capabilities and reinforce the immutability pattern, maintaining good coding practices throughout the model classes.


1793-1798: LGTM: Enhanced PlayerPerformance with improved serialization and immutability

The updates to the toJson() and copyWith methods in the PlayerPerformance class align with the changes made to other classes in this file. These modifications improve serialization capabilities and reinforce the immutability pattern, maintaining consistency across all model classes.


1982-1987: LGTM: Consistent improvements across all model classes

The updates to the toJson() and copyWith methods in the RevisedTarget, TeamMatchStatus, and TeamStat classes are consistent with the changes made to other classes in this file. These modifications enhance serialization capabilities and reinforce the immutability pattern across all model classes.

Overall, this file update demonstrates a systematic improvement in the following areas:

  1. Enhanced serialization with the addition of toJson() methods
  2. Improved immutability through updated copyWith methods
  3. Better documentation for some methods
  4. Introduction of the new MatchSetting class for additional configuration options

These changes contribute to more robust and maintainable code throughout the match model classes.

Also applies to: 2196-2198, 2367-2369

data/lib/api/ball_score/ball_score_model.freezed.dart (13)

93-94: Duplicate issue: Unnecessary @JsonKey on copyWith method

The @JsonKey annotation on the copyWith method is also present here. Please remove it as previously suggested.


237-238: Duplicate issue: Unnecessary @JsonKey on copyWith method

The same issue with the @JsonKey annotation occurs in this section for the copyWith method. Refer to the earlier comment for the resolution.


481-483: Duplicate issue: Unnecessary @JsonKey on copyWith method


563-567: Duplicate issue: Unnecessary @JsonKey on copyWith method


810-812: Avoid using @JsonKey annotation on methods in BattingStat


1137-1139: Avoid using @JsonKey annotation on methods in BowlingStat


1468-1470: Avoid using @JsonKey annotation on methods in FieldingStat


1643-1645: Avoid using @JsonKey annotation on methods in OverStatModel


1829-1831: Avoid using @JsonKey annotation on methods in TeamRunStat


3397-3399: Avoid using @JsonKey annotation on methods in ExtraSummary


1826-1828: Ensure proper implementation of toJson() in TeamRunStat

Use the script:

#!/bin/bash
# Description: Check for `toJson()` method implementation in `_TeamRunStat`.

ast-grep --lang dart --pattern $'''
class _\$_TeamRunStat implements _TeamRunStat {
  Map<String, dynamic> toJson() {
    $$$
  }
}
'''

1640-1642: Ensure proper implementation of toJson() in OverStatModel

The toJson() method is declared but throws _privateConstructorUsedError. Verify that the concrete class _OverStatModel implements toJson() correctly.

Use the following script:

#!/bin/bash
# Description: Check for `toJson()` method implementation in `_OverStatModel`.

ast-grep --lang dart --pattern $'''
class _\$_OverStatModel implements _OverStatModel {
  Map<String, dynamic> toJson() {
    $$$
  }
}
'''

456-456: ⚠️ Potential issue

Duplicate issue: Unnecessary @JsonKey on hashCode

The @JsonKey annotation is applied to the hashCode getter. Similar to methods, @JsonKey should not be used on getters like hashCode. This could cause issues during serialization.

Apply this diff to remove the @JsonKey annotation:

- @JsonKey(includeFromJson: false, includeToJson: false)
  @override
  int get hashCode => Object.hashAll([...]);

Likely invalid or redundant comment.

@canopas canopas deleted a comment from coderabbitai bot Oct 10, 2024
@canopas canopas deleted a comment from coderabbitai bot Oct 10, 2024
@canopas canopas deleted a comment from coderabbitai bot Oct 10, 2024
Copy link
Collaborator

@cp-mayank cp-mayank left a comment

Choose a reason for hiding this comment

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

If i try to update setting value then i am getting consol error Unhandled Exception: Bad state: Tried to use ScoreBoardViewNotifier after dispose was called.

data/lib/utils/constant/firestore_constant.dart Outdated Show resolved Hide resolved
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 (3)
khelo/lib/ui/flow/score_board/score_board_screen.dart (3)

112-126: LGTM! Consider a minor naming improvement.

The changes to the _moreOptionButton method improve code readability and maintainability. The use of _getDefaultValue centralizes the logic for determining default values, and the onToggleMatchOptionChange method provides a more specific callback for toggle buttons.

Consider renaming the result parameter in the onTap callback to something more descriptive, such as isEnabled or toggleState, to better reflect its purpose:

 onTap: (result) => notifier
-    .onToggleMatchOptionChange(result, option),
+    .onToggleMatchOptionChange(isEnabled, option),

130-141: LGTM! Consider future-proofing the default case.

The addition of the _getDefaultValue method improves code organization by centralizing the logic for determining default values for match options. This enhances readability and maintainability.

To improve future maintainability, consider throwing an exception in the default case instead of returning a default value. This will help catch any newly added MatchOption that hasn't been handled:

 switch (option) {
   case MatchOption.continueWithInjuredPlayer:
     return state.matchSetting.continue_with_injured_player;
   case MatchOption.showForLessRuns:
     return state.matchSetting.show_wagon_wheel_for_less_run;
   case MatchOption.showForDotBall:
     return state.matchSetting.show_wagon_wheel_for_dot_ball;
   default:
-    return false;
+    throw UnimplementedError('Default value not defined for ${option.name}');
 }

This change will make it easier to identify and handle any new MatchOption cases that might be added in the future.


340-343: LGTM! Consider refactoring to reduce duplication.

The changes in the _observe methods to use matchSetting instead of individual state properties improve consistency and centralize access to match settings. This is good for maintainability and readability.

To further improve the code, consider refactoring the repeated access to matchSetting into a single method or getter. This would reduce code duplication and make future changes easier. For example:

MatchSetting get _matchSetting => ref.read(
  scoreBoardStateProvider.select((value) => value.matchSetting)
);

Then, you can use this getter in your _observe methods:

final continueWithInjuredPlayers = _matchSetting.continue_with_injured_player;
final showForLessRun = _matchSetting.show_wagon_wheel_for_less_run;
final showForDotBall = _matchSetting.show_wagon_wheel_for_dot_ball;

This refactoring would make the code more DRY and easier to maintain.

Also applies to: 364-366, 381-383, 400-402, 417-419

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b44bd26 and c078bfe.

📒 Files selected for processing (3)
  • data/lib/service/match/match_service.dart (2 hunks)
  • data/lib/utils/constant/firestore_constant.dart (1 hunks)
  • khelo/lib/ui/flow/score_board/score_board_screen.dart (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • data/lib/service/match/match_service.dart
  • data/lib/utils/constant/firestore_constant.dart
🧰 Additional context used

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 (5)
khelo/lib/ui/flow/score_board/score_board_view_model.dart (5)

55-63: LGTM: Well-implemented match setting loading

The _loadMatchSetting method is well-structured:

  • It checks for a valid matchId before subscribing.
  • It correctly updates the state with new settings or retains current settings.
  • Error handling is properly implemented.

Consider using a more specific error message in the debugPrint statement. For example:

debugPrint("ScoreBoardViewNotifier: Error while loading match setting: $e");

This will make debugging easier in the future.


1226-1242: LGTM: Well-implemented match option toggle handling

The onToggleMatchOptionChange method is well-structured:

  • It correctly handles different match options using a switch statement.
  • It updates the appropriate settings based on the toggled option.
  • It calls _updateMatchSetting to persist the changes.

Consider using Dart's enhanced switch statements for a more concise implementation:

void onToggleMatchOptionChange(bool isTrue, MatchOption option) {
  final setting = switch (option) {
    MatchOption.continueWithInjuredPlayer => state.matchSetting.copyWith(continue_with_injured_player: isTrue),
    MatchOption.showForLessRuns => state.matchSetting.copyWith(show_wagon_wheel_for_less_run: isTrue),
    MatchOption.showForDotBall => state.matchSetting.copyWith(show_wagon_wheel_for_dot_ball: isTrue),
    _ => state.matchSetting,
  };
  if (setting != state.matchSetting) {
    _updateMatchSetting(setting);
  }
}

This approach reduces repetition and makes the code more maintainable.


1244-1255: LGTM: Well-implemented match setting update

The _updateMatchSetting method is well-structured:

  • It checks for a valid matchId before proceeding.
  • It updates both the database and the local state, ensuring consistency.
  • Error handling is properly implemented.

Consider using a more descriptive error message in the debugPrint statement. For example:

debugPrint("ScoreBoardViewNotifier: Failed to update match setting. Error: $e");

This will provide more context when debugging.


1504-1516: LGTM: Updated fielding position selection with setting updates

The onFieldingPositionSelected method has been correctly updated to:

  • Update the match settings before handling the ball addition.
  • Use the new _updateMatchSetting method to persist the changes.

This ensures that the latest settings are applied before processing the ball.

Consider making this method async and using await for the _updateMatchSetting call:

Future<void> onFieldingPositionSelected(
  ScoreButton tapped,
  bool isLongTapped,
  FieldingPositionType position,
  bool showForLessRun,
  bool showForDotBall,
) async {
  final setting = state.matchSetting.copyWith(
    show_wagon_wheel_for_less_run: showForLessRun,
    show_wagon_wheel_for_dot_ball: showForDotBall,
  );
  await _updateMatchSetting(setting);
  state = state.copyWith(position: position);
  _handleAddingBall(tapped, isLongTapped);
}

This will ensure that the settings are fully updated before proceeding with the ball handling.


Line range hint 1-1703: Overall assessment: Well-implemented match settings functionality

The changes in this file successfully introduce and manage match settings throughout the ScoreBoardViewNotifier class. Key points:

  1. A new stream subscription for match settings has been added.
  2. Methods for loading and updating match settings have been implemented with proper error handling.
  3. Existing methods have been updated to consider these new settings in their logic.
  4. The changes are consistent and maintain the overall structure and style of the code.

These modifications enhance the functionality of the scoreboard, allowing for more flexible and customizable match management.

Consider breaking down this large file into smaller, more focused components in the future. This could improve maintainability and make it easier to test individual pieces of functionality.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c078bfe and c16bea4.

📒 Files selected for processing (1)
  • khelo/lib/ui/flow/score_board/score_board_view_model.dart (10 hunks)
🧰 Additional context used
🔇 Additional comments (4)
khelo/lib/ui/flow/score_board/score_board_view_model.dart (4)

38-38: LGTM: New stream subscription for MatchSetting

The addition of _matchSettingSubscription is a good practice for managing the stream of match settings. This allows for proper handling and disposal of the subscription.


52-53: LGTM: Added match setting loading

The addition of _loadMatchSetting() call in the setData method ensures that match settings are loaded after the match and innings data. This is a logical sequence of operations.


805-813: LGTM: Updated all-out logic with injured player consideration

The _isAllOut method has been correctly updated to consider the continue_with_injured_player setting. This change ensures that the all-out condition is accurately determined based on whether injured players are allowed to continue.


542-543: LGTM: Updated fielding position sheet logic

The _showFieldingPositionSheet method has been correctly updated to use the new match settings. It now considers show_wagon_wheel_for_dot_ball and show_wagon_wheel_for_less_run settings to determine when to display the fielding position sheet.

@cp-sidhdhi-p cp-sidhdhi-p merged commit 5c90edb into main Oct 11, 2024
2 checks passed
@cp-sidhdhi-p cp-sidhdhi-p deleted the sidhdhi/add-match-setting-in-collection branch October 11, 2024 10:23
This was referenced Oct 14, 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