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

Refactor the flow for deleting the group for admin. #132

Merged
merged 3 commits into from
Dec 16, 2024

Conversation

cp-sneh-s
Copy link
Collaborator

@cp-sneh-s cp-sneh-s commented Dec 12, 2024

Changelog

  • Add functionality to change admin before admin wants to leave the group

Breaking Changes

  • If admin leave the group then it was deleting the data of that group even if members were available.

New Features

  • ChangeAdminScreen :- He before leaving the group admin can change the group admin.
  • SpaceProfileScreen :- Add a icon to change the group admin.
  • When admin tries o leave the group if admin has not make any other member the group admin then it will open dialog for change the admin on click of leave group button.
Screen_recording_20241212_151114.mp4

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new screen for changing the admin of a space.
    • Added a dropdown menu in the Space Profile for admin changes, visible when there are multiple members.
    • Implemented a dialog for confirming admin changes with appropriate actions.
    • Enhanced navigation capabilities for accessing the Change Admin screen.
    • Added support for JSON serialization with Gson.
    • New string resources added to improve the user interface for group administration.
  • Bug Fixes

    • Enhanced error handling and loading states for admin change functionalities.
  • Tests

    • Adjusted visibility in test cases to improve encapsulation.

These changes enhance user experience by streamlining the admin management process within the application.

Copy link

coderabbitai bot commented Dec 12, 2024

Walkthrough

The pull request introduces a new dependency on Gson for JSON serialization and deserialization in the build.gradle.kts file. It adds a new navigation route for changing the admin of a space, implemented in MainActivity.kt, and introduces a new UI component for this functionality in ChangeAdminScreen.kt. The SpaceProfileScreen and its corresponding ViewModel are updated to manage admin changes, including new dialog interactions. Additional string resources are added for UI elements, and methods for changing the admin are implemented in the repository and service layers.

Changes

File Change Summary
app/build.gradle.kts Added dependency: implementation("com.google.code.gson:gson:2.10.1")
app/src/main/java/com/canopas/yourspace/ui/MainActivity.kt Added imports for Uri and Gson; implemented new navigation route for ChangeAdminScreen with argument handling.
app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/SpaceProfileScreen.kt Introduced dropdown for admin changes; updated button logic; added dialog for admin change; modified UserItem display.
app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/SpaceProfileViewModel.kt Added methods for admin management; updated state properties for member count and dialog visibility; restored connectivity check.
app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/edit/ChangeAdminScreen.kt Created new UI component for changing admin; includes user selection and confirmation logic.
app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/edit/ChangeAdminViewModel.kt Introduced ViewModel for managing admin change logic; includes methods for fetching space details and changing admin.
app/src/main/java/com/canopas/yourspace/ui/navigation/AppRoute.kt Added new object for ChangeAdminScreen with routing parameters and methods for navigation.
app/src/main/res/values/strings.xml Added new string resources for admin management UI elements.
app/src/test/java/com/canopas/yourspace/ui/flow/settings/space/SpaceProfileViewModelTest.kt Updated variable visibility and class-level annotation; no logic changes.
data/src/main/java/com/canopas/yourspace/data/repository/SpaceRepository.kt Added method changeSpaceAdmin(spaceId: String, newAdminId: String) for changing admin in the repository.
data/src/main/java/com/canopas/yourspace/data/service/space/ApiSpaceService.kt Added method changeAdmin(spaceId: String, newAdminId: String) for updating admin in Firestore.

Possibly related PRs

Suggested reviewers

  • cp-megh-l

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c8551d3 and 8033997.

📒 Files selected for processing (1)
  • app/src/main/res/values/strings.xml (2 hunks)
🔇 Additional comments (3)
app/src/main/res/values/strings.xml (3)

297-297: LGTM! Admin indicator text follows conventions.

The string resource follows Android naming conventions and uses appropriate parentheses formatting for UI labels.


298-298: LGTM! Title and button text are consistent.

The strings follow Android naming conventions and maintain consistency between the title and button text.

Also applies to: 300-300


299-299: Update description text for better clarity.

Based on previous review feedback, the description text should be updated for better clarity and conciseness.

