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

made a reusable component for table in routine and nursing care procedures #8608

Conversation

Sahil-Sinha-11
Copy link

@Sahil-Sinha-11 Sahil-Sinha-11 commented Sep 24, 2024

Changes made
fixes: #8562

  1. Added a reusable component.
  2. fixed width of the 2nd column onwards

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

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

Summary by CodeRabbit

  • New Features

    • Introduced a new NursingPlot component for enhanced display of nursing care data with pagination.
    • Added LogUpdateAnalayseTable for improved presentation of consultation data in a structured table format.
  • Bug Fixes

    • Enhanced handling of empty fields and messages for no data found in nursing care displays.
  • Refactor

    • Updated ConsultationNursingTab to integrate new components and streamline data presentation.

@Sahil-Sinha-11 Sahil-Sinha-11 requested a review from a team as a code owner September 24, 2024 09:35
Copy link

netlify bot commented Sep 24, 2024

Deploy Preview for care-ohc ready!

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

@nihal467
Copy link
Member

nihal467 commented Sep 24, 2024

image

  • add the translation to the options
  • the dates are shown as invalid under the nursing care section

image

  • as per issue, the first row should be frozen while scrolling, which is still not solved

@Sahil-Sinha-11 @rithviknishad

Comment on lines 13 to 19
const SharedSectionTable: React.FC<SharedSectionTableProps> = ({
data,
rows,
choices = {},
translateKey,
t,
}) => {
Copy link
Member

Choose a reason for hiding this comment

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

  1. Rename this to be LogUpdateAnalayseTable since it's built for it.
  2. use useTranslations instead of passing it as a prop.
  3. i18n suffix LOG_UPDATE_FIELD_LABEL__ is not going to change, so skip passing it as a prop.
Suggested change
const SharedSectionTable: React.FC<SharedSectionTableProps> = ({
data,
rows,
choices = {},
translateKey,
t,
}) => {
const LogUpdateAnalayseTable: React.FC<SharedSectionTableProps> = ({
data,
rows,
choices = {},
}) => {

Copy link
Member

Choose a reason for hiding this comment

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

Let's keep this in ConsultationNursingTab file itself. Keeping one section here and one section in a separate file isn't nice.

@Sahil-Sinha-11
Copy link
Author

Sahil-Sinha-11 commented Sep 27, 2024

Hey @rithviknishad I am not able to find where the dates input for nursing care is . I think the format in which it is entered is giving invalid date. How can I change it? should i change the date format in the logUpdateAnalyseTable itself if it is in other format? 02:18 AM; "15/05/2024" to " 2024-09-20 09:24:23.859000+00:00 "

@Sahil-Sinha-11
Copy link
Author

Sahil-Sinha-11 commented Sep 28, 2024

Hey @rithviknishad I fixed the date issue and fixed the 1st column in in mobile view.

@Sahil-Sinha-11
Copy link
Author

Screenshot 2024-10-06 at 11 56 20 AM Hey @rithviknishad This is how the page looks like , please tell me if I need to change anything.

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Oct 8, 2024
Copy link

github-actions bot commented Oct 8, 2024

👋 Hi, @Sahil-Sinha-11,
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.

@nihal467
Copy link
Member

nihal467 commented Oct 8, 2024

@Sahil-Sinha-11 fix the lint issue

@nihal467
Copy link
Member

nihal467 commented Oct 8, 2024

LGTM @khavinshankar @rithviknishad @Sahil-Sinha-11 fix the lint issue

@nihal467 nihal467 requested a review from rithviknishad October 8, 2024 18:41
@nihal467 nihal467 added tested and removed needs testing merge conflict pull requests with merge conflict labels Oct 8, 2024
@bodhish bodhish requested a review from rithviknishad October 21, 2024 04:41
Comment on lines 51 to 62
const dateConversion = (str: string) => {
const time = str.split(";")[0].trim();

const date = str.split(";")[1].trim();

const dd = date.split("/")[0];
const mm = date.split("/")[1];

const yyyy = date.split("/")[2];

return time + ";" + mm + "/" + dd + "/" + yyyy;
};
Copy link
Member

Choose a reason for hiding this comment

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

we can use formatDateTime instead of this right?

Copy link
Author

Choose a reason for hiding this comment

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

@rithviknishad actually formatDateTime uses days.js that expects date in format mm/dd/yyyy but the date format passed in nursingtab was different so I had to convert the format and then pass it to formatDateTime function

Copy link
Member

Choose a reason for hiding this comment

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

Whats the format of time received? I am pretty sure you can transform a format to other super easily.

Copy link
Member

Choose a reason for hiding this comment

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

From ChatGPT

In this case, you can utilize day.js to handle the date format transformation easily. Here's a suggestion for tackling the date formatting using day.js:

  1. You can parse the incoming date string using day.js, and then transform it to the format required by formatDateTime.

Here’s a sample implementation for transforming the date format:

import dayjs from 'dayjs';

const dateConversion = (str: string) => {
  const [time, date] = str.split(';').map(s => s.trim());

  // Assuming the incoming date is in "dd/mm/yyyy" format
  const parsedDate = dayjs(date, 'DD/MM/YYYY');
  
  // Format the date to the required "mm/dd/yyyy" format for formatDateTime
  const formattedDate = parsedDate.format('MM/DD/YYYY');

  return `${time}; ${formattedDate}`;
};

In this implementation:

  • The date is first split and trimmed.
  • The dayjs(date, 'DD/MM/YYYY') parses the input date, assuming the format DD/MM/YYYY.
  • The .format('MM/DD/YYYY') converts it into the required MM/DD/YYYY format for formatDateTime.

You can now pass the result to formatDateTime easily after this conversion.

Copy link
Member

Choose a reason for hiding this comment

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

backend is giving the data in standard format @Sahil-Sinha-11

image

However you are already formatting it when sending the data to the component after receiving it from the backend, and then deconstructing the formatted back to unformatted, just for format it again?

image

Copy link
Author

Choose a reason for hiding this comment

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

@rithviknishad I am not able to run the application it shows a file does not exist( pluginMap). I even tried on devlop branch.
Screenshot 2024-10-21 at 10 30 25 PM.

Copy link
Member

Choose a reason for hiding this comment

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

Copy link
Author

Choose a reason for hiding this comment

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

Hey @rithviknishad , I resolved it .

Copy link

👋 Hi, @Sahil-Sinha-11,
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 Oct 23, 2024
@github-actions github-actions bot added the stale label Nov 1, 2024
@bodhish
Copy link
Member

bodhish commented Nov 6, 2024

@nihal467 please check this PR and get it closed

@github-actions github-actions bot removed the stale label Nov 7, 2024
@nihal467
Copy link
Member

nihal467 commented Nov 8, 2024

LGTM @rithviknishad @khavinshankar can you take over the PR and clear the merge conflict

Copy link
Contributor

coderabbitai bot commented Nov 8, 2024

Walkthrough

The changes in this pull request involve significant enhancements to the ConsultationNursingTab.tsx file, introducing a new component for displaying nursing care data. The NursingPlot component fetches daily rounds data and manages pagination, while the LogUpdateAnalayseTable component replaces the previous table structure for displaying results. The modifications aim to improve the modularity and presentation of nursing consultation data, integrating new data models and ensuring cohesive information display.

Changes

File Path Change Summary
src/Components/Facility/ConsultationDetails/ConsultationNursingTab.tsx - Added NursingPlot component for fetching and displaying nursing data.
- Updated main export to include NursingPlot.
- Modified RoutineSection to use LogUpdateAnalayseTable.
src/Components/Facility/Consultations/LogUpdateAnalayseTable.tsx - Introduced LogUpdateAnalayseTable component for structured data display.
- Added SharedSectionTableProps interface for props definition.
src/Components/Facility/Consultations/NursingPlot.tsx - Removed NursingPlot component (previous version).

Assessment against linked issues

Objective Addressed Explanation
Make the Nursing Care section similar to the Routine Section by switching to a table layout (Make the component a reusable component to achieve it). (#8562)
Optional: feel free to improve the overall UI (borders or colors, etc.) (#8562) Unclear if UI improvements were made.

Possibly related PRs

  • Added dynamic lock icon and strong types #9006: This PR introduces the LogUpdateAnalayseTable component, which is directly utilized in the main PR's ConsultationNursingTab.tsx file, indicating a strong connection between the two changes.

Suggested labels

good to merge

Suggested reviewers

  • rithviknishad

Poem

In the nursing tab, oh what a sight,
With tables and plots, all done just right.
Data flows smoothly, like a gentle stream,
Enhancements abound, fulfilling the dream.
A hop and a skip, through code we shall glide,
Celebrating changes, with joy and with pride! 🐇✨


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
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 (7)
src/Components/Facility/Consultations/LogUpdateAnalayseTable.tsx (4)

6-10: Consider improving type safety of the interface.

The current interface could be more type-safe:

  1. Record<string, any> allows any value type which could lead to runtime errors
  2. The relationship between title and field in the rows array is not clearly typed

Consider this improved interface:

interface RowDefinition {
  title?: string;
  field?: string;
  subField?: boolean;
}

interface SharedSectionTableProps<T = Record<string, string | boolean | null>> {
  data: Record<string, T>;
  rows: Array<RowDefinition>;
  choices?: Record<string, Record<number | string, string>>;
}

24-26: Consider returning a consistent placeholder for null values.

Returning a space string for null values might cause layout inconsistencies. Consider using the same "-" placeholder as other empty states.

   if (value == null) {
-    return " ";
+    return "-";
   }

31-35: Improve type safety of choices lookup.

The type casting here is a bit unsafe and could be improved with better typing of the choices prop.

Consider using a more type-safe approach:

if (field && field in choices) {
  const choiceMap = choices[field];
  const choice = value in choiceMap ? choiceMap[value] : undefined;
  return choice ? t(`${field.toUpperCase()}__${choice}`) : "-";
}

46-46: Add descriptive content to empty header cell.

The empty header cell should have a descriptive label for better accessibility.

-<th className="sticky left-0 border-b-2 border-r-2 border-black bg-white"></th>
+<th className="sticky left-0 border-b-2 border-r-2 border-black bg-white" aria-label={t('field_names_column')}>
+  {t('field_names_column')}
+</th>
src/Components/Facility/ConsultationDetails/ConsultationNursingTab.tsx (3)

136-145: Simplify array transformation using flatMap

Consider replacing the map and reduce combination with flatMap for cleaner and more efficient code.

Apply this diff:

-const dataToDisplay = data
-  .map((x) =>
-    x.nursing
-      ? x.nursing.map((f: any) => {
-          f["date"] = x.date;
-          return f;
-        })
-      : [],
-  )
-  .reduce((accumulator, value) => accumulator.concat(value), []);
+const dataToDisplay = data.flatMap((x) =>
+  x.nursing
+    ? x.nursing.map((f: any) => {
+        f["date"] = x.date;
+        return f;
+      })
+    : [],
+);

138-141: Avoid mutating objects within map function

To prevent unintended side effects, avoid mutating objects inside map. Return a new object instead.

Apply this diff:

-              f["date"] = x.date;
-              return f;
+              return {
+                ...f,
+                date: x.date,
+              };

110-110: Simplify conditional statement using optional chaining

You can simplify the condition by utilizing optional chaining for cleaner code.

Apply this diff:

-if (res && res.ok && data) {
+if (res?.ok && data) {
🧰 Tools
🪛 Biome

[error] 110-110: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8d4640b and 8a886ea.

📒 Files selected for processing (3)
  • src/Components/Facility/ConsultationDetails/ConsultationNursingTab.tsx (4 hunks)
  • src/Components/Facility/Consultations/LogUpdateAnalayseTable.tsx (1 hunks)
  • src/Components/Facility/Consultations/NursingPlot.tsx (0 hunks)
💤 Files with no reviewable changes (1)
  • src/Components/Facility/Consultations/NursingPlot.tsx
🧰 Additional context used
🪛 Biome
src/Components/Facility/ConsultationDetails/ConsultationNursingTab.tsx

[error] 110-110: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (4)
src/Components/Facility/Consultations/LogUpdateAnalayseTable.tsx (2)

41-92: Implementation successfully meets PR objectives.

The component successfully implements all main requirements:

  1. Locked header row using sticky positioning
  2. Fixed width columns using Tailwind classes
  3. Reusable component structure with proper props interface

The table implementation is clean and maintainable.


76-86: 🛠️ Refactor suggestion

Add error handling for missing data.

The component assumes data will always be present for each field. Consider adding error handling for missing data.

-{Object.values(data).map((obj, idx) => {
+{Object.values(data).map((obj, idx) => {
+  if (!obj || typeof obj !== 'object') {
+    console.error(`Invalid data object at index ${idx}`);
+    return (
+      <td key={`${row.field}-${idx}`} className="w-80 border border-l-2 border-secondary-500 bg-secondary-100 p-2 text-center font-medium">
+        -
+      </td>
+    );
+  }
   const value = obj[row.field!];
   return (
     <td
src/Components/Facility/ConsultationDetails/ConsultationNursingTab.tsx (2)

169-175: Specify explicit types instead of using any

Using explicit types improves type safety and code readability. Replace any with the appropriate type.


17-17: Verify consistent spelling of LogUpdateAnalayseTable

Ensure that the spelling of LogUpdateAnalayseTable is consistent across the codebase to prevent import errors.

Run the following script to check for inconsistent usage:

✅ Verification successful

Spelling of LogUpdateAnalayseTable is consistent across the codebase

The component name LogUpdateAnalayseTable is spelled consistently in all occurrences across the codebase, including both import statements and component usage in ConsultationNursingTab.tsx and its definition in LogUpdateAnalayseTable.tsx.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for inconsistent spelling of LogUpdateAnalayseTable.

# Expected: All occurrences should use 'LogUpdateAnalayseTable'.

rg 'LogUpdateAnal(y|ay)seTable' -g '*.tsx'

Length of output: 670

Comment on lines 47 to 57
{Object.keys(data).map((date) => (
<>
<th
key={date}
className="w-40 border border-b-2 border-secondary-500 border-b-black p-1 text-sm font-semibold"
>
<p>{formatDate(date)}</p>
<p>{formatTime(date)}</p>
</th>
</>
))}
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

Add key prop to Fragment and improve accessibility.

  1. The Fragment in the date header mapping is missing a key prop
  2. The table could benefit from better accessibility
 {Object.keys(data).map((date) => (
-  <>
+  <React.Fragment key={date}>
     <th
-      key={date}
       className="w-40 border border-b-2 border-secondary-500 border-b-black p-1 text-sm font-semibold"
     >
       <p>{formatDate(date)}</p>
       <p>{formatTime(date)}</p>
     </th>
-  </>
+  </React.Fragment>
 ))}

Also, add an aria-label to the table:

-<table className="border-collapse rounded-lg border bg-secondary-100">
+<table 
+  className="border-collapse rounded-lg border bg-secondary-100"
+  aria-label={t('nursing_care_table_label')}
+>

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

Comment on lines 106 to 115
const { res, data } = await request(routes.dailyRoundsAnalyse, {
body: { page: currentPage, fields: NursingPlotFields },
pathParams: { consultationId },
});
if (res && res.ok && data) {
setResults(data.results);
setTotalCount(data.count);
}
};

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

Add error handling for failed API requests

Currently, there is no error handling if the API request fails. Consider adding error handling to improve user feedback.

Apply this diff:

           });
+          if (!res || !res.ok) {
+            // Handle error
+            console.error('Failed to fetch daily rounds data');
+            // You may also set an error state to display a user-friendly message
+            return;
+          }

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

🧰 Tools
🪛 Biome

[error] 110-110: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

@sainak sainak self-assigned this Nov 11, 2024
@sainak
Copy link
Member

sainak commented Nov 11, 2024

cosing in favor of #9079

github doesn't allow pushing changes to workflows on contributors repos

@sainak sainak closed this Nov 11, 2024
@Sahil-Sinha-11
Copy link
Author

I’m really sorry if I didn’t do it right. I’m still figuring things out, and I appreciate your patience. I’ll try to do better next time. Thanks for understanding. @rithviknishad I learned a lot, Thanks for the guidance 😀.

@sainak
Copy link
Member

sainak commented Nov 11, 2024

@Sahil-Sinha-11 you can reopen the pr and revert changes to the workflows folder, I had to close it because github was not allowing me to push to it

I'll add the changes from reviews to this pr itself

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 needs review tested
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Enhancements to Nursing tab UI
6 participants