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

removed lodash imports and dependencies and wrote js equivalents #9116

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

Conversation

SwanandBhuskute
Copy link
Contributor

@SwanandBhuskute SwanandBhuskute commented Nov 14, 2024

Proposed Changes

  • Fixes remove lodash #6006
  • remove lodash import and dependencies
  • wrote js equivalent code snippets

i was unable to check this code on the frontend , coz i am not getting on which route the output displays
kindly help

image
this was generated after build

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

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

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a custom useDebounce hook for improved debouncing in various components.
    • Added new utility functions: startCase and camelCase for string manipulation.
  • Enhancements

    • Improved error handling and state management in multiple components, including PatientRegister and ShowInvestigation.
    • Streamlined data fetching and processing logic by replacing lodash dependencies with native JavaScript methods.
    • Enhanced clarity and security in state management, particularly in handling nested properties.
    • Updated the ExcelFileDragAndDrop component for better error reporting during file selection.
  • Bug Fixes

    • Enhanced handling of undefined values in rendering logic to prevent errors.

These updates enhance performance, maintainability, and user experience across the application.

@SwanandBhuskute SwanandBhuskute requested a review from a team as a code owner November 14, 2024 11:54
Copy link
Contributor

coderabbitai bot commented Nov 14, 2024

Walkthrough

The pull request involves significant modifications to various components and utilities within the codebase, primarily aimed at removing dependencies on the lodash-es library. This includes replacing lodash functions with native JavaScript methods or custom implementations in several files, such as Notifications.js, ExcelFileDragAndDrop.tsx, and others. Additionally, the package.json file has been updated to remove lodash-es and its type definitions. New utility functions and a custom hook for debouncing have been introduced in utils.ts.

Changes

File Path Change Summary
package.json Removed dependency "lodash-es": "^4.17.21" and devDependency "@types/lodash-es": "^4.17.12".
src/Utils/Notifications.js Updated import statement for camelCase and startCase from lodash-es to local module ./utils.
src/components/Common/ExcelFIleDragAndDrop.tsx Removed import of forIn from lodash-es and replaced with native JavaScript methods. Enhanced error handling.
src/components/Facility/Investigations/Reports/index.tsx Refactored investigationList construction to use native JavaScript methods instead of lodash chaining.
src/components/Facility/Investigations/Reports/utils.tsx Introduced custom memoize function and replaced lodash methods with native implementations for data transformation.
src/components/Facility/Investigations/ShowInvestigation.tsx Replaced lodash's set function with a manual method for updating nested properties.
src/components/Facility/Investigations/Table.tsx Updated handleValueChange to manually construct nested object structure without lodash.
src/components/Form/AutoCompleteAsync.tsx Replaced lodash's debounce with a custom debounce implementation using setTimeout.
src/components/Form/Form.tsx Modified error handling logic to filter errors without using omitBy from lodash.
src/components/Patient/DiagnosesFilter.tsx Introduced custom hook useDebounce to replace lodash's debounce function.
src/components/Patient/PatientRegister.tsx Updated import statements and modified name processing logic, replacing lodash functions with local utilities.
src/components/Patient/SampleDetails.tsx Changed imports from lodash-es to local utilities and simplified rendering logic for undefined values.
src/components/Patient/SampleTestCard.tsx Updated imports and modified handling of potential undefined values for itemData.
src/Utils/utils.ts Added new utility functions startCase, camelCase, and a custom hook useDebounce.

Possibly related PRs

Suggested labels

needs review, tested

Suggested reviewers

  • rithviknishad
  • khavinshankar
  • Jacobjeevan

Poem

🐇 In the code where rabbits play,
We’ve hopped away from lodash today.
With native tools, we’ve made our stand,
Simplifying code, oh, isn’t it grand?
No more bunnies lost in chains,
Just clear paths where logic reigns! 🐇

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/Patient/DiagnosesFilter.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)

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between de43d86 and 1a136f4.

📒 Files selected for processing (2)
  • src/components/Patient/DiagnosesFilter.tsx (4 hunks)
  • src/components/Patient/PatientRegister.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Patient/DiagnosesFilter.tsx
🔇 Additional comments (3)
src/components/Patient/PatientRegister.tsx (3)

77-77: LGTM! Import changes align with PR objectives.

The changes successfully replace lodash imports with local utility functions.

Also applies to: 85-85


630-630: LGTM! Name formatting maintains functionality.

The change correctly uses the local startCase utility while maintaining the same name formatting logic.


Line range hint 750-775: Critical: Address debounce implementation issues.

The current implementation has several issues:

  1. Setting delay to 0ms effectively removes debouncing, which could lead to excessive API calls during phone number input.
  2. The useDebounce hook implementation needs improvements as noted in previous reviews:
    • Should be moved outside the component to prevent recreation on each render
    • Should properly handle callback reference updates

Recommend setting a reasonable delay (e.g., 300ms) and implementing the hook improvements:

-  const duplicateCheck = useDebounce(async (phoneNo: string) => {
+  const duplicateCheck = useDebounce(async (phoneNo: string) => {
     if (
       phoneNo &&
       PhoneNumberValidator()(parsePhoneNumber(phoneNo) ?? "") === undefined
     ) {
       const query = {
         phone_number: parsePhoneNumber(phoneNo),
       };
       const { res, data } = await request(routes.searchPatient, {
         query,
       });
       if (res?.ok && data?.results) {
         const duplicateList = !id
           ? data.results
           : data.results.filter(
               (item: DupPatientModel) => item.patient_id !== id,
             );
         if (duplicateList.length) {
           setStatusDialog({
             show: true,
             patientList: duplicateList,
           });
         }
       }
     }
-  }, 0);
+  }, 300);

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

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 1a136f4
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/673738a97ca35800080f8e31
😎 Deploy Preview https://deploy-preview-9116--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.

if (!current[key]) current[key] = {};
current = current[key];
}
current[keys[keys.length - 1]] = value;

Check warning

Code scanning / CodeQL

Prototype-polluting function Medium

The property chain
here
is recursively assigned to
current
without guarding against prototype pollution.
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: 7

🧹 Outside diff range and nitpick comments (19)
src/Utils/stringUtils.ts (2)

19-22: Add input validation to capitalize function

The implementation is simple and focused but needs input validation.

Consider this improved implementation:

-export const capitalize = (str: string) => {
+export const capitalize = (str: string): string => {
+  if (!str) return '';
+  if (str.length === 1) return str.toUpperCase();
+
   return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
 };

1-22: Consider enhancing module documentation and testing

While the utility functions provide a good foundation for replacing lodash, consider these improvements:

  1. Add JSDoc comments with examples for each function
  2. Create a comprehensive test suite covering edge cases
  3. Consider adding TypeScript strict type checks
  4. Add a module-level comment explaining the purpose of this utility file

Would you like me to help generate:

  1. JSDoc documentation with examples?
  2. A test suite for these utilities?
src/Utils/Notifications.js (1)

Line range hint 44-54: Add tests for error message formatting

The error message formatting logic uses the newly implemented string utility functions in a critical path. We should ensure the formatting behavior remains consistent after removing lodash.

Consider adding test cases for the following scenarios:

  1. Complex object keys that need camelCase transformation
  2. Various error message formats
  3. Edge cases like empty strings or special characters

Example test cases:

const testCases = [
  { 'user_name': ['Invalid'] },
  { 'COMPLEX_ERROR_KEY': ['Error 1', 'Error 2'] },
  { 'nested.key.path': ['Test error'] }
];

Would you like me to help create a comprehensive test suite for this functionality?

src/components/Patient/DiagnosesFilter.tsx (2)

37-53: Consider enhancing the useDebounce hook with cleanup and stronger typing.

The implementation is correct and follows React hooks best practices. However, consider these improvements:

-function useDebounce(callback: (...args: any[]) => void, delay: number) {
+function useDebounce<T extends (...args: any[]) => void>(
+  callback: T,
+  delay: number
+) {
   const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
 
   const debouncedCallback = useCallback(
-    (...args: any[]) => {
+    (...args: Parameters<T>) => {
       if (timeoutRef.current) {
         clearTimeout(timeoutRef.current);
       }
       timeoutRef.current = setTimeout(() => {
         callback(...args);
       }, delay);
     },
     [callback, delay],
   );
 
+  useEffect(() => {
+    return () => {
+      if (timeoutRef.current) {
+        clearTimeout(timeoutRef.current);
+      }
+    };
+  }, []);
 
   return debouncedCallback;
 }

Changes suggested:

  1. Add cleanup in useEffect to prevent memory leaks
  2. Add generic type parameter for better type inference
  3. Use Parameters utility type to maintain type safety of arguments

89-91: LGTM! Consider adding type safety to the query parameter.

The implementation successfully replaces lodash's debounce with the custom hook while maintaining the same functionality.

-  const debouncedQuery = useDebounce((query: string) => {
+  const debouncedQuery = useDebounce((query: string): void => {
     refetch({ query: { query } });
   }, 300);

Also applies to: 113-113

src/components/Facility/Investigations/Reports/utils.tsx (2)

15-42: Enhance type safety in data transformation

The implementation effectively uses native JS methods, but type safety could be improved by avoiding any types.

Consider these type improvements:

-  data.map((value: any) => [
+  data.map((value: InvestigationResponse[number]) => [

-  (acc, value: any) => {
+  (acc: { [key: string]: InvestigationResponse }, value: InvestigationResponse[number]) => {

Line range hint 89-108: Improve maintainability of color index calculation

The color index calculation uses magic numbers and could benefit from better documentation and constants.

Consider these improvements:

+ const COLOR_INDICES = {
+   YELLOW: 1,
+   GREEN: 5,
+   RED: 7,
+   INVALID: -1,
+   BUCKET_COUNT: 3
+ } as const;
+
+ /**
+  * Calculates color index based on value's position relative to min/max bounds
+  * @returns 
+  * - 1-2: Low range (yellow)
+  * - 3-5: Normal range (green)
+  * - 6-8: High range (red)
+  * - -1: Invalid input
+  */
  export const getColorIndex = memoize(
    ({ max, min, value }: { min?: number; max?: number; value?: number }) => {
      if (!max && min && value) {
-       return value < min ? 1 : 5;
+       return value < min ? COLOR_INDICES.YELLOW : COLOR_INDICES.GREEN;
      }
      // ... apply similar changes to other conditions
src/components/Form/Form.tsx (1)

60-65: LGTM! Successfully replaced lodash with native JavaScript.

The implementation correctly replaces lodash-es's omitBy with native JavaScript methods while maintaining the same functionality. The type assertion ensures type safety.

Consider extracting the filtering logic into a utility function for better maintainability and reusability:

+const filterNonEmptyEntries = <T extends Record<string, any>>(obj: T) =>
+  Object.fromEntries(
+    Object.entries(obj).filter(
+      ([_key, value]) => value !== "" && value !== null && value !== undefined
+    )
+  ) as T;

 const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
   event.preventDefault();
   event.stopPropagation();

   if (validate) {
-    const errors = Object.fromEntries(
-      Object.entries(validate(state.form)).filter(
-        ([_key, value]) =>
-          value !== "" && value !== null && value !== undefined,
-      ),
-    ) as FormErrors<T>;
+    const errors = filterNonEmptyEntries(validate(state.form)) as FormErrors<T>;
src/components/Facility/Investigations/Table.tsx (1)

62-69: Add error handling for invalid paths

The function assumes the path is always valid but should handle edge cases gracefully.

Consider adding these safety checks:

 const handleValueChange = (value: any, name: string) => {
+  if (!name || typeof name !== 'string') {
+    console.error('Invalid path provided');
+    return;
+  }
   const form = { ...state };
   const keys = name.split(".");
+  if (keys.length === 0) {
+    console.error('Empty path provided');
+    return;
+  }
   let current = form;
   for (let i = 0; i < keys.length - 1; i++) {
     const key = keys[i];
     if (!current[key]) current[key] = {};
     current = current[key];
   }
   current[keys[keys.length - 1]] = value;
   dispatch({ type: "set_form", form });
 };
🧰 Tools
🪛 GitHub Check: CodeQL

[warning] 69-69: Prototype-polluting function
The property chain here is recursively assigned to current without guarding against prototype pollution.

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

159-171: LGTM! Consider minor optimization for readability

The native JavaScript implementation successfully replaces lodash functionality. The code is clear and maintainable.

Optional: Consider this slightly more concise version using object property shorthand:

 const changedValues = Object.keys(state.initialValues).reduce(
   (acc: any, key: any) => {
     const val = state.initialValues[key];
+    const value = val?.value || null;
+    const notes = val?.notes || null;
     acc[key] = {
-      id: val?.id,
-      initialValue: val?.notes || val?.value || null,
-      value: val?.value || null,
-      notes: val?.notes || null,
+      id: val?.id,
+      initialValue: notes || value || null,
+      value,
+      notes,
     };
     return acc;
   },
   {},
 );
src/components/Form/AutoCompleteAsync.tsx (3)

Line range hint 71-92: Implementation of custom debouncing looks good, but consider memory leak prevention

The replacement of lodash's debounce with native setTimeout is well implemented. However, we should ensure cleanup when the component unmounts.

Consider adding a cleanup function in useEffect to prevent potential memory leaks:

  useEffect(() => {
    fetchDataAsync(query);
+   return () => {
+     clearTimeout(timeoutId);
+   };
  }, [query, fetchDataAsync]);

Line range hint 78-90: Consider error handling for failed API calls

The async operation inside setTimeout should include error handling to ensure the loading state is properly reset even when the API call fails.

Add try-catch block:

      timeoutId = setTimeout(async () => {
+       try {
          const data = ((await fetchData(query)) || [])?.filter((d: any) =>
            filter ? filter(d) : true,
          );

          if (showNOptions !== undefined) {
            setData(data.slice(0, showNOptions));
          } else {
            setData(data);
          }
+       } catch (error) {
+         console.error('Failed to fetch autocomplete data:', error);
+         setData([]);
+       } finally {
          setLoading(false);
+       }
      }, debounceTime);

Line range hint 14-39: Consider strengthening TypeScript types

The Props interface uses any types in several places which reduces type safety. Consider creating more specific types for the data structure.

Example improvement:

interface Option {
  id: string | number;
  label: string;
  [key: string]: any; // for additional properties
}

interface Props<T extends Option = Option> {
  // ... other props
  selected: T | T[];
  fetchData: (search: string) => Promise<T[]> | undefined;
  onChange: (selected: T | T[] | null) => void;
  optionLabel?: (option: T) => string;
  // ... rest of the props
}
src/components/Patient/SampleTestCard.tsx (1)

104-104: Consider using meaningful default values

While adding null checks is good, using empty strings as fallbacks might not be the most user-friendly approach. Consider using more descriptive defaults that indicate the absence of data.

-              {startCase(camelCase(itemData.status || ""))}
+              {startCase(camelCase(itemData.status || "Not Set"))}

-              {startCase(camelCase(itemData.result || ""))}
+              {startCase(camelCase(itemData.result || "Pending"))}

Also applies to: 136-136

src/components/Common/ExcelFIleDragAndDrop.tsx (2)

70-72: Consider enhancing date handling robustness

The current date conversion logic could benefit from some improvements:

  1. Add validation for invalid dates
  2. Consider timezone handling
  3. Avoid direct mutation of the row object
  4. Extract to a separate utility function

Consider refactoring to something like this:

+ const convertExcelDate = (date: Date): string => {
+   if (!(date instanceof Date) || isNaN(date.getTime())) {
+     return '';
+   }
+   return date.toISOString().split('T')[0];
+ };

  data.forEach((row: any) => {
-   Object.keys(row).forEach((key) => {
-     if (row[key] instanceof Date) {
-       row[key] = row[key].toISOString().split("T")[0];
-     }
-   });
+   const convertedRow = { ...row };
+   Object.keys(convertedRow).forEach((key) => {
+     if (convertedRow[key] instanceof Date) {
+       convertedRow[key] = convertExcelDate(convertedRow[key]);
+     }
+   });
+   return convertedRow;
  });

70-72: Enhance type safety by removing any types

The current implementation uses any types which reduces type safety. Consider defining proper interfaces for the Excel data structure.

Consider adding these types:

interface ExcelRow {
  [key: string]: string | Date | number;
}

interface ExcelData extends Array<ExcelRow> {}

Then update the code:

- data.forEach((row: any) => {
+ data.forEach((row: ExcelRow) => {
src/components/Facility/Investigations/Reports/index.tsx (1)

181-190: Well-implemented lodash removal with native JavaScript methods!

The refactoring effectively replaces lodash methods with native JavaScript equivalents. The implementation is clean and maintains the original functionality while reducing external dependencies.

A few suggestions to make the code even more maintainable:

-    const investigationList = Array.from(
-      data
-        .flatMap((i) => i?.data?.results || [])
-        .map((i) => ({
-          ...i,
-          name: `${i.name} ${i.groups[0].name ? " | " + i.groups[0].name : ""}`,
-        }))
-        .reduce((map, item) => map.set(item.external_id, item), new Map())
-        .values(),
-    );
+    // Extract results and handle potential null/undefined data
+    const flattenedResults = data.flatMap((i) => i?.data?.results || []);
+    
+    // Create a Map for unique entries by external_id
+    const uniqueInvestigations = new Map(
+      flattenedResults.map((i) => [
+        i.external_id,
+        {
+          ...i,
+          name: `${i.name}${i.groups[0]?.name ? ` | ${i.groups[0].name}` : ''}`,
+        },
+      ])
+    );
+    
+    const investigationList = Array.from(uniqueInvestigations.values());

Changes suggested:

  1. Split the chain into meaningful steps for better readability
  2. Use optional chaining for groups[0]?.name to prevent potential null reference
  3. Use template literals more consistently
  4. Add comments to explain the data transformation steps
src/components/Patient/SampleDetails.tsx (1)

Line range hint 385-385: Add null checks for consistency with other string transformations.

Similar to the changes in renderFlow, consider adding null checks to other instances of string transformations to maintain consistency and prevent potential runtime errors:

- {startCase(camelCase(sampleDetails.doctor_name))}
+ {startCase(camelCase(sampleDetails.doctor_name || ""))}

- {startCase(camelCase(sampleDetails.sample_type))}
+ {startCase(camelCase(sampleDetails.sample_type || ""))}

Also applies to: 461-461

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

762-762: Memoize duplicateCheck to prevent unnecessary recreations.

To avoid recreating the debounced function on every render, wrap duplicateCheck with useCallback. This ensures that duplicateCheck maintains referential equality between renders unless its dependencies change.

Apply this diff to memoize duplicateCheck:

- const duplicateCheck = useDebounce(async (phoneNo: string) => {
+ const duplicateCheck = useCallback(
+   useDebounce(async (phoneNo: string) => {
      // function body
    }, 300),
+   []
+ );
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

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

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (14)
  • package.json (0 hunks)
  • src/Utils/Notifications.js (1 hunks)
  • src/Utils/stringUtils.ts (1 hunks)
  • src/components/Common/ExcelFIleDragAndDrop.tsx (1 hunks)
  • src/components/Facility/Investigations/Reports/index.tsx (1 hunks)
  • src/components/Facility/Investigations/Reports/utils.tsx (1 hunks)
  • src/components/Facility/Investigations/ShowInvestigation.tsx (2 hunks)
  • src/components/Facility/Investigations/Table.tsx (1 hunks)
  • src/components/Form/AutoCompleteAsync.tsx (2 hunks)
  • src/components/Form/Form.tsx (1 hunks)
  • src/components/Patient/DiagnosesFilter.tsx (4 hunks)
  • src/components/Patient/PatientRegister.tsx (3 hunks)
  • src/components/Patient/SampleDetails.tsx (2 hunks)
  • src/components/Patient/SampleTestCard.tsx (3 hunks)
💤 Files with no reviewable changes (1)
  • package.json
🧰 Additional context used
🪛 GitHub Check: CodeQL
src/components/Facility/Investigations/ShowInvestigation.tsx

[warning] 101-101: Prototype-polluting function
The property chain here is recursively assigned to current without guarding against prototype pollution.

src/components/Facility/Investigations/Table.tsx

[warning] 69-69: Prototype-polluting function
The property chain here is recursively assigned to current without guarding against prototype pollution.

🔇 Additional comments (16)
src/Utils/stringUtils.ts (1)

1-9: ⚠️ Potential issue

Critical issues in camelCase implementation

The current implementation has several issues that need to be addressed:

  1. Missing input validation for null/undefined
  2. The final .toLowerCase() transform contradicts camelCase format by lowercasing all characters
  3. Implementation differs from lodash's behavior for handling special characters and multiple spaces

Consider this improved implementation:

-export const camelCase = (str: string) => {
+export const camelCase = (str: string): string => {
+  if (!str) return '';
+
   return str
-    .replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, (match, index) =>
-      index === 0 ? match.toLowerCase() : match.toUpperCase(),
-    )
-    .replace(/\s+/g, "")
-    .replace(/([A-Z])/g, (match) => match.toLowerCase());
+    .toLowerCase()
+    .replace(/[^a-zA-Z0-9]+(.)/g, (_, char) => char.toUpperCase());
 };

Let's verify the behavior matches lodash:

✅ Verification successful

Based on the gathered evidence, I can now provide a final response:

Simplify camelCase implementation while maintaining compatibility

The current implementation can be improved, but the suggested changes in the review need revision. The function is being used in combination with startCase for formatting display text from snake_case API responses (e.g., sample_typeSample Type). The final .toLowerCase() transform isn't actually an issue since it's always used with startCase.

A simpler implementation that handles the current usage patterns:

export const camelCase = (str: string): string => {
  if (!str) return '';
  return str
    .toLowerCase()
    .replace(/[^a-zA-Z0-9]+(.)/g, (_, char) => char.toUpperCase());
};

This maintains compatibility with existing usage while being more concise and handling edge cases better.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find test files that might contain lodash camelCase usage examples
rg -l "\.camelCase\(" | grep -i "test\|spec"

Length of output: 46


Script:

#!/bin/bash
# Let's search for any tests or usage of camelCase function
rg -l "camelCase"

# Also search for any lodash imports to understand the context of migration
rg "from 'lodash'" -A 1

Length of output: 264


Script:

#!/bin/bash
# Let's check the actual usage of camelCase in the files to understand the context
rg "camelCase" -B 2 -A 2 scripts/setup-care-apps.js src/components/Patient/SampleTestCard.tsx src/components/Patient/SampleDetails.tsx src/Utils/Notifications.js

# Also check if there are any lodash imports with different syntax
rg "lodash" -B 1 -A 1

Length of output: 48534


Script:

#!/bin/bash
# Let's check how camelCase is actually being used in the codebase
rg -B 2 -A 2 "camelCase\(" src/

# Also check if there are any existing tests for stringUtils
fd "stringUtils" -e test.ts -e spec.ts

Length of output: 2369

src/Utils/Notifications.js (1)

4-4: Verify stringUtils implementation completeness

The import change aligns with the PR objective of removing lodash dependencies. However, we should verify that the local implementation in stringUtils matches the lodash behavior exactly.

✅ Verification successful

Let me verify the behavior of these implementations against lodash's behavior by checking how they are used in the Notifications.js file.


Implementation is suitable for the use case

The local stringUtils implementation is appropriate for its usage in Notifications.js, where it's used to format error messages by:

  1. Converting keys to camelCase and then to startCase (e.g., "error_message" → "errorMessage" → "Error Message")
  2. The implementation matches the required behavior for this specific use case
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the stringUtils implementation exists and contains required functions

# Check if stringUtils file exists in the same directory
fd -e js -e ts "stringUtils" "src/Utils"

# Check implementation of required functions
rg -A 10 "export.*(camelCase|startCase)" "src/Utils"

Length of output: 1298


Script:

#!/bin/bash
# Check how these functions are used in Notifications.js
rg -A 5 "(camelCase|startCase)" "src/Utils/Notifications.js"

# Also check if there are any tests for these string utilities
fd -e test.js -e test.ts -e spec.js -e spec.ts "stringUtils" .

Length of output: 557

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

1-1: Verify complete removal of lodash dependencies.

Let's ensure there are no remaining lodash imports or dependencies in the codebase.

✅ Verification successful

Lodash dependency has been successfully removed

The verification shows no traces of lodash in the codebase:

  • No lodash imports found in TypeScript/JavaScript files
  • No lodash requires or usage patterns detected
  • No lodash dependencies in package.json
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining lodash imports and dependencies

# Check for lodash imports in TypeScript/JavaScript files
echo "Checking for lodash imports..."
rg -l "import.*lodash" -t ts -t tsx -t js

# Check package.json for lodash dependencies
echo "Checking package.json for lodash dependencies..."
if [ -f "package.json" ]; then
    jq '.dependencies + .devDependencies | with_entries(select(.key | contains("lodash")))' package.json
fi

Length of output: 381


Script:

#!/bin/bash
# Description: Check for any remaining lodash imports with correct file type flags
echo "Checking for lodash imports..."
rg -l "import.*lodash" --type-add 'tsx:*.tsx' --type-add 'ts:*.ts' --type-add 'js:*.js' -t tsx -t ts -t js

# Check if lodash is used without import statements (e.g., require)
echo "Checking for lodash requires..."
rg -l "require.*lodash" --type-add 'tsx:*.tsx' --type-add 'ts:*.ts' --type-add 'js:*.js' -t tsx -t ts -t js

# Check for any remaining lodash usage patterns
echo "Checking for lodash usage patterns..."
rg -l "lodash" --type-add 'tsx:*.tsx' --type-add 'ts:*.ts' --type-add 'js:*.js' -t tsx -t ts -t js

Length of output: 546

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

1-1: Successfully achieved lodash removal objective

The changes effectively replace lodash functions with native JavaScript implementations while maintaining functionality. The code is now more maintainable as it reduces external dependencies.

Regarding your question about testing the frontend changes: To help identify the specific route, I can analyze the codebase.

✅ Verification successful

Investigation Reports can be tested at /patient/:id/investigation_reports

The component is accessible through the patient routes at /patient/:id/investigation_reports where :id should be replaced with a valid patient ID. The component receives the patient ID as a prop.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for routes that import or use the Investigation Reports component
rg -l "Investigations/Reports" | grep -i "route"

Length of output: 83


Script:

#!/bin/bash
# Check the route configuration in PatientRoutes.tsx
rg -A 10 "Investigations/Reports" src/Routers/routes/PatientRoutes.tsx

Length of output: 645


Script:

#!/bin/bash
# Check the route path configuration for InvestigationReports
rg -B 5 -A 5 "InvestigationReports" src/Routers/routes/PatientRoutes.tsx

Length of output: 959

src/components/Form/Form.tsx (1)

60-66: Verify test coverage for the new error filtering logic.

Since this is a critical form validation logic, we should ensure proper test coverage exists.

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

Line range hint 1-1: Verify complete removal of lodash dependencies

Let's ensure there are no remaining lodash imports or usages in this file or related components.

✅ Verification successful

Let me verify the lodash removal more thoroughly by checking the entire codebase and the specific file.


Let me try one more verification with a simpler pattern to ensure we catch any lodash usage:


Lodash dependency removal verified successfully

The verification shows that lodash has been completely removed from the Table.tsx component. The only remaining references to lodash are in package metadata files (package-lock.json) and software bill of materials files (bom.json, fe-sbom.json), which is expected and doesn't indicate actual usage in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any remaining lodash imports in this file and related components
echo "Checking for lodash imports..."
rg -l "lodash" "src/components/Facility/Investigations"

echo "Checking package.json for lodash dependencies..."
cat package.json | jq '.dependencies | keys[] | select(contains("lodash"))'

Length of output: 309


Script:

#!/bin/bash
# Check the specific file for any lodash usage
echo "Checking Table.tsx for lodash..."
rg "lodash" "src/components/Facility/Investigations/Table.tsx"

# Check if lodash is used in imports or as _ anywhere in the file
echo -e "\nChecking for potential lodash usage as _..."
rg "import.*{.*_.*}" "src/components/Facility/Investigations/Table.tsx"
rg "import.*_ from" "src/components/Facility/Investigations/Table.tsx"

# Check if package.json exists and has lodash
echo -e "\nChecking if package.json exists and contains lodash..."
if [ -f "package.json" ]; then
    echo "Content of dependencies in package.json:"
    cat package.json | jq '.dependencies'
fi

# Check the entire codebase for lodash imports
echo -e "\nChecking entire codebase for lodash imports..."
rg "from ['\"]lodash['\"]|from ['\"]lodash/|require\(['\"]lodash['\"]" -l

Length of output: 2423


Script:

#!/bin/bash
# Check for any lodash-related strings in the specific file
echo "Checking Table.tsx for any lodash references..."
rg -i "lodash" "src/components/Facility/Investigations/Table.tsx"

# Check for potential lodash usage patterns in the file
echo -e "\nChecking for potential lodash usage patterns..."
rg "import.*_" "src/components/Facility/Investigations/Table.tsx"
rg "from.*lodash" "src/components/Facility/Investigations/Table.tsx"

# Simple check for lodash in the entire codebase
echo -e "\nChecking codebase for lodash..."
rg -l "lodash"

Length of output: 579

🧰 Tools
🪛 GitHub Check: CodeQL

[warning] 69-69: Prototype-polluting function
The property chain here is recursively assigned to current without guarding against prototype pollution.

src/components/Form/AutoCompleteAsync.tsx (1)

74-77: Verify loading state behavior during rapid typing

The loading state is set immediately but only cleared after the debounced operation completes. This could lead to a flickering loading indicator during rapid typing.

Let's verify the loading behavior in similar components:

✅ Verification successful

Loading state implementation is correct and follows best practices

After examining the implementation, the loading state behavior in AutoCompleteAsync is properly implemented:

  1. The loading indicator is managed within a debounced operation where:
    • setLoading(true) is called immediately before the debounce timeout
    • setLoading(false) is called after the data fetch completes
    • The timeout is properly cleared on each new query using clearTimeout
  2. This pattern prevents unnecessary API calls during rapid typing while providing immediate visual feedback
  3. The loading state is appropriately displayed as a spinner icon in the UI, replacing the dropdown arrow
  4. The implementation is consistent with other components in the codebase (e.g., SearchInput) that use similar debounce patterns

The current implementation actually helps prevent flickering by debouncing the actual data fetching operation while providing immediate visual feedback to the user.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other async components with loading states
rg -l "setLoading.*true.*setTimeout" --type tsx

Length of output: 77


Script:

#!/bin/bash
# Search for loading state patterns in TypeScript/React files with broader file extensions
rg -l "setLoading\(true\)" --type ts --type tsx --type jsx

# Look for debounce patterns with loading states
rg "setLoading.*setTimeout|setTimeout.*setLoading" --type ts --type tsx --type jsx -A 5

# Search for similar autocomplete components
rg "AutoComplete.*async" --type ts --type tsx --type jsx -A 5

Length of output: 298


Script:

#!/bin/bash
# Search for loading state patterns in all files
rg -l "setLoading\(true\)"

# Look for debounce patterns with loading states
rg "setLoading.*setTimeout|setTimeout.*setLoading" -A 5

# Search for the current component implementation
rg "class.*AutoCompleteAsync|function.*AutoCompleteAsync" -A 10

# Find any debounce implementations
rg "clearTimeout.*timeoutId" -A 5

Length of output: 1655


Script:

#!/bin/bash
# Let's examine the complete implementation of AutoCompleteAsync to understand the loading state management
cat src/components/Form/AutoCompleteAsync.tsx

# Also check SearchInput implementation for comparison of debounce pattern
cat src/components/Form/SearchInput.tsx

Length of output: 10365

src/components/Patient/SampleTestCard.tsx (2)

Line range hint 1-213: Overall implementation looks good

The changes successfully remove the lodash dependency while maintaining the component's functionality. The implementation includes:

  • Proper TypeScript types and interfaces
  • Responsive UI design
  • Robust error handling
  • Clear status management

15-15: Verify the local stringUtils implementation

The import change aligns with the PR objective to remove lodash dependencies. However, we should verify the implementation of these utility functions.

✅ Verification successful

Local stringUtils implementation is adequate and correctly used

The implementation of camelCase and startCase in stringUtils.ts is appropriate for the use case:

  • Both functions are properly implemented with string manipulation
  • They are used correctly in SampleTestCard.tsx for formatting status and result fields
  • The usage includes null checks with the || operator, preventing potential issues with undefined values

While there are no dedicated test files found, the implementation is straightforward and follows standard string manipulation patterns.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of camelCase and startCase in stringUtils

# Check if the utility functions exist and their implementation
fd --type f stringUtils.ts --exec cat {} \; 

# Look for tests of these utilities
fd --type f "stringUtils.test" --exec cat {} \;

Length of output: 882


Script:

#!/bin/bash
# Let's verify if these utility functions are being used correctly in the component
rg -A 2 "camelCase|startCase" "src/components/Patient/SampleTestCard.tsx"

# Also check if there are any tests for stringUtils in other test file formats
fd --type f "stringUtils" --extension test.ts --extension test.tsx --extension spec.ts --extension spec.tsx --exec cat {} \;

Length of output: 508

src/components/Common/ExcelFIleDragAndDrop.tsx (1)

70-72: LGTM! Successful replacement of lodash dependency.

The replacement of lodash-es's forIn with native Object.keys().forEach is a good change that:

  1. Removes external dependency while maintaining the same functionality
  2. Uses modern JavaScript features that are well-supported
  3. Potentially improves bundle size by removing lodash

Let's verify there are no remaining lodash imports or usages in this file:

✅ Verification successful

Confirmed: No lodash dependencies remain in the file

After reviewing the complete file content, I can verify that:

  1. There are no lodash imports present
  2. No lodash methods (including _.forIn) are being used
  3. The native Object.keys().forEach implementation is correctly handling the date conversion
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining lodash imports or usage
rg "lodash|_\." "src/components/Common/ExcelFIleDragAndDrop.tsx"

Length of output: 64


Script:

#!/bin/bash
# Let's verify the file content to ensure no lodash dependencies remain
cat "src/components/Common/ExcelFIleDragAndDrop.tsx"

Length of output: 9536

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

181-190: Verify data structure assumptions

Please ensure that the data structure assumptions remain valid after removing lodash:

  1. data array contains valid response objects
  2. results property exists in the response
  3. Each investigation object has required properties (external_id, name, groups)
✅ Verification successful

Based on the shell script results, I can now verify the data structure assumptions. Let me analyze the code in src/components/Facility/Investigations/Reports/index.tsx and related files:

  1. The Investigation interface in src/components/Facility/Investigations/Reports/types.ts confirms that the required properties exist:

    • external_id is present in investigation_object
    • name is present in investigation_object
    • groups array is defined in InvestigationType
  2. The data transformation in the code:

    const investigationList = Array.from(
      data
        .flatMap((i) => i?.data?.results || [])
        .map((i) => ({
          ...i,
          name: `${i.name} ${i.groups[0].name ? " | " + i.groups[0].name : ""}`,
        }))
        .reduce((map, item) => map.set(item.external_id, item), new Map())
        .values(),
    );
    • Safely handles undefined data with i?.data?.results || []
    • Properly accesses groups[0].name with optional chaining
    • Uses Map to deduplicate by external_id

Data structure assumptions are valid

The code handles all edge cases appropriately and the type definitions confirm the required properties are present. The removal of lodash has not impacted the data structure integrity.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the structure of investigation data across the codebase

# Check for investigation type definitions
echo "Checking investigation type definitions..."
rg -t typescript "type.*Investigation.*=.*{" -A 10

# Check for investigation object usage
echo "Checking investigation object usage..."
rg -t typescript "investigation.*\.external_id|investigation.*\.name|investigation.*\.groups"

Length of output: 479


Script:

#!/bin/bash
# Search for type definitions related to investigations
echo "Searching for investigation type definitions..."
rg "type\s+Investigation" -A 10

# Search for interfaces related to investigations
echo "Searching for investigation interfaces..."
rg "interface\s+Investigation" -A 10

# Check usage of investigation properties
echo "Checking investigation property usage..."
rg "\.external_id|\.name|\.groups\[0\]"

# Look for investigation data transformations
echo "Checking data transformations..."
rg "flatMap.*results|\.reduce.*Map.*external_id"

Length of output: 73526

src/components/Patient/SampleDetails.tsx (3)

17-17: LGTM! Import change aligns with PR objectives.

Successfully migrated from lodash-es to local string utilities.


273-273: LGTM! Improved null-safety with defensive checks.

The addition of null checks (|| "") for both flow.status and flow.notes prevents potential runtime errors when these values are undefined or null.

Also applies to: 277-277


Line range hint 1-500: Verify complete removal of lodash dependencies.

Let's verify that all lodash imports have been properly replaced in this file and related components.

✅ Verification successful

Migration from lodash to local utilities is complete and correct

The verification confirms:

  • No lodash imports remain in SampleDetails.tsx
  • Local string utility functions (camelCase, startCase, capitalize) are properly implemented in src/Utils/stringUtils.ts
  • The usage pattern is consistent across Patient components, with multiple files using the same utility functions
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining lodash imports in the codebase
# and verify the consistency of string utility usage

# Check for any remaining lodash imports in this file
echo "Checking for remaining lodash imports in SampleDetails.tsx..."
rg "from ['\"]lodash" "src/components/Patient/SampleDetails.tsx"

# Check for similar string utility usage patterns in related files
echo "Checking for similar string utility usage patterns..."
rg "startCase\(camelCase\(" "src/components/Patient/"

# Verify the implementation of local string utilities
echo "Verifying local string utility implementations..."
cat "src/Utils/stringUtils.ts"

Length of output: 1802

src/components/Patient/PatientRegister.tsx (2)

77-77: Import statement of startCase is correct.

The startCase function is correctly imported from @/Utils/stringUtils, replacing the lodash-es dependency.


629-629: Proper usage of startCase on patient name.

The code correctly formats the patient's name by converting it to lowercase and then applying startCase to capitalize it appropriately.

src/Utils/stringUtils.ts Outdated Show resolved Hide resolved
src/components/Facility/Investigations/Reports/utils.tsx Outdated Show resolved Hide resolved
src/components/Facility/Investigations/Reports/utils.tsx Outdated Show resolved Hide resolved
src/components/Facility/Investigations/Table.tsx Outdated Show resolved Hide resolved
src/components/Patient/PatientRegister.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: 3

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

Line range hint 25-96: Improve type safety and code organization in data transformation.

While the implementation is efficient, there's heavy usage of any types which reduces type safety. Consider breaking down the complex transformation into smaller, well-typed functions.

Here's a suggested approach:

interface SessionObject {
  session_external_id: string;
  session_created_date: string;
  facility_name?: string;
  facility_id?: string;
  [key: string]: any;
}

interface InvestigationValue {
  session_object: SessionObject;
  consultation_object?: {
    facility_name?: string;
    facility?: string;
  };
  investigation_object: {
    external_id: string;
    min_value?: number;
    max_value?: number;
  };
  value?: number;
  notes?: string;
}

const createSessionMap = (data: InvestigationValue[]) => {
  return Array.from(
    new Map(
      data.map((value) => [
        value.session_object.session_external_id,
        {
          ...value.session_object,
          facility_name: value.consultation_object?.facility_name,
          facility_id: value.consultation_object?.facility,
        },
      ]),
    ).values(),
  ).sort(
    (a, b) =>
      new Date(b.session_created_date).getTime() -
      new Date(a.session_created_date).getTime(),
  );
};
src/components/Facility/Investigations/Table.tsx (1)

62-80: Consider type safety and documentation improvements

While the implementation successfully replaces lodash.set, consider these enhancements:

  1. Replace value: any with a more specific type
  2. Add JSDoc documentation describing the function's purpose and parameters
  3. Consider extracting this to a reusable utility function since other components might need similar lodash.set replacements
+/**
+ * Updates a nested object property using dot notation
+ * @param value - The value to set
+ * @param name - The property path in dot notation (e.g., "a.b.c")
+ */
-const handleValueChange = (value: any, name: string) => {
+const handleValueChange = (value: string | number, name: string) => {
🧰 Tools
🪛 GitHub Check: CodeQL

[warning] 80-80: Prototype-polluting function
The property chain here is recursively assigned to current without guarding against prototype pollution.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7f75a18 and cc88800.

📒 Files selected for processing (5)
  • src/Utils/stringUtils.ts (1 hunks)
  • src/components/Facility/Investigations/Reports/utils.tsx (2 hunks)
  • src/components/Facility/Investigations/ShowInvestigation.tsx (2 hunks)
  • src/components/Facility/Investigations/Table.tsx (1 hunks)
  • src/components/Patient/PatientRegister.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Facility/Investigations/ShowInvestigation.tsx
🧰 Additional context used
🪛 GitHub Check: CodeQL
src/components/Facility/Investigations/Table.tsx

[warning] 80-80: Prototype-polluting function
The property chain here is recursively assigned to current without guarding against prototype pollution.

🔇 Additional comments (8)
src/Utils/stringUtils.ts (2)

11-22: LGTM! Well-implemented startCase function

The implementation is robust and handles all edge cases correctly:

  • Empty string validation
  • Multiple space normalization
  • Proper word capitalization
  • Empty word filtering

Note: This implementation already addresses the concerns raised in the previous review comment.


1-27: Verify lodash replacement completeness

Let's ensure all lodash string utility imports are properly replaced with these new implementations.

✅ Verification successful

Let me verify the usage of these functions in the actual files to ensure we haven't missed any replacements.


Lodash string utilities successfully replaced

The verification shows that:

  • All identified files have been updated to use the new string utility functions from @/Utils/stringUtils
  • No remaining lodash imports for these string utilities exist
  • The functions are being actively used in the components with the same patterns as before
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining lodash string utility imports and compare behavior

# Check for any remaining lodash string utility imports
echo "Checking for remaining lodash string utility imports..."
rg -l "import.*\{.*(camelCase|startCase|capitalize).*\}.*from.*lodash"

# Find all files that previously used these lodash functions
echo "Files previously using these lodash functions..."
git log -p | rg -B 2 "import.*\{.*(camelCase|startCase|capitalize).*\}.*from.*lodash"

Length of output: 1436


Script:

#!/bin/bash
# Check current usage in the identified files
echo "Checking SampleDetails.tsx..."
rg -A 2 "(camelCase|startCase|capitalize)" "src/components/Patient/SampleDetails.tsx" || echo "File not found"

echo -e "\nChecking SampleTestCard.tsx..."
rg -A 2 "(camelCase|startCase|capitalize)" "src/components/Patient/SampleTestCard.tsx" || echo "File not found"

# Also check for any current imports of these functions from lodash
echo -e "\nChecking current lodash imports in these files..."
rg "import.*lodash" "src/components/Patient/SampleDetails.tsx" "src/components/Patient/SampleTestCard.tsx" || echo "No lodash imports found"

# Check if these files are using our new utility functions
echo -e "\nChecking for imports from stringUtils..."
rg "import.*stringUtils" "src/components/Patient/SampleDetails.tsx" "src/components/Patient/SampleTestCard.tsx" || echo "No stringUtils imports found"

Length of output: 2738

src/components/Facility/Investigations/Reports/utils.tsx (2)

55-62: LGTM! Efficient session lookup implementation.

The implementation follows the previous review suggestion of using a Map for O(1) lookup performance.


Line range hint 98-99: LGTM! Appropriate use of memoization.

The getColorIndex function is now properly memoized while maintaining its original logic.

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

64-72: Security validation looks good!

The implementation correctly prevents prototype pollution by validating object keys. This addresses the security concern raised in the previous review.

src/components/Patient/PatientRegister.tsx (3)

77-77: LGTM: Import change aligns with PR objectives.

The change to import startCase from local utilities instead of lodash aligns with the PR's goal of removing lodash dependencies.


188-204: LGTM: useDebounce implementation follows best practices.

The implementation correctly incorporates the suggested improvements from previous reviews.


647-647: LGTM: Improved name case handling.

Converting the name to lowercase before applying startCase ensures consistent capitalization regardless of input format.

src/Utils/stringUtils.ts Outdated Show resolved Hide resolved
src/Utils/stringUtils.ts Outdated Show resolved Hide resolved
src/components/Facility/Investigations/Reports/utils.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: 0

🧹 Outside diff range and nitpick comments (3)
src/Utils/stringUtils.ts (3)

1-1: Enhance function documentation with examples

Consider adding examples to make the function's behavior more clear:

-// Converts a string to camelCase format, first word - lowercase and each subsequent word - uppercase letter, with no spaces.
+// Converts a string to camelCase format (e.g., "hello world" → "helloWorld", "foo-bar" → "fooBar", "FOO_BAR" → "fooBar")

19-19: Optimize word capitalization logic

The current word capitalization can be optimized by avoiding array access and using charAt:

-    .map((word) => (word ? word[0].toUpperCase() + word.slice(1) : ""))
+    .map((word) => (word ? word.charAt(0).toUpperCase() + word.slice(1) : ""))

23-28: LGTM! Consider adding an example to the documentation

The implementation is robust and efficient. As a minor enhancement, consider adding an example to the documentation:

-// Capitalize the first letter of a string
+// Capitalize the first letter of a string (e.g., "hello" → "Hello")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between cc88800 and f13a324.

📒 Files selected for processing (2)
  • src/Utils/stringUtils.ts (1 hunks)
  • src/components/Facility/Investigations/Reports/utils.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Facility/Investigations/Reports/utils.tsx
🔇 Additional comments (1)
src/Utils/stringUtils.ts (1)

1-28: Verify compatibility with lodash implementations

Let's verify that these utilities handle all edge cases similarly to the lodash implementations they're replacing:

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.

quick review only since noticed couple of things being repeated.

  1. move things to Utils/utils.ts
  2. Avoid using js to transform text. Use tailwind text transform instead.

src/components/Patient/SampleDetails.tsx Outdated Show resolved Hide resolved
src/components/Patient/SampleDetails.tsx Outdated Show resolved Hide resolved
src/components/Patient/PatientRegister.tsx Outdated Show resolved Hide resolved
src/components/Patient/DiagnosesFilter.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: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f13a324 and 17931f8.

📒 Files selected for processing (6)
  • src/Utils/Notifications.js (1 hunks)
  • src/Utils/utils.ts (2 hunks)
  • src/components/Patient/DiagnosesFilter.tsx (4 hunks)
  • src/components/Patient/PatientRegister.tsx (3 hunks)
  • src/components/Patient/SampleDetails.tsx (4 hunks)
  • src/components/Patient/SampleTestCard.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/Utils/Notifications.js
  • src/components/Patient/DiagnosesFilter.tsx
  • src/components/Patient/SampleDetails.tsx
  • src/components/Patient/SampleTestCard.tsx
🔇 Additional comments (3)
src/components/Patient/PatientRegister.tsx (3)

77-77: LGTM! Import changes align with PR objectives.

The changes correctly import startCase and useDebounce from local utility files, successfully removing lodash dependencies.

Also applies to: 85-85


630-630: LGTM! Name formatting maintains consistent behavior.

The change correctly uses the local startCase utility while maintaining proper name formatting by converting to lowercase first.


Line range hint 750-773: LGTM! Debounce implementation follows best practices.

The code now correctly uses the imported useDebounce hook instead of defining it inside the component, which addresses the previous review comments about hook redefinition. The duplicate check functionality is properly maintained with appropriate debouncing.

src/Utils/utils.ts Show resolved Hide resolved
src/Utils/utils.ts Show resolved Hide resolved
src/Utils/utils.ts Show resolved Hide resolved
Comment on lines +572 to +591
export const useDebounce = (
callback: (...args: string[]) => void,
delay: number,
) => {
const callbackRef = useRef(callback);
useEffect(() => {
callbackRef.current = callback;
}, [callback]);

const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const debouncedCallback = (...args: string[]) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
callbackRef.current(...args);
}, delay);
};
return debouncedCallback;
};
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 a hook so move it to src/hooks

Copy link
Member

Choose a reason for hiding this comment

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

remove this file

@@ -1,6 +1,7 @@
import { Stack, alert, defaultModules } from "@pnotify/core";
import * as PNotifyMobile from "@pnotify/mobile";
import { camelCase, startCase } from "lodash-es";

import { camelCase, startCase } from "./utils";
Copy link
Member

@sainak sainak Nov 15, 2024

Choose a reason for hiding this comment

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

use absolute imports

Comment on lines +95 to +118
let current = changedFields;
for (let i = 0; i < keys.length - 1; i++) {
const key = keys[i];

// Protect against prototype pollution by skipping unsafe keys - crai
if (key === "__proto__" || key === "constructor" || key === "prototype") {
continue;
}

// Use Object.create(null) to prevent accidental inheritance from Object prototype - coderabbit
current[key] = current[key] || Object.create(null);
current = current[key];
}

const lastKey = keys[keys.length - 1];

// Final key assignment, ensuring no prototype pollution vulnerability - coderabbit
if (
lastKey !== "__proto__" &&
lastKey !== "constructor" &&
lastKey !== "prototype"
) {
current[lastKey] = value;
}
Copy link
Member

Choose a reason for hiding this comment

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

extract this function to utils and reuse for ./Table component as well

Copy link
Member

@sainak sainak Nov 15, 2024

Choose a reason for hiding this comment

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

the issue with using the css transform capitalize it is just changes the visual representation of the text, but if the user tries to copy it it will be copied in its orignal form, instead of this we should make a function to convert text directly to title case and use that

cc: @rithviknishad

Copy link

👋 Hi, @SwanandBhuskute,
Conflicts have been detected against the base branch. Please rebase your branch against the base branch.


This message is automatically generated by prince-chrismc/label-merge-conflicts-action so don't hesitate to report issues/improvements there.

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Nov 19, 2024
@rithviknishad
Copy link
Member

@SwanandBhuskute

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

Successfully merging this pull request may close these issues.

remove lodash
3 participants