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

Allow to fix statistic issue from repairs #22055

Merged
merged 6 commits into from
Sep 25, 2024
Merged

Allow to fix statistic issue from repairs #22055

merged 6 commits into from
Sep 25, 2024

Conversation

bramkragten
Copy link
Member

@bramkragten bramkragten commented Sep 22, 2024

Proposed change

For: home-assistant/core#122595

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New feature (thank you!)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Example configuration

Additional information

  • This PR fixes or closes issue: fixes #
  • This PR is related to issue or discussion:
  • Link to documentation pull request:

Checklist

  • The code change is tested and works locally.
  • There is no commented out code in this PR.
  • Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

Summary by CodeRabbit

  • New Features

    • Introduced enhanced handling for specific sensor-related issues, improving repair processes.
    • Added a new function to manage various statistics-related issues with user interaction prompts.
    • Implemented optional callback functions for dialog interactions, allowing for better user experience.
    • Updated error messages and added new entries for better context and clarity in the visual editor.
  • Bug Fixes

    • Streamlined dialog closing logic for improved functionality and separation of concerns.
  • Refactor

    • Consolidated methods for handling statistics issues to reduce redundancy and improve maintainability.

Copy link
Contributor

coderabbitai bot commented Sep 22, 2024

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes introduce enhancements to the handling of statistics issues within the developer tools panel. A new function, fixStatisticsIssue, is added to manage various types of statistics-related problems, consolidating the logic previously scattered across multiple methods. The dialog handling for specific issues has also been improved, with new methods introduced to streamline the closing process and manage cancellation actions. Additionally, several error messages and translations have been updated for clarity and context.

Changes

File Path Change Summary
src/panels/config/repairs/ha-config-repairs.ts Added a conditional block in the HaConfigRepairs class to handle sensor-related issues, including translation and statistics updates. Introduced the method fixStatisticsIssue.
src/panels/developer-tools/statistics/developer-tools-statistics.ts Refactored _fixIssue method in HaPanelDevStatistics class to consolidate logic into a single asynchronous call to fixStatisticsIssue, removing the switch-case structure and enhancing maintainability. Updated import statements accordingly.
src/panels/developer-tools/statistics/dialog-statistics-fix-units-changed.ts Updated dialog closing logic by adding _closeDialog and _cancel methods for better separation of concerns. Modified event listeners to utilize the new methods.
src/panels/developer-tools/statistics/fix-statistics.ts Introduced fixStatisticsIssue function to manage various statistics issues, providing user interactions for confirmation and alerts based on issue types.
src/panels/developer-tools/statistics/show-dialog-statistics-fix-units-changed.ts Updated DialogStatisticsUnitsChangedParams interface to include optional callback functions and modified showFixStatisticsUnitsChangedDialog to return a Promise, altering the control flow for better handling of dialog interactions.
src/translations/en.json Added new error messages and modified existing ones for clarity, including messages related to the visual editor and entity states. Implemented pluralization for numeric state triggers and simplified messages for deleting sections.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 597bf5d and 027a954.

Files selected for processing (5)
  • src/panels/config/repairs/ha-config-repairs.ts (2 hunks)
  • src/panels/developer-tools/statistics/developer-tools-statistics.ts (2 hunks)
  • src/panels/developer-tools/statistics/dialog-statistics-fix-units-changed.ts (5 hunks)
  • src/panels/developer-tools/statistics/fix-statistics.ts (1 hunks)
  • src/panels/developer-tools/statistics/show-dialog-statistics-fix-units-changed.ts (1 hunks)
Additional context used
Biome
src/panels/developer-tools/statistics/fix-statistics.ts

[error] 29-29: This code is unreachable

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

(lint/correctness/noUnreachable)


[error] 53-53: This code is unreachable

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

(lint/correctness/noUnreachable)


[error] 86-86: This code is unreachable

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

(lint/correctness/noUnreachable)


[error] 135-135: This code is unreachable

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

(lint/correctness/noUnreachable)


[error] 140-140: This code is unreachable

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

(lint/correctness/noUnreachable)

Additional comments not posted (11)
src/panels/developer-tools/statistics/dialog-statistics-fix-units-changed.ts (5)

30-31: LGTM!

Moving the cancellation logic to a separate private method _cancel improves the separation of concerns and makes the code more maintainable.


Line range hint 33-38: LGTM!

The new private method _closeDialog consolidates the dialog closing logic in a single place, making it easier to maintain and understand.


47-49: LGTM!

Updating the event listener to call _closeDialog instead of closeDialog ensures that the new centralized dialog closing logic is executed when the dialog is closed.


107-109: LGTM!

Updating the secondary action button's click event to call _cancel instead of closeDialog ensures that the cancellation logic is executed when the button is clicked.


118-121: LGTM!

