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

hrms edit and deactivate bug fixes #1655

Merged
merged 2 commits into from
Oct 24, 2024
Merged

hrms edit and deactivate bug fixes #1655

merged 2 commits into from
Oct 24, 2024

Conversation

mithunhegde-egov
Copy link

@mithunhegde-egov mithunhegde-egov commented Oct 24, 2024

Choose the appropriate template for your PR:

hrms Bug fixes

  • edit employee role and boundary data was not showing
  • search employee roles was not appearing

Summary by CodeRabbit

  • New Features

    • Enhanced employee role display logic based on multi-root tenant configuration.
    • Improved error handling during employee creation, ensuring all mandatory fields are validated before submission.
  • Bug Fixes

    • Updated validation checks for mobile numbers and other form fields to ensure data integrity.
  • Chores

    • Added console logs for debugging employee and role data.

@mithunhegde-egov mithunhegde-egov requested a review from a team as a code owner October 24, 2024 06:32
Copy link
Contributor

coderabbitai bot commented Oct 24, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request introduce a new constant isMultiRootTenant, derived from Digit.Utils.getMultiRootTenant(), affecting employee role handling and jurisdiction boundaries across multiple components. The onSubmit function in CreateEmployee and EditEmployee is updated to conditionally assign tenantId based on this constant. The EmployeeDetails component's role display logic is also modified to reflect this multi-root tenant configuration. Additionally, error handling and validation mechanisms are enhanced in the CreateEmployee component, ensuring proper checks before employee creation.

Changes

File Change Summary
.../EditEmployee/EditForm.js Introduced isMultiRootTenant constant; modified logic for defaultValues and onSubmit function.
.../EmployeeDetails.js Added isMultiRootTenant constant; updated role display logic based on tenant condition.
.../createEmployee.js Enhanced error handling in onSubmit; updated jurisdiction handling and validation logic.

Possibly related PRs

Suggested reviewers

  • nabeelmd-eGov
  • jagankumar-egov

🐇 In the fields where the rabbits play,
New constants hop in, brightening the day.
With roles and boundaries, clear as can be,
Multi-root tenants, oh what a spree!
Error checks added, all snug and tight,
Creating new employees feels just right! 🌼


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@@ -62,6 +63,9 @@ const Details = () => {
return <Loader />;
}

console.log(":data of the employee", data);
console.log("role data is", data?.Employees?.[0]?.user.roles.map((ele) => t(`ACCESSCONTROL_ROLES_ROLES_` + ele?.code)));
Copy link
Collaborator

Choose a reason for hiding this comment

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

Remove them

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)
micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/createEmployee.js (2)

Line range hint 183-194: Consider refactoring role mapping for better maintainability.

The nested array mapping could be simplified using array methods.

Consider this more maintainable approach:

-    let roles = data?.Jurisdictions?.map((ele) => {
-      return ele.roles?.map((item) => {
-        if(isMultiRootTenant){
-          item["tenantId"] = tenantId;
-        }
-        else{
-          item["tenantId"] = ele.boundary;
-        }
-        return item;
-      });
-    });
-    const mappedroles = [].concat.apply([], roles);
+    const mappedroles = data?.Jurisdictions?.flatMap(ele => 
+      ele.roles?.map(item => ({
+        ...item,
+        tenantId: isMultiRootTenant ? tenantId : ele.boundary
+      }))
+    ) || [];

Line range hint 235-251: Enhance mutation error handling.

The current error handling only displays the first error. Consider handling multiple errors and providing more detailed feedback.

Consider this enhancement:

   mutationCreate.mutate(
     {
       Employees: Employees,
     },
     {
       onError: (error, variables) => {
+        const errors = error?.response?.data?.Errors;
+        const errorMessage = errors?.length > 1 
+          ? `Multiple errors: ${errors.map(e => e.message).join(', ')}` 
+          : errors?.[0]?.message || 'HRMS_CREATE_ERROR';
         setShowToast({
           key: "error",
-          label: error?.response?.data?.Errors?.[0]?.code ? error?.response?.data?.Errors?.[0]?.code : "HRMS_CREATE_ERROR",
+          label: errorMessage,
         });
       },
       onSuccess: async (data) => {
         navigateToAcknowledgement({ id: data?.Employees?.[0]?.code, message: "HRMS_CREATE_EMPLOYEE_RESPONSE_MESSAGE" });
       },
     }
   );
micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/EmployeeDetails.js (1)

Line range hint 1-238: Consider splitting the component for better maintainability.

The Details component is handling multiple responsibilities:

  • Personal details display
  • Jurisdiction details
  • Assignment details
  • Action management
  • Modal handling

Consider breaking this into smaller, focused components:

  • EmployeePersonalDetails
  • EmployeeJurisdictions
  • EmployeeAssignments
  • EmployeeActions

This would improve:

  • Code maintainability
  • Testing
  • Reusability
  • Performance (through selective re-rendering)

Would you like assistance in restructuring this component?

🧰 Tools
🪛 Biome

[error] 67-67: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 68b5b2e and b9d64fb.

📒 Files selected for processing (3)
  • micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/EditEmployee/EditForm.js (3 hunks)
  • micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/EmployeeDetails.js (3 hunks)
  • micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/createEmployee.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/EditEmployee/EditForm.js (1)

Pattern **/*.js: check

micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/EmployeeDetails.js (1)

Pattern **/*.js: check

micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/createEmployee.js (1)

Pattern **/*.js: check

🪛 Biome
micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/EmployeeDetails.js

[error] 67-67: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


[error] 177-177: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


[error] 177-177: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

🔇 Additional comments (5)
micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/EditEmployee/EditForm.js (3)

85-87: Verify role visibility changes.

The conditional role filtering based on isMultiRootTenant significantly changes which roles are visible to users. Please ensure:

  1. This change aligns with the intended access control requirements
  2. No unintended role visibility issues are introduced

Let's check for potential role-related issues:

#!/bin/bash
# Search for role filtering patterns in other components
rg "roles\.filter.*tenantId" --type js

194-199: ⚠️ Potential issue

Security: Verify tenant role assignment logic.

The conditional tenantId assignment for roles is a critical security change. Please:

  1. Add unit tests to verify correct role-tenant mapping
  2. Document the security implications of this change

Let's check for similar role-tenant assignments:

#!/bin/bash
# Search for similar role-tenant assignments
rg "item\[.?tenantId.?\].*=.*tenant" --type js

Fix the inconsistent indentation:

-        if(isMultiRootTenant){
-          item["tenantId"] = tenantId;
-        }
-        else{
-          item["tenantId"] = ele.boundary;
-        }
+        if (isMultiRootTenant) {
+          item["tenantId"] = tenantId;
+        } else {
+          item["tenantId"] = ele.boundary;
+        }

17-17: Document the purpose and impact of isMultiRootTenant.

This new configuration affects critical tenant-specific behavior. Please add:

  1. JSDoc comments explaining the purpose and impact of this flag
  2. Error handling in case getMultiRootTenant() fails

Let's check if this utility is properly defined:

micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/createEmployee.js (2)

Line range hint 157-182: LGTM: Comprehensive validation checks added.

The enhanced error handling includes critical validations for:

  • Mandatory fields
  • Current assignment presence
  • Base tenant requirement
  • Duplicate jurisdiction prevention

These checks will help prevent invalid data submission and improve user feedback.


Line range hint 15-15: Verify multi-tenant configuration initialization.

The new isMultiRootTenant constant is critical for role management. Ensure that Digit.Utils.getMultiRootTenant() is properly initialized during application bootstrap.

✅ Verification successful

Based on the search results, I can now provide a comprehensive verification of the multi-tenant configuration initialization. Let me analyze the findings:

  1. The getMultiRootTenant() function is defined in micro-ui/web/micro-ui-internals/packages/libraries/src/utils/index.js and it reads the configuration from window globals:
const getMultiRootTenant = () => {
  return window?.globalConfigs?.getConfig("MULTI_ROOT_TENANT") || false;
};
  1. The initialization of isMultiRootTenant in createEmployee.js is properly using this utility function:
const isMultiRootTenant = Digit.Utils.getMultiRootTenant();
  1. The configuration is consistently used across multiple modules (HRMS, PGR, Core) and affects various functionalities like:
  • Tenant ID handling
  • Role management
  • URL transformations
  • UI component behavior

Let me verify the bootstrap configuration by checking the application initialization:


Let me try a broader search to find the configuration initialization:


Let me check the sample global config and core initialization:


Based on the comprehensive analysis of the codebase, I can now provide the final verification response:

Multi-tenant configuration is properly initialized and safe to use

The isMultiRootTenant constant in createEmployee.js is correctly implemented through Digit.Utils.getMultiRootTenant(). This utility function:

  1. Is properly defined in the libraries package
  2. Safely reads from the global configuration with a fallback
  3. Is consistently used across the application
  4. Gets initialized during application bootstrap through the global config system

The implementation is safe because:

  • The global config is initialized before the application renders
  • It has a proper fallback value (false) if not configured
  • The configuration is immutable (defined in a closure)
  • The usage pattern is consistent across all modules (HRMS, PGR, Core)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for getMultiRootTenant initialization and usage
rg -A 3 "getMultiRootTenant"

Length of output: 36240


Script:

#!/bin/bash
# Search for MULTI_ROOT_TENANT configuration initialization
rg -A 3 "MULTI_ROOT_TENANT.*config"

Length of output: 37


Script:

#!/bin/bash
# Search for global config initialization patterns
rg -l "globalConfigs|window\.config|MULTI_ROOT_TENANT" --type js

# Also check any config files
fd -e config.js -e config.json

Length of output: 2607


Script:

#!/bin/bash
# Check sample global config
cat micro-ui/web/micro-ui-internals/sampleGlobalConfig.js

# Check core App initialization
cat micro-ui/web/core/App.js

Length of output: 3915

Comment on lines 66 to 68
console.log(":data of the employee", data);
console.log("role data is", data?.Employees?.[0]?.user.roles.map((ele) => t(`ACCESSCONTROL_ROLES_ROLES_` + ele?.code)));

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

Remove console.log statements.

Debug console logs should not be committed to production code. These statements expose sensitive employee data and role information which could be a security concern.

Apply this diff to remove the debug statements:

-  console.log(":data of the employee", data);
-  console.log("role data is", data?.Employees?.[0]?.user.roles.map((ele) => t(`ACCESSCONTROL_ROLES_ROLES_` + ele?.code)));
-
📝 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
console.log(":data of the employee", data);
console.log("role data is", data?.Employees?.[0]?.user.roles.map((ele) => t(`ACCESSCONTROL_ROLES_ROLES_` + ele?.code)));
🧰 Tools
🪛 Biome

[error] 67-67: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between b9d64fb and d405b79.

📒 Files selected for processing (1)
  • micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/EmployeeDetails.js (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/EmployeeDetails.js (1)

Pattern **/*.js: check