-    <string name="space_setting_change_admin_description">To leave the group, you must assign another member as admin. This action is irreversible unless the new admin changes it.</string>
+    <string name="space_setting_change_admin_description">To leave the group, you must assign another member as admin. This action is irreversible unless the new admin changes it.</string>

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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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 generate docstrings to generate docstrings for this PR. (Experiment)
  • @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 or 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: 10

🧹 Outside diff range and nitpick comments (4)
app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/SpaceProfileViewModel.kt (1)

190-195: Add null safety check for spaceInfo.

The null check is good, but consider adding an error state for when spaceInfo is null to provide better user feedback.

 fun onChangeAdminClicked() {
     val spaceInfo = _state.value.spaceInfo
     if (spaceInfo != null) {
         navigateToChangeAdminScreen(spaceInfo)
         _state.value = _state.value.copy(showChangeAdminDialog = false)
+    } else {
+        _state.value = _state.value.copy(error = Exception("Space information not available"))
     }
 }
app/src/main/res/values/strings.xml (1)

297-300: Consider clarifying the admin change description.

The strings follow good naming conventions and are user-friendly. However, the description could be more specific about the consequences of not changing the admin.

Consider updating the description to be more explicit:

-    <string name="space_setting_change_admin_description">There are members in this group. Please change the admin before leaving.</string>
+    <string name="space_setting_change_admin_description">There are members in this group. To preserve the group and its data, please assign a new admin before leaving.</string>
app/src/main/java/com/canopas/yourspace/ui/navigation/AppRoute.kt (2)

29-31: Rename method to better reflect its purpose

The method name getSpaceDetail doesn't accurately reflect its purpose of creating a route for the admin change screen. Consider renaming it to createRoute or adminChangeRoute for better clarity.

-        fun getSpaceDetail(
+        fun createRoute(
             spaceInfo: String
         ) = object : AppRoute {

33-35: Consider adding nullability configuration for the navigation argument

The navigation argument might need to handle null values in certain scenarios (e.g., deep linking). Consider configuring nullability similar to other routes in the file.

             override val arguments = listOf(
-                navArgument(KEY_SPACE_NAME) { type = NavType.StringType }
+                navArgument(KEY_SPACE_NAME) {
+                    type = NavType.StringType
+                    nullable = false
+                }
             )
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d1088e1 and ca9c741.

📒 Files selected for processing (11)
  • app/build.gradle.kts (1 hunks)
  • app/src/main/java/com/canopas/yourspace/ui/MainActivity.kt (4 hunks)
  • app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/SpaceProfileScreen.kt (7 hunks)
  • app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/SpaceProfileViewModel.kt (6 hunks)
  • app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/edit/ChangeAdminScreen.kt (1 hunks)
  • app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/edit/ChangeAdminViewModel.kt (1 hunks)
  • app/src/main/java/com/canopas/yourspace/ui/navigation/AppRoute.kt (1 hunks)
  • app/src/main/res/values/strings.xml (2 hunks)
  • app/src/test/java/com/canopas/yourspace/ui/flow/settings/space/SpaceProfileViewModelTest.kt (1 hunks)
  • data/src/main/java/com/canopas/yourspace/data/repository/SpaceRepository.kt (1 hunks)
  • data/src/main/java/com/canopas/yourspace/data/service/space/ApiSpaceService.kt (2 hunks)
🔇 Additional comments (9)
app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/SpaceProfileScreen.kt (3)

23-24: Necessary imports added for new components.

The imports for MoreVert icon and DropdownMenu are required for the new admin menu functionality.


111-121: Addition of Change Admin dialog is correctly implemented.

The AppAlertDialog correctly prompts the admin to change the admin before leaving the space.


Line range hint 317-336: Flow correctly handles admin leaving by prompting to change admin.

The logic ensures that if the admin tries to leave the space, they are prompted to assign a new admin, which aligns with the PR objectives.

app/build.gradle.kts (1)

214-214: Verify the gson library version for security vulnerabilities.

Ensure that the added gson library version 2.10.1 is free from known vulnerabilities. Keeping dependencies updated and secure is crucial for application security.

Run the following script to check for the latest version and any security advisories for the gson library:

✅ Verification successful

The current version 2.10.1 of gson appears to be secure but not the latest

The verification shows that:

  • No known vulnerabilities were found in the OSV database for the gson library
  • A newer version (2.11.0) is available, but the current version 2.10.1 is still recent and secure

While updating to the latest version 2.11.0 could be considered, version 2.10.1 is sufficiently recent and has no reported security vulnerabilities, making it safe to use.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for security advisories and latest versions of the `gson` library.

# Fetch the latest version from Maven Central
latest_version=$(curl -s 'https://repo1.maven.org/maven2/com/google/code/gson/gson/maven-metadata.xml' | grep '<latest>' | sed 's/.*<latest>\(.*\)<\/latest>.*/\1/')
echo "Latest version of gson available: $latest_version"

# Check for known vulnerabilities using OSV API
echo "Checking for known vulnerabilities in gson:"
curl -s "https://api.osv.dev/v1/query" -d '{
  "package": {
    "name": "com.google.code.gson:gson",
    "ecosystem": "Maven"
  }
}' | jq '.vulnerabilities[] | {severity: .database_specific.severity, summary: .summary, affected_versions: .affected[].ranges[]}'

Length of output: 680

app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/SpaceProfileViewModel.kt (2)

59-61: LGTM! State update includes member count.

The state update correctly includes the new spaceMemberCount property with a safe default value of 1.


236-246: LGTM! Internet connectivity check is properly implemented.

The implementation correctly observes connectivity status and updates the state accordingly.

app/src/main/java/com/canopas/yourspace/ui/MainActivity.kt (1)

4-4: LGTM: Required imports added for new functionality.

The new imports support the ChangeAdminScreen navigation and parameter handling.

Also applies to: 26-26, 53-53, 56-56, 62-62

app/src/test/java/com/canopas/yourspace/ui/flow/settings/space/SpaceProfileViewModelTest.kt (1)

32-32: LGTM: Improved code organization.

Good improvements:

  1. Moving @OptIn to class level reduces annotation repetition
  2. Making user1 private properly encapsulates the test data

Also applies to: 36-36

app/src/main/java/com/canopas/yourspace/ui/navigation/AppRoute.kt (1)

23-39: LGTM! The route configuration follows established patterns

The ChangeAdminScreen object is well-structured and consistent with other route definitions in the file. It properly:

  • Defines constants for path components
  • Uses type-safe navigation arguments
  • Follows the established pattern for route creation

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: 6

🧹 Outside diff range and nitpick comments (4)
app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/SpaceProfileViewModel.kt (1)

3-3: Consider keeping fetchSpaceDetail private and separating concerns

The method's visibility has been changed from private to public, which could expose internal implementation details. Consider:

  1. Keeping it private and exposing a more focused public API
  2. Separating the data fetching from state management
- fun fetchSpaceDetail() = viewModelScope.launch(appDispatcher.IO) {
+ private fun fetchSpaceDetail() = viewModelScope.launch(appDispatcher.IO) {
     _state.emit(_state.value.copy(isLoading = true))
     try {
         val spaceInfo = spaceRepository.getSpaceInfo(spaceID)
-        val locationEnabled =
-            spaceInfo?.members?.firstOrNull { it.user.id == authService.currentUser?.id }?.isLocationEnable
-                ?: false
-        _state.emit(
-            _state.value.copy(
-                isLoading = false,
-                spaceInfo = spaceInfo,
-                currentUserId = authService.currentUser?.id,
-                isAdmin = spaceInfo?.space?.admin_id == authService.currentUser?.id,
-                spaceName = spaceInfo?.space?.name,
-                locationEnabled = locationEnabled,
-                spaceMemberCount = spaceInfo?.members?.size ?: 1
-            )
-        )
+        updateStateWithSpaceInfo(spaceInfo)
     } catch (e: Exception) {
         Timber.e(e, "Failed to fetch space detail")
         _state.emit(_state.value.copy(error = e, isLoading = false))
     }
 }
+
+ private fun updateStateWithSpaceInfo(spaceInfo: SpaceInfo?) {
+     val locationEnabled =
+         spaceInfo?.members?.firstOrNull { it.user.id == authService.currentUser?.id }?.isLocationEnable
+             ?: false
+     _state.emit(
+         _state.value.copy(
+             isLoading = false,
+             spaceInfo = spaceInfo,
+             currentUserId = authService.currentUser?.id,
+             isAdmin = spaceInfo?.space?.admin_id == authService.currentUser?.id,
+             spaceName = spaceInfo?.space?.name,
+             locationEnabled = locationEnabled,
+             spaceMemberCount = spaceInfo?.members?.size ?: 1
+         )
+     )
+ }

Also applies to: 14-14, 44-61

app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/edit/ChangeAdminViewModel.kt (1)

68-71: Enhance error handling in changeAdmin

The current error handling is too generic. Consider handling specific error cases to provide better user feedback.

-            } catch (e: Exception) {
-                Timber.e(e, "Failed to change admin")
-                _state.emit(_state.value.copy(error = e))
+            } catch (e: Exception) {
+                Timber.e(e, "Failed to change admin")
+                val error = when (e) {
+                    is IOException -> NetworkError(e)
+                    is SecurityException -> PermissionError(e)
+                    else -> UnknownError(e)
+                }
+                _state.emit(_state.value.copy(error = error))
app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/edit/ChangeAdminScreen.kt (1)

78-80: Add loading indicator for admin change operation

The loading indicator only shows during space detail fetching. Add loading state for the admin change operation as well.

-                if (state.isLoading) {
+                if (state.isLoading || state.isChangingAdmin) {
                     AppProgressIndicator()
                 }
app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/SpaceProfileScreen.kt (1)

71-75: Simplify coroutine usage in LaunchedEffect by removing unnecessary withContext.

The withContext(Dispatchers.IO) inside LaunchedEffect may be unnecessary. Since LaunchedEffect already runs in a coroutine scope, and viewModel.fetchSpaceDetail() should handle threading internally if needed, removing withContext simplifies the code without affecting functionality.

Consider applying this diff:

 LaunchedEffect(Unit) {
-    withContext(Dispatchers.IO) {
         viewModel.fetchSpaceDetail()
-    }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ca9c741 and c8551d3.

📒 Files selected for processing (6)
  • app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/SpaceProfileScreen.kt (11 hunks)
  • app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/SpaceProfileViewModel.kt (7 hunks)
  • app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/edit/ChangeAdminScreen.kt (1 hunks)
  • app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/edit/ChangeAdminViewModel.kt (1 hunks)
  • app/src/test/java/com/canopas/yourspace/ui/flow/settings/space/SpaceProfileViewModelTest.kt (11 hunks)
  • data/src/main/java/com/canopas/yourspace/data/repository/SpaceRepository.kt (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • data/src/main/java/com/canopas/yourspace/data/repository/SpaceRepository.kt
  • app/src/test/java/com/canopas/yourspace/ui/flow/settings/space/SpaceProfileViewModelTest.kt
🔇 Additional comments (4)
app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/SpaceProfileViewModel.kt (1)

189-208: Consider using a safer serialization approach.

The current implementation directly encodes the entire SpaceInfo object, which might expose sensitive data. Consider creating a minimal DTO with only the required fields for the admin change screen.

app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/edit/ChangeAdminViewModel.kt (2)

36-55: LGTM! Well-structured space detail fetching

The implementation properly handles loading states, error cases, and updates all relevant state properties.


57-73: ⚠️ Potential issue

Incorrect state updates in changeAdmin function

The state updates after changing admin are incorrect. When transferring admin rights, the current user becomes a regular member.

 _state.emit(
     _state.value.copy(
-        isAdmin = true,
-        currentUserId = newAdminId
+        isAdmin = authService.currentUser?.id == newAdminId,
+        currentUserId = authService.currentUser?.id
     )
 )
app/src/main/java/com/canopas/yourspace/ui/flow/settings/space/SpaceProfileScreen.kt (1)

417-438: LGTM!

Passing isAdminUser as a parameter to UserItem and conditionally displaying the admin label improves code clarity and follows best practices by avoiding direct state access within the composable.

@cp-sneh-s cp-sneh-s requested a review from cp-megh-l December 12, 2024 11:05
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