diff --git a/src/data/energy.ts b/src/data/energy.ts index 61d23aca0e53..c4d66110746e 100644 --- a/src/data/energy.ts +++ b/src/data/energy.ts @@ -173,7 +173,7 @@ export interface WaterSourceTypeEnergyPreference { unit_of_measurement?: string | null; } -type EnergySource = +export type EnergySource = | SolarSourceTypeEnergyPreference | GridSourceTypeEnergyPreference | BatterySourceTypeEnergyPreference diff --git a/src/panels/config/energy/components/ha-energy-grid-settings.ts b/src/panels/config/energy/components/ha-energy-grid-settings.ts index eeb6234e9935..fd8dfa2c9e6b 100644 --- a/src/panels/config/energy/components/ha-energy-grid-settings.ts +++ b/src/panels/config/energy/components/ha-energy-grid-settings.ts @@ -22,6 +22,7 @@ import { EnergyPreferencesValidation, energySourcesByType, EnergyValidationIssue, + EnergySource, FlowFromGridSourceEnergyPreference, FlowToGridSourceEnergyPreference, GridSourceTypeEnergyPreference, @@ -449,11 +450,8 @@ export class EnergyGridSettings extends LitElement { ), }; - try { - await this._savePreferences(preferences); - } catch (err: any) { - showAlertDialog(this, { title: `Failed to save config: ${err.message}` }); - } + const cleanedPreferences = this._removeEmptySources(preferences); + await this._savePreferences(cleanedPreferences); } private async _deleteToSource(ev) { @@ -479,18 +477,37 @@ export class EnergyGridSettings extends LitElement { ), }; + const cleanedPreferences = this._removeEmptySources(preferences); + await this._savePreferences(cleanedPreferences); + } + + private _removeEmptySources(preferences: EnergyPreferences) { + // Check if grid sources became an empty type and remove if so + preferences.energy_sources = preferences.energy_sources.reduce< + EnergySource[] + >((acc, source) => { + if ( + source.type !== "grid" || + source.flow_from.length > 0 || + source.flow_to.length > 0 + ) { + acc.push(source); + } + return acc; + }, []); + + return preferences; + } + + private async _savePreferences(preferences: EnergyPreferences) { try { - await this._savePreferences(preferences); + const result = await saveEnergyPreferences(this.hass, preferences); + fireEvent(this, "value-changed", { value: result }); } catch (err: any) { showAlertDialog(this, { title: `Failed to save config: ${err.message}` }); } } - private async _savePreferences(preferences: EnergyPreferences) { - const result = await saveEnergyPreferences(this.hass, preferences); - fireEvent(this, "value-changed", { value: result }); - } - static get styles(): CSSResultGroup { return [haStyle, energyCardStyles]; }