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

User Profile Replacement/Removal #9382

Merged

Conversation

Jacobjeevan
Copy link
Contributor

@Jacobjeevan Jacobjeevan commented Dec 11, 2024

Proposed Changes

image

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

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

Summary by CodeRabbit

  • New Features

    • Introduced a new software update component for managing user software updates.
    • Added functionality for managing user information edits with improved error handling and notifications.
    • Enhanced user management interactions with a focus on new user creation.
  • Bug Fixes

    • Adjusted verification processes in patient discharge tests to focus on essential elements.
    • Removed outdated user profile management tests and streamlined user management interactions.
  • Chores

    • Removed unused components and imports related to user profile management to simplify the codebase.
    • Updated routing configuration to streamline user profile access.

Copy link
Contributor

coderabbitai bot commented Dec 11, 2024

Warning

Rate limit exceeded

@nihal467 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 20 minutes and 11 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 40b95a9 and d230d6a.

📒 Files selected for processing (1)
  • cypress/e2e/patient_spec/PatientConsultationDischarge.cy.ts (1 hunks)

Walkthrough

This pull request introduces a comprehensive restructuring of user management components and test suites. The changes focus on consolidating user profile functionality into the UserHome component, removing the standalone UserProfile component, and updating related routing and test configurations. The modifications streamline user management by eliminating redundant profile-related code and introducing a more integrated approach to user details and interactions.

Changes

File Change Summary
cypress/e2e/users_spec/UsersCreation.cy.ts Removed user profile update tests, updated import paths and test interactions
cypress/e2e/users_spec/UsersManage.cy.ts Enhanced error handling and user information edit test cases
cypress/e2e/users_spec/UsersProfile.cy.ts Completely removed test suite for user profile management
cypress/pageobject/Users/ManageUserPage.ts Refactored with new helper methods for user information editing
cypress/pageobject/Users/UserProfilePage.ts Completely removed page object class
src/Routers/routes/UserRoutes.tsx Modified routing to use tab-based approach for user profile
src/components/Users/ManageUsers.tsx Removed user facilities management logic
src/components/Users/UserHome.tsx Updated URL prefix and breadcrumb logic
src/components/Users/UserProfile.tsx Removed entire component
src/components/Users/UserSoftwareUpdate.tsx New component for managing software updates
src/components/Users/UserSummary.tsx Added software update component to user summary

Assessment against linked issues

Objective Addressed Explanation
Redirect Profile Page to User Details [#9364]
Remove Profile Component [#9364]

Possibly related PRs

  • Rewriting UsersCreation.cy.ts according to POM approach #8930: The changes in the main PR involve modifications to the UsersCreation.cy.ts test file, which are related to the refactoring of the same file in this retrieved PR, enhancing the structure and readability of user creation tests.
  • Users Manage Test Fix #9368: The main PR's updates to the user management tests, particularly regarding the verification of working hours, align with the modifications in this retrieved PR that enhance the user management test suite.
  • Fixed the user management page cypress issue #9384: The changes in the main PR to improve the user management tests, including the addition of new test cases for working hours, are related to the modifications in this retrieved PR that also focus on enhancing user management functionalities.
  • User creation form bug fix #9404: The main PR addresses a bug fix in the user creation form, which is relevant to the changes in this retrieved PR that also focus on fixing issues in the user creation process.

Suggested labels

needs review, P1

Suggested reviewers

  • rithviknishad

Poem

🐰 A Rabbit's Ode to User Management Transformation
Profiles merged, components refined,
Old routes retired, new paths designed,
Tabs dance where pages once did stand,
A cleaner system, built by my hand!
User details now sing with glee! 🎉


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. (Beta)
  • @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 Dec 11, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit d230d6a
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/676915efff0f3c0008671201
😎 Deploy Preview https://deploy-preview-9382--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.

- Removed logic to test profile in user creation (already done elsewhere)
- Removed ununsed logic in UserProfilePage
	- Makes uses of logic in ManageUsers instead since it's the same page
- Removed UserFacilities (logic related to sidebar for managing facilities/no longer used)
@Jacobjeevan Jacobjeevan marked this pull request as ready for review December 11, 2024 13:55
@Jacobjeevan Jacobjeevan requested a review from a team as a code owner December 11, 2024 13:55
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: 5

🧹 Outside diff range and nitpick comments (8)
cypress/e2e/users_spec/UsersProfile.cy.ts (4)

Line range hint 33-33: Update hardcoded URL in beforeEach

The cy.awaitUrl("/user/profile") still references the old profile route which has been removed.

-    cy.awaitUrl("/user/profile");
+    cy.awaitUrl("/user/details");

37-44: Extract test data to constants or fixtures

Consider extracting test data like "Devo", "Doctoro", and date formats to constants or fixtures for better maintainability.

const TEST_DATA = {
  firstName: "Devo",
  lastName: "Doctoro",
  dateFormat: "M/D/YYYY"
};

55-91: Improve test organization and readability

This test case handles multiple concerns (qualifications, working hours, video link). Consider:

  1. Breaking it into smaller, focused test cases
  2. Using test data builders or fixtures
  3. Extracting repeated patterns into custom commands

Example refactor:

describe('Professional Information', () => {
  it('should update qualification details', () => {
    // qualification specific test
  });
  
  it('should update working hours', () => {
    // working hours specific test
  });
  
  it('should update video connect link', () => {
    // video link specific test
  });
});

70-71: Consider moving date formatting logic to a helper

The date manipulation logic should be extracted to a helper function for reusability and easier testing.

// utils/dateHelpers.ts
export const calculateExperienceDate = (yearsOfExperience: string): string => {
  const date = dayjs().subtract(parseInt(yearsOfExperience), "year");
  return date.format("YYYY-MM-DD");
};
src/components/Users/UserSoftwareUpdate.tsx (2)

12-17: Add TypeScript types for better type safety

Consider adding TypeScript interface for the update status state.

+interface UpdateStatus {
+  isChecking: boolean;
+  isUpdateAvailable: boolean;
+}

 export default function UserSoftwareUpdate() {
-  const [updateStatus, setUpdateStatus] = useState({
+  const [updateStatus, setUpdateStatus] = useState<UpdateStatus>({
     isChecking: false,
     isUpdateAvailable: false,
   });

38-71: Enhance accessibility for update status buttons

The buttons need ARIA labels and roles for better accessibility.

-        <Button disabled>
+        <Button 
+          disabled
+          aria-label={t("checking_for_update")}
+          role="status"
+        >
           <div className="flex items-center gap-4">
             <CareIcon icon="l-sync" className="text-2xl animate-spin" />
             {t("checking_for_update")}
           </div>
         </Button>

-        <Button disabled>
+        <Button 
+          disabled
+          aria-label={t("update_available")}
+          role="alert"
+        >
           <div className="flex items-center gap-4">
             <CareIcon
               icon="l-exclamation"
               className="text-2xl text-warning"
             />
             {t("update_available")}
           </div>
         </Button>

-        <Button variant="primary" onClick={checkUpdates}>
+        <Button 
+          variant="primary" 
+          onClick={checkUpdates}
+          aria-label={t("check_for_update")}
+        >
cypress/e2e/users_spec/UsersCreation.cy.ts (2)

Line range hint 89-127: Consider adding test coverage for new user details page integration.

While the user creation test is comprehensive, consider adding assertions to verify:

  1. Successful redirection to the new user details page after creation
  2. Proper tab selection in the new interface
 userCreationPage.clickSaveUserButton();
 cy.wait("@createUser").its("response.statusCode").should("eq", 201);
 cy.verifyNotification("User added successfully");
+// Verify redirection to user details page
+cy.url().should('include', '/user/details');
+// Verify active tab
+cy.get('[data-testid="user-details-tab"]').should('have.class', 'active');

Line range hint 129-134: Consider expanding mandatory field validation test.

The current test only verifies error messages. Consider adding positive validation cases to ensure the error messages clear correctly when valid data is entered.

 userCreationPage.clickSaveUserButton();
 cy.get(".error-text", { timeout: 10000 }).should("be.visible");
 cy.verifyErrorMessages(EXPECTED_ERROR_MESSAGES);
+// Add validation for error message clearance
+userCreationPage.typeUserName(username);
+cy.contains("Please enter the username").should("not.exist");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e89530d and 6f26109.

📒 Files selected for processing (11)
  • cypress/e2e/users_spec/UsersCreation.cy.ts (1 hunks)
  • cypress/e2e/users_spec/UsersManage.cy.ts (0 hunks)
  • cypress/e2e/users_spec/UsersProfile.cy.ts (2 hunks)
  • cypress/pageobject/Users/ManageUserPage.ts (3 hunks)
  • cypress/pageobject/Users/UserProfilePage.ts (1 hunks)
  • src/Routers/routes/UserRoutes.tsx (1 hunks)
  • src/components/Users/ManageUsers.tsx (0 hunks)
  • src/components/Users/UserHome.tsx (3 hunks)
  • src/components/Users/UserProfile.tsx (0 hunks)
  • src/components/Users/UserSoftwareUpdate.tsx (1 hunks)
  • src/components/Users/UserSummary.tsx (2 hunks)
💤 Files with no reviewable changes (3)
  • cypress/e2e/users_spec/UsersManage.cy.ts
  • src/components/Users/UserProfile.tsx
  • src/components/Users/ManageUsers.tsx
🔇 Additional comments (7)
src/components/Users/UserHome.tsx (1)

41-42: LGTM! Clean implementation of user-aware navigation.

The changes effectively handle URL construction and breadcrumb display based on whether the user is viewing their own profile or another user's profile.

Also applies to: 101-105, 132-132

cypress/pageobject/Users/ManageUserPage.ts (1)

153-162: LGTM! Well-structured test helper methods.

The new methods follow best practices:

  • Proper scrolling before interactions
  • Consistent verification approach
  • Clear separation of edit and verify operations

Also applies to: 184-197, 222-226

src/components/Users/UserSoftwareUpdate.tsx (1)

1-10: Verify UpdatableApp integration and implementation

The component relies on UpdatableApp and checkForUpdate from Common components. Let's verify their implementation to ensure proper integration.

✅ Verification successful

Let me gather more information about the UpdatableApp component since the previous command only showed the checkForUpdate function.


Let me try a different approach to find the UpdatableApp component implementation.


UpdatableApp integration looks properly implemented

The verification shows that both UpdatableApp and checkForUpdate are properly implemented in the Common components:

  • checkForUpdate is a well-structured async function that handles version checking and update detection
  • UpdatableApp is a React component that manages update state and integrates with the check functionality
  • The implementation includes proper error handling, version management via localStorage, and UI feedback
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check implementation of UpdatableApp and checkForUpdate
ast-grep --pattern 'export const checkForUpdate = $_' 
ast-grep --pattern 'export default function UpdatableApp($_) {
  $$$
}'

Length of output: 2300


Script:

#!/bin/bash
# Search for UpdatableApp component implementation and its usage
rg -A 10 "function UpdatableApp" src/components/Common/UpdatableApp.tsx

Length of output: 73


Script:

#!/bin/bash
# Search for UpdatableApp component using different patterns
rg -A 20 "export default.*UpdatableApp" src/components/Common/UpdatableApp.tsx
rg -A 20 "const UpdatableApp" src/components/Common/UpdatableApp.tsx

Length of output: 1230

src/components/Users/UserSummary.tsx (1)

211-216: Verify scope of software update feature

The addition of the software update feature appears to be outside the scope of the PR objectives, which focus on profile page redirection and removal. Please clarify if this is an intentional addition or should be moved to a separate PR.

cypress/e2e/users_spec/UsersCreation.cy.ts (3)

9-9: LGTM! Import changes align with profile removal.

The simplified imports reflect the removal of profile-related functionality while maintaining necessary utilities for user creation.


Line range hint 136-147: Verify facility page redirection with new user details page.

The facility page user redirection test should be updated to verify proper navigation to the new user details page interface.


Line range hint 11-57: Verify test data constants against new user details page.

The test data constants and error messages should be verified to ensure they match the new user details page implementation.

✅ Verification successful

Error messages in test suite match the actual form validation

Based on the search results, the error messages defined in the test suite (EXPECTED_ERROR_MESSAGES) match the actual form validation messages used in the codebase:

  • The user form validation messages are defined in src/components/Users/UserFormValidations.tsx and src/components/Users/UserAddEditForm.tsx
  • The error messages cover all required fields:
    • User type selection
    • Phone number validation
    • Username validation
    • Date format validation
    • Password requirements
    • First/Last name validation
    • Email validation
    • Gender selection
    • State/District/Local body selection

The test data constants accurately reflect the validation messages shown to users when form fields are invalid or missing.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for field validations in the new user details component
ast-grep --pattern 'const EXPECTED_ERROR_MESSAGES = [
  $$$
]'

# Search for form field definitions
rg -A 5 'interface.*FormValues|type.*FormValues'

Length of output: 1297


Script:

#!/bin/bash
# Search for form validation messages in component files
rg -A 1 "Please select the User Type|Please enter valid phone number|Please enter the username|Please enter date in DD/MM/YYYY format|Password is required|Confirm password is required|First Name is required|Last Name is required|Please enter a valid email address|Please select the Gender|Please select the state|Please select the district|Please select the local body" --type ts --type tsx

# Search for form field validation logic
ast-grep --pattern 'const validate = {
  $$$
}'

# Search for form field validation functions
ast-grep --pattern 'function validate$_($$$) {
  $$$
}'

Length of output: 528


Script:

#!/bin/bash
# Search for validation messages in all files, fixing the file type flag
rg -A 1 "Please select the User Type|Please enter valid phone number|Please enter the username|Please enter date in DD/MM/YYYY format|Password is required|Confirm password is required|First Name is required|Last Name is required|Please enter a valid email address|Please select the Gender|Please select the state|Please select the district|Please select the local body" --type typescript

# Search for form validation in component files
rg -A 3 "validation|errorMessage|error message" --type typescript src/

# Look for user creation form component
fd -e ts -e tsx "UserCreation" src/

Length of output: 568


Script:

#!/bin/bash
# First find all TypeScript files that might contain validation messages
fd -e ts -e tsx . | xargs rg -l "validation|error|message"

# Find user creation related components and their validation logic
fd -e ts -e tsx . | xargs rg -A 3 "createUser|UserCreation|addUser"

# Search for form field validation patterns in all TypeScript files
fd -e ts -e tsx . | xargs rg -A 2 "required|invalid|Please"

Length of output: 70818

src/Routers/routes/UserRoutes.tsx Show resolved Hide resolved
cypress/pageobject/Users/UserProfilePage.ts Outdated Show resolved Hide resolved
cypress/e2e/users_spec/UsersProfile.cy.ts Outdated Show resolved Hide resolved
src/components/Users/UserSoftwareUpdate.tsx Show resolved Hide resolved
Comment on lines +204 to +217
<>
<UserColumns
heading={t("language_selection")}
note={t("set_your_local_language")}
Child={LanguageSelector}
childProps={userColumnsData}
/>
<UserColumns
heading={t("software_update")}
note={t("check_for_available_update")}
Child={UserSoftwareUpdate}
childProps={userColumnsData}
/>
</>
Copy link
Contributor

@coderabbitai coderabbitai bot Dec 11, 2024

Choose a reason for hiding this comment

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

💡 Codebase verification

Translation keys missing in non-English locales

The software update section's translation keys need to be added to all non-English locale files:

  • software_update key missing in hi.json, kn.json, ml.json, mr.json, ta.json
  • check_for_available_update key missing in hi.json, kn.json, ml.json, mr.json, ta.json
🔗 Analysis chain

Verify translation keys for software update section

The new software update section uses translation keys that need to be verified in the i18n files.


Translation keys are properly defined in English locale but missing in others

The verification shows that both translation keys software_update and check_for_available_update are defined in the English locale file (en.json), but might be missing in other locale files. Let me verify other locales.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if translation keys exist in i18n files
rg -g '*.json' '"software_update":'
rg -g '*.json' '"check_for_available_update":'

Length of output: 232


Script:

#!/bin/bash
# List all locale files
fd -e json -p public/locale/

# Check content of all locale files for these keys
for locale in $(fd -e json -p public/locale/); do
  echo "=== $locale ==="
  jq '.software_update, .check_for_available_update' "$locale"
done

Length of output: 1443

Copy link
Member

Choose a reason for hiding this comment

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

Read the readme. Crowdin handles translations for languages other than English. We do not add them via PRs.

Copy link
Contributor

Choose a reason for hiding this comment

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

@rithviknishad Understood. We respect your decision to handle non-English translations outside of PRs using Crowdin.


✏️ Learnings added
Learnt from: rithviknishad
PR: ohcnetwork/care_fe#9382
File: src/components/Users/UserSummary.tsx:204-217
Timestamp: 2024-12-23T05:11:53.287Z
Learning: For non-English translations, the team uses Crowdin instead of handling them via PR. Specifically, translation keys like "software_update" and "check_for_available_update" should not be added via PR.

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.

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

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

@Jacobjeevan Jacobjeevan added needs testing needs review and removed merge conflict pull requests with merge conflict labels Dec 12, 2024
@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Dec 12, 2024
Copy link

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


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

@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Dec 12, 2024
@coderabbitai coderabbitai bot mentioned this pull request Dec 15, 2024
6 tasks
@nihal467
Copy link
Member

@Jacobjeevan check the cypress failure

@Jacobjeevan
Copy link
Contributor Author

@Jacobjeevan check the cypress failure

Done

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

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

Copy link
Member

@nihal467 nihal467 left a comment

Choose a reason for hiding this comment

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

  • Evaluate both UserProfile.cy.ts and UserManage.cy.ts test files, identify common tests, keep one file, and delete the other.
  • Remove any unused functions resulting from the above changes.
  • Replace all submit button interactions with the reusable function cy.clickSubmitButton.
  • Review the functionality of cy.typeIntoField() in our codebase to understand how a boolean parameter can be passed to clear the input field when required, eliminating the need for separate functions for clearing and inputting data.
  • When creating a combination action (e.g., editUserDetails()), first create individual functions for each action and call them using this.functionName() within the combination function.
  • Check the command.ts file and use reusable functions for all types of dropdowns and date selections.

@bodhish
Copy link
Member

bodhish commented Dec 20, 2024

Why are we holding on to this>

@nihal467 nihal467 self-assigned this Dec 23, 2024
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 comments (1)
cypress/e2e/users_spec/UsersManage.cy.ts (1)

Line range hint 347-394: Break down facility linking test into smaller, focused tests

The current test is too complex and tests multiple scenarios. This makes it harder to maintain and debug failures.

Consider breaking it down into these focused test cases:

describe("facility linking", () => {
  it("should link facility to user without home facility", () => {
    // Test only the basic facility linking
  });

  it("should set facility as home facility", () => {
    // Test only the home facility setting
  });

  it("should unlink facility from user", () => {
    // Test only the facility unlinking
  });

  it("should reflect changes in doctor connect", () => {
    // Test only the doctor connect visibility
  });
});
🧹 Nitpick comments (5)
cypress/support/index.ts (1)

55-55: Add a usage note for “formatDate”

Consider adding a JSDoc comment or usage note that clarifies the expected format of “rawDate” (e.g., “DDMMYYYY”) so that future developers can avoid confusion when invoking this method.

cypress/pageobject/Users/ManageUserPage.ts (3)

122-134: Add documentation for the skipVerification parameter

The editPhoneNumber method includes a skipVerification parameter, but its purpose and impact aren't documented. Consider adding JSDoc comments to explain when and why this parameter should be used.

+  /**
+   * Edits the phone number field
+   * @param phoneNumber - The phone number to enter
+   * @param clearBeforeTyping - Whether to clear the field before typing
+   * @param skipVerification - Whether to skip phone number format verification
+   */
   editPhoneNumber(
     phoneNumber: string,
     clearBeforeTyping = true,
     skipVerification = true,
   ) {

154-181: Consider adding TypeScript interfaces for professional info

The professional info editing methods are well-structured. Consider adding TypeScript interfaces to improve type safety and documentation.

interface ProfessionalInfo {
  qualification: string;
  doctorYoE?: string;
  medicalCouncilRegistration?: string;
}

324-334: Consider combining related verification methods

The verification methods for years of experience and council registration could be combined to reduce code duplication and improve maintainability.

-  verifyYoeAndCouncilRegistrationDoesntExist() {
-    cy.get("#view-years_of_experience").should("not.exist");
-    cy.get("#view-doctor_medical_council_registration").should("not.exist");
-  }
-
-  verifyYoeAndCouncilRegistrationExist() {
-    cy.get("#view-years_of_experience").should("be.visible");
-    cy.get("#view-doctor_medical_council_registration").should("be.visible");
-  }
+  verifyDoctorSpecificFields(shouldExist: boolean) {
+    const assertion = shouldExist ? "be.visible" : "not.exist";
+    cy.get("#view-years_of_experience").should(assertion);
+    cy.get("#view-doctor_medical_council_registration").should(assertion);
+  }
cypress/e2e/users_spec/UsersManage.cy.ts (1)

54-85: Consider moving test data to a separate constants file

The test data setup is well-structured, but moving it to a separate constants file would improve reusability and maintenance.

// testData/userManagement.ts
export const TEST_DATA = {
  basicInfo: {
    errorMessages: ["First Name is required", "Last Name is required"],
    modifiedValues: {
      firstName: "Devo",
      lastName: "Districto",
      rawDOB: "11081999",
      gender: "Female"
    }
  }
};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 748919a and d9aa02d.

📒 Files selected for processing (4)
  • cypress/e2e/users_spec/UsersManage.cy.ts (10 hunks)
  • cypress/pageobject/Users/ManageUserPage.ts (5 hunks)
  • cypress/support/commands.ts (1 hunks)
  • cypress/support/index.ts (1 hunks)
🧰 Additional context used
📓 Learnings (2)
cypress/e2e/users_spec/UsersManage.cy.ts (1)
Learnt from: Jacobjeevan
PR: ohcnetwork/care_fe#9080
File: cypress/pageobject/Users/ManageUserPage.ts:181-188
Timestamp: 2024-11-14T10:28:32.680Z
Learning: In the Cypress tests for user management (`cypress/pageobject/Users/ManageUserPage.ts`), the method `verifyDoctorQualification()` is intended to verify qualifications specifically for the Doctor role.
cypress/pageobject/Users/ManageUserPage.ts (1)
Learnt from: Jacobjeevan
PR: ohcnetwork/care_fe#9080
File: cypress/pageobject/Users/ManageUserPage.ts:181-188
Timestamp: 2024-11-14T10:28:32.680Z
Learning: In the Cypress tests for user management (`cypress/pageobject/Users/ManageUserPage.ts`), the method `verifyDoctorQualification()` is intended to verify qualifications specifically for the Doctor role.
🔇 Additional comments (1)
cypress/pageobject/Users/ManageUserPage.ts (1)

68-85: Well-structured refactoring of basic info editing methods!

The code demonstrates good separation of concerns and follows the page object pattern effectively. The helper methods are well-named and focused on single responsibilities.

cypress/support/commands.ts Outdated Show resolved Hide resolved
cypress/e2e/users_spec/UsersManage.cy.ts 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: 2

🔭 Outside diff range comments (3)
cypress/e2e/users_spec/UsersManage.cy.ts (3)

Line range hint 112-180: Reduce duplication in professional info tests

The nurse and doctor professional info tests share similar validation logic. Consider extracting common validation steps into shared functions.

Extract shared logic:

const validateProfessionalInfo = (role: 'nurse' | 'doctor', config: {
  qualification: string,
  yoe?: string,
  registrationNumber?: string
}) => {
  manageUserPage.clickProfessionalInfoViewButton();
  if (role === 'doctor') {
    manageUserPage.verifyYoeAndCouncilRegistrationExist();
  } else {
    manageUserPage.verifyYoeAndCouncilRegistrationDoesntExist();
  }
  // ... rest of the validation logic
};

Line range hint 230-248: Add retry logic for password change verification

The password change verification could be flaky due to timing issues with the notification system.

Add retry logic:

- cy.verifyNotification("Password updated successfully");
+ cy.verifyNotification("Password updated successfully", {
+   timeout: 10000,
+   retryInterval: 500
+ });

Line range hint 262-267: Add API verification for user deletion

The deletion test should verify through both UI and API to ensure complete removal.

Add API verification:

cy.request({
  method: 'GET',
  url: `/api/v1/users/${doctorToDelete}`,
  failOnStatusCode: false
}).then((response) => {
  expect(response.status).to.equal(404);
});
♻️ Duplicate comments (1)
cypress/e2e/users_spec/UsersManage.cy.ts (1)

315-344: 🛠️ Refactor suggestion

Split working hours test as previously suggested

As mentioned in the previous review, this test combines multiple concerns and should be split into focused test cases.

🧹 Nitpick comments (2)
cypress/e2e/users_spec/UsersManage.cy.ts (2)

4-4: Consider moving test data to fixtures

The test file contains a significant amount of hardcoded test data. Consider moving this data to a fixture file to improve maintainability and reusability.

Create a new fixture file cypress/fixtures/users.json:

{
  "users": {
    "nurse": {
      "username": "dummynurse1"
    },
    "doctors": {
      "dev": {
        "username": "devdoctor",
        "firstName": "Dev",
        "lastName": "Doctor"
      },
      "dummy": {
        "username": "dummydoctor4"
      }
    }
  }
}

Then update the test file:

+ let testData;
+ before(() => {
+   cy.fixture('users.json').then((data) => {
+     testData = data;
+   });
+ });

Also applies to: 12-31


54-87: Enhance test coverage with data-driven testing

The basic info edit test could be more comprehensive by using data-driven testing to cover various scenarios.

Consider using test cases array:

const testCases = [
  {
    scenario: 'valid inputs',
    firstName: 'Devo',
    lastName: 'Districto',
    dob: '11081999',
    gender: 'Female',
    expectError: false
  },
  {
    scenario: 'invalid date',
    firstName: 'Devo',
    lastName: 'Districto',
    dob: '99999999',
    gender: 'Female',
    expectError: true
  }
];

testCases.forEach(({ scenario, firstName, lastName, dob, gender, expectError }) => {
  it(`handles basic info edit - ${scenario}`, () => {
    // Test implementation using parameters
  });
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d9aa02d and 3778e23.

📒 Files selected for processing (1)
  • cypress/e2e/users_spec/UsersManage.cy.ts (10 hunks)
🧰 Additional context used
📓 Learnings (1)
cypress/e2e/users_spec/UsersManage.cy.ts (1)
Learnt from: Jacobjeevan
PR: ohcnetwork/care_fe#9080
File: cypress/pageobject/Users/ManageUserPage.ts:181-188
Timestamp: 2024-11-14T10:28:32.680Z
Learning: In the Cypress tests for user management (`cypress/pageobject/Users/ManageUserPage.ts`), the method `verifyDoctorQualification()` is intended to verify qualifications specifically for the Doctor role.
🔇 Additional comments (1)
cypress/e2e/users_spec/UsersManage.cy.ts (1)

Line range hint 269-314: Split skills management tests into focused test cases

Similar to the previous feedback about working hours tests, these tests should be split into focused test cases.

Split into:

  1. Skill linking verification
  2. Skill unlinking verification
  3. Doctor connect reflection verification

cypress/e2e/users_spec/UsersManage.cy.ts Show resolved Hide resolved
cypress/e2e/users_spec/UsersManage.cy.ts Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
cypress/support/commands.ts (3)

232-232: Consider making the timeout value configurable.
By assigning a fixed timeout value of 10 seconds, tests may take longer than necessary if the application responds promptly. Consider externalizing this timeout to enable quicker feedback loops and more flexibility in different test environments.


233-235: Validate element readiness before verifying visibility.
While using “.should('be.visible')” is a good practice, occasionally elements are visible but not fully interactive. If any flakiness arises, you might consider combining “.should('be.visible')” with additional checks (e.g., “.should('not.be.disabled')”).


236-238: Verify each assertion in isolation.
Currently, each text in “texts” is checked within the same element container sequentially. For debugging clarity, consider splitting them into distinct test steps or logging which text is being verified. This can help if one assertion fails while verifying multiple texts.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3778e23 and 986e55d.

📒 Files selected for processing (1)
  • cypress/support/commands.ts (1 hunks)

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

🧹 Nitpick comments (1)
cypress/e2e/patient_spec/PatientConsultationDischarge.cy.ts (1)

123-123: Expand verification to cover all relevant fields.

The test name implies verification of all relevant fields ("Discharge a recovered patient with all relevant fields"), yet only the prescribed medicine is being checked. Consider reintroducing verification for the discharge reason (e.g., "Recovered") and the discharge advice to ensure comprehensive coverage.

Below is a proposed diff to include these fields:

-    cy.verifyContentPresence("#discharge-information", [patientMedicine]);
+    cy.verifyContentPresence("#discharge-information", [
+      patientDischargeReason1,
+      patientDischargeAdvice,
+      patientMedicine
+    ]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 986e55d and 40b95a9.

📒 Files selected for processing (1)
  • cypress/e2e/patient_spec/PatientConsultationDischarge.cy.ts (1 hunks)
🧰 Additional context used
📓 Learnings (1)
cypress/e2e/patient_spec/PatientConsultationDischarge.cy.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.

@nihal467
Copy link
Member

LGTM

@nihal467 nihal467 added tested reviewed reviewed by a core member and removed needs testing labels Dec 23, 2024
@rithviknishad rithviknishad merged commit 0291d9c into ohcnetwork:develop Dec 23, 2024
19 of 20 checks passed
Copy link

@nihal467 @Jacobjeevan Your efforts have helped advance digital healthcare and TeleICU systems. 🚀 Thank you for taking the time out to make CARE better. We hope you continue to innovate and contribute; your impact is immense! 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
reviewed reviewed by a core member tested
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Redirect Profile Page to User Details, Remove Profile Component
4 participants