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

Discharge Summary #10570

Merged
merged 7 commits into from
Feb 18, 2025
Merged

Discharge Summary #10570

merged 7 commits into from
Feb 18, 2025

Conversation

amjithtitus09
Copy link
Contributor

@amjithtitus09 amjithtitus09 commented Feb 12, 2025

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

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

Summary by CodeRabbit

  • New Features

    • Enhanced messaging for discharge summaries with new prompts and notifications.
    • Introduced a route for detailed encounter views, allowing navigation with a sub-page parameter.
    • Enabled discharge summary generation via an API endpoint.
    • Added a direct link to the discharge summary in the patient info dropdown menu.
  • Refactor

    • Updated file management by revising file categories and streamlining tab navigation.
    • Improved component interfaces to support granular sub-page interactions across encounters and files.
    • Modified organization data representation in the UI for better formatting and clarity.
    • Adjusted styling for better layout in various components.

@amjithtitus09 amjithtitus09 requested a review from a team as a code owner February 12, 2025 10:28
Copy link
Contributor

coderabbitai bot commented Feb 12, 2025

Walkthrough

The changes integrate discharge summary functionality across both front-end and back-end components. New internationalization keys and updated text improve user messaging for discharge summaries. A new route with a sub-page parameter is added to support detailed encounter views. Additionally, an API endpoint to generate discharge summaries has been introduced, and several components have been updated to handle mutations, dynamic tab filtering, and enhanced dropdown navigation.

Changes

Files Change Summary
public/locale/en.json Added multiple new keys (e.g., "discharge_summaries", "discharge_summary_emailed", etc.) and modified "download_discharge_summary" for consistent capitalization.
src/Routers/routes/ConsultationRoutes.tsx Added a new route at /facility/:facilityId/encounter/:encounterId/:tab/:subPage that renders the EncounterShow component with parameters.
src/Utils/request/api.tsx Introduced the generateDischargeSummary method with a POST request to /api/v1/encounter/{encounterId}/generate_discharge_summary/ returning { detail: string }.
src/components/Files/FilesTab.tsx, src/pages/Encounters/EncounterShow.tsx, src/pages/Encounters/tabs/EncounterFilesTab.tsx Enhanced components to support discharge summary functionality by adding a new subPage prop, revising file categories, implementing a mutation for summary generation, and updating dropdown/menu navigation.
src/components/Patient/PatientInfoCard.tsx Modified the dropdown menu to include a link to the discharge summary for the encounter.
src/Utils/utils.ts, src/components/Facility/ConsultationDetails/QuickAccess.tsx, src/pages/Appointments/AppointmentDetail.tsx Replaced the stringifyGeoOrganization function with stringifyNestedObject for broader applicability in formatting organization data.
src/components/Location/LocationHistorySheet.tsx Changed the class name of the SheetContent component for styling adjustments.
src/components/Location/LocationTree.tsx Adjusted the margin-left property of child nodes in the LocationNode component for visual layout changes.

Suggested labels

tested

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

Hoppin' through the code with glee,
I add new keys and routes merrily.
Discharge summaries now bloom bright and clear,
With API calls that make bugs disappear.
A rabbit's delight in every commit, so dear! 🐇


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 Feb 12, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 0d2c430
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67b421bd8e690a0008c51c48
😎 Deploy Preview https://deploy-preview-10570.preview.ohc.network
📱 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
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (5)
src/Utils/request/api.tsx (1)

565-569: Consider enhancing the API endpoint definition.

The endpoint is well-structured, but consider the following improvements:

  1. Add a request body type if any parameters are required
  2. Use a more descriptive response type name instead of the generic detail field

Please verify:

  1. Are there any required parameters for generating the discharge summary?
  2. What information should be included in the response besides the status message?
✅ Verification successful

🌐 Web query:

What are the best practices for RESTful API response structures when generating documents?

💡 Result:

When designing RESTful API response structures for document generation, key best practices focus on clarity, consistency, and developer usability. These principles ensure APIs are intuitive to consume while maintaining robustness across different scenarios.

