Skip to content
This repository was archived by the owner on Jun 27, 2025. It is now read-only.

feat: small enhancements#32

Merged
hankhongg merged 4 commits into
mainfrom
feat/small-enhancements
May 30, 2025
Merged

feat: small enhancements#32
hankhongg merged 4 commits into
mainfrom
feat/small-enhancements

Conversation

@hankhongg

@hankhongg hankhongg commented May 30, 2025

Copy link
Copy Markdown
Contributor

Closes #12 , #13 , #14 , #15

Summary by CodeRabbit

  • New Features

    • Introduced a map-based location picker, allowing users to select and autofill addresses in forms.
    • Added a "Transfer" action button on the home screen for quick access to fund transfers.
    • Enhanced the transfer workflow with a dynamic source selection card and streamlined recipient handling.
  • Improvements

    • Address input fields in sign-up and account detail screens now support map-based selection and improved editing.
    • More specific error messages and improved error handling for creating and deleting sources.
    • Prevented account deletion unless all sources are empty.
  • Bug Fixes

    • Fixed UI updates and feedback for source creation errors.
  • Dependencies

    • Added flutter_map, latlong2, and geocoding packages for map and geolocation features.

@hankhongg hankhongg requested a review from a team as a code owner May 30, 2025 08:31
@coderabbitai

coderabbitai Bot commented May 30, 2025

Copy link
Copy Markdown

Walkthrough

This update introduces map-based address selection across several screens, refines error handling for source creation and deletion, and enhances the transfer workflow. New dependencies for map and geocoding support are added. The code now enforces empty sources before account deletion and improves UI integration for dynamic source management and address input.

Changes

File(s) Change Summary
lib/core/bloc/source/source_logic.dart, lib/core/bloc/source/source_state.dart Refined error handling in SourceBloc by introducing SourceCreatedError and SourceDeletedError states for more granular feedback during source creation and deletion.
lib/core/services/source_service.dart, lib/core/services/user_service.dart Added source balance checks before deletion; introduced new methods for fetching sources, checking if all sources are empty, and improved error handling. Account deletion now requires all sources to be empty.
lib/core/services/auth_service.dart, lib/core/bloc/user/user_logic.dart Changed user deletion flow to use UserService.deleteUserAccount with error handling; commented out direct Supabase admin deletion.
lib/presentation/components/transfer_card.dart Refactored to fetch and display user sources dynamically via Bloc; added UI for selecting sources and entering transfer details.
lib/presentation/screen/transaction/transfer_screen.dart Updated to require a UserModel, removed manual recipient entry, and integrated the new TransferCard for streamlined transfers.
lib/presentation/screen/transaction/add_source_screen.dart Improved SnackBar handling and error state display for source creation.
lib/presentation/screen/auth/sign_up_details_screen.dart, lib/presentation/screen/setting/account_detail_screen.dart Integrated map-based address picking with a new controller, navigation to a location picker, and updated field interactions.
lib/presentation/screen/common/location_picker_screen.dart Added a new screen for picking a location on a map and reverse geocoding to an address.
lib/presentation/screen/main/home.dart Added a "Transfer" action button to the home screen.
lib/presentation/routes/router.dart, lib/presentation/routes/routes.dart Added a new route for the location picker and updated transfer route to accept a UserModel.
pubspec.yaml Added dependencies: flutter_map, latlong2, and geocoding for map and geolocation features.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant HomeScreen
    participant TransferScreen
    participant TransferCard
    participant UserBloc
    participant SourceService

    User->>HomeScreen: Tap "Transfer"
    HomeScreen->>TransferScreen: Navigate with UserModel
    TransferScreen->>TransferCard: Show transfer UI for user
    TransferCard->>UserBloc: Dispatch SourcesFetching(userId)
    UserBloc->>SourceService: Fetch user sources
    SourceService-->>UserBloc: Return sources
    UserBloc-->>TransferCard: Emit SourcesFetchedSuccess
    TransferCard->>User: Display sources for selection
Loading
sequenceDiagram
    participant User
    participant SignUpDetailsScreen
    participant LocationPickerScreen
    participant GeocodingService

    User->>SignUpDetailsScreen: Tap address map icon
    SignUpDetailsScreen->>LocationPickerScreen: Navigate to map picker
    User->>LocationPickerScreen: Tap on map
    LocationPickerScreen->>GeocodingService: Reverse geocode coordinates
    GeocodingService-->>LocationPickerScreen: Return address
    LocationPickerScreen->>SignUpDetailsScreen: Pop with address and coordinates
    SignUpDetailsScreen->>User: Display selected address
Loading

Assessment against linked issues

Objective Addressed Explanation
Export image (to clipboard, share, save) the ticket/transaction (#12) No code related to exporting images or tickets/transactions is present.

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Map-based address selection and location picker integration (lib/presentation/screen/common/location_picker_screen.dart, lib/presentation/screen/auth/sign_up_details_screen.dart, lib/presentation/screen/setting/account_detail_screen.dart) These features are unrelated to the ticket export functionality described in the linked issue.
Refined error handling for source creation/deletion (lib/core/bloc/source/source_logic.dart, lib/core/bloc/source/source_state.dart) Not related to exporting tickets or transactions.
Enforcing empty sources before account deletion (lib/core/services/user_service.dart, lib/core/services/source_service.dart) Not within the scope of ticket export.
Transfer workflow and UI changes (lib/presentation/components/transfer_card.dart, lib/presentation/screen/transaction/transfer_screen.dart, lib/presentation/screen/main/home.dart) These changes pertain to transfers and not to exporting tickets/transactions.

Possibly related PRs

  • feat: export tickets pt2 #31: Adds a new SourceDeleting event and success state to SourceBloc, which is related to the current PR’s refinement of error handling for source deletion.

Poem

A hop, a skip, a map to see,
Now picking places is easy as can be!
With sources checked and errors clear,
Transfers and addresses bring users cheer.
Though tickets wait for export's day,
This bunny codes and hops away!
🗺️🐇✨


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@sonarqubecloud

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 15

🔭 Outside diff range comments (2)
lib/presentation/screen/transaction/transfer_screen.dart (1)

27-80: 💡 Verification agent

🧩 Analysis chain

Form validation is disconnected from TransferCard.

The _formKey is still used for validation, but it's not connected to the actual form fields inside TransferCard. This means validation won't work as expected.

Consider either:

  1. Moving the form validation logic into TransferCard
  2. Exposing the form fields from TransferCard to the parent
  3. Using a callback to get the form data from TransferCard

🏁 Script executed:

#!/bin/bash
# Verify if TransferCard has its own form validation
ast-grep --pattern 'class TransferCard extends $_ {
  $$$
  GlobalKey<FormState> $_ = $_
  $$$
}'

Length of output: 99


🏁 Script executed:

#!/bin/bash
# Search transfer_screen.dart for Form widget declaration, _formKey references, and TransferCard placement
rg -n "Form\(" lib/presentation/screen/transaction/transfer_screen.dart
rg -n "_formKey" lib/presentation/screen/transaction/transfer_screen.dart
rg -n "TransferCard" lib/presentation/screen/transaction/transfer_screen.dart

Length of output: 462


#!/bin/bash
# Locate TransferCard implementation and display its code for inspection
transfer_card_file=$(rg -n 'class TransferCard' lib/presentation | head -1 | cut -d: -f1)
echo "TransferCard file: $transfer_card_file"
echo "----- Start of TransferCard (lines 1–200) -----"
sed -n '1,200p' "$transfer_card_file"
echo "----- Next section (lines 201–400) -----"
sed -n '201,400p' "$transfer_card_file"

🏁 Script executed:

#!/bin/bash
# Locate the TransferCard implementation and print its first 200 lines
transfer_card_file=$(rg -l 'class TransferCard' -g '*.dart' | head -n1)
echo "Found TransferCard in: $transfer_card_file"
echo "----- Start of $transfer_card_file (lines 1–200) -----"
sed -n '1,200p' "$transfer_card_file"

Length of output: 7904


🏁 Script executed:

#!/bin/bash
# Print transfer_screen.dart around the Form to inspect children and fields
echo "----- transfer_screen.dart lines 80–200 -----"
sed -n '80,200p' lib/presentation/screen/transaction/transfer_screen.dart

Length of output: 4468


Connect TransferCard fields to the Form’s validation

The Form in lib/presentation/screen/transaction/transfer_screen.dart wraps the TransferCard, but all inputs inside TransferCard are plain TextFields—no TextFormFields or validators—so _formKey.currentState!.validate() will always succeed.

To fix this, you can:

  • In lib/presentation/components/transfer_card.dart:
    • Replace each TextField (Account Number, Amount, Description) with TextFormField.
    • Add a validator: (value) => value == null || value.isEmpty ? 'This field is required' : null (and any business rules) to each.
  • Decide where validation should live:
    • Pass the parent’s GlobalKey<FormState> into TransferCard and register its fields under that key, or
    • Handle validation entirely inside TransferCard (e.g. wrap its own Form around the fields and expose a validate() method or callback).
  • Ensure that _processTransfer() only proceeds when all field validators pass and that you can access the validated input values (via controllers or callbacks).

Files to update:

  • lib/presentation/screen/transaction/transfer_screen.dart (Form at lines ~107–130)
  • lib/presentation/components/transfer_card.dart (replace TextField → TextFormField and add validator)
lib/core/services/source_service.dart (1)

120-124: 💡 Verification agent

🧩 Analysis chain

Review status code handling for delete operation.

The delete operation treats both 200 and 409 (Conflict) as success. A 409 status typically indicates the resource couldn't be deleted due to a conflict. Consider logging or handling this case differently.


🌐 Web query:

What does HTTP status code 409 mean in the context of a DELETE operation?

💡 Result:

HTTP status code 409 means "Conflict." In the context of a DELETE operation, it indicates that the request could not be processed because of a conflict with the current state of the resource.

For example, a 409 Conflict when attempting to delete a resource might occur if there are dependent resources or constraints that prevent the resource from being deleted at that time. It signals that the request is valid, but the server cannot complete the DELETE action due to a conflict that must be resolved first.


Handle HTTP 409 (Conflict) Separately in Delete Operation

The HTTP spec defines 409 as “Conflict” – it means the server couldn’t perform the DELETE due to a state conflict (e.g., dependent resources). Returning it as a “success” may mask real issues that need resolution.

Please update lib/core/services/source_service.dart (lines 120–124):

• Treat 409 as a distinct error or log-and-throw a more specific exception.
• Reserve the 200 path for true success.

Suggested diff:

-    if (response.statusCode == 200 || response.statusCode == 409) {
-      return response;
-    } else {
-      throw Exception("Failed to delete source: ${response.statusCode}");
-    }
+    if (response.statusCode == 200) {
+      return response;
+    } else if (response.statusCode == 409) {
+      // Conflict: deletion blocked by dependent resources or constraints
+      throw Exception("Conflict deleting source (409): please resolve dependencies before retrying.");
+    } else {
+      throw Exception("Failed to delete source: ${response.statusCode}");
+    }
🧹 Nitpick comments (9)
lib/presentation/screen/transaction/add_source_screen.dart (2)

30-30: Remove debug print statement for production.

The debug print statement should be removed before merging to production to avoid cluttering logs.

-        print("🔥 BlocConsumer listener fired: $state");

41-48: Consider consolidating similar error handling.

Both SourceCreatedError and SourceError show identical red SnackBars with the error message. Consider consolidating them for cleaner code:

-        } else if (state is SourceCreatedError) {
-          ScaffoldMessenger.of(context).showSnackBar(
-            SnackBar(content: Text(state.message), backgroundColor: Colors.red),
-          );
-        } else if (state is SourceError) {
-          ScaffoldMessenger.of(context).showSnackBar(
-            SnackBar(content: Text(state.message), backgroundColor: Colors.red),
-          );
+        } else if (state is SourceCreatedError || state is SourceError) {
+          ScaffoldMessenger.of(context).showSnackBar(
+            SnackBar(
+              content: Text(state.message), 
+              backgroundColor: Colors.red
+            ),
+          );
lib/presentation/screen/common/location_picker_screen.dart (2)

17-17: Fix incorrect location comment.

The comment says "SG default" (Singapore) but the coordinates (10.762622, 106.660172) point to Ho Chi Minh City, Vietnam.

-  final defaultLocation = LatLng(10.762622, 106.660172); // SG default
+  final defaultLocation = LatLng(10.762622, 106.660172); // Ho Chi Minh City default

Or update the coordinates to actually point to Singapore:

-  final defaultLocation = LatLng(10.762622, 106.660172); // SG default
+  final defaultLocation = LatLng(1.3521, 103.8198); // Singapore default

57-80: Improve FAB interaction by disabling when no location is selected.

The floating action button should be visually disabled when no location is selected to provide better UX.

      floatingActionButton: FloatingActionButton.extended(
-        onPressed: () async {
+        onPressed: selectedLatLng != null ? () async {
          if (selectedLatLng != null) {
            // ... existing logic
          }
-        },
+        } : null,
+        backgroundColor: selectedLatLng != null ? null : Colors.grey,
        label: const Text("Confirm"),
        icon: const Icon(Icons.check),
      ),
lib/presentation/screen/auth/sign_up_details_screen.dart (2)

226-227: Remove redundant properties.

The readOnly: false (which is the default) and empty onTap: () {} appear unnecessary and can be removed for cleaner code.

            controller: _addressController,
-            readOnly: false,
-            onTap: () {},

236-248: Add error handling for location picker navigation.

Consider adding error handling for the location picker navigation to provide better user feedback if something goes wrong.

                onPressed: () async {
-                  final result = await context.push(
-                    Routes.common.locationPicker,
-                  );
-                  if (result != null && result is Map) {
-                    //final LatLng location = result["location"];
-                    final String address = result["address"];
-
-                    setState(() {
-                      _addressController.text = address;
-                      userModel.address = address;
-                    });
-                  }
+                  try {
+                    final result = await context.push(
+                      Routes.common.locationPicker,
+                    );
+                    if (result != null && result is Map) {
+                      final String address = result["address"] ?? "";
+                      
+                      if (address.isNotEmpty) {
+                        setState(() {
+                          _addressController.text = address;
+                          userModel.address = address;
+                        });
+                      }
+                    }
+                  } catch (e) {
+                    ScaffoldMessenger.of(context).showSnackBar(
+                      SnackBar(
+                        content: Text("Could not open location picker: $e"),
+                        backgroundColor: Colors.red,
+                      ),
+                    );
+                  }
                },
lib/presentation/screen/transaction/transfer_screen.dart (1)

29-29: Fix inconsistent comment.

The comment mentions "deposit" but this is a transfer screen.

-      // Process deposit logic would go here
+      // Process transfer logic would go here
lib/core/services/source_service.dart (1)

52-53: Remove debug print statements.

Debug print statements should be removed before merging to production.

-    print("response status code: ${response.statusCode}");
-    print("response body: ${response.body}");
-      print("response status code: ${response.statusCode}");
-      print("response body: ${response.body}");
-      print("Error during POST: $e");

Also applies to: 85-86, 94-94

lib/presentation/screen/setting/account_detail_screen.dart (1)

291-291: Consider removing redundant parameter.

Setting readOnly: false is redundant since false is the default value for TextFormField.

-          readOnly: false, // allow typing
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7b0a07a and fa199c4.

⛔ Files ignored due to path filters (1)
  • pubspec.lock is excluded by !**/*.lock
📒 Files selected for processing (16)
  • lib/core/bloc/source/source_logic.dart (2 hunks)
  • lib/core/bloc/source/source_state.dart (2 hunks)
  • lib/core/bloc/user/user_logic.dart (1 hunks)
  • lib/core/services/auth_service.dart (1 hunks)
  • lib/core/services/source_service.dart (3 hunks)
  • lib/core/services/user_service.dart (2 hunks)
  • lib/presentation/components/transfer_card.dart (1 hunks)
  • lib/presentation/routes/router.dart (3 hunks)
  • lib/presentation/routes/routes.dart (2 hunks)
  • lib/presentation/screen/auth/sign_up_details_screen.dart (3 hunks)
  • lib/presentation/screen/common/location_picker_screen.dart (1 hunks)
  • lib/presentation/screen/main/home.dart (2 hunks)
  • lib/presentation/screen/setting/account_detail_screen.dart (3 hunks)
  • lib/presentation/screen/transaction/add_source_screen.dart (1 hunks)
  • lib/presentation/screen/transaction/transfer_screen.dart (5 hunks)
  • pubspec.yaml (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: Dart Check
lib/core/services/source_service.dart

[warning] 64-64: The operand can't be 'null', so the condition is always 'false'. Try removing the condition, an enclosing condition, or the whole conditional statement. (unnecessary_null_comparison)

⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Build APK (x64)
  • GitHub Check: Build APK (arm64)
  • GitHub Check: Build APK (arm)
  • GitHub Check: Build IPA
🔇 Additional comments (25)
pubspec.yaml (1)

65-67:

Details

✅ Verification successful

Verify package versions and security status for new mapping dependencies.

The added dependencies support the new location picker functionality. Please ensure these package versions are current and secure.


🌐 Web query:

What are the latest stable versions of flutter_map, latlong2, and geocoding packages for Flutter? Are there any known security vulnerabilities in versions 8.1.1, 0.9.1, and 4.0.0 respectively?

💡 Result:

Latest Stable Versions

  • flutter_map: The latest stable version is 8.1.1 (published for Flutter 3.6, uploaded recently)[4][8].
  • latlong2: The latest stable version is 0.9.1 (released in March 2024)[10].
  • geocoding: The latest stable version is 4.0.0 (released roughly 1 day ago)[7].

All the versions you mentioned—flutter_map 8.1.1, latlong2 0.9.1, and geocoding 4.0.0—are the most current stable releases as of May 30, 2025.

Security Vulnerabilities in the Referenced Versions

  • flutter_map 8.1.1: There are no publicized security vulnerabilities for flutter_map version 8.1.1. The changelog and release notes for this version focus on bug fixes (such as resolving infinite loops with rotated polygon labels), stability, and user-facing features, with no mention of security issues[4][8].

  • latlong2 0.9.1: There are no reported or listed security vulnerabilities for latlong2 version 0.9.1 according to Flutter Gems and public package sources as of the last updates in March and April 2025[10].

  • geocoding 4.0.0: No security issues have been reported for geocoding version 4.0.0. The release is very recent and there remain no advisories or indications of vulnerabilities on pub.dev or associated sources[7].

Summary Table

Package Latest Stable Version Security Vulnerabilities in Latest Version?
flutter_map 8.1.1 None known as of May 2025
latlong2 0.9.1 None known as of May 2025
geocoding 4.0.0 None known as of May 2025

There are no known or reported security vulnerabilities in flutter_map 8.1.1, latlong2 0.9.1, or geocoding 4.0.0 at this time[4][7][10]. If you are using these versions, you are on the latest stable builds with no documented security risks according to public package repositories and release documentation.

Citations:


Dependencies are up-to-date and secure

All three newly added packages are at their latest stable releases and have no known security vulnerabilities as of May 2025:

  • flutter_map: 8.1.1 – latest stable, no reported issues
  • latlong2: 0.9.1 – latest stable, no reported issues
  • geocoding: 4.0.0 – latest stable, no reported issues

No further changes are needed here.

lib/presentation/routes/router.dart (2)

12-12: LGTM: Import addition for new location picker functionality.

The import for LocationPickerScreen is correctly added to support the new location picker route.


223-230: LGTM: Well-structured location picker route implementation.

The new location picker route is properly implemented with correct path mapping and returns a const widget instance for better performance.

lib/presentation/routes/routes.dart (2)

8-8: LGTM: Consistent addition of common route group.

The addition of the common route group follows the established pattern and maintains consistency with other route groups.


55-60: LGTM: Well-structured _Common route class implementation.

The implementation follows the established pattern with:

  • Consistent const constructor
  • Proper root path structure
  • Clear locationPicker getter method
lib/core/bloc/source/source_state.dart (2)

17-21: LGTM: Well-structured error state for source creation.

The SourceCreatedError class follows the established pattern and provides specific error handling for source creation operations, which will improve user feedback.


35-39: LGTM: Consistent error state implementation for source deletion.

The SourceDeletedError class maintains consistency with the existing error handling pattern and enables granular error management for deletion operations.

lib/presentation/screen/main/home.dart (2)

2-2: LGTM: Appropriate import for the new Transfer button styling.

The AppTheme import is necessary for the AppTheme.accentCopper color used in the new Transfer button.


550-565: LGTM: Well-implemented Transfer button addition.

The changes properly:

  • Adjust the "New Saving Plan" button width to accommodate the new Transfer button
  • Add the Transfer button with consistent styling and appropriate navigation
  • Pass the required UserModel to the transfer route as expected by the routing updates

The layout and functionality integration looks solid.

lib/core/services/auth_service.dart (1)

209-221: ⚠️ Potential issue

Fix the order of operations to prevent premature cleanup on deletion failure.

The current implementation signs out the user and clears the JWT token even if the UserService.deleteUserAccount call fails. This could leave the user in an inconsistent state where they're signed out but their account still exists.

Move the signOut and JWT cleanup inside a success block:

  static Future<void> deleteUser() async {
    final user = supabaseClient.auth.currentUser;
    if (user == null) {
      throw "User not found";
    }
    final userId = user.id;
    try {
      final response = await UserService.deleteUserAccount(userId);
      if (response.statusCode != 204) {
        throw "Failed to delete user account";
      }
+     // Only sign out and clear token after successful deletion
+     await supabaseClient.auth.signOut();
+     await LocalStorageService().delete("JWT");
    } catch (e) {
      throw Exception("Error deleting user: $e");
    }
-   await supabaseClient.auth.signOut();
-
-   //await supabaseClient.auth.admin.deleteUser(userId);
-   await LocalStorageService().delete("JWT");
  }

Likely an incorrect or invalid review comment.

lib/core/services/user_service.dart (2)

6-6: LGTM: Necessary import for source validation.

The SourceService import is required for the new checkAllSourcesIsEmpty method used in the account deletion validation.


207-214: LGTM: Excellent addition of business rule validation.

The precondition check ensures data integrity by preventing account deletion when sources still contain balances. The error message is clear and provides actionable guidance to the user.

This is a good example of implementing proper business rules in the service layer.

lib/core/bloc/source/source_logic.dart (2)

30-37: Improved error specificity for source creation.

The change from generic SourceError to SourceCreatedError provides better error granularity. Including the HTTP status code in the error message will help with debugging.


49-59: Enhanced error handling for source deletion with context-specific messages.

The implementation provides helpful, context-aware error messages:

  • HTTP 409: Suggests the source has money in it
  • Other failures: Suggests the source is in use
  • Both cases use the specific SourceDeletedError type

This gives users clear guidance on why the deletion failed and what they need to do.

lib/presentation/screen/transaction/add_source_screen.dart (1)

32-32: Good practice: Hide current SnackBar before showing new one.

This prevents multiple SnackBars from queuing up and provides a better user experience.

lib/presentation/screen/auth/sign_up_details_screen.dart (2)

132-132: Proper controller lifecycle management.

Good practice adding the TextEditingController and properly disposing it in the dispose() method to prevent memory leaks.

Also applies to: 148-152


225-253: Well-integrated location picker functionality.

The integration with the location picker is well implemented:

  • Suffix icon provides intuitive access to map selection
  • Updates both controller text and model on selection
  • Maintains existing form validation flow with onSaved
lib/core/services/source_service.dart (2)

62-97: Good implementation of duplicate source validation!

The check for existing sources before creation prevents duplicate source IDs for the same user, which is a good defensive programming practice.

🧰 Tools
🪛 GitHub Actions: Dart Check

[warning] 64-64: The operand can't be 'null', so the condition is always 'false'. Try removing the condition, an enclosing condition, or the whole conditional statement. (unnecessary_null_comparison)


100-105: Excellent addition of balance check before deletion!

Ensuring the source is empty before deletion prevents data loss and maintains data integrity.

lib/presentation/screen/setting/account_detail_screen.dart (6)

3-3: LGTM!

The import is necessary for the new location picker navigation functionality.


290-290: Good semantic improvement.

Changing to Icons.home_outlined provides better semantic meaning for an address field.


361-362: Well-designed method signature enhancement.

The new parameters are properly designed with sensible defaults and maintain backward compatibility.


370-370: LGTM!

Correctly implements the readOnly functionality.


371-371: Verify the intended UX behavior.

The onTap logic only triggers when readOnly is true, but the address field is set to readOnly: false. This means users can only access the map picker via the suffix icon, not by tapping the field directly.

Is this the intended behavior? Consider if tapping the field should also trigger the map picker for consistency.


378-385: Excellent suffix icon implementation.

The implementation follows good practices:

  • Conditional rendering based on callback availability
  • Semantically appropriate icon
  • Good accessibility with tooltip
  • Clean callback invocation

if (response.statusCode == 200) {
emit(DeleteAccountSuccess());
AuthService.deleteUser();
//AuthService.deleteUser();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Critical: Verify complete account deletion flow after commenting out AuthService.deleteUser().

Commenting out the AuthService.deleteUser() call could break the account deletion flow, potentially leaving users authenticated even after "deleting" their account. While the AI summary mentions refactored deletion logic in other services, this bloc no longer triggers actual user deletion from the authentication system.


🏁 Script executed:

#!/bin/bash
# Description: Verify the complete account deletion flow and check if AuthService.deleteUser() is called elsewhere
# Expected: Find where user authentication deletion is now handled

echo "=== Searching for AuthService.deleteUser() calls ==="
rg "AuthService\.deleteUser" -A 3 -B 3

echo -e "\n=== Searching for UserService.deleteUserAccount implementation ==="
ast-grep --pattern 'deleteUserAccount($_) {
  $$$
}'

echo -e "\n=== Checking if AuthService methods are called in UserService ==="
rg "AuthService\." lib/core/services/user_service.dart -A 2 -B 2

Length of output: 1105


🏁 Script executed:

#!/bin/bash
# Locate the implementation of deleteUserAccount in the services layer
echo "=== Locating deleteUserAccount implementation ==="
rg -n "deleteUserAccount" lib/core/services -A 5 -B 5

Length of output: 1724


Fix Required: Restore complete deletion & sign-out in account deletion flow

The current bloc implementation in lib/core/bloc/user/user_logic.dart (around line 67) directly calls

final response = await UserService.deleteUserAccount(event.userId);
if (response.statusCode == 200) {
  emit(DeleteAccountSuccess());
  //AuthService.deleteUser();
}

and has commented out the AuthService.deleteUser() call. This:

  • Bypasses the auth‐system cleanup (sign-out, token revocation, local credential clearing).
  • Mismatches expected HTTP codes: UserService.deleteUserAccount returns 204, not 200, so failures may be swallowed.

AuthService.deleteUser() (in lib/core/services/auth_service.dart) wraps both the backend call and local sign-out, checking for 204 and throwing if it fails.

Please update the bloc to either:

  1. Revert to using AuthService.deleteUser():
    - final response = await UserService.deleteUserAccount(event.userId);
    - if (response.statusCode == 200) {
    -   emit(DeleteAccountSuccess());
    -   //AuthService.deleteUser();
    - }
    + await AuthService.deleteUser();
    + emit(DeleteAccountSuccess());
  2. Or, if you opt to keep UserService.deleteUserAccount:
    • Change the check to response.statusCode == 204
    • Explicitly call await AuthService.signOut() (or equivalent cleanup) after a successful deletion.

This will ensure users are both removed from the backend and signed out locally.

🤖 Prompt for AI Agents
In lib/core/bloc/user/user_logic.dart at line 67, the account deletion flow is
incomplete because AuthService.deleteUser() is commented out, causing missing
authentication cleanup and incorrect HTTP status code checks. Fix this by either
restoring the call to AuthService.deleteUser() to handle backend deletion and
sign-out together, or if keeping UserService.deleteUserAccount, update the
status code check to 204 and add an explicit call to AuthService.signOut() after
successful deletion to ensure proper user sign-out and cleanup.

Comment on lines +133 to +134
final model = state.extra as UserModel;
return TransferScreen(model: model);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify all navigation calls to transfer route pass UserModel.

The transfer route now requires a UserModel passed via state.extra. This is a breaking change that could cause runtime exceptions if existing navigation calls don't provide the required model.


🏁 Script executed:

#!/bin/bash
# Description: Find all navigation calls to transfer route to verify UserModel is passed
# Expected: All calls should pass UserModel via extra parameter

echo "=== Searching for navigation calls to transfer route ==="
rg "go.*transfer|push.*transfer|context\.go.*Routes\.transaction\.transfer" -A 5 -B 2

echo -e "\n=== Searching for TransferScreen constructor calls ==="
rg "TransferScreen\(" -A 3 -B 2

Length of output: 2500


Include the required UserModel when navigating to the transfer route

A navigation call to the transfer screen is missing the extra: UserModel parameter, which will cause a runtime cast error in the router.

• lib/presentation/screen/home.dart

// Currently:
onTap: () => context.push(Routes.transaction.transfer),

// Should be:
onTap: () => context.push(
  Routes.transaction.transfer,
  extra: model, // pass a valid UserModel instance
),

Ensure every context.push(Routes.transaction.transfer, …) supplies a UserModel via extra:.

🤖 Prompt for AI Agents
In lib/presentation/screen/home.dart around the lines where navigation to the
transfer route occurs, the context.push call to Routes.transaction.transfer is
missing the required UserModel passed via the extra parameter. Update all such
navigation calls to include extra: model, where model is a valid UserModel
instance, to prevent runtime cast errors in the router expecting state.extra as
UserModel.

Comment on lines +58 to +77
onPressed: () async {
if (selectedLatLng != null) {
// Try reverse geocoding
List<Placemark> placemarks = await placemarkFromCoordinates(
selectedLatLng!.latitude,
selectedLatLng!.longitude,
);

// Build readable address
Placemark place = placemarks.first;
String address =
"${place.street}, ${place.locality}, ${place.administrativeArea}";

// Return both LatLng and address as Map
Navigator.pop(context, {
"location": selectedLatLng,
"address": address,
});
}
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for geocoding operations.

The reverse geocoding operation can fail due to network issues or API limits. Add proper error handling to provide user feedback.

        onPressed: () async {
          if (selectedLatLng != null) {
-            // Try reverse geocoding
-            List<Placemark> placemarks = await placemarkFromCoordinates(
-              selectedLatLng!.latitude,
-              selectedLatLng!.longitude,
-            );
-
-            // Build readable address
-            Placemark place = placemarks.first;
-            String address =
-                "${place.street}, ${place.locality}, ${place.administrativeArea}";
-
-            // Return both LatLng and address as Map
-            Navigator.pop(context, {
-              "location": selectedLatLng,
-              "address": address,
-            });
+            try {
+              // Try reverse geocoding
+              List<Placemark> placemarks = await placemarkFromCoordinates(
+                selectedLatLng!.latitude,
+                selectedLatLng!.longitude,
+              );
+
+              if (placemarks.isNotEmpty) {
+                // Build readable address
+                Placemark place = placemarks.first;
+                String address = [
+                  place.street,
+                  place.locality,
+                  place.administrativeArea
+                ].where((part) => part != null && part.isNotEmpty).join(", ");
+
+                // Return both LatLng and address as Map
+                Navigator.pop(context, {
+                  "location": selectedLatLng,
+                  "address": address.isNotEmpty ? address : "Unknown location",
+                });
+              } else {
+                // No address found, return coordinates only
+                Navigator.pop(context, {
+                  "location": selectedLatLng,
+                  "address": "${selectedLatLng!.latitude}, ${selectedLatLng!.longitude}",
+                });
+              }
+            } catch (e) {
+              // Show error and return coordinates as fallback
+              ScaffoldMessenger.of(context).showSnackBar(
+                SnackBar(
+                  content: Text("Could not get address: $e"),
+                  backgroundColor: Colors.orange,
+                ),
+              );
+              Navigator.pop(context, {
+                "location": selectedLatLng,
+                "address": "${selectedLatLng!.latitude}, ${selectedLatLng!.longitude}",
+              });
+            }
          }
        },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
onPressed: () async {
if (selectedLatLng != null) {
// Try reverse geocoding
List<Placemark> placemarks = await placemarkFromCoordinates(
selectedLatLng!.latitude,
selectedLatLng!.longitude,
);
// Build readable address
Placemark place = placemarks.first;
String address =
"${place.street}, ${place.locality}, ${place.administrativeArea}";
// Return both LatLng and address as Map
Navigator.pop(context, {
"location": selectedLatLng,
"address": address,
});
}
},
onPressed: () async {
if (selectedLatLng != null) {
try {
// Try reverse geocoding
List<Placemark> placemarks = await placemarkFromCoordinates(
selectedLatLng!.latitude,
selectedLatLng!.longitude,
);
if (placemarks.isNotEmpty) {
// Build readable address
Placemark place = placemarks.first;
String address = [
place.street,
place.locality,
place.administrativeArea
].where((part) => part.isNotEmpty).join(", ");
// Return both LatLng and address as Map
Navigator.pop(context, {
"location": selectedLatLng,
"address": address.isNotEmpty ? address : "Unknown location",
});
} else {
// No address found, return coordinates only
Navigator.pop(context, {
"location": selectedLatLng,
"address": "${selectedLatLng!.latitude}, ${selectedLatLng!.longitude}",
});
}
} catch (e) {
// Show error and return coordinates as fallback
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("Could not get address: $e"),
backgroundColor: Colors.orange,
),
);
Navigator.pop(context, {
"location": selectedLatLng,
"address": "${selectedLatLng!.latitude}, ${selectedLatLng!.longitude}",
});
}
}
},
🤖 Prompt for AI Agents
In lib/presentation/screen/common/location_picker_screen.dart around lines 58 to
77, the reverse geocoding call placemarkFromCoordinates lacks error handling,
which can cause the app to crash or hang if the operation fails. Wrap the
geocoding call and subsequent code in a try-catch block to catch exceptions, and
in the catch block, provide user feedback such as showing an error message or a
snackbar indicating the failure. This ensures graceful handling of network or
API errors during geocoding.

const SizedBox(height: 16),
Text(
"Your transfer of ${NumberFormat.currency(locale: 'vi_VN', symbol: 'đ', decimalDigits: 0).format(double.parse(_amountController.text))} to ${_recipientController.text} has been processed successfully.",
"Your transfer of ${NumberFormat.currency(locale: 'vi_VN', symbol: 'đ', decimalDigits: 0).format(double.parse(_amountController.text))} has been processed successfully.",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix broken amount reference in success message.

The _amountController is no longer connected to any input field. The TransferCard manages its own state, so you'll need to either pass the amount back to this screen or retrieve it from the TransferCard.

Would you like me to suggest a solution that properly retrieves the transfer amount from the TransferCard component?

🤖 Prompt for AI Agents
In lib/presentation/screen/transaction/transfer_screen.dart at line 56, the
success message references _amountController.text, but _amountController is no
longer linked to any input field since TransferCard manages its own state. To
fix this, modify the code to obtain the transfer amount from the TransferCard
component by either passing the amount back to this screen via a callback or
accessing a getter/property from TransferCard that exposes the current amount,
then use that value in the success message formatting instead of
_amountController.text.

Comment on lines 21 to 24
void dispose() {
_amountController.dispose();
_recipientController.dispose();
_noteController.dispose();
super.dispose();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove disposal of unused controllers.

Since the controllers are no longer used, their disposal can be removed.

   @override
   void dispose() {
-    _amountController.dispose();
-    _noteController.dispose();
     super.dispose();
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
void dispose() {
_amountController.dispose();
_recipientController.dispose();
_noteController.dispose();
super.dispose();
@override
void dispose() {
super.dispose();
}
🤖 Prompt for AI Agents
In lib/presentation/screen/transaction/transfer_screen.dart around lines 21 to
24, the dispose method is disposing _amountController and _noteController which
are no longer used. Remove the disposal calls for these controllers from the
dispose method to clean up unused code.

Icons.description_outlined,
color: theme.primaryColor,
),
counterText: "${amountController.text.length}/$limitLength",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix character counter to update dynamically.

The character counter won't update as the user types because it's not wrapped in a setState or using a ValueListenableBuilder.

Wrap the TextField in a StatefulBuilder or use ValueListenableBuilder:

ValueListenableBuilder<TextEditingValue>(
  valueListenable: descriptionController,
  builder: (context, value, child) {
    return TextField(
      // ... existing properties ...
      decoration: InputDecoration(
        // ... existing properties ...
        counterText: "${value.text.length}/$limitLength",
        // ... rest of decoration ...
      ),
    );
  },
)
🤖 Prompt for AI Agents
In lib/presentation/components/transfer_card.dart at line 210, the character
counter for the TextField does not update dynamically because it uses a static
reference to the controller's text length. To fix this, wrap the TextField with
a ValueListenableBuilder that listens to the TextEditingController's value, and
update the counterText inside the builder using the current text length from the
value parameter. This ensures the counter updates in real-time as the user
types.

final TextEditingController amountController = TextEditingController();
final int limitLength = 160;
late int selectedIndex;
late int selectedIndexProvider;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove unused variable.

The selectedIndexProvider variable is defined but never used.

-  late int selectedIndexProvider;

Also remove its initialization on line 26:

     selectedIndex = 0;
-    selectedIndexProvider = 0;
🤖 Prompt for AI Agents
In lib/presentation/components/transfer_card.dart at line 20, the variable
selectedIndexProvider is declared but never used. Remove this variable
declaration and also remove its initialization on line 26 to clean up unused
code.


static Future<http.Response> deleteSource(String sourceId) async {
final source = await fetchSource(sourceId);
if (int.parse(source.balance!) != 0) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for balance parsing.

Using int.parse on the balance field could throw if the balance is null or not a valid integer.

-    if (int.parse(source.balance!) != 0) {
+    final balance = int.tryParse(source.balance ?? '0') ?? 0;
+    if (balance != 0) {

Similarly for line 133:

-        if (int.parse(source.balance!) != 0) {
+        final balance = int.tryParse(source.balance ?? '0') ?? 0;
+        if (balance != 0) {

Also applies to: 133-133

🤖 Prompt for AI Agents
In lib/core/services/source_service.dart at lines 101 and 133, the code uses
int.parse on source.balance without handling potential errors. Update these
lines to safely parse the balance by adding error handling such as try-catch
blocks or using int.tryParse to avoid exceptions if balance is null or invalid.
Ensure that the code gracefully handles parsing failures, for example by
treating invalid or null balances as zero or by implementing appropriate
fallback logic.


static Future<http.Response> createSource(String sourceId) async {
final user = supabaseClient.auth.currentUser;
if (user == null || user.id == null) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove unnecessary null check.

The pipeline correctly identifies that user.id cannot be null if user is not null. In Supabase, a User object always has an id.

-    if (user == null || user.id == null) {
+    if (user == null) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (user == null || user.id == null) {
- if (user == null || user.id == null) {
+ if (user == null) {
🧰 Tools
🪛 GitHub Actions: Dart Check

[warning] 64-64: The operand can't be 'null', so the condition is always 'false'. Try removing the condition, an enclosing condition, or the whole conditional statement. (unnecessary_null_comparison)

🤖 Prompt for AI Agents
In lib/core/services/source_service.dart at line 64, remove the null check for
user.id in the condition since user.id is guaranteed to be non-null if user is
not null. Update the if statement to only check if user is null.

Comment on lines +295 to +306
onMapPick: () async {
final result = await context.push(
Routes.common.locationPicker,
);
if (result != null && result is Map) {
final String address = result["address"];
setState(() {
controllerAddress.text = address;
newUserModel.address = address;
});
}
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve type safety and error handling.

The current implementation has type safety concerns and lacks error handling:

  1. Type casting without validation: result is Map check doesn't ensure the map contains the expected "address" key
  2. No error handling: Navigation failures or unexpected result formats aren't handled

Apply this diff to improve type safety:

           onMapPick: () async {
-            final result = await context.push(
-              Routes.common.locationPicker,
-            );
-            if (result != null && result is Map) {
-              final String address = result["address"];
-              setState(() {
-                controllerAddress.text = address;
-                newUserModel.address = address;
-              });
-            }
+            try {
+              final result = await context.push(
+                Routes.common.locationPicker,
+              );
+              if (result != null && 
+                  result is Map<String, dynamic> && 
+                  result.containsKey("address") && 
+                  result["address"] is String) {
+                final String address = result["address"] as String;
+                setState(() {
+                  controllerAddress.text = address;
+                  newUserModel.address = address;
+                });
+              }
+            } catch (e) {
+              // Handle navigation errors gracefully
+              _showSnackBar(context, "Failed to pick location", isError: true);
+            }
           },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
onMapPick: () async {
final result = await context.push(
Routes.common.locationPicker,
);
if (result != null && result is Map) {
final String address = result["address"];
setState(() {
controllerAddress.text = address;
newUserModel.address = address;
});
}
},
onMapPick: () async {
+ try {
+ final result = await context.push(
+ Routes.common.locationPicker,
+ );
+ if (result != null &&
+ result is Map<String, dynamic> &&
+ result.containsKey("address") &&
+ result["address"] is String) {
+ final String address = result["address"] as String;
+ setState(() {
+ controllerAddress.text = address;
+ newUserModel.address = address;
+ });
+ }
+ } catch (e) {
+ // Handle navigation errors gracefully
+ _showSnackBar(context, "Failed to pick location", isError: true);
+ }
},
🤖 Prompt for AI Agents
In lib/presentation/screen/setting/account_detail_screen.dart around lines 295
to 306, improve type safety and error handling by first verifying that the
result is a Map containing the "address" key before accessing it. Add null
checks and type checks for the "address" value to ensure it is a String. Also,
wrap the navigation call in a try-catch block to handle potential navigation
failures gracefully, logging or handling errors as appropriate.

@hankhongg hankhongg merged commit 7a0ba8b into main May 30, 2025
8 of 9 checks passed
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[mobile] export ticket

1 participant