Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Edit feature for facilities in organization | pincode, geo_organization info auto populates #9662

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

Conversation

Mahendar0701
Copy link
Contributor

@Mahendar0701 Mahendar0701 commented Jan 2, 2025

Proposed Changes

  • Fixes Switch to using CreateFacilityForm #9849

  • Pincode autofill and geo_organization info auto populates

  • Added edit feature for facility in orgainization
    image

  • Added support for organization selector in facility form
    image

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

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

Summary by CodeRabbit

Release Notes

  • New Features

    • Added pincode-based location details retrieval for facility creation.
    • Enhanced facility management with improved organization selection.
    • Introduced internationalization for facility creation and update workflows.
    • Added an option to edit existing facilities directly from the interface.
  • Improvements

    • Updated facility creation and editing interfaces with dynamic handling.
    • Improved organization selector with more robust state management.
    • Restructured facility cards for better user interaction and navigation.
  • Localization

    • Added new translation keys for location and visibility settings.
    • Implemented translation support for facility creation/update titles.

The release introduces more flexible facility management with enhanced location and organization selection capabilities.

@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

This pull request introduces comprehensive changes to the facility creation and management workflow. The modifications primarily focus on enhancing the FacilityForm and related components to support facility editing, improve organization selection, and add pincode-based location details. Key improvements include internationalization of strings, dynamic form handling for create and update scenarios, and integration of pincode detail retrieval functionality.

Changes

File Change Summary
src/components/Facility/FacilityCreate.tsx Added pincode and organization level state management, internationalized titles.
src/components/Facility/FacilityForm.tsx Updated form to support creating and updating facilities, added facilityId handling.
src/pages/Organization/components/OrganizationSelector.tsx Enhanced state initialization with parentSelectedLevels prop.
src/types/organization/organizationApi.ts Added useFetchOrganizationByName function.
public/locale/en.json Added new translation keys for location and visibility settings.
src/Utils/utils.ts Improved error handling in getPincodeDetails function.
src/pages/Organization/components/AddFacilitySheet.tsx Updated to handle facility creation and editing, added facilityId support.
src/pages/Organization/OrganizationFacilities.tsx Changed facility card structure for improved interaction model.

Assessment against linked issues

Objective Addressed Explanation
Edit existing facility support
Organization selector support
Pincode exception handling
Rename CreateFacilityForm to FacilityForm

Possibly related PRs

Suggested labels

needs review, needs testing

Suggested reviewers

  • bodhish
  • rithviknishad
  • Jacobjeevan

Poem

🐰 Hop, hop, through code so bright,
Facilities bloom with newfound might!
Pincode magic, levels aligned,
Forms dancing, perfectly designed!
A rabbit's code, a joyful sight! 🏡✨


📜 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 5ffb199 and 5bda95e.

📒 Files selected for processing (1)
  • src/Utils/utils.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Check: cypress-run (1)
src/Utils/utils.ts

[failure] 116-116:
Cannot find name 'toast'.

🪛 GitHub Actions: Cypress Tests
src/Utils/utils.ts

[error] 116-116: TypeScript error: Cannot find name 'toast'. The 'toast' identifier is not defined or imported.

🪛 GitHub Actions: Deploy Care Fe
src/Utils/utils.ts

[error] 116-116: Cannot find name 'toast'. TypeScript compilation error

🔇 Additional comments (1)
src/Utils/utils.ts (1)

115-118: ⚠️ Potential issue

Fix missing toast import and improve error handling.

The error handling addition is good, but there are a few issues to address:

  1. The toast import is missing, causing build failures.
  2. The error handling could be more informative and robust.

First, add the toast import at the top of the file:

+ import { toast } from "@/components/toast";

Then, improve the error handling:

   if (!data.records || data.records.length === 0) {
-    toast.error("Invalid pincode");
+    toast.error(`Invalid pincode: ${pincode}. Please enter a valid Indian pincode.`);
     return null;
   }

Consider adding validation for the pincode format before making the API call:

 export const getPincodeDetails = async (pincode: string, apiKey: string) => {
+  if (!/^\d{6}$/.test(pincode)) {
+    toast.error("Please enter a valid 6-digit pincode");
+    return null;
+  }
   const response = await fetch(

Let's verify the toast import path and usage across the codebase:

🧰 Tools
🪛 GitHub Check: cypress-run (1)

[failure] 116-116:
Cannot find name 'toast'.

🪛 GitHub Actions: Cypress Tests

[error] 116-116: TypeScript error: Cannot find name 'toast'. The 'toast' identifier is not defined or imported.

🪛 GitHub Actions: Deploy Care Fe

[error] 116-116: Cannot find name 'toast'. TypeScript compilation error

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link

netlify bot commented Jan 2, 2025

Deploy Preview for care-ohc failed.

Name Link
🔨 Latest commit 5bda95e
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6783b257f77a090008910cb5

@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
Copy link

👋 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.

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Jan 10, 2025
@github-actions github-actions bot added the Deploy-Failed Deplyment is not showing preview label Jan 10, 2025
@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Jan 10, 2025
@Mahendar0701 Mahendar0701 changed the title Fix : Switch to using CreateFacilityForm Edit feature for facilities in organization | pincode, geo_organization info auto populates Jan 11, 2025
@Mahendar0701 Mahendar0701 marked this pull request as ready for review January 11, 2025 07:19
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/Facility/FacilityCreate.tsx (1)

Line range hint 523-534: Internationalize visibility settings strings.

The visibility settings section contains hardcoded English strings. These should be internationalized for consistency with the rest of the application.

 <FormLabel className="text-base">
-  Make this facility public
+  {t("make_facility_public")}
 </FormLabel>
 <p className="text-sm text-muted-foreground">
-  When enabled, this facility will be visible to the
-  public and can be discovered by anyone using the
-  platform
+  {t("facility_public_description")}
 </p>
🧹 Nitpick comments (5)
src/components/Facility/FacilityForm.tsx (2)

58-58: Improve the validation error message for 'geo_organization'

The error message for the geo_organization field is currently set to "required", which might not be informative for users. Consider providing a more descriptive message to enhance user understanding.

Apply this diff to improve the error message:

-      geo_organization: z.string().min(1, { message: "required" }),
+      geo_organization: z.string().min(1, { message: "Geo organization is required" }),

396-405: Synchronize 'geo_organization' value with form state

The value prop of OrganizationSelector is set to facilityData?.geo_organization, which may not update if the user changes the field. To keep the component in sync with the form state, consider using form.watch("geo_organization").

Apply this diff to synchronize the value:

-                    value={facilityData?.geo_organization}
+                    value={form.watch("geo_organization")}
src/pages/Organization/components/AddFacilitySheet.tsx (1)

16-16: Align component naming with file name for consistency

The component is named CreateFacilityForm but is imported from "FacilityForm". For clarity and consistency, consider renaming the component or updating the import statement to match the file name.

If the component is intended to be FacilityForm, update the export and import:

In FacilityForm.tsx:

- export default function CreateFacilityForm(props: FacilityProps) {
+ export default function FacilityForm(props: FacilityProps) {

In AddFacilitySheet.tsx:

- import CreateFacilityForm from "@/components/Facility/FacilityForm";
+ import FacilityForm from "@/components/Facility/FacilityForm";

Alternatively, if the component name is correct, consider renaming the file to CreateFacilityForm.tsx.

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

Line range hint 91-106: Simplify phone number validation logic.

The current validation combines multiple checks in a way that might be confusing. Consider extracting this into a separate validator function for better maintainability.

+const validatePhoneNumber = (value: string) => {
+  return PhoneNumberValidator(["mobile", "landline"])(value) !== undefined && phonePreg(value);
+};
+
 phone_number: z
   .string()
   .min(1, { message: t("required") })
-  .refine(
-    (val: string) => {
-      if (
-        !PhoneNumberValidator(["mobile", "landline"])(val) === undefined ||
-        !phonePreg(val)
-      ) {
-        return false;
-      }
-      return true;
-    },
-    {
-      message: t("invalid_phone_number"),
-    },
-  ),
+  .refine(validatePhoneNumber, { message: t("invalid_phone_number") }),

224-232: Enhance error handling for pincode queries.

The current error handling only shows a generic "Invalid pincode" message. Consider providing more specific error information to help users understand and resolve the issue.

 if (isPincodeError) {
-  toast.error("Invalid pincode");
+  toast.error(t("invalid_pincode_details"), {
+    description: t("please_check_pincode_and_try_again"),
+  });
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4599c93 and a932b00.

📒 Files selected for processing (6)
  • public/locale/en.json (2 hunks)
  • src/components/Facility/FacilityCreate.tsx (8 hunks)
  • src/components/Facility/FacilityForm.tsx (8 hunks)
  • src/pages/Organization/OrganizationFacilities.tsx (1 hunks)
  • src/pages/Organization/components/AddFacilitySheet.tsx (1 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 context used
🪛 Biome (1.9.4)
src/pages/Organization/OrganizationFacilities.tsx

[error] 117-117: Missing key property for this element in iterable.

The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.

(lint/correctness/useJsxKeyInIterable)

🔇 Additional comments (2)
src/components/Facility/FacilityCreate.tsx (2)

Line range hint 63-77: Consider implementing debouncing for pincode changes.

To prevent potential race conditions when users type quickly, consider implementing debouncing for pincode changes. This will help manage API requests more efficiently and prevent stale data updates.

+import { useDebounce } from "@/hooks/useDebounce";
+
 const [pincode, setPincode] = useState("");
+const debouncedPincode = useDebounce(pincode, 300);

Line range hint 1-566: Implementation successfully addresses the PR objectives.

The changes effectively implement the facility editing feature with pincode-based autofill and organization selection. The code is well-structured and includes proper form validation, error handling, and internationalization support.

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

Mahendar0701 commented Jan 11, 2025

@rithviknishad @Jacobjeevan

I added edit feature and support for organization selector for facility form in organization

And i have a doubt
Which approach should i use for auto fill of geo_organization info ?
Should i follow the one in #9711 , or is mine fine?

@github-actions github-actions bot added needs-triage question Further information is requested labels Jan 11, 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 (5)
src/Utils/utils.ts (3)

193-196: Use i18n for error messages

The error message is hardcoded. Since the file already imports t from i18next, use it for internationalization.

-    toast.error("Invalid pincode");
+    toast.error(t("invalid_pincode"));

193-196: Add TypeScript interface for the API response

Define an interface for the API response to improve type safety and code maintainability.

interface PincodeApiResponse {
  records: Array<{
    pincode: string;
    officename: string;
    statename: string;
    districtname: string;
    // add other fields as needed
  }>;
}

193-196: Consider implementing caching for pincode data

Since pincode data rarely changes, consider implementing a caching mechanism to:

  1. Reduce API calls
  2. Improve performance
  3. Handle rate limiting
src/components/Facility/FacilityForm.tsx (2)

213-213: Consider reducing geolocation timeout.

The current 10-second timeout for geolocation might lead to a poor user experience. Consider reducing it to 5 seconds and providing a retry option.

-        { timeout: 10000 },
+        { timeout: 5000 },

220-224: Optimize pincode validation and data fetching.

The current implementation might trigger unnecessary API calls as it validates the pincode on every change.

Consider debouncing the pincode validation:

  const { data: pincodeData } = useQuery({
    queryKey: ["pincodeDetails", pincode],
    queryFn: () => getPincodeDetails(pincode, careConfig.govDataApiKey),
-    enabled: validatePincode(pincode) && pincode != facilityData?.pincode,
+    enabled: validatePincode(pincode) && pincode !== facilityData?.pincode,
+    staleTime: 5 * 60 * 1000, // Cache pincode data for 5 minutes
  });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a932b00 and f735ac9.

📒 Files selected for processing (5)
  • public/locale/en.json (10 hunks)
  • src/Utils/utils.ts (1 hunks)
  • src/components/Facility/FacilityForm.tsx (12 hunks)
  • src/pages/Organization/OrganizationFacilities.tsx (1 hunks)
  • src/pages/Organization/components/AddFacilitySheet.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • public/locale/en.json
🔇 Additional comments (4)
src/Utils/utils.ts (1)

193-196: Review API key handling

The API key is passed as a parameter which could expose it in client-side code. Consider:

  1. Moving the API call to a backend service
  2. Implementing proper API key rotation
  3. Adding rate limiting
src/pages/Organization/components/AddFacilitySheet.tsx (1)

24-27: LGTM! Well-structured component with clear separation of create/edit modes.

The component effectively handles both creation and editing scenarios with proper conditional rendering and internationalization support.

Also applies to: 34-48

src/components/Facility/FacilityForm.tsx (2)

380-385: LGTM! Well-implemented pincode change handler.

The implementation correctly handles pincode changes and resets the selected levels appropriately.


134-139: Review form reset behavior after update.

The current implementation resets the form immediately after a successful update, which might clear user input if they're still making changes.

Consider showing a confirmation dialog before resetting the form or removing the reset altogether since the sheet will likely close:

    onSuccess: (_data: FacilityModel) => {
      toast.success(t("facility_updated_successfully"));
      queryClient.invalidateQueries({ queryKey: ["organizationFacilities"] });
-     form.reset();
      onSubmitSuccess?.();
    },

src/pages/Organization/OrganizationFacilities.tsx Outdated 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

🧹 Nitpick comments (3)
src/components/Facility/FacilityForm.tsx (3)

79-83: Initialize pincode state with form value

The pincode state should be initialized with the form's pincode value to ensure consistency when editing a facility.

-  const [pincode, setPincode] = useState("");
+  const [pincode, setPincode] = useState(form.getValues("pincode") || "");

Also applies to: 89-91


130-150: Enhance error handling for API failures

The error handling could be improved in the following ways:

  1. Add specific error messages for different API failure scenarios
  2. Handle network timeouts
  3. Add retry logic for pincode API calls
 const { data: pincodeData } = useQuery({
   queryKey: ["pincodeDetails", pincode],
   queryFn: () => getPincodeDetails(pincode, careConfig.govDataApiKey),
   enabled: validatePincode(pincode) && pincode != facilityData?.pincode,
+  retry: 3,
+  retryDelay: 1000,
+  onError: (error) => {
+    toast.error(t("pincode_fetch_error"));
+  }
 });

Also applies to: 152-158, 220-224


392-401: Enhance accessibility for form controls

Consider adding the following accessibility improvements:

  1. ARIA labels for the organization selector
  2. Loading state announcements for screen readers
 <OrganizationSelector
   required={true}
   value={facilityData?.geo_organization}
   parentSelectedLevels={selectedLevels}
+  aria-label={t("select_organization")}
   onChange={(value) => {
     form.setValue("geo_organization", value);
   }}
 />

Also applies to: 546-570

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f735ac9 and a68184f.

📒 Files selected for processing (3)
  • src/components/Facility/FacilityForm.tsx (12 hunks)
  • src/pages/Organization/OrganizationFacilities.tsx (1 hunks)
  • src/pages/Organization/components/AddFacilitySheet.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/pages/Organization/OrganizationFacilities.tsx
  • src/pages/Organization/components/AddFacilitySheet.tsx
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Redirect rules - care-ohc
  • GitHub Check: OSSAR-Scan
  • GitHub Check: cypress-run (1)
🔇 Additional comments (2)
src/components/Facility/FacilityForm.tsx (2)

1-1: LGTM! Import and schema changes align with requirements.

The additions of careConfig, useQuery, and organization-related imports, along with the schema update for geo_organization, properly support the new auto-population features.

Also applies to: 3-3, 43-44, 47-49, 58-58


Line range hint 1-574: Implementation successfully meets PR objectives

The changes effectively implement the facility edit feature with auto-population of pincode and geo_organization information. The code is well-structured, includes proper error handling, and uses TypeScript effectively.

src/components/Facility/FacilityForm.tsx Outdated 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/Facility/FacilityForm.tsx (2)

130-150: Consider enhancing error handling with more specific error messages.

The error handling is good but could be more informative for users.

 onError: (error: Error) => {
   const errorData = error.cause as { errors: { msg: string[] } };
   if (errorData?.errors?.msg) {
     errorData.errors.msg.forEach((msg) => {
       toast.error(msg);
     });
   } else {
-    toast.error(t("facility_update_error"));
+    toast.error(t("facility_update_error"), {
+      description: error.message || t("please_try_again_later")
+    });
   }
 }

180-197: Add cleanup to prevent memory leaks.

The form reset effect should handle component unmounting.

 useEffect(() => {
+  let mounted = true;
   if (facilityData) {
+    if (!mounted) return;
     form.reset({
       facility_type: facilityData.facility_type,
       // ... other fields
     });
   }
+  return () => {
+    mounted = false;
+  };
 }, [facilityData, form]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a68184f and 4a9f3a6.

📒 Files selected for processing (2)
  • src/components/Facility/FacilityCreate.tsx (9 hunks)
  • src/components/Facility/FacilityForm.tsx (12 hunks)
🔇 Additional comments (4)
src/components/Facility/FacilityForm.tsx (3)

1-1: LGTM! Imports and schema updates are well-structured.

The new imports and schema changes appropriately support the pincode and organization auto-fill functionality.

Also applies to: 3-3, 47-47, 48-48, 58-58


79-83: LGTM! Interface changes enhance component reusability.

The renamed interface and added facilityId prop properly support both create and edit scenarios.


238-244: 🛠️ Refactor suggestion

Handle potential race conditions in organization data fetching.

The sequential organization queries could lead to race conditions if responses arrive out of order.

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

Likely invalid or redundant comment.

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

259-259: LGTM! Internationalization is well implemented.

The translation keys are consistently used and properly structured.

Also applies to: 513-515

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

👋 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: 0

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

224-232: ⚠️ Potential issue

Move error handling to useEffect.

The current error handling can trigger multiple toasts during renders. Move it to useEffect for better user experience.

-if (isPincodeError) {
-  toast.error("Invalid pincode");
-}
+useEffect(() => {
+  if (isPincodeError) {
+    toast.error(t("invalid_pincode"));
+  }
+  return () => {
+    toast.dismiss();
+  };
+}, [isPincodeError, t]);
🧹 Nitpick comments (1)
src/components/Facility/FacilityCreate.tsx (1)

234-250: Add loading states for organization selection.

The organization selection logic should handle loading states to provide better feedback to users.

+const [isLoadingOrg, setIsLoadingOrg] = useState(false);
+
 useEffect(() => {
+  setIsLoadingOrg(true);
   if (stateOrg && districtOrg) {
     setSelectedLevels([stateOrg, districtOrg]);
   } else {
     setSelectedLevels([]);
   }
+  setIsLoadingOrg(false);
 }, [stateOrg, districtOrg]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4a9f3a6 and 5ffb199.

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

1-1: LGTM! Well-structured imports and state management.

The new imports and state variables are properly organized and typed, supporting the pincode auto-fill and organization selection features.

Also applies to: 63-66, 75-77


158-158: LGTM! Proper form reset handling.

The form reset logic correctly handles the geo_organization field, ensuring it's properly populated during facility editing.


513-515: LGTM! Well-structured visibility settings section.

The visibility settings section is properly internationalized and follows the UI pattern consistently.


375-379: Verify organization prefill functionality.

Based on the PR comments, please verify that the organization prefill works correctly when editing an existing facility.

✅ Verification successful

Organization prefill implementation is correct

The code properly handles organization prefill in edit mode through the useEffect hook that initializes the form with facility data, including the geo_organization field. The watch and setValue implementations in the reviewed code correctly maintain the field's state.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if organization field is properly handled in edit mode
ast-grep --pattern 'useEffect(() => {
  if (facilityData) {
    $$$
    geo_organization: $$$
    $$$
  }
}, $$$)'

Length of output: 116


Script:

#!/bin/bash
# Search for form initialization with facilityData
rg "facilityData" -A 5 -B 5 "src/components/Facility/FacilityCreate.tsx"

# Also check for form default values
ast-grep --pattern 'defaultValues: {
  $$$
}'

Length of output: 1731

@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Jan 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
changes required Deploy-Failed Deplyment is not showing preview needs-triage question Further information is requested test failed
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Switch to using CreateFacilityForm
5 participants