Skip to content
This repository has been archived by the owner on Nov 26, 2024. It is now read-only.

Develop #990

Merged
merged 15 commits into from
Oct 29, 2024
Merged

Develop #990

merged 15 commits into from
Oct 29, 2024

Conversation

debasishchakraborty-egovt
Copy link
Collaborator

@debasishchakraborty-egovt debasishchakraborty-egovt commented Oct 29, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced HRMS card functionality for state administrators with additional modules.
    • Introduced internationalization support in UI customizations.
  • Bug Fixes

    • Updated validation logic for tax head codes to allow for more flexible checks.
  • Documentation

    • Improved formatting and readability across multiple components and configurations for better maintainability.
  • Style

    • Consistent formatting applied to various components and methods for improved clarity and readability.

Copy link

coderabbitai bot commented Oct 29, 2024

Walkthrough

The changes in this pull request involve multiple components across different modules, primarily focusing on the DemandService class and various frontend files. Key modifications include the alteration of the updateAsync method in DemandService to improve the handling of audit details, the addition of new user role functionalities in the HRMS card, and various formatting and readability enhancements across several JavaScript files. Additionally, the ChallanValidator class has updated its validation logic for tax head codes, refining error handling to better reflect the new conditions.

Changes

File Change Summary
business-services/billing-service/src/main/java/org/egov/demand/service/DemandService.java Modified the updateAsync method to disable previous audit detail updates and introduced isolated handling of audit details for each demand.
frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/components/hrmscard.js Added new functionality for state administrators with conditional rendering of modules; reformatted existing module for consistency.
frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/Response.js Enhanced formatting and readability, updated error handling, and standardized string formatting in the Response.js file.
frontend/micro-ui/web/micro-ui-internals/packages/modules/payment/src/configs/UICustomizations.js Introduced internationalization support, improved formatting, and updated the populateReqCriteria method to include useTranslation.
frontend/micro-ui/web/src/Customisations/UICustomizations.js Added internationalization support, improved readability and formatting across several methods, and updated the populateReqCriteria method to include useTranslation.
municipal-services/echallan-services/src/main/java/org/egov/echallan/validator/ChallanValidator.java Modified the validateFields method to change tax head code validation logic and refined error handling to better reflect the new validation conditions.

Possibly related PRs

  • updated createdtime code #984: This PR modifies the updateAsync method in the DemandService class, similar to the main PR, which also focuses on changes to the updateAsync method, specifically regarding the handling of audit details.
  • Created date issue #988: This PR also addresses changes in the updateAsync method of the DemandService class, enhancing the management of audit details, which aligns closely with the changes made in the main PR.

Suggested reviewers

  • pradeepkumarcm-egov
  • JithendarKumar-eGov

Poem

🐇 In the fields where demands grow,
Audit details now flow,
With roles for admins bright,
New modules take flight,
Formatting's a joy, oh what a show,
Code's clearer now, as we all know! 🌼


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

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

🧹 Outside diff range and nitpick comments (5)
frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/components/hrmscard.js (1)

Line range hint 35-49: Consider extracting workbench URLs to configuration constants.

While the implementation is correct, the hardcoded workbench URLs (/workbench-ui/employee/workbench/...) should be moved to a configuration file or constants. This would make it easier to maintain and update these URLs across the application if the paths change in the future.

Example implementation:

// config.js
export const WORKBENCH_URLS = {
  VILLAGE_MASTER: '/workbench-ui/employee/workbench/mdms-search-v2',
  LOCALISATION: '/workbench-ui/employee/workbench/localisation-search'
};

// hrmscard.js
import { WORKBENCH_URLS } from './config';
// ...
{
  label: t("WORK_BENCH_URL_VILLAGE_MASTER_DATA"),
  link: `${window?.location?.origin}${WORKBENCH_URLS.VILLAGE_MASTER}?moduleName=tenant&masterName=tenants`,
  category: t("HR_EDIT_MASTER"),
}
municipal-services/echallan-services/src/main/java/org/egov/echallan/validator/ChallanValidator.java (1)

Line range hint 1-180: Improve code maintainability and documentation.

The validator contains several areas that could be improved:

  1. There are multiple commented-out validation blocks without explanation
  2. Validation patterns and error message formats are inconsistent
  3. The method is quite long and handles multiple concerns

Consider the following improvements:

  1. Remove or document commented code with TODO tickets
  2. Extract validation groups into separate methods
  3. Standardize error message format
  4. Add documentation explaining the validation rules and business logic

Example refactor for better organization:

@Component
@Slf4j
public class ChallanValidator {
    private void validateTaxHeadCodes(List<String> current, List<String> required, Map<String, String> errorMap) {
        if (!current.isEmpty() && !required.isEmpty()) {
            if (!current.stream().anyMatch(required::contains)) {
                errorMap.put(
                    ErrorCodes.INVALID_TAXHEAD_CODE,
                    "At least one mandatory tax head code must be present"
                );
            }
        }
    }

    private void validateAmounts(List<Amount> amounts, Map<String, String> errorMap) {
        // Extract amount validation logic here
    }

    // Additional extracted methods...
}

Would you like me to propose a complete refactoring plan?

frontend/micro-ui/web/micro-ui-internals/packages/modules/payment/src/configs/UICustomizations.js (1)

185-193: Enhance consumer code validation

The current validation only checks the length of the consumer code. Consider adding more robust validation:

  1. Check for valid characters
  2. Add specific format validation if applicable

Example enhancement:

  if (!consumerCode) return false;
- if (consumerCode.length < 10 || consumerCode.length > 25) {
+ const validFormat = /^[A-Z0-9-_]+$/i;  // adjust regex based on your requirements
+ if (consumerCode.length < 10 || consumerCode.length > 25 || !validFormat.test(consumerCode)) {
    return { warning: true, label: "ES_COMMON_ENTER_VALID_CONSUMER_CODE" };
  }
frontend/micro-ui/web/src/Customisations/UICustomizations.js (1)

Line range hint 96-122: Improve error handling in updatePayload for works.purchase.

The function should validate the existence of required fields before accessing them to prevent potential runtime errors.

Apply this diff to add validation:

   if (businessService === businessServiceMap?.["works.purchase"]) {
+    if (!applicationDetails?.additionalDetails?.projectId || !applicationDetails?.billDate || !applicationDetails?.referenceId) {
+      throw new Error("Missing required fields for works.purchase payload");
+    }
     const workflow = {
       // ... existing workflow code ...
     };
business-services/billing-service/src/main/java/org/egov/demand/service/DemandService.java (1)

232-239: Remove commented-out code.

This block of commented code should be removed as it's no longer needed and the new implementation properly handles audit details. Keeping commented-out code reduces readability and can lead to confusion about which implementation is current.

-//		for (Demand demand : demands) {
-//			AuditDetails currAuditDetails = demand.getAuditDetails();
-//			if (currAuditDetails != null) {
-//				auditDetail.setCreatedTime(currAuditDetails.getCreatedTime());
-//				auditDetail.setCreatedBy(currAuditDetails.getCreatedBy());
-//			}
-//			demand.setAuditDetails(auditDetail);
-//		}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 91fdc2a and 1c68bd4.

📒 Files selected for processing (6)
  • business-services/billing-service/src/main/java/org/egov/demand/service/DemandService.java (3 hunks)
  • frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/components/hrmscard.js (3 hunks)
  • frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/Response.js (5 hunks)
  • frontend/micro-ui/web/micro-ui-internals/packages/modules/payment/src/configs/UICustomizations.js (6 hunks)
  • frontend/micro-ui/web/src/Customisations/UICustomizations.js (17 hunks)
  • municipal-services/echallan-services/src/main/java/org/egov/echallan/validator/ChallanValidator.java (1 hunks)
🧰 Additional context used
🪛 Biome
frontend/micro-ui/web/micro-ui-internals/packages/modules/payment/src/configs/UICustomizations.js

[error] 119-138: 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/src/Customisations/UICustomizations.js

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

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


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

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


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

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


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

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


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

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 668-693: 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)

🔇 Additional comments (8)
frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/pages/Response.js (3)

25-25: LGTM! Proper use of optional chaining.

The formatting improvement and safe property access using optional chaining is well implemented.


92-94: LGTM! Proper loading state handling.

The loading state condition correctly handles both the initial loading and mutation states.


108-110: 🛠️ Refactor suggestion

Consider using environment variables for context path.

Direct access to window.contextPath could be unsafe. Consider using environment variables or a configuration service.

- <Link to={`${props.parentRoute.includes("employee") ? `/${window?.contextPath}/employee` : `/${window?.contextPath}/citizen`}`}>
+ // Add to your environment config
+ const BASE_CONTEXT_PATH = process.env.REACT_APP_CONTEXT_PATH || '';
+ // In component:
+ <Link to={`${props.parentRoute.includes("employee") ? `/${BASE_CONTEXT_PATH}/employee` : `/${BASE_CONTEXT_PATH}/citizen`}`}>
frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/components/hrmscard.js (2)

97-101: LGTM! Formatting improvements enhance readability.

The reformatting of the state reports link maintains functionality while improving code consistency.


Line range hint 35-49: Verify workbench routes and translations.

Please ensure that:

  1. The new workbench routes (/mdms-search-v2 and /localisation-search) are properly configured in the workbench UI.
  2. The translation keys are defined in the localization files.

Also applies to: 97-101

municipal-services/echallan-services/src/main/java/org/egov/echallan/validator/ChallanValidator.java (1)

94-97: ⚠️ Potential issue

Review the business impact of relaxed tax head validation.

The validation logic has been significantly relaxed from requiring all mandatory tax head codes to requiring just one. This change could lead to incomplete challans being generated.

Consider the following concerns:

  1. Is this relaxation intentional and approved by the business team?
  2. Could this lead to revenue leakage or billing issues?
  3. The error message is inconsistent with the new validation logic, as it still suggests all mandatory codes are required.

Let's check how tax head codes are used elsewhere:

If this change is intentional, consider updating the code as follows:

-			if (!(currentTaxHeadCodes.stream().anyMatch(requiredTaxHeadCodes::contains)))
-				errorMap.put("INVALID_TAXHEAD_CODE_DETAILS",
-						"Mandatory taxhead codes details are not present in request for provided business service");
+			if (!currentTaxHeadCodes.stream().anyMatch(requiredTaxHeadCodes::contains)) {
+				errorMap.put("INVALID_TAXHEAD_CODE_DETAILS",
+						"At least one mandatory tax head code must be present in the request for the provided business service");
+			}
frontend/micro-ui/web/micro-ui-internals/packages/modules/payment/src/configs/UICustomizations.js (1)

4-4: LGTM: Import added for internationalization support

The addition of useTranslation import is appropriate for the i18n implementation throughout the file.

business-services/billing-service/src/main/java/org/egov/demand/service/DemandService.java (1)

Line range hint 253-275: LGTM! Improved audit details handling.

The new implementation correctly handles audit details by:

  1. Creating separate audit detail objects for each demand
  2. Properly preserving creation information while updating modification details
  3. Consistently applying the same pattern to both demands and demand details

This approach prevents shared state issues and maintains proper audit history.


const onError = (error, variables) => {
setErrorInfo(error?.response?.data?.Errors[0]?.code || 'ERROR');
setErrorInfo(error?.response?.data?.Errors[0]?.code || "ERROR");
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Standardize error handling approach.

The error message extraction is inconsistent between the onError function and DisplayText function. Consider creating a utility function for consistent error handling.

+ const getErrorMessage = (error) => {
+   return error?.response?.data?.Errors?.[0]?.code || "ERROR";
+ };

  const onError = (error, variables) => {
-   setErrorInfo(error?.response?.data?.Errors[0]?.code || "ERROR");
+   setErrorInfo(getErrorMessage(error));
    setMutationHappened(true);
  };

  const DisplayText = (action, isSuccess, isEmployee, t) => {
    if (!isSuccess) {
-     return mutation?.error?.response?.data?.Errors[0].code || "ERROR";
+     return getErrorMessage(mutation?.error);
    }
    // ...
  };

Also applies to: 86-86

Comment on lines +46 to +50
useEffect(() => {
if (!window.location.href.includes("/hrms/create") && sessionFormData && Object.keys(sessionFormData) != 0) {
clearSessionFormData();
clearSessionFormData();
}
},[location]);
}, [location]);
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 useEffect implementation issues.

The cleanup effect has several issues that should be addressed:

  1. Use strict equality (!==) instead of loose equality (!=)
  2. The location dependency isn't defined (should be from react-router)
  3. Missing cleanup function

Here's the suggested fix:

- useEffect(() => {
-   if (!window.location.href.includes("/hrms/create") && sessionFormData && Object.keys(sessionFormData) != 0) {
-     clearSessionFormData();
-   }
- }, [location]);
+ import { useLocation } from 'react-router-dom';
+ // Add at the component start:
+ const location = useLocation();
+ 
+ useEffect(() => {
+   if (!window.location.href.includes("/hrms/create") && sessionFormData && Object.keys(sessionFormData) !== 0) {
+     clearSessionFormData();
+   }
+   return () => {
+     // Cleanup if needed
+   };
+ }, [location, sessionFormData, clearSessionFormData]);

Committable suggestion was skipped due to low confidence.

Comment on lines +164 to +171
const result = data?.MdmsRes?.tenant?.tenants
?.filter((row) => row?.divisionCode && row?.divisionName)
?.map((row) => {
return {
...row,
updatedCode: `${row?.divisionName} - ${t(row?.code)}`,
};
});
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 memoizing the transformed data

The data transformation and sorting operation could be expensive for large datasets. Consider memoizing the result using useMemo if this component re-renders frequently.

