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

Merging Develop into Master #970

Merged
merged 20 commits into from
Oct 8, 2024
Merged

Merging Develop into Master #970

merged 20 commits into from
Oct 8, 2024

Conversation

mukund-egov
Copy link
Collaborator

@mukund-egov mukund-egov commented Oct 8, 2024

Summary by CodeRabbit

  • New Features

    • Introduced multiple new build configurations for various services and applications.
    • Enhanced the MonthlyLedgerReport functionality, allowing users to download the report.
    • Improved user search form with dynamic role mapping and enhanced validation.
  • Bug Fixes

    • Addressed issues with division uniqueness checks in forms for employee creation and editing.
  • Chores

    • Removed obsolete CSS package references and scripts from project configurations.
  • Documentation

    • Updated comments and formatting for better clarity and maintainability across various components.

Copy link

coderabbitai bot commented Oct 8, 2024

Walkthrough

The pull request introduces significant changes to multiple files, primarily focusing on the addition and modification of build configurations in build-config.yml, updates to UI components for improved functionality and performance, and restructuring of project dependencies in package.json files. New build configurations for various services have been added, while the egov-bff configuration has been removed. UI components have been enhanced for better user interaction, and certain CSS dependencies have been eliminated from the project structure.

Changes

File Path Change Summary
build/build-config.yml Added multiple new build configurations for various services (e.g., ws-services, billing-service, egov-user, etc.) and removed the configuration for egov-bff.
frontend/mgramseva/lib/screeens/reports/monthly_ledger_report.dart Replaced an invisible Opacity widget wrapping TextButton.icon with a direct implementation to make the button visible and functional for downloading the monthly ledger report.
frontend/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js Added internationalization support, updated the businessServiceMap, expanded the updatePayload method for a new case, and made various formatting improvements for readability across several methods.
frontend/micro-ui/web/micro-ui-internals/package.json Removed the packages/css entry from the workspaces section and deleted dev:css and build:css scripts from the scripts section, indicating a shift away from managing the CSS package.
frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/components/SearchUserForm.js Wrapped the SearchUserForm component in React.memo for performance optimization, expanded hierarchy state management, improved form handling with react-hook-form, and enhanced validation logic.
frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/components/pageComponents/jurisdiction.js Refactored logic for managing unique divisions, improved data handling with a Set, and adjusted rendering logic for the Jurisdiction component.
frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/EditEmployee/EditForm.js Introduced a new function hasUniqueDivisions to check for unique division codes and updated validation logic in the onFormValueChange function.
frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/createEmployee.js Added the hasUniqueDivisions function for division uniqueness checks and refactored the onFormValueChange method for clarity in validation logic.
frontend/micro-ui/web/package.json Removed the micro-ui-internals/packages/css workspace and the dependency on @egovernments/digit-ui-css version 1.5.54.
frontend/micro-ui/web/src/App.js Removed the import statement for the CSS file from @egovernments/digit-ui-css, maintaining core functionality while eliminating the stylesheet.

Possibly related PRs

Suggested reviewers

  • pradeepkumarcm-egov

Poem

In the burrow where code does bloom,
New builds arise, dispelling gloom.
With buttons bright and forms so neat,
The user’s path is now complete.
So hop along, let changes flow,
In this code garden, watch it grow! 🐇✨


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This change is to solve numeric code problem.

Copy link

@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: 8

🧹 Outside diff range and nitpick comments (9)
frontend/mgramseva/lib/screeens/reports/monthly_ledger_report.dart (1)

92-106: Approve changes with suggestions for improvement

The replacement of the Opacity widget with a visible TextButton.icon is a positive change that improves functionality and usability. The download button is now accessible to users, and the addition of the download icon enhances clarity.

However, consider the following suggestions for further improvement:

  1. Add a loading indicator while the download is in progress to provide visual feedback to the user.
  2. Consider adding a tooltip to the button to provide more context about the download functionality.
  3. Ensure that the new button doesn't negatively impact the layout on smaller screen sizes.

Here's a sample implementation incorporating these suggestions:

