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

Feature: Fetch recommended acts of service (kids-1508) #1146

Merged
merged 3 commits into from
Oct 9, 2024

Conversation

Daniela510
Copy link
Contributor

@Daniela510 Daniela510 commented Oct 9, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new RecommendationTypes enum to categorize recommendations.
    • Added a method to fetch recommendations for acts of service.
  • Improvements

    • Updated the Organisation class to include a new type field for better categorization.
    • Enhanced recommendation fetching logic to support both organizations and acts.
  • Bug Fixes

    • Corrected repository method calls to ensure accurate recommendations are fetched.
  • Documentation

    • Updated method signatures for clarity and consistency.

@Daniela510 Daniela510 requested a review from a team as a code owner October 9, 2024 10:31
Copy link
Contributor

coderabbitai bot commented Oct 9, 2024

Walkthrough

The changes introduced in this pull request involve significant modifications to the Organisation class, which now includes a new type field of the RecommendationTypes enum. The GratefulCubit class updates its method for fetching recommendations, and the GratefulRecommendationsRepository interface has been renamed and expanded. Additionally, a new method for handling recommendations related to acts of service has been added. The FamilyAPIService class has also been updated with a new method to fetch recommendations for acts of service.

Changes

File Path Change Summary
lib/features/family/features/recommendation/organisations/models/organisation.dart Updated Organisation class to replace collectGroupId with type, modified constructor and methods.
lib/features/family/features/reflect/data/recommendation_types.dart Introduced new enum RecommendationTypes with constants and a static method for initialization.
lib/features/family/features/reflect/bloc/grateful_cubit.dart Changed repository method in _fetchRecommendationsForCurrentProfile to getOrganisationsRecommendations.
lib/features/family/features/reflect/domain/grateful_recommendations_repository.dart Renamed method from getGratefulRecommendations to getOrganisationsRecommendations, added getActsRecommendations.
lib/features/family/features/reflect/domain/grateful_recommendations_repository_impl.dart Updated repository implementation to manage both organisations and acts recommendations.
lib/features/family/network/api_service.dart Added new method getRecommendedAOS to handle POST requests for acts of service recommendations.

Possibly related PRs

Suggested reviewers

  • TammiLion

🐰 In fields where bunnies play,
New types of joy are here today.
With organisations bright and new,
Recommendations come in view.
Let’s hop along and spread the cheer,
For acts of service, we hold dear! 🌼


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.

@github-actions github-actions bot added the enhancement New feature or request label Oct 9, 2024
Copy link
Contributor

@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: 8

🧹 Outside diff range and nitpick comments (4)
lib/features/family/features/reflect/data/recommendation_types.dart (1)

1-4: Consider consistency in enum value strings

The enum values and their associated strings are consistent, except for actOfService. Its string value 'actsofservice' differs from the enum name.

Consider changing it to maintain consistency:

-  actOfService('actsofservice');
+  actOfService('actofservice');

Alternatively, if the inconsistent string is intentional (e.g., to match an external API), consider adding a comment explaining the reason for the difference.

lib/features/family/features/reflect/bloc/grateful_cubit.dart (1)

111-116: Improved formatting, but consider enhancing null safety.

The changes improve the readability of the RecommendationsUIModel constructor. However, there's a potential null safety issue on line 115.

Consider using elementAtOrNull for consistency and to avoid potential exceptions:

-            name: _profiles.elementAtOrNull(_currentProfileIndex)?.firstName ??
-                '',
-            category: _profiles.elementAt(_currentProfileIndex).gratitude),
+            name: _profiles.elementAtOrNull(_currentProfileIndex)?.firstName ?? '',
+            category: _profiles.elementAtOrNull(_currentProfileIndex)?.gratitude),

This change ensures that both name and category are handled consistently with regard to null safety.

lib/features/family/network/api_service.dart (1)

157-177: Approve with suggestions for improvement

The getRecommendedAOS method is well-implemented and consistent with the existing code structure. However, consider the following suggestions for improvement:

  1. Add a comment or rename the method to clarify what "AOS" stands for, improving code readability.
  2. Consider adding logging statements for easier debugging, especially for API calls.
  3. Implement explicit network error handling to differentiate between server errors and network issues.

Here's an example of how you might implement these suggestions:

/// Fetches recommended Acts of Service (AOS) based on the provided criteria
Future<List<dynamic>> getRecommendedActsOfService(
  Map<String, dynamic> body,
) async {
  const endpoint = '/givtservice/v1/game/aos-recommendation';
  final url = Uri.https(_apiURL, endpoint);

  try {
    final response = await client.post(
      url,
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode(body),
    );

    if (response.statusCode >= 400) {
      throw GivtServerFailure(
        statusCode: response.statusCode,
        body: jsonDecode(response.body) as Map<String, dynamic>,
      );
    }

    final decodedBody = json.decode(response.body) as Map<String, dynamic>;
    return decodedBody['items'] as List<dynamic>;
  } catch (e) {
    // Log the error for debugging
    print('Error fetching recommended acts of service: $e');
    if (e is SocketException) {
      throw NetworkError('Failed to connect to the server');
    }
    rethrow;
  }
}