The new _cancel method handles cancellation actions by invoking a cancelCallback (if defined) and then closing the dialog using the centralized _closeDialog method. Updating the _fixIssue method to call _closeDialog instead of closeDialog ensures consistency in the dialog closing logic.

Also applies to: 133-134

src/panels/developer-tools/statistics/show-dialog-statistics-fix-units-changed.ts (1)

9-10: Optional parameters enhance flexibility

The addition of the optional cancelCallback and making fixedCallback optional in the DialogStatisticsUnitsChangedParams interface improves the flexibility of the dialog handling, accommodating cases where callbacks may not be necessary.

src/panels/developer-tools/statistics/fix-statistics.ts (1)

137-139: Add missing import for showFixStatisticsUnitsChangedDialog

Ensure that the showFixStatisticsUnitsChangedDialog function is correctly imported to prevent runtime errors.

Run the following script to check if the import path is correct:

src/panels/config/repairs/ha-config-repairs.ts (1)

18-18: Import statement is correct

The import of fixStatisticsIssue from "../../developer-tools/statistics/fix-statistics" is properly specified.

src/panels/developer-tools/statistics/developer-tools-statistics.ts (3)

9-9: Approved import of LocalizeFunc.

The addition of the LocalizeFunc import ensures proper typing for localization functions.


22-22: Approved import of fixStatisticsIssue.

Importing fixStatisticsIssue allows for centralized handling of statistics issues.


261-279: Refactored _fixIssue method enhances maintainability.

The asynchronous refactoring of the _fixIssue method simplifies issue handling by delegating to fixStatisticsIssue. This reduces code redundancy and improves readability.

confirmText: localize("ui.common.delete"),
destructive: true,
confirm: async () => {
await clearStatistics(element.hass, [issue.data.statistic_id]);
Copy link
Contributor

Choose a reason for hiding this comment

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

Handle potential exceptions from asynchronous operations

The await clearStatistics() calls at lines 26, 83, and 132 perform asynchronous operations that might fail. It's good practice to handle potential exceptions to prevent unhandled promise rejections.

Consider wrapping the await calls in try...catch blocks:

           confirm: async () => {
-            await clearStatistics(element.hass, [issue.data.statistic_id]);
+            try {
+              await clearStatistics(element.hass, [issue.data.statistic_id]);
+            } catch (error) {
+              // Handle error (e.g., show an error dialog)
+              showAlertDialog(element, {
+                title: localize("ui.panel.developer-tools.tabs.statistics.fix_issue.error_title"),
+                text: localize("ui.panel.developer-tools.tabs.statistics.fix_issue.error_text", { error }),
+              });
+            }
           },

Also applies to: 83-83, 132-132

await clearStatistics(element.hass, [issue.data.statistic_id]);
},
});
break;
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove unreachable break statement after return

At line 86, the break; statement is unreachable because the function has already returned. Removing it will prevent confusion.

Apply this diff to fix the issue:

-          break;
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
break;
Tools
Biome

[error] 86-86: This code is unreachable

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