HTTP Status Codes

Use semantic HTTP status codes to indicate request outcomes:

  • 200 OK for successful GET requests returning data ([3][5])
  • 201 Created after successful POST operations ([3][9])
  • 400 Bad Request for client-side input errors ([5][7])
  • 404 Not Found for missing resources ([7][9])

Data Structure

Adopt these patterns:

// Single resource response
{
  "id": "doc_123",
  "title": "API Guide",
  "author": "J. Smith",
  "created_at": "2025-02-12T10:31:06Z"
}

// List response with pagination
{
  "data": [
    { /* document object */ },
    { /* document object */ }
  ],
  "pagination": {
    "total": 100,
    "page": 5,
    "limit": 20
  }
}

([3][4][9])

Error Handling

Provide actionable error details:

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid document format",
    "details": [
      {
        "field": "title",
        "issue": "Maximum length exceeded (255 chars)"
      }
    ]
  }
}

([5][7][9])

Content Negotiation

Support multiple formats through headers:

Accept: application/json
Content-Type: application/json; charset=utf-8

([1][4][9])

Versioning

Implement through:

  1. URL path (/v1/documents)
  2. Custom headers (X-API-Version: 1.0)
    ([1][4][5])

Documentation Essentials

Include interactive examples using OpenAPI/Swagger with:

  • Request/response schemas
  • Authentication requirements
  • Error code explanations
  • Live testing capabilities ([2][8][10])

For document generation APIs specifically:

  1. Use template references in requests:
    {
      "template_id": "invoice_template",
      "data": {
        "customer_name": "Acme Corp",
        "items": [/*...*/]
      }
    }
  2. Return generation metadata:
    {
      "document_id": "doc_987",
      "download_url": "/documents/doc_987.pdf",
      "generated_at": "2025-02-12T10:35:00Z"
    }

([6][8][10])

Best practices evolve around making responses self-descriptive while maintaining strict adherence to REST principles. Implement consistent formatting across all endpoints and provide comprehensive documentation to ensure smooth integration experiences.

Citations:


Enhance API Endpoint Definition

  • API Parameters: The current configuration relies solely on the URL parameter (encounterId), and there’s no dedicated request body type. Verify if the discharge summary generation requires any additional data (e.g., options to customize the summary) beyond the encounter identifier.
  • Response Structure: Instead of returning just a generic detail message, consider expanding the response to include specific metadata. Best practices for document-generating endpoints recommend returning details such as:
    • document_id – a unique identifier for the generated document
    • download_url – a URL from which the document can be retrieved
    • generated_at – a timestamp indicating when the document was generated

These enhancements would align your API with established RESTful best practices, providing clients with clear, actionable information.

src/components/Files/FilesTab.tsx (3)

89-94: Consider using TypeScript enums or const objects for file categories.

While the implementation works, using TypeScript enums or const objects would provide better type safety and autocompletion.

-  const fileCategories = [
-    { value: "all", label: "All" },
-    { value: "audio", label: "Audio" },
-    { value: "xray", label: "X-Ray" },
-    { value: "identity_proof", label: "Identity Proof" },
-    { value: "unspecified", label: "Unspecified" },
-    { value: "discharge_summary", label: "Discharge Summary" },
-  ] as const;
+  const FILE_CATEGORIES = {
+    ALL: "all",
+    AUDIO: "audio",
+    XRAY: "xray",
+    IDENTITY_PROOF: "identity_proof",
+    UNSPECIFIED: "unspecified",
+    DISCHARGE_SUMMARY: "discharge_summary",
+  } as const;
+
+  const fileCategories = [
+    { value: FILE_CATEGORIES.ALL, label: "All" },
+    { value: FILE_CATEGORIES.AUDIO, label: "Audio" },
+    { value: FILE_CATEGORIES.XRAY, label: "X-Ray" },
+    { value: FILE_CATEGORIES.IDENTITY_PROOF, label: "Identity Proof" },
+    { value: FILE_CATEGORIES.UNSPECIFIED, label: "Unspecified" },
+    { value: FILE_CATEGORIES.DISCHARGE_SUMMARY, label: "Discharge Summary" },
+  ] as const;

