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

Prefill Structured Data; Add Edit Links for Structured #9992

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

Conversation

gigincg
Copy link
Member

@gigincg gigincg commented Jan 15, 2025

Proposed Changes

  • Add Edit Support for Structured Fields

@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 new questionnaires for Allergy Intolerance, Medication Statement, Diagnosis, and Symptoms.
    • Enhanced medication request and allergy tracking functionality.
    • Introduced a new component for displaying medication requests.
    • Added a message for "No allergies recorded".
  • Improvements

    • Updated localization support for various components.
    • Improved type safety for allergy verification statuses.
    • Added facility context to patient-related components.
  • Refactoring

    • Restructured medication request and allergy-related components.
    • Updated data fetching mechanisms using React Query.
    • Enhanced loading and rendering logic for allergy and diagnosis lists.
    • Refactored components to improve modularity and maintainability.

@gigincg gigincg requested a review from a team as a code owner January 15, 2025 12:05
Copy link
Contributor

coderabbitai bot commented Jan 15, 2025

Walkthrough

This pull request introduces a comprehensive set of changes across multiple components and files, focusing on enhancing localization, improving type safety, and refactoring components related to patient information such as allergies, medications, diagnoses, and symptoms. The changes include adding new localization entries, removing an endpoint, updating component structures, introducing new layout components, and improving type definitions for allergy verification and clinical statuses.

Changes

File Change Summary
public/locale/en.json Added new localization key "no_allergies_recorded"
src/Utils/request/api.tsx Removed medicationRequest endpoint
src/components/Medicine/MedicationRequestTable/index.tsx Renamed MedicineAdministrationSheet to MedicationRequestTable, updated data fetching logic
src/components/Patient/allergy/list.tsx Added facilityId prop, introduced AllergyListLayout component
src/components/Patient/diagnosis/list.tsx Added facilityId prop, introduced DiagnosisListLayout component
src/components/Patient/symptoms/list.tsx Added facilityId prop, introduced SymptomListLayout component
src/components/Questionnaire/QuestionTypes/AllergyQuestion.tsx Added ALLERGY_VERIFICATION_STATUS and AllergyVerificationStatus
src/types/emr/allergyIntolerance/allergyIntolerance.ts Added new types and updated interfaces for allergy statuses
src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx Updated to use useQuery for fetching medications, added patientId prop
src/components/Questionnaire/QuestionnaireForm.tsx Modified navigation prompt logic to prevent showing in development mode
src/components/Questionnaire/data/StructuredFormData.tsx Added new questionnaires for allergy intolerance, medication statement, diagnosis, and symptom
src/pages/Encounters/PrintPrescription.tsx Updated import for medication requests to use new API module
src/pages/Encounters/tabs/EncounterMedicinesTab.tsx Replaced MedicineAdministrationSheet with MedicationRequestTable
src/pages/Encounters/tabs/EncounterUpdatesTab.tsx Added facilityId prop to EncounterUpdatesTab component

Suggested labels

needs review, needs testing

Suggested reviewers

  • rithviknishad
  • bodhish

Possibly related PRs

Poem

🐰 A Rabbit's Refactor Tale 🐰

Types refined, components reshaped,
Localization strings carefully draped,
Allergies sorted, medications clear,
Code dancing with precision, oh so dear!
A symphony of changes, neat and bright! 🌟


📜 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 3de35dd and 82c70b5.

📒 Files selected for processing (4)
  • public/locale/en.json (1 hunks)
  • src/Utils/request/api.tsx (0 hunks)
  • src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (7 hunks)
  • src/components/Questionnaire/QuestionnaireForm.tsx (1 hunks)
💤 Files with no reviewable changes (1)
  • src/Utils/request/api.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/components/Questionnaire/QuestionnaireForm.tsx
  • public/locale/en.json
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: care-fe
🔇 Additional comments (5)
src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (5)

Line range hint 1-68: LGTM! Dependencies and prop changes are well-structured.

The new imports and prop changes align well with the component's enhanced functionality.


144-165: LGTM! Well-implemented medication removal logic.

The implementation correctly handles both existing and new records:

  • Existing records are soft-deleted by marking them as "entered_in_error"
  • New records are completely removed from the array

319-344: LGTM! UI changes provide clear visual feedback.

The implementation includes:

  • Clear tooltips for medication status
  • Proper button state management
  • Visual indication for medications marked as errors

Also applies to: 519-526


83-88: 🛠️ Refactor suggestion

Add error handling and loading states to the query implementation.

The current implementation lacks error handling and loading states. This could lead to a poor user experience if the API call fails or is in progress.

-const { data: patientMedications } = useQuery({
+const { data: patientMedications, error, isLoading } = useQuery({
+  enabled: !!patientId,
   queryKey: ["medications", patientId],
   queryFn: query(medicationRequestApi.list, {
     pathParams: { patientId },
   }),
 });

+if (error) {
+  toast.error(t("error_fetching_medications"));
+  return null;
+}
+
+if (isLoading) {
+  return <LoadingSpinner />;
+}

Likely invalid or redundant comment.


90-107: ⚠️ Potential issue

Fix useEffect dependencies and potential race conditions.

The effect hook has missing dependencies and potential race conditions:

  1. Missing dependencies could lead to stale closures
  2. Race conditions could occur if medications are updated elsewhere while fetching
 useEffect(() => {
-  if (patientMedications?.results && !medications.length) {
+  if (patientMedications?.results && !medications.length && !isLoading) {
     updateQuestionnaireResponseCB({
       ...questionnaireResponse,
       values: [
         {
           type: "medication_request",
           value: patientMedications.results,
         },
       ],
     });
     if (patientMedications.count > patientMedications.results.length) {
       toast.info(
         `Showing first ${patientMedications.results.length} of ${patientMedications.count} medications`,
       );
     }
   }
-}, [patientMedications]);
+}, [patientMedications, medications.length, questionnaireResponse, updateQuestionnaireResponseCB, isLoading]);

Likely invalid or redundant comment.


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

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 82c70b5
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/678a1f7e6f7c650008f55d9a
😎 Deploy Preview https://deploy-preview-9992--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 15, 2025

Deploying care-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 82c70b5
Status: ✅  Deploy successful!
Preview URL: https://c529a41e.care-fe.pages.dev
Branch Preview URL: https://structured-prefills.care-fe.pages.dev

View logs

Copy link

cypress bot commented Jan 15, 2025

CARE    Run #4346

Run Properties:  status check passed Passed #4346  •  git commit 82c70b5bc6: Prefill Structured Data; Add Edit Links for Structured
Project CARE
Branch Review structured_prefills
Run status status check passed Passed #4346
Run duration 02m 06s
Commit git commit 82c70b5bc6: Prefill Structured Data; Add Edit Links for Structured
Committer Gigin George
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 5
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: 0

🔭 Outside diff range comments (1)
src/components/Medicine/MedicationRequestTable/index.tsx (1)

Line range hint 211-218: Ensure consistent usage of status values

There's an inconsistency in the status value for "on hold": in the filtering logic, you use "on_hold", but in the getStatusVariant function, you check for "on-hold" (with a hyphen). This could lead to incorrect badge variants being displayed.

Apply this diff to correct the status value in getStatusVariant:

        switch (status) {
          case "active":
            return "default";
-          case "on-hold":
+          case "on_hold":
            return "secondary";
          case "cancelled":
            return "destructive";
          case "completed":
            return "primary";
          default:
            return "secondary";
        }
🧹 Nitpick comments (8)
src/components/Medicine/MedicationRequestTable/index.tsx (3)

56-63: Use patientId in pathParams for consistency

In the useQuery call, consider using the already defined patientId variable instead of encounter?.patient?.id || "" in the pathParams. This improves readability and ensures consistency throughout the code.

Apply this diff:

-          pathParams: { patientId: encounter?.patient?.id || "" },
+          pathParams: { patientId: patientId || "" },

56-63: Add error handling for data fetching

Consider adding error handling to manage potential errors during data fetching with useQuery. This ensures the component can gracefully handle and display error states to the user.


Line range hint 280-286: Implement the TODO for displaying dose and rate

There's a TODO comment indicating that the Medicine Administration Sheet needs to be rebuilt to properly display the dose and rate information. Implementing this functionality will enhance the completeness of the prescription entries.

Do you want me to help implement the dose and rate display or open a GitHub issue to track this task?

src/types/emr/allergyIntolerance/allergyIntolerance.ts (1)

41-47: Consider using i18n for verification status labels.

The hardcoded English strings in ALLERGY_VERIFICATION_STATUS should be moved to i18n files for better internationalization support.

-export const ALLERGY_VERIFICATION_STATUS = {
-  unconfirmed: "Unconfirmed",
-  confirmed: "Confirmed",
-  refuted: "Refuted",
-  presumed: "Presumed",
-  "entered-in-error": "Entered in Error",
-};
+export const ALLERGY_VERIFICATION_STATUS = {
+  unconfirmed: t("allergy.verification.unconfirmed"),
+  confirmed: t("allergy.verification.confirmed"),
+  refuted: t("allergy.verification.refuted"),
+  presumed: t("allergy.verification.presumed"),
+  "entered-in-error": t("allergy.verification.entered_in_error"),
+};
src/components/Patient/symptoms/list.tsx (1)

69-97: Consider extracting common layout pattern.

The layout component pattern is repeated across different list components. Consider creating a shared ListLayout component.

// src/components/shared/ListLayout.tsx
interface ListLayoutProps {
  title: string;
  editHref?: string;
  facilityId?: string;
  children: ReactNode;
}

export const ListLayout = ({
  title,
  editHref,
  facilityId,
  children,
}: ListLayoutProps) => {
  return (
    <Card>
      <CardHeader className="px-4 py-0 pt-4 flex justify-between flex-row">
        <CardTitle>{t(title)}</CardTitle>
        {facilityId && editHref && (
          <Link
            href={editHref}
            className="flex items-center gap-1 text-sm hover:text-gray-500"
          >
            <PencilIcon size={12} />
            {t("edit")}
          </Link>
        )}
      </CardHeader>
      <CardContent>{children}</CardContent>
    </Card>
  );
};
src/components/Patient/allergy/list.tsx (1)

114-119: Consider using a more explicit sorting function.

The sorting logic could be more readable with a dedicated function and explicit return values.

-            .sort((a, _b) => {
-              if (a.clinical_status === "inactive") {
-                return 1;
-              }
-              return -1;
-            })
+            .sort((a, b) => {
+              const isAInactive = a.clinical_status === "inactive";
+              const isBInactive = b.clinical_status === "inactive";
+              return isAInactive === isBInactive ? 0 : isAInactive ? 1 : -1;
+            })
src/components/Questionnaire/QuestionTypes/AllergyQuestion.tsx (1)

510-529: Enhance type safety with runtime validation.

The desktop view implementation could benefit from additional type safety.

Consider this safer implementation:

 onValueChange={(value) => {
-  if (value in ALLERGY_VERIFICATION_STATUS) {
+  if (Object.keys(ALLERGY_VERIFICATION_STATUS).includes(value)) {
     onUpdate?.({
       verification_status: value as AllergyVerificationStatus,
     });
   }
 }}
src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (1)

77-101: Consider adding error handling for the query.

The data fetching implementation looks good but could benefit from error handling.

Consider adding error handling:

-const { data: patientMedications } = useQuery({
+const { data: patientMedications, error } = useQuery({
   queryKey: ["medications", patientId],
   queryFn: query(medicationRequestApi.list, {
     pathParams: { patientId },
   }),
 });

 useEffect(() => {
+  if (error) {
+    toast.error("Failed to fetch medications");
+    return;
+  }
   if (patientMedications?.results && !medications.length) {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2fc9e33 and 4e7325b.

📒 Files selected for processing (15)
  • public/locale/en.json (1 hunks)
  • src/Utils/request/api.tsx (0 hunks)
  • src/components/Medicine/MedicationRequestTable/index.tsx (5 hunks)
  • src/components/Patient/allergy/list.tsx (5 hunks)
  • src/components/Patient/diagnosis/list.tsx (3 hunks)
  • src/components/Patient/symptoms/list.tsx (3 hunks)
  • src/components/Questionnaire/QuestionTypes/AllergyQuestion.tsx (4 hunks)
  • src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (4 hunks)
  • src/components/Questionnaire/QuestionnaireForm.tsx (1 hunks)
  • src/components/Questionnaire/data/StructuredFormData.tsx (1 hunks)
  • src/pages/Encounters/PrintPrescription.tsx (2 hunks)
  • src/pages/Encounters/tabs/EncounterMedicinesTab.tsx (1 hunks)
  • src/pages/Encounters/tabs/EncounterUpdatesTab.tsx (2 hunks)
  • src/types/emr/allergyIntolerance/allergyIntolerance.ts (2 hunks)
  • src/types/emr/medicationRequest/medicationRequestApi.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • src/Utils/request/api.tsx
🧰 Additional context used
📓 Learnings (1)
src/components/Questionnaire/QuestionnaireForm.tsx (1)
Learnt from: Jacobjeevan
PR: ohcnetwork/care_fe#9838
File: src/components/Questionnaire/QuestionnaireForm.tsx:100-105
Timestamp: 2025-01-14T05:04:43.093Z
Learning: The QuestionnaireForm component in care_fe uses raviger's useNavigationPrompt hook for handling navigation prompts, replacing a previous custom hook implementation.
🔇 Additional comments (26)
src/pages/Encounters/tabs/EncounterMedicinesTab.tsx (1)

1-8: Component replacement is correctly implemented

The MedicationRequestTable component replaces MedicineAdministrationSheet appropriately. The component is correctly imported and rendered with the required facilityId prop.

src/types/emr/medicationRequest/medicationRequestApi.ts (1)

6-13: API module is correctly defined

The medicationRequestApi module is properly structured, and the endpoint for listing medication requests is correctly specified with the appropriate path, method, and response type.

src/types/emr/allergyIntolerance/allergyIntolerance.ts (2)

4-11: LGTM! Well-defined type definitions enhance type safety.

The introduction of AllergyVerificationStatus and AllergyClinicalStatus types helps prevent invalid values and improves code maintainability.


16-17: LGTM! Type-safe interface updates.

Replacing string types with specific enum-like types improves type safety and provides better IntelliSense support.

Also applies to: 31-32

src/pages/Encounters/tabs/EncounterUpdatesTab.tsx (2)

10-13: LGTM! Consistent prop addition.

The facilityId prop is correctly added to the component's props.


22-44: LGTM! Consistent prop passing to child components.

The facilityId prop is consistently passed to all relevant list components.

src/components/Patient/symptoms/list.tsx (2)

18-18: LGTM! Clean props interface update.

The facilityId prop is correctly added as optional.

Also applies to: 21-25


36-65: LGTM! Well-structured component refactoring.

The use of SymptomListLayout improves code organization and reusability.

src/components/Patient/diagnosis/list.tsx (2)

69-97: Apply the same layout component suggestion.

Similar to the symptoms list, consider using a shared ListLayout component here as well.


84-92: Verify the requirement for encounterId check.

The edit link visibility differs from the symptoms component. Verify if both components should have the same conditions.

src/components/Questionnaire/data/StructuredFormData.tsx (5)

43-61: LGTM! Well-structured allergy questionnaire definition.

The allergy intolerance questionnaire follows the established pattern and includes all required fields.


63-81: LGTM! Well-structured medication questionnaire definition.

The medication statement questionnaire maintains consistency with other questionnaire definitions.


83-101: LGTM! Well-structured diagnosis questionnaire definition.

The diagnosis questionnaire follows the same pattern as other questionnaires.


103-121: LGTM! Well-structured symptom questionnaire definition.

The symptom questionnaire maintains consistency with other questionnaire definitions.


126-129: LGTM! Questionnaires properly exported.

All new questionnaires are correctly added to the FIXED_QUESTIONNAIRES export.

src/components/Patient/allergy/list.tsx (3)

26-26: LGTM! Optional facilityId prop added.

The facilityId prop is correctly marked as optional.


31-35: LGTM! Component signature updated.

The AllergyList component signature properly includes the new facilityId prop.


166-194: LGTM! Well-structured layout component.

The AllergyListLayout component properly handles the conditional rendering of the edit link based on facilityId and encounterId.

src/pages/Encounters/PrintPrescription.tsx (1)

27-27: LGTM! API import and usage updated.

The medicationRequestApi import and its usage in the query function are correctly implemented.

Also applies to: 96-96

src/components/Questionnaire/QuestionnaireForm.tsx (1)

101-101: LGTM! Navigation prompt disabled in dev mode.

Good improvement for developer experience. The change aligns with the retrieved learning about using raviger's useNavigationPrompt hook.

src/components/Questionnaire/QuestionTypes/AllergyQuestion.tsx (2)

50-53: LGTM! Good type safety improvements.

The imports are well-organized and improve type safety by introducing dedicated types and constants for allergy verification statuses.


Line range hint 355-371: LGTM! Clean implementation of verification status handling.

The mobile view implementation correctly uses type assertion and maps through the verification statuses dynamically.

src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (3)

2-2: LGTM! Well-organized imports.

The imports are properly organized and include necessary dependencies for data fetching and notifications.

Also applies to: 4-5


46-46: LGTM! Good separation of concerns.

The API and utility imports maintain a clean separation of concerns.

Also applies to: 57-57


62-62: LGTM! Clear interface definition.

The props interface is well-defined with the new patientId requirement.

Also applies to: 72-72

public/locale/en.json (1)

1346-1346: LGTM! Clear and consistent message.

The new localization entry follows the established pattern and provides a clear message.

Copy link

👋 Hi, @gigincg,
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 15, 2025
@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Jan 15, 2025
@github-actions github-actions bot added the Deploy-Failed Deplyment is not showing preview label Jan 15, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (3)
src/pages/Encounters/EncounterShow.tsx (2)

Line range hint 91-156: Clean up commented code and improve error handling.

There's a significant amount of commented-out code that should be removed if no longer needed. Additionally, error handling could be improved.

Consider:

  1. Removing commented code if it's no longer needed
  2. Adding error boundaries for better error isolation
  3. Implementing comprehensive error states
- // const encounterQuery = useTanStackQueryInstead(routes.encounter.get, {
-   // pathParams: { id: consultationId },
- // });
-
- // const consultationData = encounterQuery.data;
- // const bedId = consultationData?.current_bed?.bed_object?.id;

Line range hint 179-285: Enhance accessibility in navigation and tab components.

The navigation and tab components need accessibility improvements:

  1. Add proper ARIA attributes for tab navigation
  2. Ensure keyboard navigation works correctly
  3. Add screen reader support

Example improvements:

 <nav
   className="flex space-x-6 overflow-x-auto pb-2 pl-2"
   id="encounter_tab_nav"
+  role="tablist"
+  aria-label={t('encounter_tabs')}
 >
   {keysOf(tabs).map((tab) => (
     <Link
       key={tab}
       className={tabButtonClasses(props.tab === tab)}
       href={`/facility/${facilityId}/encounter/${encounterData.id}/${tab}`}
+      role="tab"
+      aria-selected={props.tab === tab}
+      aria-controls={`${tab}-panel`}
     >
       {t(`ENCOUNTER_TAB__${tab}`)}
     </Link>
   ))}
 </nav>
src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx (1)

Line range hint 105-122: Remove type casting and improve type safety in handleAddMedication.

The FIXME comment indicates a type casting issue that should be addressed.

-    value: newMedications as MedicationStatement[], // FIXME: Remove this cast
+    value: newMedications,

Consider updating the MEDICATION_STATEMENT_INITIAL_VALUE type to ensure type safety without casting:

const MEDICATION_STATEMENT_INITIAL_VALUE: Omit<MedicationStatement, 'medication' | 'patient' | 'encounter' | 'id'> & {
  status: MedicationStatementStatus;
} = {
  status: "active",
  reason: undefined,
  dosage_text: "",
  effective_period: undefined,
  information_source: MedicationStatementInformationSourceType.PATIENT,
  note: undefined,
};
🧹 Nitpick comments (6)
src/pages/Encounters/EncounterShow.tsx (2)

Line range hint 22-34: Consider splitting component responsibilities and improving data flow.

The component handles multiple concerns (data fetching, routing, UI). Consider:

  1. Extracting tab configuration into a separate module
  2. Creating a custom hook for encounter data fetching
  3. Re-evaluating the removal of EncounterProvider as prop drilling might impact maintainability

Also applies to: 39-43


Line range hint 39-43: Improve type safety and centralize route handling.

Consider:

  1. Creating typed route constants
  2. Centralizing URL construction
  3. Adding route parameter validation

Example implementation:

// routes.ts
export const encounterRoutes = {
  tab: (params: { facilityId: string, encounterId: string, tab: keyof typeof defaultTabs }) =>
    `/facility/${params.facilityId}/encounter/${params.encounterId}/${params.tab}`,
  // ... other routes
} as const;

Also applies to: 246-259

src/components/Medicine/MedicationRequestTable/index.tsx (1)

Line range hint 82-90: Enhance internationalization coverage.

Several UI strings should be moved to i18n files to align with the PR objectives:

  • "No matches found"
  • "No Prescriptions"
  • "No medications match"
  • "No medications have been prescribed yet"

Consider moving these strings to the i18n files:

-          <h3 className="font-medium">
-            {searching ? "No matches found" : "No Prescriptions"}
-          </h3>
-          <p className="text-sm text-muted-foreground">
-            {searching
-              ? `No medications match "${searchQuery}"`
-              : "No medications have been prescribed yet"}
-          </p>
+          <h3 className="font-medium">
+            {searching ? t("no_matches_found") : t("no_prescriptions")}
+          </h3>
+          <p className="text-sm text-muted-foreground">
+            {searching
+              ? t("no_medications_match", { query: searchQuery })
+              : t("no_medications_prescribed")}
+          </p>

Also applies to: 156-159

src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx (1)

85-102: Consider adding loading state handling and race condition prevention.

While the initialization logic works, there are a few improvements to consider:

  1. Add loading state handling to prevent UI flicker
  2. Add error handling for failed requests
  3. Prevent overwriting existing medications if they were manually added while fetching
 useEffect(() => {
-  if (patientMedications?.results && !medications.length) {
+  if (patientMedications?.results && !medications.length && !isError) {
     updateQuestionnaireResponseCB({
       ...questionnaireResponse,
       values: [
         {
           type: "medication_statement",
           value: patientMedications.results,
         },
       ],
     });
     if (patientMedications.count > patientMedications.results.length) {
       toast.info(
         `Showing first ${patientMedications.results.length} of ${patientMedications.count} medication statements`,
       );
     }
+  } else if (isError) {
+    toast.error("Failed to fetch existing medications");
   }
-}, [patientMedications]);
+}, [patientMedications, isError]);
src/types/emr/medicationStatement/medicationStatementApi.ts (2)

8-8: Add type safety for path parameters.

The path parameter {patientId} should be properly typed to ensure type safety when making API calls.

Consider adding path parameter typing:

-    path: "/api/v1/patient/{patientId}/medication/statement/",
+    path: "/api/v1/patient/{patientId}/medication/statement/" as const,
+    params: Type<{ patientId: string }>(),

6-12: Consider adding CRUD operations for complete structured data support.

Since this PR aims to add edit support for structured fields, consider extending the API to include:

  • POST endpoint for creating new statements
  • PUT/PATCH endpoint for updating statements
  • DELETE endpoint for removing statements

This would provide a complete set of operations for managing medication statements.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fcb58c7 and 4caed51.

📒 Files selected for processing (6)
  • src/components/Facility/ConsultationDetails/EncounterContext.tsx (0 hunks)
  • src/components/Medicine/MedicationRequestTable/index.tsx (5 hunks)
  • src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx (5 hunks)
  • src/pages/Encounters/EncounterShow.tsx (2 hunks)
  • src/pages/Encounters/tabs/EncounterMedicinesTab.tsx (1 hunks)
  • src/types/emr/medicationStatement/medicationStatementApi.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • src/components/Facility/ConsultationDetails/EncounterContext.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: care-fe
🔇 Additional comments (11)
src/pages/Encounters/tabs/EncounterMedicinesTab.tsx (1)

1-1: LGTM! Clean component refactor.

The switch to MedicationRequestTable with additional props improves type safety and data handling. Props are correctly derived from the parent component.

Also applies to: 8-12

src/components/Medicine/MedicationRequestTable/index.tsx (3)

1-1: LGTM! Well-implemented data fetching with React Query.

The implementation follows best practices:

  • Type-safe props interface
  • Proper query key structure
  • Query enabled condition prevents unnecessary requests

Also applies to: 17-17, 20-20, 22-26, 56-63


107-114: LGTM! Edit functionality properly implemented.

The edit button implementation:

  • Follows UI/UX patterns
  • Uses correct routing structure
  • Maintains consistent styling

Line range hint 284-301: Track technical debt: Rebuild Medicine Administration Sheet.

There's a TODO comment and commented-out code for dose_and_rate handling. Let's ensure this is tracked for future implementation.

Would you like me to:

  1. Create a GitHub issue to track this technical debt?
  2. Help implement the dose_and_rate handling?
src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx (4)

Line range hint 1-48: LGTM! Import statements and prop interface changes are well-organized.

The new imports and the addition of the patientId prop align well with the enhanced functionality for medication management.


78-83: LGTM! Data fetching implementation is correct.

The query key and fetching logic are properly implemented using @tanstack/react-query.


124-143: LGTM! Medication removal logic handles existing and new medications appropriately.

The differentiation between existing and new medications is well implemented, preserving history for existing records while allowing complete removal of new ones.


238-264: LGTM! The remove button implementation with tooltips enhances user experience.

The UI changes effectively communicate the difference between removing new medications and marking existing ones as entered-in-error. The tooltips and icons provide clear visual feedback.

src/types/emr/medicationStatement/medicationStatementApi.ts (3)

1-4: LGTM! Imports are well-structured.

The imports are appropriate for the functionality, using proper type imports and consistent path aliasing.


14-14: LGTM! Export is appropriate.

The default export of the API constant follows the module pattern consistently.


6-12: Verify the impact of switching from medicationRequest to medicationStatement.

Based on the AI summary, this endpoint is replacing usage of medicationRequestApi. This architectural change might require:

  1. Data migration plan for existing medication requests
  2. Update of dependent components
  3. Backwards compatibility consideration

Let's verify the impact:

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 (3)
src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (3)

144-165: Improve type safety and maintainability of status handling.

The status handling could be improved by using type assertions and constants for better maintainability.

+const MEDICATION_STATUS = {
+  ENTERED_IN_ERROR: 'entered_in_error' as const
+} as const;

 const medication = medications[medicationToDelete];
 if (medication.id) {
   // For existing records, update status to entered-in-error
   const newMedications = medications.map((med, i) =>
     i === medicationToDelete
-      ? { ...med, status: "entered_in_error" as const }
+      ? { ...med, status: MEDICATION_STATUS.ENTERED_IN_ERROR }
       : med,
   );

519-526: Improve semantics of error state styling.

The opacity styling for error state could be more semantic and maintainable.

-      className={cn(
-        "grid grid-cols-1 lg:grid-cols-[280px,180px,170px,160px,300px,230px,180px,250px,180px,160px,48px] border-b hover:bg-gray-50/50",
-        {
-          "opacity-50": medication.status === "entered_in_error",
-        },
-      )}
+      className={cn(
+        "grid grid-cols-1 lg:grid-cols-[280px,180px,170px,160px,300px,230px,180px,250px,180px,160px,48px] border-b hover:bg-gray-50/50",
+        "medication-row",
+        {
+          "medication-row--error": medication.status === MEDICATION_STATUS.ENTERED_IN_ERROR,
+        },
+      )}

Add the following CSS:

.medication-row--error {
  opacity: 0.5;
  pointer-events: none;
}

319-344: Extract tooltip text to constants.

The tooltip text should be extracted to constants for better maintainability and reusability.

+const TOOLTIP_TEXT = {
+  ENTERED_IN_ERROR: t("medication_already_marked_as_error"),
+  REMOVE: t("remove_medication"),
+} as const;

 <TooltipContent>
-  {medication.status === "entered_in_error"
-    ? t("medication_already_marked_as_error")
-    : t("remove_medication")}
+  {medication.status === MEDICATION_STATUS.ENTERED_IN_ERROR
+    ? TOOLTIP_TEXT.ENTERED_IN_ERROR
+    : TOOLTIP_TEXT.REMOVE}
 </TooltipContent>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4caed51 and 3de35dd.

📒 Files selected for processing (1)
  • src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: cypress-run (1)
  • GitHub Check: OSSAR-Scan

Comment on lines +83 to +88
const { data: patientMedications } = useQuery({
queryKey: ["medications", patientId],
queryFn: query(medicationRequestApi.list, {
pathParams: { patientId },
}),
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error and loading state handling for the query.

The useQuery implementation lacks error handling and loading state management, which could lead to poor user experience when the API call fails or is in progress.

 const { data: patientMedications } = useQuery({
+  enabled: !!patientId,
   queryKey: ["medications", patientId],
   queryFn: query(medicationRequestApi.list, {
     pathParams: { patientId },
   }),
 });
+const isLoading = !patientMedications;
+if (isLoading) {
+  return <LoadingSpinner />;
+}

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +90 to +107
useEffect(() => {
if (patientMedications?.results && !medications.length) {
updateQuestionnaireResponseCB({
...questionnaireResponse,
values: [
{
type: "medication_request",
value: patientMedications.results,
},
],
});
if (patientMedications.count > patientMedications.results.length) {
toast.info(
`Showing first ${patientMedications.results.length} of ${patientMedications.count} medications`,
);
}
}
}, [patientMedications]);
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 useEffect dependencies and potential race condition.

The useEffect hook is missing questionnaireResponse and updateQuestionnaireResponseCB in its dependency array, which could lead to stale closures. Also, there's a potential race condition if the medications are updated elsewhere while fetching.

 useEffect(() => {
-  if (patientMedications?.results && !medications.length) {
+  if (patientMedications?.results && !medications.length && !isLoading) {
     updateQuestionnaireResponseCB({
       ...questionnaireResponse,
       values: [
         {
           type: "medication_request",
           value: patientMedications.results,
         },
       ],
     });
     if (patientMedications.count > patientMedications.results.length) {
       toast.info(
         `Showing first ${patientMedications.results.length} of ${patientMedications.count} medications`,
       );
     }
   }
-}, [patientMedications]);
+}, [patientMedications, medications.length, questionnaireResponse, updateQuestionnaireResponseCB]);

Committable suggestion skipped: line range outside the PR's diff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Deploy-Failed Deplyment is not showing preview
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants