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

partially revert c9343d5 to fix investigation issues #9026

Merged
merged 5 commits into from
Nov 6, 2024

Conversation

sainak
Copy link
Member

@sainak sainak commented Nov 6, 2024

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

Summary by CodeRabbit

  • Bug Fixes
    • Updated import statements for lodash functions to use a namespace import, ensuring consistent access across components.
  • Refactor
    • Adjusted usage of lodash's chain function to align with new import style, maintaining existing functionality and logic across components.

@sainak sainak requested a review from a team as a code owner November 6, 2024 13:28
Copy link
Contributor

coderabbitai bot commented Nov 6, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes involve modifying the import statements for the lodash library across several components. The updates transition from named imports of specific functions to a namespace import, allowing access to functions like chain through the _ namespace. This adjustment affects how the chain function is utilized in the InvestigationReports, transformData, and ShowInvestigation components, but does not alter the overall logic, state management, or functionality of these components.

Changes

File Path Change Summary
src/components/Facility/Investigations/Reports/... Changed import of chain to a namespace import _, affecting usage in InvestigationReports.
src/components/Facility/Investigations/Reports/... Modified import for chain to a wildcard import _ in transformData, with unchanged logic.
src/components/Facility/Investigations/... Updated import to use _ for lodash, modifying handleUpdateCancel to use _.chain.

Assessment against linked issues

Objective Addressed Explanation
Investigation Report is not being rendered properly (#9022) The changes do not address the rendering issue reported.

🐇 In the code, I hop and play,
With lodash functions, I find my way.
From chain to _, a simple switch,
The logic stays, without a hitch.
So let the reports come out just right,
With every change, we bring delight! 🌟


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 6, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 3a2a778
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/672b9a2f7537f8000812518d
😎 Deploy Preview https://deploy-preview-9026--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 Nov 6, 2024

Deploying care-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 3a2a778
Status: ✅  Deploy successful!
Preview URL: https://2d9657cd.care-fe.pages.dev
Branch Preview URL: https://sainak-fix-lodash-chain.care-fe.pages.dev

View logs

@sainak sainak added bug Something isn't working needs testing needs review P1 breaking issue or vital feature labels Nov 6, 2024
@github-actions github-actions bot added the Deploy-Failed Deplyment is not showing preview label Nov 6, 2024
Copy link

cypress bot commented Nov 6, 2024

CARE    Run #3828

Run Properties:  status check failed Failed #3828  •  git commit 15e3e9318c: partially revert c9343d5 to fix investigation issues
Project CARE
Branch Review sainak/fix-lodash-chain
Run status status check failed Failed #3828
Run duration 04m 54s
Commit git commit 15e3e9318c: partially revert c9343d5 to fix investigation issues
Committer Aakash Singh
View all properties for this run ↗︎

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

Tests for review

Failed  cypress/e2e/patient_spec/PatientHomepage.cy.ts • 1 failed test • UI-Chrome

View Output

Test Artifacts
Patient Homepage present functionalities > Patient Details based advance filters applied in the patient tab Test Replay Screenshots

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

🧹 Outside diff range and nitpick comments (5)
src/components/Facility/Investigations/Reports/utils.tsx (2)

Line range hint 7-17: Consider improving type safety and simplifying chain operations.

The first chain operation uses any type and could be improved:

  1. Define proper types instead of using any
  2. Consider using array methods directly for better tree shaking and readability
-  const sessions = _.chain(data)
-    .map((value: any) => {
+  const sessions = data.map((value: InvestigationResponse[number]) => {
       return {
         ...value.session_object,
         facility_name: value.consultation_object?.facility_name,
         facility_id: value.consultation_object?.facility,
       };
     })
-    .uniqBy("session_external_id")
-    .orderBy("session_created_date", "desc")
-    .value();
+    .filter((value, index, self) => 
+      self.findIndex(v => v.session_external_id === value.session_external_id) === index
+    )
+    .sort((a, b) => 
+      new Date(b.session_created_date).getTime() - new Date(a.session_created_date).getTime()
+    );

18-21: Simplify the grouping operation.

The second chain operation could be simplified:

-  const groupByInvestigation = _.chain(data)
-    .groupBy("investigation_object.external_id")
-    .values()
-    .value();
+  const groupByInvestigation = Object.values(
+    data.reduce((acc, item) => {
+      const key = item.investigation_object.external_id;
+      (acc[key] = acc[key] || []).push(item);
+      return acc;
+    }, {} as Record<string, InvestigationResponse[]>)
+  );
src/components/Facility/Investigations/ShowInvestigation.tsx (2)

Line range hint 154-161: Simplify the chain operation for better performance.

The current implementation uses lodash chain which can be replaced with a simpler and more performant solution using native JavaScript methods.

Consider this alternative implementation:

-    const changedValues = _.chain(state.initialValues)
-      .map((val: any, _key: string) => ({
-        id: val?.id,
-        initialValue: val?.notes || val?.value || null,
-        value: val?.value || null,
-        notes: val?.notes || null,
-      }))
-      .reduce((acc: any, cur: any) => ({ ...acc, [cur.id]: cur }), {})
-      .value();
+    const changedValues = Object.values(state.initialValues).reduce(
+      (acc, val) => ({
+        ...acc,
+        [val.id]: {
+          id: val?.id,
+          initialValue: val?.notes || val?.value || null,
+          value: val?.value || null,
+          notes: val?.notes || null,
+        },
+      }),
+      {}
+    );

This approach:

  • Eliminates lodash chain dependency
  • Reduces complexity with a single reduce operation
  • Maintains the same functionality

Line range hint 1-190: Improve type safety to prevent potential rendering issues.

Given that this PR aims to fix investigation report rendering issues, improving type safety would help prevent future problems.

Consider:

  1. Replace any types with proper interfaces:
interface Investigation {
  id: string;
  value: number | null;
  notes: string | null;
}

interface ChangedField {
  id: string;
  initialValue: string | number | null;
  value: number | null;
  notes: string | null;
}

interface State {
  changedFields: Record<string, ChangedField>;
  initialValues: Record<string, Investigation>;
}
  1. Type the reducer action:
type Action = 
  | { type: "set_changed_fields"; changedFields: State["changedFields"] }
  | { type: "set_initial_values"; initialValues: State["initialValues"] };
src/components/Facility/Investigations/Reports/index.tsx (1)

Line range hint 182-191: Consider simplifying the data transformation chain.

The current chain of operations can be simplified and made more performant:

  1. Flatten and process in a single pass
  2. Remove redundant operations
  3. Use TypeScript types for better type safety

Here's a suggested improvement:

type InvestigationResult = {
  name: string;
  groups: Array<{ name: string }>;
  external_id: string;
  [key: string]: any;
};

const investigationList = data
  .flatMap((response) => response?.data?.results || [])
  .filter((item): item is InvestigationResult => !!item)
  .map((item) => ({
    ...item,
    name: `${item.name}${item.groups[0]?.name ? ` | ${item.groups[0].name}` : ''}`,
  }))
  .filter((item, index, array) => 
    array.findIndex(t => t.external_id === item.external_id) === index
  );

This approach:

  • Provides better type safety
  • Removes unnecessary chaining
  • Simplifies the string template logic
  • Uses native array methods for better performance
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bbcfef0 and f21e487.

📒 Files selected for processing (3)
  • src/components/Facility/Investigations/Reports/index.tsx (2 hunks)
  • src/components/Facility/Investigations/Reports/utils.tsx (2 hunks)
  • src/components/Facility/Investigations/ShowInvestigation.tsx (2 hunks)
🔇 Additional comments (3)
src/components/Facility/Investigations/Reports/utils.tsx (1)

Line range hint 1-21: Consider eliminating lodash dependency for better tree shaking.

The current changes still rely on lodash, which may not fully resolve the tree shaking issues mentioned in the PR objectives. Consider using native JavaScript methods instead:

  1. Replace _.chain() with native array methods
  2. Replace findIndex with Array.prototype.findIndex
  3. Replace memoize with a custom implementation or a smaller package like memoizee

This would:

  • Eliminate the lodash dependency completely
  • Improve bundle size through better tree shaking
  • Leverage modern JavaScript features

Let's check the impact of lodash on the bundle:

src/components/Facility/Investigations/ShowInvestigation.tsx (1)

1-2: ⚠️ Potential issue

Reconsider the import strategy to enable tree shaking.

The current import approach defeats the PR's objective of improving tree shaking:

  1. import * as _ from "lodash-es" imports the entire lodash library
  2. Separate import of set shows inconsistent import strategy

Consider using specific imports for better tree shaking:

-import * as _ from "lodash-es";
-import { set } from "lodash-es";
+import { set, chain } from "lodash-es";

Likely invalid or redundant comment.

src/components/Facility/Investigations/Reports/index.tsx (1)

Line range hint 1-391: Verify error handling for API responses.

The component makes multiple API calls but could improve its error handling:

  1. Investigation group fetching
  2. Patient data fetching
  3. Investigation data fetching

Let's verify the error handling coverage:

Consider adding proper error handling:

const fetchInvestigation = useCallback(async () => {
  dispatch({
    type: "set_loading",
    payload: { ...isLoading, investigationLoading: true },
  });

  try {
    const data = await Promise.all(
      selectedGroup.map((group) =>
        request(routes.listInvestigations, {
          query: { group: group },
        }),
      ),
    );
    // ... process data ...
  } catch (error) {
    Notification.Error({
      msg: t("failed_to_fetch_investigations"),
    });
  } finally {
    dispatch({
      type: "set_loading",
      payload: { ...isLoading, investigationLoading: false },
    });
  }
}, [isLoading, selectedGroup, t]);

Comment on lines 1 to 2
import * as _ from "lodash-es";
import { findIndex, memoize } from "lodash-es";
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

Consider using named imports consistently for better tree shaking.

The current mix of namespace and named imports from lodash-es is inconsistent. Since the PR aims to fix tree shaking issues, consider using named imports exclusively:

-import * as _ from "lodash-es";
-import { findIndex, memoize } from "lodash-es";
+import { chain, findIndex, memoize } from "lodash-es";

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

@@ -1,4 +1,4 @@
import { chain } from "lodash-es";
import * as _ from "lodash-es";
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

Consider alternative approaches to lodash import.

While switching to namespace import fixes the immediate issue, there are better approaches to handle tree-shaking with lodash:

  1. Use individual imports from lodash-es:
import { flatMap, compact, flatten, unionBy } from 'lodash-es';
  1. Or use per-method packages:
import flatMap from 'lodash/flatMap';
import compact from 'lodash/compact';
import flatten from 'lodash/flatten';
import unionBy from 'lodash/unionBy';

Both approaches provide better tree-shaking support than namespace imports.

@rithviknishad rithviknishad removed the Deploy-Failed Deplyment is not showing preview label Nov 6, 2024
@sainak sainak removed bug Something isn't working P1 breaking issue or vital feature labels Nov 6, 2024
Copy link
Member

@rithviknishad rithviknishad left a comment

Choose a reason for hiding this comment

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

#6006 should solve it

@rithviknishad rithviknishad merged commit c27f595 into develop Nov 6, 2024
21 of 22 checks passed
@rithviknishad rithviknishad deleted the sainak/fix-lodash-chain branch November 6, 2024 16:36
Copy link

github-actions bot commented Nov 6, 2024

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

Investigation Report is not being rendered properly
4 participants