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

Added warning toast if user click on search without filling, and adde… #1700

Open
wants to merge 2 commits into
base: console
Choose a base branch
from

Conversation

rachana-egov
Copy link

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

…d dynamic column for pop inbox table

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced PopInboxTable component with dynamic rendering of table columns based on comprehensive demographic data.
    • Improved EditVillagePopulationPopUp for better population data management with a unified state structure.
    • Dynamic display of additional fields in the VillageView component, allowing for flexible data representation.
  • Bug Fixes

    • Added user feedback for empty boundary selections in the PopInbox component, enhancing error handling.

These updates improve user experience and data management across the application.

@rachana-egov rachana-egov requested a review from a team as a code owner October 29, 2024 09:10
Copy link
Contributor

coderabbitai bot commented Oct 29, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces significant enhancements across several components within the micro-plan module. The PopInboxTable component now utilizes a new censusData array for dynamic table column generation based on demographic information. The EditVillagePopulationPopUp component has refactored its state management for better handling of population data. The PopInbox component improves error handling during boundary selection, and the VillageView component dynamically renders additional fields from the data object, enhancing flexibility in displaying population-related information.

Changes

File Change Summary
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/PopInboxTable.js Added a new censusData array for demographic information and modified the rendering logic to dynamically generate table columns based on additionalFields. Updated the data prop in DataTable to use censusData.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/editVillagePopulationPopUP.js Refactored state management to use a single state object confirmedValues for population data. Updated useEffect to initialize state from census.additionalFields and modified handleSave to prepare updated payloads.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PopInbox.js Enhanced error handling by adding a warning toast if selectedBoundaries is empty during the onSearch function.
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/viewVillage.js Replaced static population data display with dynamic rendering of data.additionalFields, improving flexibility in displaying varying datasets.

Possibly related PRs

Suggested reviewers

  • nipunarora-eGov

🐰 In the meadow, changes bloom,
A table grows, dispelling gloom.
With data bright, the fields expand,
A pop-up's charm, at our command.
Boundaries checked, no errors to find,
In this garden of code, joy intertwined! 🌼


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

🧹 Outside diff range comments (4)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/viewVillage.js (3)

Line range hint 71-106: Enhance API integration robustness and maintainability.

Consider the following improvements for the data fetching implementation:

  1. Move API URLs to a configuration file to improve maintainability
  2. Add error handling and user feedback for failed API calls
  3. Show loading states during sequential data fetching

Consider creating an API configuration file:

// api-config.js
export const API_ENDPOINTS = {
  CENSUS_SEARCH: '/census-service/_search',
  EMPLOYEE_SEARCH: '/health-hrms/employees/_search'
};

Then update the API calls to use these configurations and add error handling:

const { isLoading, data, error } = Digit.Hooks.useCustomAPIHook({
  url: API_ENDPOINTS.CENSUS_SEARCH,
  body: {
    CensusSearchCriteria: {
      tenantId,
      source: microplanId,
      areaCodes: [boundaryCode]
    }
  },
  config: {
    enabled: true,
    select: (data) => data?.Census[0],
    onError: (error) => {
      Digit.Hooks.useToast.error("Failed to fetch census data");
    }
  }
});

Line range hint 147-169: Optimize state management and effect hooks.

The current implementation has several areas for improvement:

  1. Multiple useEffect hooks could lead to unnecessary re-renders
  2. Missing cleanup functions in useEffect
  3. Potential race conditions in state updates

Consider consolidating the state management:

useEffect(() => {
  const cleanup = { isMounted: true };
  
  const updateStates = async () => {
    if (!workflowData || !data) return;
    
    // Update assignee name
    if (employeeData?.user?.name && cleanup.isMounted) {
      setAssigneeName(employeeData.user.name);
    }
    
    // Update available actions
    const selectedState = workflowData.states?.find(
      (state) => state.state === data?.status
    );
    
    const availableActions = selectedState?.actions?.filter((action) =>
      action.roles.some((role) => userRoles.includes(role))
    );
    
    if (cleanup.isMounted) {
      setAvailableActionsForUser(availableActions || []);
    }
  };
  
  updateStates();
  
  return () => {
    cleanup.isMounted = false;
  };
}, [workflowData, data, employeeData, userRoles]);

Line range hint 182-277: Enhance accessibility and error handling.

The component needs improvements in accessibility and error handling:

  1. Add ARIA labels and roles
  2. Implement keyboard navigation
  3. Add error boundaries

Consider these improvements:

+import { ErrorBoundary } from '@egovernments/digit-ui-react-components';

+const VillageViewContent = () => {
  // ... existing component code ...
  return (
    <div role="main" aria-label={t('HCM_MICROPLAN_VILLAGE_VIEW_LABEL')}>
      <Button
+       aria-label={t('HCM_MICROPLAN_EDIT_POPULATION_BUTTON_LABEL')}
+       onKeyDown={(e) => e.key === 'Enter' && handleEditPopulationClick()}
        className="custom-class"
        icon="Edit"
        label="Edit Confirmed Population"
        onClick={handleEditPopulationClick}
      />
      // ... rest of the JSX
    </div>
  );
};

const VillageView = () => (
+  <ErrorBoundary fallback={<div>Something went wrong</div>}>
+    <VillageViewContent />
+  </ErrorBoundary>
);
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PopInbox.js (1)

Line range hint 516-524: Remove commented-out prop in Toast component.

The error prop is commented out but not used. Consider removing this commented code to maintain cleaner code.

 {showToast && (
   <Toast style={{ zIndex: 10001 }}
     label={showToast.label}
     type={showToast.key}
-    // error={showToast.key === "error"}
     transitionTime={showToast.transitionTime}
     onClose={() => setShowToast(null)}
   />
 )}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 7a622f5 and 5662067.

📒 Files selected for processing (4)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/PopInboxTable.js (5 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/editVillagePopulationPopUP.js (5 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PopInbox.js (1 hunks)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/viewVillage.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/PopInboxTable.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/pages/employee/PopInbox.js (1)

Pattern **/*.js: check

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

Pattern **/*.js: check

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

[error] 990-990: Unsafe usage of optional chaining.

If it short-circuits with 'undefined' the evaluation will throw TypeError here:

(lint/correctness/noUnsafeOptionalChaining)

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

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (4)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/pages/employee/PopInbox.js (1)

69-78: LGTM: Empty boundary validation implemented correctly.

The validation logic for empty boundary selection is well-implemented. It provides appropriate user feedback via toast message while preserving the original functionality when boundaries are selected.

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

146-146: ⚠️ Potential issue

Fix typo in translation key

There's a typographical error in the translation key HCM_MICROPLAN_EDIT_POPULATION_SEND_FOR_APPOVAL. It should be HCM_MICROPLAN_EDIT_POPULATION_SEND_FOR_APPROVAL.

Apply the following diff to correct the typo:

              label={t(`HCM_MICROPLAN_EDIT_POPULATION_SEND_FOR_APPOVAL`)}
+             label={t(`HCM_MICROPLAN_EDIT_POPULATION_SEND_FOR_APPROVAL`)}

Likely invalid or redundant comment.

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

1041-1041: Ensure proper handling of assignee data

In the INBOX_ASSIGNEE column, the selector uses props?.employeeNameData?.[row?.assignee] || t("ES_COMMON_NA"). Verify that employeeNameData is always defined and that row.assignee corresponds to a valid key. To avoid potential undefined values, consider providing a default mapping or handling cases where the assignee is not found.


1131-1131: Confirm the data source for DataTable

At line 1131, the data prop for the DataTable component is set to censusData. Ensure that this is the intended data source and that censusData contains the correct and updated data. If the data was previously coming from props.censusData, verify that all references are updated accordingly.

coderabbitai[bot]
coderabbitai bot previously approved these changes Oct 30, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range comments (1)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/PopInboxTable.js (1)

Line range hint 1095-1120: Consider passing data through props for flexibility

The data prop in the DataTable component is currently set to the hardcoded censusData. For better flexibility and reusability of the PopInboxTable component, consider passing censusData through props.

Apply this diff:

- data={censusData}
+ data={props.censusData}

Ensure that props.censusData is provided when using the PopInboxTable component.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 5662067 and 411056a.

📒 Files selected for processing (1)
  • health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/PopInboxTable.js (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/PopInboxTable.js (1)

Pattern **/*.js: check

🔇 Additional comments (1)
health/micro-ui/web/micro-ui-internals/packages/modules/microplan/src/components/PopInboxTable.js (1)

23-960: Avoid hardcoding data within the component

The censusData array is still hardcoded within the component. As previously mentioned, this can lead to maintainability issues and unnecessarily increase the bundle size. Consider fetching this data from an API, context, or passing it as props to make the component more dynamic and easier to maintain.

Comment on lines +1036 to 1038
selector: (row, index) => props?.employeeNameData?.[row?.assignee] || t("ES_COMMON_NA"),
sortable: true,
},
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure consistency in optional chaining usage

In the selector for the INBOX_ASSIGNEE column, optional chaining is used inconsistently. Consider updating the code to consistently use optional chaining for better readability and to prevent potential runtime errors.

Apply this diff:

- selector: (row, index) => props?.employeeNameData?.[row?.assignee] || t("ES_COMMON_NA"),
+ selector: (row) => props?.employeeNameData?.[row?.assignee] || t("ES_COMMON_NA"),

This change also removes the unused index parameter.

📝 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
selector: (row, index) => props?.employeeNameData?.[row?.assignee] || t("ES_COMMON_NA"),
sortable: true,
},
selector: (row) => props?.employeeNameData?.[row?.assignee] || t("ES_COMMON_NA"),
sortable: true,
},

Comment on lines +995 to +1014
selector: (row) => {
const fieldValue = row.additionalFields.find((f) => f.key === field.key)?.value || t("ES_COMMON_NA");

// Render a button if editable is true, otherwise render the field value as text
return row.additionalFields.find((f) => f.key === field.key)?.editable ? (
<div style={{ display: 'flex', alignItems: 'center' }}>
<span style={{ marginRight: '24px' }}>{fieldValue}</span>
{props.showEditColumn && <Button
onClick={() => {
setShowEditVillagePopup(row);
}}
variation="secondary"
icon={"Edit"}
size="medium"
/>}
</div>
) : (
fieldValue
);
},
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Optimize by storing the result of the find operation

The function row.additionalFields.find((f) => f.key === field.key) is called multiple times. To improve performance and readability, store its result in a variable to avoid redundant calls.

Apply this diff to refactor:

selector: (row) => {
+  const fieldData = row.additionalFields.find((f) => f.key === field.key);
+  const fieldValue = fieldData?.value || t("ES_COMMON_NA");

-  const fieldValue = row.additionalFields.find((f) => f.key === field.key)?.value || t("ES_COMMON_NA");

-  return row.additionalFields.find((f) => f.key === field.key)?.editable ? (
+  return fieldData?.editable ? (
      <div style={{ display: 'flex', alignItems: 'center' }}>
        <span style={{ marginRight: '24px' }}>{fieldValue}</span>
        {props.showEditColumn && (
          <Button
            onClick={() => {
              setShowEditVillagePopup(row);
            }}
            variation="secondary"
            icon={"Edit"}
            size="medium"
          />
        )}
      </div>
    ) : (
      fieldValue
    );
},
📝 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
selector: (row) => {
const fieldValue = row.additionalFields.find((f) => f.key === field.key)?.value || t("ES_COMMON_NA");
// Render a button if editable is true, otherwise render the field value as text
return row.additionalFields.find((f) => f.key === field.key)?.editable ? (
<div style={{ display: 'flex', alignItems: 'center' }}>
<span style={{ marginRight: '24px' }}>{fieldValue}</span>
{props.showEditColumn && <Button
onClick={() => {
setShowEditVillagePopup(row);
}}
variation="secondary"
icon={"Edit"}
size="medium"
/>}
</div>
) : (
fieldValue
);
},
selector: (row) => {
const fieldData = row.additionalFields.find((f) => f.key === field.key);
const fieldValue = fieldData?.value || t("ES_COMMON_NA");
return fieldData?.editable ? (
<div style={{ display: 'flex', alignItems: 'center' }}>
<span style={{ marginRight: '24px' }}>{fieldValue}</span>
{props.showEditColumn && <Button
onClick={() => {
setShowEditVillagePopup(row);
}}
variation="secondary"
icon={"Edit"}
size="medium"
/>}
</div>
) : (
fieldValue
);
},

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