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

robustify UserCreateForm #9852

Closed
wants to merge 10 commits into from

Conversation

rajku-dev
Copy link
Contributor

@rajku-dev rajku-dev commented Jan 8, 2025

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

    • Added comprehensive validation messages for user inputs.
    • Enhanced form validation for date of birth, phone number, and username.
    • Expanded gender options in user creation form.
    • Introduced optional date disabling in DatePicker component.
  • Bug Fixes

    • Prevented negative age input in patient registration.
    • Improved form submission logic to disable buttons when no changes are made.
  • Localization

    • Added new translation entries for validation messages in English locale.

@rajku-dev rajku-dev requested a review from a team as a code owner January 8, 2025 16:52
Copy link
Contributor

coderabbitai bot commented Jan 8, 2025

Walkthrough

This pull request introduces comprehensive validation improvements across multiple components and localization files. The changes focus on enhancing user input validation for forms, particularly in user creation, patient registration, and form submissions. Key improvements include adding validation messages for username, phone number, and date of birth fields, preventing future date selections, disabling submit buttons when no changes are made, and ensuring non-negative age inputs.

Changes

File Change Summary
public/locale/en.json Added multiple validation messages for username, phone number, date of birth, and required fields
src/components/Users/CreateUserForm.tsx Updated form validation, added mutation hook, enhanced error handling and localization
src/components/ui/date-picker.tsx Added optional disabled prop to control date selection
src/types/user/user.ts Introduced new UserCreateRequest type
src/types/user/userApi.ts Updated API request body type to use UserCreateRequest
src/components/Facility/FacilityCreate.tsx Modified submit button to disable when form is not dirty
src/components/Schedule/ScheduleExceptionForm.tsx Updated submit button disabled state logic
src/components/Patient/PatientRegistration.tsx Improved age input validation to prevent negative values

Assessment against linked issues

Objective Addressed Explanation
Disable submit button using isDirty
Prevent future Date of Birth
Phone number validation (+91 and 10 digits)
Prevent negative age values

Possibly related PRs

Suggested labels

needs review, needs testing, P1

Suggested reviewers

  • Jacobjeevan
  • rithviknishad

Poem

🐰 Validation's dance, a rabbit's delight,
Forms now shine with rules so bright!
No future dates or negative age,
Our inputs dance upon the page.
CodeRabbit's magic makes forms clean and tight! 🎉


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 8, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit b59e80a
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67814b7f87cdd200082eaf8b
😎 Deploy Preview https://deploy-preview-9852--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.

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/CreateUserForm.tsx (1)

Line range hint 112-114: Initialize alt_phone_number to an empty string to prevent incomplete submissions.

Setting the default value of alt_phone_number to "+91" may result in submitting an incomplete phone number if the user doesn't modify this field. Initializing it to an empty string ensures that validation will prompt the user if necessary.

Apply this diff to correct the default value:

        defaultValues: {
          user_type: "staff",
          phone_number: "+91",
-         alt_phone_number: "+91",
+         alt_phone_number: "",
          phone_number_is_whatsapp: true,
          gender: "male",
        },
🧹 Nitpick comments (1)
src/components/Users/CreateUserForm.tsx (1)

83-85: Ensure date comparison for date_of_birth excludes time component.

Comparing date_of_birth directly with new Date() includes time components, which may cause issues due to time zone differences. To accurately validate dates, compare only the date parts.

Apply this diff to refine the date comparison:

         .refine((dob) => dob <= new Date(), {
           message: t("date_of_birth_cannot_be_in_future"),
         }),
+        .refine((dob) => dob >= new Date("1900-01-01"), {
+          message: t("date_of_birth_cannot_be_before_1900"),
+        }),

Alternatively, strip the time component when performing the comparison.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8bec8bc and 2f7d401.

📒 Files selected for processing (5)
  • public/locale/en.json (4 hunks)
  • src/components/Users/CreateUserForm.tsx (13 hunks)
  • src/components/ui/date-picker.tsx (2 hunks)
  • src/types/user/user.ts (1 hunks)
  • src/types/user/userApi.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (5)
src/types/user/userApi.ts (1)

4-4: LGTM!

The request body type for the create endpoint has been correctly updated to UserCreateRequest, ensuring the API call aligns with the expected data structure.

Also applies to: 16-16

src/components/ui/date-picker.tsx (1)

19-19: Well-implemented date validation enhancement!

The addition of the disabled prop is a clean and flexible solution that:

  • Provides a type-safe way to implement date validation
  • Follows React's functional programming patterns
  • Properly propagates the validation to the underlying Calendar component

Also applies to: 22-22, 48-48

public/locale/en.json (3)

672-672: LGTM: Clear date validation message!

The message is user-friendly and clearly explains the validation rule.


1420-1420: LGTM: Clear phone number format requirement!

The message explicitly states the expected format (+91 followed by 10 digits).


1868-1873: LGTM: Comprehensive username validation messages!

The messages clearly explain all username requirements:

  • Length constraints (4-16 characters)
  • Allowed characters (lowercase, numbers, dots, underscores, hyphens)
  • Special character rules (no consecutive ones, must start/end with alphanumeric)

src/components/Users/CreateUserForm.tsx Show resolved Hide resolved
src/components/Users/CreateUserForm.tsx Show resolved Hide resolved
src/components/Users/CreateUserForm.tsx Show resolved Hide resolved
src/types/user/user.ts Show resolved Hide resolved
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: 3

🧹 Nitpick comments (2)
src/components/Schedule/ScheduleExceptionForm.tsx (1)

255-259: Good addition of form dirty state check!

The addition of form.formState.isDirty check prevents unnecessary form submissions and provides better UX feedback. Consider adding a tooltip to explain why the button is disabled when the form is pristine.

 <Button
   variant="primary"
   type="submit"
   disabled={isPending || !form.formState.isDirty}
+  title={!form.formState.isDirty ? "No changes to save" : ""}
 >
src/components/Facility/FacilityCreate.tsx (1)

Line range hint 255-259: Consider form-specific state management patterns.

The addition of form dirty state checks shows a good intention to prevent unnecessary submissions. However, the implementation should be adjusted based on the form's purpose:

  1. For edit/update forms: Keep the dirty state check
  2. For create forms: Use validation state instead
  3. For dual-purpose forms: Apply conditional logic

This will provide a more intuitive user experience across different form types.

Also applies to: 322-326, 421-425, 506-510

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2f7d401 and 27e1e0d.

📒 Files selected for processing (4)
  • src/components/Encounter/CreateEncounterForm.tsx (1 hunks)
  • src/components/Facility/CreateFacilityForm.tsx (1 hunks)
  • src/components/Facility/FacilityCreate.tsx (1 hunks)
  • src/components/Schedule/ScheduleExceptionForm.tsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: OSSAR-Scan

src/components/Encounter/CreateEncounterForm.tsx Outdated Show resolved Hide resolved
src/components/Facility/CreateFacilityForm.tsx Outdated Show resolved Hide resolved
src/components/Facility/FacilityCreate.tsx Show resolved Hide resolved
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: 1

🔭 Outside diff range comments (1)
src/components/Patient/PatientRegistration.tsx (1)

Consider splitting the PatientRegistration component for better maintainability

The component, while functional, handles too many responsibilities and could benefit from being split into smaller, focused components:

  • Create separate components for each form section (general info, address, contact details)
  • Extract form state management logic into custom hooks
  • Consider using form management libraries like react-hook-form or formik

The application already has proper error boundaries at the router level and adequate security measures in place.

🔗 Analysis chain

Line range hint 1-1000: Consider architectural improvements for better maintainability and security.

  1. The component is handling too many responsibilities. Consider splitting it into smaller components for each section.
  2. Add server-side validation to complement client-side validation.
  3. Implement error boundaries to gracefully handle rendering failures.
  4. Consider adding CSRF protection to mutations.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for CSRF token usage in API calls
rg -A 5 "useMutation|useQuery" | rg "csrf"

# Check component size and complexity
ast-grep --pattern 'export default function PatientRegistration' -A 1000 | wc -l

Length of output: 127


Script:

#!/bin/bash
# Check request utilities for CSRF implementation
rg -p "csrf" src/Utils/request/

# Check component size with a more specific pattern
rg -p "^export default function PatientRegistration" -A 1000 "src/components/Patient/PatientRegistration.tsx"

# Look for error boundary implementations
rg -p "ErrorBoundary" src/

Length of output: 32332


Script:

#!/bin/bash
# Check request utilities implementation
rg -p "mutate|query" "src/Utils/request/"

# Check for any security headers or tokens in API calls
rg -p "headers|token" "src/Utils/request/"

Length of output: 5920

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 27e1e0d and a596d2f.

📒 Files selected for processing (1)
  • src/components/Patient/PatientRegistration.tsx (1 hunks)
🔇 Additional comments (1)
src/components/Patient/PatientRegistration.tsx (1)

Line range hint 1-1000: Add comprehensive test coverage.

The component lacks test coverage for critical functionality:

  • Age validation and year calculation
  • Form submission and error handling
  • Duplicate patient detection
  • Phone number validation

Would you like me to help create a test suite for this component? I can generate comprehensive tests covering all the critical paths.

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Jan 9, 2025
Copy link

github-actions bot commented Jan 9, 2025

👋 Hi, @rajku-dev,
Conflicts have been detected against the base branch. Please rebase your branch against the base branch.


This message is automatically generated by prince-chrismc/label-merge-conflicts-action so don't hesitate to report issues/improvements there.

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

🧹 Nitpick comments (1)
src/components/Users/CreateUserForm.tsx (1)

89-95: Enhance date of birth validation.

The date validation correctly prevents future dates but could be improved by:

  1. Adding a reasonable minimum date (e.g., 120 years ago)
  2. Adding a minimum age requirement if applicable
  date_of_birth: z
    .date({
      required_error: t("this_field_is_required"),
    })
    .refine((dob) => dob <= new Date(), {
      message: t("date_of_birth_cannot_be_in_future"),
+   })
+   .refine((dob) => dob >= new Date(new Date().setFullYear(new Date().getFullYear() - 120)), {
+     message: t("date_of_birth_too_old"),
+   })
+   .refine((dob) => dob <= new Date(new Date().setFullYear(new Date().getFullYear() - 13)), {
+     message: t("minimum_age_required"),
    }),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a596d2f and 9bad651.

📒 Files selected for processing (4)
  • public/locale/en.json (4 hunks)
  • src/components/Facility/CreateFacilityForm.tsx (1 hunks)
  • src/components/Users/CreateUserForm.tsx (14 hunks)
  • src/types/user/userApi.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/types/user/userApi.ts
  • src/components/Facility/CreateFacilityForm.tsx
🧰 Additional context used
🪛 GitHub Check: lint
src/components/Users/CreateUserForm.tsx

[failure] 3-3:
Replace Loader2·}·from·"lucide-react with useQuery·}·from·"@tanstack/react-query


[failure] 4-4:
Replace useQuery·}·from·"@tanstack/react-query with Loader2·}·from·"lucide-react


[failure] 37-37:
Replace ⏎import·mutate·from·"@/Utils/request/mutate";⏎import·*·as·Notification·from·"@/Utils/Notifications with import·*·as·Notification·from·"@/Utils/Notifications";⏎import·mutate·from·"@/Utils/request/mutate

🪛 eslint
src/components/Users/CreateUserForm.tsx

[error] 3-3: Replace Loader2·}·from·"lucide-react with useQuery·}·from·"@tanstack/react-query

(prettier/prettier)


[error] 4-4: Replace useQuery·}·from·"@tanstack/react-query with Loader2·}·from·"lucide-react

(prettier/prettier)


[error] 37-39: Replace ⏎import·mutate·from·"@/Utils/request/mutate";⏎import·*·as·Notification·from·"@/Utils/Notifications with import·*·as·Notification·from·"@/Utils/Notifications";⏎import·mutate·from·"@/Utils/request/mutate

(prettier/prettier)

🪛 GitHub Actions: Lint Code Base
src/components/Users/CreateUserForm.tsx

[error] 3-3: Replace Loader2 with useQuery from @tanstack/react-query (prettier/prettier)

🔇 Additional comments (6)
src/components/Users/CreateUserForm.tsx (5)

79-79: Consider supporting international phone numbers instead of hardcoding '+91'.

This issue was previously identified. The current validation restricts phone numbers to Indian format only, limiting the application's international usability.


182-188: Improve error handling in the mutation's onError callback.

The current error handling assumes a specific error structure which may lead to runtime errors if the API response doesn't match the expected format.


191-208: Serialize date_of_birth before sending in API request.

The date_of_birth field needs to be serialized to ISO string format before sending to the API.


518-526: Well implemented submit button logic!

The button implementation follows best practices:

  • Prevents duplicate submissions using isPending
  • Shows loading state with spinner
  • Properly disables when form is invalid or pristine

244-244: Excellent form field labeling!

The form fields follow accessibility best practices:

  • Required fields are properly marked
  • Labels are properly translated
  • FormLabel components are used consistently

Also applies to: 258-258, 272-272, 289-289, 307-307, 326-326, 341-341, 360-360, 402-402

public/locale/en.json (1)

677-677: Well-written validation messages!

The new validation messages are:

  • Clear and user-friendly
  • Properly formatted
  • Consistent with existing messages

Also applies to: 1433-1433, 1768-1768, 1892-1897

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

🧹 Nitpick comments (3)
src/components/Users/CreateUserForm.tsx (3)

85-92: Enhance date of birth validation.

The date validation can be improved by:

  1. Making the minimum date configurable instead of hardcoding "1900-01-01"
  2. Adding a reasonable maximum age validation
   date_of_birth: z
     .date({
       required_error: t("this_field_is_required"),
     })
     .refine((dob) => dob <= new Date(), {
       message: t("date_of_birth_cannot_be_in_future"),
+    })
+    .refine((dob) => {
+      const minDate = new Date();
+      minDate.setFullYear(minDate.getFullYear() - 120); // Max age of 120 years
+      return dob >= minDate;
+    }, {
+      message: t("date_of_birth_too_old"),
     }),

Line range hint 128-137: Improve WhatsApp number synchronization.

The current implementation directly sets the alt_phone_number when isWhatsApp changes. Consider adding a confirmation dialog when switching from WhatsApp mode to prevent accidental data loss.

   useEffect(() => {
     if (isWhatsApp) {
       form.setValue("alt_phone_number", phoneNumber);
+      form.trigger("alt_phone_number");
     }
+    // Don't clear alt_phone_number when disabling WhatsApp mode
+    // to prevent accidental data loss
     if (usernameInput && usernameInput.length > 0) {
       form.trigger("username");
     }
   }, [phoneNumber, isWhatsApp, form, usernameInput]);

340-345: Standardize input restrictions across phone number fields.

Both phone number inputs should have consistent maxLength and type restrictions.

   <Input
     type="tel"
     placeholder="+91XXXXXXXXXX"
     maxLength={13}
+    pattern="[+][0-9]{12}"
     {...field}
   />
   
   // In alt_phone_number input
   <Input
     placeholder="+91XXXXXXXXXX"
     type="tel"
     {...field}
     maxLength={13}
+    pattern="[+][0-9]{12}"
     disabled={isWhatsApp}
   />

Also applies to: 363-365

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9bad651 and 212b4dc.

📒 Files selected for processing (1)
  • src/components/Users/CreateUserForm.tsx (13 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: cypress-run (1)
🔇 Additional comments (4)
src/components/Users/CreateUserForm.tsx (4)

74-84: Consider supporting international phone numbers.

The phone number validation is currently restricted to Indian numbers (+91). This limits the application's international usability.


179-185: Improve error handling in the mutation's onError callback.

The current error handling assumes a specific error structure which could lead to runtime errors.


188-205: Serialize date_of_birth before sending in API request.

The date_of_birth field needs to be serialized to ISO string format before sending to the API.


515-523: LGTM! Well-implemented submit button state management.

The submit button correctly handles:

  • Form validation state
  • Dirty state tracking
  • Loading indicator
  • Proper disable conditions

@github-actions github-actions bot added merge conflict pull requests with merge conflict and removed merge conflict pull requests with merge conflict labels Jan 9, 2025
Copy link

👋 Hi, @rajku-dev,
Conflicts have been detected against the base branch. Please rebase your branch against the base branch.


This message is automatically generated by prince-chrismc/label-merge-conflicts-action so don't hesitate to report issues/improvements there.

@rajku-dev
Copy link
Contributor Author

Please review the changes @Jacobjeevan

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

🧹 Nitpick comments (2)
public/locale/en.json (2)

1454-1454: Consider parameterizing the country code.

The message hardcodes "+91" which makes it less reusable for other country codes. Consider parameterizing this value for better internationalization support.

-  "phone_number_must_start": "Phone number must start with +91 followed by 10 digits",
+  "phone_number_must_start": "Phone number must start with {{countryCode}} followed by {{digitCount}} digits",

1921-1926: Standardize the phrasing of username validation messages.

The username validation messages would benefit from consistent phrasing. Some use contractions ("can't") while others don't ("must be"). Consider standardizing:

-  "username_consecutive_special_characters": "Username can't contain consecutive special characters",
+  "username_consecutive_special_characters": "Username must not contain consecutive special characters",
-  "username_contain_lowercase_special": "Username can only contain lowercase letters, numbers, and . _ -",
+  "username_contain_lowercase_special": "Username must only contain lowercase letters, numbers, and . _ -",
   "username_less_than": "Username must be less than 16 characters",
   "username_more_than": "Username must be at least 4 characters",
   "username_start_end_letter_number": "Username must start and end with a letter or number"
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 212b4dc and 35ef107.

📒 Files selected for processing (4)
  • public/locale/en.json (4 hunks)
  • src/components/Facility/CreateFacilityForm.tsx (1 hunks)
  • src/components/Facility/FacilityCreate.tsx (1 hunks)
  • src/components/Patient/PatientRegistration.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/components/Facility/CreateFacilityForm.tsx
  • src/components/Facility/FacilityCreate.tsx
  • src/components/Patient/PatientRegistration.tsx
🔇 Additional comments (2)
public/locale/en.json (2)

683-683: LGTM! Clear validation message.

The validation message for date of birth is clear, concise, and follows the established format.


1796-1796: LGTM! Generic validation message.

The generic required field message is reusable and follows standard validation message format.

@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Jan 10, 2025
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

🧹 Nitpick comments (2)
public/locale/en.json (2)

1461-1461: Consider making phone validation more flexible for international numbers.

The current validation message is specific to Indian phone numbers (+91). Consider making it more generic to support international phone numbers, especially if the application might be used globally in the future.

-  "phone_number_must_start": "Phone number must start with +91 followed by 10 digits",
+  "phone_number_must_start": "Phone number must start with country code (e.g., +91) followed by the number",

1930-1935: LGTM! Comprehensive username validation rules.

The username validation messages are clear, specific, and follow security best practices. Consider adding example messages to help users understand the rules better.

Add example messages to illustrate valid and invalid usernames:

  "username_consecutive_special_characters": "Username can't contain consecutive special characters",
+ "username_consecutive_special_characters_example": "Example: 'john.doe' is valid, 'john..doe' is not",
  "username_contain_lowercase_special": "Username can only contain lowercase letters, numbers, and . _ -",
+ "username_contain_lowercase_special_example": "Example: 'john.doe_123' is valid",
  "username_less_than": "Username must be less than 16 characters",
  "username_more_than": "Username must be at least 4 characters",
+ "username_length_example": "Example: 'john' to 'john.doe.smith'",
  "username_start_end_letter_number": "Username must start and end with a letter or number"
+ "username_start_end_letter_number_example": "Example: 'john.doe' is valid, '.john.' is not"
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 35ef107 and 1282374.

📒 Files selected for processing (1)
  • public/locale/en.json (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Redirect rules - care-ohc
  • GitHub Check: Header rules - care-ohc
  • GitHub Check: Pages changed - care-ohc
  • GitHub Check: CodeQL-Build
  • GitHub Check: cypress-run (1)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (2)
public/locale/en.json (2)

683-683: LGTM! Clear validation message.

The validation message for preventing future dates in date of birth is clear and user-friendly.


1808-1808: LGTM! Standard required field message.

The generic required field validation message follows common UX patterns and can be reused across different form fields.

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Jan 10, 2025
Copy link

👋 Hi, @rajku-dev,
Conflicts have been detected against the base branch. Please rebase your branch against the base branch.


This message is automatically generated by prince-chrismc/label-merge-conflicts-action so don't hesitate to report issues/improvements there.

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

🧹 Nitpick comments (1)
src/components/Schedule/ScheduleExceptionForm.tsx (1)

Line range hint 76-105: Add error handling and simplify success handling.

The mutation setup should include error handling, and the success effect could be more concise:

 const {
   mutate: createException,
   isPending,
   isSuccess,
+  error,
 } = useMutation({
   mutationFn: mutate(ScheduleAPIs.exceptions.create, {
     pathParams: { facility_id: facilityId },
   }),
+  onSuccess: () => {
+    toast.success("Exception created successfully");
+    setOpen(false);
+    form.reset();
+    onRefresh?.();
+  },
+  onError: (error) => {
+    toast.error(error.message || "Failed to create exception");
+  },
 });

-useEffect(() => {
-  if (isSuccess) {
-    toast.success("Exception created successfully");
-    setOpen(false);
-    form.reset();
-    onRefresh?.();
-  }
-}, [isSuccess]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1282374 and b59e80a.

📒 Files selected for processing (1)
  • src/components/Schedule/ScheduleExceptionForm.tsx (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: cypress-run (1)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (4)
src/components/Schedule/ScheduleExceptionForm.tsx (4)

31-34: LGTM! Import statements are well-organized.

The new imports for ScheduleAPIs, useSlug, and UserBase align well with the component's functionality.

Also applies to: 38-38


55-58: LGTM! Props and component structure improvements.

Good improvements:

  • Component name better reflects its purpose
  • Props interface is more focused with user and optional onRefresh
  • Facility ID is properly obtained from the useSlug hook

Also applies to: 60-62


121-123: LGTM! Clean UI implementation with proper button states.

The UI implementation follows best practices:

  • Responsive form layout
  • Proper button states with loading indicators
  • Clear action labels

Also applies to: 252-256


60-60: Verify component usage across the codebase.

Let's ensure this component is used consistently and all callers provide the required props.

✅ Verification successful

Component usage is consistent and correct

The ScheduleExceptionForm component is properly used in UserAvailabilityTab.tsx with all required props being provided. No issues were found in the implementation or usage patterns.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for component usage
rg -l "ScheduleExceptionForm|CreateScheduleExceptionSheet" --type ts --type tsx

# Search for any direct API calls that might bypass this component
rg "exceptions.create" --type ts --type tsx

Length of output: 181


Script:

#!/bin/bash
# Find all TypeScript and React TypeScript files
echo "TypeScript and React files:"
fd "\.(ts|tsx)$"

# Search for component usage
echo -e "\nComponent usage:"
rg "ScheduleExceptionForm|CreateScheduleExceptionSheet"

# Search for API calls
echo -e "\nAPI calls:"
rg "exceptions\.create"

Length of output: 18502

Comment on lines +40 to +51
const formSchema = z.object({
reason: z.string().min(1, "Reason is required"),
valid_from: z.date({ required_error: "From date is required" }),
valid_to: z.date({ required_error: "To date is required" }),
start_time: z
.string()
.min(1, "Start time is required") as unknown as z.ZodType<Time>,
end_time: z
.string()
.min(1, "End time is required") as unknown as z.ZodType<Time>,
unavailable_all_day: z.boolean(),
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add missing validation rules to prevent invalid schedule exceptions.

The form schema should include additional validation rules to ensure data integrity:

  1. Validate that the end date is after or equal to the start date
  2. Validate that the end time is after the start time (when not all day)
  3. Prevent past dates from being selected
 const formSchema = z.object({
   reason: z.string().min(1, "Reason is required"),
   valid_from: z.date({ required_error: "From date is required" })
+    .min(new Date(), "Date cannot be in the past"),
   valid_to: z.date({ required_error: "To date is required" })
+    .min(new Date(), "Date cannot be in the past"),
   start_time: z
     .string()
     .min(1, "Start time is required") as unknown as z.ZodType<Time>,
   end_time: z
     .string()
     .min(1, "End time is required") as unknown as z.ZodType<Time>,
   unavailable_all_day: z.boolean(),
+ }).refine(
+   (data) => {
+     return data.valid_to >= data.valid_from;
+   },
+   {
+     message: "End date must be after or equal to start date",
+     path: ["valid_to"],
+   }
+ ).refine(
+   (data) => {
+     if (data.unavailable_all_day) return true;
+     return data.end_time > data.start_time;
+   },
+   {
+     message: "End time must be after start time",
+     path: ["end_time"],
+   }
);
📝 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
const formSchema = z.object({
reason: z.string().min(1, "Reason is required"),
valid_from: z.date({ required_error: "From date is required" }),
valid_to: z.date({ required_error: "To date is required" }),
start_time: z
.string()
.min(1, "Start time is required") as unknown as z.ZodType<Time>,
end_time: z
.string()
.min(1, "End time is required") as unknown as z.ZodType<Time>,
unavailable_all_day: z.boolean(),
});
const formSchema = z.object({
reason: z.string().min(1, "Reason is required"),
valid_from: z.date({ required_error: "From date is required" })
.min(new Date(), "Date cannot be in the past"),
valid_to: z.date({ required_error: "To date is required" })
.min(new Date(), "Date cannot be in the past"),
start_time: z
.string()
.min(1, "Start time is required") as unknown as z.ZodType<Time>,
end_time: z
.string()
.min(1, "End time is required") as unknown as z.ZodType<Time>,
unavailable_all_day: z.boolean(),
}).refine(
(data) => {
return data.valid_to >= data.valid_from;
},
{
message: "End date must be after or equal to start date",
path: ["valid_to"],
}
).refine(
(data) => {
if (data.unavailable_all_day) return true;
return data.end_time > data.start_time;
},
{
message: "End time must be after start time",
path: ["end_time"],
}
);

@rajku-dev rajku-dev closed this Jan 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
merge conflict pull requests with merge conflict
Projects
None yet
2 participants