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

Integrated search api and update api and created comment logs timelin… #1573

Merged
merged 2 commits into from
Oct 18, 2024

Conversation

rachana-egov
Copy link
Contributor

@rachana-egov rachana-egov commented Oct 18, 2024

…e component

Summary by CodeRabbit

  • New Features

    • Updated stylesheet to the latest version for improved styling.
    • Introduced a new TimelinePopUpWrapper component for displaying workflow timelines.
    • Enhanced VillageView component to fetch and display dynamic census data.
    • Added a new route for census service in the proxy configuration.
  • Bug Fixes

    • Improved functionality of existing pop-up components to handle census data correctly.
  • Chores

    • Refined validation functions for better clarity and added a new utility function for date formatting.

Copy link
Contributor

coderabbitai bot commented Oct 18, 2024

📝 Walkthrough

Walkthrough

The pull request includes updates to several HTML and JavaScript files within the micro-ui project. Key changes involve updating the stylesheet link for the @egovernments/digit-ui-css package from version 1.0.85-campaign to 1.0.86-campaign. Additionally, multiple components and utility functions have been modified to enhance functionality, including the addition of a new route in the proxy setup, updates to props in various pop-up components, and the introduction of a new TimelinePopUpWrapper component. The utility functions have also been refined, including the addition of a new function for converting epoch time to a formatted date.

Changes

File Change Summary
health/micro-ui/web/micro-ui-internals/example/public/index.html Updated stylesheet link from 1.0.85-campaign to 1.0.86-campaign.
health/micro-ui/web/public/index.html Updated stylesheet link from 1.0.85-campaign to 1.0.86-campaign.
health/micro-ui/web/micro-ui-internals/example/src/setupProxy.js Added new route "/census-service" to the proxy middleware configuration.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/accessbilityPopUP.js Updated AccessibilityPopUp to accept census prop and modified handleSave function.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/editVillagePopulationPopUP.js Updated EditVillagePopulationPopUp to accept census prop for dynamic population management.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/securityPopUp.js Updated SecurityPopUp to utilize census prop for state initialization and save operations.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/viewVillage.js Enhanced VillageView to fetch census data, introduced Loader component, and added new state variables.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/timelinePopUpWrapper.js Introduced new TimelinePopUpWrapper component for displaying workflow timelines.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/utils/utilities.js Refined validation functions and added epochToDateTime function for formatting epoch time.

Possibly related PRs

Suggested reviewers

  • nipunarora-eGov

🐰 In the garden where changes bloom,
A stylesheet update makes room,
New pop-ups dance with census grace,
A timeline wraps in a warm embrace.
With utilities refined, we hop along,
Celebrating code, where we belong! 🌼


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.

coderabbitai[bot]
coderabbitai bot previously requested changes Oct 18, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 25

🧹 Outside diff range comments (3)
health/micro-ui/web/micro-ui-internals/example/public/index.html (1)

Line range hint 14-22: Consider consolidating CSS imports

The HTML file includes multiple CSS imports from various versions of @egovernments/digit-ui-css and other related packages. This approach may lead to conflicts, increased load times, and maintenance difficulties.

Consider the following recommendations:

  1. Consolidate CSS imports to use a single, consistent version where possible.
  2. Remove or comment out unused CSS imports to reduce load times and potential conflicts.
  3. Document the purpose of each CSS import, especially when multiple versions are necessary.

Example refactor:

<!-- Main DIGIT UI CSS -->
<link rel="stylesheet" href="https://unpkg.com/@egovernments/digit-ui-css@1.0.86-campaign/dist/index.css" />

<!-- Component-specific CSS (if needed) -->
<link rel="stylesheet" href="https://unpkg.com/@egovernments/digit-ui-components-css@0.0.2-beta.39/dist/index.css"/>

<!-- Module-specific CSS (if needed) -->
<link rel="stylesheet" href="https://unpkg.com/@egovernments/digit-ui-css@1.0.50-microplan/dist/index.css" />

<!-- Removed duplicate and potentially conflicting CSS imports -->
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/utils/utilities.js (1)

Line range hint 78-125: LGTM: Improved boundary validation logic

The changes to the recursiveParentFind function enhance readability and efficiency. The new implementation with a parent-children map is clearer and more maintainable.

Consider using a more descriptive variable name instead of i in the extraParent filter:

- const extraParent = missingParents?.filter((i) => i?.type !== state?.lowestHierarchy);
+ const extraParent = missingParents?.filter((item) => item?.type !== state?.lowestHierarchy);
🧰 Tools
🪛 Biome

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/accessbilityPopUP.js (1)

Line range hint 92-113: Use the t function for translations in Dropdown components.

In the Dropdown components, the t prop is currently set to an identity function t={(label) => label}, meaning labels are not being translated. Replace it with the actual translation function t to ensure proper localization.

Apply this diff to fix the issue:

-                  t={(label) => label} // Replace with translation function
+                  t={t}

This change should be applied to all Dropdown components where the translation function is required.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between aac8a5e and 5777604.

⛔ Files ignored due to path filters (1)
  • health/micro-ui/web/micro-ui-internals/packages/css/package.json is excluded by !**/*.json
📒 Files selected for processing (10)
  • health/micro-ui/web/micro-ui-internals/example/public/index.html (1 hunks)
  • health/micro-ui/web/micro-ui-internals/example/src/setupProxy.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/css/src/pages/employee/villageView.scss (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/accessbilityPopUP.js (4 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/editVillagePopulationPopUP.js (3 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/securityPopUp.js (4 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/timelinePopUpWrapper.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/viewVillage.js (8 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/utils/utilities.js (13 hunks)
  • health/micro-ui/web/public/index.html (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
health/micro-ui/web/micro-ui-internals/example/src/setupProxy.js (1)

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/accessbilityPopUP.js (1)

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/editVillagePopulationPopUP.js (1)

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/securityPopUp.js (1)

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/timelinePopUpWrapper.js (1)

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/viewVillage.js (1)

Pattern **/*.js: check

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/utils/utilities.js (1)