Note: You'll need to define a NetworkError class or use an appropriate existing error class for network-related errors.

lib/features/family/features/reflect/domain/grateful_recommendations_repository_impl.dart (1)

Line range hint 46-57: Optimize the sortRecommendationsByChurchTag method

The current sorting implementation can be simplified for better readability. You can use the compareTo method for a more concise comparison.

Consider refactoring the sorting logic:

organisations.sort((a, b) {
  final aHasChurchTag = a.tags.any((tag) => tag.key == "CHURCH");
  final bHasChurchTag = b.tags.any((tag) => tag.key == "CHURCH");
  return bHasChurchTag.compareTo(aHasChurchTag);
});

This refactor makes the sorting function cleaner and easier to understand.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 77541c0 and 27bd44d.

📒 Files selected for processing (6)
  • lib/features/family/features/recommendation/organisations/models/organisation.dart (5 hunks)
  • lib/features/family/features/reflect/bloc/grateful_cubit.dart (2 hunks)
  • lib/features/family/features/reflect/data/recommendation_types.dart (1 hunks)
  • lib/features/family/features/reflect/domain/grateful_recommendations_repository.dart (1 hunks)
  • lib/features/family/features/reflect/domain/grateful_recommendations_repository_impl.dart (3 hunks)
  • lib/features/family/network/api_service.dart (1 hunks)
🧰 Additional context used
🔇 Additional comments (6)
lib/features/family/features/reflect/data/recommendation_types.dart (1)

6-8: LGTM: Well-structured enum implementation

The constructor and value field are well-implemented. This structure supports the fromString method and allows for easy extension if needed in the future.

lib/features/family/features/reflect/domain/grateful_recommendations_repository.dart (1)

9-11: LGTM: Method renaming improves clarity

The renaming of getGratefulRecommendations to getOrganisationsRecommendations is a good change. It makes the method's purpose more explicit and aligns well with clean code principles.

To ensure this change is consistently applied throughout the codebase, please run the following script:

✅ Verification successful

Verified: Method renaming successfully applied

No remaining references to getGratefulRecommendations found. All usages are updated to getOrganisationsRecommendations, ensuring consistency across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to the old method name

# Test: Search for the old method name. Expect: No results.
rg --type dart 'getGratefulRecommendations'

# Test: Search for the new method name. Expect: At least one result (this file).
rg --type dart 'getOrganisationsRecommendations'

Length of output: 4871

lib/features/family/features/reflect/bloc/grateful_cubit.dart (2)

Line range hint 1-214: Overall, the changes look good but require some follow-up.

The modifications to GratefulCubit align well with the PR objectives of fetching recommended acts of service. The code changes are minimal and focused, primarily updating the method for fetching recommendations and improving code formatting.

To ensure a smooth integration of these changes:

  1. Implement the suggested null safety improvement in the _emitData method.
  2. Run the provided verification script to check for any potential impacts on other parts of the codebase.
  3. Review and update any affected UI components or tests that may rely on the structure of the fetched recommendations.

Great job on keeping the changes focused and maintaining the overall structure of the class!


131-131: Verify impact of changed recommendation retrieval method.

The change from getGratefulRecommendations to getOrganisationsRecommendations aligns with the PR objectives. However, this modification might affect the structure or type of recommendations being fetched.

Please ensure that:

  1. The Organisation model can handle the new recommendation type.
  2. Any UI components displaying these recommendations are updated accordingly.

Run the following script to verify the usage of the new method and potential impacts:

✅ Verification successful

Recommendation retrieval method change verified successfully.

The switch from getGratefulRecommendations to getOrganisationsRecommendations has been properly implemented. The Organisation model has been updated to handle the new recommendation types, and no residual usage of the old method was found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of getOrganisationsRecommendations and potential impacts

# Test 1: Check for any remaining usage of the old method
echo "Checking for any remaining usage of getGratefulRecommendations:"
rg "getGratefulRecommendations" --type dart

# Test 2: Check for usage of getOrganisationsRecommendations in other files
echo "Checking usage of getOrganisationsRecommendations in other files:"
rg "getOrganisationsRecommendations" --type dart

# Test 3: Check for any TODOs or FIXMEs related to recommendations
echo "Checking for TODOs or FIXMEs related to recommendations:"
rg "TODO|FIXME" --type dart | rg -i "recommend"

# Test 4: Check Organisation model for any recent changes
echo "Checking Organisation model for recent changes:"
git log -p -- "**/organisation.dart"

Length of output: 23112

lib/features/family/features/recommendation/organisations/models/organisation.dart (2)

57-57: Proper inclusion of type in equality, copying, and serialization

The type field has been added to:

  • Line 57: The props list for equality checks.
  • Line 68 & 81: The copyWith method.
  • Line 98: The toJson serialization method.

This is appropriate and ensures that type is considered in object comparisons, can be copied with modifications, and is included in JSON representations.

Also applies to: 81-81, 98-98


5-5: Verify the imported module path

The import statement at line 5:

import 'package:givt_app/features/family/features/reflect/data/recommendation_types.dart';

Please verify that the path to recommendation_types.dart is correct and that the file exists at this location. This ensures that there are no import errors during compilation.

You can run the following script to check if recommendation_types.dart exists in the specified path:

✅ Verification successful

Import path verified successfully

The file lib/features/family/features/reflect/data/recommendation_types.dart exists at the specified location. The import statement is correct and should not cause any compilation issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for the existence of 'recommendation_types.dart' in the project
fd recommendation_types.dart

Length of output: 98

Copy link
Contributor

@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 (1)
lib/features/family/features/reflect/domain/grateful_recommendations_repository_impl.dart (1)

14-15: Consider initializing recommendation caches lazily

The _organisationRecommendations and _actsRecommendations maps are initialized eagerly. If these caches are not always utilized, consider initializing them lazily to optimize memory usage.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 27bd44d and cba67a1.

📒 Files selected for processing (2)
  • lib/features/family/features/reflect/data/recommendation_types.dart (1 hunks)
  • lib/features/family/features/reflect/domain/grateful_recommendations_repository_impl.dart (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/features/family/features/reflect/data/recommendation_types.dart
🧰 Additional context used
📓 Learnings (1)
lib/features/family/features/reflect/domain/grateful_recommendations_repository_impl.dart (1)
Learnt from: Daniela510
PR: givtnl/givt-app#1146
File: lib/features/family/features/reflect/domain/grateful_recommendations_repository_impl.dart:79-92
Timestamp: 2024-10-09T11:09:27.326Z
Learning: In the `_getActsForProfile` method in `lib/features/family/features/reflect/domain/grateful_recommendations_repository_impl.dart`, the `interests` variable is guaranteed to be non-null.
🔇 Additional comments (2)
lib/features/family/features/reflect/domain/grateful_recommendations_repository_impl.dart (2)

116-135: Ensure methods are declared in the interface

The methods getOrganisationsRecommendations and getActsRecommendations are implemented but need to be declared in the GratefulRecommendationsRepository interface to fulfill the contract.

Run the following script to verify that both methods are declared in the interface:

This will confirm whether the interface includes the new method signatures.

✅ Verification successful

Methods correctly declared in the GratefulRecommendationsRepository interface.

The verification confirms that both getOrganisationsRecommendations and getActsRecommendations are properly declared in the GratefulRecommendationsRepository interface.

  • getOrganisationsRecommendations found in grateful_recommendations_repository.dart
  • getActsRecommendations found in grateful_recommendations_repository.dart
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the interface declares the required methods.

# Test: Search for method declarations in the interface file.
# Expect: Both methods should be declared in GratefulRecommendationsRepository.

rg --type dart 'abstract class GratefulRecommendationsRepository' -A 15 -g '**/grateful_recommendations_repository.dart' | rg 'Future<List<Organisation>> getOrganisationsRecommendations\('

rg --type dart 'abstract class GratefulRecommendationsRepository' -A 15 -g '**/grateful_recommendations_repository.dart' | rg 'Future<List<Organisation>> getActsRecommendations\('

Length of output: 657


89-95: 🛠️ Refactor suggestion

Remove unnecessary null checks on interests

Based on the retrieved learning, the interests variable in _getActsForProfile is guaranteed to be non-null. The use of the null-aware operator ?. is therefore unnecessary and can be removed to simplify the code.

Applying this change simplifies the code:

final interests = profile.gratitude?.tags;
final response = await _familyApiService.getRecommendedAOS(
  {
    'pageSize': 10,
-   'tags': interests?.map((tag) => tag.key).toList(),
+   'tags': interests.map((tag) => tag.key).toList(),
    'includePreferredChurch': true,
  },
);

Learnings applied from previous interactions regarding the non-null guarantee of interests.

⛔ Skipped due to learnings
Learnt from: Daniela510
PR: givtnl/givt-app#1146
File: lib/features/family/features/reflect/domain/grateful_recommendations_repository_impl.dart:79-92
Timestamp: 2024-10-09T11:09:27.326Z
Learning: In the `_getActsForProfile` method in `lib/features/family/features/reflect/domain/grateful_recommendations_repository_impl.dart`, the `interests` variable is guaranteed to be non-null.

@Daniela510 Daniela510 merged commit acb8ad5 into develop Oct 9, 2024
1 check passed
@Daniela510 Daniela510 deleted the feat/kids-1508-fetch-acts-recs branch October 9, 2024 12:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants