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

Edit User Details #10027

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from

Conversation

Jacobjeevan
Copy link
Contributor

@Jacobjeevan Jacobjeevan commented Jan 17, 2025

Proposed Changes

  • Fixes Add Edit profile support in the user profile page #9957
  • Currently only supports editing for logged in user, need to wire up permissions (this needs to be done for other options as well, such as add/link user/edit user role etc).
  • To do: Modify Backend to store and support the following: alt phone number, qualification, doctor experience, medical council registration number.

image

image

image

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Copy link
Contributor

coderabbitai bot commented Jan 17, 2025

Walkthrough

This pull request introduces comprehensive enhancements to user management functionality across multiple components. The changes include adding localization support for user-related actions, creating a new EditUserSheet component, refactoring the UserForm to support both user creation and editing, and introducing new type definitions for user models. The modifications enable more flexible user profile management, with improved internationalization and a more dynamic form handling approach.

Changes

File Change Summary
public/locale/en.json Added localization keys for user management actions like "Add User", "Edit User", "Update User"
src/common/constants.tsx Added new GENDERS constant derived from GENDER_TYPES
src/components/Patient/PatientRegistration.tsx Removed local GENDERS definition, now importing from constants
src/components/Users/UserForm.tsx Renamed from CreateUserForm, added support for editing existing users
src/components/Users/UserSummary.tsx Added EditUserSheet integration for user editing
src/pages/Organization/components/AddUserSheet.tsx Updated to use internationalization and new UserForm
src/pages/Organization/components/EditUserRoleSheet.tsx Added EditUserSheet component
src/pages/Organization/components/EditUserSheet.tsx New component for editing user details
src/types/user/user.ts Added CreateUserModel and UpdateUserModel types
src/types/user/userApi.ts Updated API definitions for user creation and update

Assessment against linked issues

Objective Addressed Explanation
Allow users to edit own profile
Allow admins to edit profile of anyone in org

Possibly related PRs

Suggested labels

needs review, tested, urgent

Suggested reviewers

  • rithviknishad

Poem

🐰 A rabbit's tale of user might,
Editing profiles with pure delight
Forms that dance, translations bright
Flexibility is our coding knight
User management takes its flight! 🚀

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Jan 17, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 068e075
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/678a02e528574f00080758bb
😎 Deploy Preview https://deploy-preview-10027--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@Jacobjeevan Jacobjeevan marked this pull request as ready for review January 17, 2025 11:21
@Jacobjeevan Jacobjeevan requested a review from a team as a code owner January 17, 2025 11:21
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🔭 Outside diff range comments (1)
src/components/Users/UserForm.tsx (1)

Line range hint 53-109: Review conditional schema for consistency and completeness

The form schema conditionally makes several fields optional based on isEditMode. While this allows flexibility, please verify:

  • All required fields are enforced correctly in both modes.
  • Optional fields in edit mode still validate correctly if provided.
  • Conditional logic does not introduce unintended side effects.
🧹 Nitpick comments (12)
src/components/Users/UserForm.tsx (8)

2-2: Consider removing unused import useQuery

The useQuery import from @tanstack/react-query is not used in this section of the code. Removing unused imports can help keep the code clean and improve readability.

-import { useMutation, useQuery } from "@tanstack/react-query";
+import { useMutation } from "@tanstack/react-query";

124-130: Handle potential query issues when fetching user data

The useQuery hook depends on existingUsername. Ensure that existingUsername is defined before initiating the query to prevent unnecessary network requests or errors.

Consider adding a check to prevent the query from running if existingUsername is undefined or empty.


132-146: Remove debug statements from production code

The console.log(userData); statement is useful for debugging but should be removed to keep the console clean in production.

- console.log(userData);

157-160: Optimize form triggering for better performance

The form.trigger("username"); is called inside a useEffect without specifying dependencies strictly. This could lead to unnecessary re-renders or validations.

Ensure that form.trigger("username"); is only called when necessary, possibly by adjusting the dependencies of the useEffect.


206-216: Enhance error handling for user creation

The createUser mutation lacks detailed error handling. Consider capturing specific error messages from the API to provide more informative feedback to the user.

You could access error.response.data if available to display validation errors returned from the server.


218-230: Implement comprehensive error handling for user updates

Similarly, the updateUser mutation could benefit from enhanced error handling to provide users with specific feedback when an update fails.


246-247: Remove leftover console logs

There is a console.log(form.formState.errors); statement that should be removed to clean up the code.

- console.log(form.formState.errors);

318-369: Confirm password update flow

Password fields are hidden in edit mode, meaning users cannot change their passwords through this form. If password updates are required, consider adding functionality to handle password changes securely.

If implementing password updates, ensure that current password verification and appropriate security measures are in place.

src/pages/Organization/components/EditUserSheet.tsx (2)

15-20: Props interface looks good, but consider adding validation props.

The interface is well-structured. Consider adding validation props to handle cases where editing might be restricted.

 interface EditUserSheetProps {
   existingUsername: string;
   open: boolean;
   setOpen: (open: boolean) => void;
   onUserUpdated?: (user: UserBase) => void;
+  isEditable?: boolean;
+  validationError?: string;
 }

31-34: Add ARIA labels for better accessibility.

The sheet content should have appropriate ARIA labels for screen readers.

       <SheetContent
         className="w-full sm:max-w-2xl overflow-y-auto"
         data-cy="add-user-form"
+        aria-label={t("edit_user_form")}
       >
src/components/Users/UserSummary.tsx (1)

110-120: Consider adding loading state to the edit button.

The edit button should reflect loading state during user updates.

           <Button
             variant="outline"
             className="w-fit self-end"
             data-cy="edit-user-button"
+            disabled={isUpdating}
             onClick={() => setShowEditUserSheet(true)}
           >
             <CareIcon icon="l-pen" className="mr-2 h-4 w-4" />
-            {t("edit_user")}
+            {isUpdating ? t("updating") : t("edit_user")}
           </Button>
src/pages/Organization/components/EditUserRoleSheet.tsx (1)

249-258: Move edit button next to user info for better UX.

Consider relocating the edit button to be closer to the user information section for improved user experience.

The edit button would be more intuitive if placed near the user's details (around line 154) rather than at the bottom of the action buttons.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bef340f and 068e075.

📒 Files selected for processing (10)
  • public/locale/en.json (5 hunks)
  • src/common/constants.tsx (1 hunks)
  • src/components/Patient/PatientRegistration.tsx (1 hunks)
  • src/components/Users/UserForm.tsx (9 hunks)
  • src/components/Users/UserSummary.tsx (3 hunks)
  • src/pages/Organization/components/AddUserSheet.tsx (3 hunks)
  • src/pages/Organization/components/EditUserRoleSheet.tsx (3 hunks)
  • src/pages/Organization/components/EditUserSheet.tsx (1 hunks)
  • src/types/user/user.ts (1 hunks)
  • src/types/user/userApi.ts (2 hunks)
🧰 Additional context used
📓 Learnings (1)
src/components/Users/UserForm.tsx (1)
Learnt from: rajku-dev
PR: ohcnetwork/care_fe#9887
File: src/components/Users/CreateUserForm.tsx:93-93
Timestamp: 2025-01-14T09:22:13.878Z
Learning: In CreateUserForm.tsx, the gender validation schema uses string literals that match GENDER_TYPES.map(g => g.id). Using GENDER_TYPES directly with z.enum() fails because it's marked with 'as const' which makes it a readonly tuple type incompatible with Zod's enum.
🔇 Additional comments (18)
src/components/Users/UserForm.tsx (7)

44-44: Ensure existingUsername is passed as a prop when in edit mode

The existingUsername prop is added to determine edit mode. Verify that this prop is correctly passed from the parent component when editing a user to prevent unexpected behavior.


49-49: Confirm the reliability of the isEditMode check

The isEditMode flag uses double negation on existingUsername. Ensure that existingUsername is reliably defined (not an empty string or falsy value) when in edit mode to prevent logic errors.


94-96: Re-evaluate optional geo_organization field in edit mode

The geo_organization field is optional in edit mode. Confirm if the organization should be editable or required when updating a user, as changing a user's organization might have significant implications.


168-168: Prevent username availability check in edit mode

The username availability check should not run in edit mode, as the username is not intended to be changed. The enabled condition already accounts for this, but double-check to ensure it's functioning as expected.


251-278: Review conditional rendering of user type selection

The user type selection is hidden in edit mode. Ensure that this aligns with the application's requirements. If user roles should be editable, consider displaying this field when appropriate permissions are granted.


552-568: Validate the necessity of geo_organization in edit mode

The geo_organization field is conditionally rendered only in create mode. Confirm whether users should be able to change their organization during an edit. If so, adjust the form to allow editing this field.


571-573: Button label correctly reflects the form mode

The submit button label changes based on isEditMode, which enhances user experience by providing appropriate context.

src/types/user/userApi.ts (2)

15-15: Update TBody to use CreateUserModel

Changing TBody to CreateUserModel in the create method ensures that the correct data structure is used when creating a user.


27-32: Add update method to userApi

The update method allows for updating user data via a PUT request. Ensure that the backend supports this endpoint and that it properly handles partial updates.

Double-check if Partial<UpdateUserModel> aligns with the backend expectations. If the backend supports PATCH requests for partial updates, consider using HttpMethod.PATCH instead.

src/types/user/user.ts (2)

18-33: Define CreateUserModel for user creation

The CreateUserModel type includes all necessary fields for creating a new user, which improves type safety and clarity.


35-35: Review fields excluded in UpdateUserModel

The UpdateUserModel omits username and password, indicating these fields are not updatable. Verify if users should be able to change their passwords or usernames, and adjust the model accordingly.

src/pages/Organization/components/AddUserSheet.tsx (2)

44-45: LGTM! Good use of translations.

The translation keys are descriptive and follow the established pattern.


Line range hint 48-53: Verify UserForm compatibility.

The switch from CreateUserForm to UserForm needs verification to ensure all creation-specific functionality is preserved.

✅ Verification successful

The switch to UserForm is compatible and safe

The UserForm component is a unified implementation that handles both user creation and editing. When used without the existingUsername prop (as in AddUserSheet), it operates in creation mode with all the necessary functionality preserved.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if UserForm maintains all props from CreateUserForm
ast-grep --pattern 'interface $interface {
  $$$
}' | grep -A 10 'CreateUserForm|UserForm'

Length of output: 92


Script:

#!/bin/bash
# Find both component definitions and their types
echo "=== Searching for UserForm ==="
rg "UserForm" -A 5 -B 5

echo -e "\n=== Searching for CreateUserForm ==="
rg "CreateUserForm" -A 5 -B 5

echo -e "\n=== Looking for type definitions ==="
ast-grep --pattern 'type $name = {
  $$$
}'

ast-grep --pattern 'export const $name: FC<{
  $$$
}>'

Length of output: 12532

src/components/Users/UserSummary.tsx (1)

103-108: LGTM! Clean integration of EditUserSheet.

The component integration is well-structured and maintains proper prop passing.

src/pages/Organization/components/EditUserRoleSheet.tsx (1)

124-125: LGTM! Good permission handling.

The use of useAuthUser and editUserPermissions follows best practices for permission management.

src/common/constants.tsx (1)

107-109: LGTM! Well-implemented constant definition.

The implementation follows best practices by:

  • Maintaining type safety with proper TypeScript types
  • Reusing the existing GENDER_TYPES constant
  • Following the established pattern in the codebase
src/components/Patient/PatientRegistration.tsx (1)

48-48: LGTM! Good refactoring to use centralized constant.

The change improves maintainability by using the centralized GENDERS constant instead of a local definition.

public/locale/en.json (1)

352-352: LGTM! Well-structured localization additions.

The new localization keys follow consistent naming patterns and provide clear, descriptive messages for user management functionality.

Also applies to: 702-702, 830-830, 2114-2114, 2152-2152

src/components/Users/UserForm.tsx Show resolved Hide resolved
Comment on lines +233 to +237
if (isEditMode) {
updateUser({
...data,
} as UpdateUserModel);
} else {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure correct data is sent in the update request

When updating a user, all fields from data are being sent. If the API expects only changed fields, consider sending only the modified fields to prevent unintended data overwrites.

Consider using diff or selectively including fields:

const updatedFields = { /* include only the fields that have changed */ };
updateUser(updatedFields as UpdateUserModel);

src/components/Users/UserForm.tsx Show resolved Hide resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add Edit profile support in the user profile page
1 participant