Pattern **/*.js: check

🪛 Biome
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/securityPopUp.js

[error] 63-63: Avoid passing children using a prop

The canonical way to pass children in React is to use JSX elements

(lint/correctness/noChildrenProp)

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/timelinePopUpWrapper.js

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 761-761: Avoid passing children using a prop

The canonical way to pass children in React is to use JSX elements

(lint/correctness/noChildrenProp)

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/utils/utilities.js

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 363-363: This let declares a variable that is only assigned once.

'path' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)

🔇 Additional comments (10)
health/micro-ui/web/micro-ui-internals/packages/css/src/pages/employee/villageView.scss (1)

58-58: Spacing adjustment for .middle-child class

The margin for the .middle-child class has been changed from margin-top: 1rem; to margin-bottom: 1.5rem;. This modification will affect the vertical spacing of elements using this class, potentially impacting the overall layout of the village view.

Please ensure that this change aligns with the intended design:

  1. Verify that shifting the margin from top to bottom doesn't negatively impact the layout.
  2. Confirm that the increased margin (from 1rem to 1.5rem) provides the desired spacing between elements.
  3. Check the visual appearance of the village view to ensure it meets the updated design requirements.

If you need any assistance in verifying these changes or if further adjustments are needed, please let me know.

health/micro-ui/web/public/index.html (1)

17-17: 🧹 Nitpick (assertive)

LGTM! CSS version updated for HCM Workbench module.

The update of the @egovernments/digit-ui-css package from version 1.0.85-campaign to 1.0.86-campaign looks good. This change appears to be related to the inclusion of the HCM Workbench module as mentioned in the comment.

To ensure this change doesn't introduce any unexpected styling issues, please verify the application's appearance after this update. Run the following script to check for any other files that might be affected by this CSS version change:

Consider updating the comment above the link to be more specific:

-  <!-- added below css for hcm-workbench module inclusion-->
+  <!-- Updated CSS version to 1.0.86-campaign for HCM Workbench module inclusion -->

This will provide more context for future developers about the nature of this change.

health/micro-ui/web/micro-ui-internals/example/src/setupProxy.js (1)

99-100: New route added for census service

The addition of the "/census-service" route to the proxy configuration is noted. This change allows requests to the census service to be proxied through the application.

To ensure this change is consistent with the application's architecture, please run the following verification:

This script will help identify any related changes or configurations for the census service across the codebase.

✅ Verification successful

Census Service Proxy Configuration Verified

The addition of the "/census-service" route to setupProxy.js has been verified and aligns with its usage across the codebase. Requests to the census service are correctly proxied, ensuring seamless integration with existing components.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the census service integration

# Test 1: Check if there are any new files or changes related to the census service
echo "Checking for census service related files:"
fd -e js -e jsx -e ts -e tsx census

# Test 2: Verify if there are any imports or uses of the census service in the codebase
echo "Checking for census service usage:"
rg --type js --type jsx --type ts --type tsx "census.*service"

# Test 3: Check for any configuration related to the census service
echo "Checking for census service configuration:"
rg --type js --type json "census.*service"

Length of output: 943

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/utils/utilities.js (5)

35-36: LGTM: Improved code structure and flexibility

The addition of the getValueFromPath function enhances the flexibility of accessing nested object properties. This change improves the overall structure and readability of the code.


132-143: LGTM: Improved field validation logic

The refactored areFieldsValid function is more concise and efficient. It correctly handles empty arrays and uses a functional approach with the some method to check field validity. This implementation is easier to read and maintain.

🧰 Tools
🪛 Biome

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


Line range hint 191-211: LGTM: Added validators for microplan assumptions and data upload

The addition of microplanAssumptionsValidator and uploadDataValidator functions, along with their integration into the validator switch statement, enhances the overall validation process. These changes ensure more comprehensive form validation across different scenarios.


220-223: LGTM: Improved current month retrieval

The modification to the getCurrentMonth function using an array of month names simplifies the process and improves code readability. This approach is more maintainable and less error-prone than using numeric month values.


Line range hint 1-487: Overall: Significant improvements to utility functions

The changes in this file have greatly enhanced its functionality and maintainability. Key improvements include:

  1. Refactored validation functions with improved logic and error handling.
  2. Enhanced boundary data processing with the introduction of materialized paths.
  3. New utility functions like epochToDateTime for better date-time handling.
  4. Improved code structure and readability across multiple functions.

These changes provide better support for the microplan module and should improve the overall performance and maintainability of the codebase.

🧰 Tools
🪛 Biome

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/securityPopUp.js (1)

31-43: ⚠️ Potential issue

Ensure the Census data is correctly formatted for the API

The updatedCensus object represents a single census entry, but the API endpoint /census-service/_update may expect the Census data to be an array of census objects. The comment mentions "Sending back the modified Census array," but currently, an object is being sent. Verify that the API expects an array and adjust accordingly.

If the API expects an array, wrap updatedCensus in an array:

body: {
- Census: updatedCensus, // Sending back the modified Census array
+ Census: [updatedCensus], // Sending back the modified Census array
},

Please check the API documentation to confirm the expected request format.

health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/accessbilityPopUP.js (1)

Line range hint 105-109: Verify the options provided to the transportation mode Dropdown.

The options for the transportation mode Dropdown are hardcoded to only include OTHER. Is this intentional? If there are additional transportation modes, consider updating the options to reflect all possible choices.

@@ -19,7 +19,7 @@


<link rel="stylesheet" href="https://unpkg.com/@egovernments/digit-ui-components-css@0.0.2-beta.39/dist/index.css"/>
<link rel="stylesheet" href="https://unpkg.com/@egovernments/digit-ui-css@1.0.85-campaign/dist/index.css" />
<link rel="stylesheet" href="https://unpkg.com/@egovernments/digit-ui-css@1.0.86-campaign/dist/index.css" />
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

CSS Update Results in Unreachable Stylesheet

  • The updated stylesheet link https://unpkg.com/@egovernments/digit-ui-css@1.0.86-campaign/dist/index.css responds with a 404 error, indicating the CSS file is not accessible.
  • This issue may lead to missing styles and adversely affect the application's user interface.

Please verify the correct URL for the CSS file or consider reverting the version update to ensure stylesheet accessibility.

🔗 Analysis chain

CSS package version updated

The stylesheet link for @egovernments/digit-ui-css has been updated from version 1.0.85-campaign to 1.0.86-campaign. This change ensures that the application uses the latest version of the specified CSS package.

To ensure this update doesn't introduce any breaking changes or unintended side effects, please run the following verification script:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any visual regressions or console errors after updating the CSS version

# Test: Check if the new CSS file is accessible
curl -I https://unpkg.com/@egovernments/digit-ui-css@1.0.86-campaign/dist/index.css

# Test: Search for any TODOs or FIXMEs related to CSS updates
rg -i "todo|fixme" --type html --type css --type js

Length of output: 94644

Comment on lines +99 to +100
"/service-request",
"/census-service"
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Trailing comma added after "/service-request"

The addition of a trailing comma after "/service-request" is a good practice. It improves code maintainability by making future additions to the list easier and resulting in cleaner diffs.

Consider adding trailing commas to other elements in the array for consistency. This can be done in a separate cleanup task if desired.

Comment on lines +145 to +188


const assumptionsFormValidator = (formData) => {

let requiredFields = []
if(formData?.selectedRegistrationProcess && formData?.selectedDistributionProcess){
requiredFields = [
formData?.selectedRegistrationProcess,
formData?.selectedDistributionProcess,
]
if (!areFieldsValid(requiredFields)) {
return { key: "error", label: "ERROR_MANDATORY_FIELDS" };
}
}else if(formData?.selectedRegistrationDistributionMode){
requiredFields = [
formData?.selectedRegistrationDistributionMode,
]
if (!areFieldsValid(requiredFields)) {
return { key: "error", label: "ERROR_MANDATORY_FIELDS" };
}
}
let requiredFields = []
if (formData?.selectedRegistrationProcess && formData?.selectedDistributionProcess) {
requiredFields = [
formData?.selectedRegistrationProcess,
formData?.selectedDistributionProcess,
]
if (!areFieldsValid(requiredFields)) {
return { key: "error", label: "ERROR_MANDATORY_FIELDS" };
}
} else if (formData?.selectedRegistrationDistributionMode) {
requiredFields = [
formData?.selectedRegistrationDistributionMode,
]
if (!areFieldsValid(requiredFields)) {
return { key: "error", label: "ERROR_MANDATORY_FIELDS" };
}
}

const processesAreValid = formData?.selectedRegistrationProcess?.code && formData?.selectedDistributionProcess?.code;
if (processesAreValid && (formData?.selectedRegistrationProcess.code === formData?.selectedDistributionProcess.code)) {
return { key: "error", label: "ERROR_REGISTRATION_AND_DISTRIBUTION_ARE_SAME" }; // Customize as needed
return { key: "error", label: "ERROR_REGISTRATION_AND_DISTRIBUTION_ARE_SAME" }; // Customize as needed
}

if (!areFieldsValid(requiredFields)) {
return { key: "error", label: "ERROR_MANDATORY_FIELDS" };
return { key: "error", label: "ERROR_MANDATORY_FIELDS" };
}

return null; // Return null if all validations pass
};




const microplanAssumptionsValidator = (formData)=>{

if(!areFieldsValid(formData.assumptionValues)){
return { key: "error", label: "ERROR_MANDATORY_FIELDS" };
}
const microplanAssumptionsValidator = (formData) => {

return null
if (!areFieldsValid(formData.assumptionValues)) {
return { key: "error", label: "ERROR_MANDATORY_FIELDS" };
}

return null
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

LGTM: Enhanced assumptions form validation

The assumptionsFormValidator function now provides more comprehensive validation for different scenarios, including checks for registration and distribution processes. This improvement enhances the overall robustness of the form validation.

Consider extracting the error messages into constants for better maintainability:

const ERROR_MANDATORY_FIELDS = "ERROR_MANDATORY_FIELDS";
const ERROR_REGISTRATION_AND_DISTRIBUTION_ARE_SAME = "ERROR_REGISTRATION_AND_DISTRIBUTION_ARE_SAME";

// Then use these constants in the return statements
return { key: "error", label: ERROR_MANDATORY_FIELDS };
return { key: "error", label: ERROR_REGISTRATION_AND_DISTRIBUTION_ARE_SAME };

Comment on lines +430 to +455
function epochToDateTime(epoch) {
// Create a new Date object using the epoch time
const date = new Date(epoch);
// Extract the date components
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0"); // Months are 0-based, so add 1
const day = String(date.getDate()).padStart(2, "0");

// Extract the time components
let hours = date.getHours();
const minutes = String(date.getMinutes()).padStart(2, "0");
const seconds = String(date.getSeconds()).padStart(2, "0");

// Determine AM/PM and convert to 12-hour format
const ampm = hours >= 12 ? "PM" : "AM";
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
const formattedHours = String(hours).padStart(2, "0");

// Format the date and time
const formattedDate = `${day}/${month}/${year}`;
const formattedTime = `${formattedHours}:${minutes}:${seconds} ${ampm}`;

// Return the formatted date and time
return `${formattedDate} ${formattedTime}`;

Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

LGTM: Added epoch to date-time conversion utility

The new epochToDateTime function is a valuable addition, providing a clean way to convert epoch time to a formatted date and time string. It handles both date and time components, including AM/PM formatting, which enhances the utility's versatility.

Consider using template literals for string formatting to improve readability:

- const formattedDate = `${day}/${month}/${year}`;
- const formattedTime = `${formattedHours}:${minutes}:${seconds} ${ampm}`;
- return `${formattedDate} ${formattedTime}`;
+ const formattedDate = `${day}/${month}/${year}`;
+ const formattedTime = `${formattedHours}:${minutes}:${seconds} ${ampm}`;
+ return `${formattedDate} ${formattedTime}`;

Committable suggestion was skipped due to low confidence.

Comment on lines +363 to +397
let path = [];
let currentBoundary = boundary;

// Build the path from the boundary's parent up to the root
while (currentBoundary && currentBoundary.parent) {
currentBoundary = boundaryMap[currentBoundary.parent];
if (currentBoundary) {
path.push(currentBoundary.code);
}
}

// Join the reversed path into a single string
return path.reverse().join('.');
// Join the reversed path into a single string
return path.reverse().join('.');
}

// First, create a map for easy access to boundaries by code
const boundaryMap = boundaryData.reduce((map, boundary) => {
map[boundary.code] = boundary;
return map;
map[boundary.code] = boundary;
return map;
}, {});

// Iterate over all boundaries
boundaryData.forEach(boundary => {
const { type, code } = boundary;
const { type, code } = boundary;

// Initialize type if not already in the hierarchy
if (!hierarchy[type]) {
hierarchy[type] = {};
}
// Initialize type if not already in the hierarchy
if (!hierarchy[type]) {
hierarchy[type] = {};
}

// Build the reversed materialized path for this boundary
const materializedPath = buildMaterializedPath(boundary, boundaryMap);
// Build the reversed materialized path for this boundary
const materializedPath = buildMaterializedPath(boundary, boundaryMap);

// Assign the materialized path to the boundary in the hierarchy
hierarchy[type][code] = materializedPath;
// Assign the materialized path to the boundary in the hierarchy
hierarchy[type][code] = materializedPath;
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

LGTM: Enhanced boundary data hierarchy creation

The refactored createBoundaryDataByHierarchy function now builds a materialized path for each boundary, which can significantly improve performance for hierarchical queries. This approach provides a more structured and efficient way to represent boundary hierarchies.

Consider using optional chaining to simplify the null checks:

- while (currentBoundary && currentBoundary.parent) {
+ while (currentBoundary?.parent) {
📝 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 path = [];
let currentBoundary = boundary;
// Build the path from the boundary's parent up to the root
while (currentBoundary && currentBoundary.parent) {
currentBoundary = boundaryMap[currentBoundary.parent];
if (currentBoundary) {
path.push(currentBoundary.code);
}
}
// Join the reversed path into a single string
return path.reverse().join('.');
// Join the reversed path into a single string
return path.reverse().join('.');
}
// First, create a map for easy access to boundaries by code
const boundaryMap = boundaryData.reduce((map, boundary) => {
map[boundary.code] = boundary;
return map;
map[boundary.code] = boundary;
return map;
}, {});
// Iterate over all boundaries
boundaryData.forEach(boundary => {
const { type, code } = boundary;
const { type, code } = boundary;
// Initialize type if not already in the hierarchy
if (!hierarchy[type]) {
hierarchy[type] = {};
}
// Initialize type if not already in the hierarchy
if (!hierarchy[type]) {
hierarchy[type] = {};
}
// Build the reversed materialized path for this boundary
const materializedPath = buildMaterializedPath(boundary, boundaryMap);
// Build the reversed materialized path for this boundary
const materializedPath = buildMaterializedPath(boundary, boundaryMap);
// Assign the materialized path to the boundary in the hierarchy
hierarchy[type][code] = materializedPath;
// Assign the materialized path to the boundary in the hierarchy
hierarchy[type][code] = materializedPath;
let path = [];
let currentBoundary = boundary;
// Build the path from the boundary's parent up to the root
while (currentBoundary?.parent) {
currentBoundary = boundaryMap[currentBoundary.parent];
if (currentBoundary) {
path.push(currentBoundary.code);
}
}
// Join the reversed path into a single string
return path.reverse().join('.');
}
// First, create a map for easy access to boundaries by code
const boundaryMap = boundaryData.reduce((map, boundary) => {
map[boundary.code] = boundary;
return map;
}, {});
// Iterate over all boundaries
boundaryData.forEach(boundary => {
const { type, code } = boundary;
// Initialize type if not already in the hierarchy
if (!hierarchy[type]) {
hierarchy[type] = {};
}
// Build the reversed materialized path for this boundary
const materializedPath = buildMaterializedPath(boundary, boundaryMap);
// Assign the materialized path to the boundary in the hierarchy
hierarchy[type][code] = materializedPath;
🧰 Tools
🪛 Biome

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 363-363: This let declares a variable that is only assigned once.

'path' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


<div className="label-pair">
<span className="label-heading">{t(`HCM_MICROPLAN_DISCRICT_LABEL`)}</span>
<span className="label-text">Dist1</span>
<span className="label-text">{data.boundaryCode}</span>
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

Add null checks when accessing properties of 'data' to prevent runtime errors.

When rendering data from the data object, ensure that properties exist to prevent potential undefined or null dereferences, which can cause runtime errors if the properties are missing. Consider using optional chaining.

For example:

<span className="label-text">{data?.boundaryCode}</span>

Update other property accesses accordingly:

  • Line 97: {data?.boundaryCode}
  • Line 102: {data?.boundaryCode}
  • Line 107: {data?.boundaryCode}
  • Line 185: {data?.additionalDetails?.targetPopulation}
  • Line 195: {data?.additionalDetails?.confirmedTargetPopulation}
  • Line 200: {data?.additionalDetails?.confirmedTotalPopulation}
  • Line 205: {data?.assignee} (Ensure assignee is defined and formatted correctly for display)

Also applies to: 102-102, 107-107, 185-185, 195-195, 200-200, 205-205


🛠️ Refactor suggestion

Refactor repeated 'label-pair' blocks into a reusable component.

The div elements with className "label-pair" are repeated multiple times with similar structure. Consider creating a reusable LabelPair component to reduce code duplication and improve maintainability.

Example:

const LabelPair = ({ headingKey, text }) => (
  <div className="label-pair">
    <span className="label-heading">{t(headingKey)}</span>
    <span className="label-text">{text}</span>
  </div>
);

Usage:

<LabelPair headingKey="HCM_MICROPLAN_DISCRICT_LABEL" text={data?.boundaryCode} />

Also applies to: 102-102, 107-107, 185-185, 190-190, 195-195, 200-200, 205-205

Comment on lines +763 to +772
{timelineSteps.map((step, index) => (
<Timeline
key={index}
label={step.label}

subElements={step.subElements}
variant={step.variant}
showConnector={step.showConnector}
/>
))}
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider using unique keys when rendering lists

Using the index as the key in list rendering can lead to issues if the list items change order or if new items are added. If possible, use a unique identifier from the data (e.g., a unique ID from each process instance) as the key for the Timeline components to ensure optimal performance and correctness.

const [timelineSteps, setTimelineSteps] = useState([]);

useEffect(() => {
if (hardCodeData && hardCodeData.ProcessInstances) {
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Simplify condition with optional chaining

You can use optional chaining to simplify the condition in the if statement.

Apply this minor change:

-if (workflowData && workflowData.ProcessInstances) {
+if (workflowData?.ProcessInstances) {

Committable suggestion was skipped due to low confidence.

🧰 Tools
🪛 Biome

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

Comment on lines +756 to +776
return (
<PopUp
onClose={onClose}
heading={t(heading)}
onOverlayClick={onClose}
children={[
<TimelineMolecule key="timeline" initialVisibleCount={4}>
{timelineSteps.map((step, index) => (
<Timeline
key={index}
label={step.label}

subElements={step.subElements}
variant={step.variant}
showConnector={step.showConnector}
/>
))}
</TimelineMolecule>
]}
/>
);
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

Avoid passing children using a prop

Instead of passing the children via a prop to the PopUp component, nest the TimelineMolecule inside the PopUp component directly. This approach aligns with React best practices and enhances code readability.

Apply this diff to refactor the code:

 return (
     <PopUp
         onClose={onClose}
         heading={t(heading)}
         onOverlayClick={onClose}
-        children={[
-            <TimelineMolecule key="timeline" initialVisibleCount={4}>
-                {timelineSteps.map((step, index) => (
-                    <Timeline
-                        key={index}
-                        label={step.label}
-                        subElements={step.subElements}
-                        variant={step.variant}
-                        showConnector={step.showConnector}
-                    />
-                ))}
-            </TimelineMolecule>
-        ]}
     >
+        <TimelineMolecule key="timeline" initialVisibleCount={4}>
+            {timelineSteps.map((step, index) => (
+                <Timeline
+                    key={index}
+                    label={step.label}
+                    subElements={step.subElements}
+                    variant={step.variant}
+                    showConnector={step.showConnector}
+                />
+            ))}
+        </TimelineMolecule>
     </PopUp>
 );
📝 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
return (
<PopUp
onClose={onClose}
heading={t(heading)}
onOverlayClick={onClose}
children={[
<TimelineMolecule key="timeline" initialVisibleCount={4}>
{timelineSteps.map((step, index) => (
<Timeline
key={index}
label={step.label}
subElements={step.subElements}
variant={step.variant}
showConnector={step.showConnector}
/>
))}
</TimelineMolecule>
]}
/>
);
return (
<PopUp
onClose={onClose}
heading={t(heading)}
onOverlayClick={onClose}
>
<TimelineMolecule key="timeline" initialVisibleCount={4}>
{timelineSteps.map((step, index) => (
<Timeline
key={index}
label={step.label}
subElements={step.subElements}
variant={step.variant}
showConnector={step.showConnector}
/>
))}
</TimelineMolecule>
</PopUp>
);
🧰 Tools
🪛 Biome

[error] 761-761: Avoid passing children using a prop

The canonical way to pass children in React is to use JSX elements

(lint/correctness/noChildrenProp)

Comment on lines +738 to +754
useEffect(() => {
if (hardCodeData && hardCodeData.ProcessInstances) {


// Map API response to timeline steps
const steps = hardCodeData.ProcessInstances.map((instance, index) => ({
label: instance.state.applicationStatus,
variant: 'completed',
subElements: [Digit.Utils.microplanv1.epochToDateTime(instance?.auditDetails?.lastModifiedTime),
instance?.assignes?.length > 0 ? instance.assignes[0]?.name : 'NA',
t(`${instance.comment}`)
],
showConnector: true
}));
setTimelineSteps(steps);
}
}, []);
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

Use fetched data instead of hardcoded data

The component fetches workflow data using useCustomAPIHook, but the fetched data (workflowData) is not used. Instead, the hardcoded data (hardCodeData) is utilized in the useEffect. To ensure the component displays up-to-date and accurate information, consider using workflowData instead of hardCodeData.

Apply this diff to fix the issue:

-useEffect(() => {
-    if (hardCodeData && hardCodeData.ProcessInstances) {
+useEffect(() => {
+    if (workflowData && workflowData.ProcessInstances) {
         // Map API response to timeline steps
-        const steps = hardCodeData.ProcessInstances.map((instance, index) => ({
+        const steps = workflowData.ProcessInstances.map((instance, index) => ({

Also, add workflowData to the dependency array of useEffect to update timelineSteps when new data is fetched:

-}, []);
+}, [workflowData]);
📝 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
useEffect(() => {
if (hardCodeData && hardCodeData.ProcessInstances) {
// Map API response to timeline steps
const steps = hardCodeData.ProcessInstances.map((instance, index) => ({
label: instance.state.applicationStatus,
variant: 'completed',
subElements: [Digit.Utils.microplanv1.epochToDateTime(instance?.auditDetails?.lastModifiedTime),
instance?.assignes?.length > 0 ? instance.assignes[0]?.name : 'NA',
t(`${instance.comment}`)
],
showConnector: true
}));
setTimelineSteps(steps);
}
}, []);
useEffect(() => {
if (workflowData && workflowData.ProcessInstances) {
// Map API response to timeline steps
const steps = workflowData.ProcessInstances.map((instance, index) => ({
label: instance.state.applicationStatus,
variant: 'completed',
subElements: [Digit.Utils.microplanv1.epochToDateTime(instance?.auditDetails?.lastModifiedTime),
instance?.assignes?.length > 0 ? instance.assignes[0]?.name : 'NA',
t(`${instance.comment}`)
],
showConnector: true
}));
setTimelineSteps(steps);
}
}, [workflowData]);
🧰 Tools
🪛 Biome

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

@nipunarora-eGov nipunarora-eGov dismissed coderabbitai[bot]’s stale review October 18, 2024 14:57

aware of hardcoding, will integrate once we have data

@nipunarora-eGov nipunarora-eGov merged commit 91fbffb into console Oct 18, 2024
3 checks passed
@nipunarora-eGov nipunarora-eGov deleted the view_village_enhance branch October 18, 2024 14:57
@nabeelmd-eGov nabeelmd-eGov mentioned this pull request Dec 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.

2 participants