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

Improved Button Responsiveness and Layout Adjustments #9161

Conversation

gurramkarthiknetha
Copy link

@gurramkarthiknetha gurramkarthiknetha commented Nov 19, 2024

Proposed Changes

  • Fixes fix the responsive ness #9156
    image
    here i changed the hap between the red button and green oulined button
  • Change 2
    -image
    here i changed the responsive-ness wrap
  • Change 3
  • image
  • here i improved the responsive ness of the buttons by align to center
  • Change 4
  • image
  • here i changed it level
  • Change 5
  • image
  • here i changed it level
    @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

    • Enhanced layout for various components, improving user interface consistency and responsiveness.
    • Added conditional checks for user roles in patient management, ensuring appropriate access to functionalities.
    • Introduced a confirmation dialog for changing patient code statuses in consent records.
    • Added new button for requesting sample tests in the mobile view of the PatientHome component.
    • Implemented new accessibility features by adding id attributes to various form fields and components.
  • Bug Fixes

    • Improved handling of existing consent records during file uploads to prevent errors.
  • Style

    • Updated spacing and layout styles across multiple components for better visual presentation.
    • Enhanced hover effects on buttons for improved user interaction feedback.

fixed responsiveness of the website with small changes
@gurramkarthiknetha gurramkarthiknetha requested a review from a team as a code owner November 19, 2024 14:43
Copy link
Contributor

coderabbitai bot commented Nov 19, 2024

Walkthrough

The pull request introduces several modifications across multiple components to enhance layout responsiveness and user interface. Key changes include updates to CSS class names for improved spacing and alignment in the AdvancedFilterButton, FacilityCard, KanbanBoard, ManagePatients, and PatientConsentRecords components. Additionally, logic adjustments were made to handle user roles and state management in the ManagePatients and PatientConsentRecords components, improving the control flow and user experience.

Changes

File Path Change Summary
src/CAREUI/interactive/FiltersSlideover.tsx Updated className of AdvancedFilterButton to include mt-2 for margin-top.
src/components/Facility/FacilityCard.tsx Changed className for facility details div to add gap; updated notification buttons layout.
src/components/Kanban/Board.tsx Added responsive CSS classes to KanbanBoard and updated KanbanSection for smaller viewports.
src/components/Patient/ManagePatients.tsx Updated button layout with gap; modified onTabChange for user role checks; adjusted ExportMenu.
src/components/Patient/PatientConsentRecords.tsx Introduced showPCSChangeModal state; refined handleUpload logic and updated upload button rendering.

Assessment against linked issues

Objective Addressed Explanation
Fix the responsiveness (#9156)

Possibly related issues

Possibly related PRs

Suggested labels

needs review, tested

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

🐇 "In the code where the buttons play,
A little margin brightens the way.
With gaps and flex, they dance and sway,
Making the layout a joy each day!"
🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
  • @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 19, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit ccb3981
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67596bbf375ed900082d56cc
😎 Deploy Preview https://deploy-preview-9161--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (9)
src/components/Kanban/Board.tsx (3)

61-61: Improve class naming convention

While the addition of flex-wrap styling for responsive design is good, the class name containerss appears to have a typo and doesn't follow clear naming conventions.

Consider renaming to something more semantic like:

-<div className="flex items-stretch px-0 pb-2 containerss">
+<div className="flex items-stretch px-0 pb-2 kanban-sections-container">

149-149: Improve CSS class organization and naming

The className string is becoming long and mixes utility classes with custom classes. The bshadow class name is not descriptive enough.

Consider:

  1. Using a more descriptive name like kanban-section-shadow
  2. Organizing classes using a CSS-in-JS solution or CSS modules
  3. Creating a dedicated class that encapsulates all these styles
-"relative mr-2 w-[300px] shrink-0 rounded-xl bg-secondary-200 bshadow"
+"kanban-section relative mr-2 w-[300px] shrink-0 rounded-xl bg-secondary-200"

Then define the styles in your CSS:

.kanban-section {
  box-shadow: /* your shadow values */;
}

Line range hint 108-117: Consider performance and type safety improvements

The scroll event handler could benefit from debouncing, and the response type could be more strictly typed.

Consider these improvements:

  1. Debounce the scroll event handler:
import { debounce } from 'lodash';

const debouncedOnBoardReachEnd = debounce(async () => {
  // existing logic
}, 150);

useEffect(() => {
  props.boardRef.current?.addEventListener("scroll", debouncedOnBoardReachEnd);
  return () => {
    props.boardRef.current?.removeEventListener("scroll", debouncedOnBoardReachEnd);
    debouncedOnBoardReachEnd.cancel();
  };
}, [props.boardRef, fetchingNextPage, hasMore]);
  1. Add proper typing for the API response:
interface PaginatedResponse<T> {
  results: T[];
  next: string | null;
  count: number;
}
src/components/Common/ButtonV2.tsx (1)

104-104: Reconsider adding global margin to base button styles

Adding mt-2 to the base button styles will affect all instances of ButtonV2 across the application. This could potentially break existing layouts and violates the principle of separation of concerns, as spacing should typically be controlled by the parent component.

Consider these alternatives:

  1. Add the margin where specifically needed using the className prop
  2. Create a new variant or prop for buttons that need this spacing
  3. Handle the spacing in the parent component's layout

Example of better approaches:

// Option 1: Add margin only where needed
<ButtonV2 className="mt-2" />

// Option 2: Add a prop for spacing
type ButtonProps = {
  // ... existing props
  spacing?: 'none' | 'compact' | 'normal' | 'loose';
}

// Option 3: Handle in parent (preferred)
<div className="space-y-2">
  <ButtonV2 />
  <ButtonV2 />
</div>
src/components/Patient/PatientConsentRecords.tsx (1)

235-235: LGTM! Consider using CSS modules for better maintainability.

The addition of mt-2 class improves vertical spacing consistency. However, consider using CSS modules or styled-components to better manage these utility classes and improve maintainability.

-    "button-size-default button-shape-square button-primary-default inline-flex mt-2 h-min w-full cursor-pointer items-center justify-center gap-2 whitespace-pre font-medium outline-offset-1 transition-all duration-200 ease-in-out"
+    styles.uploadButton // Define in a separate CSS module
src/components/Facility/FacilityCard.tsx (1)

Line range hint 1-276: Consider these architectural improvements for better maintainability.

While the current changes improve the layout, here are some suggestions to enhance the component's maintainability:

  1. Consider extracting the notification modal into a separate component to reduce complexity
  2. The responsive layout logic could be simplified by using Tailwind's @screen directives in a separate CSS file
  3. Common class combinations could be extracted into reusable Tailwind components

Example of extracting the notification modal:

// NotificationModal.tsx
interface NotificationModalProps {
  facilityId: string;
  facilityName: string;
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (message: string) => void;
}

const NotificationModal: React.FC<NotificationModalProps> = ({
  facilityId,
  facilityName,
  isOpen,
  onClose,
  onSubmit
}) => {
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  
  // ... rest of the modal logic
};
src/style/index.css (2)

1319-1323: Consider using a more conventional class name

The class name containerss with double 's' appears to be a typo or non-conventional naming. Consider renaming it to something more semantic like responsive-container or simply container.

-    .containerss{
+    .responsive-container {
         flex-wrap: wrap;
         gap: 5px;
         margin-bottom: 5px;
     }

1324-1327: Remove commented code and use a more descriptive class name

  1. The commented-out box-shadow property should either be implemented or removed.
  2. Consider using a more descriptive class name than bshadow to better convey its purpose.
-    .bshadow{
-        border:solid rgb(168, 168, 168);
-        /* box-shadow: 3px solid rgb(0, 0, 0) !important; */
-    }
+    .bordered-container {
+        border: solid rgb(168, 168, 168);
+    }
src/components/Patient/ManagePatients.tsx (1)

844-844: LGTM! Consider extracting the className into a constant.

The addition of flex-wrap improves the layout handling of filter controls, especially on smaller screens. However, for better maintainability, consider extracting the long className string into a constant or using a CSS module.

+ const filterControlsClassName = "flex w-full flex-col items-center justify-end flex-wrap gap-2 lg:ml-3 lg:w-fit lg:flex-row lg:gap-3";
- <div className="flex w-full flex-col items-center justify-end flex-wrap gap-2 lg:ml-3 lg:w-fit lg:flex-row lg:gap-3">
+ <div className={filterControlsClassName}>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ea713df and 645a562.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (8)
  • src/CAREUI/interactive/FiltersSlideover.tsx (1 hunks)
  • src/components/Common/ButtonV2.tsx (1 hunks)
  • src/components/Common/Menu.tsx (1 hunks)
  • src/components/Facility/FacilityCard.tsx (2 hunks)
  • src/components/Kanban/Board.tsx (2 hunks)
  • src/components/Patient/ManagePatients.tsx (1 hunks)
  • src/components/Patient/PatientConsentRecords.tsx (1 hunks)
  • src/style/index.css (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • src/CAREUI/interactive/FiltersSlideover.tsx
  • src/components/Common/Menu.tsx
🧰 Additional context used
🪛 Biome
src/style/index.css

[error] 1328-1328: expected } but instead the file ends

the file ends here

(parse)

🔇 Additional comments (2)
src/components/Facility/FacilityCard.tsx (2)

91-91: LGTM! Improved spacing between flex items.

The addition of gap-2 creates consistent spacing between items in the facility name section, improving the visual layout.


223-223: LGTM! Enhanced button alignment.

The addition of justify-center improves the visual alignment of the action buttons, particularly on smaller screens where the container might wrap.

@@ -101,7 +101,7 @@ export const buttonStyles = ({
shadow = !ghost,
}: ButtonStyleProps) => {
return classNames(
"inline-flex h-min cursor-pointer items-center justify-center gap-2 whitespace-pre font-medium outline-offset-1 transition-all duration-200 ease-in-out disabled:cursor-not-allowed disabled:bg-secondary-200 disabled:text-secondary-500",
"inline-flex h-min cursor-pointer items-center justify-center gap-2 whitespace-pre mt-2 font-medium outline-offset-1 transition-all duration-200 ease-in-out disabled:cursor-not-allowed disabled:bg-secondary-200 disabled:text-secondary-500",
Copy link
Contributor

@coderabbitai coderabbitai bot Nov 19, 2024

Choose a reason for hiding this comment

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

💡 Codebase verification

Adding default margin-top could cause layout inconsistencies

The mt-2 class has been added to the base button styles which could cause unexpected spacing in existing implementations. Based on the evidence:

  1. The ButtonV2 component is widely used across 100+ files in the codebase
  2. Current implementations use explicit className props for spacing when needed (e.g., m-2, py-[11px])
  3. The default margin-top in the base styles could interfere with existing layouts where buttons are precisely positioned

Recommendation:

  • Remove the mt-2 from the base button styles
  • Let consuming components control their own spacing through className props as they currently do
🔗 Analysis chain

Verify the impact on existing button instances

Let's assess how this change affects existing button implementations across the codebase.


The previous search showed widespread usage of ButtonV2 across the codebase. Now we need to examine actual usage patterns and the component definition to understand if the new margin will conflict with existing implementations.


The previous results show some ButtonV2 usages with custom classes, but we need to see the full component implementation and check specifically for margin-top conflicts to make a proper assessment.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for ButtonV2 usage patterns that might conflict with the new margin
echo "Checking for ButtonV2 instances with existing margin classes..."
rg -l "ButtonV2.*className.*mt-" 

echo "Checking for all ButtonV2 usages to understand the scope of impact..."
rg -l "ButtonV2"

echo "Checking for potential negative margin overrides that might be compensating for spacing..."
rg -l "ButtonV2.*className.*-mt-"

Length of output: 6867


Script:

#!/bin/bash
# Let's check for actual ButtonV2 usage patterns with className to understand margin conflicts
echo "Checking ButtonV2 usages with className prop..."
rg "ButtonV2.*className.*" -A 1

# Let's also check the ButtonV2 component definition to understand its composition
echo "Checking ButtonV2 component definition..."
rg "const ButtonV2" -A 10 src/components/Common/ButtonV2.tsx

Length of output: 1040


Script:

#!/bin/bash
# Let's check the full ButtonV2 component implementation to understand the className composition
echo "Checking full ButtonV2 implementation..."
cat src/components/Common/ButtonV2.tsx

# Let's also check for any existing margin-top classes in ButtonV2 usages
echo "Checking for existing margin-top classes in ButtonV2 usages..."
rg "ButtonV2.*className.*mt-[0-9]" -B 1 -A 1

Length of output: 7373

Copy link
Contributor

Choose a reason for hiding this comment

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

ButtonV2 is widely used - make sure this doesn't cause any issues elsewhere. Instead of modifying it here, modify wherever the specific issue is occurring.

Copy link
Contributor

Choose a reason for hiding this comment

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

Understood, @Jacobjeevan. To prevent potential issues elsewhere, I've removed the mt-2 class from the ButtonV2 component. Instead, we can add the mt-2 class to the specific instances where the margin is needed.

For example, in src/CAREUI/interactive/FiltersSlideover.tsx, update the AdvancedFilterButton:

<ButtonV2 className="w-full bg-white md:w-auto mt-2" onClick={toggleSlideover}>
  <CareIcon className="care-l-filter text-lg" />
  <span>Advanced Filters</span>
</ButtonV2>

This ensures that the margin is applied only where necessary without impacting other components.


✏️ Learnings added
Learnt from: Jacobjeevan
PR: ohcnetwork/care_fe#9161
File: src/components/Common/ButtonV2.tsx:104-104
Timestamp: 2024-11-20T05:14:50.931Z
Learning: When adjusting styling for widely used components like `ButtonV2`, avoid modifying the base styles to prevent unintended effects across the application. Instead, apply style changes directly in the specific instances where needed.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Copy link
Contributor

Choose a reason for hiding this comment

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

@gurramkarthiknetha We are switching over the Shadcn, gradually phasing out ButtonV2, so let's not modify here anyways.

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

src/style/index.css Outdated Show resolved Hide resolved
@@ -101,7 +101,7 @@ export const buttonStyles = ({
shadow = !ghost,
}: ButtonStyleProps) => {
return classNames(
"inline-flex h-min cursor-pointer items-center justify-center gap-2 whitespace-pre font-medium outline-offset-1 transition-all duration-200 ease-in-out disabled:cursor-not-allowed disabled:bg-secondary-200 disabled:text-secondary-500",
"inline-flex h-min cursor-pointer items-center justify-center gap-2 whitespace-pre mt-2 font-medium outline-offset-1 transition-all duration-200 ease-in-out disabled:cursor-not-allowed disabled:bg-secondary-200 disabled:text-secondary-500",
Copy link
Contributor

Choose a reason for hiding this comment

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

ButtonV2 is widely used - make sure this doesn't cause any issues elsewhere. Instead of modifying it here, modify wherever the specific issue is occurring.

src/style/index.css Outdated Show resolved Hide resolved
@Jacobjeevan
Copy link
Contributor

Jacobjeevan commented Nov 20, 2024

Also follow the PR format what we have (refer to other PRs). Edit the title to be readable as well.

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 (2)
src/style/index.css (2)

1319-1323: Consider renaming the class for better maintainability

The class name containerss appears to have a typo (extra 's'). Consider renaming it to container or a more semantic name that describes its purpose.

-    .containerss{
+    .container{
         flex-wrap: wrap;
         gap: 5px;
         margin-bottom: 5px;
     }

1324-1326: Improve border specification

The border property is missing width specification. Consider using a more explicit border declaration for better consistency.

     .bshadow{
-        border:solid rgb(168, 168, 168);
+        border: 1px solid rgb(168, 168, 168);
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 645a562 and 4465945.

📒 Files selected for processing (2)
  • src/components/Common/ButtonV2.tsx (1 hunks)
  • src/style/index.css (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Common/ButtonV2.tsx
🧰 Additional context used
🪛 Biome
src/style/index.css

[error] 1330-1330: expected } but instead the file ends

the file ends here

(parse)

🔇 Additional comments (1)
src/style/index.css (1)

1318-1330: LGTM! The media query implementation looks good

The responsive adjustments for smaller screens are well-structured and the use of rem units in .mtrequired is good for accessibility.

🧰 Tools
🪛 Biome

[error] 1330-1330: expected } but instead the file ends

the file ends here

(parse)

src/components/Common/ButtonV2.tsx Outdated Show resolved Hide resolved
@@ -36,7 +36,7 @@ export default function DropdownMenu({
<Menu as="div" className="relative inline-block w-full text-left">
<MenuButton
disabled={props.disabled}
className={`button-size-${size} button-${variant}-default button-shape-square flex w-full cursor-pointer items-center justify-center gap-2 font-medium outline-offset-1 transition-all duration-200 ease-in-out disabled:cursor-not-allowed disabled:bg-secondary-200 disabled:text-secondary-500 lg:justify-between ${props.className}`}
className={`button-size-${size} button-${variant}-default button-shape-square flex w-full cursor-pointer items-center justify-center gap-2 font-medium outline-offset-1 transition-all duration-200 ease-in-out disabled:cursor-not-allowed disabled:bg-secondary-200 disabled:text-secondary-500 mt-2 lg:justify-between ${props.className}`}
Copy link
Contributor

Choose a reason for hiding this comment

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

Make sure it isn't causing any issues elsewhere as Menu is used throughout.

Copy link
Contributor

Choose a reason for hiding this comment

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

Same for Menu as well.

Copy link
Contributor

Choose a reason for hiding this comment

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

Same with menu as well, switching over to Shadcn, so let's not modify this.

@@ -58,7 +58,7 @@ export default function KanbanBoard<T extends { id: string }>(
</div>
<DragDropContext onDragEnd={props.onDragEnd}>
<div className="h-full overflow-scroll" ref={board}>
<div className="flex items-stretch px-0 pb-2">
<div className="flex items-stretch px-0 pb-2 containerss">
Copy link
Contributor

@Jacobjeevan Jacobjeevan Nov 20, 2024

Choose a reason for hiding this comment

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

Tailwind allows for custom breakpoints for one-off cases, let's use that instead of creating a new class.

https://tailwindcss.com/docs/responsive-design#using-custom-breakpoints Check the very last section.

Copy link
Contributor

Choose a reason for hiding this comment

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

Remove the custom class @gurramkarthiknetha

Use the existing breakpoints in Tailwind instead.

src/components/Kanban/Board.tsx Outdated Show resolved Hide resolved
@Jacobjeevan
Copy link
Contributor

Also follow the PR format what we have (refer to other PRs). Edit the title to be readable as well.

Also this ☝️ @gurramkarthiknetha

@gurramkarthiknetha
Copy link
Author

Now i kept from the same branch .
Did i need to change any more

"integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==",
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
Copy link
Contributor

Choose a reason for hiding this comment

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

Leave out package-lock from the commit please.

Copy link
Contributor

Choose a reason for hiding this comment

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

@gurramkarthiknetha Leave package-lock out of the commit.

src/components/Kanban/Board.tsx Outdated Show resolved Hide resolved
src/components/Kanban/Board.tsx Outdated Show resolved Hide resolved
@rithviknishad
Copy link
Member

@gurramkarthiknetha It's required to follow the original PR template and link the issue in it. Also keep a proper readable title that conveys what has changed in the PR.

@gurramkarthiknetha gurramkarthiknetha changed the title issue #9156 fixed Improved Button Responsiveness and Layout Adjustments Nov 22, 2024
@gurramkarthiknetha
Copy link
Author

now is this ok

src/components/Common/ButtonV2.tsx Outdated Show resolved Hide resolved
@@ -36,7 +36,7 @@ export default function DropdownMenu({
<Menu as="div" className="relative inline-block w-full text-left">
<MenuButton
disabled={props.disabled}
className={`button-size-${size} button-${variant}-default button-shape-square flex w-full cursor-pointer items-center justify-center gap-2 font-medium outline-offset-1 transition-all duration-200 ease-in-out disabled:cursor-not-allowed disabled:bg-secondary-200 disabled:text-secondary-500 lg:justify-between ${props.className}`}
className={`button-size-${size} button-${variant}-default button-shape-square flex w-full cursor-pointer items-center justify-center gap-2 font-medium outline-offset-1 transition-all duration-200 ease-in-out disabled:cursor-not-allowed disabled:bg-secondary-200 disabled:text-secondary-500 mt-2 lg:justify-between ${props.className}`}
Copy link
Contributor

Choose a reason for hiding this comment

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

Same for Menu as well.

package-lock.json Show resolved Hide resolved
@Jacobjeevan
Copy link
Contributor

@gurramkarthiknetha Any updates on the PR?

@gurramkarthiknetha
Copy link
Author

i am still working on this issue i will keep pr by tonight

@rithviknishad
Copy link
Member

rithviknishad commented Dec 3, 2024

@gurramkarthiknetha avoid requesting reviews without making the requested changes

@gurramkarthiknetha
Copy link
Author

@rithviknishad @Jacobjeevan, if any changes are required, please let me know, and I will update them.

Copy link
Contributor

@Jacobjeevan Jacobjeevan left a comment

Choose a reason for hiding this comment

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

Latest push doesn't seem to have included any additional changes here @gurramkarthiknetha.

Please make sure to address each of the comments before requesting for review.

"integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==",
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
Copy link
Contributor

Choose a reason for hiding this comment

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

@gurramkarthiknetha Leave package-lock out of the commit.

@@ -101,7 +101,7 @@ export const buttonStyles = ({
shadow = !ghost,
}: ButtonStyleProps) => {
return classNames(
"inline-flex h-min cursor-pointer items-center justify-center gap-2 whitespace-pre font-medium outline-offset-1 transition-all duration-200 ease-in-out disabled:cursor-not-allowed disabled:bg-secondary-200 disabled:text-secondary-500",
"inline-flex h-min cursor-pointer items-center justify-center gap-2 whitespace-pre mt-2 font-medium outline-offset-1 transition-all duration-200 ease-in-out disabled:cursor-not-allowed disabled:bg-secondary-200 disabled:text-secondary-500",
Copy link
Contributor

Choose a reason for hiding this comment

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

@gurramkarthiknetha We are switching over the Shadcn, gradually phasing out ButtonV2, so let's not modify here anyways.

@@ -36,7 +36,7 @@ export default function DropdownMenu({
<Menu as="div" className="relative inline-block w-full text-left">
<MenuButton
disabled={props.disabled}
className={`button-size-${size} button-${variant}-default button-shape-square flex w-full cursor-pointer items-center justify-center gap-2 font-medium outline-offset-1 transition-all duration-200 ease-in-out disabled:cursor-not-allowed disabled:bg-secondary-200 disabled:text-secondary-500 lg:justify-between ${props.className}`}
className={`button-size-${size} button-${variant}-default button-shape-square flex w-full cursor-pointer items-center justify-center gap-2 font-medium outline-offset-1 transition-all duration-200 ease-in-out disabled:cursor-not-allowed disabled:bg-secondary-200 disabled:text-secondary-500 mt-2 lg:justify-between ${props.className}`}
Copy link
Contributor

Choose a reason for hiding this comment

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

Same with menu as well, switching over to Shadcn, so let's not modify this.

@@ -58,7 +58,7 @@ export default function KanbanBoard<T extends { id: string }>(
</div>
<DragDropContext onDragEnd={props.onDragEnd}>
<div className="h-full overflow-scroll" ref={board}>
<div className="flex items-stretch px-0 pb-2">
<div className="flex items-stretch px-0 pb-2 containerss">
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove the custom class @gurramkarthiknetha

Use the existing breakpoints in Tailwind instead.

src/components/Kanban/Board.tsx Outdated Show resolved Hide resolved
src/style/index.css 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: 12

🧹 Outside diff range and nitpick comments (25)
public/locale/en.json (1)

266-267: LGTM! ABHA QR linking translations are clear and well-structured.

The translations are descriptive and follow the established naming pattern for ABHA-related entries.

Consider adding an ellipsis at the end of the description to indicate an action that will follow:

-  "abha_link_options__link_with_qr__description": "Link Existing ABHA Number by Scanning the ABHA QR",
+  "abha_link_options__link_with_qr__description": "Link Existing ABHA Number by Scanning the ABHA QR...",
src/components/Patient/PatientHome.tsx (2)

1298-1298: Add the same ID to the desktop version of the sample request button.

The button implementation looks good, but for consistency in testing and analytics, consider adding the same ID to the desktop version of this button.


Line range hint 1290-1305: Consider refactoring repeated button patterns.

The mobile view section contains multiple buttons with similar patterns for authorization, navigation, and disabled states. Consider extracting these patterns into a reusable component to reduce code duplication and improve maintainability.

Example refactor:

interface ActionButtonProps {
  id?: string;
  icon: string;
  text: string;
  path: string;
  requiresActivePatient?: boolean;
  authorizeFor?: typeof NonReadOnlyUsers;
}

const PatientActionButton: React.FC<ActionButtonProps> = ({
  id,
  icon,
  text,
  path,
  requiresActivePatient = false,
  authorizeFor,
}) => (
  <ButtonV2
    id={id}
    className="w-full"
    disabled={requiresActivePatient && isPatientInactive(patientData, facilityId)}
    onClick={() => navigate(path)}
    authorizeFor={authorizeFor}
  >
    <span className="flex w-full items-center justify-start gap-2">
      <CareIcon icon={icon} className="text-xl" />
      {text}
    </span>
  </ButtonV2>
);

Usage:

<PatientActionButton
  id="sample-request-btn"
  icon="l-medkit"
  text="Request Sample Test"
  path={`/facility/${patientData?.facility}/patient/${id}/sample-test`}
  requiresActivePatient
  authorizeFor={NonReadOnlyUsers}
/>
src/components/Patient/SampleDetails.tsx (3)

365-365: Document the purpose of DOM IDs

Consider adding a comment or documentation explaining the purpose of these IDs (e.g., for testing, accessibility, or third-party integrations). This helps maintain the code and evaluate their necessity.


373-375: Extract name formatting logic to a utility function

Consider extracting the name formatting logic (startCase(camelCase())) to a reusable utility function. This would improve maintainability and ensure consistent name formatting across the application.

+ // Add to utils.ts
+ export const formatName = (name: string) => startCase(camelCase(name));

- <span id="doctor_name">
-   {startCase(camelCase(sampleDetails.doctor_name))}
- </span>
+ <span id="doctor_name">
+   {formatName(sampleDetails.doctor_name)}
+ </span>

Line range hint 1-401: Consider component decomposition for better maintainability

The SampleDetails component is handling multiple responsibilities. Consider:

  1. Extracting the patient card into a separate component
  2. Creating a dedicated component for medical information display
  3. Implementing proper error boundaries for API failures
  4. Adding loading states for individual sections

This would improve:

  • Code maintainability
  • Reusability
  • Error handling
  • Performance through selective re-renders
src/components/Facility/ConsultationDetails/ConsultationNursingTab.tsx (3)

8-11: Import Statement Adjustment Needed

The import statement includes both NursingPlotFields and NursingPlotRes, but NursingPlot has been removed. Ensure that all unused imports are removed to keep the codebase clean.

Apply this diff to remove the unused imports:

 import { ConsultationTabProps } from "@/components/Facility/ConsultationDetails/index";
-import LogUpdateAnalyseTable from "@/components/Facility/Consultations/LogUpdateAnalyseTable";
 import {
-  NursingPlotFields,
-  NursingPlotRes,
   RoutineAnalysisRes,
   RoutineFields,
 } from "@/components/Facility/models";

Line range hint 21-37: Potential Inefficient Value Handling in getDisplayValue Function

In the getDisplayValue function, there's a nested conditional logic that could be simplified for better readability and performance.

Consider refactoring the function as follows:

 const getDisplayValue = (
   value: string | boolean | null | undefined,
   field?: string,
 ): string => {
-  if (typeof value === "boolean") {
-    return t(value ? "yes" : "no");
-  }
-
-  if (field && choices[field]) {
-    const choiceMap = choices[field];
-    const choice =
-      typeof value === "string" || typeof value === "number"
-        ? choiceMap[value]
-        : undefined;
-    return choice ? t(`${field.toUpperCase()}__${choice}`) : "-";
-  }
-
-  return typeof value === "string" ? value : "-";
+  if (value === null || value === undefined) return "-";
+  if (typeof value === "boolean") return t(value ? "yes" : "no");
+  if (field && choices[field]) {
+    const choice = choices[field][value];
+    return choice ? t(`${field.toUpperCase()}__${choice}`) : "-";
+  }
+  return String(value);
 };

165-174: Pagination Component Not Handling Page Size

The pagination component is checking if totalCount > PAGINATION_LIMIT, but there is no handling for different page sizes.

Consider making PAGINATION_LIMIT dynamic or ensuring that it reflects the actual page size used in the API call.

src/components/Facility/Consultations/LogUpdateAnalyseTable.tsx (1)

42-90: Accessibility Improvements for Table Component

The table lacks some accessibility features, such as proper scope attributes for headers and row labels.

Consider adding scope attributes to th elements to improve accessibility.

 <th
   className="sticky left-0 border-b-2 border-r-2 border-black bg-white"
+  scope="col"
 >
 </th>

And for row headers:

 <th
   className={classNames(
     "sticky left-0 border border-r-2 border-secondary-500 border-r-black bg-white p-2",
     row.subField ? "pl-4 font-medium" : "font-bold",
   )}
+  scope="row"
 >
cypress/pageobject/utils/paginationHelpers.ts (1)

1-13: Return Cypress chainables for method chaining

Consider returning Cypress chainable objects from your methods to enable method chaining in your tests.

Apply this diff to return the chainables:

 export const pageNavigation = {
   navigateToNextPage() {
-    cy.get("button#next-pages").click();
+    return cy.get("button#next-pages").click();
   },

   verifyCurrentPageNumber(pageNumber: number) {
-    cy.url().should("include", `page=${pageNumber}`);
+    return cy.url().should("include", `page=${pageNumber}`);
   },

   navigateToPreviousPage() {
-    cy.get("button#prev-pages").click();
+    return cy.get("button#prev-pages").click();
   },
 };
src/Integrations/Plausible.tsx (1)

13-22: Good addition of configuration validation!

The validation for Plausible configuration is a good defensive programming practice. However, consider using a more structured logging approach.

Consider using a structured logger or creating a common logging utility:

-      console.error(
-        `Plausible analytics disabled. Missing configuration: ${missingConfig.join(", ")}`,
-      );
+      logger.error("Plausible analytics disabled", {
+        missingConfig: missingConfig.join(", "),
+        component: "Plausible"
+      });
cypress/e2e/assets_spec/AssetHomepage.cy.ts (1)

81-84: LGTM! Consider enhancing pagination verification.

The migration to pageNavigation helper improves code reusability. The addition of page number verification strengthens the test.

Consider adding verification for the presence of next/previous buttons before navigation:

+    pageNavigation.verifyPaginationControls();
     pageNavigation.navigateToNextPage();
     pageNavigation.verifyCurrentPageNumber(2);
     pageNavigation.navigateToPreviousPage();
     pageNavigation.verifyCurrentPageNumber(1);
cypress/e2e/sample_test_spec/SampleTestRequest.cy.ts (1)

11-24: Consider moving test data to fixtures.

Moving test data constants to a fixture file would improve maintainability and reusability across tests.

Create a fixture file and load test data:

+ // cypress/fixtures/sample-test-data.json
+ {
+   "patientName": "Dummy Patient Eleven",
+   "sampleTestType": "BA/ETA",
+   "icmrCategory": "Cat 0",
+   ...
+ }

- const patientName = "Dummy Patient Eleven";
- const sampleTestType = "BA/ETA";
- ...
+ let testData;
+ before(() => {
+   cy.fixture('sample-test-data.json').then((data) => {
+     testData = data;
+   });
+ });
package.json (1)

Line range hint 1-1: Consider splitting unrelated changes into separate PRs

The current changes, while technically sound, appear to address multiple unrelated concerns:

  1. API testing improvements in PatientConsultation.ts
  2. Test maintenance in PatientConsultationDischarge.cy.ts
  3. Environment validation setup in package.json

Consider splitting these changes into separate PRs to maintain focused code reviews and clearer change history. This would help align with the PR's stated objective of improving button responsiveness and layout adjustments.

cypress/support/commands.ts (1)

129-132: Consider making the cancel button selector more flexible.

The current implementation uses a hard-coded ID selector which could be brittle. Consider making it more flexible like the submit button command.

-Cypress.Commands.add("clickCancelButton", (buttonText = "Cancel") => {
-  cy.get("#cancel").contains(buttonText).scrollIntoView();
-  cy.get("#cancel").contains(buttonText).click();
+Cypress.Commands.add("clickCancelButton", (buttonText = "Cancel") => {
+  cy.get("button[type='button']").contains(buttonText).scrollIntoView();
+  cy.get("button[type='button']").contains(buttonText).click();
});
src/components/Facility/TransferPatientDialog.tsx (2)

78-93: Simplify the handleChange implementation.

The current implementation can be simplified by moving the length check into the condition.

 const handleChange = (e: FieldChangeEvent<unknown>) => {
-  const value = String(e.value);
-
-  if (e.name === "year_of_birth") {
-    if (value.length <= 4) {
-      dispatch({
-        type: "set_form",
-        form: { ...state.form, [e.name]: e.value },
-      });
-    }
-  } else {
+  if (e.name === "year_of_birth" && String(e.value).length > 4) {
+    return;
+  }
+  
+  dispatch({
+    type: "set_form",
+    form: { ...state.form, [e.name]: e.value },
+  });
-  }
 };

95-110: Extract validation messages to constants to avoid duplication.

The validation messages for year constraints are duplicated across handleOnBlur and validateForm. Consider extracting them to constants.

+const YEAR_VALIDATION_MESSAGES = {
+  MAX_YEAR: (maxYear: number) => `Cannot be greater than ${maxYear}`,
+  MIN_YEAR: 'Cannot be smaller than 1900'
+};

 const handleOnBlur = (e: React.FocusEvent<HTMLInputElement>) => {
   const yearValue = Number(state.form.year_of_birth);
   if (!state.form.year_of_birth) return;
   let errorMessage = "";
   if (yearValue > maxYear) {
-    errorMessage = `Cannot be greater than ${maxYear}`;
+    errorMessage = YEAR_VALIDATION_MESSAGES.MAX_YEAR(maxYear);
   } else if (yearValue < 1900) {
-    errorMessage = `Cannot be smaller than 1900`;
+    errorMessage = YEAR_VALIDATION_MESSAGES.MIN_YEAR;
   }
   // ... rest of the code

   // In validateForm
   if (parseInt(state.form[field] || "0") > maxYear) {
-    errors[field] = `Cannot be greater than ${maxYear}`;
+    errors[field] = YEAR_VALIDATION_MESSAGES.MAX_YEAR(maxYear);
     invalidForm = true;
   }

   if (parseInt(state.form[field] || "0") < 1900) {
-    errors[field] = `Cannot be smaller than 1900`;
+    errors[field] = YEAR_VALIDATION_MESSAGES.MIN_YEAR;
     invalidForm = true;
   }

Also applies to: 134-138

cypress/e2e/patient_spec/PatientHomepage.cy.ts (1)

167-168: LGTM! Consider enhancing pagination verification.

The changes improve test maintainability by using the centralized pageNavigation helper. The implementation correctly verifies navigation and page content differences.

Consider adding verification for:

  • Total number of pages
  • Items per page
  • Correct ordering of results

Also applies to: 175-175

src/components/Facility/BedCapacity.tsx (1)

282-295: Consider simplifying button rendering logic.

The current implementation has nested conditions for button rendering. This could be simplified for better maintainability.

Consider this alternative approach:

-            {headerText === "Add Bed Capacity" && (
-              <Submit
-                id="bed-capacity-save-and-exit"
-                onClick={(e) => handleSubmit(e, "Save and Exit")}
-                label="Save Bed Capacity"
-              />
-            )}
-            {!isLastOptionType && (
-              <Submit
-                id="bed-capacity-save"
-                onClick={(e) => handleSubmit(e)}
-                label={buttonText}
-              />
-            )}
+            {(headerText === "Add Bed Capacity" || !isLastOptionType) && (
+              <>
+                {headerText === "Add Bed Capacity" && (
+                  <Submit
+                    id="bed-capacity-save-and-exit"
+                    onClick={(e) => handleSubmit(e, "Save and Exit")}
+                    label="Save Bed Capacity"
+                  />
+                )}
+                {!isLastOptionType && (
+                  <Submit
+                    id="bed-capacity-save"
+                    onClick={(e) => handleSubmit(e)}
+                    label={buttonText}
+                  />
+                )}
+              </>
+            )}
cypress/e2e/patient_spec/PatientRegistration.cy.ts (1)

67-67: LGTM! Consider standardizing patient naming convention.

The changes improve maintainability by using template literals and more readable patient names.

Consider standardizing the patient naming convention across all test files for consistency. For example:

  • Use word representation consistently (e.g., "Dummy Patient One" instead of "Dummy Patient 1")
  • Document the naming convention in test utilities or constants

Also applies to: 246-246

cypress/pageobject/Facility/FacilityCreation.ts (1)

305-307: Consider consolidating notification verification methods

The new verifyErrorNotification method is identical to the existing verifySuccessNotification method. Consider consolidating them into a single method with a more generic name to avoid code duplication.

-  verifySuccessNotification(message: string) {
-    cy.verifyNotification(message);
-  }
-
-  verifyErrorNotification(message: string) {
-    cy.verifyNotification(message);
-  }
+  verifyNotification(message: string) {
+    cy.verifyNotification(message);
+  }
cypress/e2e/facility_spec/FacilityCreation.cy.ts (1)

337-351: LGTM: Well-structured access control test with good practices

The test case effectively validates access restrictions for non-admin users:

  • Good use of array to test multiple user roles
  • Proper cleanup with cy.clearCookies()
  • Clear error message verification

Consider adding more non-admin roles to the test coverage.

 const nonAdminLoginMethods = [
   loginPage.loginAsDevDoctor.bind(loginPage),
   loginPage.loginAsStaff.bind(loginPage),
+  loginPage.loginAsNurse.bind(loginPage),
+  loginPage.loginAsLabTechnician.bind(loginPage),
 ];
src/components/Notifications/NotificationsList.tsx (1)

292-332: Enhanced error handling in unsubscribe function

The refactored unsubscribe function includes several improvements:

  1. Proper async/await usage
  2. Comprehensive error handling
  3. Cleanup in finally block
  4. Specific error messages for different failure scenarios

However, consider extracting the subscription update logic into a separate function for better reusability.

+ const updateSubscriptionConfig = async (username: string, config: { pf_endpoint: string, pf_p256dh: string, pf_auth: string }) => {
+   return request(routes.updateUserPnconfig, {
+     pathParams: { username },
+     body: config,
+   });
+ };

  const unsubscribe = async () => {
    try {
      // ... existing checks ...
      
      if (subscription) {
        try {
          await subscription.unsubscribe();
-         await request(routes.updateUserPnconfig, {
-           pathParams: { username },
-           body: {
-             pf_endpoint: "",
-             pf_p256dh: "",
-             pf_auth: "",
-           },
-         });
+         await updateSubscriptionConfig(username, {
+           pf_endpoint: "",
+           pf_p256dh: "",
+           pf_auth: "",
+         });
          
          setIsSubscribed("NotSubscribed");
          // ... rest of the code ...
src/components/Facility/FacilityHome.tsx (1)

463-475: Add accessibility attributes to the button

While the button implementation looks good, consider adding accessibility attributes for better screen reader support.

 <ButtonV2
   variant="primary"
   ghost
   border
   className="mt-2 flex w-full flex-row justify-center md:w-auto"
   onClick={() => navigate(`/facility/${facilityId}/patient`)}
   authorizeFor={NonReadOnlyUsers}
+  aria-label={t("add_details_of_patient")}
+  role="button"
 >
   <CareIcon icon="l-plus" className="text-lg" />
   <span className="text-sm">{t("add_details_of_patient")}</span>
 </ButtonV2>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d166687 and ccb3981.

📒 Files selected for processing (55)
  • cypress/e2e/assets_spec/AssetHomepage.cy.ts (2 hunks)
  • cypress/e2e/facility_spec/FacilityCreation.cy.ts (1 hunks)
  • cypress/e2e/facility_spec/FacilityHomepage.cy.ts (3 hunks)
  • cypress/e2e/facility_spec/FacilityLocation.cy.ts (3 hunks)
  • cypress/e2e/hcx_spec/HcxClaims.cy.ts (3 hunks)
  • cypress/e2e/patient_spec/PatientBedManagement.cy.ts (1 hunks)
  • cypress/e2e/patient_spec/PatientConsultationCreation.cy.ts (9 hunks)
  • cypress/e2e/patient_spec/PatientConsultationDischarge.cy.ts (6 hunks)
  • cypress/e2e/patient_spec/PatientDoctorConnect.cy.ts (1 hunks)
  • cypress/e2e/patient_spec/PatientDoctorNotes.cy.ts (1 hunks)
  • cypress/e2e/patient_spec/PatientFileUpload.ts (1 hunks)
  • cypress/e2e/patient_spec/PatientHomepage.cy.ts (2 hunks)
  • cypress/e2e/patient_spec/PatientInvestigation.cy.ts (2 hunks)
  • cypress/e2e/patient_spec/PatientLogUpdate.cy.ts (15 hunks)
  • cypress/e2e/patient_spec/PatientPrescription.cy.ts (10 hunks)
  • cypress/e2e/patient_spec/PatientRegistration.cy.ts (2 hunks)
  • cypress/e2e/sample_test_spec/SampleTestRequest.cy.ts (1 hunks)
  • cypress/e2e/users_spec/UsersHomepage.cy.ts (3 hunks)
  • cypress/e2e/users_spec/UsersManage.cy.ts (1 hunks)
  • cypress/pageobject/Asset/AssetPagination.ts (0 hunks)
  • cypress/pageobject/Facility/FacilityCreation.ts (2 hunks)
  • cypress/pageobject/Login/LoginPage.ts (1 hunks)
  • cypress/pageobject/Patient/PatientConsultation.ts (1 hunks)
  • cypress/pageobject/Patient/PatientCreation.ts (2 hunks)
  • cypress/pageobject/Patient/PatientFileupload.ts (2 hunks)
  • cypress/pageobject/Patient/PatientHome.ts (0 hunks)
  • cypress/pageobject/Sample/SampleTestCreate.ts (1 hunks)
  • cypress/pageobject/Users/UserSearch.ts (0 hunks)
  • cypress/pageobject/utils/paginationHelpers.ts (1 hunks)
  • cypress/support/commands.ts (1 hunks)
  • cypress/support/index.ts (1 hunks)
  • package.json (2 hunks)
  • public/locale/en.json (4 hunks)
  • src/CAREUI/interactive/LegendInput.tsx (1 hunks)
  • src/Integrations/Plausible.tsx (1 hunks)
  • src/Integrations/Sentry.tsx (1 hunks)
  • src/components/Auth/Login.tsx (1 hunks)
  • src/components/Facility/BedCapacity.tsx (2 hunks)
  • src/components/Facility/ConsultationDetails/ConsultationNursingTab.tsx (4 hunks)
  • src/components/Facility/Consultations/LogUpdateAnalyseTable.tsx (1 hunks)
  • src/components/Facility/Consultations/NursingPlot.tsx (0 hunks)
  • src/components/Facility/FacilityHome.tsx (2 hunks)
  • src/components/Facility/TransferPatientDialog.tsx (3 hunks)
  • src/components/Facility/models.tsx (1 hunks)
  • src/components/Kanban/Board.tsx (2 hunks)
  • src/components/Notifications/NotificationsList.tsx (2 hunks)
  • src/components/Patient/DailyRounds.tsx (3 hunks)
  • src/components/Patient/ManagePatients.tsx (2 hunks)
  • src/components/Patient/PatientHome.tsx (1 hunks)
  • src/components/Patient/PatientRegister.tsx (6 hunks)
  • src/components/Patient/SampleDetails.tsx (2 hunks)
  • src/components/Patient/SampleTest.tsx (5 hunks)
  • src/components/Patient/SampleTestCard.tsx (5 hunks)
  • src/components/Patient/SampleViewAdmin.tsx (3 hunks)
  • vite.config.mts (2 hunks)
💤 Files with no reviewable changes (4)
  • cypress/pageobject/Asset/AssetPagination.ts
  • src/components/Facility/Consultations/NursingPlot.tsx
  • cypress/pageobject/Patient/PatientHome.ts
  • cypress/pageobject/Users/UserSearch.ts
✅ Files skipped from review due to trivial changes (5)
  • cypress/e2e/patient_spec/PatientDoctorNotes.cy.ts
  • cypress/e2e/patient_spec/PatientFileUpload.ts
  • src/CAREUI/interactive/LegendInput.tsx
  • src/components/Auth/Login.tsx
  • src/components/Patient/SampleTestCard.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/components/Kanban/Board.tsx
  • src/components/Patient/ManagePatients.tsx
🧰 Additional context used
📓 Learnings (3)
src/Integrations/Sentry.tsx (2)
Learnt from: sainak
PR: ohcnetwork/care_fe#9160
File: src/Integrations/Sentry.tsx:4-16
Timestamp: 2024-11-19T14:04:36.276Z
Learning: When Sentry is disabled, the `src/Integrations/Sentry.tsx` module is replaced with a dummy module that has skeleton handlers based on the main file, so additional checks in `initSentry` are unnecessary.
Learnt from: sainak
PR: ohcnetwork/care_fe#9160
File: src/Integrations/Sentry.tsx:19-25
Timestamp: 2024-11-19T14:04:32.755Z
Learning: In the `src/Integrations/Sentry.tsx` file, the Sentry module may be replaced with a dummy module that has skeleton handlers based on the main file, so additional error handling in the `captureException` function is not required.
cypress/pageobject/Patient/PatientConsultation.ts (1)
Learnt from: Jacobjeevan
PR: ohcnetwork/care_fe#9145
File: cypress/e2e/patient_spec/PatientConsultationCreation.cy.ts:93-94
Timestamp: 2024-11-18T10:48:08.501Z
Learning: In `cypress/e2e/patient_spec/PatientConsultationCreation.cy.ts`, bed capacity verification assertions after patient admission are already being performed elsewhere, so adding them here is unnecessary.
cypress/e2e/facility_spec/FacilityLocation.cy.ts (2)
Learnt from: Jacobjeevan
PR: ohcnetwork/care_fe#9145
File: cypress/e2e/facility_spec/FacilityCreation.cy.ts:177-180
Timestamp: 2024-11-18T10:44:30.303Z
Learning: In `cypress/e2e/facility_spec/FacilityCreation.cy.ts`, when testing bed and staff capacity individually for additional error verification, we prefer to use separate method calls to handle bed and staff capacity, rather than using `facilityPage.createNewFacility(testFacilityData)` which also handles bed management.
Learnt from: kihan2518B
PR: ohcnetwork/care_fe#8956
File: cypress/e2e/facility_spec/FacilityCreation.cy.ts:261-261
Timestamp: 2024-12-04T18:58:47.241Z
Learning: In `cypress/e2e/facility_spec/FacilityCreation.cy.ts`, the test case titled "Create a new facility with no bed and doctor capacity" includes steps to select bed types and specializations before validation. This is done intentionally to verify that error messages are shown properly when no capacity is specified.
🔇 Additional comments (45)
src/components/Patient/SampleTest.tsx (3)

219-219: LGTM! Added IDs improve form field accessibility.

The addition of id attributes to the sample type and ICMR category select fields enhances accessibility and testability.

Also applies to: 234-234


260-264: LGTM! Added ID improves ICMR label field accessibility.

The addition of id attribute to the ICMR label text field enhances accessibility and testability.


Line range hint 283-345: LGTM! Added IDs improve form accessibility.

The addition of id attributes to various form fields (fast track, doctor name, atypical presentation, etc.) and the submit button enhances accessibility and testability.

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

158-161: LGTM! Added ID improves patient name accessibility.

The addition of id="sample-test-patient-name" to the patient name div enhances accessibility and testability.


280-280: LGTM! Added ID improves button accessibility.

The addition of id="sample-details-btn" to the sample details button enhances accessibility and testability.

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

62-62: LGTM! Added import for enhanced form field.

The addition of RangeAutocompleteFormField import supports the improved SPO2 input implementation.


707-730: LGTM! Enhanced SPO2 input with range validation.

The new implementation using RangeAutocompleteFormField provides better user experience with:

  • Range validation (0-100%)
  • Visual thresholds for different SPO2 levels
  • Clear labeling of normal and abnormal ranges

803-818: LGTM! Improved SPO2 thresholds with translations.

The updated thresholds now use translated labels for different SPO2 levels, improving internationalization support:

  • Severe hypoxemia
  • Moderate hypoxemia
  • Mild hypoxemia
  • Normal
public/locale/en.json (1)

208-211: LGTM! SpO2 level translations are accurate and consistent.

The translations for SpO2 levels follow medical terminology and maintain consistent naming patterns with other entries in the file.

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

1298-1298: Verify the sample test request navigation path.

Let's verify that the navigation path for sample test requests is consistent between mobile and desktop views.

✅ Verification successful

Based on the search results, I can now provide a final response regarding the navigation path consistency:

Sample test request navigation is consistent across all views

The codebase shows consistent navigation behavior for sample test requests:

  • Both mobile and desktop views use the same navigation path /sample/${id}
  • The responsive design is properly implemented using Tailwind CSS classes
  • The sample test card and related components adapt appropriately to different screen sizes using responsive classes like sm:, md:, lg:, etc.
  • The navigation is triggered through the same onClick handlers regardless of viewport size
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistency in sample test request navigation paths

# Search for sample test related navigation paths
rg -A 2 "navigate.*sample-test" src/

Length of output: 38


Script:

#!/bin/bash
# Let's try a broader search for navigation related to samples or test requests
# First, let's look for any references to the sample-request-btn ID
rg "sample-request-btn" src/ -B 2 -A 2

# Also search for any navigation paths containing "sample" or "test"
rg "navigate.*(?:sample|test)" src/ -B 2 -A 2

# Look for route definitions related to samples or tests
rg "path:.*(?:sample|test)" src/ -B 2 -A 2

Length of output: 3111


Script:

#!/bin/bash
# Let's check for any mobile-specific navigation or responsive components
# Search for mobile view related code near sample test components
rg -B 3 -A 3 "(?i)mobile.*sample|sample.*mobile" src/

# Look for responsive design elements in the sample test related components
rg -B 3 -A 3 "(?:xs|sm|md|lg|xl):[^\"']+" src/components/Patient/SampleTestCard.tsx src/components/Patient/PatientHome.tsx

# Check for any conditional rendering based on screen size
rg "useMediaQuery|useBreakpoint" src/components/Patient/ -B 2 -A 2

Length of output: 28111

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

383-383: Review medical data handling practices

The addition of DOM IDs to sensitive medical information (diagnosis, differential diagnosis, etiology) should align with healthcare data protection requirements (e.g., HIPAA). Consider:

  1. Implementing data masking for sensitive information in the DOM
  2. Adding proper access control attributes
  3. Documenting compliance requirements for frontend data display

Also applies to: 391-391, 399-401

src/components/Facility/models.tsx (1)

394-397: ⚠️ Potential issue

Ensure Consistency in Type Definitions

The updated NursingPlotRes interface specifies that procedure and description are of type string. Verify that these fields are always present and of the specified type in the data received from the API.

Run the following script to check the types of procedure and description in nursing data:

If the fields are sometimes null or undefined, adjust the type definitions accordingly.

✅ Verification successful

Based on the code analysis, I can now generate the final response:

Type Definition is Consistent with Implementation

The codebase shows that the nursing array's procedure and description fields are consistently used as strings:

  • In NursingCare.tsx, the description is either obtained from existing data or defaulted to an empty string ("")
  • In ConsultationNursingTab.tsx, these fields are used in data transformation without any type checking or null handling, indicating they are treated as required string fields
  • The implementation shows no handling of null or undefined cases for these fields
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all entries in the nursing data have `procedure` and `description` as strings.

# Test: Use `jq` to parse and check the data structure. Expect: All entries have `procedure` and `description` as strings.
curl -s <API_ENDPOINT> | jq '.results[] | .nursing[] | select(.procedure | type != "string" or .description | type != "string")'

# Note: Replace <API_ENDPOINT> with the actual endpoint used to fetch nursing data.

Length of output: 311


Script:

#!/bin/bash
# Let's analyze the codebase to understand how these fields are used

# Search for usage of nursing data structure
rg -A 5 -B 5 "nursing.*procedure.*description" 

# Search for API response handling related to nursing data
rg -A 5 "nursing.*\[" 

# Look for any test files or mock data
fd -e test.tsx -e test.ts -e mock.ts -e mock.tsx -X rg "nursing"

Length of output: 2886

vite.config.mts (1)

106-128: Great use of environment variable validation

The addition of the ValidateEnv plugin with a zod schema enhances configuration validation and strengthens application robustness.

src/Integrations/Sentry.tsx (1)

10-13: Avoid redundant checks in Sentry initialization

Based on previous learnings, when Sentry is disabled, the Sentry.tsx module is replaced with a dummy module that provides skeleton handlers. The additional check for careConfig.sentry.environment is unnecessary and can be removed to simplify the code.

cypress/e2e/patient_spec/PatientInvestigation.cy.ts (2)

10-10: LGTM: Patient name standardization improves readability

The change from "Dummy Patient 14" to "Dummy Patient Thirteen" aligns with the broader effort to standardize patient names across test files, making the test data more readable and consistent.


31-31: LGTM: Method name change improves clarity

The update from submitButton to clickSubmitButton makes the action more explicit and aligns with the standardized button interaction methods defined in the support file.

cypress/support/index.ts (1)

17-18: Verify all test files for method rename impact

The interface changes look good:

  1. Renaming submitButton to clickSubmitButton improves clarity
  2. Adding clickCancelButton provides consistent button handling

Let's verify that all test files have been updated to use the new method names:

✅ Verification successful

All test files have been updated to use the new method names

The verification shows:

  1. No occurrences of the old submitButton() method were found
  2. The new clickSubmitButton() is widely used across test files
  3. The new clickCancelButton() is properly implemented and used in multiple test files
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining uses of old method name

# Search for old method name
echo "Checking for remaining uses of submitButton..."
rg "submitButton\(" --type ts

# Search for new method usage to verify adoption
echo "Verifying usage of new methods..."
rg "clickSubmitButton\(" --type ts
rg "clickCancelButton\(" --type ts

Length of output: 7134

cypress/e2e/patient_spec/PatientBedManagement.cy.ts (1)

14-15: LGTM: Consistent patient name standardization

The changes to switchPatientOne and switchPatientTwo follow the established pattern of using word form instead of numerals, improving readability and maintaining consistency across test files.

cypress/pageobject/Login/LoginPage.ts (1)

23-23: Verify consistent usage of clickSubmitButton across test files

The change from submitButton to clickSubmitButton improves clarity. Let's ensure this change is applied consistently.

Also applies to: 29-29

✅ Verification successful

All instances of submitButton have been replaced with clickSubmitButton

The verification shows that the old cy.submitButton() method is no longer used anywhere in the cypress directory, while cy.clickSubmitButton() is consistently used across all test files. The change has been applied uniformly throughout the test suite.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any remaining usage of old submitButton method
echo "Checking for old submitButton usage:"
rg "cy\.submitButton\(" "cypress/"

echo "Checking for new clickSubmitButton usage:"
rg "cy\.clickSubmitButton\(" "cypress/"

Length of output: 6538

cypress/pageobject/Patient/PatientFileupload.ts (1)

61-61: Verify custom command implementation

The changes from cy.submitButton to cy.clickSubmitButton appear to be part of a standardization effort. However, we should verify that this custom command is properly defined.

Also applies to: 92-92

✅ Verification successful

Custom command is properly implemented

The clickSubmitButton command is correctly defined in cypress/support/commands.ts and is widely used across the codebase. The command is also properly typed in cypress/support/index.ts. The change from cy.submitButton to cy.clickSubmitButton is valid and consistent with the standardization effort.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the custom command definition
rg -A 5 "Cypress.Commands.add\('clickSubmitButton'" cypress/support/

Length of output: 76


Script:

#!/bin/bash
# Let's try a broader search for the command definition
rg -g "*.{ts,js}" "clickSubmitButton" cypress/

# Also search for any command definitions in support directory
rg -g "*.{ts,js}" "Cypress.Commands.add" cypress/support/

Length of output: 8210

cypress/e2e/users_spec/UsersHomepage.cy.ts (2)

88-91: LGTM: Improved code organization with centralized pagination

The refactor to use centralized pagination methods from pageNavigation helper improves code maintainability and reduces duplication.


2-2: Verify imported module and test data dependencies

The changes introduce centralized pagination handling and update test data:

  1. New import of pageNavigation helper
  2. Updated doctorUserName from "devdoctor1" to "dev-doctor2"

Also applies to: 20-20

✅ Verification successful

Changes are safe and properly implemented

The verification shows:

  1. The pageNavigation helper exists and is properly exported with navigation methods
  2. The helper is already being used consistently across multiple test files (facility, patient specs)
  3. The test data change (dev-doctor2) appears to be isolated to the UsersHomepage test and doesn't affect other tests
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the pagination helper exists
rg -l "export.*pageNavigation" cypress/pageobject/utils/paginationHelpers.ts

# Check for other occurrences of the old test data
rg "devdoctor1" cypress/

Length of output: 149


Script:

#!/bin/bash
# Let's verify the actual implementation of pageNavigation
rg -A 5 "export.*pageNavigation" cypress/pageobject/utils/paginationHelpers.ts

# Check for any other files using devdoctor1 or dev-doctor2
rg -l "dev-?doctor[12]" cypress/

# Check for other files using pagination to understand the impact
rg -l "pagination" cypress/

Length of output: 570


Script:

#!/bin/bash
# Let's check how pagination is implemented in other files to ensure consistency
rg -A 3 "pagination" cypress/e2e/patient_spec/PatientHomepage.cy.ts cypress/e2e/facility_spec/FacilityHomepage.cy.ts

# Check the full context of test data usage in UsersHomepage
rg -A 3 -B 3 "dev-?doctor[12]" cypress/e2e/users_spec/UsersHomepage.cy.ts

Length of output: 2026

cypress/e2e/hcx_spec/HcxClaims.cy.ts (1)

14-14: Verify test data and UI element selectors

The changes include:

  1. Updated hcxPatientName from "Dummy Patient 14" to "Dummy Patient Thirteen"
  2. Changed to cy.clickSubmitButton
  3. Added new UI interactions for insurance policy editing

Please verify:

  1. The new patient name exists in the test environment
  2. The selector "#edit-insurance-policy" exists in the UI

Also applies to: 51-51, 83-84

✅ Verification successful

Let me analyze the test data dependencies and UI interactions more thoroughly with these commands. I'm looking for:

  1. All patient name patterns to understand the naming convention
  2. Insurance policy related selectors and their usage
  3. The implementation of the new button click method

This will help verify the changes more effectively.


Changes are consistent with test data and UI implementation

The verification results show:

  1. "Dummy Patient Thirteen" is already used in multiple test files (PatientInvestigation.cy.ts and PatientConsultationCreation.cy.ts), confirming it's a valid test data value
  2. The insurance policy selector exists in both the source code (src/components/HCX/PolicyEligibilityCheck.tsx) and is used consistently in cypress tests
  3. cy.clickSubmitButton is widely used across the test suite, including in HcxClaims.cy.ts
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for other occurrences of the old patient name
rg "Dummy Patient 14" cypress/

# Check for the existence of the new selector
rg -A 5 "edit-insurance-policy" "src/"

Length of output: 69


Script:

#!/bin/bash
# Search for any patient name patterns in cypress tests
rg "Dummy Patient" cypress/

# Search for insurance policy related selectors in both cypress and src
rg -A 3 "insurance.*policy" cypress/ src/

# Look for button click implementations
ast-grep --pattern 'cy.clickSubmitButton'

Length of output: 9873

cypress/pageobject/Patient/PatientConsultation.ts (1)

116-122: Verify alignment with PR objectives

These new API interception methods, while well-implemented, appear unrelated to the PR's stated objective of improving button responsiveness and layout adjustments. Consider:

  1. Moving these changes to a separate PR focused on test improvements
  2. Documenting why these API verification methods are necessary for the UI changes
✅ Verification successful

API interception methods are necessary for UI responsiveness testing

The new API interception methods are actually related to the PR's objective of improving button responsiveness. The changes in the codebase show:

  1. Multiple button-related changes from submitButton to clickSubmitButton in consultation flows
  2. UI responsiveness improvements in patient consultation views
  3. The API interception methods are needed to properly test the button click responses and ensure the UI remains responsive during API calls

The methods follow Cypress best practices by:

  • Intercepting the patient details API that's called during button interactions
  • Verifying the response to ensure the UI updates correctly
  • Supporting the overall goal of improving button responsiveness testing
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if these API endpoints are related to any UI components being modified
rg -l "patientDetails" | grep -i "button\|layout\|responsive"

Length of output: 61


Script:

#!/bin/bash
# Let's first check what files contain patientDetails to understand the context
rg -l "patientDetails"

# Then check the PR changes to see if there are any UI-related modifications
git diff HEAD~1 --name-only

# Finally, let's look at the content of the test file to understand the context
rg -A 5 -B 5 "patientDetails" cypress/pageobject/Patient/PatientConsultation.ts

Length of output: 3106


Script:

#!/bin/bash
# Let's check the content of the test files that use PatientConsultation to understand the context
rg -l "PatientConsultation" cypress/e2e/patient_spec/

# And look at the specific changes in the PR for these files
git diff HEAD~1 cypress/e2e/patient_spec/PatientConsultationCreation.cy.ts
git diff HEAD~1 cypress/e2e/patient_spec/PatientConsultationDischarge.cy.ts

# Also check if there are any UI component changes related to patient consultation
git diff HEAD~1 src/components/Patient/

Length of output: 28162

cypress/e2e/patient_spec/PatientConsultationDischarge.cy.ts (1)

37-38: Verify custom command implementation

The change from submitButton to clickSubmitButton is more descriptive, but we should verify the custom command implementation.

Also applies to: 55-56, 80-81, 112-113

✅ Verification successful

Custom command clickSubmitButton is properly implemented and old command is fully replaced

The verification confirms:

  • The new clickSubmitButton command is properly defined in cypress/support/commands.ts
  • No occurrences of the old submitButton() command were found in the test files
  • The implementation correctly handles button text and includes scroll + click actions
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the new command is properly defined
rg -A 5 "Cypress.Commands.add\(['\"]clickSubmitButton" "cypress/support/"

# Verify no remaining uses of old command
rg "submitButton\(\)" "cypress/e2e/"

Length of output: 564

package.json (1)

102-102: Clarify necessity of new dependencies

The addition of environment validation packages (@julr/vite-plugin-validate-env and zod) appears unrelated to the PR's focus on button responsiveness and layout adjustments. Consider:

  1. Moving these dependency additions to a separate PR focused on environment validation
  2. Documenting why these packages are necessary for the UI changes

Also applies to: 149-150

cypress/support/commands.ts (1)

124-127: LGTM! Well-implemented submit button command.

The implementation is robust with:

  • Type-specific selector for better reliability
  • ScrollIntoView for improved test stability
  • Optional parameter for flexibility
cypress/pageobject/Patient/PatientCreation.ts (1)

26-26: LGTM! Consistent usage of the new button command.

The changes properly implement the new clickSubmitButton command, improving consistency across the test suite.

Also applies to: 60-60

src/components/Facility/TransferPatientDialog.tsx (1)

218-218: LGTM! Good addition of blur event handling.

The addition of the onBlur handler improves the user experience by providing immediate feedback when the input loses focus.

cypress/e2e/users_spec/UsersManage.cy.ts (1)

63-63: LGTM! Good test setup enhancement.

The addition of home facility selection before linking skills improves the test's robustness by ensuring proper facility context.

cypress/e2e/patient_spec/PatientPrescription.cy.ts (1)

29-29: Consistent method naming and patient identifiers.

The changes improve code consistency by:

  1. Using more explicit method names (clickSubmitButton instead of submitButton).
  2. Standardizing patient identifiers to use word form instead of numbers.

Also applies to: 39-39, 47-47, 49-49, 54-54, 56-56, 66-66, 76-76, 86-86, 100-100, 111-111, 119-119, 132-132, 134-134, 139-139, 148-148, 158-158

cypress/e2e/facility_spec/FacilityHomepage.cy.ts (3)

2-3: LGTM! Good modularization of pagination logic.

The import of pageNavigation helper aligns with the codebase's move towards centralized pagination handling.


86-89: Clean pagination method updates.

The changes improve code organization by using the centralized pagination helper, making the code more maintainable and consistent across the test suite.


155-155: Consistent button click method naming.

The standardization of button click methods to use clickSubmitButton improves code clarity and maintainability.

Also applies to: 163-163

src/components/Facility/BedCapacity.tsx (1)

80-81: LGTM! Improved handling of disabled options.

The early return optimization when all options are disabled improves performance and code clarity.

cypress/e2e/facility_spec/FacilityLocation.cy.ts (2)

174-175: LGTM: Pagination helper refactor

The change to use the new pageNavigation helper is consistent with the codebase-wide refactoring of pagination functionality.


196-196: LGTM: Standardized button submission method

The change from submitButton to clickSubmitButton aligns with the standardization of button submission methods across the test suite.

Also applies to: 203-203

cypress/pageobject/Facility/FacilityCreation.ts (1)

279-279: LGTM: Standardized button submission method

The change from submitButton to clickSubmitButton maintains consistency with the test suite's button submission standardization.

cypress/e2e/facility_spec/FacilityCreation.cy.ts (1)

320-335: LGTM: Comprehensive district permission test

The test case effectively validates the district-level access control for facility creation. The setup and verification steps are clear and well-structured.

cypress/e2e/patient_spec/PatientLogUpdate.cy.ts (2)

35-35: LGTM: Patient name standardization improves readability

The change from numeric to word format in patient names (e.g., "Dummy Patient Nine" instead of "Dummy Patient 9") improves readability and consistency.

Also applies to: 37-37, 39-39, 41-41


58-58: Verify test stability after button click method changes

The change from submitButton to clickSubmitButton appears to be part of a broader standardization effort. While the change is good for consistency, we should ensure test stability.

Also applies to: 77-77, 94-94, 98-98, 107-107, 111-111, 115-115, 123-123, 129-129, 146-146, 159-159, 169-169, 177-177, 180-180, 206-206, 209-209, 254-254, 266-266, 284-284, 310-310, 327-327, 339-339, 349-349

✅ Verification successful

Let me check the actual usage context of both methods to ensure there's no mixed usage within files.


The change to clickSubmitButton has been fully implemented

The search results confirm that:

  1. There are no remaining instances of the old submitButton method in the codebase
  2. The new clickSubmitButton method is consistently used across all test files with proper button text parameters
  3. All usages follow the same pattern and are working with notifications/verifications
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistent usage of clickSubmitButton across test files

# Check if there are any remaining instances of the old method
rg -l 'submitButton\(' 'cypress/e2e'

# Check if the new method is consistently used
rg -l 'clickSubmitButton\(' 'cypress/e2e'

Length of output: 586


Script:

#!/bin/bash
# Check actual usage of both methods with surrounding context
echo "=== Checking submitButton usage ==="
rg 'submitButton\(' 'cypress/e2e' -A 1 -B 1

echo -e "\n=== Checking clickSubmitButton usage ==="
rg 'clickSubmitButton\(' 'cypress/e2e' -A 1 -B 1

Length of output: 17867

cypress/e2e/patient_spec/PatientConsultationCreation.cy.ts (1)

378-378: LGTM: Consistent with standardization changes

The changes maintain consistency with the standardization effort seen across test files:

  1. Patient name updated to word format ("Dummy Patient Thirteen")
  2. Button click method updated to clickSubmitButton

Also applies to: 389-389

src/components/Notifications/NotificationsList.tsx (1)

247-250: Improved service worker availability check

Good addition of the service worker availability check before proceeding with subscription logic. This prevents potential runtime errors.

src/components/Facility/FacilityHome.tsx (2)

463-475: LGTM! Authorization and responsive layout implementation

The button implementation:

  • Correctly uses authorization check through patientRegisterAuth
  • Implements responsive layout with proper class names
  • Follows the team's button component standards
  • Uses translations for internationalization

51-51: Verify the imported authorization function

Let's ensure the patientRegisterAuth function is properly exported from the PatientRegister component.

✅ Verification successful

Import statement is correctly implemented

The verification confirms that:

  • The patientRegisterAuth function is properly exported from src/components/Patient/PatientRegister.tsx
  • It's correctly imported and used in FacilityHome.tsx for conditional button rendering
  • The function is used consistently across both files with the same parameter signature (authUser, facilityObject, facilityId)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the exported function exists in the source file

# Check if the function is exported from PatientRegister
ast-grep --pattern 'export $_ patientRegisterAuth'

# Check all references to this function
rg "patientRegisterAuth" -A 2

Length of output: 1014

@@ -331,7 +331,7 @@ export const SampleDetails = ({ id }: DetailRoute) => {
<span className="font-semibold leading-relaxed">
{t("patient")}:{" "}
</span>
{sampleDetails?.patient_name}
<span id="patient_name">{sampleDetails?.patient_name}</span>
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Consider using data-testid instead of ID for patient name element

The codebase shows consistent usage of data-testid for testing and accessibility purposes, including sensitive patient information. The current approach of using id="patient_name" should be changed to use data-testid instead, which is the established pattern in this codebase for handling test selectors and accessibility markers.

Examples from the codebase:

  • data-testid="patient-details" for patient information sections
  • data-testid="patient-dashboard" for patient dashboard
  • data-testid="patient-present-health" for health information

This change would:

  1. Follow the established pattern in the codebase
  2. Better separate testing/accessibility concerns from styling/behavioral IDs
  3. Reduce exposure of PII in the DOM structure
🔗 Analysis chain

Consider data privacy implications of exposing patient name in DOM ID

While adding IDs improves accessibility and testability, exposing PII in DOM IDs could pose security risks. Consider using a more generic ID or data-testid attribute if this is for testing purposes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for other instances of potentially exposed PII in DOM IDs
rg -i 'id=["\'](.*?)(name|email|phone|address|passport|birth|nationality)' --type tsx --type jsx

Length of output: 279


Script:

#!/bin/bash
# Search for DOM elements with IDs containing PII-related terms
rg -i 'id=["\''][^"\']*?(name|email|phone|address|passport|birth|nationality)' --type tsx --type jsx

# Also check for data-testid attributes as they might be used for testing
rg -i 'data-testid=["\''][^"\']*?(name|email|phone|address|passport|birth|nationality)' --type tsx --type jsx

# Look for patient-related information in IDs
rg -i 'id=["\'']patient[^"\']*?' --type tsx --type jsx

Length of output: 283


Script:

#!/bin/bash
# Search for DOM elements with IDs containing PII-related terms, using simpler pattern
rg "id=\"patient_name\"" --type tsx --type jsx -A 2 -B 2

# Look for other patient-related IDs in the component
rg "id=\"patient" --type tsx --type jsx -A 2 -B 2

# Check if data-testid is used anywhere in the codebase
rg "data-testid" --type tsx --type jsx

Length of output: 230


Script:

#!/bin/bash
# Search for DOM elements with IDs containing PII-related terms without file type filters
rg "id=\"patient_name\"" -A 2 -B 2

# Look for other patient-related IDs
rg "id=\"patient" -A 2 -B 2

# Check for data-testid attribute usage
rg "data-testid"

# Check the file extension of SampleDetails to confirm the correct type
fd "SampleDetails"

Length of output: 27043

Comment on lines +254 to +259
<RoutineSection {...props} />
</div>
<div>
<h4 aria-label={t("nursing_care")}>{t("nursing_care")}</h4>
<NursingPlot {...props} />
</div>
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Incorrect Component Usage

In the ConsultationNursingTab, the RoutineSection and NursingPlot components are being used directly, but their imports are not shown in the code. Ensure that these components are properly imported.

Add the necessary import statements for RoutineSection and confirm that NursingPlot is defined correctly.

 import { ConsultationTabProps } from "@/components/Facility/ConsultationDetails/index";
+import RoutineSection from "./RoutineSection";
+import NursingPlot from "./NursingPlot";

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

Comment on lines +127 to +140
const tableData = Object.entries(results).reduce(
(acc: Record<string, Record<string, string>>, [date, result]) => {
if ("nursing" in result) {
result.nursing.forEach((field) => {
if (field.procedure && !acc[date]) acc[date] = {};
acc[date][field.procedure] = field.description;
// Add procedure to the set of procedures to display
fieldsToDisplay.add(field.procedure);
});
}
return acc;
},
{},
);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Type Assertion Could Cause Runtime Errors

In the reducer function for tableData, there's a type assertion that acc[date] exists before assigning to it, which might not always be the case.

Adjust the logic to ensure acc[date] is properly initialized before assignment.

 const tableData = Object.entries(results).reduce(
   (acc: Record<string, Record<string, string>>, [date, result]) => {
     if ("nursing" in result) {
       result.nursing.forEach((field) => {
         if (field.procedure) {
-          if (!acc[date]) acc[date] = {};
+          acc[date] = acc[date] || {};
           acc[date][field.procedure] = field.description;
           // Add procedure to the set of procedures to display
           fieldsToDisplay.add(field.procedure);
         }
       });
     }
     return acc;
   },
   {},
 );
📝 Committable suggestion

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

Suggested change
const tableData = Object.entries(results).reduce(
(acc: Record<string, Record<string, string>>, [date, result]) => {
if ("nursing" in result) {
result.nursing.forEach((field) => {
if (field.procedure && !acc[date]) acc[date] = {};
acc[date][field.procedure] = field.description;
// Add procedure to the set of procedures to display
fieldsToDisplay.add(field.procedure);
});
}
return acc;
},
{},
);
const tableData = Object.entries(results).reduce(
(acc: Record<string, Record<string, string>>, [date, result]) => {
if ("nursing" in result) {
result.nursing.forEach((field) => {
if (field.procedure) {
acc[date] = acc[date] || {};
acc[date][field.procedure] = field.description;
// Add procedure to the set of procedures to display
fieldsToDisplay.add(field.procedure);
}
});
}
return acc;
},
{},
);

Comment on lines +142 to +144
fieldsToDisplay = fieldsToDisplay.intersection(
new Set(NURSING_CARE_PROCEDURES),
);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential Issue with Set Intersection Method

The Set.prototype.intersection method is not a standard JavaScript method and may not work as expected.

Replace with a standard approach to ensure compatibility.

 fieldsToDisplay = new Set(
   [...fieldsToDisplay].filter((x) => NURSING_CARE_PROCEDURES.includes(x)),
 );
📝 Committable suggestion

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

Suggested change
fieldsToDisplay = fieldsToDisplay.intersection(
new Set(NURSING_CARE_PROCEDURES),
);
fieldsToDisplay = new Set(
[...fieldsToDisplay].filter((x) => NURSING_CARE_PROCEDURES.includes(x)),
);

Comment on lines +93 to +117
const NursingPlot = ({ consultationId }: ConsultationTabProps) => {
const { t } = useTranslation();
const [results, setResults] = useState<{ [date: string]: NursingPlotRes }>(
{},
);
const [currentPage, setCurrentPage] = useState(1);
const [totalCount, setTotalCount] = useState(0);

useEffect(() => {
const fetchDailyRounds = async (
currentPage: number,
consultationId: string,
) => {
const { res, data } = await request(routes.dailyRoundsAnalyse, {
body: { page: currentPage, fields: NursingPlotFields },
pathParams: { consultationId },
});
if (res?.ok && data) {
setResults(data.results as { [date: string]: NursingPlotRes });
setTotalCount(data.count);
}
};

fetchDailyRounds(currentPage, consultationId);
}, [consultationId, currentPage]);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Error Handling for Data Fetching in useEffect Hook

The fetchDailyRounds function within the useEffect hook does not include error handling. If the API call fails, it could lead to unhandled promises or undefined states.

Consider adding error handling to manage API call failures gracefully.

 useEffect(() => {
   const fetchDailyRounds = async (
     currentPage: number,
     consultationId: string,
   ) => {
     try {
       const { res, data } = await request(routes.dailyRoundsAnalyse, {
         body: { page: currentPage, fields: NursingPlotFields },
         pathParams: { consultationId },
       });
       if (res?.ok && data) {
         setResults(data.results as { [date: string]: NursingPlotRes });
         setTotalCount(data.count);
+      } else {
+        // Handle response errors
+        console.error("Failed to fetch daily rounds data");
+      }
     } catch (error) {
       // Handle network or other errors
+      console.error("An error occurred while fetching data:", error);
     }
   };

   fetchDailyRounds(currentPage, consultationId);
 }, [consultationId, currentPage]);
📝 Committable suggestion

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

Suggested change
const NursingPlot = ({ consultationId }: ConsultationTabProps) => {
const { t } = useTranslation();
const [results, setResults] = useState<{ [date: string]: NursingPlotRes }>(
{},
);
const [currentPage, setCurrentPage] = useState(1);
const [totalCount, setTotalCount] = useState(0);
useEffect(() => {
const fetchDailyRounds = async (
currentPage: number,
consultationId: string,
) => {
const { res, data } = await request(routes.dailyRoundsAnalyse, {
body: { page: currentPage, fields: NursingPlotFields },
pathParams: { consultationId },
});
if (res?.ok && data) {
setResults(data.results as { [date: string]: NursingPlotRes });
setTotalCount(data.count);
}
};
fetchDailyRounds(currentPage, consultationId);
}, [consultationId, currentPage]);
const NursingPlot = ({ consultationId }: ConsultationTabProps) => {
const { t } = useTranslation();
const [results, setResults] = useState<{ [date: string]: NursingPlotRes }>(
{},
);
const [currentPage, setCurrentPage] = useState(1);
const [totalCount, setTotalCount] = useState(0);
useEffect(() => {
const fetchDailyRounds = async (
currentPage: number,
consultationId: string,
) => {
try {
const { res, data } = await request(routes.dailyRoundsAnalyse, {
body: { page: currentPage, fields: NursingPlotFields },
pathParams: { consultationId },
});
if (res?.ok && data) {
setResults(data.results as { [date: string]: NursingPlotRes });
setTotalCount(data.count);
} else {
// Handle response errors
console.error("Failed to fetch daily rounds data");
}
} catch (error) {
// Handle network or other errors
console.error("An error occurred while fetching data:", error);
}
};
fetchDailyRounds(currentPage, consultationId);
}, [consultationId, currentPage]);

Comment on lines +10 to +13
const patientName = "Dummy Patient Eleven";
const doctorUser = "Dev Doctor";
const nurseUser = "Dev Staff";
const teleIcuUser = "Dev Doctor Two";
const teleIcuUser = "Tester Doctor";
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Test data is consistent with ongoing standardization

The changes in PatientDoctorConnect.cy.ts align with the existing test data patterns:

  • Patient names consistently use spelled-out numbers ("Eleven", "Twelve", "Thirteen", etc.)
  • Doctor name "Dev Doctor" is the standard pattern used across consultation and doctor-related tests

The change from "Dev Doctor Two" to "Tester Doctor" in this file appears to be an isolated instance and should be reverted to maintain consistency with other test files where "Dev Doctor" is the standard pattern.

  • cypress/e2e/patient_spec/PatientDoctorConnect.cy.ts: Change teleIcuUser back to "Dev Doctor" instead of "Tester Doctor"
🔗 Analysis chain

Verify test data consistency across the test suite

The changes to test data constants (patientName and teleIcuUser) should be consistent with other test files to maintain data integrity.


Let me gather more information about the test data patterns to ensure a comprehensive verification.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining numeric patient names and inconsistent doctor names
echo "Checking for numeric patient names:"
rg -l "Dummy Patient \d+" "cypress/"

echo "Checking for inconsistent doctor names:"
rg -l "Dev Doctor Two|Tester Doctor" "cypress/"

Length of output: 306


Script:

#!/bin/bash
# Search for all patient name patterns and doctor names in cypress tests
echo "All patient name patterns:"
rg "Dummy Patient" "cypress/" -A 1

echo -e "\nAll doctor user patterns:"
rg "(?:const|let)\s+\w*[Dd]octor\w*\s*=\s*[\"']([^\"']+)[\"']" "cypress/"

Length of output: 4816

Comment on lines +36 to +87
it("should request a new sample test", () => {
// Ensure patient list API is loaded before proceeding
cy.awaitUrl("/patients");
patientPage.visitPatient(patientName);
patientConsultationPage.interceptPatientDetailsAPI();
patientConsultationPage.clickPatientDetails();
patientConsultationPage.verifyPatientDetailsResponse();
// Visit SampleRequest Page
sampleTestPage.visitSampleRequestPage();
// Fill Sample Test Request Form
sampleTestPage.selectSampleType(sampleTestType);
sampleTestPage.selectIcmrCategory(icmrCategory);
sampleTestPage.fillIcmrLabel(icmrLabel);
sampleTestPage.fillFastTrackReason(fastTrackReason);
sampleTestPage.fillDoctorName(doctorName);
sampleTestPage.fillAtypicalPresentation(atypicalDetails);
sampleTestPage.fillDiagnosis(diagnosis);
sampleTestPage.fillEtiology(etiologyIdentified);
sampleTestPage.fillDiffDiagnosis(differentialDiagnosis);
sampleTestPage.checkHasSari();
sampleTestPage.checkHasAri();
sampleTestPage.checkIsUnusualCourse();
sampleTestPage.interceptSampleTestReq();
// Submit the form and verify notification
cy.clickSubmitButton("Confirm your request to send sample for testing");
sampleTestPage.verifySampleTestReq();
cy.verifyNotification("Sample test created successfully");
// Check the updated request history
sampleTestPage.checkRequestHistory(
sampleTestStatus,
expectedSampleTestType,
fastTrackReason,
sampleTestResult,
);
// Checking Reflection on Sample Page
cy.awaitUrl("/sample");
sampleTestPage.interceptGetSampleTestReq();
sampleTestPage.searchPatientSample(patientName);
sampleTestPage.verifyGetSampleTestReq();
sampleTestPage.verifyPatientName(patientName);
sampleTestPage.interceptGetSampleTestReq();
sampleTestPage.clickOnSampleDetailsBtn();
sampleTestPage.verifyGetSampleTestReq();
sampleTestPage.verifyPatientTestDetails(
patientName,
fastTrackReason,
doctorName,
diagnosis,
differentialDiagnosis,
etiologyIdentified,
);
});
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 breaking down the test into smaller, focused test cases.

While the test is well-structured, it's testing multiple functionalities in a single test case. This could make maintenance and debugging more difficult.

Consider splitting into multiple test cases:

it('should navigate to sample request page', () => {
  // Navigation and initial setup
});

it('should fill and submit sample test form', () => {
  // Form filling and submission
});

it('should verify sample test creation', () => {
  // Verification steps
});

it('should handle form submission errors', () => {
  // Error cases
});

Comment on lines +58 to +62
sampleTestPage.interceptSampleTestReq();
// Submit the form and verify notification
cy.clickSubmitButton("Confirm your request to send sample for testing");
sampleTestPage.verifySampleTestReq();
cy.verifyNotification("Sample test created successfully");
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 API failures.

The test should handle potential API failures gracefully.

Add error case handling:

     sampleTestPage.interceptSampleTestReq();
     cy.clickSubmitButton("Confirm your request to send sample for testing");
-    sampleTestPage.verifySampleTestReq();
+    cy.wait('@sampleTestReq').then((interception) => {
+      if (interception.response?.statusCode === 201) {
+        cy.verifyNotification("Sample test created successfully");
+      } else {
+        cy.verifyNotification("Failed to create sample test");
+      }
+    });
-    cy.verifyNotification("Sample test created successfully");
📝 Committable suggestion

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

Suggested change
sampleTestPage.interceptSampleTestReq();
// Submit the form and verify notification
cy.clickSubmitButton("Confirm your request to send sample for testing");
sampleTestPage.verifySampleTestReq();
cy.verifyNotification("Sample test created successfully");
sampleTestPage.interceptSampleTestReq();
cy.clickSubmitButton("Confirm your request to send sample for testing");
cy.wait('@sampleTestReq').then((interception) => {
if (interception.response?.statusCode === 201) {
cy.verifyNotification("Sample test created successfully");
} else {
cy.verifyNotification("Failed to create sample test");
}
});

Comment on lines +97 to +113
interceptSampleTestReq(): void {
cy.intercept("POST", "**/api/v1/patient/*/test_sample/").as(
"sampleDetails",
);
}

verifySampleTestReq(): void {
cy.wait("@sampleDetails").its("response.statusCode").should("eq", 201);
}

interceptGetSampleTestReq(): void {
cy.intercept("GET", "**/api/v1/test_sample/**").as("getSampleTestReq");
}

verifyGetSampleTestReq(): void {
cy.wait("@getSampleTestReq").its("response.statusCode").should("eq", 200);
}
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

Enhance API interception handling.

The API interception methods could be more robust with additional validations and timeout handling.

Add timeout and response validation:

   interceptSampleTestReq(): void {
     cy.intercept("POST", "**/api/v1/patient/*/test_sample/").as(
       "sampleDetails",
     );
   }

   verifySampleTestReq(): void {
-    cy.wait("@sampleDetails").its("response.statusCode").should("eq", 201);
+    cy.wait("@sampleDetails", { timeout: 10000 }).then((interception) => {
+      expect(interception.response?.statusCode).to.eq(201);
+      expect(interception.response?.body).to.have.property("id");
+      expect(interception.response?.body).to.have.property("status");
+    });
   }

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

Comment on lines +69 to +71
searchPatientSample(patientName: string): void {
cy.get("#search_patient_name").should("be.visible").type(patientName);
}
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

Enhance search method resilience.

The search method could be more robust by handling loading states and search results.

Add loading and results handling:

   searchPatientSample(patientName: string): void {
-    cy.get("#search_patient_name").should("be.visible").type(patientName);
+    cy.get("#search_patient_name")
+      .should("be.visible")
+      .should("be.enabled")
+      .type(patientName);
+    cy.get("#search-results-loading").should("not.exist");
+    cy.get("#search-results").should("exist");
   }

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

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

👋 Hi, @gurramkarthiknetha,
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.

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

Successfully merging this pull request may close these issues.

fix the responsive ness
3 participants