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

Merged
merged 74 commits into from
Jan 16, 2025

Conversation

Mahendar0701
Copy link
Contributor

@Mahendar0701 Mahendar0701 commented Jan 2, 2025

Proposed Changes

  • Fixes Switch to using Create Facility Form #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

  • Removed Features

    • Removed facility creation and update routes.
    • Eliminated direct facility creation form.
  • New Features

    • Added EditFacilitySheet for inline facility editing.
    • Introduced new organization and facility hooks.
    • Enhanced pincode-based state and district lookup.
  • Internationalization

    • Updated localization keys for facility-related actions.
    • Improved translation support across components.
  • Performance & UX

    • Streamlined facility management workflow.
    • Added more robust error handling for pincode details.
  • Type Changes

    • Updated facility data model to include geographical coordinates.
    • Modified type definitions across multiple components.

@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 significant changes to facility management functionality, including the complete removal of the FacilityCreate component and enhancements to the FacilityForm to support both creation and editing of facilities. A new EditFacilitySheet component is introduced for inline editing. The routing structure is updated to reflect these changes, and localization keys are added for better internationalization. Additionally, type definitions are modified to accommodate new data structures.

Changes

File Change Summary
src/components/Facility/FacilityCreate.tsx Completely removed the component
src/components/Facility/FacilityForm.tsx Updated to support create and update operations, added optional facilityId, enhanced localization
src/Routers/routes/FacilityRoutes.tsx Removed create and update routes, added facility detail route
src/types/facility/facility.ts Updated FacilityData interface with new properties like latitude, longitude, pincode type change
public/locale/en.json Added new localization keys for facility management
src/pages/Organization/components/OrganizationSelector.tsx Added properties for selected organization and error handling
src/pages/Organization/components/AddFacilitySheet.tsx Updated imports and button text for localization
src/pages/Organization/components/EditFacilitySheet.tsx Introduced new component for editing facilities
src/hooks/useOrganization.ts Added a custom hook for fetching organizations
src/hooks/useStateAndDistrictFromPincode.ts Introduced a custom hook for state and district retrieval based on pincode
src/pages/Appointments/AppointmentDetail.tsx Updated facility prop type in AppointmentDetails component
src/pages/Appointments/components/AppointmentTokenCard.tsx Updated facility prop type in AppointmentTokenCard component
src/pages/Appointments/utils.ts Updated facility type in printAppointment function
src/Utils/utils.ts Added error handling in getPincodeDetails function
src/Utils/request/api.tsx Changed response type for getPermittedFacility route

Assessment against linked issues

Objective Addressed Explanation
Support editing existing facility
Support organization selector
Pincode exception handling
Rename CreateFacilityForm -> FacilityForm

Possibly related PRs

Suggested labels

changes required

Suggested reviewers

  • rithviknishad
  • bodhish
  • Jacobjeevan

Poem

🐰 A Rabbit's Ode to Facility Forms 🏥

Farewell, old create, your time has passed,
A new form rises, sleek and fast!
With edits smooth and data neat,
Our facility management's now complete!

Hop, hop, hooray for code so bright! 🌟

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 ready!

Name Link
🔨 Latest commit 195b2a1
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6788e8ea8aec09000881ae49
😎 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
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 (5)
src/hooks/useOrganization.ts (1)

22-32: Add type safety for API response.

Consider adding type definitions for the API response to improve type safety and maintainability.

+interface OrganizationResponse {
+  results: Array<{
+    // Add organization properties here
+    id: string;
+    name: string;
+    // ... other properties
+  }>;
+}

 export function useOrganization({
   orgType = "",
   parentId = "",
   name = "",
   enabled = true,
 }: UseOrganizationParams) {
-  const { data, isLoading, isError } = useQuery({
+  const { data, isLoading, isError } = useQuery<OrganizationResponse>({
     queryKey: ["organization", orgType, name, parentId],
     // ... rest of the implementation
   });

Also applies to: 40-44

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

71-71: Consider improving geo_organization validation.

The current validation only checks for a non-empty string, but based on the usage in the component, this field should validate an Organization ID.

-    geo_organization: z.string().min(1, t("organization_required")),
+    geo_organization: z
+      .string()
+      .min(1, t("organization_required"))
+      .regex(/^[0-9a-fA-F]{24}$/, t("invalid_organization_id")),

73-75: Consider making phone number validation more flexible.

The phone number validation is currently hardcoded for Indian numbers (+91). Consider making this configurable or supporting international formats.

-      .regex(/^\+91[0-9]{10}$/, t("phone_number_validation")),
+      .regex(/^\+[1-9]\d{1,14}$/, t("phone_number_validation")), // Support E.164 format

169-170: Consider increasing geolocation timeout.

The current timeout of 10 seconds might be too short for slower devices or poor GPS signals.

-       { timeout: 10000 },
+       { timeout: 30000, maximumAge: 300000, enableHighAccuracy: true },

200-221: Add cleanup to form reset effect.

The effect that resets form data should clean up to prevent memory leaks.

  useEffect(() => {
+   let mounted = true;
    if (facilityData) {
+     if (!mounted) return;
      setSelectedLevels([
        facilityData.geo_organization as unknown as Organization,
      ]);
      form.reset({
        // ... form reset logic
      });
    }
+   return () => {
+     mounted = false;
+   };
  }, [facilityData]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 130fe35 and f59b850.

📒 Files selected for processing (4)
  • public/locale/en.json (13 hunks)
  • src/components/Facility/FacilityForm.tsx (12 hunks)
  • src/hooks/useOrganization.ts (1 hunks)
  • src/hooks/useStateAndDistrictFromPincode.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/hooks/useStateAndDistrictFromPincode.ts
  • public/locale/en.json
🔇 Additional comments (4)
src/hooks/useOrganization.ts (3)

1-7: LGTM! Well-organized imports.

The imports are properly organized and all dependencies are being used.


9-14: LGTM! Clean interface definition.

The interface is well-defined with appropriate types and optionality.


34-38: LGTM! Proper error handling implementation.

Error handling is correctly implemented using useEffect to prevent multiple toast notifications, as suggested in the previous review.

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

Line range hint 1-56: LGTM! Well-structured imports and type definitions.

The imports are well-organized using absolute paths, and the FacilityProps interface is properly defined with optional properties.

src/components/Facility/FacilityForm.tsx Show resolved Hide resolved
src/components/Facility/FacilityForm.tsx Show resolved Hide resolved
src/components/Facility/FacilityForm.tsx Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/hooks/useStateAndDistrictFromPincode.ts (1)

22-33: 🛠️ Refactor suggestion

Add error retry for pincode API and handle rate limiting.

The pincode API is a critical external dependency. Consider:

  1. Adding retry configuration
  2. Implementing rate limiting handling
  3. Caching successful responses
 useQuery<PincodeResponse>({
   queryKey: ["pincode-details", pincode],
   queryFn: () => getPincodeDetails(pincode, careConfig.govDataApiKey),
   enabled: pincode !== "" && validatePincode(pincode),
+  retry: (failureCount, error: any) => {
+    // Don't retry on rate limiting
+    if (error?.response?.status === 429) return false;
+    return failureCount < 3;
+  },
+  staleTime: 1000 * 60 * 60, // Cache for 1 hour
+  cacheTime: 1000 * 60 * 60 * 24, // Keep in cache for 24 hours
 });
🧹 Nitpick comments (2)
src/hooks/useStateAndDistrictFromPincode.ts (2)

62-69: Enhance error handling with specific error messages.

The current error handling uses generic toast messages. Consider:

  1. Adding specific error messages based on the error type
  2. Providing retry options for users
  3. Implementing a fallback UI for error states
 useEffect(() => {
   if (isStateError || isPincodeError) {
-    toast.info(t("pincode_state_auto_fill_error"));
+    const errorMessage = isPincodeError
+      ? t("pincode_fetch_error")
+      : t("state_org_fetch_error");
+    toast.error(errorMessage, {
+      action: {
+        label: t("retry"),
+        onClick: () => refetch(),
+      },
+    });
   }
   if (isDistrictError && !isStateError) {
-    toast.info(t("pincode_district_auto_fill_error"));
+    toast.error(t("district_org_fetch_error"), {
+      action: {
+        label: t("retry"),
+        onClick: () => refetch(),
+      },
+    });
   }
 }, [isStateError, isPincodeError, isDistrictError]);

73-78: Consider returning granular loading and error states.

The current implementation combines all loading and error states. For better UX, consider returning individual states to allow more precise UI feedback.

 return {
   stateOrg,
   districtOrg,
-  isLoading: isPincodeLoading || isStateLoading || isDistrictLoading,
-  isError: isPincodeError || isStateError || isDistrictError,
+  loadingStates: {
+    isPincodeLoading,
+    isStateLoading,
+    isDistrictLoading,
+  },
+  errorStates: {
+    isPincodeError,
+    isStateError,
+    isDistrictError,
+  },
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f59b850 and 2c80f20.

📒 Files selected for processing (1)
  • src/hooks/useStateAndDistrictFromPincode.ts (1 hunks)
🧰 Additional context used
🪛 eslint
src/hooks/useStateAndDistrictFromPincode.ts

[error] 7-7: Insert useOrganization·}·from·"@/hooks/useOrganization";⏎⏎import·{·

(prettier/prettier)


[error] 9-11: Delete ";⏎⏎import·{·useOrganization·}·from·"@/hooks/useOrganization

(prettier/prettier)

🪛 GitHub Check: lint
src/hooks/useStateAndDistrictFromPincode.ts

[failure] 7-7:
Insert useOrganization·}·from·"@/hooks/useOrganization";⏎⏎import·{·


[failure] 9-9:
Delete ";⏎⏎import·{·useOrganization·}·from·"@/hooks/useOrganization

🪛 GitHub Actions: Lint Code Base
src/hooks/useStateAndDistrictFromPincode.ts

[error] 7-7: Prettier formatting error: Missing import statement for useOrganization from @/hooks/useOrganization

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: cypress-run (1)
🔇 Additional comments (2)
src/hooks/useStateAndDistrictFromPincode.ts (2)

13-20: LGTM! Well-defined interfaces.

The interfaces are focused and follow TypeScript best practices.


38-50: Validate state organization selection.

The current implementation assumes the first organization in the array is the correct one. Consider:

  1. Adding validation for the organization type and structure
  2. Handling cases where multiple organizations match the state name

src/hooks/useStateAndDistrictFromPincode.ts 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

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

201-212: ⚠️ Potential issue

Improve type safety for geo_organization handling.

The current implementation uses unsafe type casting. Consider using proper type checking.

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

65-85: Consider adding validation for coordinates pair.

While individual latitude and longitude validations are present, consider adding a custom validation to ensure both coordinates are either both present or both absent to prevent partial location data.

 const facilityFormSchema = z.object({
   // ... other fields
   latitude: z
     .string()
     .optional()
     .refine((val) => !val || validateLatitude(val), t("invalid_latitude")),
   longitude: z
     .string()
     .optional()
     .refine((val) => !val || validateLongitude(val), t("invalid_longitude")),
+  }).refine(
+    (data) => {
+      const hasLat = !!data.latitude;
+      const hasLng = !!data.longitude;
+      return (hasLat && hasLng) || (!hasLat && !hasLng);
+    },
+    { message: t("both_coordinates_required") }
 });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2c80f20 and 88f4110.

📒 Files selected for processing (3)
  • public/locale/en.json (13 hunks)
  • src/components/Facility/FacilityForm.tsx (12 hunks)
  • src/hooks/useStateAndDistrictFromPincode.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/hooks/useStateAndDistrictFromPincode.ts
  • public/locale/en.json
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: cypress-run (1)
🔇 Additional comments (4)
src/components/Facility/FacilityForm.tsx (4)

51-55: LGTM! Props interface is well-defined.

The FacilityProps interface clearly defines the component's contract with optional properties that make sense for both create and edit scenarios.


177-196: LGTM! Smart handling of pincode-based organization selection.

The implementation intelligently manages organization selection based on pincode, with proper cleanup and timeout handling. The use of useEffect with appropriate dependencies and cleanup is particularly well done.


355-375: Well-implemented pincode autofill feedback.

The UI feedback for pincode autofill is accessibility-aware with proper ARIA attributes and clear visual indicators.


524-542: LGTM! Comprehensive button state handling.

The submit button implementation properly handles:

  • Dirty form state check
  • Loading states for both create and update
  • Clear visual feedback
  • Proper accessibility attributes

src/components/Facility/FacilityForm.tsx 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, @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

♻️ Duplicate comments (4)
src/components/Facility/FacilityForm.tsx (4)

116-127: 🛠️ Refactor suggestion

Add error handling to the update mutation.

The update mutation should handle errors and show appropriate error messages to users.


128-134: 🛠️ Refactor suggestion

Handle loading and error states for facility data fetch.

The facility query should handle loading and error states to improve user experience.


201-203: ⚠️ Potential issue

Improve type safety for geo_organization handling.

The current implementation uses unsafe type casting.


379-393: 🛠️ Refactor suggestion

Add form label for OrganizationSelector.

The organization selector is missing a visible label, which impacts accessibility.

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

51-56: Consider adding type constraints for facilityId.

The facilityId prop is typed as an optional string without any constraints. Consider adding validation to ensure it's a valid UUID or matches your ID format.

 interface FacilityProps {
   organizationId?: string;
-  facilityId?: string;
+  facilityId?: `${string}-${string}-${string}-${string}-${string}`;
   onSubmitSuccess?: () => void;
 }

73-75: Improve phone number validation regex.

The current regex /^\+91[0-9]{10}$/ is strict and only allows Indian phone numbers. Consider making it more flexible to support:

  1. Optional spaces or hyphens
  2. Optional country codes
-      .regex(/^\+91[0-9]{10}$/, t("phone_number_validation")),
+      .regex(/^\+?91[-\s]?[0-9]{10}$/, t("phone_number_validation")),

522-525: Reconsider form submission disabled state.

The current implementation disables the submit button when the form is not dirty (!form.formState.isDirty). This prevents users from submitting a form they've reviewed without changes, which might be a valid use case.

   disabled={
-    !form.formState.isDirty ||
     (facilityId ? isUpdatePending : isPending)
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 88f4110 and d1bac5e.

📒 Files selected for processing (2)
  • public/locale/en.json (13 hunks)
  • src/components/Facility/FacilityForm.tsx (12 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • public/locale/en.json

src/components/Facility/FacilityForm.tsx Show resolved Hide resolved
@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Jan 16, 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 (1)
src/components/Facility/FacilityForm.tsx (1)

65-85: Consider adding validation for coordinates format.

The latitude and longitude validation could be enhanced to ensure proper decimal format.

     latitude: z
       .string()
       .optional()
-      .refine((val) => !val || validateLatitude(val), t("invalid_latitude")),
+      .refine((val) => !val || validateLatitude(val), t("invalid_latitude"))
+      .refine(
+        (val) => !val || /^-?\d+(\.\d{1,6})?$/.test(val),
+        "Latitude must have up to 6 decimal places"
+      ),
     longitude: z
       .string()
       .optional()
-      .refine((val) => !val || validateLongitude(val), t("invalid_longitude")),
+      .refine((val) => !val || validateLongitude(val), t("invalid_longitude"))
+      .refine(
+        (val) => !val || /^-?\d+(\.\d{1,6})?$/.test(val),
+        "Longitude must have up to 6 decimal places"
+      ),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d1bac5e and 15ada03.

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

51-56: LGTM! Props interface is well-defined.

The FacilityProps interface clearly defines the component's contract with optional properties for both creation and editing scenarios.


359-374: LGTM! Good accessibility implementation.

The auto-fill notification includes proper ARIA attributes and visual feedback.


522-546: LGTM! Well-implemented loading states.

The submit button correctly handles loading states and provides clear feedback during form submission.


116-134: 🛠️ Refactor suggestion

Add error handling to mutations and queries.

The mutations and queries should handle error cases to provide better user feedback.

   const { mutate: updateFacility, isPending: isUpdatePending } = useMutation({
     mutationFn: mutate(routes.updateFacility, {
       pathParams: { id: facilityId || "" },
     }),
     onSuccess: (_data: FacilityModel) => {
       toast.success(t("facility_updated_successfully"));
       queryClient.invalidateQueries({ queryKey: ["organizationFacilities"] });
       form.reset();
       onSubmitSuccess?.();
     },
+    onError: (error: Error) => {
+      toast.error(t("facility_update_failed"), {
+        description: error.message
+      });
+    },
   });

-  const { data: facilityData } = useQuery({
+  const { data: facilityData, error: facilityError } = useQuery({
     queryKey: ["facility", facilityId],
     queryFn: query(routes.getPermittedFacility, {
       pathParams: { id: facilityId || "" },
     }),
     enabled: !!facilityId,
+    onError: (error: Error) => {
+      toast.error(t("facility_fetch_failed"), {
+        description: error.message
+      });
+    },
   });

Likely invalid or redundant comment.


379-393: 🛠️ Refactor suggestion

Add form label for OrganizationSelector.

The organization selector is missing a visible label, which impacts accessibility.

 <FormItem className="md:col-span-2 grid-cols-1 grid md:grid-cols-2 gap-5">
+  <FormLabel required>{t("organization")}</FormLabel>
   <FormControl>
     <OrganizationSelector
       {...field}
       value={form.watch("geo_organization")}
       selected={selectedLevels}
       onChange={(value) =>
         form.setValue("geo_organization", value)
       }
       required
     />
   </FormControl>
   <FormMessage />
 </FormItem>

Likely invalid or redundant comment.

src/components/Facility/FacilityForm.tsx Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
cypress/e2e/facility_spec/facility_creation.cy.ts (1)

5-8: Consider making LOCATION_HIERARCHY data dynamic.

The hardcoded values for localBody and ward could make tests brittle. Consider moving this to test data generation utilities like other facility data.

-const LOCATION_HIERARCHY = {
-  localBody: "Aluva",
-  ward: "4",
-};
+import { generateLocationHierarchy } from "../../utils/facilityData";
+const LOCATION_HIERARCHY = generateLocationHierarchy();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 15ada03 and 195b2a1.

📒 Files selected for processing (2)
  • cypress/e2e/facility_spec/facility_creation.cy.ts (2 hunks)
  • cypress/pageObject/facility/FacilityCreation.ts (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: cypress-run (1)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (4)
cypress/e2e/facility_spec/facility_creation.cy.ts (1)

44-44: LGTM! Good test coverage for location hierarchy.

The step is well-placed in the test flow and aligns with the PR objective of handling geo-organization information.

cypress/pageObject/facility/FacilityCreation.ts (3)

109-109: Consider the impact of reduced typing delay on test stability.

The typing delay has been reduced from 500ms to 200ms. While this makes tests faster, it might impact stability on slower systems or under heavy load.

Consider adding a comment explaining why this value was chosen and what factors were considered.


129-133: LGTM! Well-structured location hierarchy implementation.

The new method is well-implemented with:

  • Proper TypeScript typing
  • Reuse of existing cy.typeAndSelectOption helper
  • Method chaining support
  • Clear data-cy selectors

99-99: Verify if UI validation message matches the updated test assertion.

The validation message case has been changed from "Invalid pincode" to "Invalid Pincode". Please ensure this matches the actual UI validation message.

✅ Verification successful

Validation message case is correctly updated

The updated test assertion "Invalid Pincode" matches the official translation in the application's locale files, confirming this is the correct case to use.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the validation message string in the codebase
rg -i "invalid.?pincode" --type ts --type tsx

Length of output: 75


Script:

#!/bin/bash
# Search for pincode validation messages with various cases
rg -i "invalid.*pincode|pincode.*invalid" 

# Search for pincode-related form fields or validations
rg -i "pincode.*validation|validation.*pincode|pincode.*message"

Length of output: 1266

@nihal467
Copy link
Member

nihal467 commented Jan 16, 2025

conditional approving it.

Enhancement as a another PR

image

auto-fill the dropdown, based on the current organisation page user

@rithviknishad rithviknishad merged commit a4b4206 into ohcnetwork:develop Jan 16, 2025
17 checks passed
Copy link

@Mahendar0701 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
Development

Successfully merging this pull request may close these issues.

Switch to using Create Facility Form
5 participants