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

Fix: Distinguish Active and Ended Medicines #10963

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

Conversation

Sulochan-khadka
Copy link
Contributor

@Sulochan-khadka Sulochan-khadka commented Mar 3, 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
    • The medication list now prioritizes active medications for easier viewing.
    • A visual badge has been added to clearly indicate the status of each medication.

@Sulochan-khadka Sulochan-khadka requested a review from a team as a code owner March 3, 2025 10:15
Copy link
Contributor

coderabbitai bot commented Mar 3, 2025

Walkthrough

This change updates the MedicationRequestQuestion component to sort medication entries by status. A new constant, sortedMedications, is added to prioritize "active" medications over "ended" ones, with a fallback for unrecognized statuses. The component's rendering logic now maps the sorted array and conditionally displays a Badge component styled according to the medication status.

Changes

File Path Change Summary
src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx Added a new constant sortedMedications to sort medications by status and updated rendering to include a conditional Badge component for status visualization.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant MRQ as MedicationRequestQuestion Component
    participant S as Sorting Logic
    participant B as Badge Component

    U ->> MRQ: Initiate component render
    MRQ ->> S: Sort medications by status
    S -->> MRQ: Return sortedMedications
    MRQ ->> B: Conditionally render badge based on status
    B -->> MRQ: Return styled badge
    MRQ -->> U: Display sorted list with badges
Loading

Possibly related PRs

  • Medication Request | Added Authored On field  #10094: The changes in the main PR, which focus on sorting medications and enhancing their display, are related to the modifications in the retrieved PR that introduce the authored_on field and update the MedicationRequestQuestion component, as both involve direct alterations to the same component's logic and structure.

Suggested labels

tested, reviewed

Suggested reviewers

  • amjithtitus09
  • rithviknishad

Poem

I'm just a little rabbit, hopping with delight,
Sorting meds aligns our code just right.
Active and ended, each finds its place,
With badges shining, they light up the space.
Code carrots crunch as I celebrate this sight!
🥕🐇 Happy coding, day and night!


📜 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 95c250c and 268689c.

📒 Files selected for processing (1)
  • src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: cypress-run (1)

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.
  • @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 Mar 3, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 268689c
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67c684d45b5bc2000848c9bd
😎 Deploy Preview https://deploy-preview-10963.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.

@Sulochan-khadka
Copy link
Contributor Author

@nihal467 @amjithtitus09 Review the PR Please.

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

536-550: Consider refactoring the nested conditional rendering.

The current implementation has nested conditional checks which can make the code harder to maintain. Consider simplifying the logic.

-        <span>
-          {(medication.status === "active" ||
-            medication.status === "ended") && (
-            <Badge
-              variant={medication.status === "active" ? "primary" : "outline"}
-              className={`inline-flex items-center gap-1 ${
-                medication.status === "ended"
-                  ? "bg-gray-50/50 text-gray-500 border-gray-200"
-                  : ""
-              }`}
-            >
-              {t(`${medication.status}`)}
-            </Badge>
-          )}
-        </span>
+        {(medication.status === "active" || medication.status === "ended") && (
+          <Badge
+            variant={medication.status === "active" ? "primary" : "outline"}
+            className={`inline-flex items-center gap-1 ${
+              medication.status === "ended"
+                ? "bg-gray-50/50 text-gray-500 border-gray-200"
+                : ""
+            }`}
+          >
+            {t(`${medication.status}`)}
+          </Badge>
+        )}

186-191: Consider adding type safety for medication status.

The current implementation relies on string comparisons for status values without type validation. Consider using a more type-safe approach.

+  // Define allowed status types
+  type MedicationStatus = 'active' | 'ended' | string;
+
   const sortedMedications = [...medications].sort((a, b) => {
-    const statusOrder = { active: 0, ended: 1 };
-    const aOrder = statusOrder[a.status as keyof typeof statusOrder] ?? 2;
-    const bOrder = statusOrder[b.status as keyof typeof statusOrder] ?? 2;
+    const statusOrder: Record<MedicationStatus, number> = { active: 0, ended: 1 };
+    const aOrder = statusOrder[a.status as MedicationStatus] ?? 2;
+    const bOrder = statusOrder[b.status as MedicationStatus] ?? 2;
     return aOrder - bOrder;
   });

537-547: Extract status badge into a separate component for reusability.

Since the status badge might be used elsewhere in the application, consider extracting it into a reusable component.

This would make the code more maintainable and promote consistency across the application when displaying medication statuses.

// Suggested component (to be added elsewhere)
interface MedicationStatusBadgeProps {
  status: string;
}

const MedicationStatusBadge: React.FC<MedicationStatusBadgeProps> = ({ status }) => {
  if (status !== 'active' && status !== 'ended') return null;
  
  return (
    <Badge
      variant={status === "active" ? "primary" : "outline"}
      className={`inline-flex items-center gap-1 ${
        status === "ended"
          ? "bg-gray-50/50 text-gray-500 border-gray-200"
          : ""
      }`}
    >
      {t(`${status}`)}
    </Badge>
  );
};

// Then in your render function:
// <MedicationStatusBadge status={medication.status} />

186-191: Add caching for sorted medications to improve performance.

The current implementation re-sorts the medications array on every render. Consider using memoization to improve performance if the medications array is large.

-  const sortedMedications = [...medications].sort((a, b) => {
-    const statusOrder = { active: 0, ended: 1 };
-    const aOrder = statusOrder[a.status as keyof typeof statusOrder] ?? 2;
-    const bOrder = statusOrder[b.status as keyof typeof statusOrder] ?? 2;
-    return aOrder - bOrder;
-  });
+  const sortedMedications = React.useMemo(() => {
+    return [...medications].sort((a, b) => {
+      const statusOrder = { active: 0, ended: 1 };
+      const aOrder = statusOrder[a.status as keyof typeof statusOrder] ?? 2;
+      const bOrder = statusOrder[b.status as keyof typeof statusOrder] ?? 2;
+      return aOrder - bOrder;
+    });
+  }, [medications]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dd8c696 and 86ca8ea.

📒 Files selected for processing (1)
  • src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Redirect rules - care-ohc
  • GitHub Check: Header rules - care-ohc
  • GitHub Check: Pages changed - care-ohc
  • GitHub Check: cypress-run (1)
🔇 Additional comments (4)
src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (4)

18-18: Added necessary UI component import.

The Badge component import is now included to support the new visual indicators for medication status.


186-191: Good implementation of medication sorting logic.

The sorting logic effectively prioritizes medications with "active" status (order 0) before those with "ended" status (order 1), and places all other statuses (order 2) at the end. This meets the PR objective of distinguishing between active and ended medicines.

The implementation uses a clean approach with a statusOrder object and proper TypeScript typing with keyof typeof statusOrder.


273-273: Successfully applied the sorting to the rendered medication list.

The change from medications.map to sortedMedications.map ensures that medications are displayed in the prioritized order (active first, then ended, then others).


526-550: Well-implemented visual distinction between active and ended medications.

The code effectively implements the PR objective by:

  1. Adding status badges that visually distinguish between active and ended medications
  2. Using appropriate styling (primary badge for active, outline with gray for ended)
  3. Adding conditional text styling (graying out ended medication names)
  4. Ensuring the UI changes only apply to medications with relevant statuses

The implementation includes proper class conditionals and follows the existing styling patterns of the application.

…estion.tsx

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@rithviknishad
Copy link
Member

PR's not following the merge checklist will not be considered for review

@rithviknishad rithviknishad added invalid This doesn't seem right changes required labels Mar 4, 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

♻️ Duplicate comments (1)
src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (1)

544-546: 🛠️ Refactor suggestion

Ensure translation key format is correct

The current translation usage might not work as expected. Using template literals with the t function can be problematic if the translation system isn't configured to handle dynamic keys.

-              {t(`${medication.status}`)}
+              {t(medication.status)}

Also, ensure that both "active" and "ended" translations exist in all locales, not just English.

🧹 Nitpick comments (1)
src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (1)

186-191: Good implementation of medication sorting logic

The sorting implementation correctly prioritizes "active" medications over "ended" ones, improving the user experience. The use of keyof typeof for type safety is a good practice. Consider using useMemo for performance optimization if there are many medications:

-  const sortedMedications = [...medications].sort((a, b) => {
+  const sortedMedications = React.useMemo(() => [...medications].sort((a, b) => {
     const statusOrder = { active: 0, ended: 1 };
     const aOrder = statusOrder[a.status as keyof typeof statusOrder] ?? 2;
     const bOrder = statusOrder[b.status as keyof typeof statusOrder] ?? 2;
     return aOrder - bOrder;
-  });
+  }), [medications]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 86ca8ea and 95c250c.

📒 Files selected for processing (1)
  • src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (4 hunks)
🔇 Additional comments (3)
src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (3)

18-18: Appropriate use of Badge component

Good addition of the Badge component import which is used to visually distinguish medication statuses.


273-273: LGTM! Using the sorted medications array

Appropriately using the sorted array to render medications, ensuring active medications are displayed before ended ones.


526-549: Visual distinction for medication statuses needs i18n consideration

The Badge component implementation effectively distinguishes between active and ended medications. However, there's a potential i18n issue.

#!/bin/bash
# Description: Verify translation keys exist for medication statuses in i18n files

# Check for the "active" and "ended" keys in all translation files
echo "Looking for 'active' translation key:"
rg -l '"active":\s*"' --type json public/locales/

echo -e "\nLooking for 'ended' translation key:"
rg -l '"ended":\s*"' --type json public/locales/

Also, for consistent display in desktop layout, consider making the medication name always visible regardless of status:

-        <span
-          className={`break-words line-clamp-2 hidden lg:block ${
-            medication.status === "ended" ? "text-gray-500" : ""
-          }`}
-        >
+        <span
+          className={`break-words line-clamp-2 hidden lg:block ${
+            medication.status === "ended" ? "text-gray-500" : ""
+          }`}
+        >
           {medication.medication?.display}
         </span>

@@ -182,6 +183,12 @@ export function MedicationRequestQuestion({
questionnaireResponse.question_id,
);
};
const sortedMedications = [...medications].sort((a, b) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

image

Current logic would result in "active", "ended" and then everything else.

{medication.medication?.display}
</span>
<span>
{(medication.status === "active" ||
Copy link
Contributor

Choose a reason for hiding this comment

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

Same here, only showing badge for active or ended.

Copy link
Contributor

Choose a reason for hiding this comment

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

Complete the merge checklist as well.

@Jacobjeevan
Copy link
Contributor

@Sulochan-khadka Any updates?

@Sulochan-khadka
Copy link
Contributor Author

@Sulochan-khadka Any updates?

ETA : EOD

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
changes required invalid This doesn't seem right
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Edit medication questionnaire | Distinguish active & inactive medicines
3 participants