TextButton.icon(
  onPressed: () async {
    if (reportProvider.selectedBillPeriod == null) {
      Notifiers.getToastMessage(
          context,
          '${ApplicationLocalizations.of(context).translate(i18.common.SELECT_BILLING_CYCLE)}',
          'ERROR');
    } else {
      setState(() => _isDownloading = true);
      try {
        await reportProvider.getMonthlyLedgerReport(download: true);
      } finally {
        setState(() => _isDownloading = false);
      }
    }
  },
  icon: _isDownloading ? CircularProgressIndicator() : Icon(Icons.download_sharp),
  label: Text(ApplicationLocalizations.of(context).translate(i18.common.CORE_DOWNLOAD)),
  tooltip: ApplicationLocalizations.of(context).translate(i18.common.DOWNLOAD_TOOLTIP),
)

Note: You'll need to add a _isDownloading boolean state variable to the widget's state class.

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

162-176: Improved form validation logic

The changes to the onFormValueChange function enhance the validation process by incorporating the new hasUniqueDivisions check for state admins. The conditional logic is now more comprehensive and handles both state admin and non-state admin cases effectively.

To further improve readability, consider extracting the complex condition into a separate function. This would make the code more maintainable and easier to understand.

Here's a suggested refactor to improve readability:

const isFormValid = (formData, isStateAdmin) => {
  const baseConditions = 
    formData?.SelectEmployeeGender?.gender.code &&
    formData?.SelectEmployeeName?.employeeName &&
    formData?.SelectEmployeePhoneNumber?.mobileNumber &&
    formData?.Jurisdictions?.length;

  const stateAdminConditions = 
    hasUniqueDivisions(formData?.Jurisdictions) &&
    !formData?.Jurisdictions.some((juris) => juris?.division == undefined || juris?.divisionBoundary?.length === 0);

  const nonStateAdminConditions = 
    !formData?.Jurisdictions.some((juris) => juris?.roles?.length === 0) &&
    isValid &&
    checkfield &&
    phonecheck &&
    checkMailNameNum(formData) &&
    hasUniqueTenantIds(formData?.Jurisdictions);

  return baseConditions && (isStateAdmin ? stateAdminConditions : nonStateAdminConditions);
};

// In onFormValueChange:
if (isFormValid(formData, STATE_ADMIN)) {
  setSubmitValve(true);
} else {
  setSubmitValve(false);
}

This refactoring separates the complex condition into a more readable and maintainable function.

frontend/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js (5)

Line range hint 89-114: LGTM: New case added for "muster roll" business service

The addition of the "muster roll" case improves the function's completeness and consistency with other business services. The implementation follows the existing pattern, which is good for maintainability.

Consider extracting the common workflow object construction logic into a separate function to reduce code duplication across different business service cases. This would improve maintainability and reduce the risk of inconsistencies when adding new cases in the future.


136-145: LGTM: Additional fields added to works.purchase bill

The addition of new fields in additionalFieldsToSet and their inclusion in the bill object provides more context for the works.purchase business service. The use of object spreading is a clean way to merge these fields.

For improved clarity and maintainability, consider adding a comment explaining the purpose of these additional fields and why they're being added to the bill object. This will help future developers understand the rationale behind these additions.


175-181: LGTM: Extended getBusinessService function for new business types

The getBusinessService function has been updated to include conditions for "works.purchase", "works.wages", and "works.supervision". This extends the functionality consistently with the existing pattern. The improved formatting enhances readability.

As the number of business services grows, consider refactoring this function to use a lookup object or switch statement for better scalability and maintainability. This would make it easier to add new business services in the future without extending the if-else chain.


Line range hint 204-254: LGTM with a note: AttendanceInboxConfig improvements and extensions

The AttendanceInboxConfig object has been updated with improved formatting and extended functionality for handling organization IDs and attendance-related data. These changes enhance the code structure and readability.

There's a delete operation on line 254 that might impact performance:

delete data.state;

Consider using an undefined assignment instead:

data.state = undefined;

This change would avoid the potential performance impact of the delete operator.

🧰 Tools
🪛 Biome

[error] 254-254: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


Line range hint 440-592: LGTM: Extensive improvements to OpenPaymentSearch

The OpenPaymentSearch object has been significantly enhanced with:

  1. Improved handling of business services and tenant IDs.
  2. Extended additionalCustomizations function with new cases for various data types.
  3. Implementation of a customValidationCheck function for consumer code validation.

These changes improve the robustness and functionality of the open payment search feature.

In the additionalCustomizations function, consider using a switch statement instead of multiple if-else statements for the different keys. This would improve readability and maintainability, especially as more cases are added. For example:

switch (key) {
  case "OP_BILL_DATE":
    return Digit.DateUtils.ConvertEpochToDate(value);
  case "OP_BILL_TOTAL_AMT":
    return <span>{`₹ ${value}`}</span>;
  // ... other cases ...
  default:
    return <span>{t("ES_COMMON_NA")}</span>;
}

This structure would make it easier to add or modify cases in the future.

🧰 Tools
🪛 Biome

[error] 483-483: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 484-484: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 525-544: This code is unreachable

... because either this statement, ...

... this statement, ...

... this statement, ...

... this statement, ...

... this statement, ...

... this statement, ...

... this statement, ...

... this statement, ...

... or this statement will return from the function beforehand

(lint/correctness/noUnreachable)

frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/components/SearchUserForm.js (2)

158-169: Remove commented-out code within 'clearSearch' function

The clearSearch function contains commented-out code from lines 158 to 169. Removing unnecessary commented code improves the readability and maintainability of the codebase.

You can safely remove these lines:

-    // dispatch({
-    //   type: uiConfig?.type === "filter" ? "clearFilterForm" : "clearSearchForm",
-    //   state: { ...uiConfig?.defaultValues }
-    // })
-    // Here reset tableForm as well
-    // dispatch({
-    //   type: "tableForm",
-    //   state: { limit: 10, offset: 0 }
-    //   // Need to pass form with empty strings
-    // })

474-476: Handle potential '-1' result from 'findIndex' when slicing 'childLevels'

In lines 474-476, when calculating childLevels, if findIndex returns -1, adding 1 results in 0, causing slice(0) to include all elements. Ensure that this is the intended behavior or add a check to handle cases where the level is not found.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5f94c27 and a477f0a.

📒 Files selected for processing (10)
  • build/build-config.yml (0 hunks)
  • frontend/mgramseva/lib/screeens/reports/monthly_ledger_report.dart (1 hunks)
  • frontend/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js (20 hunks)
  • frontend/micro-ui/web/micro-ui-internals/package.json (0 hunks)
  • frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/components/SearchUserForm.js (10 hunks)
  • frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/components/pageComponents/jurisdiction.js (2 hunks)
  • frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/EditEmployee/EditForm.js (4 hunks)
  • frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/createEmployee.js (4 hunks)
  • frontend/micro-ui/web/package.json (0 hunks)
  • frontend/micro-ui/web/src/App.js (0 hunks)
💤 Files with no reviewable changes (4)
  • build/build-config.yml
  • frontend/micro-ui/web/micro-ui-internals/package.json
  • frontend/micro-ui/web/package.json
  • frontend/micro-ui/web/src/App.js
🧰 Additional context used
📓 Learnings (1)
frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/EditEmployee/EditForm.js (1)
Learnt from: Hari-egov
PR: egovernments/punjab-mgramseva#817
File: frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/EditEmployee/EditForm.js:141-143
Timestamp: 2024-06-19T05:23:48.125Z
Learning: Hari-egov prefers to keep the existing complex logic in `EditForm.js` as is, despite its complexity.
🪛 Biome
frontend/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js

[error] 220-220: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 254-254: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 525-544: This code is unreachable

... because either this statement, ...

... this statement, ...

... this statement, ...

... this statement, ...

... this statement, ...

... this statement, ...

... this statement, ...

... this statement, ...

... or this statement will return from the function beforehand

(lint/correctness/noUnreachable)

frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/components/SearchUserForm.js

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (5)
frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/createEmployee.js (2)

106-116: LGTM: New function to check for unique divisions

The hasUniqueDivisions function is well-implemented. It efficiently uses a Set to track unique division codes and correctly handles potential undefined values. This addition enhances the form validation process by ensuring division uniqueness.


Line range hint 1-385: Overall assessment: Improved form validation

The changes in this file enhance the employee creation process by introducing more robust validation, particularly for division uniqueness. The new hasUniqueDivisions function and the modifications to the onFormValueChange function are well-implemented and improve the overall functionality of the component.

The code maintains good practices and is generally well-structured. The suggested refactoring for the complex condition in onFormValueChange would further improve readability and maintainability.

frontend/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js (2)

3-3: LGTM: Import added and businessServiceMap updated

The addition of the useTranslation import suggests improved internationalization support, which is a good practice. The businessServiceMap update fixes a minor syntax issue.

Also applies to: 29-29


Line range hint 148-165: LGTM: Extended functionality for new business services

The enableModalSubmit and enableHrmsSearch functions have been updated to include conditions for "muster roll" and "works.purchase" business services. This extends the functionality consistently with the existing pattern. The improved formatting enhances readability.

frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/components/pageComponents/jurisdiction.js (1)

90-90: Verify the uniqueness logic in uniqueDivisions

The uniqueness check now compares item.id === obj.id && item.code === obj.code. Please verify that this condition correctly identifies unique divisions. If id and code are not sufficient to guarantee uniqueness, this might lead to duplicate entries in uniqueDivisions.

Run the following script to check for divisions that might have the same id and code:

Comment on lines +165 to +169
if (
formData?.SelectUserTypeAndDesignation[0] &&
formData?.SelectUserTypeAndDesignation[0]?.department != undefined &&
formData?.SelectUserTypeAndDesignation[0]?.designation != undefined
) {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use strict equality checks to avoid unexpected type coercion

In the conditional statements at lines 167 and 168, consider using !== undefined instead of != undefined to prevent unintended type coercion.

Apply this diff to update the condition:

 if (
   formData?.SelectUserTypeAndDesignation[0] &&
-  formData?.SelectUserTypeAndDesignation[0]?.department != undefined &&
-  formData?.SelectUserTypeAndDesignation[0]?.designation != undefined
+  formData?.SelectUserTypeAndDesignation[0]?.department !== undefined &&
+  formData?.SelectUserTypeAndDesignation[0]?.designation !== undefined
 ) {
   isValid = true;
 } else {
   isValid = false;
 }
📝 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
if (
formData?.SelectUserTypeAndDesignation[0] &&
formData?.SelectUserTypeAndDesignation[0]?.department != undefined &&
formData?.SelectUserTypeAndDesignation[0]?.designation != undefined
) {
if (
formData?.SelectUserTypeAndDesignation[0] &&
formData?.SelectUserTypeAndDesignation[0]?.department !== undefined &&
formData?.SelectUserTypeAndDesignation[0]?.designation !== undefined
) {

Comment on lines +137 to +147
function hasUniqueDivisions(items) {
const uniqueDivisions = new Set();
for (const item of items) {
const divisionCode = item?.division?.code;
if (divisionCode && uniqueDivisions.has(divisionCode)) {
return false;
}
uniqueDivisions.add(divisionCode);
}
return true;
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider refactoring to reduce code duplication between hasUniqueTenantIds and hasUniqueDivisions

The functions hasUniqueTenantIds and hasUniqueDivisions share similar logic. You could create a generic function that checks for uniqueness based on a provided key. This would enhance code reusability and maintainability.

Comment on lines +183 to +196
formData?.SelectEmployeeName?.employeeName &&
formData?.SelectEmployeePhoneNumber?.mobileNumber &&
STATE_ADMIN
? formData?.Jurisdictions?.length &&
!formData?.Jurisdictions.some((juris) => juris?.division == undefined || juris?.divisionBoundary?.length === 0) &&
hasUniqueDivisions(formData?.Jurisdictions)
: formData?.Jurisdictions?.length &&
formData?.Jurisdictions.length &&
!formData?.Jurisdictions.some((juris) => juris?.roles?.length === 0) &&
isValid &&
checkfield &&
phonecheck &&
checkMailNameNum(formData) &&
hasUniqueTenantIds(formData?.Jurisdictions)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix logical error due to operator precedence in the conditional expression

The if condition starting at line 183 uses the ternary operator ? : within a chain of logical AND && operators. Because the ternary operator has lower precedence than the logical AND operator, this can lead to incorrect evaluation of the condition.

Apply this diff to add parentheses and ensure the condition is evaluated as intended:

 if (
   formData?.SelectEmployeeGender?.gender.code &&
   formData?.SelectEmployeeName?.employeeName &&
   formData?.SelectEmployeePhoneNumber?.mobileNumber &&
+  (
     STATE_ADMIN
       ? formData?.Jurisdictions?.length &&
         !formData?.Jurisdictions.some((juris) => juris?.division == undefined || juris?.divisionBoundary?.length === 0) &&
         hasUniqueDivisions(formData?.Jurisdictions)
       : formData?.Jurisdictions?.length &&
         formData?.Jurisdictions.length &&
         !formData?.Jurisdictions.some((juris) => juris?.roles?.length === 0) &&
         isValid &&
         checkfield &&
         phonecheck &&
         checkMailNameNum(formData) &&
         hasUniqueTenantIds(formData?.Jurisdictions)
+  )
 ) {
   setSubmitValve(true);
 } else {
   setSubmitValve(false);
 }
📝 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
formData?.SelectEmployeeName?.employeeName &&
formData?.SelectEmployeePhoneNumber?.mobileNumber &&
STATE_ADMIN
? formData?.Jurisdictions?.length &&
!formData?.Jurisdictions.some((juris) => juris?.division == undefined || juris?.divisionBoundary?.length === 0) &&
hasUniqueDivisions(formData?.Jurisdictions)
: formData?.Jurisdictions?.length &&
formData?.Jurisdictions.length &&
!formData?.Jurisdictions.some((juris) => juris?.roles?.length === 0) &&
isValid &&
checkfield &&
phonecheck &&
checkMailNameNum(formData) &&
hasUniqueTenantIds(formData?.Jurisdictions)
formData?.SelectEmployeeName?.employeeName &&
formData?.SelectEmployeePhoneNumber?.mobileNumber &&
(
STATE_ADMIN
? formData?.Jurisdictions?.length &&
!formData?.Jurisdictions.some((juris) => juris?.division == undefined || juris?.divisionBoundary?.length === 0) &&
hasUniqueDivisions(formData?.Jurisdictions)
: formData?.Jurisdictions?.length &&
formData?.Jurisdictions.length &&
!formData?.Jurisdictions.some((juris) => juris?.roles?.length === 0) &&
isValid &&
checkfield &&
phonecheck &&
checkMailNameNum(formData) &&
hasUniqueTenantIds(formData?.Jurisdictions)
)

Comment on lines +278 to +280
formData.zoneCode = result[0];
formData.circleCode = result[0];
formData.divisionCode = result[0];
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use 'setValue' to update form fields instead of mutating 'formData' directly

In lines 278-280 and 429-432, you're directly modifying formData to set default field values. Similarly, in functions like setRequiredOptions, showAllData, and onSubmit, formData or data are being mutated directly. Since form data is managed by react-hook-form, direct mutation may not update the form state as expected. Instead, use the setValue function provided by react-hook-form to update form fields.

Apply these changes:

// In the select function at line 278
-formData.zoneCode = result[0];
-formData.circleCode = result[0];
-formData.divisionCode = result[0];
+setValue('zoneCode', result[0]);
+setValue('circleCode', result[0]);
+setValue('divisionCode', result[0]);

// In the 'setRequiredOptions' function at line 429
-function setRequiredOptions(formData) {
-  formData.zoneCode = userData[0];
-  formData.circleCode = userData[0];
-  formData.divisionCode = userData[0];
+function setRequiredOptions() {
+  setValue('zoneCode', userData[0]);
+  setValue('circleCode', userData[0]);
+  setValue('divisionCode', userData[0]);
}

// In 'showAllData' function at line 323
-if (divisionAdmin) setRequiredOptions(formData);
+if (divisionAdmin) setRequiredOptions();

// In 'onSubmit' function at line 356
-if (divisionAdmin) setRequiredOptions(data);
+if (divisionAdmin) setRequiredOptions();

Also applies to: 323-323, 356-356, 429-432

const circleC = userData[0].circleCode;
const divisionC = userData[0].divisionCode;

if (tree && tree[zoneC] && tree[zoneC][circleC]) {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Simplify null checks using optional chaining

At line 422, you can simplify the null checks by using optional chaining to make the code more concise and readable.

Apply this change:

-if (tree && tree[zoneC] && tree[zoneC][circleC]) {
+if (tree?.[zoneC]?.[circleC]) {
📝 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
if (tree && tree[zoneC] && tree[zoneC][circleC]) {
if (tree?.[zoneC]?.[circleC]) {
🧰 Tools
🪛 Biome

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

Comment on lines +107 to +108
const divisionAdmin = Digit.UserService.hasAccess(["DIV_ADMIN"]);

Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Inconsistent Role Naming Detected: 'DIV_ADMIN' vs 'DIVISION ADMIN'

Multiple instances of both 'DIV_ADMIN' and 'DIVISION ADMIN' are found across the codebase, leading to potential access control issues. Please standardize the role name to ensure consistent behavior.

  • frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/components/SearchUserForm.js
  • frontend/micro-ui/web/micro-ui-internals/packages/modules/core/src/pages/Inbox.js
  • frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/createEmployee.js
  • (and other listed files)
🔗 Analysis chain

Ensure consistent role naming: 'DIV_ADMIN' vs 'DIVISION ADMIN'

In line 107, the role is referenced as 'DIV_ADMIN', but elsewhere, such as in line 225, roles are filtered using 'DIVISION ADMIN'. This inconsistency may lead to unexpected behavior when checking user access or filtering roles. Please ensure that the role names are consistent throughout the codebase.

To verify all occurrences of these role names in the codebase, you can run the following script:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all occurrences of 'DIV_ADMIN' and 'DIVISION ADMIN' in the codebase

# Search for 'DIV_ADMIN'
rg --type js --type jsx 'DIV_ADMIN'

# Search for 'DIVISION ADMIN'
rg --type js --type jsx 'DIVISION ADMIN'

Length of output: 134


Script:

#!/bin/bash
# Description: Find all occurrences of 'DIV_ADMIN' and 'DIVISION ADMIN' in .js and .jsx files

# Search for 'DIV_ADMIN' in .js and .jsx files
rg 'DIV_ADMIN' -g '*.js' -g '*.jsx'

# Search for 'DIVISION ADMIN' in .js and .jsx files
rg 'DIVISION ADMIN' -g '*.js' -g '*.jsx'

Length of output: 4824

Comment on lines +153 to +166

if (isEdit && STATE_ADMIN) {
let divisionData = [];
let divisionDataSet = new Set();
if (isEdit && jurisdictionData.length > 0) {
jurisdictionData?.map((jurisdiction) => {
if (jurisdiction?.divisionBoundary && jurisdiction?.divisionBoundary?.length > 0 && divisionData.length === 0) {
divisionData.push(jurisdiction);
} else if (divisionData.length > 0) {
if (divisionData[divisionData.length - 1]?.division?.code !== jurisdiction?.division?.code) {
divisionData.push(jurisdiction);
jurisdictionData?.forEach((jurisdiction) => {
if (jurisdiction?.divisionBoundary && jurisdiction?.divisionBoundary?.length > 0) {
// If divisionData set doesn't already have this division, add it
if (!Array.from(divisionDataSet).some((item) => item.division?.code === jurisdiction?.division?.code)) {
divisionDataSet.add(jurisdiction);
}
}
});
}
let divisionData = Array.from(divisionDataSet);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Optimize the construction of divisionDataSet

The current implementation converts the Set to an array on each iteration, which can be inefficient:

if (!Array.from(divisionDataSet).some((item) => item.division?.code === jurisdiction?.division?.code)) {
  divisionDataSet.add(jurisdiction);
}

Consider using a Map or adjusting the Set to store division codes directly for more efficient lookups:

- let divisionDataSet = new Set();
+ let divisionCodeSet = new Set();
  // ...
  jurisdictionData?.forEach((jurisdiction) => {
    if (jurisdiction?.divisionBoundary && jurisdiction?.divisionBoundary?.length > 0) {
-     if (!Array.from(divisionDataSet).some((item) => item.division?.code === jurisdiction?.division?.code)) {
-       divisionDataSet.add(jurisdiction);
+     if (!divisionCodeSet.has(jurisdiction.division?.code)) {
+       divisionCodeSet.add(jurisdiction.division.code);
+       divisionDataSet.add(jurisdiction);
      }
    }
  });

- let divisionData = Array.from(divisionDataSet);
+ let divisionData = Array.from(divisionDataSet);

Comment on lines +159 to +161
// If divisionData set doesn't already have this division, add it
if (!Array.from(divisionDataSet).some((item) => item.division?.code === jurisdiction?.division?.code)) {
divisionDataSet.add(jurisdiction);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Simplify duplicate checking in divisionDataSet

To improve readability and performance, you can simplify the duplicate check by using the Set's inherent properties:

- if (!Array.from(divisionDataSet).some((item) => item.division?.code === jurisdiction?.division?.code)) {
-   divisionDataSet.add(jurisdiction);
- }
+ const divisionCode = jurisdiction.division?.code;
+ if (!divisionDataSet.has(divisionCode)) {
+   divisionDataSet.add(divisionCode);
+   uniqueJurisdictions.push(jurisdiction);
+ }

This way, you avoid converting the Set to an array and improve the efficiency of the operation.

Committable suggestion was skipped due to low confidence.

@pradeepkumarcm-egov pradeepkumarcm-egov merged commit 7ea4871 into master Oct 8, 2024
1 of 2 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Oct 10, 2024
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.

3 participants