Compare commits

...
Author SHA1 Message Date
Petar Petrov c21822fe9b Add fixed costs to the energy dashboard 2026-11-16 18:10:42 +02:00
19 changed files with 999 additions and 26 deletions

No files matched your search

+1
View File
@@ -207,6 +207,7 @@ export class HaEmbedProvider extends LitElement {
}));
hass.mockWS("energy/info", (): EnergyInfo => ({
cost_sensors: {},
fixed_cost_sensors: {},
solar_forecast_domains: [],
}));
this._applyColorScheme();
+3
View File
@@ -120,10 +120,12 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
stat_consumption: "sensor.gas_heat_pump",
},
],
fixed_costs: [],
};
hass.mockWS("energy/get_prefs", (): EnergyPreferences => prefs);
hass.mockWS("energy/info", (): EnergyInfo => ({
cost_sensors: {},
fixed_cost_sensors: {},
solar_forecast_domains: [],
}));
hass.mockWS("energy/validate", () => ({
@@ -131,6 +133,7 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
device_consumption: prefs.device_consumption.map(() => []),
device_consumption_water: prefs.device_consumption_water.map(() => []),
device_consumption_gas: prefs.device_consumption_gas.map(() => []),
fixed_costs: prefs.fixed_costs.map(() => []),
}));
hass.mockWS(
"energy/fossil_energy_consumption",
+54
View File
@@ -32,6 +32,7 @@ import type { EntityNameItem } from "../common/entity/entity_name_config";
import { formatNumberWithUnit } from "../common/number/format_number";
import { normalizeValueBySIPrefix } from "../common/number/normalize-by-si-prefix";
import { groupBy } from "../common/util/group-by";
import { generateUuidV4 } from "../common/util/uuid";
import type { HomeAssistant, HomeAssistantRegistries } from "../types";
import { fileDownload } from "../util/file_download";
import type {
@@ -340,6 +341,31 @@ export interface WaterSourceTypeEnergyPreference {
name?: string;
}
export type FixedCostType = "grid" | "gas" | "water";
export type FixedCostPeriod = "day" | "month" | "year";
export interface FixedCostEnergyPreference {
id: string;
type: FixedCostType;
name: string;
// Charged at the start of each period, exactly one of these is set
number_amount: number | null;
entity_amount: string | null;
period: FixedCostPeriod;
}
export const emptyFixedCostEnergyPreference = (
type: FixedCostType
): FixedCostEnergyPreference => ({
id: generateUuidV4(),
type,
name: "",
number_amount: null,
entity_amount: null,
period: "day",
});
export type EnergySource =
| SolarSourceTypeEnergyPreference
| HomeSourceTypeEnergyPreference
@@ -353,6 +379,7 @@ export interface EnergyPreferences {
device_consumption: DeviceConsumptionEnergyPreference[];
device_consumption_water: DeviceConsumptionEnergyPreference[];
device_consumption_gas: DeviceConsumptionEnergyPreference[];
fixed_costs: FixedCostEnergyPreference[];
}
export const EMPTY_PREFERENCES: EnergyPreferences = {
@@ -360,10 +387,13 @@ export const EMPTY_PREFERENCES: EnergyPreferences = {
device_consumption: [],
device_consumption_water: [],
device_consumption_gas: [],
fixed_costs: [],
};
export interface EnergyInfo {
cost_sensors: Record<string, string>;
// Fixed cost id to the entity ID of its cost sensor
fixed_cost_sensors: Record<string, string>;
solar_forecast_domains: string[];
}
@@ -378,6 +408,7 @@ export interface EnergyPreferencesValidation {
device_consumption: EnergyValidationIssue[][];
device_consumption_water: EnergyValidationIssue[][];
device_consumption_gas: EnergyValidationIssue[][];
fixed_costs: EnergyValidationIssue[][];
}
export const getEnergyInfo = (callWS: HomeAssistant["callWS"]) =>
@@ -440,6 +471,13 @@ export interface EnergySourceByType {
export const energySourcesByType = (prefs: EnergyPreferences) =>
groupBy(prefs.energy_sources, (item) => item.type) as EnergySourceByType;
export type FixedCostsByType = Partial<
Record<FixedCostType, FixedCostEnergyPreference[]>
>;
export const fixedCostsByType = (prefs: EnergyPreferences) =>
groupBy(prefs.fixed_costs, (item) => item.type) as FixedCostsByType;
const ENERGY_DEVICE_NAME = [
{ type: "parent_device" },
{ type: "device" },
@@ -715,6 +753,15 @@ export const getReferencedStatisticIds = (
...prefs.device_consumption_gas.map((d) => d.stat_consumption)
);
}
for (const fixedCost of prefs.fixed_costs) {
if (includeTypes && !includeTypes.includes(fixedCost.type)) {
continue;
}
const costStatId = info.fixed_cost_sensors[fixedCost.id];
if (costStatId) {
statIDs.push(costStatId);
}
}
return statIDs;
};
@@ -2895,6 +2942,13 @@ export const downloadEnergyData = (
printCategory("device_consumption_gas", gasDevices, state.gasUnit);
}
energyData.prefs.fixed_costs.forEach((fixedCost) => {
const costId = state.info.fixed_cost_sensors[fixedCost.id];
if (costId) {
processStat(costId, `${fixedCost.type}_fixed_cost`, currency);
}
});
const { summedData } = getSummedData(state);
const { consumption } = computeConsumptionData(summedData, undefined);
@@ -0,0 +1,381 @@
import { mdiCashClock, mdiDelete, mdiPlus } from "@mdi/js";
import type { ContextType } from "@lit/context";
import type { HassEntities } from "home-assistant-js-websocket";
import type { CSSResultGroup, TemplateResult } from "lit";
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { consume } from "../../../../common/decorators/consume";
import { preserveUnchangedEntityStatesRecord } from "../../../../common/decorators/consume-context-entry";
import { transform } from "../../../../common/decorators/transform";
import type { HASSDomCurrentTargetEvent } from "../../../../common/dom/fire_event";
import { fireEvent } from "../../../../common/dom/fire_event";
import { stopPropagation } from "../../../../common/dom/stop_propagation";
import { formatNumber } from "../../../../common/number/format_number";
import "../../../../components/automation/ha-automation-row";
import "../../../../components/ha-button";
import "../../../../components/ha-card";
import "../../../../components/ha-icon-button";
import "../../../../components/ha-svg-icon";
import {
configContext,
formattersContext,
internationalizationContext,
statesContext,
} from "../../../../data/context";
import type {
EnergyPreferences,
EnergyPreferencesValidation,
EnergyValidationIssue,
FixedCostEnergyPreference,
FixedCostType,
} from "../../../../data/energy";
import { saveEnergyPreferences } from "../../../../data/energy";
import { getStatisticLabel } from "../../../../data/recorder";
import {
showAlertDialog,
showConfirmationDialog,
} from "../../../../dialogs/generic/show-dialog-box";
import { haStyle } from "../../../../resources/styles";
import type {
HomeAssistant,
HomeAssistantConfig,
HomeAssistantFormatters,
} from "../../../../types";
import { showEnergySettingsDialog } from "../dialogs/show-dialogs-energy";
import type { EnergyEditorConfig } from "../editors/energy-editor";
import "../ha-energy-editor-page";
import type { EnergyEditorPageConfig } from "../ha-energy-editor-page";
import "./ha-energy-validation-result";
import { energyCardStyles } from "./styles";
type CostElement = HTMLElement & { cost: FixedCostEnergyPreference };
@customElement("ha-energy-fixed-cost-settings")
export class EnergyFixedCostSettings extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public type!: FixedCostType;
@property({ attribute: false })
public preferences!: EnergyPreferences;
@property({ attribute: false })
public validationResult?: EnergyPreferencesValidation;
/** Path of the list page, editors open on pages under it instead of dialogs */
@property({ attribute: false }) public listPath?: string;
/** Shows the editor page of the item with this key, or `new` to add one */
@property({ attribute: false }) public editKey?: string;
@property({ type: Boolean }) public narrow = false;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, string>({
transformer: ({ config }) => config.currency,
})
private _currency!: string;
@state()
@consume({ context: formattersContext, subscribe: true })
@transform<
HomeAssistantFormatters,
HomeAssistantFormatters["formatEntityName"]
>({
transformer: ({ formatEntityName }) => formatEntityName,
})
private _formatEntityName!: HomeAssistantFormatters["formatEntityName"];
// Only the amount entities, so other state changes don't render
@state()
@consume({ context: statesContext, subscribe: true })
@transform<HassEntities, HassEntities>({
transformer: function (this: EnergyFixedCostSettings, states) {
const amountStates: HassEntities = {};
for (const cost of this._costs()) {
const entityId = cost.entity_amount;
if (entityId && states?.[entityId]) {
amountStates[entityId] = states[entityId];
}
}
return preserveUnchangedEntityStatesRecord(
this._amountStates,
amountStates
);
},
watch: ["preferences", "type"],
})
private _amountStates?: HassEntities;
protected render(): TemplateResult {
if (this.listPath && this.editKey !== undefined) {
return html`<ha-energy-editor-page
.hass=${this.hass}
.narrow=${this.narrow}
.backPath=${this.listPath}
.config=${this._editorPage(this.editKey)}
></ha-energy-editor-page>`;
}
const costs: FixedCostEnergyPreference[] = [];
const validation: EnergyValidationIssue[][] = [];
this.preferences.fixed_costs.forEach((cost, idx) => {
if (cost.type !== this.type) {
return;
}
costs.push(cost);
const issues = this.validationResult?.fixed_costs[idx];
if (issues) {
validation.push(issues);
}
});
return html`
<ha-card>
<h1 class="card-header">
<ha-svg-icon .path=${mdiCashClock}></ha-svg-icon>
${this._i18n.localize("ui.panel.config.energy.fixed_costs.title")}
</h1>
<div class="card-content">
<p>
${this._i18n.localize("ui.panel.config.energy.fixed_costs.sub")}
</p>
${validation.map(
(issues) => html`
<ha-energy-validation-result
.hass=${this.hass}
.issues=${issues}
></ha-energy-validation-result>
`
)}
${
costs.length > 0
? html`
<div class="items">
${costs.map(
(cost) => html`
<ha-card outlined>
<ha-automation-row
.cost=${cost}
.href=${this._editorHref(cost)}
@click=${this.listPath ? nothing : this._editCost}
>
<ha-svg-icon
slot="leading-icon"
.path=${mdiCashClock}
></ha-svg-icon>
<div slot="header" class="row-header">
<span class="label">${cost.name}</span>
<span class="label secondary"
>${this._amountPerPeriod(cost)}</span
>
</div>
<ha-icon-button
slot="icons"
.label=${this._i18n.localize(
"ui.panel.config.energy.fixed_costs.delete_fixed_cost"
)}
.path=${mdiDelete}
.cost=${cost}
@click=${this._deleteCostClicked}
@keydown=${stopPropagation}
></ha-icon-button>
</ha-automation-row>
</ha-card>
`
)}
</div>
`
: nothing
}
<ha-button
.href=${this._editorHref()}
@click=${this.listPath ? nothing : this._addCost}
appearance="filled"
size="s"
>
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon>
${this._i18n.localize(
"ui.panel.config.energy.fixed_costs.add_fixed_cost"
)}
</ha-button>
</div>
</ha-card>
`;
}
private _costs(): FixedCostEnergyPreference[] {
return (this.preferences?.fixed_costs ?? []).filter(
(cost) => cost.type === this.type
);
}
private _amountPerPeriod(cost: FixedCostEnergyPreference): string {
const amount = cost.entity_amount
? getStatisticLabel(
this._amountStates ?? {},
this._formatEntityName,
cost.entity_amount,
undefined
)
: formatNumber(cost.number_amount ?? 0, this._i18n.locale, {
style: "currency",
currency: this._currency,
});
return this._i18n.localize(
`ui.panel.config.energy.fixed_costs.amount_per_period.${cost.period}`,
{ amount }
);
}
private _addCost() {
this._openEditor();
}
private _editCost(ev: HASSDomCurrentTargetEvent<CostElement>) {
this._openEditor(ev.currentTarget.cost);
}
private _openEditor(cost?: FixedCostEnergyPreference) {
showEnergySettingsDialog(this, { editor: this._editorConfig(cost) });
}
private _editorHref(cost?: FixedCostEnergyPreference) {
return this.listPath
? `${this.listPath}/fixed_cost/${cost ? encodeURIComponent(cost.id) : "new"}`
: undefined;
}
private _editorConfig(cost?: FixedCostEnergyPreference): EnergyEditorConfig {
return {
kind: "fixed_cost",
params: {
cost: cost ? { ...cost } : undefined,
type: this.type,
saveCallback: (newCost) => this._saveCost(newCost),
},
};
}
private _costIndex(cost: FixedCostEnergyPreference) {
return this.preferences.fixed_costs.findIndex(
(item) => item.id === cost.id
);
}
// Kept per item: a save replaces the preferences right before the page leaves
private _editorPage = memoizeOne(
(key: string): EnergyEditorPageConfig | undefined => {
if (key === "new") {
return this._pageConfig(this._editorConfig());
}
const cost = this._costs().find((item) => item.id === key);
return cost && this._pageConfig(this._editorConfig(cost), cost);
}
);
private _pageConfig(
editor: EnergyEditorConfig,
cost?: FixedCostEnergyPreference
): EnergyEditorPageConfig {
if (!cost) {
return {
editor,
title: this._i18n.localize(
"ui.panel.config.energy.fixed_costs.add_fixed_cost"
),
};
}
return {
editor,
title: cost.name,
delete: {
label: this._i18n.localize(
"ui.panel.config.energy.fixed_costs.delete_fixed_cost"
),
action: () => this._deleteCost(cost),
},
};
}
private async _saveCost(cost: FixedCostEnergyPreference) {
const costs = [...this.preferences.fixed_costs];
const index = this._costIndex(cost);
if (index === -1) {
costs.push(cost);
} else {
costs[index] = cost;
}
await this._savePreferences({ ...this.preferences, fixed_costs: costs });
}
private _deleteCostClicked(ev: HASSDomCurrentTargetEvent<CostElement>) {
ev.stopPropagation();
this._deleteCost(ev.currentTarget.cost);
}
private async _deleteCost(cost: FixedCostEnergyPreference): Promise<boolean> {
if (
!(await showConfirmationDialog(this, {
title: this._i18n.localize(
"ui.panel.config.energy.fixed_costs.delete_confirm_title"
),
text: this._i18n.localize(
"ui.panel.config.energy.fixed_costs.delete_confirm_text",
{ name: cost.name }
),
confirmText: this._i18n.localize("ui.common.delete"),
destructive: true,
}))
) {
return false;
}
const index = this._costIndex(cost);
if (index === -1) {
return false;
}
try {
await this._savePreferences({
...this.preferences,
fixed_costs: this.preferences.fixed_costs.filter(
(_cost, idx) => idx !== index
),
});
} catch (err: any) {
showAlertDialog(this, {
title: this._i18n.localize(
"ui.panel.config.energy.save_config_failed",
{ error: err.message }
),
});
return false;
}
return true;
}
private async _savePreferences(preferences: EnergyPreferences) {
const result = await saveEnergyPreferences(this.hass, preferences);
fireEvent(this, "value-changed", { value: result });
return result;
}
static get styles(): CSSResultGroup {
return [haStyle, energyCardStyles];
}
}
declare global {
interface HTMLElementTagNameMap {
"ha-energy-fixed-cost-settings": EnergyFixedCostSettings;
}
}
@@ -27,6 +27,7 @@ const HEADERS = {
water: "ui.panel.config.energy.device_consumption_water.dialog.header",
gas: "ui.panel.config.energy.device_consumption_gas.dialog.header",
},
fixed_cost: "ui.panel.config.energy.fixed_costs.dialog.header",
} as const;
@customElement("dialog-energy-settings")
@@ -7,6 +7,8 @@ import type {
DeviceConsumptionEnergyPreference,
EnergyGasUnitClass,
EnergyInfo,
FixedCostEnergyPreference,
FixedCostType,
GasSourceTypeEnergyPreference,
GridSourceTypeEnergyPreference,
HomeSourceTypeEnergyPreference,
@@ -75,6 +77,12 @@ export interface EnergyWaterGasDeviceEditorParams extends EnergyDeviceEditorPara
allowedUnitClass?: EnergyGasUnitClass;
}
export interface EnergyFixedCostEditorParams {
cost?: FixedCostEnergyPreference;
type: FixedCostType;
saveCallback: (cost: FixedCostEnergyPreference) => Promise<void>;
}
export type EnergyEditorConfig =
| { kind: "grid"; params: EnergyGridSourceEditorParams }
| { kind: "solar"; params: EnergySolarSourceEditorParams }
@@ -83,7 +91,8 @@ export type EnergyEditorConfig =
| { kind: "device"; params: EnergyDeviceEditorParams }
| { kind: "gas"; params: EnergyGasSourceEditorParams }
| { kind: "water"; params: EnergyWaterSourceEditorParams }
| { kind: "water_gas_device"; params: EnergyWaterGasDeviceEditorParams };
| { kind: "water_gas_device"; params: EnergyWaterGasDeviceEditorParams }
| { kind: "fixed_cost"; params: EnergyFixedCostEditorParams };
export interface EnergyEditorStatus {
/** Whether there are changes to save */
@@ -0,0 +1,294 @@
import type { CSSResultGroup, PropertyValues } from "lit";
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consume } from "../../../../common/decorators/consume";
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
import { transform } from "../../../../common/decorators/transform";
import type { HASSDomCurrentTargetEvent } from "../../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import "../../../../components/entity/ha-entity-picker";
import "../../../../components/ha-alert";
import "../../../../components/ha-markdown";
import "../../../../components/ha-select";
import type {
HaSelectOption,
HaSelectSelectEvent,
} from "../../../../components/ha-select";
import "../../../../components/input/ha-input";
import type { HaInput } from "../../../../components/input/ha-input";
import { configContext } from "../../../../data/context";
import type {
FixedCostEnergyPreference,
FixedCostPeriod,
} from "../../../../data/energy";
import { emptyFixedCostEnergyPreference } from "../../../../data/energy";
import { DirtyStateProviderMixin } from "../../../../mixins/dirty-state-provider-mixin";
import type { HomeAssistantConfig, ValueChangedEvent } from "../../../../types";
import type {
EnergyEditorStatus,
EnergyFixedCostEditorParams,
} from "./energy-editor";
import { EnergyEditorMixin, energyEditorStyles } from "./energy-editor";
type AmountType = "number" | "entity";
interface FixedCostFormState {
cost: FixedCostEnergyPreference;
amountType: AmountType;
}
const PERIODS: FixedCostPeriod[] = ["day", "month", "year"];
@customElement("ha-energy-fixed-cost-editor")
export class HaEnergyFixedCostEditor extends EnergyEditorMixin(
DirtyStateProviderMixin<FixedCostFormState>()(LitElement)
) {
@property({ attribute: false })
public params!: EnergyFixedCostEditorParams;
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, string>({
transformer: ({ config }) => config.currency,
})
private _currency!: string;
@state() private _cost?: FixedCostEnergyPreference;
@state() private _amountType: AmountType = "number";
@state() private _numberAmountText = "";
@state() private _error?: string;
@state() private _saving = false;
protected willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
if (changedProps.has("params")) {
this._init();
}
}
private _init() {
const params = this.params;
this._error = undefined;
this._saving = false;
this._cost = params.cost
? { ...params.cost }
: emptyFixedCostEnergyPreference(params.type);
this._amountType = this._cost.entity_amount ? "entity" : "number";
this._numberAmountText =
typeof this._cost.number_amount === "number"
? String(this._cost.number_amount)
: "";
this._initDirtyTracking(
{ type: "deep" },
{ cost: this._cost, amountType: this._amountType }
);
}
protected get editorStatus(): EnergyEditorStatus {
const cost = this._cost;
return {
dirty: this.isDirtyState,
valid:
!!cost?.name.trim() &&
(this._amountType === "number"
? Number.isFinite(cost.number_amount)
: !!cost.entity_amount),
saving: this._saving,
};
}
protected render() {
if (!this._cost) {
return nothing;
}
return html`
${
this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: nothing
}
<ha-input
.label=${this._localize(
"ui.panel.config.energy.fixed_costs.dialog.name"
)}
type="text"
required
.disabled=${this._saving}
.value=${this._cost.name}
@input=${this._nameChanged}
></ha-input>
<div class="group">
<ha-select
.label=${this._localize(
"ui.panel.config.energy.fixed_costs.dialog.amount_type"
)}
.value=${this._amountType}
.options=${this._amountTypeOptions()}
.disabled=${this._saving}
@selected=${this._amountTypeChanged}
></ha-select>
${this._renderAmount()}
</div>
<ha-select
.label=${this._localize(
"ui.panel.config.energy.fixed_costs.dialog.period"
)}
.helper=${this._localize(
"ui.panel.config.energy.fixed_costs.dialog.period_helper"
)}
.value=${this._cost.period}
.options=${this._periodOptions()}
.disabled=${this._saving}
@selected=${this._periodChanged}
></ha-select>
`;
}
private _renderAmount() {
if (this._amountType === "entity") {
return html`<ha-entity-picker
.disabled=${this._saving}
include-domains='["sensor", "input_number"]'
.value=${this._cost!.entity_amount ?? undefined}
.label=${this._localize(
"ui.panel.config.energy.fixed_costs.dialog.amount_entity_label"
)}
.helper=${html`<ha-markdown
.content=${this._localize(
"ui.panel.config.energy.fixed_costs.dialog.amount_entity_helper",
{ currency: this._currency, period: this._cost!.period }
)}
></ha-markdown>`}
@value-changed=${this._amountEntityChanged}
></ha-entity-picker>`;
}
return html`<ha-input
.disabled=${this._saving}
.label=${this._localize(
"ui.panel.config.energy.fixed_costs.dialog.amount_number_label"
)}
.hint=${this._localize(
"ui.panel.config.energy.fixed_costs.dialog.amount_number_helper"
)}
step="any"
type="number"
required
auto-validate
.value=${this._numberAmountText}
@input=${this._numberAmountChanged}
>
<span slot="end">${this._currency}</span>
</ha-input>`;
}
private _amountTypeOptions(): HaSelectOption[] {
return [
{
value: "number",
label: this._localize(
"ui.panel.config.energy.fixed_costs.dialog.amount_number"
),
},
{
value: "entity",
label: this._localize(
"ui.panel.config.energy.fixed_costs.dialog.amount_entity"
),
},
];
}
private _periodOptions(): HaSelectOption[] {
return PERIODS.map((period) => ({
value: period,
label: this._localize(
`ui.panel.config.energy.fixed_costs.dialog.period_${period}`
),
}));
}
private _nameChanged(ev: HASSDomCurrentTargetEvent<HaInput>) {
this._cost = { ...this._cost!, name: ev.currentTarget.value ?? "" };
this._updateFormDirtyState();
}
private _amountTypeChanged(ev: HaSelectSelectEvent) {
this._amountType = ev.detail.value as AmountType;
this._updateFormDirtyState();
}
private _numberAmountChanged(ev: HASSDomCurrentTargetEvent<HaInput>) {
// Render the typed text so partial input such as "-" is not rewritten
this._numberAmountText = ev.currentTarget.value ?? "";
const amount = parseFloat(this._numberAmountText);
this._cost = {
...this._cost!,
number_amount: Number.isFinite(amount) ? amount : null,
};
this._updateFormDirtyState();
}
private _amountEntityChanged(ev: ValueChangedEvent<string>) {
this._cost = { ...this._cost!, entity_amount: ev.detail.value || null };
this._updateFormDirtyState();
}
private _periodChanged(ev: HaSelectSelectEvent) {
this._cost = {
...this._cost!,
period: ev.detail.value as FixedCostPeriod,
};
this._updateFormDirtyState();
}
private _updateFormDirtyState(): void {
this._updateDirtyState({ cost: this._cost!, amountType: this._amountType });
}
public async save(): Promise<boolean> {
const params = this.params;
const cost = this._cost!;
const isNumber = this._amountType === "number";
const isCurrent = () => this.params === params && this.isConnected;
this._error = undefined;
this._saving = true;
try {
await params.saveCallback({
...cost,
name: cost.name.trim(),
number_amount: isNumber ? cost.number_amount : null,
entity_amount: isNumber ? null : cost.entity_amount,
});
if (isCurrent()) {
this._markDirtyStateClean();
}
return true;
} catch (err: any) {
if (isCurrent()) {
this._error = err.message;
}
return false;
} finally {
if (isCurrent()) {
this._saving = false;
}
}
}
static get styles(): CSSResultGroup {
return energyEditorStyles;
}
}
declare global {
interface HTMLElementTagNameMap {
"ha-energy-fixed-cost-editor": HaEnergyFixedCostEditor;
}
}
@@ -2,6 +2,7 @@ import { html, nothing } from "lit";
import type { EnergyEditorConfig } from "./energy-editor";
import "./ha-energy-battery-source-editor";
import "./ha-energy-device-editor";
import "./ha-energy-fixed-cost-editor";
import "./ha-energy-gas-source-editor";
import "./ha-energy-grid-source-editor";
import "./ha-energy-home-source-editor";
@@ -51,6 +52,11 @@ export const renderEnergyEditor = (config: EnergyEditorConfig) => {
class="energy-editor"
.params=${config.params}
></ha-energy-water-gas-device-editor>`;
case "fixed_cost":
return html`<ha-energy-fixed-cost-editor
class="energy-editor"
.params=${config.params}
></ha-energy-fixed-cost-editor>`;
default:
return nothing;
}
+50 -4
View File
@@ -15,6 +15,7 @@ import type {
EnergyPreferencesValidation,
EnergyInfo,
EnergyPreferences,
FixedCostType,
} from "../../../data/energy";
import {
getEnergyPreferenceValidation,
@@ -31,6 +32,7 @@ import type { HomeAssistant, Route } from "../../../types";
import "../../../components/ha-alert";
import "./components/ha-energy-device-settings";
import "./components/ha-energy-device-settings-water-gas";
import "./components/ha-energy-fixed-cost-settings";
import "./components/ha-energy-grid-settings";
import "./components/ha-energy-solar-settings";
import "./components/ha-energy-home-settings";
@@ -47,6 +49,7 @@ const INITIAL_CONFIG: EnergyPreferences = {
device_consumption: [],
device_consumption_water: [],
device_consumption_gas: [],
fixed_costs: [],
};
const TABS: PageNavigation[] = [
@@ -72,9 +75,15 @@ const TABS: PageNavigation[] = [
// Editor pages are at <tab>/<kind>/<key>, with `new` as the key of a new item
const EDITOR_KINDS: Record<string, string[]> = {
electricity: ["grid", "solar", "home", "battery", "device"],
gas: ["gas", "device"],
water: ["water", "device"],
electricity: ["grid", "solar", "home", "battery", "device", "fixed_cost"],
gas: ["gas", "device", "fixed_cost"],
water: ["water", "device", "fixed_cost"],
};
const FIXED_COST_TYPES: Record<string, FixedCostType> = {
electricity: "grid",
gas: "gas",
water: "water",
};
@customElement("ha-config-energy")
@@ -196,6 +205,7 @@ class HaConfigEnergy extends LitElement {
.validationResult=${this._validationResult}
@value-changed=${this._prefsChanged}
></ha-energy-grid-settings>
${this._renderFixedCostSettings("grid", listPath)}
<ha-energy-solar-settings
.hass=${this.hass}
.preferences=${this._preferences!}
@@ -239,6 +249,7 @@ class HaConfigEnergy extends LitElement {
.validationResult=${this._validationResult}
@value-changed=${this._prefsChanged}
></ha-energy-gas-settings>
${this._renderFixedCostSettings("gas", listPath)}
<ha-energy-device-settings-water-gas
.hass=${this.hass}
.resource=${"gas"}
@@ -259,6 +270,7 @@ class HaConfigEnergy extends LitElement {
.validationResult=${this._validationResult}
@value-changed=${this._prefsChanged}
></ha-energy-water-settings>
${this._renderFixedCostSettings("water", listPath)}
<ha-energy-device-settings-water-gas
.hass=${this.hass}
.resource=${"water"}
@@ -274,6 +286,26 @@ class HaConfigEnergy extends LitElement {
}
}
private _renderFixedCostSettings(type: FixedCostType, listPath: string) {
const prefs = this._preferences!;
// The dashboard only shows fixed costs next to a source of their type,
// without one the card stays so existing costs can be deleted
if (
!prefs.energy_sources.some((source) => source.type === type) &&
!prefs.fixed_costs.some((cost) => cost.type === type)
) {
return nothing;
}
return html`<ha-energy-fixed-cost-settings
.hass=${this.hass}
.type=${type}
.preferences=${prefs}
.listPath=${listPath}
.validationResult=${this._validationResult}
@value-changed=${this._prefsChanged}
></ha-energy-fixed-cost-settings>`;
}
private _renderEditorPage(kind: string, key: string) {
const listPath = `${this.route.prefix}/${this._currTab}`;
switch (`${this._currTab}/${kind}`) {
@@ -378,6 +410,19 @@ class HaConfigEnergy extends LitElement {
.editKey=${key}
@value-changed=${this._prefsChanged}
></ha-energy-device-settings-water-gas>`;
case "electricity/fixed_cost":
case "gas/fixed_cost":
case "water/fixed_cost":
return html`<ha-energy-fixed-cost-settings
class="editor-page"
.hass=${this.hass}
.narrow=${this.narrow}
.type=${FIXED_COST_TYPES[this._currTab]}
.preferences=${this._preferences!}
.listPath=${listPath}
.editKey=${key}
@value-changed=${this._prefsChanged}
></ha-energy-fixed-cost-settings>`;
default:
return nothing;
}
@@ -505,7 +550,8 @@ class HaConfigEnergy extends LitElement {
ha-energy-gas-settings,
ha-energy-water-settings,
ha-energy-device-settings,
ha-energy-device-settings-water-gas {
ha-energy-device-settings-water-gas,
ha-energy-fixed-cost-settings {
display: block;
margin-bottom: 12px;
}
@@ -35,6 +35,7 @@ export class EnergySetupWizard extends LitElement implements LovelaceCard {
device_consumption: [],
device_consumption_water: [],
device_consumption_gas: [],
fixed_costs: [],
};
public getCardSize() {
@@ -21,9 +21,14 @@ import {
statesContext,
uiContext,
} from "../../../../data/context";
import type { EnergyData, EnergySourceByType } from "../../../../data/energy";
import type {
EnergyData,
EnergySourceByType,
FixedCostType,
} from "../../../../data/energy";
import {
energySourcesByType,
fixedCostsByType,
getBatteryEnergyStatIds,
getBatteryName,
validateEnergyCollectionKey,
@@ -177,8 +182,8 @@ export class HuiEnergySourcesTableCard
type: string,
statId: string,
idx: number,
energy: number,
compareEnergy: number,
energy: number | null,
compareEnergy: number | null,
energyUnit: string,
cost: number | null,
compareCost: number | null,
@@ -200,18 +205,24 @@ export class HuiEnergySourcesTableCard
}
: undefined;
const formattedEnergy = formatNumberWithUnit(
energy,
energyUnit,
this._i18n.locale,
formatOptions
);
const formattedCompareEnergy = formatNumberWithUnit(
compareEnergy,
energyUnit,
this._i18n.locale,
formatOptions
);
const formattedEnergy =
energy === null
? ""
: formatNumberWithUnit(
energy,
energyUnit,
this._i18n.locale,
formatOptions
);
const formattedCompareEnergy =
compareEnergy === null
? ""
: formatNumberWithUnit(
compareEnergy,
energyUnit,
this._i18n.locale,
formatOptions
);
const label =
name ||
@@ -447,7 +458,8 @@ export class HuiEnergySourcesTableCard
types.water?.some(
(flow) =>
flow.stat_cost || flow.entity_energy_price || flow.number_energy_price
)
) ||
this._data.prefs.fixed_costs.some((fixedCost) => types[fixedCost.type])
);
const units = {
@@ -605,6 +617,60 @@ export class HuiEnergySourcesTableCard
"ui.panel.lovelace.cards.energy.energy_distribution.grid"
);
const fixedCosts = fixedCostsByType(this._data.prefs);
const _renderFixedCosts = (type: FixedCostType) => {
const sourceCount = types[type]?.length;
if (!sourceCount) {
return nothing;
}
return fixedCosts[type]?.map((fixedCost, idx) => {
const statId = this._data!.info.fixed_cost_sensors[fixedCost.id];
if (!statId) {
return nothing;
}
const cost = calculateStatisticSumGrowth(this._data!.stats[statId]);
const costCompare = compare
? calculateStatisticSumGrowth(this._data!.statsCompare[statId])
: null;
if (cost === null && costCompare === null) {
return nothing;
}
if (type === "grid") {
hasGridCost = true;
totalGridCost += cost ?? 0;
totalGridCostCompare += costCompare ?? 0;
} else {
hasCosts[type] = true;
totalCosts[type] += cost ?? 0;
totalCostsCompare[type] += costCompare ?? 0;
}
if (showOnlyTotals) {
return nothing;
}
// Shades after the source rows keep the bullets distinct from them
return this._renderRow(
computedStyles,
type === "grid" ? "grid_consumption" : type,
statId,
sourceCount + idx,
null,
null,
"",
cost,
costCompare,
showCosts,
compare,
fixedCost.name
);
});
};
const _renderSimpleCategory = (type: "solar" | "gas" | "water") =>
html` ${types[type]?.map((source, idx) => {
const cost_stat =
@@ -646,6 +712,7 @@ export class HuiEnergySourcesTableCard
source.name
);
})}
${type === "solar" ? nothing : _renderFixedCosts(type)}
${
types[type]
? this._renderTotalRow(
@@ -1017,6 +1084,7 @@ export class HuiEnergySourcesTableCard
)
: gridName
)}
${_renderFixedCosts("grid")}
${
types.grid &&
types.grid.some(
+29
View File
@@ -5026,6 +5026,35 @@
"flow_rate_energy_sources": "[%key:ui::panel::config::energy::gas::dialog::flow_rate_energy_sources%]"
}
},
"fixed_costs": {
"title": "Fixed costs",
"sub": "Track costs that don't depend on how much you use, like a standing charge. Each one is added at the start of its period.",
"add_fixed_cost": "Add fixed cost",
"delete_fixed_cost": "Delete fixed cost",
"delete_confirm_title": "Delete fixed cost?",
"delete_confirm_text": "{name} will be permanently deleted.",
"amount_per_period": {
"day": "{amount} per day",
"month": "{amount} per month",
"year": "{amount} per year"
},
"dialog": {
"header": "Configure fixed cost",
"name": "[%key:ui::common::name%]",
"amount_type": "Amount",
"amount_number": "Use a fixed amount",
"amount_entity": "Use an entity with the current amount",
"amount_number_label": "Fixed amount",
"amount_number_helper": "Use a negative amount for a rebate or credit.",
"amount_entity_label": "Entity with the current amount",
"amount_entity_helper": "The state of this entity is the amount for each period. Its unit must be `{currency}` or `{currency}/{period}`.",
"period": "Period",
"period_day": "Every day",
"period_month": "Every month",
"period_year": "Every year",
"period_helper": "The amount is added at the start of each period, for example at midnight for a daily cost or on the first of the month for a monthly cost."
}
},
"integral": {
"energy": {
"create_title": "{count, plural,\n one {Create energy sensor?}\n other {Create energy sensors?}\n}",
@@ -28,6 +28,7 @@ const gasPrefs = (sources: number): EnergyPreferences => ({
device_consumption: [],
device_consumption_water: [],
device_consumption_gas: [],
fixed_costs: [],
});
const small = generateEnergyData(1, {
@@ -34,6 +34,7 @@ const solarPrefs = (sources: number, forecast: boolean): EnergyPreferences => {
device_consumption: [],
device_consumption_water: [],
device_consumption_gas: [],
fixed_costs: [],
};
};
+72 -4
View File
@@ -24,6 +24,7 @@ import {
getEnergyLiveDayPeriod,
shouldFallbackEnergyPeriodToYesterday,
getEnergyDataCollection,
getReferencedStatisticIds,
saveEnergyPreferences,
EMPTY_PREFERENCES,
CompareMode,
@@ -34,6 +35,7 @@ import type {
EnergyPreferences,
EnergySource,
EnergySumData,
FixedCostEnergyPreference,
} from "../../src/data/energy";
import type { DeviceRegistryEntry } from "../../src/data/device/device_registry";
import type { EntityRegistryDisplayEntry } from "../../src/data/entity/entity_registry";
@@ -1528,6 +1530,7 @@ describe("getEnergyDataCollection overlapping refreshes", () => {
const pending: {
resolve: (info: {
cost_sensors: Record<string, string>;
fixed_cost_sensors: Record<string, string>;
solar_forecast_domains: string[];
}) => void;
reject: (error: Error) => void;
@@ -1573,7 +1576,11 @@ describe("getEnergyDataCollection overlapping refreshes", () => {
const complete = async (
request: ReturnType<typeof createCollection>["pending"][number]
) => {
request.resolve({ cost_sensors: {}, solar_forecast_domains: [] });
request.resolve({
cost_sensors: {},
fixed_cost_sensors: {},
solar_forecast_domains: [],
});
await vi.advanceTimersByTimeAsync(0);
};
@@ -1961,7 +1968,11 @@ describe("getEnergyDataCollection live day", () => {
hass.config = { ...hass.config, time_zone: "America/New_York" };
const callWS = vi.fn(async (msg: { type: string }) => {
if (msg.type === "energy/info") {
return { cost_sensors: {}, solar_forecast_domains: [] };
return {
cost_sensors: {},
fixed_cost_sensors: {},
solar_forecast_domains: [],
};
}
throw new Error(`unexpected ${msg.type}`);
});
@@ -2166,7 +2177,11 @@ describe("getEnergyDataCollection statistics range", () => {
const callWS = vi.fn(async (msg: Record<string, unknown>) => {
switch (msg.type) {
case "energy/info":
return { cost_sensors: {}, solar_forecast_domains: [] };
return {
cost_sensors: {},
fixed_cost_sensors: {},
solar_forecast_domains: [],
};
case "recorder/get_statistics_metadata":
return [];
case "recorder/statistics_during_period":
@@ -2266,7 +2281,11 @@ describe("getEnergyDataCollection gas energy unit", () => {
const callWS = vi.fn(async (msg: Record<string, unknown>) => {
switch (msg.type) {
case "energy/info":
return { cost_sensors: {}, solar_forecast_domains: [] };
return {
cost_sensors: {},
fixed_cost_sensors: {},
solar_forecast_domains: [],
};
case "recorder/get_statistics_metadata":
return statisticIds.map((id) => gasMetadata(id, gasUnits[id]));
case "recorder/statistics_during_period":
@@ -2868,3 +2887,52 @@ describe("computeConsumptionData with a home meter", () => {
assert.equal(consumption.used_grid[1], baseline.used_grid[1]);
});
});
describe("getReferencedStatisticIds fixed costs", () => {
const fixedCost = (
id: string,
type: FixedCostEnergyPreference["type"]
): FixedCostEnergyPreference => ({
id,
type,
name: id,
number_amount: 1,
entity_amount: null,
period: "day",
});
const prefs: EnergyPreferences = {
...EMPTY_PREFERENCES,
fixed_costs: [
fixedCost("grid", "grid"),
fixedCost("gas", "gas"),
fixedCost("water", "water"),
fixedCost("not_set_up", "grid"),
],
};
const info = {
cost_sensors: {},
fixed_cost_sensors: {
grid: "sensor.grid_fixed_cost",
gas: "sensor.gas_fixed_cost",
water: "sensor.water_fixed_cost",
},
solar_forecast_domains: [],
};
it("fetches each fixed cost with the statistics of its type", () => {
assert.deepEqual(
getReferencedStatisticIds(prefs, info, [
"grid",
"solar",
"home",
"battery",
"gas",
"device",
]),
["sensor.grid_fixed_cost", "sensor.gas_fixed_cost"]
);
assert.deepEqual(getReferencedStatisticIds(prefs, info, ["water"]), [
"sensor.water_fixed_cost",
]);
});
});
+6 -1
View File
@@ -93,6 +93,7 @@ export const generateEnergyPreferences = (
device_consumption: [],
device_consumption_water: [],
device_consumption_gas: [],
fixed_costs: [],
};
};
@@ -159,7 +160,11 @@ export const generateEnergyData = (
start: new Date(FIXED_EPOCH_MS),
end: new Date(FIXED_EPOCH_MS + days * dayMs),
prefs,
info: { cost_sensors: {}, solar_forecast_domains: [] },
info: {
cost_sensors: {},
fixed_cost_sensors: {},
solar_forecast_domains: [],
},
stats,
statsMetadata: {},
statsCompare,
@@ -27,6 +27,7 @@ const makePrefs = (
device_consumption: [],
device_consumption_water: [],
device_consumption_gas: [],
fixed_costs: [],
...prefs,
});
@@ -39,6 +39,7 @@ const gasOnlyPrefs = (sources: number): EnergyPreferences => ({
device_consumption: [],
device_consumption_water: [],
device_consumption_gas: [],
fixed_costs: [],
});
// Fixed "now" so the end fallback is deterministic.
@@ -133,6 +134,7 @@ describe("generateEnergyGasGraphData", () => {
device_consumption: [],
device_consumption_water: [],
device_consumption_gas: [],
fixed_costs: [],
};
const energyData = generateEnergyData(5, {
days: 2,
@@ -49,6 +49,7 @@ const solarPrefs = (opts: {
device_consumption: [],
device_consumption_water: [],
device_consumption_gas: [],
fixed_costs: [],
};
};
@@ -80,6 +81,7 @@ describe("generateEnergySolarGraphData", () => {
device_consumption: [],
device_consumption_water: [],
device_consumption_gas: [],
fixed_costs: [],
},
});
const result = generateEnergySolarGraphData({