(lint/correctness/noUnreachable)

)}</a
>`,
});
break;
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove unreachable break statement after return

The break; statement at line 53 is unreachable due to the preceding return statement. Eliminating the break; statement will improve code clarity.

Apply this diff to fix the issue:

-          break;
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
break;
Tools
Biome

[error] 53-53: This code is unreachable

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

(lint/correctness/noUnreachable)

return showFixStatisticsUnitsChangedDialog(element, {
issue,
});
break;
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove unreachable break statement after return

At line 140, the break; statement is unreachable because of the preceding return. It can be safely removed to tidy up the code.

Apply this diff to fix the issue:

-          break;
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
break;
Tools
Biome

[error] 140-140: This code is unreachable

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

(lint/correctness/noUnreachable)

} from "../../lovelace/custom-card-helpers";
import { showFixStatisticsUnitsChangedDialog } from "./show-dialog-statistics-fix-units-changed";

export const fixStatisticsIssue = async (element, localize, issue) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Add explicit type annotations to function parameters

For improved type safety and code clarity, consider adding explicit type annotations to the fixStatisticsIssue function parameters: element, localize, and issue.

Apply this diff to add type annotations:

-export const fixStatisticsIssue = async (element, localize, issue) => {
+import { HomeAssistant } from "../../../types";
+import { LocalizeFunc } from "../../../common/translations/localize";
+import { StatisticsValidationIssue } from "../../../data/recorder";
+
+export const fixStatisticsIssue = async (
+  element: HTMLElement & { hass: HomeAssistant },
+  localize: LocalizeFunc,
+  issue: StatisticsValidationIssue
+) => {
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
export const fixStatisticsIssue = async (element, localize, issue) => {
import { HomeAssistant } from "../../../types";
import { LocalizeFunc } from "../../../common/translations/localize";
import { StatisticsValidationIssue } from "../../../data/recorder";
export const fixStatisticsIssue = async (
element: HTMLElement & { hass: HomeAssistant },
localize: LocalizeFunc,
issue: StatisticsValidationIssue
) => {

Comment on lines 137 to 142
[
"entity_not_recorded",
"entity_no_longer_recorded",
"unsupported_state_class",
"units_changed",
].includes(issue.translation_key)
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor translation keys into a constant

For better maintainability and readability, consider defining the array of translation keys as a constant outside the method.

Apply this refactor:

  1. Define the constant at the top of the file or outside the class:
const STATISTICS_ISSUE_TRANSLATION_KEYS = [
  "entity_not_recorded",
  "entity_no_longer_recorded",
  "unsupported_state_class",
  "units_changed",
];
  1. Update the condition in the _openShowMoreDialog method:
         issue.translation_key &&
-        [
-          "entity_not_recorded",
-          "entity_no_longer_recorded",
-          "unsupported_state_class",
-          "units_changed",
-        ].includes(issue.translation_key)
+        STATISTICS_ISSUE_TRANSLATION_KEYS.includes(issue.translation_key)

Comment on lines 134 to 157
} else if (
issue.domain === "sensor" &&
issue.translation_key &&
[
"entity_not_recorded",
"entity_no_longer_recorded",
"unsupported_state_class",
"units_changed",
].includes(issue.translation_key)
) {
const localize =
await this.hass.loadFragmentTranslation("developer-tools");
const data = await fetchRepairsIssueData(
this.hass.connection,
issue.domain,
issue.issue_id
);
if ("issue_type" in data.issue_data) {
await fixStatisticsIssue(this, localize, {
type: data.issue_data.issue_type,
data: data.issue_data,
});
this.hass.callWS({ type: "recorder/update_statistics_issues" });
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Add missing await for this.hass.callWS

In line 156, the this.hass.callWS method returns a Promise. To ensure the WebSocket call completes before proceeding, you should use await when calling this.hass.callWS(...).

Apply this diff to fix the issue:

             await fixStatisticsIssue(this, localize, {
               type: data.issue_data.issue_type,
               data: data.issue_data,
             });
-            this.hass.callWS({ type: "recorder/update_statistics_issues" });
+            await this.hass.callWS({ type: "recorder/update_statistics_issues" });
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
} else if (
issue.domain === "sensor" &&
issue.translation_key &&
[
"entity_not_recorded",
"entity_no_longer_recorded",
"unsupported_state_class",
"units_changed",
].includes(issue.translation_key)
) {
const localize =
await this.hass.loadFragmentTranslation("developer-tools");
const data = await fetchRepairsIssueData(
this.hass.connection,
issue.domain,
issue.issue_id
);
if ("issue_type" in data.issue_data) {
await fixStatisticsIssue(this, localize, {
type: data.issue_data.issue_type,
data: data.issue_data,
});
this.hass.callWS({ type: "recorder/update_statistics_issues" });
}
} else if (
issue.domain === "sensor" &&
issue.translation_key &&
[
"entity_not_recorded",
"entity_no_longer_recorded",
"unsupported_state_class",
"units_changed",
].includes(issue.translation_key)
) {
const localize =
await this.hass.loadFragmentTranslation("developer-tools");
const data = await fetchRepairsIssueData(
this.hass.connection,
issue.domain,
issue.issue_id
);
if ("issue_type" in data.issue_data) {
await fixStatisticsIssue(this, localize, {
type: data.issue_data.issue_type,
data: data.issue_data,
});
await this.hass.callWS({ type: "recorder/update_statistics_issues" });
}

Comment on lines 138 to 139
"entity_not_recorded",
"entity_no_longer_recorded",
Copy link
Collaborator

Choose a reason for hiding this comment

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

Core doesn't create issues for these two

Copy link
Member Author

Choose a reason for hiding this comment

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

Doesn't harm having them here, rather have all of it 🙃

piitaya
piitaya previously approved these changes Sep 25, 2024
src/translations/en.json Outdated Show resolved Hide resolved
src/translations/en.json Outdated Show resolved Hide resolved
src/translations/en.json Outdated Show resolved Hide resolved
@home-assistant home-assistant bot marked this pull request as draft September 25, 2024 13:06
@home-assistant
Copy link

Please take a look at the requested changes, and use the Ready for review button when you are done, thanks 👍

Learn more about our pull request process.

@bramkragten bramkragten marked this pull request as ready for review September 25, 2024 13:11
@home-assistant home-assistant bot requested a review from piitaya September 25, 2024 13:11
@piitaya piitaya merged commit 7658123 into dev Sep 25, 2024
14 checks passed
@piitaya piitaya deleted the fix-statistics-issue branch September 25, 2024 13:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants