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

Patient Registration form refactor #9854

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

Conversation

khavinshankar
Copy link
Member

@khavinshankar khavinshankar commented Jan 9, 2025

  • Refactored PatientRegistration component to use react hook form
  • Added a couple of plugin hooks
  • Exposed core envs to global scope

Summary by CodeRabbit

Release Notes

  • Localization

    • Added multiple new validation messages and prompts for improved user guidance in forms.
  • Patient Registration

    • Enhanced patient registration form with improved validation using Zod and react-hook-form.
    • Simplified form layout and structure for better user experience.
  • Plugin System

    • Integrated new plugin component for patient actions in the PatientHome component.
    • Removed outdated plugin component from the EncounterContext.
  • Configuration

    • Improved handling of environment variables and expanded shared dependencies in build configuration.

khavinshankar and others added 30 commits January 8, 2025 23:48
…updating related components. Refactor organization level retrieval to use metadata for improved localization. Remove deprecated organization levels constant and clean up unused code in various components.
- Introduced a new PermissionContext to manage user permissions and super admin status across the application.
- Updated AppRouter to utilize PermissionProvider for managing permissions.
- Changed UserModel to store permissions as strings instead of objects.
- Refactored OrganizationFacilities and OrganizationPatients components to use updated permission checks and organization identifiers.
- Enhanced OrganizationLayout to conditionally render navigation items based on user permissions.