🪛 Biome
micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/EmployeeDetails.js

[error] 175-175: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


[error] 175-175: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

🔇 Additional comments (1)
micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/EmployeeDetails.js (1)

24-24: LGTM: Multi-root tenant configuration.

The addition of isMultiRootTenant constant properly integrates with the existing utility functions and supports the PR's objective of fixing employee role management issues.

Comment on lines +174 to +175
text={
isMultiRootTenant? data?.Employees?.[0]?.user.roles.map((ele) => t(`ACCESSCONTROL_ROLES_ROLES_` + ele?.code)):(data?.Employees?.[0]?.user.roles.filter((ele) => ele.tenantId == element?.boundary).map((ele) => t(`ACCESSCONTROL_ROLES_ROLES_` + ele?.code)))}
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

Improve role display logic for better maintainability and safety.

The current implementation has several areas for improvement:

  1. Uses string concatenation instead of template literals
  2. Uses loose equality comparison
  3. Lacks null safety checks
  4. Has complex nested logic

Consider this enhanced version of the previous refactoring suggestion:

  text={
-   isMultiRootTenant? data?.Employees?.[0]?.user.roles.map((ele) => t(`ACCESSCONTROL_ROLES_ROLES_` + ele?.code)):(data?.Employees?.[0]?.user.roles.filter((ele) => ele.tenantId == element?.boundary).map((ele) => t(`ACCESSCONTROL_ROLES_ROLES_` + ele?.code)))}
+   (() => {
+     const roles = data?.Employees?.[0]?.user?.roles;
+     if (!roles?.length) return 'NA';
+     
+     const filteredRoles = isMultiRootTenant 
+       ? roles 
+       : roles.filter((role) => role?.tenantId === element?.boundary);
+     
+     return filteredRoles.map((role) => 
+       t(`ACCESSCONTROL_ROLES_ROLES_${role?.code || ''}`)
+     );
+   })()
+ }

This refactoring:

  1. Uses template literals (fixes static analysis warning)
  2. Adds comprehensive null safety checks
  3. Uses strict equality comparison
  4. Handles empty roles gracefully
  5. Improves readability by breaking down the logic
  6. Uses meaningful variable names
📝 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
text={
isMultiRootTenant? data?.Employees?.[0]?.user.roles.map((ele) => t(`ACCESSCONTROL_ROLES_ROLES_` + ele?.code)):(data?.Employees?.[0]?.user.roles.filter((ele) => ele.tenantId == element?.boundary).map((ele) => t(`ACCESSCONTROL_ROLES_ROLES_` + ele?.code)))}
text={
(() => {
const roles = data?.Employees?.[0]?.user?.roles;
if (!roles?.length) return 'NA';
const filteredRoles = isMultiRootTenant
? roles
: roles.filter((role) => role?.tenantId === element?.boundary);
return filteredRoles.map((role) =>
t(`ACCESSCONTROL_ROLES_ROLES_${role?.code || ''}`)
);
})()
}
🧰 Tools
🪛 Biome

[error] 175-175: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


[error] 175-175: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

@jagankumar-egov jagankumar-egov merged commit f228527 into develop Oct 24, 2024
3 of 4 checks passed
@jagankumar-egov jagankumar-egov deleted the hrms-edit-bug branch October 24, 2024 06:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants