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

Fix state & district autofill & multiple other small issues in Patient Registration page #9711

Merged

Conversation

yash-learner
Copy link
Member

@yash-learner yash-learner commented Jan 3, 2025

Proposed Changes


auto_fill_state_._district_based_on_pincode.webm

@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

Release Notes

  • New Features

    • Enhanced pincode handling with automatic state and district retrieval
    • Added visual notification for autofilled pincode information
  • Improvements

    • Streamlined patient registration workflow
    • Simplified organization selection process
  • Test Updates

    • Updated patient creation test data and page object model
    • Removed manual state and district selection from test scenarios

The changes focus on improving the patient registration experience by introducing more intelligent location-based data entry and simplifying the user interface.

Copy link
Contributor

coderabbitai bot commented Jan 3, 2025

Walkthrough

The pull request introduces improvements to the patient registration workflow, focusing on enhancing pincode-based auto-filling of state and district information. The changes modify the PatientRegistration component to integrate a new hook useStateAndDistrictFromPincode, which automatically derives state and district based on pincode input. The implementation includes a new state for tracking selected organization levels and a mechanism to display an autofill notification, streamlining the patient registration process.

Changes

File Change Summary
src/components/Patient/PatientRegistration.tsx - Added CareIcon import
- Integrated useStateAndDistrictFromPincode hook
- Added selectedLevels and showAutoFilledPincode states
- Updated useEffect to manage organization levels and autofill notification
cypress/e2e/patient_spec/patient_creation.cy.ts - Removed state and district properties from testPatientData
cypress/pageObject/Patients/PatientCreation.ts - Removed state and district from PatientFormData interface
- Eliminated selectState and selectDistrict methods

Assessment against linked issues

Objective Addressed Explanation
Auto-fill state and district from pincode [#9668]
Render state and district automatically

Possibly related PRs

Suggested labels

changes required

Suggested reviewers

  • rithviknishad
  • bodhish

Poem

🐰 A pincode's magic, swift and bright,
Fills state and district with delight!
No more manual entry's strain,
Automation breaks the data chain,
Patient reg made light as flight! 🏥✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ebee745 and 060f3e3.

📒 Files selected for processing (2)
  • cypress/e2e/patient_spec/patient_creation.cy.ts (0 hunks)
  • cypress/pageObject/Patients/PatientCreation.ts (0 hunks)
💤 Files with no reviewable changes (2)
  • cypress/e2e/patient_spec/patient_creation.cy.ts
  • cypress/pageObject/Patients/PatientCreation.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: cypress-run (1)
  • GitHub Check: CodeQL-Build
  • GitHub Check: OSSAR-Scan

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

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 4dd0e93
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67780083aa0cb90008faa259
😎 Deploy Preview https://deploy-preview-9711--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

netlify bot commented Jan 3, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 060f3e3
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6788fed8407ec50008279dcb
😎 Deploy Preview https://deploy-preview-9711--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.

@yash-learner yash-learner changed the title Fix state & district autofill Fix state & district autofill in Patient Registration page Jan 3, 2025
@yash-learner yash-learner changed the title Fix state & district autofill in Patient Registration page Fix state & district autofill in Patient Registration page & multiple other small issues Jan 3, 2025
@yash-learner yash-learner changed the title Fix state & district autofill in Patient Registration page & multiple other small issues Fix state & district autofill & multiple other small issues in Patient Registration page Jan 3, 2025
Comment on lines 323 to 337
async function fetchOrganizationByName(name: string, parentId?: string) {
try {
const data = await query(organizationApi.list, {
queryParams: {
org_type: "govt",
parent: parentId || "",
name,
},
})({ signal: new AbortController().signal });
return data.results?.[0];
} catch (error) {
toast.error("Error fetching organization");
return undefined;
}
}
Copy link
Member Author

Choose a reason for hiding this comment

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

At some point, we may need to extract this into a separate hook

Copy link
Contributor

@Jacobjeevan Jacobjeevan Jan 4, 2025

Choose a reason for hiding this comment

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

Yea, go ahead and do that since same logic is being used in #9662.

Also check Rithvik's comment below.

cc: @Mahendar0701

@yash-learner yash-learner marked this pull request as ready for review January 3, 2025 21:45
@yash-learner yash-learner requested a review from a team as a code owner January 3, 2025 21:45
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 (6)
src/pages/Organization/components/OrganizationSelector.tsx (2)

23-24: Add documentation for new props.
Prefer adding a short explanation or a JSDoc comment for parentSelectedLevels and errorMessage to guide future maintainers on their usage.


170-171: Push only meaningful errors.
errors={[props.errorMessage || ""]} might cause an empty string to appear if there's no actual error. Consider conditionally passing an empty array instead to avoid confusing UI.

-errors={[props.errorMessage || ""]}
+errors={props.errorMessage ? [props.errorMessage] : []}
src/components/Patient/PatientRegistration.tsx (4)

6-6: Confirm i18n usage for toast messages.
Since you are using translations in other notifications, consider localizing toast errors to maintain a consistent user experience.


208-213: Consider grouping pincode org fetch logic.
The logic fetches the state org first, then sets selectedLevels to [] early if state org is not found. Consider returning a partial selection if the state is found but not the district – or add a fallback mechanism.


326-340: Add robust error details.
toast.error("Error fetching organization") might leave users uncertain about the exact cause. Consider including the organization name in the error text or using a more descriptive message.


625-625: Improve UX for disabled text area.
You correctly remove editing with cursor-not-allowed if addresses match. Optionally, add a tooltip or note explaining why the field is disabled for clarity.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 68c4c3d and f58e7b5.

📒 Files selected for processing (2)
  • src/components/Patient/PatientRegistration.tsx (7 hunks)
  • src/pages/Organization/components/OrganizationSelector.tsx (5 hunks)
🔇 Additional comments (6)
src/pages/Organization/components/OrganizationSelector.tsx (3)

33-36: Initialize state thoughtfully.
Using parentSelectedLevels || [] is fine. Consider logging or handling scenarios where parentSelectedLevels might be empty due to unexpected data, ensuring robust default behaviors.


112-124: Validate data removal edge cases.
When the user removes all levels (newLevels.length === 0), you reset the selection. This is correct for typical usage. Confirm that removing the top-level organization doesn't break parent-child flows if the parent-level has siblings or alternative branches.


127-132: Avoid re-initialization loops.
The useEffect reassigns state when parentSelectedLevels changes. This is correct but be aware of potential repeated updates if parent-level changes are frequent.

src/components/Patient/PatientRegistration.tsx (3)

85-85: Validate usage of local org state.
selectedLevels is used to maintain hierarchical organization data derived from the pincode. Ensure that clearing it in one place does not inadvertently disrupt other parts of registration.


219-222: Handle partial fetch failures.
If the district API fails, current logic omits selecting the state org. Evaluate whether you want to preserve the state org even if the district is not found.


676-683: Check null-safety for error message.
You pass errorMessage={errors.geo_organization?.[0]} but if geo_organization is missing or empty, it may show an undefined or empty string in OrganizationSelector. Confirm the UI reflects a real error only when relevant.

Copy link
Member

@rithviknishad rithviknishad left a comment

Choose a reason for hiding this comment

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

not a fan of this approach. how about we stick with how dependent queries are made as per tanstacks docs?

https://tanstack.com/query/latest/docs/framework/react/guides/dependent-queries#usequery-dependent-query

this way we wouldn't need to try catch either and stick with the simplicity.

cc @bodhish

Copy link

github-actions bot commented Jan 5, 2025

👋 Hi, @yash-learner,
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.

@yash-learner
Copy link
Member Author

not a fan of this approach. how about we stick with how dependent queries are made as per tanstacks docs?

https://tanstack.com/query/latest/docs/framework/react/guides/dependent-queries#usequery-dependent-query

this way we wouldn't need to try catch either and stick with the simplicity.

cc @bodhish

@rithviknishad

Updated it in this bdd739f, 6905db3. Does it look good ?

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 (12)
src/hooks/useOrganization.ts (2)

7-12: Add User Facing Documentation Comment for UseOrganizationParams

Though this interface is self-explanatory, adding a short JSDoc comment or code comment could clarify the accepted parameters for future maintainers and reduce confusion about which fields are optional.


20-31: Ensure error handling is robust

While isError is returned, there is no specialized error handling in the queryFn or an onError callback for the query. If additional failover or fallback logic is required when the API call fails, consider adding a custom onError in the useQuery options or a shared error boundary.

src/hooks/useStateAndDistrictFromPincode.ts (3)

14-16: Clarify hook naming or add doc comment

The function name useStateAndDistrictFromPincode is descriptive, but consider adding inline documentation about how it fetches pincode details, extracts the state and district, and loads the corresponding organizations. This can improve maintainability.


43-53: Consider concurrency or caching benefits

The second organization query is nested behind the first's result for stateOrg?.id. This is logical. If you anticipate repeated lookups or the same pincodes, ensure that React Query’s caching strategy is adequately configured to minimize network calls.


56-61: Combine isError states carefully

This hook merges three possible error states into one, which is correct for a simplified approach. However, distinct error messages can help users identify which step failed (e.g., the pincode fetch vs. the state org fetch). Consider returning more granular error states if needed.

src/components/Patient/PatientRegistration.tsx (7)

6-6: Check the usage of CareIcon import

The CareIcon import is newly added. Verify whether all necessary icons are being efficiently imported. For performance, you might consider a dynamic icon library approach if your codebase loads many icons.


30-30: Mention the custom hook in documentation or inline comments

useStateAndDistrictFromPincode is introduced here. A short comment indicating its purpose in the patient registration flow (e.g., “Auto-fills state and district based on pincode”) could guide future contributors.


79-79: Refactor state management for clarity

selectedLevels and setSelectedLevels hold the acquired organizations. Consider whether these should be combined or abstracted to a single object (like geoOrganization) if there’s no plan to scale beyond two levels. This might simplify future expansions.


189-191: Decouple logic from the UI effect

The useStateAndDistrictFromPincode hook is invoked inline here. If you anticipate using the same logic in other forms, it might be beneficial to centralize or abstract the effect of pincode changes, e.g., in a custom reducer or separate function for clarity.


194-206: Enhance user feedback for partial auto-fill

If some part of the data can’t be automatically derived from the pincode (e.g., the district wasn’t found), the pincode_autofill message still appears if levels.length > 0. Consider either partial messages or fallback for missing details.


580-580: UI clarity for disabled text area

When sameAddress is true, the permanent address is disabled. The cursor-not-allowed is good, but consider adding a tooltip or helper text to clarify that the permanent address matches the current address. This could improve UX.


Line range hint 596-606: Refine timed feedback approach

You’re displaying _showAutoFilledPincode for 2 seconds to highlight auto-filling. This is a subtle user experience detail. If users need more time or have accessibility needs, consider a more stable or dismissible notification.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f58e7b5 and 45a3d9f.

📒 Files selected for processing (3)
  • src/components/Patient/PatientRegistration.tsx (8 hunks)
  • src/hooks/useOrganization.ts (1 hunks)
  • src/hooks/useStateAndDistrictFromPincode.ts (1 hunks)
🔇 Additional comments (5)
src/hooks/useOrganization.ts (1)

14-19: Confirm default parameter usage logic

Currently, the default values for orgType, parentId, and name are all empty strings. If the intended scenario requires no query to run until a valid name is provided, this setup is fine. Otherwise, you might consider enabling queries based on other parameter conditions (like orgType).

src/hooks/useStateAndDistrictFromPincode.ts (2)

17-25: Validate pincode more thoroughly

validatePincode(pincode) is used to control the enabled property, but ensure it returns false for invalid or partial input. If user input can be partially typed, consider whether the query should wait until the pincode is a specific length (e.g., 6 digits in India).


30-40: Check for fallback behavior when stateName is missing

If pincodeDetails.statename is an empty string, the state query is disabled, which is correct. Just confirm that this is the desired behavior. If there is a possibility of partial matches or alternate naming, you might need more robust fallback or alias logic for stateName.

src/components/Patient/PatientRegistration.tsx (2)

43-46: Validate usage of new or changed imports

With the introduction of OrganizationSelector from @/pages/Organization/components/OrganizationSelector, ensure no cyclical imports exist and confirm version compatibility. This is more of a housekeeping check.


631-638: Verify the OrganizationSelector usage

OrganizationSelector is receiving parentSelectedLevels and an errorMessage. Ensure that the error logic is consistent with your form validation approach. If you have an external form library or inline validation, confirm that the error message updates as expected.

Co-authored-by: Jacob John Jeevan <mail@jacobjeevan.me>
Co-authored-by: mahendar <mahendarchikkolla@gmail.com>
@Jacobjeevan Jacobjeevan force-pushed the issues/9668/fix-auto-fill branch from 2ac7d08 to 1d3740e Compare January 14, 2025 12:33
@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Jan 14, 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: 1

🧹 Nitpick comments (2)
src/components/Patient/PatientRegistration.tsx (2)

198-218: Consider optimizing the useEffect cleanup.

The effect handles the autofill notification well, but there are a few improvements possible:

  1. The cleanup function could be more explicit about its purpose
  2. The effect could be split into two separate effects - one for levels management and one for notification
-  useEffect(() => {
-    if (patientId) return;
-    const levels: Organization[] = [];
-    if (stateOrg) levels.push(stateOrg);
-    if (districtOrg) levels.push(districtOrg);
-    setSelectedLevels(levels);
-
-    if (levels.length == 2) {
-      setShowAutoFilledPincode(true);
-      const timer = setTimeout(() => {
-        setShowAutoFilledPincode(false);
-      }, 5000);
-      return () => clearTimeout(timer);
-    }
-    return () => setShowAutoFilledPincode(false);
-  }, [stateOrg, districtOrg, patientId]);
+  useEffect(() => {
+    if (patientId) return;
+    const levels: Organization[] = [];
+    if (stateOrg) levels.push(stateOrg);
+    if (districtOrg) levels.push(districtOrg);
+    setSelectedLevels(levels);
+  }, [stateOrg, districtOrg, patientId]);
+
+  useEffect(() => {
+    if (patientId) return;
+    if (stateOrg && districtOrg) {
+      setShowAutoFilledPincode(true);
+      const timer = setTimeout(() => {
+        setShowAutoFilledPincode(false);
+      }, 5000);
+      return () => {
+        clearTimeout(timer);
+        setShowAutoFilledPincode(false);
+      };
+    }
+  }, [stateOrg, districtOrg, patientId]);

Line range hint 277-293: Simplify the form reset logic.

The current implementation has nested ternary operations which could be simplified for better readability.

-      setSelectedLevels([
-        patientQuery.data.geo_organization as unknown as Organization,
-      ]);
-      form.reset({
-        ...patientQuery.data,
-        same_phone_number:
-          patientQuery.data.phone_number ===
-          patientQuery.data.emergency_phone_number,
-        same_address:
-          patientQuery.data.address === patientQuery.data.permanent_address,
-        age_or_dob: patientQuery.data.date_of_birth ? "dob" : "age",
-        age: !patientQuery.data.date_of_birth
-          ? patientQuery.data.age
-          : undefined,
-        date_of_birth: patientQuery.data.date_of_birth
-          ? patientQuery.data.date_of_birth
-          : undefined,
+      const { date_of_birth, age, phone_number, emergency_phone_number, address, permanent_address, geo_organization } = patientQuery.data;
+      setSelectedLevels([geo_organization as unknown as Organization]);
+      
+      form.reset({
+        ...patientQuery.data,
+        same_phone_number: phone_number === emergency_phone_number,
+        same_address: address === permanent_address,
+        age_or_dob: date_of_birth ? "dob" : "age",
+        age: date_of_birth ? undefined : age,
+        date_of_birth: date_of_birth || undefined,
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1d3740e and e4b9514.

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

84-85: LGTM! State management is well-structured.

The new state variables are appropriately typed and follow React's best practices.


706-721: LGTM! Accessibility implementation is well done.

The autofill notification includes proper ARIA attributes and follows accessibility best practices:

  • Uses role="status" for live regions
  • Includes aria-live="polite" for screen readers
  • Marks icon as aria-hidden="true"

761-764: LGTM! Organization selector integration is correct.

The component properly handles the selected levels and value propagation.

@@ -757,7 +794,7 @@ export default function PatientRegistration(
</div>
{!patientPhoneSearch.isLoading &&
!!duplicatePatients?.length &&
!!parsePhoneNumber(debouncedNumber || "") &&
!!parsePhoneNumber(form.watch("phone_number") || "") &&
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Phone number parsing implementation needs improvement

The current implementation has several limitations that could affect robustness:

  • The minimum length check of 12 digits is too restrictive for valid international numbers
  • Special case handling of "+91" should be generalized
  • Limited validation of number format and country codes
🔗 Analysis chain

Verify phone number parsing edge cases.

The phone number parsing should be tested with various formats to ensure robust handling.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for phone number parsing usage and validation
rg -A 2 "parsePhoneNumber" 

Length of output: 4594


Script:

#!/bin/bash
# Get the implementation of parsePhoneNumber function
ast-grep --pattern 'export const parsePhoneNumber = $_'

Length of output: 944

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

🧹 Nitpick comments (5)
src/hooks/useStateAndDistrictFromPincode.ts (5)

1-1: Consider moving API key to environment variables.

The API key should not be directly exposed in the configuration file. Consider moving it to environment variables for better security.

Also applies to: 30-30


28-32: Enhance query configuration and type safety.

Consider the following improvements:

  1. Add retry configuration for better error handling
  2. Configure stale time for caching optimization
  3. Specify error type for better type safety
   } = useQuery<PincodeResponse>({
     queryKey: ["pincode-details", pincode],
     queryFn: () => getPincodeDetails(pincode, careConfig.govDataApiKey),
     enabled: pincode !== "" && validatePincode(pincode),
+    retry: 2,
+    staleTime: 5 * 60 * 1000, // 5 minutes
+    gcTime: 10 * 60 * 1000, // 10 minutes
   });

37-49: Improve state organization selection logic.

The current implementation blindly selects the first organization without validation. Consider adding validation and using select transform for better performance.

   } = useOrganization({
     orgType: "govt",
     parentId: "",
     name: stateName,
     enabled: !!stateName,
+    select: (orgs) => {
+      const validOrg = orgs.find(org => 
+        org.type === "State" && org.name.toLowerCase() === stateName?.toLowerCase()
+      );
+      return validOrg ? [validOrg] : [];
+    }
   });

-  const stateOrg = stateOrgs?.[0];
+  const stateOrg = stateOrgs?.[0] ?? null;

50-60: Apply similar improvements to district organization query.

Consider applying the same improvements as suggested for the state organization query.

   } = useOrganization({
     orgType: "govt",
     parentId: stateOrg?.id,
     name: districtName,
     enabled: !!stateOrg?.id && !!districtName,
+    select: (orgs) => {
+      const validOrg = orgs.find(org => 
+        org.type === "District" && org.name.toLowerCase() === districtName?.toLowerCase()
+      );
+      return validOrg ? [validOrg] : [];
+    }
   });

61-66: Enhance error handling with specific error cases.

The current error handling is basic. Consider:

  1. Adding specific error cases (network, validation, not found)
  2. Providing more detailed feedback to users
  3. Adding error boundaries for unexpected failures
-  if (isStateError || isPincodeError) {
+  if (isPincodeError) {
+    toast.error(t("pincode_invalid_or_not_found"));
+  } else if (isStateError) {
+    toast.error(t("state_org_fetch_failed"));
+  }
-  if (isDistrictError && !isStateError) {
+  if (isDistrictError && stateOrg) {
     toast.info(t("pincode_district_auto_fill_error"));
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e4b9514 and 22687f3.

📒 Files selected for processing (2)
  • src/hooks/useOrganization.ts (1 hunks)
  • src/hooks/useStateAndDistrictFromPincode.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/hooks/useOrganization.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: CodeQL-Build
  • GitHub Check: OSSAR-Scan
  • GitHub Check: cypress-run (1)

src/hooks/useStateAndDistrictFromPincode.ts Outdated Show resolved Hide resolved
src/hooks/useStateAndDistrictFromPincode.ts Outdated Show resolved Hide resolved
@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Jan 16, 2025
Copy link

👋 Hi, @yash-learner,
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.

@Jacobjeevan Jacobjeevan removed the merge conflict pull requests with merge conflict label Jan 16, 2025
@nihal467
Copy link
Member

LGTM

@rithviknishad rithviknishad merged commit 4d0c3df into ohcnetwork:develop Jan 17, 2025
19 checks passed
Copy link

@yash-learner 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
Projects
None yet
5 participants