653-671: Enhance tab navigation accessibility.

While the tab navigation works, consider adding ARIA labels and roles for better screen reader support.

-<TabsList className="grid w-auto grid-cols-2 w-fit">
+<TabsList className="grid w-auto grid-cols-2 w-fit" aria-label="File categories">
   <TabsTrigger value="all" asChild>
     <Link
       className="text-gray-600"
       href={`/facility/${encounter?.facility.id}/encounter/${encounter?.id}/files/all`}
+      role="tab"
+      aria-selected={subPage === "all"}
     >
       {t("all")}
     </Link>
   </TabsTrigger>
   <TabsTrigger value="discharge_summary" asChild>
     <Link
       className="text-gray-600"
       href={`/facility/${encounter?.facility.id}/encounter/${encounter?.id}/files/discharge_summary`}
+      role="tab"
+      aria-selected={subPage === "discharge_summary"}
     >
       {t("discharge_summary")}
     </Link>
   </TabsTrigger>
 </TabsList>

676-705: Enhance button keyboard accessibility.

While the buttons work well, consider adding keyboard shortcuts for common actions.

 <Button
   variant="outline_primary"
   className="flex flex-row items-center"
   onClick={() => queryClient.invalidateQueries({ queryKey: ["files"] })}
+  title={`${t("refresh")} (Ctrl+R)`}
+  onKeyDown={(e) => {
+    if (e.ctrlKey && e.key === 'r') {
+      e.preventDefault();
+      queryClient.invalidateQueries({ queryKey: ["files"] });
+    }
+  }}
 >
   <CareIcon icon="l-sync" />
   <span className="ml-2">{t("refresh")}</span>
 </Button>
public/locale/en.json (1)

954-954: Consider adding email validation message.

While the email-related strings are clear, consider adding a validation message for invalid email format.

Add a new key for email validation:

+"invalid_email_format": "Please enter a valid email address format (e.g., example@email.com)",

Also applies to: 978-978

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7d7cfd6 and 9e27bd6.

📒 Files selected for processing (7)
  • public/locale/en.json (10 hunks)
  • src/Routers/routes/ConsultationRoutes.tsx (1 hunks)
  • src/Utils/request/api.tsx (1 hunks)
  • src/components/Files/FilesTab.tsx (8 hunks)
  • src/components/Patient/PatientInfoCard.tsx (2 hunks)
  • src/pages/Encounters/EncounterShow.tsx (3 hunks)
  • src/pages/Encounters/tabs/EncounterFilesTab.tsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: cypress-run (1)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (9)
src/pages/Encounters/tabs/EncounterFilesTab.tsx (1)

11-11: LGTM!

The subPage prop is correctly passed through to the FilesTab component.

src/Routers/routes/ConsultationRoutes.tsx (1)

34-46: LGTM!

The new route is well-structured and correctly passes all required parameters to the EncounterShow component.

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

29-29: LGTM!

The subPage prop is correctly:

  • Typed as optional in both interfaces
  • Destructured from props
  • Passed down to child components

Also applies to: 48-48, 52-52, 79-79

src/components/Patient/PatientInfoCard.tsx (1)

448-472: LGTM! The discharge summary menu item is well integrated.

The implementation correctly adds a discharge summary option to the dropdown menu, with proper internationalization and routing.

src/components/Files/FilesTab.tsx (2)

1-64: LGTM! Props and imports are well structured.

The new imports and the optional subPage prop are properly integrated to support the discharge summary functionality.


113-123: LGTM! Query parameters are properly integrated.

The subPage parameter is correctly added to both the query key and filter parameters.

public/locale/en.json (3)

736-740: LGTM! Clear and consistent discharge summary related messages.

The new keys provide clear messaging for discharge summary functionality:

  • Consistent capitalization in "Discharge Summary" across all messages
  • Clear error and status messages
  • Informative disclaimer about computer-generated content

Also applies to: 747-747


773-773: LGTM! Improved capitalization consistency.

The modification of "download_discharge_summary" value from "Download discharge summary" to "Download Discharge Summary" improves consistency with other discharge summary related strings.


1078-1079: LGTM! Clear action button labels.

The action-related strings are clear and follow consistent capitalization:

  • "Generate" as a generic action
  • "Generate Discharge Summary" and "Regenerate Discharge Summary" as specific actions

Also applies to: 1762-1762

Copy link

cypress bot commented Feb 12, 2025

CARE    Run #4847

Run Properties:  status check failed Failed #4847  •  git commit 0d2c430bf5: Discharge Summary
Project CARE
Branch Review discharge-summary-ui
Run status status check failed Failed #4847
Run duration 04m 12s
Commit git commit 0d2c430bf5: Discharge Summary
Committer Amjith Titus
View all properties for this run ↗︎

Test results
Tests that failed  Failures 5
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 5
Tests that passed  Passing 1
View all changes introduced in this branch ↗︎

Tests for review

Failed  patient_spec/patient_creation.cy.ts • 1 failed test

View Output

Test Artifacts
Patient Management > creates a new non-binary patient | O+ blood group | multi-line address and verifies registration Test Replay Screenshots
Failed  facility_spec/facility_creation.cy.ts • 1 failed test

View Output

Test Artifacts
Facility Management > Create a new facility using the admin role and verify validation errors Test Replay Screenshots
Failed  users_spec/user_creation.cy.ts • 1 failed test

View Output

Test Artifacts
User Creation > should create a new user successfully Test Replay Screenshots
Failed  patient_spec/patient_details.cy.ts • 1 failed test

View Output

Test Artifacts
Patient Management > Assign users to a patient Test Replay Screenshots
Failed  patient_spec/patient_encounter.cy.ts • 1 failed test

View Output

Test Artifacts
Patient Encounter Questionnaire > Create a new ABG questionnaire and verify the values Test Replay Screenshots

Copy link

cloudflare-workers-and-pages bot commented Feb 12, 2025

Deploying care-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 0d2c430
Status: ✅  Deploy successful!
Preview URL: https://ad691c29.care-fe.pages.dev
Branch Preview URL: https://discharge-summary-ui.care-fe.pages.dev

View logs

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

272-287: LGTM! The generic implementation improves reusability.

The new stringifyNestedObject function is well-designed with:

  • Type-safe generic constraints
  • Customizable separator
  • Proper handling of optional parent property

Consider adding JSDoc documentation to describe the function's purpose and parameters:

+/**
+ * Converts a nested object hierarchy into a string representation.
+ * @param obj - The object to stringify, must have a name property and optional parent
+ * @param separator - The separator to use between levels, defaults to ", "
+ * @returns A string representation of the object hierarchy
+ */
 export const stringifyNestedObject = <
   T extends { name: string; parent?: Partial<T> },
 >(
   obj: T,
   separator = ", ",
 ) => {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bb61cac and cfa06ef.

📒 Files selected for processing (5)
  • src/Utils/utils.ts (1 hunks)
  • src/components/Facility/ConsultationDetails/QuickAccess.tsx (2 hunks)
  • src/components/Location/LocationHistorySheet.tsx (1 hunks)
  • src/components/Location/LocationTree.tsx (1 hunks)
  • src/pages/Appointments/AppointmentDetail.tsx (2 hunks)
✅ Files skipped from review due to trivial changes (2)
  • src/components/Location/LocationHistorySheet.tsx
  • src/components/Location/LocationTree.tsx
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: cypress-run (1)
  • GitHub Check: Cloudflare Pages: care-fe
🔇 Additional comments (2)
src/components/Facility/ConsultationDetails/QuickAccess.tsx (1)

89-89: LGTM! The change improves consistency in handling nested objects.

The switch to stringifyNestedObject aligns with the codebase's standardized approach for displaying hierarchical organization data.

src/pages/Appointments/AppointmentDetail.tsx (1)

324-324: LGTM! The change maintains consistency across the codebase.

The switch to stringifyNestedObject aligns with the standardized approach for displaying hierarchical data.

Copy link
Contributor

@Jacobjeevan Jacobjeevan left a comment

Choose a reason for hiding this comment

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

image

Adjust for mobile, lgtm otherwise

Copy link

Conflicts have been detected against the base branch. Please merge the base branch into your branch.
cc: @amjithtitus09

See: https://docs.ohc.network/docs/contributing#how-to-resolve-merge-conflicts

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Feb 17, 2025
@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Feb 18, 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

🧹 Nitpick comments (4)
src/Utils/utils.ts (1)

236-251: Add safety checks and documentation to the generic utility.

The implementation is well-structured and more reusable than the previous organization-specific function. Consider these improvements:

+/**
+ * Converts a nested object structure into a string representation by traversing its parent chain.
+ * Each object in the chain must have a name property and may have a parent reference.
+ *
+ * @example
+ * const obj = { name: "Child", parent: { name: "Parent" } };
+ * stringifyNestedObject(obj); // "Child, Parent"
+ * stringifyNestedObject(obj, " > "); // "Child > Parent"
+ *
+ * @param obj - The object to stringify
+ * @param separator - Optional separator between names (default: ", ")
+ * @returns A string representation of the object hierarchy
+ */
 export const stringifyNestedObject = <
   T extends { name: string; parent?: Partial<T> },
 >(
   obj: T,
   separator = ", ",
 ) => {
+  if (!obj) return "";
+
   const levels: string[] = [];
+  const seen = new Set<Partial<T>>();
 
   let current: Partial<T> | undefined = obj;
-  while (current?.name) {
+  while (current?.name && !seen.has(current)) {
     levels.push(current.name);
+    seen.add(current);
     current = current.parent;
   }
 
   return levels.join(separator);
 };

The improvements include:

  1. Added JSDoc documentation with examples
  2. Added protection against circular references using a Set
  3. Added null/undefined check for input object
src/components/Files/FilesTab.tsx (3)

64-64: Enhance type safety for the subPage prop.

Consider using a union type of valid page values instead of a string type to prevent potential runtime errors.

-  subPage?: string;
+  subPage?: "all" | "discharge_summary" | "xray" | "identity_proof" | "unspecified";

674-707: Remove unnecessary fragments.

The fragments wrapping the refresh and generate buttons are redundant as they each contain only one child component.

-          {subPage === "discharge_summary" && (
-            <>
-              <Button
-                variant="outline_primary"
-                className="flex flex-row items-center"
-                onClick={async () => {
-                  await queryClient.invalidateQueries({
-                    queryKey: ["files"],
-                  });
-                  toast.success(t("refreshed"));
-                }}
-              >
-                <CareIcon icon="l-sync" />
-                <span className="ml-2">{t("refresh")}</span>
-              </Button>
-            </>
-          )}
-          {subPage === "discharge_summary" && (
-            <>
-              <Button
-                variant="primary"
-                className="flex flex-row items-center"
-                onClick={() => generateDischargeSummary()}
-                disabled={isGenerating}
-              >
-                <CareIcon icon="l-file-medical" className="hidden md:block" />
-                <span>
-                  {isGenerating
-                    ? t("generating")
-                    : t("generate_discharge_summary")}
-                </span>
-              </Button>
-            </>
-          )}
+          {subPage === "discharge_summary" && (
+              <Button
+                variant="outline_primary"
+                className="flex flex-row items-center"
+                onClick={async () => {
+                  await queryClient.invalidateQueries({
+                    queryKey: ["files"],
+                  });
+                  toast.success(t("refreshed"));
+                }}
+              >
+                <CareIcon icon="l-sync" />
+                <span className="ml-2">{t("refresh")}</span>
+              </Button>
+          )}
+          {subPage === "discharge_summary" && (
+              <Button
+                variant="primary"
+                className="flex flex-row items-center"
+                onClick={() => generateDischargeSummary()}
+                disabled={isGenerating}
+              >
+                <CareIcon icon="l-file-medical" className="hidden md:block" />
+                <span>
+                  {isGenerating
+                    ? t("generating")
+                    : t("generate_discharge_summary")}
+                </span>
+              </Button>
+          )}
🧰 Tools
🪛 Biome (1.9.4)

[error] 675-689: Avoid using unnecessary Fragment.

A fragment is redundant if it contains only one child, or if it is the child of a html element, and is not a keyed fragment.
Unsafe fix: Remove the Fragment

(lint/complexity/noUselessFragments)


[error] 692-706: Avoid using unnecessary Fragment.

A fragment is redundant if it contains only one child, or if it is the child of a html element, and is not a keyed fragment.
Unsafe fix: Remove the Fragment

(lint/complexity/noUselessFragments)


654-671: Consider making tab navigation more dynamic.

The current implementation hardcodes tabs for "all" and "discharge_summary". Consider generating tabs dynamically from the fileCategories array to make it more maintainable.

-        <TabsList className="grid w-auto grid-cols-2 w-fit">
-          <TabsTrigger value="all" asChild>
-            <Link
-              className="text-gray-600"
-              href={`/facility/${encounter?.facility.id}/encounter/${encounter?.id}/files/all`}
-            >
-              {t("all")}
-            </Link>
-          </TabsTrigger>
-          <TabsTrigger value="discharge_summary" asChild>
-            <Link
-              className="text-gray-600"
-              href={`/facility/${encounter?.facility.id}/encounter/${encounter?.id}/files/discharge_summary`}
-            >
-              {t("discharge_summary")}
-            </Link>
-          </TabsTrigger>
-        </TabsList>
+        <TabsList className={`grid w-auto grid-cols-${fileCategories.length} w-fit`}>
+          {fileCategories.map((category) => (
+            <TabsTrigger key={category.value} value={category.value} asChild>
+              <Link
+                className="text-gray-600"
+                href={`/facility/${encounter?.facility.id}/encounter/${encounter?.id}/files/${category.value}`}
+              >
+                {t(category.value)}
+              </Link>
+            </TabsTrigger>
+          ))}
+        </TabsList>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4bec005 and 9efc836.

📒 Files selected for processing (6)
  • public/locale/en.json (10 hunks)
  • src/Routers/routes/ConsultationRoutes.tsx (1 hunks)
  • src/Utils/request/api.tsx (1 hunks)
  • src/Utils/utils.ts (1 hunks)
  • src/components/Files/FilesTab.tsx (8 hunks)
  • src/components/Patient/PatientInfoCard.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/Routers/routes/ConsultationRoutes.tsx
  • src/components/Patient/PatientInfoCard.tsx
  • src/Utils/request/api.tsx
  • public/locale/en.json
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/Files/FilesTab.tsx

[error] 675-689: Avoid using unnecessary Fragment.

A fragment is redundant if it contains only one child, or if it is the child of a html element, and is not a keyed fragment.
Unsafe fix: Remove the Fragment

(lint/complexity/noUselessFragments)


[error] 692-706: Avoid using unnecessary Fragment.

A fragment is redundant if it contains only one child, or if it is the child of a html element, and is not a keyed fragment.
Unsafe fix: Remove the Fragment

(lint/complexity/noUselessFragments)

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Test
  • GitHub Check: lint
  • GitHub Check: cypress-run (1)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: OSSAR-Scan
  • GitHub Check: Cloudflare Pages: care-fe
🔇 Additional comments (3)
src/Utils/utils.ts (1)

229-234: LGTM! Well-structured generic utility function.

The function follows the same pattern as conditionalAttribute but for arrays, with good type safety through generics.

src/components/Files/FilesTab.tsx (2)

97-106: Add error handling to the discharge summary mutation.

The mutation handles success but lacks error handling. Consider adding an onError handler to show error messages to users.


113-124: LGTM! Query implementation is well-structured.

The query implementation correctly handles the subPage parameter and follows React Query best practices.

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 (2)
src/components/Files/FilesTab.tsx (2)

653-671: Consider adding loading state to tab navigation.

The tab navigation could benefit from a loading state to prevent jarring UI updates during navigation.

Consider adding a loading state:

-      <Tabs defaultValue={subPage}>
+      <Tabs defaultValue={subPage} className={cn(filesLoading && "opacity-50 pointer-events-none")}>

674-707: Remove unnecessary fragments.

The fragments wrapping single elements are redundant.

Apply this diff to remove unnecessary fragments:

-          {subPage === "discharge_summary" && (
-            <>
               <Button
                 variant="outline_primary"
                 className="flex flex-row items-center"
                 onClick={async () => {
                   await queryClient.invalidateQueries({
                     queryKey: ["files"],
                   });
                   toast.success(t("refreshed"));
                 }}
               >
                 <CareIcon icon="l-sync" />
                 <span className="ml-2">{t("refresh")}</span>
               </Button>
-            </>
-          )}
-          {subPage === "discharge_summary" && (
-            <>
               <Button
                 variant="primary"
                 className="flex flex-row items-center"
                 onClick={() => generateDischargeSummary()}
                 disabled={isGenerating}
               >
                 <CareIcon icon="l-file-medical" className="hidden sm:block" />
                 <span>
                   {isGenerating
                     ? t("generating")
                     : t("generate_discharge_summary")}
                 </span>
               </Button>
-            </>
-          )}
🧰 Tools
🪛 Biome (1.9.4)

[error] 675-689: Avoid using unnecessary Fragment.

A fragment is redundant if it contains only one child, or if it is the child of a html element, and is not a keyed fragment.
Unsafe fix: Remove the Fragment

(lint/complexity/noUselessFragments)


[error] 692-706: Avoid using unnecessary Fragment.

A fragment is redundant if it contains only one child, or if it is the child of a html element, and is not a keyed fragment.
Unsafe fix: Remove the Fragment

(lint/complexity/noUselessFragments)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9efc836 and 0d2c430.

📒 Files selected for processing (1)
  • src/components/Files/FilesTab.tsx (8 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/Files/FilesTab.tsx

[error] 675-689: Avoid using unnecessary Fragment.

A fragment is redundant if it contains only one child, or if it is the child of a html element, and is not a keyed fragment.
Unsafe fix: Remove the Fragment

(lint/complexity/noUselessFragments)


[error] 692-706: Avoid using unnecessary Fragment.

A fragment is redundant if it contains only one child, or if it is the child of a html element, and is not a keyed fragment.
Unsafe fix: Remove the Fragment

(lint/complexity/noUselessFragments)

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Test
  • GitHub Check: cypress-run (1)
  • GitHub Check: CodeQL-Build
  • GitHub Check: OSSAR-Scan
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (2)
src/components/Files/FilesTab.tsx (2)

1-65: LGTM! Clean import organization and interface update.

The new imports and interface changes are well-structured and properly typed.


97-106: Add error handling to the discharge summary mutation.

The mutation lacks error handling which could leave users unaware of failures.

Apply this diff to add error handling:

 const { mutate: generateDischargeSummary, isPending: isGenerating } =
   useMutation<{ detail: string }, HTTPError>({
     mutationFn: mutate(routes.encounter.generateDischargeSummary, {
       pathParams: { encounterId: encounter?.id || "" },
     }),
     onSuccess: (response) => {
       toast.success(response.detail);
       refetch();
     },
+    onError: (error) => {
+      toast.error(t("error_generating_discharge_summary"));
+      console.error("Error generating discharge summary:", error);
+    },
   });

@amjithtitus09 amjithtitus09 merged commit 4bb0fb7 into develop Feb 18, 2025
17 of 23 checks passed
@amjithtitus09 amjithtitus09 deleted the discharge-summary-ui branch February 18, 2025 06:07
Copy link

@amjithtitus09 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.

Re introduce discharge summary
3 participants