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 : Pincode exception error and auto populate of geo_organization info on facility edit #9662

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

Conversation

Mahendar0701
Copy link
Contributor

@Mahendar0701 Mahendar0701 commented Jan 2, 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 internationalization for the page title in the FacilityCreate component.
    • Introduced a new prompt for selecting a location in the user interface.
    • Enhanced the OrganizationSelector component to better handle external input and improve error handling.
    • Implemented pincode validation and automatic fetching of related organization details.
    • Added a new function to fetch organization data based on name and optional parent ID.
  • Bug Fixes

    • Resolved potential type inconsistencies when handling facility location data during form reset.
    • Improved data type handling for pincode, latitude, and longitude fields.
    • Enhanced error handling for invalid pincode responses.

@Mahendar0701 Mahendar0701 requested a review from a team as a code owner January 2, 2025 14:36
Copy link
Contributor

coderabbitai bot commented Jan 2, 2025

Walkthrough

The pull request modifies the FacilityCreate component to ensure that the pincode, latitude, and longitude fields are treated as strings during form population, addressing potential type inconsistencies. It introduces new state variables to manage selected organizational levels and enhances internationalization by translating page titles. The OrganizationSelector component is updated to handle the value and parentSelectedLevels props, and a new key is added to the localization JSON for user prompts, improving the overall user interface.

Changes

File Change Summary
src/components/Facility/FacilityCreate.tsx Added handlePincodeChange function for pincode validation; introduced useFetchOrganizationByName function; added selectedLevels state variable; updated form schema to convert pincode, latitude, and longitude to strings; updated onChange handler for pincode; translated page title.
public/locale/en.json Added new key "select_location_from": "Select location from" for user prompts.
src/pages/Organization/components/OrganizationSelector.tsx Introduced new useEffect to parse value prop as JSON; updated props destructuring to include value and parentSelectedLevels.
src/Utils/utils.ts Enhanced getPincodeDetails with error handling.
src/types/organization/organizationApi.ts Added useFetchOrganizationByName function and updated export structure.

Assessment against linked issues

Objective Addressed Explanation
Resolve "Expected String, Received Number" error for pincode [#9649]
Prepopulate State, District, Local Body, and Ward fields [#9648] The changes do not address the prepopulation of these fields in the edit form.

Possibly related PRs

Suggested Labels

tested, reviewed

Suggested Reviewers

  • bodhish
  • rithviknishad

Poem

🐰 In fields of code, where numbers roam,
Strings now guide them safely home.
Pincode's journey, no errors in sight,
With translations bright, all feels just right!
A rabbit's cheer for changes so grand,
Hopping along, hand in hand! 🌟


📜 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 e87535d and 4599c93.

📒 Files selected for processing (3)
  • public/locale/en.json (2 hunks)
  • src/components/Facility/FacilityCreate.tsx (9 hunks)
  • src/types/organization/organizationApi.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/types/organization/organizationApi.ts
  • public/locale/en.json
  • src/components/Facility/FacilityCreate.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: cypress-run (1)

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

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 4599c93
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/677b9e4db8559f00081e4130
😎 Deploy Preview https://deploy-preview-9662--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.

@bodhish
Copy link
Member

bodhish commented Jan 2, 2025

On facility edit the organisation is also not getting prefilled, I think we should solve that also

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.

minor thing, but let's also ensure i18n is done on all files that are being touched in PRs. There are two places that needs to be updated in this PR's changed file

@Mahendar0701
Copy link
Contributor Author

On facility edit the organisation is also not getting prefilled, I think we should solve that also

You mean geo_organization info , i think it is being addressed in issue #9648

@bodhish
Copy link
Member

bodhish commented Jan 2, 2025

I don't think jeevan is working on it, I will assign it to you. lets have one PR.

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/pages/Organization/components/OrganizationSelector.tsx (1)

35-55: Enhance defensive checks around JSON parsing.
Currently, a try/catch block is in place to catch JSON.parse errors, logging them to the console. Consider adding a fallback path or early return to ensure the component’s state remains stable in edge cases (e.g., an empty string or invalid structure) to avoid undesired behavior.

 useEffect(() => {
   if (value) {
     try {
       const parsedValue =
         typeof value === "string" ? JSON.parse(value) : value;
       if (parsedValue) {
         // ...
       }
     } catch (e) {
+      setSelectedLevels([]);
       console.error("Invalid value for geo_organization:", e);
     }
   }
 }, [value]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 03fd617 and 080f442.

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

2-2: Import statement is correctly updated.
No issues found with the import of React hooks.


31-31: Prop destructuring for new value is fine.
The value prop is properly introduced here, and the necessary props are being destructured clearly.


171-171: No issues with the Autocomplete value assignment.
Using the last selected organization’s id or an empty string is a sensible approach.

public/locale/en.json (1)

1584-1584: New i18n key added.
The "select_location_from": "Select location from" entry aligns with the updated UI text references. Ensure that its usage is consistent across the app, and consider whether this prompt needs additional context or placeholders.

@Mahendar0701 Mahendar0701 changed the title Fix : Pincode exception error on facility edit Fix : Pincode exception error and autofill of geo_organization info on facility edit Jan 3, 2025
@nihal467
Copy link
Member

nihal467 commented Jan 3, 2025

image

the issue still presist, can you attach a video after fixing the issue

@Mahendar0701
Copy link
Contributor Author

Mahendar0701 commented Jan 3, 2025

image

the auto-fill is not working in facility detail page

@nihal467 The existing values are populating on facility edit as described in #9648

image

@Mahendar0701 Mahendar0701 changed the title Fix : Pincode exception error and autofill of geo_organization info on facility edit Fix : Pincode exception error and auto populate of geo_organization info on facility edit Jan 3, 2025
@rithviknishad
Copy link
Member

edit may work fine, but is it auto-filling when pincode is entered?

@Mahendar0701
Copy link
Contributor Author

edit may work fine, but is it auto-filling when pincode is entered?

Nope , i will fix that too 👍

@rithviknishad rithviknishad removed their request for review January 3, 2025 09:21
@Jacobjeevan
Copy link
Contributor

#9711 (review)

Comment on lines 202 to 219
export function useFetchOrganizationByName(name: string, parentId?: string) {
return useQuery({
queryKey: ["organization", name, parentId],
queryFn: async () => {
const data = await query(organizationApi.list, {
queryParams: {
org_type: "govt",
parent: parentId || "",
name: name || "",
},
})({ signal: new AbortController().signal });

return data.results?.[0];
},
enabled: !!name,
});
}

Copy link
Contributor Author

@Mahendar0701 Mahendar0701 Jan 4, 2025

Choose a reason for hiding this comment

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

@bodhish @rithviknishad @Jacobjeevan you mean something like this?? #9711 (review)

Copy link
Member

Choose a reason for hiding this comment

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

move this to types/organization/organizationApi itself instead of defining it here.

Comment on lines 224 to 257
const { data: pincodeData, isError: isPincodeError } = useQuery({
queryKey: ["pincodeDetails", pincode],
queryFn: () => getPincodeDetails(pincode, careConfig.govDataApiKey),
enabled: validatePincode(pincode),
});

if (isPincodeError) {
Notification.Error({ msg: "Invalid pincode" });
}

const stateName = pincodeData?.statename;

const districtName = pincodeData?.districtname;

const { data: stateOrg } = useFetchOrganizationByName(stateName);
const { data: districtOrg } = useFetchOrganizationByName(
districtName,
stateOrg?.id,
);

useEffect(() => {
if (stateOrg && districtOrg) {
setSelectedLevels([stateOrg, districtOrg]);
} else {
setSelectedLevels([]);
}
}, [stateOrg, districtOrg]);

console.log("selectedLevels", selectedLevels);

const handlePincodeChange = (value: string) => {
setPincode(value);
};

Copy link
Contributor Author

Choose a reason for hiding this comment

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

used usequery tanstack, is this approach acceptable??

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 (4)
src/Utils/utils.ts (1)

195-198: Clarify the fallback behavior after invalid pincodes
When no records are returned, the function simply returns null after displaying an error notification. This behavior might cause unexpected downstream null reference checks. Consider returning an empty object or a more descriptive error object to better inform consuming code.

  if (!data.records || data.records.length === 0) {
    Notification.Error({ msg: "Invalid pincode" });
-   return null;
+   return { error: true };
  }
src/components/Facility/FacilityCreate.tsx (3)

62-66: Group relevant imports and reduce overhead
Multiple utility imports are introduced in sequential lines. Consider grouping them to maintain concise import sections if your coding guidelines permit it.


238-243: Check for concurrency issues in organization data
When both stateOrg and districtOrg are queried, if stateOrg changes faster, you might fetch an outdated districtOrg. Consider a single combined query for more reliable data.


244-251: Improve readability when clearing selected levels
Ensure the user experience is clear if no valid state/district org is found. Potential default fallback or user-facing notice might be beneficial.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 02a4ca0 and c811b60.

📒 Files selected for processing (3)
  • public/locale/en.json (1 hunks)
  • src/Utils/utils.ts (3 hunks)
  • src/components/Facility/FacilityCreate.tsx (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • public/locale/en.json
🔇 Additional comments (6)
src/Utils/utils.ts (1)

202-219: Ensure consistent error handling and loading states in consumer code
This hook returns the first fetched organization, but the consumer code must handle errors and loading states. Double-check if auto-retries or stale data could cause unexpected behavior.

✅ Verification successful

Let me gather more context about the error handling in the consumer code.


Error handling and loading states are properly implemented in consumer code

The consumer code in FacilityCreate.tsx properly handles both error and loading states:

  • The hook is used with proper destructuring of data only: const { data: stateOrg } = useFetchOrganizationByName(stateName)
  • Loading states are handled through a global isLoading state that's used in the submit button
  • The hook is enabled conditionally based on the presence of name parameter (as seen in the hook implementation)
  • The component handles missing data gracefully through optional chaining when using stateOrg?.id
  • The results are used in a useEffect that safely handles both presence and absence of data: if (stateOrg && districtOrg) { ... } else { ... }
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Searching for usage of `useFetchOrganizationByName` to verify error handling
rg -A 3 "useFetchOrganizationByName"

Length of output: 1056


Script:

#!/bin/bash
# Check the implementation of FacilityCreate.tsx to see how errors and loading states are handled
cat src/components/Facility/FacilityCreate.tsx

Length of output: 18685

src/components/Facility/FacilityCreate.tsx (5)

77-79: Pincode state management works but consider form synchronization
Defining a separate pincode state is helpful, but be mindful of potential duplication with the React Hook Form field. Ensure they remain in sync.


234-237: Gracefully handle missing pincode data
Ensure statename or districtname are not undefined before using them downstream.


364-364: Validate changed pincode
Every time the user updates pincode, ensure it’s validated. The existing approach is correct, but confirm that a partial pincode doesn’t trigger spurious queries.


376-381: Double-check geo_organization updates
When updating the geo_organization field, verify that OrganizationSelector is providing correct data. Also ensure any default or fallback organization is properly managed if none is selected.


463-463: Good usage of translation function
The introduced translation for "Select location from" is consistent with i18n best practices.

src/components/Facility/FacilityCreate.tsx Outdated Show resolved Hide resolved
@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Jan 5, 2025
Copy link

github-actions bot commented Jan 5, 2025

👋 Hi, @Mahendar0701,
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 (2)
src/pages/Organization/components/OrganizationSelector.tsx (2)

170-170: Enhance type safety for Autocomplete value

Consider adding type assertion for better type safety.

-              value={selectedLevels[selectedLevels.length - 1]?.id || ""}
+              value={(selectedLevels[selectedLevels.length - 1]?.id as string) || ""}

31-31: Consider splitting component responsibilities

The TODO comment suggests renaming to GovtOrganizationSelector, but there are broader architectural improvements possible:

  1. Split the display of selected organizations and the selection interface into separate components
  2. Create a custom hook for organization data fetching logic
  3. Consider implementing a proper state machine for the multi-level selection process

This would improve maintainability and make the component more focused on its core responsibilities.

Would you like me to provide a detailed proposal for this refactoring?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c811b60 and d9078ad.

📒 Files selected for processing (2)
  • public/locale/en.json (1 hunks)
  • src/pages/Organization/components/OrganizationSelector.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • public/locale/en.json
🧰 Additional context used
🪛 eslint
src/pages/Organization/components/OrganizationSelector.tsx

[error] 2-3: Delete

(prettier/prettier)

🪛 GitHub Check: lint
src/pages/Organization/components/OrganizationSelector.tsx

[failure] 2-2:
Delete

🪛 GitHub Actions: Lint Code Base
src/pages/Organization/components/OrganizationSelector.tsx

[error] 2-2: Prettier formatting error: Delete unnecessary line break

🔇 Additional comments (2)
src/pages/Organization/components/OrganizationSelector.tsx (2)

23-23: LGTM: Props interface enhancement

The addition of parentSelectedLevels prop and its proper destructuring aligns well with the requirement to support auto-population of organization information.

Also applies to: 33-33


37-54: Verify integration with facility edit form

While the changes support organization auto-population, we should verify the integration with the facility edit form:

  1. Confirm that the parent component correctly passes the organization hierarchy
  2. Ensure the component handles facility edit state transitions properly

Let's verify the integration:

✅ Verification successful

Let me gather more information about the integration:


Integration with facility edit form is properly implemented

The verification shows that the OrganizationSelector integration is correctly implemented:

  1. In FacilityCreate.tsx:

    • Maintains organization hierarchy state via selectedLevels
    • Properly passes parentSelectedLevels to OrganizationSelector
    • Updates form state via form.setValue("geo_organization", value)
  2. In CreateFacilityForm.tsx:

    • Uses OrganizationSelector within a form field
    • Handles value changes through form control

The component correctly handles both create and edit scenarios, with proper state management and form integration.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for FacilityCreate/Edit components that use OrganizationSelector
rg -l "OrganizationSelector" src/components/Facility/
# Check how parentSelectedLevels is populated
rg -A 5 "parentSelectedLevels" src/components/Facility/

Length of output: 717


Script:

#!/bin/bash
# Check how selectedLevels is managed in FacilityCreate
ast-grep --pattern 'const selectedLevels = $_' src/components/Facility/FacilityCreate.tsx

# Check the form initialization and state management
rg -B 5 -A 10 "selectedLevels" src/components/Facility/FacilityCreate.tsx

# Check CreateFacilityForm usage of OrganizationSelector
rg -B 5 -A 10 "OrganizationSelector" src/components/Facility/CreateFacilityForm.tsx

Length of output: 3122

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

🔭 Outside diff range comments (1)
src/components/Facility/FacilityCreate.tsx (1)

Add unit tests for the FacilityCreate component

Based on the verification results, there appears to be no existing test coverage for the FacilityCreate component or any other React components in the codebase. While there is a basic test script in package.json, it's only configured for Snyk security testing. The component handles complex form logic including validation, API integration, and error handling, making it a critical candidate for testing.

Key areas to cover in tests:

  • Form field validation logic
  • Pincode lookup functionality
  • Organization selection behavior
  • API integration for facility creation
  • Error handling scenarios
  • Loading state management

Consider setting up a testing framework like Jest with React Testing Library to implement these tests.

🔗 Analysis chain

Line range hint 74-77: Add unit tests for the FacilityCreate component

Consider adding unit tests to cover:

  1. Form validation
  2. Pincode lookup and organization selection
  3. Error handling scenarios
  4. Integration with the backend API
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for existing test files
fd -e test.tsx -e spec.tsx "FacilityCreate"

Length of output: 43


Script:

#!/bin/bash
# Let's try a broader search for test files in the repository
fd -e test.tsx -e spec.tsx

# Also search for any test files containing "Facility" in case the naming is different
fd -e test.tsx -e spec.tsx "Facility"

# Let's also check if there's a __tests__ directory structure
fd -t d "__tests__"

# Search for any test-related imports or test setup in the codebase
rg -i "import.*test" "src/"

Length of output: 236


Script:

#!/bin/bash
# Let's check if there's any testing framework setup or configuration files
fd "jest.config" "test.config"

# Check for any testing utilities or test setup files
rg -l "test-utils" "src/"

# Look for any testing-related dependencies in package.json
cat package.json | grep -i "test"

# Check if there are any test files with .test.js/.test.ts extensions
fd -e test.js -e test.ts

Length of output: 311

♻️ Duplicate comments (1)
src/components/Facility/FacilityCreate.tsx (1)

228-237: 🛠️ Refactor suggestion

Enhance error handling and prevent race conditions

While the pincode query implementation is functional, consider these improvements:

  1. Clear any previously fetched data when a pincode error occurs
  2. Add debouncing to prevent unnecessary API calls during rapid typing
+ const [debouncedPincode] = useDebounce(pincode, 500);
  const { data: pincodeData, isError: isPincodeError } = useQuery({
-   queryKey: ["pincodeDetails", pincode],
+   queryKey: ["pincodeDetails", debouncedPincode],
-   queryFn: () => getPincodeDetails(pincode, careConfig.govDataApiKey),
+   queryFn: () => getPincodeDetails(debouncedPincode, careConfig.govDataApiKey),
-   enabled: validatePincode(pincode),
+   enabled: validatePincode(debouncedPincode),
  });

  if (isPincodeError) {
    Notification.Error({ msg: "Invalid pincode" });
+   // Clear any previously fetched data
+   form.setValue("geo_organization", "");
+   setSelectedLevels([]);
  }
🧹 Nitpick comments (4)
src/components/Facility/FacilityCreate.tsx (4)

238-257: Optimize organization data fetching and remove debug logging

  1. The current implementation could cause unnecessary re-renders. Consider using useMemo for derived state.
  2. Remove the debug console.log statement from production code.
- const stateName = pincodeData?.statename;
- const districtName = pincodeData?.districtname;

+ const { stateName, districtName } = useMemo(() => ({
+   stateName: pincodeData?.statename,
+   districtName: pincodeData?.districtname
+ }), [pincodeData]);

  const { data: stateOrg } = useFetchOrganizationByName(stateName);
  const { data: districtOrg } = useFetchOrganizationByName(
    districtName,
    stateOrg?.id,
  );

  useEffect(() => {
    if (stateOrg && districtOrg) {
      setSelectedLevels([stateOrg, districtOrg]);
    } else {
      setSelectedLevels([]);
    }
  }, [stateOrg, districtOrg]);

- console.log("selectedLevels", selectedLevels);

258-261: Add input sanitization to pincode handler

Consider sanitizing the pincode input to ensure only numeric values are processed.

  const handlePincodeChange = (value: string) => {
-   setPincode(value);
+   const sanitizedValue = value.replace(/[^0-9]/g, '');
+   setPincode(sanitizedValue);
  };

380-385: Add error handling for organization selection

Consider handling edge cases where the organization selection fails or becomes invalid.

  value={facilityData?.geo_organization}
  parentSelectedLevels={selectedLevels}
  onChange={(value) => {
+   try {
      // Update geo_organization value in form
      form.setValue("geo_organization", value);
+   } catch (error) {
+     console.error('Failed to update organization:', error);
+     Notification.Error({ msg: t("failed_to_update_organization") });
+   }
  }}

Line range hint 84-117: Improve validation schema maintainability

Consider extracting validation schema to a separate file for better maintainability and reusability.

+ // src/schemas/facility.ts
+ export const facilityFormSchema = z.object({...})
+ export type FacilityFormValues = z.infer<typeof facilityFormSchema>;

- const facilityFormSchema = z.object({...})
- type FacilityFormValues = z.infer<typeof facilityFormSchema>;
+ import { facilityFormSchema, FacilityFormValues } from '@/schemas/facility';
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0f49a53 and b6b2318.

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

1-1: LGTM: Clean implementation of new imports and state management

The new imports and state variables are well-structured and properly typed for managing pincode and organization data.

Also applies to: 63-67, 78-79


264-264: LGTM: Good accessibility and internationalization implementation

The form implementation follows accessibility best practices with proper labels, error messages, and internationalization support.

Also applies to: 467-467

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 (6)
src/components/Facility/FacilityCreate.tsx (6)

225-229: Add user feedback for ongoing requests.
While the useQuery for pincodeData is running, the user might not see any indication of loading. Consider adding a loading state or spinner to improve UX.


231-233: Duplicate error notifications.
If multiple invalid pincode entries occur, multiple toasts or notifications might pile up, potentially oversaturating the user. Consider debouncing or grouping errors to reduce user alert fatigue.


245-251: Avoid re-renders when partial data is fetched.
The current logic clears selectedLevels if stateOrg or districtOrg is missing—potentially causing flickers for the user while waiting on the second fetch. Consider a short-circuit if either is still loading.


253-254: Remove debug logs in production.
console.log("selectedLevels", selectedLevels); should likely be removed or wrapped in a debug flag for production code.


365-365: Use typed event.
Within onChange={(value) => { … }}, clarifying value’s type can help avoid confusion. If “value” is a string, you can strongly type it to ensure safe usage.


463-463: Internationalize tooltip text.
"select_location_from" is already translated, but the entire tooltip text might need translation beyond that phrase. Confirm that all relevant text strings are also in I18n files.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b6b2318 and e87535d.

📒 Files selected for processing (4)
  • public/locale/en.json (1 hunks)
  • src/Utils/utils.ts (1 hunks)
  • src/components/Facility/FacilityCreate.tsx (7 hunks)
  • src/types/organization/organizationApi.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • public/locale/en.json
  • src/Utils/utils.ts
🔇 Additional comments (4)
src/types/organization/organizationApi.ts (1)

65-81: Consider null or empty results handling.
This function returns data.results?.[0], which may be undefined if no organizations match the parameters. Ensure the calling code handles a possible undefined result.

src/components/Facility/FacilityCreate.tsx (3)

75-76: Keep track of partial selection states.
The selectedLevels and pincode states are logically related. If pincode is changed or cleared, verify that selectedLevels remains consistent and does not reference outdated organizations.


239-244: Validate stateOrg and districtOrg.
If either call returns no data, stateOrg or districtOrg will be undefined. This might unintentionally reset selectedLevels. Confirm that you genuinely intend to discard partial matches if one level is missing.


377-381: Pass updated value for new facility creation.
value={facilityData?.geo_organization} will remain undefined when creating a new facility. Confirm that this use case is acceptable or initialize it to an empty string to avoid react warnings.

src/components/Facility/FacilityCreate.tsx Show resolved Hide resolved
src/components/Facility/FacilityCreate.tsx Outdated Show resolved Hide resolved
@Mahendar0701
Copy link
Contributor Author

Mahendar0701 commented Jan 6, 2025

@rithviknishad can you please review the changes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
5 participants