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

User creation form bug fix #9404

Conversation

Jacobjeevan
Copy link
Contributor

@Jacobjeevan Jacobjeevan commented Dec 13, 2024

Proposed Changes

@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

Summary by CodeRabbit

  • New Features

    • Local body selection field in the User Add/Edit form now conditionally renders based on user type.
  • Bug Fixes

    • Removed weekly_working_hours and video_connect_link as required fields for new user creation.
  • Documentation

    • Updated validation logic to reflect changes in required fields for new user creation.

Copy link
Contributor

coderabbitai bot commented Dec 13, 2024

Walkthrough

The changes in this pull request modify the rendering logic of the local body selection field in the UserAddEditForm component, ensuring it is displayed conditionally based on the showLocalbody variable. Additionally, the UserFormValidations.tsx file has been updated to remove the weekly_working_hours and video_connect_link fields from the newUserFields array, indicating these fields are no longer required for new user creation. The validation logic for existing fields remains unchanged.

Changes

File Change Summary
src/components/Users/UserAddEditForm.tsx Modified rendering logic for the local body field to depend on showLocalbody and includedFields.
src/components/Users/UserFormValidations.tsx Removed weekly_working_hours and video_connect_link from newUserFields; retained in edit fields.

Assessment against linked issues

Objective Addressed Explanation
Hide the Average Working Hour and video conference link from the user creation form (9403)
Hide local body field from the user creation form for specific user types (9403)

Possibly related PRs

Suggested labels

needs review, tested

Suggested reviewers

  • rithviknishad

Poem

In fields of code, where changes bloom,
A rabbit hops, dispelling gloom.
With local bodies now tucked away,
New users find a brighter day.
Validation's dance, a gentle sway,
In our form, all's well, hooray! 🐇✨


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. (Experiment)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary 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 Dec 13, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 3ce8af5
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/675bc902d8781e0008abdbba
😎 Deploy Preview https://deploy-preview-9404--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 December 13, 2024 05:54
@Jacobjeevan Jacobjeevan requested a review from a team as a code owner December 13, 2024 05:54
@Jacobjeevan Jacobjeevan added needs testing needs review P1 breaking issue or vital feature labels Dec 13, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (4)
src/components/Users/UserAddEditForm.tsx (4)

Line range hint 1182-1203: Consider clearing local body value when hidden

While the conditional rendering of the local body field is correct, consider clearing the local_body value in the form state when showLocalbody becomes false to prevent any stale values from being submitted.

 {showLocalbody && includedFields?.includes("local_body") && (
   <>
     {isLocalbodyLoading ? (
       <CircularProgress />
     ) : (
       <SelectFormField
         {...field("local_body")}
         label={t("local_body")}
         required
         position="above"
         placeholder={t("choose_localbody")}
         options={localBodies}
         optionLabel={(o) => o.name}
         optionValue={(o) => o.id}
         onChange={(e) => {
           handleFieldChange(e, field);
+          if (!showLocalbody) {
+            dispatch({
+              type: "set_form",
+              form: {
+                ...state.form,
+                local_body: 0,
+              },
+            });
+          }
         }}
         aria-label={t("local_body")}
       />
     )}
   </>
 )}

Line range hint 516-529: Enhance phone number validation

The current phone number validation could be more robust. Consider adding additional checks for:

  • Country code validation
  • Minimum and maximum length validation
  • Format validation for different phone number types (mobile vs landline)
 const validatePhoneNumber = (phoneNumber: string) => {
   const parsedPhoneNumber = parsePhoneNumber(phoneNumber);
   if (!parsedPhoneNumber) return false;
-  return PhoneNumberValidator()(parsedPhoneNumber) === undefined;
+  const baseValidation = PhoneNumberValidator()(parsedPhoneNumber) === undefined;
+  if (!baseValidation) return false;
+  
+  // Additional validation rules
+  const phoneNumberWithoutCountryCode = parsedPhoneNumber.replace(/^\+\d{1,3}/, '');
+  const isValidLength = phoneNumberWithoutCountryCode.length >= 10 && phoneNumberWithoutCountryCode.length <= 12;
+  const hasValidFormat = /^\+\d{1,3}\d{10,12}$/.test(parsedPhoneNumber);
+  
+  return isValidLength && hasValidFormat;
 };

Line range hint 1-1203: Consider breaking down the component for better maintainability

The component is quite large and handles multiple responsibilities. Consider:

  1. Breaking down form sections into separate components
  2. Moving validation logic to a separate utility file
  3. Creating a custom hook for form state management

This would improve maintainability, testability, and reusability.

Example structure:

// components/Users/Form/Sections/PersonalInfo.tsx
// components/Users/Form/Sections/ContactInfo.tsx
// components/Users/Form/Sections/LocationInfo.tsx
// components/Users/Form/Sections/Credentials.tsx

// hooks/useUserForm.ts
// utils/userValidation.ts

Line range hint 533-614: Improve form error handling UX

While the validation is thorough, consider enhancing the user experience by:

  1. Adding inline validation feedback as users type
  2. Showing a summary of all errors at the top of the form
  3. Automatically scrolling to the first error field
 const validateForm = (formData: UserForm) => {
   const errors: Partial<Record<keyof UserForm, FieldError>> = {};
   const fieldsToValidate = includedFields || Object.keys(formData);
+  const errorSummary: string[] = [];
   const facilityError = fieldsToValidate.includes("facilities")
     ? validateFacility(formData, selectedFacility)
     : null;
   if (facilityError) {
     errors.facilities = facilityError;
+    errorSummary.push(facilityError);
   }
+  
+  // Scroll to first error
+  if (Object.keys(errors).length > 0) {
+    const firstErrorField = document.querySelector(`[name="${Object.keys(errors)[0]}"]`);
+    firstErrorField?.scrollIntoView({ behavior: 'smooth', block: 'center' });
+  }
+
+  return { errors, errorSummary };
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ead041b and 3ce8af5.

📒 Files selected for processing (2)
  • src/components/Users/UserAddEditForm.tsx (1 hunks)
  • src/components/Users/UserFormValidations.tsx (0 hunks)
💤 Files with no reviewable changes (1)
  • src/components/Users/UserFormValidations.tsx

@nihal467
Copy link
Member

LGTM

@nihal467
Copy link
Member

LGTM

@rithviknishad rithviknishad merged commit 2611a32 into ohcnetwork:develop Dec 13, 2024
24 checks passed
Copy link

@Jacobjeevan Your efforts have helped advance digital healthcare and TeleICU systems. 🚀 Thank you for taking the time out to make CARE better. We hope you continue to innovate and contribute; your impact is immense! 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs review P1 breaking issue or vital feature tested
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Refactor New User Creation Form to Restore Conditional Checks and Hide Unnecessary Field
3 participants