This commit improves the permission management system and ensures consistent handling of user permissions throughout the application.
- Introduced a new `searchPostFix` prop in `ValueSetSelect` to allow appending a suffix to the search query.
- Updated `MedicationRequestQuestion` and `MedicationStatementQuestion` components to utilize the `searchPostFix` prop with a default value of " clinical drug".
- This change enhances search functionality by providing more context in search queries.
Bumps [@tanstack/react-query-devtools](https://github.com/TanStack/query/tree/HEAD/packages/react-query-devtools) from 5.62.11 to 5.62.15.
- [Release notes](https://github.com/TanStack/query/releases)
- [Commits](https://github.com/TanStack/query/commits/HEAD/packages/react-query-devtools)

---
updated-dependencies:
- dependency-name: "@tanstack/react-query-devtools"
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Bodhisha Thomas <[email protected]>
Co-authored-by: Bodhish Thomas <[email protected]>
* Enhance encounter data handling by adding encounterId prop across multiple components

- Added `encounterId` prop to `ObservationChart`, `ObservationHistoryTable`, `ObservationsList`, `QuestionnaireResponsesList`, and `StructuredResponseView` components to improve data fetching and display related to specific encounters.
- Updated query parameters in API calls to include `encounterId` for better data context.
- Refactored `EncounterPlotsTab` and `EncounterUpdatesTab` to pass the new `encounterId` prop, ensuring consistent data handling across the application.

This change improves the overall functionality and user experience by ensuring that encounter-specific data is accurately retrieved and displayed.

* fix: disable encounter create button during save to prevent multiple submissions #9794
…anizationSelector labels

- Removed unused state and commented-out code in PatientHome for improved readability.
- Enhanced patient data display by updating the last updated and created by fields to use `updated_by` instead of `modified_by`.
- Updated date formatting functions to ensure consistent display of patient and encounter dates.
- Changed labels in FacilityOrganizationSelector from "Organization" to "Select Department" and adjusted related text for clarity.

These changes streamline the codebase and improve user interface clarity.
Copy link
Contributor

coderabbitai bot commented Jan 9, 2025

Walkthrough

This pull request introduces several changes across multiple files, focusing on enhancing localization, modifying the plugin architecture, and refactoring patient registration forms. Key modifications include adding new entries to the localization JSON file for improved user prompts and validation messages, integrating react-hook-form with Zod for form management in the PatientRegistration component, and adjusting the Vite configuration to expose core environment variables. The overall structure and functionality of various components have been refined to improve user experience and maintainability.

Changes

File Change Summary
public/locale/en.json Added multiple localization keys for validation messages and prompts
scripts/setup-care-apps.ts Improved formatting of pluginMapContent string generation
src/components/Facility/ConsultationDetails/EncounterContext.tsx Removed PLUGIN_Component usage
src/components/Patient/PatientHome.tsx Added PLUGIN_Component and modified layout
src/components/Patient/PatientRegistration.tsx Refactored form using react-hook-form and Zod validation
src/pluginTypes.ts Updated type definitions for patient-related components and plugins
vite.config.mts Added __CORE_ENV__ and expanded shared dependencies

Possibly related PRs

Suggested labels

needs review, tested, changes required

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

🐰 A rabbit's tale of code so bright,
Forms validated with Zod's might,
Plugins dance, components sway,
Localization finds its way!
Refactored magic takes its flight! 🚀


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

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit e18e448
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6780ab2f9c52610008403abf
😎 Deploy Preview https://deploy-preview-9854--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link

cloudflare-workers-and-pages bot commented Jan 9, 2025

Deploying care-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: e18e448
Status: ✅  Deploy successful!
Preview URL: https://cc6f06ef.care-fe.pages.dev
Branch Preview URL: https://abdm-micro-fe.care-fe.pages.dev

View logs

@khavinshankar khavinshankar marked this pull request as ready for review January 9, 2025 04:43
@khavinshankar khavinshankar requested a review from a team as a code owner January 9, 2025 04:43
Copy link

cypress bot commented Jan 9, 2025

CARE    Run #4225

Run Properties:  status check passed Passed #4225  •  git commit e18e44805d: Patient Registration form refactor
Project CARE
Branch Review abdm_micro_fe
Run status status check passed Passed #4225
Run duration 01m 33s
Commit git commit e18e44805d: Patient Registration form refactor
Committer Khavin Shankar
View all properties for this run ↗︎

Test results
Tests that failed  Failures 0
Tests that were flaky  Flaky 0
Tests that did not run due to a developer annotating a test with .skip  Pending 0
Tests that did not run due to a failure in a mocha hook  Skipped 0
Tests that passed  Passing 6
View all changes introduced in this branch ↗︎

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

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

229-242: Unnecessary use of useMemo for duplicatePatients

The duplicatePatients variable does not benefit significantly from memoization here, as the computation is minimal. Using useMemo might introduce unnecessary complexity.

You may simplify the code by removing useMemo:

-const duplicatePatients = useMemo(() => {
-  return patientPhoneSearch.data?.results.filter((p) => p.id !== patientId);
-}, [patientPhoneSearch.data, patientId]);
+const duplicatePatients = patientPhoneSearch.data?.results.filter((p) => p.id !== patientId);
src/pluginTypes.ts (1)

27-28: Update PatientRegistrationFormComponentType to use specific form types

Currently, form is typed as UseFormReturn<any>, which may reduce type safety. Consider specifying the exact form schema type to enhance type checking and prevent potential bugs.

For example:

-import { UseFormReturn } from "react-hook-form";
+import { UseFormReturn, FieldValues } from "react-hook-form";
+import { z } from "zod";
+import { formSchema } from "@/components/Patient/PatientRegistration";

export type PatientRegistrationFormComponentType = React.FC<{
-  form: UseFormReturn<any>;
+  form: UseFormReturn<z.infer<typeof formSchema>>;
  patientId?: string;
}>;

Ensure that the formSchema is exported from PatientRegistration and imported here.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8bec8bc and 0e5aea6.

📒 Files selected for processing (7)
  • public/locale/en.json (1 hunks)
  • scripts/setup-care-apps.ts (1 hunks)
  • src/components/Facility/ConsultationDetails/EncounterContext.tsx (0 hunks)
  • src/components/Patient/PatientHome.tsx (3 hunks)
  • src/components/Patient/PatientRegistration.tsx (7 hunks)
  • src/pluginTypes.ts (2 hunks)
  • vite.config.mts (2 hunks)
💤 Files with no reviewable changes (1)
  • src/components/Facility/ConsultationDetails/EncounterContext.tsx
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/Patient/PatientRegistration.tsx

[error] 418-418: 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)


[error] 457-457: 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 (6)
scripts/setup-care-apps.ts (1)

44-51: Ensure proper formatting of generated pluginMap.ts content

The added line breaks in the template string may affect the formatting of the generated pluginMap.ts. Verify that the output is as intended and the code remains syntactically correct.

Run the script and check the contents of pluginMap.ts to ensure it is correctly formatted and imports are resolved properly.

src/pluginTypes.ts (1)

22-24: Ensure PatientHomeActionsComponentType props are correctly typed

The new PatientHomeActionsComponentType expects a patient prop of type Patient. Verify that this aligns with the actual data being passed and that the Patient type correctly represents the patient data structure.

If necessary, update the Patient type import to match the correct patient model used in your application.

vite.config.mts (1)

198-203: LGTM: Shared dependencies update

Good addition of react-i18next and @tanstack/react-query to the shared dependencies. This will help avoid duplicate package loading across federated modules.

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

14-14: LGTM: Clean plugin integration

The PLUGIN_Component integration is well-implemented with proper props passing for patient data and styling.

Also applies to: 155-159


138-139: LGTM: Improved markup structure

Good cleanup of the div structure while maintaining the styling consistency.

public/locale/en.json (1)

1433-1433: LGTM: Added blood group selection message

The translation key follows the established naming pattern and provides clear user guidance.

src/components/Patient/PatientRegistration.tsx Outdated Show resolved Hide resolved
src/components/Patient/PatientRegistration.tsx Outdated Show resolved Hide resolved
src/components/Patient/PatientRegistration.tsx Outdated Show resolved Hide resolved
src/components/Patient/PatientRegistration.tsx Outdated Show resolved Hide resolved
vite.config.mts Show resolved Hide resolved
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.

i18n for schema errors missing

src/components/Patient/PatientRegistration.tsx Outdated Show resolved Hide resolved
src/components/Patient/PatientRegistration.tsx Outdated Show resolved Hide resolved
src/components/Patient/PatientRegistration.tsx Outdated Show resolved Hide resolved
src/components/Patient/PatientRegistration.tsx Outdated Show resolved Hide resolved
src/components/Patient/PatientRegistration.tsx Outdated Show resolved Hide resolved
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.

quick pass, lgtm

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/Patient/PatientRegistration.tsx (3)

169-172: Simplify year of birth calculation

The year of birth calculation in the success handler is complex and could be simplified.

Consider extracting this logic into a helper function:

+          const getYearOfBirth = (data: PatientModel) => {
+            if (data.date_of_birth) return new Date(data.date_of_birth).getFullYear();
+            return data.age ? new Date().getFullYear() - Number(data.age) : undefined;
+          };
+
           navigate(`/facility/${facilityId}/patients/verify`, {
             query: {
               phone_number: resp.phone_number,
-              year_of_birth:
-                form.getValues("yob_or_dob") === "dob"
-                  ? new Date(resp.date_of_birth!).getFullYear()
-                  : new Date().getFullYear() - Number(resp.age!),
+              year_of_birth: getYearOfBirth(resp),
               partial_id: resp?.id?.slice(0, 5),
             },
           });

273-279: Potential race condition in debounced phone number search

The current implementation might lead to race conditions where an older search result could override a newer one if the responses arrive out of order.

Consider using a request identifier or AbortController to handle this:

   useEffect(() => {
+    const abortController = new AbortController();
     const handler = setTimeout(() => {
       const phoneNumber = form.getValues("phone_number");
       if (!patientId || patientQuery.data?.phone_number !== phoneNumber) {
         setSuppressDuplicateWarning(false);
       }
       setDebouncedNumber(phoneNumber);
     }, 500);
 
     return () => {
       clearTimeout(handler);
+      abortController.abort();
     };
   }, [form.watch("phone_number")]); // eslint-disable-line react-hooks/exhaustive-deps

437-457: Add aria-labels for better accessibility

The blood group select component lacks proper aria-labels for screen readers.

Add appropriate aria labels:

                     <Select
                       {...field}
                       onValueChange={field.onChange}
                       defaultValue={field.value}
+                      aria-label={t("blood_group")}
                     >
                       <FormControl>
-                        <SelectTrigger>
+                        <SelectTrigger aria-label={t("select_blood_group")}>
                           <SelectValue
                             placeholder={t("please_select_blood_group")}
                           />
                         </SelectTrigger>
                       </FormControl>
-                      <SelectContent>
+                      <SelectContent aria-label={t("blood_group_options")}>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0e5aea6 and d6a8e1d.

📒 Files selected for processing (2)
  • public/locale/en.json (9 hunks)
  • src/components/Patient/PatientRegistration.tsx (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • public/locale/en.json
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: care-fe
🔇 Additional comments (2)
src/components/Patient/PatientRegistration.tsx (2)

488-495: ⚠️ Potential issue

Handle undefined values in date fields

The date field splitting logic doesn't handle undefined values, which could lead to runtime errors.

Add null checks and default values:

-                                value={
-                                  form.watch("date_of_birth")?.split("-")[2]
-                                }
+                                value={form.watch("date_of_birth")?.split("-")[2] || ""}
                                 onChange={(e) =>
                                   form.setValue(
                                     "date_of_birth",
-                                    `${form.watch("date_of_birth")?.split("-")[0]}-${form.watch("date_of_birth")?.split("-")[1]}-${e.target.value}`,
+                                    `${form.watch("date_of_birth")?.split("-")[0] || "YYYY"}-${form.watch("date_of_birth")?.split("-")[1] || "MM"}-${e.target.value}`,
                                   )
                                 }

Likely invalid or redundant comment.


562-574: 🛠️ Refactor suggestion

Simplify age calculation logic

The age calculation logic is complex and could be simplified. Also, the current implementation might not handle edge cases correctly.

Consider extracting this logic into a helper function:

+const calculateAge = (yearOfBirth: string) => {
+  const currentYear = new Date().getFullYear();
+  const parsedYear = Number(yearOfBirth);
+  return isNaN(parsedYear) ? '' : String(currentYear - parsedYear);
+};
+
+const calculateYearOfBirth = (age: string) => {
+  const currentYear = new Date().getFullYear();
+  const parsedAge = Number(age);
+  return isNaN(parsedAge) ? '' : String(currentYear - parsedAge);
+};

-                            value={
-                              new Date().getFullYear() -
-                              Number(form.watch("year_of_birth"))
-                            }
+                            value={calculateAge(form.watch("year_of_birth") || '')}
                             onChange={(e) =>
                               form.setValue(
                                 "year_of_birth",
-                                String(
-                                  new Date().getFullYear() -
-                                    Number(e.target.value),
-                                ),
+                                calculateYearOfBirth(e.target.value),
                               )
                             }

Likely invalid or redundant comment.

@khavinshankar khavinshankar requested a review from gigincg January 9, 2025 05:32
@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Jan 10, 2025
Copy link

👋 Hi, @khavinshankar,
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 removed the merge conflict pull requests with merge conflict label Jan 10, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

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

1450-1450: Fix typo in validation message

The word "Permanant" is misspelled in the validation message key and value.

Apply this diff to fix the typo:

-  "permanant_address_is_required": "Permanant address is required",
+  "permanent_address_is_required": "Permanent address is required",

Remember to update any references to this key in the code as well.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d6a8e1d and e18e448.

📒 Files selected for processing (2)
  • public/locale/en.json (9 hunks)
  • src/components/Patient/PatientRegistration.tsx (8 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Test
  • GitHub Check: OSSAR-Scan
  • GitHub Check: OSSAR-Scan
  • GitHub Check: Cloudflare Pages: care-fe
🔇 Additional comments (3)
src/components/Patient/PatientRegistration.tsx (3)

248-263: Add missing dependency in useEffect

The useEffect hook depends on form.reset but form is not included in the dependency array. This could lead to stale closures if the form reference changes.


555-566: Fix age calculation logic

The age calculation in the form appears to be incorrect. The current implementation may lead to wrong age values being displayed and stored.


404-416: Add key props to list items

Missing key props in list rendering can cause React performance issues and warnings.

Also applies to: 443-447

Comment on lines +89 to +91
phone_number: z
.string()
.regex(/^\+\d{12}$/, t("phone_number_must_be_10_digits")),
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix inconsistency in phone number validation

The regex pattern /^\+\d{12}$/ requires exactly 12 digits after the '+' sign, but the error message says "must be a 10-digit mobile number". This mismatch will confuse users.

Apply this diff to fix the validation:

-            .regex(/^\+\d{12}$/, t("phone_number_must_be_10_digits")),
+            .regex(/^\+\d{10}$/, t("phone_number_must_be_10_digits")),

Make the same change for emergency_phone_number validation as well.

Also applies to: 93-95

Comment on lines +476 to +489
<Input
type="number"
placeholder="DD"
{...field}
value={
form.watch("date_of_birth")?.split("-")[2]
}
onChange={(e) =>
form.setValue(
"date_of_birth",
`${form.watch("date_of_birth")?.split("-")[0]}-${form.watch("date_of_birth")?.split("-")[1]}-${e.target.value}`,
)
}
/>
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add validation for undefined date of birth values

When splitting form.watch("date_of_birth"), if the value is undefined or in an unexpected format, it could cause runtime errors.

Apply this diff to add validation:

value={
-  form.watch("date_of_birth")?.split("-")[2]
+  form.watch("date_of_birth")?.split("-")?.[2] || ""
}
onChange={(e) =>
  form.setValue(
    "date_of_birth",
-    `${form.watch("date_of_birth")?.split("-")[0]}-${form.watch("date_of_birth")?.split("-")[1]}-${e.target.value}`,
+    `${form.watch("date_of_birth")?.split("-")?.[0] || ""}-${form.watch("date_of_birth")?.split("-")?.[1] || ""}-${e.target.value}`,
  )
}

Apply similar changes to the month and year input handlers.

Also applies to: 495-508, 514-527

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.