const memoizedResult = useMemo(() => {
  const result = data?.MdmsRes?.tenant?.tenants
    ?.filter((row) => row?.divisionCode && row?.divisionName)
    ?.map((row) => ({
      ...row,
      updatedCode: `${row?.divisionName} - ${t(row?.code)}`,
    }))
    ?.sort((a, b) => {
      const nameA = (a.divisionName || "").toLowerCase().trim();
      const nameB = (b?.divisionName || "").toLowerCase().trim();
      return nameA.localeCompare(nameB);
    });
  return result;
}, [data?.MdmsRes?.tenant?.tenants, t]);

Comment on lines +123 to 138
if (key === "OP_BILL_TOTAL_AMT") {
return <span>{`₹ ${value}`}</span>;
}

if(key === "OP_CONS_CODE") {
return <span className="link">
if (key === "OP_CONS_CODE") {
return (
<span className="link">
<Link
to={`/${window.contextPath}/citizen/payment/open-view?tenantId=${row.tenantId}&businessService=${row.businessService}&consumerCode=${row.consumerCode}`}
>
{String(value ? (column.translate ? t(column.prefix ? `${column.prefix}${value}` : value) : value) : t("ES_COMMON_NA"))}
</Link>
</span>
</span>
);
}
},
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 unreachable code after switch statement

The code block after the switch statement is unreachable due to the default case that always returns. This means the conditions for 'OP_BILL_DATE', 'OP_BILL_TOTAL_AMT', and 'OP_CONS_CODE' will never be executed.

Move these conditions into the switch statement:

    switch (key) {
        case "OP_CONS_CODE":
          return (
            <span className="link">
              <Link
                to={`/${window.contextPath}/citizen/payment/open-view?tenantId=${row.tenantId}&businessService=WS&consumerCode=${row.connectionNo}`}
              >
                {String(value ? (column.translate ? t(column.prefix ? `${column.prefix}${value}` : value) : value) : t("ES_COMMON_NA"))}
              </Link>
            </span>
          );
+       case "OP_BILL_DATE":
+         return Digit.DateUtils.ConvertEpochToDate(value);
+       case "OP_BILL_TOTAL_AMT":
+         return <span>{`₹ ${value}`}</span>;
        default:
          return <span>{t("ES_COMMON_DEFAULT_NA")}</span>;
    }
-   if (key === "OP_BILL_DATE") {
-     return Digit.DateUtils.ConvertEpochToDate(value);
-   }
-   if (key === "OP_BILL_TOTAL_AMT") {
-     return <span>{`₹ ${value}`}</span>;
-   }
-   if (key === "OP_CONS_CODE") {
-     return (
-       <span className="link">
-         <Link
-           to={`/${window.contextPath}/citizen/payment/open-view?tenantId=${row.tenantId}&businessService=${row.businessService}&consumerCode=${row.consumerCode}`}
-         >
-           {String(value ? (column.translate ? t(column.prefix ? `${column.prefix}${value}` : value) : value) : t("ES_COMMON_NA"))}
-         </Link>
-       </span>
-     );
-   }

Committable suggestion was skipped due to low confidence.

🧰 Tools
🪛 Biome

[error] 119-138: 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)

Comment on lines +30 to +32
let { consumerCode, businessService, tenantId } = data?.state?.searchForm || {};
businessService = businessService?.code;
tenantId = tenantId?.[0]?.code;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add null checks for nested property destructuring

The current destructuring could throw errors if data.state is undefined.

Consider adding null checks:

