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

Added the CSV Export button In Discharged Patients #9142

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

Conversation

AnveshNalimela
Copy link
Contributor

@AnveshNalimela AnveshNalimela commented Nov 16, 2024

Proposed Changes

  • Fixes Add CSV Export support for Facility Specific Discharge Page #8993
    added export button with restriction based on seven-day period selection.
    Introduced an ExportMenu component to handle export of live patients when export is allowed.
    Implemented tooltip guidance for when export is not allowed, prompting the user to select a valid seven-day period.

@ohcnetwork/care-fe-code-reviewers

{CF705BEA-D06D-47A0-A06E-A5C69B52F219}

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 filtering options for discharged patients, including multiple date ranges and attributes.
    • Introduction of an ExportMenu for exporting patient data, with notifications for invalid selections.
    • Improved badge rendering for patient attributes, enhancing the user interface.
  • Bug Fixes

    • Refined logic for validating and updating phone number inputs.
    • Added functionality to prevent duplicate patient entries based on policy IDs.

@AnveshNalimela AnveshNalimela requested a review from a team as a code owner November 16, 2024 16:33
Copy link
Contributor

coderabbitai bot commented Nov 16, 2024

Walkthrough

The pull request introduces significant updates to the DischargedPatientsList component, enhancing its functionality for managing discharged patients. Key modifications include new imports for date handling and notifications, an updated useFilters hook with a resultsPerPage property, and an expanded params object for detailed filtering. A new function manages duplicate patient entries, while the rendering logic now includes an ExportMenu that is conditionally displayed based on date range evaluations. Enhanced badge rendering for patient attributes also improves the user interface.

Changes

File Path Change Summary
src/components/Facility/DischargedPatientsList.tsx - Added imports for dayjs, Notification, and request.
- Updated useFilters with resultsPerPage.
- Expanded params object for detailed filtering.
- Refined phone number handling logic.
- Added preventDuplicatePatientsDuetoPolicyId function for managing duplicates.
- Introduced ExportMenu based on isExportAllowed flag.
- Enhanced badge rendering for patient attributes.

Assessment against linked issues

Objective Addressed Explanation
Add export functionality to the facility-specific discharge patient list page. (#[8993])
Ensure the export option is enabled only after a 7-day period is selected in the date-based advanced filter. (#[8993])

Possibly related PRs

  • Fix min date for discharge  #9083: Changes in the DischargeModal component regarding date handling and validation logic are related to the DischargedPatientsList component, as both components deal with patient discharge processes and date management.

Suggested labels

needs review, tested

Suggested reviewers

  • rithviknishad

Poem

In the land of hops and playful cheer,
A list of patients, now crystal clear.
With exports ready, and filters so bright,
We manage discharges with all of our might!
No duplicates here, just smooth sailing ahead,
Hooray for the changes, let’s hop out of bed! 🐰✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

src/components/Facility/DischargedPatientsList.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

Error: Failed to load parser '@typescript-eslint/parser' declared in '.eslintrc.json': Cannot find module '@typescript-eslint/parser'
Require stack:

  • /.eslintrc.json
    at Module._resolveFilename (node:internal/modules/cjs/loader:1248:15)
    at Function.resolve (node:internal/modules/helpers:145:19)
    at Object.resolve (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:2346:46)
    at ConfigArrayFactory._loadParser (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3325:39)
    at ConfigArrayFactory._normalizeObjectConfigDataBody (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3099:43)
    at _normalizeObjectConfigDataBody.next ()
    at ConfigArrayFactory._normalizeObjectConfigData (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3040:20)
    at _normalizeObjectConfigData.next ()
    at ConfigArrayFactory.loadInDirectory (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:2886:28)
    at CascadingConfigArrayFactory._loadConfigInAncestors (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3871:46)

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 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 Nov 16, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 472221a
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6738d19a5d3e100008995f2d
😎 Deploy Preview https://deploy-preview-9142--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
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: 4

🧹 Outside diff range and nitpick comments (3)
src/components/Facility/DischargedPatientsList.tsx (3)

203-210: Use forEach instead of map for side effects

The Array.prototype.map method is used for transforming arrays and returns a new array. Since the returned array isn't utilized, forEach is more appropriate for iterating over the array for side effects.

Apply this diff to use forEach:

-    lines.map((line: any, i: number) => {
+    lines.forEach((line: any, i: number) => {

199-245: Correct grammatical errors in comments

There are typographical errors and grammatical issues in the comments, such as "imforamation" and "there" instead of "their". Correcting these will improve code readability.

Example correction:

-    // Generate a array which contains imforamation of duplicate patient IDs and there respective linenumbers
+    // Generate an array that contains information about duplicate patient IDs and their respective line numbers

455-465: Adjust scroll target to appropriate filter section

When the export is not allowed, clicking the export button opens the advanced filter and scrolls to an element with the ID bed-type-select. Since the issue is related to selecting a date range, the scroll target should be the date range selector.

Apply this diff to update the scroll target:

-                          const element =
-                            document.getElementById("bed-type-select");
+                          const element =
+                            document.getElementById("created-date-select");

Ensure that the date range selector has the corresponding ID created-date-select or adjust the ID accordingly.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between da5d576 and f44f67f.

📒 Files selected for processing (1)
  • src/components/Facility/DischargedPatientsList.tsx (5 hunks)
🔇 Additional comments (1)
src/components/Facility/DischargedPatientsList.tsx (1)

195-196: ⚠️ Potential issue

Reevaluate the logic for allowing export

The isExportAllowed condition may not align with the requirement that the export is permitted only when a valid seven-day period is selected. Currently, if no date ranges are selected (durations contains zeros), isExportAllowed might erroneously allow exports.

Please verify and adjust the logic to ensure that export is allowed only when at least one date range of up to seven days is selected. Consider modifying the condition as follows:

-    durations.every((x) => x >= 0 && x <= 7) &&
-    !durations.every((x) => x === 0);
+    durations.some((x) => x > 0 && x <= 7);

disabled={!isExportAllowed}
exportItems={[
{
label: "Export Live patients",
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

Update export label to "Export Discharged patients"

The label for the export action is currently "Export Live patients", which does not reflect the context of the discharged patients list.

Apply this diff to correct the label:

-                          label: "Export Live patients",
+                          label: "Export Discharged patients",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
label: "Export Live patients",
label: "Export Discharged patients",

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

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
src/components/Facility/DischargedPatientsList.tsx (2)

452-505: Improve configurability of export UI behavior

The implementation has several hard-coded values that should be configurable:

  1. Timeout duration for scroll animation
  2. Scroll behavior configuration
  3. Magic number in tooltip text

Consider these improvements:

+ const EXPORT_CONFIG = {
+   SCROLL_DELAY_MS: 500,
+   MAX_EXPORT_DAYS: 7,
+   SCROLL_BEHAVIOR: 'smooth' as ScrollBehavior
+ };
+
  <div className="tooltip w-full md:w-auto" id="patient-export">
    {!isExportAllowed ? (
      <ButtonV2
        onClick={() => {
          advancedFilter.setShow(true);
          setTimeout(() => {
            const element = document.getElementById("bed-type-select");
            if (element)
              element.scrollIntoView({ 
-               behavior: "smooth" 
+               behavior: EXPORT_CONFIG.SCROLL_BEHAVIOR
              });
            Notification.Warn({
-             msg: "Please select a seven day period.",
+             msg: `Please select a ${EXPORT_CONFIG.MAX_EXPORT_DAYS} day period.`,
            });
-         }, 500);
+         }, EXPORT_CONFIG.SCROLL_DELAY_MS);
        }}

473-497: Add loading state to export functionality

The export action should indicate its progress to prevent multiple clicks and provide feedback to users.

Consider adding loading state:

  <ExportMenu
    disabled={!isExportAllowed}
    exportItems={[
      {
        label: "Export Discharged patients",
+       showLoading: true,
        action: async () => {
+         try {
            const query = {
              ...qParams,
              csv: true,
            };
            const pathParams = { facility_external_id };
            const { data } = await request(
              routes.listFacilityDischargedPatients,
              {
                query,
                pathParams,
              },
            );
            return data ?? null;
+         } catch (error) {
+           Notification.Error({
+             msg: "Failed to export patients data",
+           });
+           return null;
+         }
        },
        parse: preventDuplicatePatientsDuetoPolicyId,
      },
    ]}
  />
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f44f67f and 472221a.

📒 Files selected for processing (1)
  • src/components/Facility/DischargedPatientsList.tsx (5 hunks)
🔇 Additional comments (1)
src/components/Facility/DischargedPatientsList.tsx (1)

183-192: ⚠️ Potential issue

Fix duration calculation logic

The current implementation has a few issues:

  1. The duration calculation can result in negative values
  2. The comment about XOR is misleading as it's using logical operators

Apply this diff to fix the issues:

  const durations = date_range_fields.map((field: string[]) => {
-   // XOR (checks if only one of the dates is set)
+   // Check if exactly one date is set
    if ((field[0] && !field[1]) || (!field[0] && field[1])) {
      return -1;
    }
    if (field[0] && field[1]) {
-     return dayjs(field[0]).diff(dayjs(field[1]), "days");
+     return Math.abs(dayjs(field[1]).diff(dayjs(field[0]), "days"));
    }
    return 0;
  });

Likely invalid or redundant comment.

Comment on lines +198 to +248
const preventDuplicatePatientsDuetoPolicyId = (data: any) => {
// Generate a array which contains imforamation of duplicate patient IDs and there respective linenumbers
const lines = data.split("\n"); // Split the data into individual lines
const idsMap = new Map(); // To store indices of lines with the same patient ID

lines.map((line: any, i: number) => {
const patientId = line.split(",")[0]; // Extract the patient ID from each line
if (idsMap.has(patientId)) {
idsMap.get(patientId).push(i); // Add the index to the existing array
} else {
idsMap.set(patientId, [i]); // Create a new array with the current index
}
});

const linesWithSameId = Array.from(idsMap.entries())
.filter(([_, indices]) => indices.length > 1)
.map(([patientId, indices]) => ({
patientId,
indexSame: indices,
}));

// after getting the array of duplicate patient IDs and there respective linenumbers we will merge the policy IDs of the duplicate patients

linesWithSameId.map((lineInfo) => {
const indexes = lineInfo.indexSame;
//get policyid of all the duplicate patients and merge them by seperating them with a semicolon
const mergedPolicyId = indexes
.map((currentIndex: number) => lines[currentIndex].split(",")[5])
.join(";");
// replace the policy ID of the first patient with the merged policy ID
const arrayOfCurrentLine = lines[indexes[0]].split(",");
arrayOfCurrentLine[5] = mergedPolicyId;
const lineAfterMerge = arrayOfCurrentLine.join(",");
lines[indexes[0]] = `${lineAfterMerge}`;
});

// after merging the policy IDs of the duplicate patients we will remove the duplicate patients from the data
const uniqueLines = [];
const ids = new Set(); // To keep track of unique patient IDs

for (const line of lines) {
const patientId = line.split(",")[0]; // Extract the patient ID from each line
if (!ids.has(patientId)) {
uniqueLines.push(line);
ids.add(patientId);
}
}

const cleanedData = uniqueLines.join("\n"); // Join the unique lines back together
return cleanedData;
};
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

Improve robustness of CSV processing

The current implementation has several issues that could make it fragile:

  1. Uses 'any' type instead of proper typing
  2. Assumes specific CSV column positions without validation
  3. No error handling for malformed data

Consider these improvements:

- const preventDuplicatePatientsDuetoPolicyId = (data: any) => {
+ interface CSVRow {
+   patientId: string;
+   policyId: string;
+   [key: string]: string;
+ }
+ 
+ const preventDuplicatePatientsDuetoPolicyId = (data: string) => {
+   try {
      const lines = data.split("\n");
-     const idsMap = new Map();
+     const idsMap = new Map<string, number[]>();
+     const PATIENT_ID_INDEX = 0;
+     const POLICY_ID_INDEX = 5;

      lines.map((line: string, i: number) => {
+       if (!line.trim()) return;
+       const columns = line.split(",");
+       if (columns.length <= POLICY_ID_INDEX) {
+         throw new Error(`Invalid CSV format at line ${i + 1}`);
+       }
-       const patientId = line.split(",")[0];
+       const patientId = columns[PATIENT_ID_INDEX];
        // ... rest of the implementation
      });
+   } catch (error) {
+     console.error("Error processing CSV:", error);
+     throw new Error("Failed to process CSV data");
+   }
  };

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

Comment on lines +82 to +154
const params = {
page: qParams.page || 1,
limit: resultsPerPage,
name: qParams.name || undefined,
patient_no: qParams.patient_no || undefined,
is_active:
!qParams.last_consultation__new_discharge_reason &&
(qParams.is_active || "False"),
phone_number: qParams.phone_number
? parsePhoneNumber(qParams.phone_number)
: undefined,
emergency_phone_number: qParams.emergency_phone_number
? parsePhoneNumber(qParams.emergency_phone_number)
: undefined,
local_body: qParams.lsgBody || undefined,
facility: qParams.facility,
facility_type: qParams.facility_type || undefined,
district: qParams.district || undefined,
offset: (qParams.page ? qParams.page - 1 : 0) * resultsPerPage,
created_date_before: qParams.created_date_before || undefined,
created_date_after: qParams.created_date_after || undefined,
modified_date_before: qParams.modified_date_before || undefined,
modified_date_after: qParams.modified_date_after || undefined,
ordering: qParams.ordering || undefined,
category: qParams.category || undefined,
gender: qParams.gender || undefined,
age_min: qParams.age_min || undefined,
age_max: qParams.age_max || undefined,
date_declared_positive_before:
qParams.date_declared_positive_before || undefined,
date_declared_positive_after:
qParams.date_declared_positive_after || undefined,
ration_card_category: qParams.ration_card_category || undefined,
last_consultation_medico_legal_case:
qParams.last_consultation_medico_legal_case || undefined,
last_consultation_encounter_date_before:
qParams.last_consultation_encounter_date_before || undefined,
last_consultation_encounter_date_after:
qParams.last_consultation_encounter_date_after || undefined,
last_consultation_discharge_date_before:
qParams.last_consultation_discharge_date_before || undefined,
last_consultation_discharge_date_after:
qParams.last_consultation_discharge_date_after || undefined,
last_consultation_admitted_bed_type_list:
qParams.last_consultation_admitted_bed_type_list || undefined,
last_consultation__consent_types:
qParams.last_consultation__consent_types || undefined,
last_consultation__new_discharge_reason:
qParams.last_consultation__new_discharge_reason || undefined,
last_consultation_current_bed__location:
qParams.last_consultation_current_bed__location || undefined,
number_of_doses: qParams.number_of_doses || undefined,
covin_id: qParams.covin_id || undefined,
is_kasp: qParams.is_kasp || undefined,
is_declared_positive: qParams.is_declared_positive || undefined,
last_vaccinated_date_before:
qParams.last_vaccinated_date_before || undefined,
last_vaccinated_date_after: qParams.last_vaccinated_date_after || undefined,
last_consultation_is_telemedicine:
qParams.last_consultation_is_telemedicine || undefined,
is_antenatal: qParams.is_antenatal || undefined,
last_menstruation_start_date_after:
(qParams.is_antenatal === "true" &&
dayjs().subtract(9, "month").format("YYYY-MM-DD")) ||
undefined,
ventilator_interface: qParams.ventilator_interface || undefined,
diagnoses: qParams.diagnoses || undefined,
diagnoses_confirmed: qParams.diagnoses_confirmed || undefined,
diagnoses_provisional: qParams.diagnoses_provisional || undefined,
diagnoses_unconfirmed: qParams.diagnoses_unconfirmed || undefined,
diagnoses_differential: qParams.diagnoses_differential || undefined,
review_missed: qParams.review_missed || undefined,
};
Copy link
Member

Choose a reason for hiding this comment

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

are you sure these filters are present in the discharged patient list?

Comment on lines +198 to +242
const preventDuplicatePatientsDuetoPolicyId = (data: any) => {
// Generate a array which contains imforamation of duplicate patient IDs and there respective linenumbers
const lines = data.split("\n"); // Split the data into individual lines
const idsMap = new Map(); // To store indices of lines with the same patient ID

lines.map((line: any, i: number) => {
const patientId = line.split(",")[0]; // Extract the patient ID from each line
if (idsMap.has(patientId)) {
idsMap.get(patientId).push(i); // Add the index to the existing array
} else {
idsMap.set(patientId, [i]); // Create a new array with the current index
}
});

const linesWithSameId = Array.from(idsMap.entries())
.filter(([_, indices]) => indices.length > 1)
.map(([patientId, indices]) => ({
patientId,
indexSame: indices,
}));

// after getting the array of duplicate patient IDs and there respective linenumbers we will merge the policy IDs of the duplicate patients

linesWithSameId.map((lineInfo) => {
const indexes = lineInfo.indexSame;
//get policyid of all the duplicate patients and merge them by seperating them with a semicolon
const mergedPolicyId = indexes
.map((currentIndex: number) => lines[currentIndex].split(",")[5])
.join(";");
// replace the policy ID of the first patient with the merged policy ID
const arrayOfCurrentLine = lines[indexes[0]].split(",");
arrayOfCurrentLine[5] = mergedPolicyId;
const lineAfterMerge = arrayOfCurrentLine.join(",");
lines[indexes[0]] = `${lineAfterMerge}`;
});

// after merging the policy IDs of the duplicate patients we will remove the duplicate patients from the data
const uniqueLines = [];
const ids = new Set(); // To keep track of unique patient IDs

for (const line of lines) {
const patientId = line.split(",")[0]; // Extract the patient ID from each line
if (!ids.has(patientId)) {
uniqueLines.push(line);
ids.add(patientId);
Copy link
Member

Choose a reason for hiding this comment

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

this is duplicate code, same as present in normal patients list page. do create a utility function out of it and reuse it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add CSV Export support for Facility Specific Discharge Page
2 participants