updated apps

This commit is contained in:
2026-07-14 23:57:03 -04:00
parent 6cc7212cef
commit 010e828e9c
797 changed files with 45153 additions and 4246 deletions
@@ -0,0 +1,358 @@
/** Dialog to discover HA "problem" sensors and adopt them as maintenance tasks.
*
* Lists binary/problem sensors that aren't already tracked, preselects them all,
* and turns each into a maintenance task that triggers while the problem is
* active and clears when it resolves. A selection either attaches to a suggested
* existing object or spins up a fresh object bound to the sensor's device.
*/
import { css, html, LitElement, nothing } from "lit";
import { property, state } from "lit/decorators.js";
import { t, ensureLocale } from "../styles";
import { describeWsError } from "../ws-errors";
import type { HomeAssistant } from "../types";
interface ProblemSensor {
entity_id: string;
name: string;
state: string;
device_id: string | null;
device_name: string | null;
area_name: string | null;
suggested_entry_id: string | null;
suggested_object_name: string;
suggested_part_id: string | null;
suggested_part_name: string | null;
}
interface DiscoverResponse {
sensors: ProblemSensor[];
}
interface AdoptResponse {
tasks_created: number;
objects_created: number;
total: number;
errors?: string[];
}
export class MaintenanceAdoptProblemSensorsDialog extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private _open = false;
@state() private _loading = false;
@state() private _adopting = false;
@state() private _error = "";
@state() private _sensors: ProblemSensor[] = [];
@state() private _selected: Set<string> = new Set();
private _localeReady = false;
private get _lang(): string {
return this.hass?.language || "en";
}
updated(changed: Map<string, unknown>): void {
if (changed.has("hass") && this.hass && !this._localeReady) {
this._localeReady = true;
ensureLocale(this._lang).then(() => this.requestUpdate());
}
}
public async open(): Promise<void> {
this._open = true;
this._loading = true;
this._error = "";
this._sensors = [];
this._selected = new Set();
try {
const resp = await this.hass.connection.sendMessagePromise<DiscoverResponse>({
type: "maintenance_supporter/problem_sensors/discover",
});
this._sensors = resp.sensors || [];
this._selected = new Set(this._sensors.map((s) => s.entity_id));
} catch (e) {
this._error = describeWsError(e, this._lang);
} finally {
this._loading = false;
}
}
private _close(): void {
this._open = false;
}
private _toggle = (entityId: string): void => {
const next = new Set(this._selected);
if (next.has(entityId)) next.delete(entityId);
else next.add(entityId);
this._selected = next;
};
private _toggleAll = (): void => {
if (this._selected.size === this._sensors.length) {
this._selected = new Set();
} else {
this._selected = new Set(this._sensors.map((s) => s.entity_id));
}
};
private _adopt = async (): Promise<void> => {
if (this._selected.size === 0 || this._adopting) return;
this._adopting = true;
this._error = "";
try {
const selections = this._sensors
.filter((s) => this._selected.has(s.entity_id))
.map((s) => ({
entity_id: s.entity_id,
name: s.name,
entry_id: s.suggested_entry_id ?? undefined,
object_name: s.suggested_object_name,
device_id: s.device_id ?? undefined,
part_id: s.suggested_part_id ?? undefined,
}));
const result = await this.hass.connection.sendMessagePromise<AdoptResponse>({
type: "maintenance_supporter/problem_sensors/adopt",
selections,
});
this.dispatchEvent(
new CustomEvent("problem-sensors-adopted", {
bubbles: true,
composed: true,
detail: result,
}),
);
this._open = false;
} catch (e) {
this._error = describeWsError(e, this._lang);
} finally {
this._adopting = false;
}
};
render() {
if (!this._open) return html``;
const L = this._lang;
const allSelected =
this._sensors.length > 0 && this._selected.size === this._sensors.length;
return html`
<div class="overlay" @click=${this._close}>
<div class="card" @click=${(e: Event) => e.stopPropagation()}>
<div class="title">${t("adopt_problem_title", L)}</div>
<div class="hint">${t("adopt_problem_hint", L)}</div>
${this._error ? html`<div class="error">${this._error}</div>` : nothing}
${this._loading
? html`<div class="loading">…</div>`
: this._sensors.length === 0
? html`<div class="empty">${t("adopt_problem_none", L)}</div>`
: html`
<label class="select-all">
<input
type="checkbox"
.checked=${allSelected}
@change=${this._toggleAll}
/>
<span>${t("selected", L)}: ${this._selected.size} / ${this._sensors.length}</span>
</label>
<div class="list">
${this._sensors.map((s) => {
const checked = this._selected.has(s.entity_id);
const active = s.state === "on";
const sub = [s.device_name, s.area_name]
.filter(Boolean)
.join(" · ");
return html`
<label class="row">
<input
type="checkbox"
.checked=${checked}
@change=${() => this._toggle(s.entity_id)}
/>
<div class="row-main">
<div class="row-top">
<span class="row-name">${s.name}</span>
<span class="chip ${active ? "chip-active" : "chip-ok"}">
${active
? t("adopt_problem_active", L)
: t("adopt_problem_ok", L)}
</span>
</div>
${sub ? html`<div class="row-sub">${sub}</div>` : nothing}
<div class="row-target">
${s.suggested_object_name}${s.suggested_entry_id
? nothing
: html` <span class="new-tag">${t("adopt_problem_new_object", L)}</span>`}
</div>
${s.suggested_part_name
? html`<div class="row-part">
<ha-icon icon="mdi:package-variant-closed"></ha-icon>
${t("adopt_problem_part", L).replace("{name}", s.suggested_part_name)}
</div>`
: nothing}
</div>
</label>
`;
})}
</div>
`}
<div class="actions">
<ha-button appearance="plain" @click=${this._close}>
${t("cancel", L)}
</ha-button>
<ha-button
@click=${this._adopt}
.disabled=${this._selected.size === 0 || this._adopting}
>
${t("adopt_problem_adopt", L)}
</ha-button>
</div>
</div>
</div>
`;
}
static styles = css`
.overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.card {
background: var(--card-background-color, #fff);
color: var(--primary-text-color);
border-radius: 12px;
padding: 20px;
display: flex;
flex-direction: column;
gap: 12px;
min-width: 360px;
max-width: 560px;
width: 90vw;
max-height: 80vh;
overflow: hidden;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
}
.title {
font-size: 18px;
font-weight: 500;
}
.hint {
color: var(--secondary-text-color);
font-size: 13px;
}
.error {
color: var(--error-color, #f44336);
font-size: 13px;
}
.loading,
.empty {
color: var(--secondary-text-color);
font-size: 14px;
padding: 12px 0;
}
.select-all {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
color: var(--secondary-text-color);
cursor: pointer;
}
.select-all input {
cursor: pointer;
}
.list {
display: flex;
flex-direction: column;
gap: 6px;
overflow-y: auto;
max-height: 50vh;
}
.row {
display: flex;
align-items: flex-start;
gap: 10px;
padding: 8px;
border: 1px solid var(--divider-color);
border-radius: 6px;
cursor: pointer;
}
.row input {
margin-top: 2px;
cursor: pointer;
}
.row-main {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
flex: 1;
}
.row-top {
display: flex;
align-items: center;
gap: 8px;
}
.row-name {
font-weight: 500;
font-size: 13px;
}
.row-sub {
color: var(--secondary-text-color);
font-size: 12px;
}
.row-target {
color: var(--secondary-text-color);
font-size: 12px;
}
.row-part {
color: var(--secondary-text-color);
font-size: 12px;
display: flex;
align-items: center;
gap: 4px;
}
.row-part ha-icon {
--mdc-icon-size: 14px;
}
.new-tag {
font-style: italic;
}
.chip {
font-size: 11px;
padding: 1px 8px;
border-radius: 10px;
white-space: nowrap;
}
.chip-active {
background: var(--error-color, #f44336);
color: #fff;
}
.chip-ok {
background: var(--divider-color);
color: var(--secondary-text-color);
}
.actions {
display: flex;
justify-content: flex-end;
gap: 8px;
padding-top: 8px;
}
`;
}
if (!customElements.get("maintenance-adopt-problem-sensors-dialog")) {
customElements.define(
"maintenance-adopt-problem-sensors-dialog",
MaintenanceAdoptProblemSensorsDialog,
);
}
@@ -3,7 +3,7 @@
import { LitElement, html, css, nothing } from "lit";
import { property, state } from "lit/decorators.js";
import type { HomeAssistant } from "../types";
import { t } from "../styles";
import { t, nativeFieldStyles } from "../styles";
import { describeWsError } from "../ws-errors";
export class MaintenanceCompleteDialog extends LitElement {
@@ -17,6 +17,10 @@ export class MaintenanceCompleteDialog extends LitElement {
// v2.20 (#83): task type + unit drive the reading-value field below.
@property() public taskType = "";
@property() public readingUnit = "";
/** Buy task (part_ref): default restock quantity — shows an editable qty field. */
@property({ attribute: false }) public restockDefault: number | null = null;
/** "Consumes: 1× HEPA-Filter (Shelf B)" hint lines for consuming tasks. */
@property({ type: Array }) public consumesInfo: string[] = [];
@state() private _open = false;
@state() private _notes = "";
@state() private _cost = "";
@@ -29,6 +33,7 @@ export class MaintenanceCompleteDialog extends LitElement {
@state() private _photoPreview = "";
@state() private _photoUploading = false;
@state() private _readingValue = "";
@state() private _restockQty = "";
public open(): void {
if (this._open) return;
@@ -43,6 +48,7 @@ export class MaintenanceCompleteDialog extends LitElement {
this._photoPreview = "";
this._photoUploading = false;
this._readingValue = "";
this._restockQty = this.restockDefault !== null ? String(this.restockDefault) : "";
}
private _toggleCheck(idx: number): void {
@@ -129,6 +135,10 @@ export class MaintenanceCompleteDialog extends LitElement {
const rv = parseFloat(this._readingValue);
if (!isNaN(rv)) data.reading_value = rv;
}
if (this.restockDefault !== null && this._restockQty !== "") {
const rq = parseInt(this._restockQty, 10);
if (!isNaN(rq) && rq >= 1) data.restock_quantity = rq;
}
await this.hass.connection.sendMessagePromise(data);
this._open = false;
this.dispatchEvent(new CustomEvent("task-completed"));
@@ -171,6 +181,20 @@ export class MaintenanceCompleteDialog extends LitElement {
@input=${(e: Event) => (this._readingValue = (e.target as HTMLInputElement).value)} />
</label>`
: nothing}
${this.consumesInfo.length
? html`<div class="consumes-hint">
${this.consumesInfo.map((line) => html`<div>${line}</div>`)}
</div>`
: nothing}
${this.restockDefault !== null
? html`
<label class="field">
<span class="field-label">${t("restock_quantity_label", L)}</span>
<input type="number" step="1" min="1" class="field-input"
.value=${this._restockQty}
@input=${(e: Event) => (this._restockQty = (e.target as HTMLInputElement).value)} />
</label>`
: nothing}
<!-- Native <input>s rather than <ha-textfield>: when this dialog
is opened from a Lovelace card via dialog-mount, ha-textfield
isn't yet registered (HA loads it lazily when its own panels
@@ -248,7 +272,7 @@ export class MaintenanceCompleteDialog extends LitElement {
`;
}
static styles = css`
static styles = [nativeFieldStyles, css`
.dialog-title {
font-size: 18px;
font-weight: 500;
@@ -266,27 +290,18 @@ export class MaintenanceCompleteDialog extends LitElement {
gap: 8px;
padding-top: 16px;
}
.consumes-hint {
font-size: 13px;
color: var(--secondary-text-color);
border-left: 3px solid var(--primary-color);
padding: 4px 8px;
margin: 4px 0 8px;
}
.error {
color: var(--error-color, #f44336);
font-size: 13px;
}
.field { display: flex; flex-direction: column; gap: 4px; }
.field-label {
font-size: 12px;
color: var(--secondary-text-color);
}
.field-input {
padding: 8px 10px; font-size: 14px;
background: var(--secondary-background-color, rgba(0,0,0,0.06));
color: var(--primary-text-color);
border: 1px solid var(--divider-color); border-radius: 6px;
font-family: inherit;
width: 100%; box-sizing: border-box;
}
.field-input:focus {
outline: none;
border-color: var(--primary-color);
}
/* .field/.field-label/.field-input come from nativeFieldStyles */
.photo-pick {
display: inline-flex;
align-items: center;
@@ -387,7 +402,7 @@ export class MaintenanceCompleteDialog extends LitElement {
color: var(--text-primary-color, #fff);
border-color: var(--primary-color);
}
`;
`];
}
// Safe registration — avoids duplicate define when both panel and card load
@@ -3,7 +3,7 @@
import { LitElement, html, css, nothing } from "lit";
import { property, state } from "lit/decorators.js";
import type { HomeAssistant } from "../types";
import { t } from "../styles";
import { t, nativeFieldStyles } from "../styles";
export interface ConfirmOptions {
title: string;
@@ -126,22 +126,15 @@ export class MaintenanceConfirmDialog extends LitElement {
`;
}
static styles = css`
static styles = [nativeFieldStyles, css`
.dialog-title {
font-size: 18px;
font-weight: 500;
padding-bottom: 12px;
}
.field { display: flex; flex-direction: column; gap: 4px; margin-top: 12px; }
.field-label { font-size: 12px; color: var(--secondary-text-color); }
.field-input {
padding: 8px 10px; font-size: 14px;
background: var(--secondary-background-color, rgba(0,0,0,0.06));
color: var(--primary-text-color);
border: 1px solid var(--divider-color); border-radius: 6px;
font-family: inherit; width: 100%; box-sizing: border-box;
}
.field-input:focus { outline: none; border-color: var(--primary-color); }
/* shared native-field scaffold from nativeFieldStyles; the prompt input
follows the message text, hence the extra top margin here */
.field { margin-top: 12px; }
.content {
padding: 8px 0;
min-width: 280px;
@@ -162,7 +155,7 @@ export class MaintenanceConfirmDialog extends LitElement {
ha-button.danger {
--mdc-theme-primary: var(--error-color, #f44336);
}
`;
`];
}
if (!customElements.get("maintenance-confirm-dialog")) {
@@ -8,6 +8,7 @@
*/
import { LitElement, html, css, nothing } from "lit";
import { isSafeHttpUrl } from "../helpers/url";
import { property, state } from "lit/decorators.js";
import { t, ensureLocale } from "../styles";
import { describeWsError } from "../ws-errors";
@@ -246,7 +247,7 @@ export class MaintenanceDocumentsSection extends LitElement {
if (doc.kind === "file") void this._preview(doc);
// Only open http(s) links — never a javascript:/data: URL (the same scheme
// guard the rest of the panel applies before opening user-supplied URLs).
else if (doc.url && /^https?:\/\//i.test(doc.url)) window.open(doc.url, "_blank", "noopener");
else if (isSafeHttpUrl(doc.url)) window.open(doc.url, "_blank", "noopener");
}
private _startEdit(doc: MaintenanceDocument): void {
@@ -484,7 +485,7 @@ export class MaintenanceDocumentsSection extends LitElement {
</button>`
: html`<a
class="icon-btn"
href=${doc.url && /^https?:\/\//i.test(doc.url) ? doc.url : "#"}
href=${isSafeHttpUrl(doc.url) ? doc.url : "#"}
target="_blank"
rel="noopener noreferrer"
title=${t("doc_open", L)}
@@ -9,6 +9,7 @@
*/
import { LitElement, html, css, nothing } from "lit";
import { isSafeHttpUrl } from "../helpers/url";
import { property, state } from "lit/decorators.js";
import { t, STATUS_COLORS } from "../styles";
import { describeWsError } from "../ws-errors";
@@ -239,7 +240,7 @@ export class MaintenanceObjectQuickActionsDialog extends LitElement {
<span class="meta-value">${
// Only render http(s) values as links (never javascript:/data:);
// value-based so it works in every UI language, not just English.
/^https?:\/\//i.test(value)
isSafeHttpUrl(value)
? html`<a href="${value}" target="_blank" rel="noopener noreferrer">${value}</a>`
: value
}</span>
@@ -0,0 +1,483 @@
/**
* Spare parts & consumables section on the object detail page.
*
* Shows the object's parts list (stock badge, storage location, identifiers,
* shopping link), lets admins add/edit/delete parts, and adjust stock
* (inventory correction / manual restock). Follows the documents-section
* conventions: standalone LitElement fed by the panel, native <input>s in the
* inline form (the ha-textfield-in-custom-panel trap), t() i18n.
*
* After a create/delete (entity set changes → backend reloads the entry) it
* fires "parts-changed" so the panel re-fetches objects; stock adjustments
* update the local copy from the WS response for instant feedback.
*/
import { LitElement, html, css, nothing } from "lit";
import { isSafeHttpUrl } from "../helpers/url";
import { property, state } from "lit/decorators.js";
import { t, ensureLocale } from "../styles";
import { describeWsError } from "../ws-errors";
import type { HomeAssistant, MaintenancePart } from "../types";
// Per-part document links (v2.26) — the task-documents component in part mode.
import "./task-documents";
interface PartForm {
id?: string;
name: string;
vendor: string;
mpn: string;
gtin: string;
storage_location: string;
product_url: string;
unit: string;
cost: string;
stock: string;
reorder_threshold: string;
restock_quantity: string;
auto_buy_task: boolean;
notes: string;
}
const EMPTY_FORM: PartForm = {
name: "",
vendor: "",
mpn: "",
gtin: "",
storage_location: "",
product_url: "",
unit: "",
cost: "",
stock: "",
reorder_threshold: "",
restock_quantity: "",
auto_buy_task: true,
notes: "",
};
export class MaintenancePartsSection extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public entryId!: string;
@property({ attribute: false }) public parts: MaintenancePart[] = [];
@property({ type: Boolean }) public canWrite = false;
@state() private _editing: PartForm | null = null;
@state() private _busy = false;
@state() private _error = "";
@state() private _restockFor: string | null = null;
@state() private _restockQty = "";
@state() private _restockInvalid = false;
@state() private _docsFor: string | null = null;
private get _lang(): string {
return this.hass?.locale?.language || this.hass?.language || "en";
}
public connectedCallback(): void {
super.connectedCallback();
// Lazy-load the locale bundle for t() (same pattern as documents-section).
void ensureLocale(this._lang).then(() => this.requestUpdate());
}
private _notifyChanged(): void {
this.dispatchEvent(new CustomEvent("parts-changed", { bubbles: true, composed: true }));
}
private async _send<T>(msg: Record<string, unknown>): Promise<T | null> {
this._busy = true;
this._error = "";
try {
return await this.hass.connection.sendMessagePromise<T>(msg);
} catch (err) {
this._error = describeWsError(err, this._lang);
return null;
} finally {
this._busy = false;
}
}
private _openAdd(): void {
this._editing = { ...EMPTY_FORM };
}
private _openEdit(part: MaintenancePart): void {
this._editing = {
id: part.id,
name: part.name,
vendor: part.vendor || "",
mpn: part.mpn || "",
gtin: part.gtin || "",
storage_location: part.storage_location || "",
product_url: part.product_url || "",
unit: part.unit || "",
cost: part.cost != null ? String(part.cost) : "",
stock: part.stock != null ? String(part.stock) : "",
reorder_threshold: part.reorder_threshold != null ? String(part.reorder_threshold) : "",
restock_quantity: part.restock_quantity != null ? String(part.restock_quantity) : "",
auto_buy_task: !!part.auto_buy_task,
notes: part.notes || "",
};
}
private _formValue(f: PartForm): Record<string, unknown> {
const num = (s: string): number | null => (s.trim() === "" ? null : Number(s));
return {
entry_id: this.entryId,
name: f.name.trim(),
vendor: f.vendor.trim() || null,
mpn: f.mpn.trim() || null,
gtin: f.gtin.trim() || null,
storage_location: f.storage_location.trim() || null,
product_url: f.product_url.trim() || null,
unit: f.unit.trim() || null,
cost: num(f.cost),
stock: num(f.stock),
reorder_threshold: num(f.reorder_threshold),
restock_quantity: num(f.restock_quantity),
auto_buy_task: f.auto_buy_task,
notes: f.notes.trim() || null,
};
}
private async _save(): Promise<void> {
const f = this._editing;
if (!f || !f.name.trim()) return;
const payload = this._formValue(f);
const type = f.id ? "maintenance_supporter/part/update" : "maintenance_supporter/part/create";
const result = await this._send<{ part_id?: string }>(f.id ? { type, part_id: f.id, ...payload } : { type, ...payload });
if (result !== null) {
this._editing = null;
this._notifyChanged();
}
}
private async _delete(part: MaintenancePart): Promise<void> {
const result = await this._send<{ success: boolean }>({
type: "maintenance_supporter/part/delete",
entry_id: this.entryId,
part_id: part.id,
});
if (result !== null) this._notifyChanged();
}
private async _restock(part: MaintenancePart): Promise<void> {
const qty = parseInt(this._restockQty, 10);
if (!Number.isFinite(qty) || qty === 0) {
// Don't silently swallow a no-op amount — keep the input open and mark
// it so the user sees WHY nothing happened (0 / empty / not a number).
this._restockInvalid = true;
return;
}
this._restockInvalid = false;
const result = await this._send<{ stock: number }>({
type: "maintenance_supporter/part/restock",
entry_id: this.entryId,
part_id: part.id,
delta: qty,
});
this._restockFor = null;
if (result !== null) {
// Instant local feedback; the panel refresh follows via parts-changed.
part.stock = result.stock;
this.requestUpdate();
this._notifyChanged();
}
}
private _identLine(part: MaintenancePart): string {
return [part.vendor, part.mpn ? `MPN: ${part.mpn}` : "", part.gtin ? `GTIN: ${part.gtin}` : ""]
.filter(Boolean)
.join(" · ");
}
private _renderRow(part: MaintenancePart) {
const L = this._lang;
const tracked = part.stock !== null && part.stock !== undefined;
const ident = this._identLine(part);
const docsOpen = this._docsFor === part.id;
return html`
<div class="part-row ${part.is_low ? "low" : ""}">
<ha-icon class="part-icon" icon=${part.is_low ? "mdi:cart-arrow-down" : "mdi:package-variant-closed"}></ha-icon>
<div class="part-main">
<div class="part-name">
${isSafeHttpUrl(part.shopping_url)
? html`<a href=${part.shopping_url} target="_blank" rel="noopener noreferrer">${part.name}</a>`
: part.name}
${tracked
? html`<span class="stock-badge ${part.is_low ? "low" : ""}"
>${part.stock}${part.unit ? ` ${part.unit}` : ""}${part.reorder_threshold != null
? html`<span class="threshold">/${part.reorder_threshold}</span>`
: nothing}</span
>`
: nothing}
</div>
<div class="part-meta">
${ident ? html`<span>${ident}</span>` : nothing}
${part.storage_location
? html`<span class="loc"><ha-icon icon="mdi:map-marker-outline"></ha-icon>${part.storage_location}</span>`
: nothing}
</div>
</div>
<ha-icon-button
title=${t("documents", L)}
class=${docsOpen ? "docs-open" : ""}
@click=${() => (this._docsFor = docsOpen ? null : part.id)}
><ha-icon icon="mdi:paperclip"></ha-icon
></ha-icon-button>
${this.canWrite
? html`
${this._restockFor === part.id
? html`
<input
class="restock-input${this._restockInvalid ? " invalid" : ""}"
type="number"
.value=${this._restockQty}
placeholder="+1"
@input=${(e: Event) => (this._restockQty = (e.target as HTMLInputElement).value)}
@keydown=${(e: KeyboardEvent) => {
if (e.key === "Enter") this._restock(part);
if (e.key === "Escape") this._restockFor = null;
}}
/>
<ha-icon-button title=${t("save", L)} @click=${() => this._restock(part)}
><ha-icon icon="mdi:check"></ha-icon
></ha-icon-button>
`
: html`
<ha-icon-button
title=${t("part_restock", L)}
.disabled=${this._busy}
@click=${() => {
this._restockFor = part.id;
this._restockInvalid = false;
this._restockQty = String(part.restock_quantity || 1);
}}
><ha-icon icon="mdi:plus-minus-variant"></ha-icon
></ha-icon-button>
`}
<ha-icon-button title=${t("edit", L)} .disabled=${this._busy} @click=${() => this._openEdit(part)}
><ha-icon icon="mdi:pencil"></ha-icon
></ha-icon-button>
<ha-icon-button title=${t("delete", L)} .disabled=${this._busy} @click=${() => this._delete(part)}
><ha-icon icon="mdi:delete-outline"></ha-icon
></ha-icon-button>
`
: nothing}
</div>
${docsOpen
? html`<div class="part-docs">
<maintenance-task-documents
.hass=${this.hass}
.entryId=${this.entryId}
.partId=${part.id}
.canWrite=${this.canWrite}
></maintenance-task-documents>
</div>`
: nothing}
`;
}
private _field(label: string, key: keyof PartForm, opts: { type?: string; placeholder?: string } = {}) {
const f = this._editing!;
return html`
<label class="form-field">
<span>${label}</span>
<input
type=${opts.type || "text"}
.value=${String(f[key] ?? "")}
placeholder=${opts.placeholder || ""}
@input=${(e: Event) => {
(this._editing as unknown as Record<string, unknown>)[key] = (e.target as HTMLInputElement).value;
this.requestUpdate();
}}
/>
</label>
`;
}
private _renderForm() {
const L = this._lang;
const f = this._editing!;
return html`
<div class="part-form">
<div class="form-grid">
${this._field(t("part_name", L), "name")}
${this._field(t("part_vendor", L), "vendor")}
${this._field("MPN", "mpn")}
${this._field("GTIN / EAN", "gtin", { placeholder: "4006381333931" })}
${this._field(t("part_storage_location", L), "storage_location")}
${this._field(t("part_product_url", L), "product_url", { placeholder: "https://…" })}
${this._field(t("part_unit", L), "unit")}
${this._field(t("part_cost", L), "cost", { type: "number" })}
${this._field(t("part_stock", L), "stock", { type: "number" })}
${this._field(t("part_reorder_threshold", L), "reorder_threshold", { type: "number" })}
${this._field(t("part_restock_quantity", L), "restock_quantity", { type: "number" })}
<label class="form-field checkbox">
<input
type="checkbox"
.checked=${f.auto_buy_task}
@change=${(e: Event) => {
this._editing = { ...f, auto_buy_task: (e.target as HTMLInputElement).checked };
}}
/>
<span>${t("part_auto_buy", L)}</span>
</label>
</div>
<div class="form-actions">
<ha-button appearance="plain" @click=${() => (this._editing = null)}>${t("cancel", L)}</ha-button>
<ha-button .disabled=${this._busy || !f.name.trim()} @click=${() => this._save()}
>${t("save", L)}</ha-button
>
</div>
</div>
`;
}
protected render() {
const L = this._lang;
if (!this.parts.length && !this.canWrite) return nothing;
return html`
<div class="section-head">
<h3>
<ha-icon icon="mdi:package-variant"></ha-icon>
${t("parts_section", L)} (${this.parts.length})
</h3>
${this.canWrite && !this._editing
? html`<ha-button appearance="plain" @click=${() => this._openAdd()}>
<ha-icon icon="mdi:plus"></ha-icon> ${t("part_add", L)}
</ha-button>`
: nothing}
</div>
${this._error ? html`<div class="error">${this._error}</div>` : nothing}
${this._editing ? this._renderForm() : nothing}
${this.parts.map((part) => this._renderRow(part))}
`;
}
static styles = css`
:host {
display: block;
margin: 12px 0;
}
.section-head {
display: flex;
align-items: center;
justify-content: space-between;
}
h3 {
display: flex;
align-items: center;
gap: 6px;
margin: 8px 0;
}
.part-row {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 4px;
border-bottom: 1px solid var(--divider-color);
}
.part-row.low .part-icon {
color: var(--warning-color, #ff9800);
}
.part-main {
flex: 1;
min-width: 0;
}
.part-name {
font-weight: 500;
display: flex;
align-items: center;
gap: 8px;
}
.part-name a {
color: var(--primary-color);
text-decoration: none;
}
.stock-badge {
font-size: 12px;
padding: 1px 8px;
border-radius: 10px;
background: var(--secondary-background-color);
}
.stock-badge.low {
background: var(--warning-color, #ff9800);
color: var(--text-primary-color, #fff);
}
.stock-badge .threshold {
opacity: 0.7;
}
.part-meta {
font-size: 12px;
color: var(--secondary-text-color);
display: flex;
gap: 12px;
flex-wrap: wrap;
}
.part-meta .loc ha-icon {
--mdc-icon-size: 13px;
}
.restock-input {
width: 64px;
padding: 4px;
border: 1px solid var(--divider-color);
border-radius: 4px;
background: var(--card-background-color);
color: var(--primary-text-color);
}
.restock-input.invalid {
border-color: var(--error-color, #f44336);
}
.docs-open {
color: var(--primary-color);
}
.part-docs {
padding: 0 4px 8px 34px;
border-bottom: 1px solid var(--divider-color);
}
.part-form {
border: 1px solid var(--divider-color);
border-radius: 8px;
padding: 12px;
margin-bottom: 8px;
}
.form-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
gap: 8px 12px;
}
.form-field {
display: flex;
flex-direction: column;
gap: 2px;
font-size: 12px;
color: var(--secondary-text-color);
}
.form-field input[type="text"],
.form-field input[type="number"] {
padding: 6px;
border: 1px solid var(--divider-color);
border-radius: 4px;
background: var(--card-background-color);
color: var(--primary-text-color);
}
.form-field.checkbox {
flex-direction: row;
align-items: center;
gap: 6px;
align-self: end;
}
.form-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 10px;
}
.error {
color: var(--error-color);
font-size: 13px;
margin: 4px 0;
}
`;
}
customElements.define("maintenance-parts-section", MaintenancePartsSection);
@@ -0,0 +1,247 @@
/** Dialog to save the current panel filters as a named view + manage views.
*
* "Views" are shared, named combinations of the task-list filters (status /
* user / archived) plus sort + group-by. This dialog saves the panel's *current*
* filter state under a name and lists existing views for deletion. Applying a
* view is done from the toolbar dropdown, not here.
*
* Uses a native <input> for the name — <ha-textfield> is not registered in the
* custom-panel context, so it renders without its field (the documented trap).
*/
import { css, html, LitElement, nothing } from "lit";
import { property, state } from "lit/decorators.js";
import { t, ensureLocale } from "../styles";
import { describeWsError } from "../ws-errors";
import type { HomeAssistant, SavedView, SavedViewFilters } from "../types";
interface ViewsResponse {
views: SavedView[];
}
export class MaintenanceSavedViewsDialog extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private _open = false;
@state() private _busy = false;
@state() private _error = "";
@state() private _name = "";
@state() private _views: SavedView[] = [];
private _filters: SavedViewFilters | null = null;
private _localeReady = false;
private get _lang(): string {
return this.hass?.language || "en";
}
updated(changed: Map<string, unknown>): void {
if (changed.has("hass") && this.hass && !this._localeReady) {
this._localeReady = true;
ensureLocale(this._lang).then(() => this.requestUpdate());
}
}
public async open(currentFilters: SavedViewFilters, views: SavedView[]): Promise<void> {
this._open = true;
this._error = "";
this._name = "";
this._filters = currentFilters;
this._views = views;
}
private _close(): void {
this._open = false;
}
private _emitChanged(views: SavedView[]): void {
this._views = views;
this.dispatchEvent(
new CustomEvent("saved-views-changed", { bubbles: true, composed: true, detail: { views } }),
);
}
private _save = async (): Promise<void> => {
const name = this._name.trim();
if (!name || this._busy || !this._filters) return;
this._busy = true;
this._error = "";
try {
const res = await this.hass.connection.sendMessagePromise<ViewsResponse>({
type: "maintenance_supporter/views/save",
name,
filters: this._filters,
});
this._name = "";
this._emitChanged(res.views || []);
} catch (e) {
this._error = describeWsError(e, this._lang);
} finally {
this._busy = false;
}
};
private _delete = async (viewId: string): Promise<void> => {
if (this._busy) return;
this._busy = true;
this._error = "";
try {
const res = await this.hass.connection.sendMessagePromise<ViewsResponse>({
type: "maintenance_supporter/views/delete",
view_id: viewId,
});
this._emitChanged(res.views || []);
} catch (e) {
this._error = describeWsError(e, this._lang);
} finally {
this._busy = false;
}
};
render() {
if (!this._open) return html``;
const L = this._lang;
return html`
<div class="overlay" @click=${this._close}>
<div class="card" @click=${(e: Event) => e.stopPropagation()}>
<div class="title">${t("views_dialog_title", L)}</div>
<div class="hint">${t("views_dialog_hint", L)}</div>
${this._error ? html`<div class="error">${this._error}</div>` : nothing}
<div class="save-row">
<input
class="name-input"
type="text"
.value=${this._name}
placeholder=${t("views_name_placeholder", L)}
maxlength="60"
@input=${(e: Event) => (this._name = (e.target as HTMLInputElement).value)}
@keydown=${(e: KeyboardEvent) => {
if (e.key === "Enter") this._save();
}}
/>
<ha-button @click=${this._save} .disabled=${!this._name.trim() || this._busy}>
${t("views_save_current", L)}
</ha-button>
</div>
${this._views.length === 0
? html`<div class="empty">${t("views_none_yet", L)}</div>`
: html`
<div class="list">
${this._views.map(
(v) => html`
<div class="row">
<span class="row-name">${v.name}</span>
<ha-icon-button
.path=${"M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z"}
.label=${t("delete", L)}
@click=${() => this._delete(v.id)}
></ha-icon-button>
</div>
`,
)}
</div>
`}
<div class="actions">
<ha-button appearance="plain" @click=${this._close}>${t("close", L)}</ha-button>
</div>
</div>
</div>
`;
}
static styles = css`
.overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.card {
background: var(--card-background-color, #fff);
color: var(--primary-text-color);
border-radius: 12px;
padding: 20px;
display: flex;
flex-direction: column;
gap: 12px;
min-width: 340px;
max-width: 480px;
width: 90vw;
max-height: 80vh;
overflow: hidden;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
}
.title {
font-size: 18px;
font-weight: 500;
}
.hint {
color: var(--secondary-text-color);
font-size: 13px;
}
.error {
color: var(--error-color, #f44336);
font-size: 13px;
}
.save-row {
display: flex;
gap: 8px;
align-items: center;
}
.name-input {
flex: 1;
padding: 8px 10px;
border: 1px solid var(--divider-color);
border-radius: 6px;
background: var(--card-background-color, #fff);
color: var(--primary-text-color);
font-size: 14px;
}
.empty {
color: var(--secondary-text-color);
font-size: 14px;
padding: 8px 0;
}
.list {
display: flex;
flex-direction: column;
gap: 6px;
overflow-y: auto;
max-height: 50vh;
}
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 6px 8px;
border: 1px solid var(--divider-color);
border-radius: 6px;
}
.row-name {
font-size: 14px;
font-weight: 500;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.actions {
display: flex;
justify-content: flex-end;
gap: 8px;
padding-top: 8px;
}
`;
}
if (!customElements.get("maintenance-saved-views-dialog")) {
customElements.define("maintenance-saved-views-dialog", MaintenanceSavedViewsDialog);
}
@@ -42,6 +42,7 @@ interface SettingsResponse {
bundling_enabled: boolean;
bundle_threshold: number;
reminder_lead_days: number[];
scope_view_id: string;
};
actions: {
complete_enabled: boolean;
@@ -91,7 +92,7 @@ interface VacationPreviewRow {
// Keep in lockstep with const.BUDGET_CURRENCIES (keys + order). Parity is
// enforced by tests/test_frontend_const_parity.py (drift fails CI).
const CURRENCIES = [
"EUR", "USD", "GBP", "JPY", "CHF", "CAD", "AUD", "CNY", "INR", "BRL",
"EUR", "USD", "GBP", "JPY", "CHF", "CAD", "AUD", "NZD", "CNY", "INR", "BRL",
"CZK", "PLN", "RUB", "SEK", "NOK", "DKK", "UAH",
];
@@ -108,6 +109,7 @@ export class MaintenanceSettingsView extends LitElement {
@state() private _toast = "";
@state() private _testingNotification = false;
@state() private _users: HAUser[] = [];
@state() private _savedViews: Array<{ id: string; name: string }> = [];
// Vacation mode section state (v1.2.0)
@state() private _vacEnabled = false;
@@ -135,6 +137,12 @@ export class MaintenanceSettingsView extends LitElement {
}> = [];
@state() private _qrObjectsLoaded = false;
// Export/Import selective-object picker state
@state() private _exportObjects: Array<{ entry_id: string; name: string; task_count: number }> = [];
@state() private _exportSelectedEntries = new Set<string>();
@state() private _exportObjectsLoaded = false;
@state() private _docArchiveLoading = false;
private _loaded = false;
private _userService: UserService | null = null;
@@ -174,6 +182,15 @@ export class MaintenanceSettingsView extends LitElement {
} catch {
/* ignore */
}
// Saved views feed the notification-scope picker (best-effort).
try {
const v = await this.hass.connection.sendMessagePromise<{ views: Array<{ id: string; name: string }> }>({
type: "maintenance_supporter/views/list",
});
this._savedViews = v.views || [];
} catch {
/* ignore */
}
this._loading = false;
}
@@ -616,6 +633,19 @@ export class MaintenanceSettingsView extends LitElement {
}} />
</label>
<div class="setting-hint">${t("settings_reminder_leads_hint", L)}</div>
<label class="setting-row">
<span class="setting-label">${t("settings_notify_scope", L)}</span>
<select
.value=${n.scope_view_id || ""}
@change=${(e: Event) => this._updateSetting("notify_scope_view_id", (e.target as HTMLSelectElement).value)}
>
<option value="" ?selected=${!n.scope_view_id}>${t("settings_notify_scope_all", L)}</option>
${this._savedViews.map(
(v) => html`<option value=${v.id} ?selected=${n.scope_view_id === v.id}>${v.name}</option>`
)}
</select>
</label>
<div class="setting-hint">${t("settings_notify_scope_hint", L)}</div>
<h4 style="margin: 16px 0 8px; font-size: 14px;">${t("settings_actions", L)}</h4>
<label class="setting-row">
@@ -1250,11 +1280,47 @@ export class MaintenanceSettingsView extends LitElement {
${t("settings_include_history", L)}
</label>
</div>
<div class="settings-actions">
${!this._exportObjectsLoaded
? html`<button @click=${this._loadExportObjects}>${t("settings_export_selection", L)}</button>`
: html`
<details class="qr-filter-panel">
<summary>${t("settings_export_selection", L)}</summary>
<div class="qr-object-list">
${this._exportObjects.length === 0
? html`<div class="hint">${t("no_objects", L)}</div>`
: this._exportObjects.map((obj) => html`
<label class="qr-object-row">
<input type="checkbox"
.checked=${this._exportSelectedEntries.size === 0 || this._exportSelectedEntries.has(obj.entry_id)}
@change=${(e: Event) => this._toggleExportObject(obj.entry_id, (e.target as HTMLInputElement).checked)} />
<span>${obj.name}</span>
<span class="qr-task-count">${obj.task_count}</span>
</label>
`)}
</div>
</details>
`}
</div>
<div class="settings-actions">
<button @click=${this._exportJson}>${t("settings_export_json", L)}</button>
<button @click=${this._exportYaml}>${t("settings_export_yaml", L)}</button>
<button @click=${this._exportCsv}>${t("settings_export_csv", L)}</button>
</div>
<div class="settings-actions docs-archive-block">
<h4>${t("settings_docs_archive", L)}</h4>
<p class="section-desc">${t("settings_docs_archive_hint", L)}</p>
<div class="settings-actions">
<button ?disabled=${this._docArchiveLoading} @click=${this._exportDocsArchive}>
${t("settings_docs_export_btn", L)}
</button>
<button ?disabled=${this._docArchiveLoading} @click=${this._triggerDocsArchiveImport}>
${this._docArchiveLoading ? "…" : t("settings_docs_import_btn", L)}
</button>
<input class="docs-archive-file" type="file" accept=".zip" hidden
@change=${this._importDocsArchive} />
</div>
</div>
<div class="import-section">
<textarea class="import-area" .value=${this._importCsv}
placeholder=${t("settings_import_placeholder", L)}
@@ -1273,12 +1339,44 @@ export class MaintenanceSettingsView extends LitElement {
// --- Export / Import actions ---
private get _selectedEntryIds(): string[] | undefined {
return this._exportSelectedEntries.size ? [...this._exportSelectedEntries] : undefined;
}
private async _loadExportObjects(): Promise<void> {
try {
const result = await this.hass.connection.sendMessagePromise({
type: "maintenance_supporter/objects",
}) as { objects: Array<{ entry_id: string; object: { name: string }; tasks: unknown[] }> };
this._exportObjects = (result.objects || []).map((o) => ({
entry_id: o.entry_id,
name: o.object.name,
task_count: (o.tasks || []).length,
})).sort((a, b) => a.name.localeCompare(b.name));
this._exportObjectsLoaded = true;
} catch {
this._showToast(t("action_error", this._lang));
}
}
private _toggleExportObject(entryId: string, on: boolean): void {
const next = new Set(this._exportSelectedEntries);
if (next.size === 0) {
for (const o of this._exportObjects) next.add(o.entry_id);
}
if (on) next.add(entryId); else next.delete(entryId);
if (next.size === this._exportObjects.length) next.clear();
this._exportSelectedEntries = next;
}
private async _exportJson(): Promise<void> {
try {
const ids = this._selectedEntryIds;
const result = await this.hass.connection.sendMessagePromise({
type: "maintenance_supporter/export",
format: "json",
include_history: this._includeHistory,
...(ids ? { entry_ids: ids } : {}),
}) as { data: string };
const ts = new Date().toISOString().slice(0, 10);
this._downloadFile(result.data, `maintenance_export_${ts}.json`, "application/json");
@@ -1290,10 +1388,12 @@ export class MaintenanceSettingsView extends LitElement {
private async _exportYaml(): Promise<void> {
try {
const ids = this._selectedEntryIds;
const result = await this.hass.connection.sendMessagePromise({
type: "maintenance_supporter/export",
format: "yaml",
include_history: this._includeHistory,
...(ids ? { entry_ids: ids } : {}),
}) as { data: string };
const ts = new Date().toISOString().slice(0, 10);
this._downloadFile(result.data, `maintenance_export_${ts}.yaml`, "application/yaml");
@@ -1305,8 +1405,10 @@ export class MaintenanceSettingsView extends LitElement {
private async _exportCsv(): Promise<void> {
try {
const ids = this._selectedEntryIds;
const result = await this.hass.connection.sendMessagePromise({
type: "maintenance_supporter/csv/export",
...(ids ? { entry_ids: ids } : {}),
}) as { csv: string };
const ts = new Date().toISOString().slice(0, 10);
this._downloadFile(result.csv, `maintenance_export_${ts}.csv`, "text/csv");
@@ -1340,6 +1442,66 @@ export class MaintenanceSettingsView extends LitElement {
this._importLoading = false;
}
// --- Documents archive (ZIP with file contents) ---
private async _exportDocsArchive(): Promise<void> {
this._docArchiveLoading = true;
try {
const raw = this._selectedEntryIds;
const q = raw ? `?entry_ids=${encodeURIComponent(raw.join(","))}` : "";
const signed = await this.hass.connection.sendMessagePromise<{ path: string }>({
type: "auth/sign_path",
path: `/api/maintenance_supporter/documents/archive${q}`,
expires: 300,
});
const a = document.createElement("a");
a.href = signed.path;
a.download = "maintenance-documents.zip";
document.body.appendChild(a);
a.click();
a.remove();
} catch {
this._showToast(t("action_error", this._lang));
}
this._docArchiveLoading = false;
}
private _triggerDocsArchiveImport(): void {
const input = this.renderRoot.querySelector(".docs-archive-file") as HTMLInputElement | null;
input?.click();
}
private async _importDocsArchive(e: Event): Promise<void> {
const input = e.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
this._docArchiveLoading = true;
try {
const form = new FormData();
form.append("file", file, file.name);
const resp = await fetch("/api/maintenance_supporter/documents/archive", {
method: "POST",
headers: { Authorization: `Bearer ${this.hass.auth?.data?.access_token ?? ""}` },
body: form,
});
if (!resp.ok) {
this._showToast(t("action_error", this._lang));
} else {
const result = (await resp.json()) as { blobs_written: number; documents_created: number };
this._showToast(
t("settings_docs_import_success", this._lang)
.replace("{blobs}", String(result.blobs_written ?? 0))
.replace("{docs}", String(result.documents_created ?? 0))
);
this.dispatchEvent(new CustomEvent("settings-changed"));
}
} catch {
this._showToast(t("action_error", this._lang));
}
input.value = "";
this._docArchiveLoading = false;
}
// --- Styles ---
static styles = css`
@@ -100,6 +100,8 @@ export class MaintenanceTaskDialog extends LitElement {
@property({ type: Boolean, attribute: "schedule-time-enabled" }) public scheduleTimeEnabled = false;
@property({ type: Boolean, attribute: "completion-actions-enabled" }) public completionActionsEnabled = false;
@property({ type: Number, attribute: "default-warning-days" }) public defaultWarningDays = 7;
/** The object's spare parts — offered as "consumes parts" checkboxes. */
@state() private parts: Array<{ id: string; name: string; unit?: string }> = [];
@state() private _open = false;
@state() private _loading = false;
@state() private _error = "";
@@ -171,6 +173,8 @@ export class MaintenanceTaskDialog extends LitElement {
@state() private _nfcTagId = "";
// v2.20 (#83): unit for `reading`-type tasks ("kWh", "m³", ...)
@state() private _readingUnit = "";
@state() private _consumesParts: Record<string, number> = {};
@state() private _partsLoadFailed = false;
@state() private _availableTags: Array<{id: string; name: string}> = [];
// User assignment
@@ -230,7 +234,7 @@ export class MaintenanceTaskDialog extends LitElement {
this._objectChoices = [];
}
this._resetFields();
await Promise.all([this._loadUsers(), this._loadTags()]);
await Promise.all([this._loadUsers(), this._loadTags(), this._loadParts()]);
this._open = true;
}
@@ -280,6 +284,7 @@ export class MaintenanceTaskDialog extends LitElement {
this._lastPerformed = task.last_performed || "";
this._nfcTagId = task.nfc_tag_id || "";
this._readingUnit = task.reading_unit || "";
this._consumesParts = Object.fromEntries((task.consumes_parts || []).map((l) => [l.part_id, l.quantity]));
this._responsibleUserId = task.responsible_user_id || null;
this._assigneePool = [...(task.assignee_pool || [])];
this._rotationStrategy = task.rotation_strategy || "";
@@ -346,7 +351,7 @@ export class MaintenanceTaskDialog extends LitElement {
this._fetchEntityAttributes(this._triggerEntityId);
}
await Promise.all([this._loadUsers(), this._loadTags()]);
await Promise.all([this._loadUsers(), this._loadTags(), this._loadParts()]);
this._open = true;
}
@@ -380,6 +385,7 @@ export class MaintenanceTaskDialog extends LitElement {
this._lastPerformed = "";
this._nfcTagId = "";
this._readingUnit = "";
this._consumesParts = {};
this._responsibleUserId = null;
this._assigneePool = [];
this._rotationStrategy = "";
@@ -662,6 +668,27 @@ export class MaintenanceTaskDialog extends LitElement {
`;
}
private async _loadParts(): Promise<void> {
// The object's parts back the "consumes parts" checkboxes. Self-loaded so
// every dialog opener (panel, card, task detail) gets them without
// threading props through.
this.parts = [];
if (!this._entryId) return;
try {
const result = (await this.hass.connection.sendMessagePromise({
type: "maintenance_supporter/object",
entry_id: this._entryId,
})) as { parts?: Array<{ id: string; name: string; unit?: string }> };
this.parts = result.parts || [];
this._partsLoadFailed = false;
} catch {
// Surface the failure: an empty-but-failed load must not just hide the
// "consumes parts" section as if the object had no parts.
this.parts = [];
this._partsLoadFailed = true;
}
}
private async _loadTags(): Promise<void> {
try {
const result = await this.hass.connection.sendMessagePromise({
@@ -762,6 +789,12 @@ export class MaintenanceTaskDialog extends LitElement {
data.last_performed = this._lastPerformed || null;
data.nfc_tag_id = this._nfcTagId || null;
data.reading_unit = this._readingUnit.trim() || null;
if (this.parts.length) {
data.consumes_parts = Object.entries(this._consumesParts).map(([part_id, quantity]) => ({
part_id,
quantity,
}));
}
data.responsible_user_id = this._responsibleUserId;
data.assignee_pool = this._assigneePool;
data.rotation_strategy =
@@ -978,6 +1011,7 @@ export class MaintenanceTaskDialog extends LitElement {
`
}
${this._renderTriggerTypeFields()}
${this._renderTriggerLiveHint()}
`}
<label>
<input
@@ -1311,6 +1345,81 @@ export class MaintenanceTaskDialog extends LitElement {
></ms-textfield>`;
}
/** Live "what happens next" hint for sensor-based triggers.
*
* Reads the bound entity's CURRENT state client-side (the dialog already
* holds `hass`) and spells out the trigger semantics against it — clearing
* the most common usage-meter confusion: a delta counter counts from the
* sensor's current reading (not from zero) and restarts after each
* completion. Renders nothing when there's no entity/state to read.
*/
private _renderTriggerLiveHint() {
if (this._triggerType === "compound") return nothing;
const entityId = this._triggerEntityId || this._triggerEntityIds[0];
if (!entityId || !this.hass?.states) return nothing;
const st = this.hass.states[entityId];
if (!st) return nothing;
const L = this._lang;
const unitAttr = st.attributes?.unit_of_measurement;
const unit = typeof unitAttr === "string" && unitAttr ? ` ${unitAttr}` : "";
const raw = this._triggerAttribute
? st.attributes?.[this._triggerAttribute]
: st.state;
const num = typeof raw === "number" ? raw : parseFloat(String(raw));
const hasNum = raw !== "unknown" && raw !== "unavailable" && raw != null && !isNaN(num);
const fmt = (v: number) => (Number.isInteger(v) ? String(v) : String(Math.round(v * 10) / 10));
const parts: string[] = [];
if (this._triggerType === "threshold") {
const above = parseFloat(this._triggerAbove);
const below = parseFloat(this._triggerBelow);
if (isNaN(above) && isNaN(below)) return nothing;
if (hasNum) parts.push(t("trigger_hint_now", L).replace("{value}", fmt(num) + unit));
if (!isNaN(above)) parts.push(t("trigger_hint_above", L).replace("{target}", fmt(above) + unit));
if (!isNaN(below)) parts.push(t("trigger_hint_below", L).replace("{target}", fmt(below) + unit));
} else if (this._triggerType === "counter") {
const target = parseFloat(this._triggerTargetValue);
if (isNaN(target)) return nothing;
if (this._triggerDeltaMode) {
if (this._taskId) {
// Editing: the baseline is the reading at the last completion (or
// task creation), not the current value — don't imply otherwise.
parts.push(t("trigger_hint_counter_delta_edit", L).replace("{target}", fmt(target) + unit));
} else if (hasNum) {
parts.push(
t("trigger_hint_counter_delta", L)
.replace("{value}", fmt(num) + unit)
.replace("{due}", fmt(num + target) + unit)
.replace("{target}", fmt(target) + unit),
);
} else {
parts.push(t("trigger_hint_counter_delta_edit", L).replace("{target}", fmt(target) + unit));
}
} else {
if (hasNum) parts.push(t("trigger_hint_now", L).replace("{value}", fmt(num) + unit));
parts.push(t("trigger_hint_counter_abs", L).replace("{target}", fmt(target) + unit));
}
} else if (this._triggerType === "runtime") {
const hours = parseFloat(this._triggerRuntimeHours);
if (isNaN(hours)) return nothing;
parts.push(t("trigger_hint_runtime", L).replace("{hours}", fmt(hours)));
parts.push(t("trigger_hint_state_now", L).replace("{value}", String(st.state)));
} else if (this._triggerType === "state_change") {
const n = parseInt(this._triggerTargetChanges, 10) || 1;
const to = this._triggerToState.trim();
parts.push(
(to
? t("trigger_hint_state_change_to", L).replace("{state}", to)
: t("trigger_hint_state_change", L)
).replace("{count}", String(n)),
);
parts.push(t("trigger_hint_state_now", L).replace("{value}", String(st.state)));
}
if (!parts.length) return nothing;
return html`<div class="trigger-live-hint">${parts.join(" ")}</div>`;
}
private _renderTriggerTypeFields() {
const L = this._lang;
if (this._triggerType === "threshold") {
@@ -1407,7 +1516,11 @@ export class MaintenanceTaskDialog extends LitElement {
<label>${t("object", L)}</label>
<select
.value=${this._entryId}
@change=${(e: Event) => (this._entryId = (e.target as HTMLSelectElement).value)}
@change=${(e: Event) => {
this._entryId = (e.target as HTMLSelectElement).value;
this._consumesParts = {};
this._loadParts();
}}
>
${this._objectChoices.map(
(o) => html`<option value=${o.entry_id} ?selected=${o.entry_id === this._entryId}>${o.name}</option>`
@@ -1442,6 +1555,49 @@ export class MaintenanceTaskDialog extends LitElement {
<div class="field-help">${t("reading_unit_help", L)}</div>
`
: nothing}
${this._partsLoadFailed
? html`<div class="field-help parts-load-failed">${t("parts_load_failed", L)}</div>`
: nothing}
${this.parts.length
? html`
<div class="field">
<label>${t("consumes_parts_label", L)}</label>
${this.parts.map((part) => {
const qty = this._consumesParts[part.id];
return html`
<div class="consumes-row">
<label class="consumes-check">
<input
type="checkbox"
.checked=${qty !== undefined}
@change=${(e: Event) => {
const next = { ...this._consumesParts };
if ((e.target as HTMLInputElement).checked) next[part.id] = next[part.id] || 1;
else delete next[part.id];
this._consumesParts = next;
}}
/>
<span>${part.name}${part.unit ? ` (${part.unit})` : ""}</span>
</label>
${qty !== undefined
? html`<input
class="consumes-qty"
type="number"
min="1"
max="999"
.value=${String(qty)}
@input=${(e: Event) => {
const v = parseInt((e.target as HTMLInputElement).value, 10);
this._consumesParts = { ...this._consumesParts, [part.id]: Number.isFinite(v) && v >= 1 ? v : 1 };
}}
/>`
: nothing}
</div>
`;
})}
</div>
`
: nothing}
<div class="select-row">
<label>${t("priority", L)}</label>
<select
@@ -1769,10 +1925,41 @@ export class MaintenanceTaskDialog extends LitElement {
resize: vertical;
box-sizing: border-box;
}
.consumes-row {
display: flex;
align-items: center;
gap: 8px;
padding: 2px 0;
}
.consumes-check {
display: flex;
align-items: center;
gap: 6px;
flex: 1;
}
.consumes-qty {
width: 64px;
padding: 4px;
border: 1px solid var(--divider-color);
border-radius: 4px;
background: var(--card-background-color);
color: var(--primary-text-color);
}
.field-help {
font-size: 12px;
color: var(--secondary-text-color);
}
/* Live computed trigger hint — reads the bound sensor and explains what
happens next. Info-accented so it reads as guidance, not an error. */
.trigger-live-hint {
font-size: 12px;
color: var(--secondary-text-color);
border-left: 3px solid var(--info-color, #2196f3);
background: rgba(33, 150, 243, 0.08);
border-radius: 0 6px 6px 0;
padding: 6px 10px;
margin: 4px 0;
}
.field-help a,
.link-button {
background: none;
@@ -1,10 +1,12 @@
/** Documents linked to a maintenance task.
/** Documents linked to a maintenance task — or (v2.26) to a spare part.
*
* A filtered view over the object's document pool via each doc's `task_ids`:
* link/unlink existing object documents to the task and open/download them. Full
* upload + management lives at the object level (documents-section); this keeps
* the manual / spare-parts list right where the maintenance work happens. Hides
* itself entirely when the object has no documents at all.
* A filtered view over the object's document pool via each doc's `task_ids`
* (task mode) or `part_ids` (part mode, set `partId` instead of `taskId`):
* link/unlink existing object documents and open/download them. Full upload +
* management lives at the object level (documents-section); this keeps the
* manual / datasheet right where the work happens. Per-task PDF page hints
* exist only in task mode. Hides itself entirely when the object has no
* documents at all.
*/
import { LitElement, html, css, nothing } from "lit";
@@ -26,6 +28,7 @@ interface Doc {
tags?: string[];
task_ids?: string[];
task_pages?: Record<string, number>;
part_ids?: string[];
}
const CATEGORIES = ["manual", "warranty", "invoice", "spare_parts", "photo", "other"] as const;
@@ -41,7 +44,9 @@ const CATEGORY_ICONS: Record<string, string> = {
export class MaintenanceTaskDocuments extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public entryId!: string;
@property({ attribute: false }) public taskId!: string;
@property({ attribute: false }) public taskId?: string;
/** Part mode: link docs to this spare part (via `part_ids`) instead of a task. */
@property({ attribute: false }) public partId?: string;
@property({ type: Boolean }) public canWrite = false;
@state() private _docs: Doc[] = [];
@@ -57,14 +62,24 @@ export class MaintenanceTaskDocuments extends LitElement {
return this.hass?.language || "en";
}
/** The id linked docs reference — a task id or (part mode) a part id. */
private get _refId(): string {
return this.partId || this.taskId || "";
}
/** The doc metadata field the link lives in. */
private get _linkField(): "task_ids" | "part_ids" {
return this.partId ? "part_ids" : "task_ids";
}
updated(changed: Map<string, unknown>): void {
super.updated(changed);
if (this.hass && !this._localeReady) {
this._localeReady = true;
void ensureLocale(this._lang).then(() => this.requestUpdate());
}
const key = `${this.entryId}|${this.taskId}`;
if (this.hass && this.entryId && this.taskId && this._loadedKey !== key) {
const key = `${this.entryId}|${this._refId}`;
if (this.hass && this.entryId && this._refId && this._loadedKey !== key) {
this._loadedKey = key;
void this._load();
}
@@ -85,22 +100,26 @@ export class MaintenanceTaskDocuments extends LitElement {
}
}
private _links(doc: Doc): string[] {
return doc[this._linkField] || [];
}
private _linked(): Doc[] {
return this._docs.filter((d) => (d.task_ids || []).includes(this.taskId));
return this._docs.filter((d) => this._links(d).includes(this._refId));
}
private _available(): Doc[] {
return this._docs.filter((d) => !(d.task_ids || []).includes(this.taskId));
return this._docs.filter((d) => !this._links(d).includes(this._refId));
}
private async _setTaskIds(doc: Doc, taskIds: string[]): Promise<void> {
private async _setLinks(doc: Doc, ids: string[]): Promise<void> {
this._busy = true;
this._error = "";
try {
await this.hass.connection.sendMessagePromise({
type: "maintenance_supporter/documents/update",
doc_id: doc.id,
task_ids: taskIds,
[this._linkField]: ids,
});
await this._load();
} catch (e) {
@@ -114,20 +133,21 @@ export class MaintenanceTaskDocuments extends LitElement {
const doc = this._docs.find((d) => d.id === this._attachId);
if (!doc) return;
this._attachId = "";
void this._setTaskIds(doc, [...(doc.task_ids || []), this.taskId]);
void this._setLinks(doc, [...this._links(doc), this._refId]);
}
private _unlink(doc: Doc): void {
void this._setTaskIds(doc, (doc.task_ids || []).filter((x) => x !== this.taskId));
void this._setLinks(doc, this._links(doc).filter((x) => x !== this._refId));
}
private _isPdf(doc: Doc): boolean {
return doc.mime === "application/pdf" || (doc.filename || "").toLowerCase().endsWith(".pdf");
}
/** The page this doc should open at for the current task, if set (PDFs only). */
/** The page this doc should open at for the current task, if set (PDFs only;
* page hints are a task-mode concept — none in part mode). */
private _pageFor(doc: Doc): number | undefined {
return this._isPdf(doc) ? doc.task_pages?.[this.taskId] : undefined;
return this._isPdf(doc) && this.taskId ? doc.task_pages?.[this.taskId] : undefined;
}
private async _open(doc: Doc): Promise<void> {
@@ -157,6 +177,7 @@ export class MaintenanceTaskDocuments extends LitElement {
/** Set (page >= 1) or clear (0) the jump-to page for this doc's task link. */
private async _setPage(doc: Doc, page: number): Promise<void> {
if (!this.taskId) return;
this._busy = true;
this._error = "";
try {
@@ -197,7 +218,7 @@ export class MaintenanceTaskDocuments extends LitElement {
<h3><ha-icon icon="mdi:paperclip"></ha-icon> ${t("documents", L)} (${linked.length})</h3>
${this._error ? html`<div class="tdoc-error">${this._error}</div>` : nothing}
${linked.length === 0
? html`<div class="tdoc-empty">${t("doc_task_none", L)}</div>`
? html`<div class="tdoc-empty">${t(this.partId ? "doc_part_none" : "doc_task_none", L)}</div>`
: html`<div class="tdoc-list">${linked.map((d) => this._renderRow(d, L))}</div>`}
${this.canWrite && available.length
? html`<div class="tdoc-attach">
@@ -223,7 +244,7 @@ export class MaintenanceTaskDocuments extends LitElement {
private _renderRow(doc: Doc, L: string) {
const isFile = doc.kind === "file";
const isPdf = this._isPdf(doc);
const page = doc.task_pages?.[this.taskId];
const page = this._pageFor(doc);
const cat = (doc.tags || []).find((x) => (CATEGORIES as readonly string[]).includes(x)) || "other";
const meta = isFile ? formatBytes(doc.size) : t("doc_link_badge", L);
return html`
@@ -247,7 +268,7 @@ export class MaintenanceTaskDocuments extends LitElement {
${meta}${page ? html` · <span class="tdoc-pagetag">${t("doc_page", L)} ${page}</span>` : nothing}
</div>
</div>
${this.canWrite && isPdf
${this.canWrite && isPdf && this.taskId
? html`<input
class="tdoc-page"
type="number"