- let { consumerCode, businessService, tenantId } = data?.state?.searchForm || {};
- businessService = businessService?.code;
- tenantId = tenantId?.[0]?.code;
+ let { consumerCode, businessService, tenantId } = data?.state?.searchForm ?? {};
+ businessService = businessService?.code ?? undefined;
+ tenantId = tenantId?.[0]?.code ?? undefined;
📝 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
let { consumerCode, businessService, tenantId } = data?.state?.searchForm || {};
businessService = businessService?.code;
tenantId = tenantId?.[0]?.code;
let { consumerCode, businessService, tenantId } = data?.state?.searchForm ?? {};
businessService = businessService?.code ?? undefined;
tenantId = tenantId?.[0]?.code ?? undefined;

Comment on lines +323 to +330
if (key === "ATM_AMOUNT_IN_RS") {
return (
<span>
{value
? Digit.Utils.dss.formatterWithoutRound(value, "number")
: t("ES_COMMON_NA")}
</span>
);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve amount formatting.

The current implementation might not handle negative amounts or zero values appropriately.

Consider adding more robust amount formatting:

   if (key === "ATM_AMOUNT_IN_RS") {
     return (
       <span>
-        {value
-          ? Digit.Utils.dss.formatterWithoutRound(value, "number")
-          : t("ES_COMMON_NA")}
+        {typeof value === 'number'
+          ? Digit.Utils.dss.formatterWithoutRound(Math.abs(value), "number")
+          : t("ES_COMMON_NA")}
       </span>
     );
   }
📝 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 (key === "ATM_AMOUNT_IN_RS") {
return (
<span>
{value
? Digit.Utils.dss.formatterWithoutRound(value, "number")
: t("ES_COMMON_NA")}
</span>
);
if (key === "ATM_AMOUNT_IN_RS") {
return (
<span>
{typeof value === 'number'
? Digit.Utils.dss.formatterWithoutRound(Math.abs(value), "number")
: t("ES_COMMON_NA")}
</span>
);

Comment on lines +719 to +726
const result = data?.MdmsRes?.tenant?.tenants
?.filter((row) => row?.divisionCode && row?.divisionName)
?.map((row) => {
return {
...row,
updatedCode: `${row?.divisionName} - ${t(row?.code)}`,
};
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve MDMS data transformation.

The current implementation might not handle edge cases where division details are missing.

Consider adding more robust data transformation:

   select: (data) => {
     const result = data?.MdmsRes?.tenant?.tenants
-      ?.filter((row) => row?.divisionCode && row?.divisionName)
+      ?.filter((row) => Boolean(row?.divisionCode && row?.divisionName))
       ?.map((row) => ({
         ...row,
-        updatedCode: `${row?.divisionName} - ${t(row?.code)}`,
+        updatedCode: `${row.divisionName} - ${t(row.code || '')}`.trim(),
       }));
-    return result;
+    return result || [];
   },
📝 Committable suggestion

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

Suggested change
const result = data?.MdmsRes?.tenant?.tenants
?.filter((row) => row?.divisionCode && row?.divisionName)
?.map((row) => {
return {
...row,
updatedCode: `${row?.divisionName} - ${t(row?.code)}`,
};
});
const result = data?.MdmsRes?.tenant?.tenants
?.filter((row) => Boolean(row?.divisionCode && row?.divisionName))
?.map((row) => ({
...row,
updatedCode: `${row.divisionName} - ${t(row.code || '')}`.trim(),
}));
return result || [];

Comment on lines 668 to 693
if (key === "OP_BILL_DATE") {
return Digit.DateUtils.ConvertEpochToDate(value);
}

if(key === "OP_BILL_TOTAL_AMT"){
return <span>{`₹ ${value}`}</span>
if (key === "OP_BILL_TOTAL_AMT") {
return <span>{`₹ ${value}`}</span>;
}

if(key === "OP_CONS_CODE") {
return <span className="link">
if (key === "OP_CONS_CODE") {
return (
<span className="link">
<Link
to={`/${window.contextPath}/citizen/payment/open-view?tenantId=${row.tenantId}&businessService=${row.businessService}&consumerCode=${row.consumerCode}`}
>
{String(value ? (column.translate ? t(column.prefix ? `${column.prefix}${value}` : value) : value) : t("ES_COMMON_NA"))}
{String(
value
? column.translate
? t(column.prefix ? `${column.prefix}${value}` : value)
: value
: t("ES_COMMON_NA")
)}
</Link>
</span>
</span>
);
}
},
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 unreachable code in additionalCustomizations.

There's unreachable code after the switch statement due to duplicate handling of "OP_CONS_CODE" and other cases.

Remove the duplicate code block:

     switch (key) {
       // ... existing cases ...
       default:
         return <span>{t("ES_COMMON_DEFAULT_NA")}</span>;
     }
-    if (key === "OP_BILL_DATE") {
-      return Digit.DateUtils.ConvertEpochToDate(value);
-    }
-    // ... remove all code until line 693 ...

Committable suggestion was skipped due to low confidence.

🧰 Tools
🪛 Biome

[error] 668-693: 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)

Comment on lines +735 to +743
if (!consumerCode) return false;
if (consumerCode.length < 10 || consumerCode.length > 25) {
return { warning: true, label: "ES_COMMON_ENTER_VALID_CONSUMER_CODE" };
}
// if ((createdFrom === "" && createdTo !== "") || (createdFrom !== "" && createdTo === ""))
// return { warning: true, label: "ES_COMMON_ENTER_DATE_RANGE" };

return false;
}
}
},
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance consumer code validation.

The validation logic for consumer code could be more robust by checking for valid characters.

Consider adding character validation:

   if (!consumerCode) return false;
-  if (consumerCode.length < 10 || consumerCode.length > 25) {
+  if (consumerCode.length < 10 || consumerCode.length > 25 || !/^[a-zA-Z0-9-_\/]+$/.test(consumerCode)) {
     return { warning: true, label: "ES_COMMON_ENTER_VALID_CONSUMER_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
if (!consumerCode) return false;
if (consumerCode.length < 10 || consumerCode.length > 25) {
return { warning: true, label: "ES_COMMON_ENTER_VALID_CONSUMER_CODE" };
}
// if ((createdFrom === "" && createdTo !== "") || (createdFrom !== "" && createdTo === ""))
// return { warning: true, label: "ES_COMMON_ENTER_DATE_RANGE" };
return false;
}
}
},
if (!consumerCode) return false;
if (consumerCode.length < 10 || consumerCode.length > 25 || !/^[a-zA-Z0-9-_\/]+$/.test(consumerCode)) {
return { warning: true, label: "ES_COMMON_ENTER_VALID_CONSUMER_CODE" };
}
// if ((createdFrom === "" && createdTo !== "") || (createdFrom !== "" && createdTo === ""))
// return { warning: true, label: "ES_COMMON_ENTER_DATE_RANGE" };
return false;
},

Comment on lines +188 to +201
data.body.inbox.processSearchCriteria.tenantId =
Digit.ULBService.getCurrentTenantId();

const musterRollNumber = data?.body?.inbox?.moduleSearchCriteria?.musterRollNumber?.trim();
if(musterRollNumber) data.body.inbox.moduleSearchCriteria.musterRollNumber = musterRollNumber
const musterRollNumber =
data?.body?.inbox?.moduleSearchCriteria?.musterRollNumber?.trim();
if (musterRollNumber)
data.body.inbox.moduleSearchCriteria.musterRollNumber =
musterRollNumber;

const attendanceRegisterName = data?.body?.inbox?.moduleSearchCriteria?.attendanceRegisterName?.trim();
if(attendanceRegisterName) data.body.inbox.moduleSearchCriteria.attendanceRegisterName = attendanceRegisterName
const attendanceRegisterName =
data?.body?.inbox?.moduleSearchCriteria?.attendanceRegisterName?.trim();
if (attendanceRegisterName)
data.body.inbox.moduleSearchCriteria.attendanceRegisterName =
attendanceRegisterName;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve string validation in preProcess.

The current implementation uses optional chaining with trim() which could throw if the value is null/undefined.

Apply this diff to add safer string validation:

-      const musterRollNumber = data?.body?.inbox?.moduleSearchCriteria?.musterRollNumber?.trim();
+      const musterRollNumber = data?.body?.inbox?.moduleSearchCriteria?.musterRollNumber;
+      const trimmedMusterRollNumber = typeof musterRollNumber === 'string' ? musterRollNumber.trim() : undefined;
-      if (musterRollNumber)
+      if (trimmedMusterRollNumber)
         data.body.inbox.moduleSearchCriteria.musterRollNumber = trimmedMusterRollNumber;

Committable suggestion was skipped due to low confidence.

@pradeepkumarcm-egov pradeepkumarcm-egov merged commit cd23535 into master Oct 29, 2024
1 of 2 checks passed
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants