Skip to content

Fix therapist registration by including email and phone in insert#193

Open
hasanravda wants to merge 2 commits intoAOSSIE-Org:mainfrom
hasanravda:feat/therapist-complete-registration
Open

Fix therapist registration by including email and phone in insert#193
hasanravda wants to merge 2 commits intoAOSSIE-Org:mainfrom
hasanravda:feat/therapist-complete-registration

Conversation

@hasanravda
Copy link
Copy Markdown
Member

@hasanravda hasanravda commented Mar 12, 2026

Closes #192

📝 Description

During therapist registration, the storePersonalInfo insert payload was missing email and phone, both of which are NOT NULL in the therapist table. This caused a PostgrestException on every new therapist sign-up. This PR fixes the crash by sourcing email from the authenticated Google user and collecting phone via a new required input field in the registration form.

🔧 Changes Made

  • supabase_auth_repository.dart - added email (from currentUser.email) and phone (from param) to the insert payload in storePersonalInfo
  • auth_repository.dart - updated storePersonalInfo interface signature to require {required String phone}
  • auth_provider.dart - forwarded phone parameter through to the repository call
  • personal_details_screen.dart - added a required Phone Number input field to the registration form

✅ Checklist

  • I have read the contributing guidelines.
  • I have added tests that prove my fix is effective or that my feature works.
  • I have added necessary documentation (if applicable).
  • Any dependent changes have been merged and published in downstream modules.

Summary by CodeRabbit

Release Notes

  • New Features
    • Phone field now required in the personal details form
    • Added user sign-out functionality
    • Enhanced Google Sign-In integration with improved phone data handling

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 12, 2026

📝 Walkthrough

Walkthrough

The pull request adds phone number collection and validation to the therapist registration flow. Updates to the auth interface, UI form, provider layer, and repository implementation ensure phone is captured during sign-up and persisted alongside email to the database, addressing a null value constraint violation.

Changes

Cohort / File(s) Summary
Auth Interface Update
therapist/lib/core/repository/auth/auth_repository.dart
Updated storePersonalInfo signature to require named parameter phone; added new checkIfUserIsNew(String userId) method returning Future<ActionResult>.
UI Form Enhancement
therapist/lib/presentation/auth/personal_details_screen.dart
Added phone input field with controller and validation; integrated phone value into storePersonalInfo call as named parameter; added controller disposal.
Provider & Repository Implementation
therapist/lib/provider/auth_provider.dart, therapist/lib/repository/supabase_auth_repository.dart
Added userPhone getter and phone population from Google Sign-In data in provider; extended storePersonalInfo to accept phone parameter; added signOut() method; updated repository to include email and phone in therapist table insert payload and preserve is_new_user flag in sign-in response.

Sequence Diagram(s)

sequenceDiagram
    participant UI as PersonalDetailsScreen
    participant Provider as AuthProvider
    participant Repo as SupabaseAuthRepository
    participant DB as Therapist Table

    UI->>UI: User enters phone & submits form
    UI->>Provider: storePersonalInfo(personalInfo, phone: '+1234567890')
    Provider->>Repo: storePersonalInfo(personalInfo, phone: '+1234567890')
    Repo->>Repo: Validate current user exists
    Repo->>Repo: Build data map with id, email, phone + personalInfoEntity fields
    Repo->>DB: Insert therapist record with complete data
    DB-->>Repo: Success / Error
    Repo-->>Provider: Return ActionResult
    Provider-->>UI: Return bool success status
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 A phone field hops into the form today,
Email and therapist data here to stay,
No more null values causing crashes bright,
Registration now flows smooth and right! ✨📱

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The pull request successfully addresses all coding requirements from issue #192: email and phone are now included in the storePersonalInfo insert payload, phone is collected via UI, and the method signature is updated across all layers.
Out of Scope Changes check ✅ Passed All changes are directly aligned with issue #192 objectives. The addition of signOut method and userPhone getter in AuthProvider are related supporting changes for the registration flow.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title accurately summarizes the main change: adding email and phone fields to the therapist registration insert, which directly addresses the core fix across all modified files.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
📝 Coding Plan
  • Generate coding plan for human review comments

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (3)
therapist/lib/core/repository/auth/auth_repository.dart (1)

29-30: Remove leftover instruction comment and add proper documentation.

The comment "Add this new method" appears to be a leftover instruction rather than documentation. Consider replacing it with proper doc comments for the new method.

📝 Suggested fix
-  // Add this new method
+  /// Checks if the user with the given [userId] is new (not yet in the therapist table).
+  ///
+  /// Returns [ActionResultSuccess] with `is_new_user` boolean, or [ActionResultFailure] on error.
   Future<ActionResult> checkIfUserIsNew(String userId);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@therapist/lib/core/repository/auth/auth_repository.dart` around lines 29 -
30, Remove the leftover inline instruction comment "Add this new method" and
replace it with a concise Dart doc comment for the method declaration
checkIfUserIsNew(String userId) describing what the method does, the meaning of
the returned Future<ActionResult>, and any expectations for the userId parameter
(e.g., non-null/format). Locate the declaration of Future<ActionResult>
checkIfUserIsNew in the auth repository interface/class and add a /// comment
above it that documents behavior, inputs, and output rather than leaving an
instruction-style comment.
therapist/lib/presentation/auth/personal_details_screen.dart (1)

190-201: Consider adding phone number format validation.

The current validation only checks for empty input. Adding basic format validation (e.g., minimum length, digits-only check) would prevent obviously invalid entries from being stored.

♻️ Suggested phone validation improvement
                 validator: (value) {
                   if (value == null || value.trim().isEmpty) {
                     return 'Please enter your phone number';
                   }
+                  final digitsOnly = value.replaceAll(RegExp(r'[^0-9]'), '');
+                  if (digitsOnly.length < 7 || digitsOnly.length > 15) {
+                    return 'Please enter a valid phone number';
+                  }
                   return null;
                 },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@therapist/lib/presentation/auth/personal_details_screen.dart` around lines
190 - 201, The phone field validator currently only checks for emptiness; update
the validator passed to _buildTextField (where phoneController is used) to also
enforce a basic phone format: trim the value, remove allowed characters (spaces,
dashes, parentheses, optional leading '+'), then check that the remaining
characters are all digits and meet a minimum length (e.g., >=7) and maximum
(e.g., <=15); return specific error messages like "Please enter a valid phone
number" when the checks fail and null when valid.
therapist/lib/repository/supabase_auth_repository.dart (1)

111-111: Replace print statements with proper logging.

Production code should use a logging framework (e.g., package:logging) or at minimum debugPrint which is no-op in release mode. The current print calls will appear in production logs.

Also applies to: 126-126, 136-136, 172-172

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@therapist/lib/repository/supabase_auth_repository.dart` at line 111, Replace
all print(...) calls inside SupabaseAuthRepository with a proper logger: add
import 'package:logging/logging.dart'; create a private Logger (e.g., final
_logger = Logger('SupabaseAuthRepository')) and replace prints at the locations
mentioned (around lines where methods like signIn/signUp/signOut/getCurrentUser
are implemented) with appropriate log levels such as _logger.warning(...) or
_logger.severe(...). Alternatively, if you prefer framework-safe no-op in
release builds, use Flutter's debugPrint(...) instead of print(...); ensure
consistent usage across the four occurrences referenced.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@therapist/lib/provider/auth_provider.dart`:
- Around line 137-149: The signOut method currently swallows all exceptions and
always clears local auth state; change it so the catch captures the exception
and stack trace (e.g., catch (e, st)) and logs them (use debugPrint or your app
Logger) instead of an empty block, and only clear/reset _isAuthenticated,
_userId, _userEmail, _userPhone, _userName, and _isNewUser (and call
notifyListeners()) after a successful sign-out attempt (i.e., after await
GoogleSignIn().signOut() / await _supabaseClient.auth.signOut() complete); if
sign-out fails, log the error and keep current local state or surface the error
to the caller.

In `@therapist/lib/repository/supabase_auth_repository.dart`:
- Around line 119-124: The map construction for `data` currently spreads
`personalInfoEntity.toMap()` after explicit keys which allows its `id` to
overwrite `currentUser.id`; change the order so `...personalInfoEntity.toMap()`
comes before the explicit fields (`'id': currentUser.id`, `'email':
currentUser.email ?? ''`, `'phone': phone`) so the explicit values in the `data`
map take precedence (alternatively remove `id` from `personalInfoEntity.toMap()`
if that better fits the domain).
- Line 121: The code currently writes 'email': currentUser.email ?? '' which
silently stores an empty string and can violate data integrity; update the
method that builds the user record (e.g., the function/method that references
currentUser.email in SupabaseAuthRepository—look for the record creation/update
logic in SupabaseAuthRepository or the method name that inserts the user) to
explicitly validate currentUser.email and fail fast: if currentUser.email is
null/empty throw or return a clear error/result indicating missing email instead
of writing an empty string, and adjust callers to handle that error path
accordingly so no invalid empty-email rows are inserted.

---

Nitpick comments:
In `@therapist/lib/core/repository/auth/auth_repository.dart`:
- Around line 29-30: Remove the leftover inline instruction comment "Add this
new method" and replace it with a concise Dart doc comment for the method
declaration checkIfUserIsNew(String userId) describing what the method does, the
meaning of the returned Future<ActionResult>, and any expectations for the
userId parameter (e.g., non-null/format). Locate the declaration of
Future<ActionResult> checkIfUserIsNew in the auth repository interface/class and
add a /// comment above it that documents behavior, inputs, and output rather
than leaving an instruction-style comment.

In `@therapist/lib/presentation/auth/personal_details_screen.dart`:
- Around line 190-201: The phone field validator currently only checks for
emptiness; update the validator passed to _buildTextField (where phoneController
is used) to also enforce a basic phone format: trim the value, remove allowed
characters (spaces, dashes, parentheses, optional leading '+'), then check that
the remaining characters are all digits and meet a minimum length (e.g., >=7)
and maximum (e.g., <=15); return specific error messages like "Please enter a
valid phone number" when the checks fail and null when valid.

In `@therapist/lib/repository/supabase_auth_repository.dart`:
- Line 111: Replace all print(...) calls inside SupabaseAuthRepository with a
proper logger: add import 'package:logging/logging.dart'; create a private
Logger (e.g., final _logger = Logger('SupabaseAuthRepository')) and replace
prints at the locations mentioned (around lines where methods like
signIn/signUp/signOut/getCurrentUser are implemented) with appropriate log
levels such as _logger.warning(...) or _logger.severe(...). Alternatively, if
you prefer framework-safe no-op in release builds, use Flutter's debugPrint(...)
instead of print(...); ensure consistent usage across the four occurrences
referenced.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d3c6879e-cb76-4fbb-9043-c899e635ac34

📥 Commits

Reviewing files that changed from the base of the PR and between 051a4f3 and 844d8bf.

📒 Files selected for processing (4)
  • therapist/lib/core/repository/auth/auth_repository.dart
  • therapist/lib/presentation/auth/personal_details_screen.dart
  • therapist/lib/provider/auth_provider.dart
  • therapist/lib/repository/supabase_auth_repository.dart

Comment on lines +137 to +149
Future<void> signOut() async {
try {
if (!kIsWeb) await GoogleSignIn().signOut();
await _supabaseClient.auth.signOut();
} catch (_) {}
_isAuthenticated = false;
_userId = null;
_userEmail = null;
_userPhone = '';
_userName = '';
_isNewUser = true;
notifyListeners();
}
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 | 🟡 Minor

Empty catch block silently swallows sign-out errors.

The catch (_) {} block discards all exceptions without logging. If sign-out fails (e.g., network issue), the user won't know and local state will still be cleared, potentially causing inconsistency.

🔧 Suggested improvement
   Future<void> signOut() async {
     try {
       if (!kIsWeb) await GoogleSignIn().signOut();
       await _supabaseClient.auth.signOut();
-    } catch (_) {}
+    } catch (e) {
+      debugPrint('Sign out error: $e');
+      // Continue to clear local state even on error
+    }
     _isAuthenticated = false;
📝 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
Future<void> signOut() async {
try {
if (!kIsWeb) await GoogleSignIn().signOut();
await _supabaseClient.auth.signOut();
} catch (_) {}
_isAuthenticated = false;
_userId = null;
_userEmail = null;
_userPhone = '';
_userName = '';
_isNewUser = true;
notifyListeners();
}
Future<void> signOut() async {
try {
if (!kIsWeb) await GoogleSignIn().signOut();
await _supabaseClient.auth.signOut();
} catch (e) {
debugPrint('Sign out error: $e');
// Continue to clear local state even on error
}
_isAuthenticated = false;
_userId = null;
_userEmail = null;
_userPhone = '';
_userName = '';
_isNewUser = true;
notifyListeners();
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@therapist/lib/provider/auth_provider.dart` around lines 137 - 149, The
signOut method currently swallows all exceptions and always clears local auth
state; change it so the catch captures the exception and stack trace (e.g.,
catch (e, st)) and logs them (use debugPrint or your app Logger) instead of an
empty block, and only clear/reset _isAuthenticated, _userId, _userEmail,
_userPhone, _userName, and _isNewUser (and call notifyListeners()) after a
successful sign-out attempt (i.e., after await GoogleSignIn().signOut() / await
_supabaseClient.auth.signOut() complete); if sign-out fails, log the error and
keep current local state or surface the error to the caller.

@hasanravda hasanravda changed the title Feat/therapist complete registration Fix therapist registration by including email and phone in insert Mar 12, 2026
@hasanravda
Copy link
Copy Markdown
Member Author

@jddeep Can you review this ! As this is solving the issue that is critical during registration.

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.

BUG: null email causes PostgreSQL NOT NULL violation during therapist registration

1 participant