diff --git a/api/.vulture_whitelist b/api/.vulture_whitelist index 4acf016..294f3eb 100644 --- a/api/.vulture_whitelist +++ b/api/.vulture_whitelist @@ -1,15 +1,19 @@ get_index # unused function (src/api/app.py:43) -list_autos # unused function (src/api/routes/automations.py:18) -upsert_auto # unused function (src/api/routes/automations.py:29) -delete_auto # unused function (src/api/routes/automations.py:37) +list_autos # unused function (src/api/routes/automations.py:12) +upsert_auto # unused function (src/api/routes/automations.py:24) +delete_auto # unused function (src/api/routes/automations.py:32) read_details # unused function (src/api/routes/details.py:10) read_ping # unused function (src/api/routes/ping.py:10) websocket_endpoint # unused function (src/api/routes/socket.py:13) -params # unused variable (src/api/types.py:18) -total_items # unused variable (src/api/types.py:19) -trigger_variables # unused variable (src/automations/types.py:11) -_.reload # unused method (src/automations_v2/manager.py:29) -_.upsert # unused method (src/automations_v2/manager.py:54) -trigger_variables # unused variable (src/automations_v2/types.py:12) -action # unused variable (src/automations_v2/types.py:16) +params # unused variable (src/api/types.py:16) +total_items # unused variable (src/api/types.py:17) +data # unused variable (src/api/types.py:18) +trigger_variables # unused variable (src/automations/types.py:13) +trigger # unused variable (src/automations/types.py:15) +condition # unused variable (src/automations/types.py:16) +action # unused variable (src/automations/types.py:17) +_.to_json # unused method (src/automations/types.py:38) +_.automation_tags # unused property (src/hass_config/loader.py:18) +_.save_automations # unused method (src/hass_config/loader.py:48) +_.save_tags # unused method (src/hass_config/loader.py:56) json_dumps # unused function (src/json_serializer.py:5) diff --git a/api/src/api/routes/automations.py b/api/src/api/routes/automations.py index 5d4b754..5898a41 100644 --- a/api/src/api/routes/automations.py +++ b/api/src/api/routes/automations.py @@ -1,10 +1,6 @@ from fastapi import APIRouter, HTTPException -from src.api.types import ( - ListData, - ListParams, - UpdateTags, -) +from src.api.types import ListData, ListParams, UpdateTags from src.automations.errors import FailedDeletion from src.automations.manager import AutomationManager from src.automations.types import ExtenededAutomation diff --git a/api/src/api/types.py b/api/src/api/types.py index e4ed78d..708f9f5 100644 --- a/api/src/api/types.py +++ b/api/src/api/types.py @@ -4,8 +4,6 @@ from pydantic import BaseModel from pydantic.fields import Field from pydantic.generics import GenericModel -from src.automations.types import ExtenededAutomation - DataT = TypeVar("DataT") diff --git a/api/src/hass_config/errors.py b/api/src/hass_config/errors.py deleted file mode 100644 index cda3e2b..0000000 --- a/api/src/hass_config/errors.py +++ /dev/null @@ -1,6 +0,0 @@ -class HassConfigError(Exception): - pass - - -class MissingFile(HassConfigError): - pass diff --git a/api/src/hass_config/loader.py b/api/src/hass_config/loader.py index 1c4c6e5..d1feafc 100644 --- a/api/src/hass_config/loader.py +++ b/api/src/hass_config/loader.py @@ -5,8 +5,6 @@ from src.automations.tags import TagManager from src.yaml_serializer import dump_yaml, load_yaml from src.yaml_serializer.types import IncludedYaml -from .errors import MissingFile - class HassConfig: def __init__(self, root_path: Path) -> None: diff --git a/api/tests/unittests/hass_config/test_loader.py b/api/tests/unittests/hass_config/test_loader.py index 3cd44de..4ff249b 100644 --- a/api/tests/unittests/hass_config/test_loader.py +++ b/api/tests/unittests/hass_config/test_loader.py @@ -1,7 +1,6 @@ from unittest import TestCase from src.automations.types import BaseAutomation -from src.hass_config.errors import MissingFile from src.hass_config.loader import HassConfig from tests.utils import create_dummy_config_folder diff --git a/webapp/.vscode/settings.json b/webapp/.vscode/settings.json new file mode 100644 index 0000000..09b1957 --- /dev/null +++ b/webapp/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "task.allowAutomaticTasks": true +} diff --git a/webapp/src/apiService/automations.ts b/webapp/src/apiService/automations.ts index 646be0a..df5cb74 100644 --- a/webapp/src/apiService/automations.ts +++ b/webapp/src/apiService/automations.ts @@ -18,13 +18,10 @@ export const makeAutomationAPI = (api: API) => ({ }); return data; }, - async update({ index, auto }: { index: number; auto: AutomationData }) { + async update(auto: AutomationData) { return await api.makeCall({ path: AUTOMTAION_ITEM, - data: { - index, - data: auto, - }, + data: auto, }); }, async updateTags({ @@ -42,13 +39,11 @@ export const makeAutomationAPI = (api: API) => ({ }, }); }, - async remove({ index }: { index: number }) { + async remove(auto: AutomationData) { return await api.makeCall({ method: "DELETE", path: AUTOMTAION_ITEM, - data: { - index, - }, + data: auto, }); }, }); diff --git a/webapp/src/apiService/mock.test.ts b/webapp/src/apiService/mock.test.ts index dae0e91..aa39722 100644 --- a/webapp/src/apiService/mock.test.ts +++ b/webapp/src/apiService/mock.test.ts @@ -24,12 +24,12 @@ test("mock api uses initial autos for initial population -- some data", async () test("populate mock api with some data", async () => { const mockApi = makeAutomationAPI(useMockAPI([], fakeUseRef as any)); - await mockApi.update({ index: 0, auto: createMockAuto() }); + await mockApi.update(createMockAuto()); let data = await mockApi.list({ limit: 10, offset: 0 }); expect(data.ok).toBe(true); expect((data as any).data.data).toHaveLength(1); expect((data as any).data.totalItems).toBe(1); - await mockApi.update({ index: 1, auto: createMockAuto() }); + await mockApi.update(createMockAuto()); data = await mockApi.list({ limit: 10, offset: 0 }); expect((data as any).data.data).toHaveLength(2); expect((data as any).data.totalItems).toBe(2); @@ -50,13 +50,13 @@ test("delete/update data from mock api", async () => { ); let data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data.data; const toBeEdited = data[0]; - toBeEdited.metadata.alias = "Bob is my uncle"; - await mockApi.update({ index: 0, auto: toBeEdited }); + toBeEdited.alias = "Bob is my uncle"; + await mockApi.update(toBeEdited); data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data.data; - expect(data[0].metadata.alias).toEqual("Bob is my uncle"); - await mockApi.remove({ index: 0 }); + expect(data[0].alias).toEqual("Bob is my uncle"); + await mockApi.remove(data[0]); data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data.data; - expect(data[0].metadata.alias === "Bob is my uncle").toEqual(false); + expect(data[0].alias === "Bob is my uncle").toEqual(false); }); test("update tags from mock api", async () => { @@ -74,7 +74,7 @@ test("update tags from mock api", async () => { ); let data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data .data as AutomationData[]; - const autoId = data[0].metadata.id; + const autoId = data[0].id; expect(data[0].tags).toStrictEqual({}); mockApi.updateTags({ automation_id: autoId, @@ -85,7 +85,7 @@ test("update tags from mock api", async () => { }); data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data .data as AutomationData[]; - expect(data[0].metadata.id).toEqual(autoId); + expect(data[0].id).toEqual(autoId); expect(data[0].tags).toStrictEqual({ room: "bathroom", type: "popup", diff --git a/webapp/src/apiService/mock.ts b/webapp/src/apiService/mock.ts index d1f88f0..4899175 100644 --- a/webapp/src/apiService/mock.ts +++ b/webapp/src/apiService/mock.ts @@ -36,8 +36,11 @@ export const useMockAPI = ( } if (path === AUTOMTAION_ITEM) { if (method === "POST") { - const { index, data: auto } = data as any; - if (index >= automationsRef.current.length) { + const auto = data as AutomationData; + const index = automationsRef.current.findIndex( + ({ id }) => auto.id === id + ); + if (index < 0) { automationsRef.current = [...automationsRef.current, auto]; } else { automationsRef.current = [ @@ -51,11 +54,10 @@ export const useMockAPI = ( data: {}, }; } else if (method === "DELETE") { - const { index } = data as any; - automationsRef.current = [ - ...automationsRef.current.slice(0, index), - ...automationsRef.current.slice(index + 1), - ]; + const auto = data as AutomationData; + automationsRef.current = automationsRef.current.filter( + ({ id }) => id !== auto.id + ); return { ok: true, data: {}, @@ -67,7 +69,7 @@ export const useMockAPI = ( const { automation_id, tags } = data as any; for (let i = 0; i < automationsRef.current.length; i++) { const auto = automationsRef.current[i]; - if (auto.metadata.id === automation_id) { + if (auto.id === automation_id) { automationsRef.current[i].tags = JSON.parse(JSON.stringify(tags)); break; } diff --git a/webapp/src/components/AutomationEditor/index.stories.tsx b/webapp/src/components/AutomationEditor/index.stories.tsx index 5b7bffc..aa69933 100644 --- a/webapp/src/components/AutomationEditor/index.stories.tsx +++ b/webapp/src/components/AutomationEditor/index.stories.tsx @@ -21,7 +21,7 @@ const Template: ComponentStory = (args) => { {} )} automation={state} @@ -46,16 +46,13 @@ Simple.args = { Type: "Smell", Use: "Flushing", }, - metadata: { - id: - "random" + String(Date.now()) + String(Date.now()) + String(Date.now()), - alias: "Random", - description: "Example Metadata", - trigger_variables: { - wowo: "!", - }, - mode: "single", + id: "random" + String(Date.now()) + String(Date.now()) + String(Date.now()), + alias: "Random", + description: "Example Metadata", + trigger_variables: { + wowo: "!", }, + mode: "single", trigger: [ { platform: "numeric_state", @@ -66,7 +63,7 @@ Simple.args = { event: "start", }, ], - sequence: [ + action: [ { condition: "and", conditions: [ @@ -102,17 +99,15 @@ EmptyStart.args = { automation: { condition: [], tags: {}, - metadata: { - id: "random", - alias: "Random", - description: "Example Metadata", - trigger_variables: { - wowo: "!", - }, - mode: "single", + id: "random", + alias: "Random", + description: "Example Metadata", + trigger_variables: { + wowo: "!", }, + mode: "single", trigger: [], - sequence: [], + action: [], }, }; @@ -122,10 +117,9 @@ BadAutomationInvalidMetadata.args = { automation: { condition: [], tags: {}, - metadata: {} as any, trigger: [], - sequence: [], - }, + action: [], + } as any, }; export const BadAutomationInvalidTriggers = Template.bind({}); @@ -134,17 +128,15 @@ BadAutomationInvalidTriggers.args = { automation: { condition: [], tags: {}, - metadata: { - id: "random", - alias: "Random", - description: "Example Metadata", - trigger_variables: { - wowo: "!", - }, - mode: "single", + id: "random", + alias: "Random", + description: "Example Metadata", + trigger_variables: { + wowo: "!", }, + mode: "single", trigger: ["haha I am a string"] as any, - sequence: [], + action: [], }, }; @@ -154,34 +146,29 @@ BadAutomationInvalidSequence.args = { automation: { condition: [], tags: {}, - metadata: { - id: "random", - alias: "Bad Choose Sequence", - description: "Example Metadata", - trigger_variables: { - wowo: "!", - }, - mode: "single", + alias: "Bad Choose Sequence", + description: "Example Metadata", + trigger_variables: { + wowo: "!", }, + mode: "single", trigger: [], - sequence: [ + action: [ { choose: {}, }, - ] as any, - }, + ], + } as any, }; export const RepeatExample = Template.bind({}); RepeatExample.args = { ...RepeatExample.args, automation: { - metadata: { - id: "1654976151462", - alias: "Get out of baby room", - description: "", - mode: "single", - }, + id: "1654976151462", + alias: "Get out of baby room", + description: "", + mode: "single", trigger: [ { type: "opened", @@ -192,7 +179,7 @@ RepeatExample.args = { }, ], condition: [], - sequence: [ + action: [ { service: "notify.mobile_app_levas_phone", data: { diff --git a/webapp/src/components/AutomationEditor/index.tsx b/webapp/src/components/AutomationEditor/index.tsx index 0ff84c8..2a97077 100644 --- a/webapp/src/components/AutomationEditor/index.tsx +++ b/webapp/src/components/AutomationEditor/index.tsx @@ -99,7 +99,7 @@ export const AutomationEditor: FC = ({ )} = ({
-
{state.data.metadata.id}
+
{state.data.id}
updateMetadata( { - ...state.data.metadata, + ...state.data, alias, }, state.data.tags @@ -148,13 +148,13 @@ export const AutomationEditor: FC = ({ label="Mode" className="automation-editor--flow-wrapper--toolbar--modes" current={{ - id: state.data.metadata.mode, + id: state.data.mode, label: "", }} onChange={({ id }) => updateMetadata( { - ...state.data.metadata, + ...state.data, mode: id, }, state.data.tags @@ -185,12 +185,12 @@ export const AutomationEditor: FC = ({ /> updateMetadata( { - ...state.data.metadata, + ...state.data, description, }, state.data.tags @@ -221,10 +221,10 @@ export const AutomationEditor: FC = ({
(k: K) => - (d: EditorData[K]) => { - const newData = { - ...data, - [k]: d, - }; - const newFails = props.validate(newData); - if (newFails) { - setState({ - failures: newFails, - data: newData, - }); - } else { - setState({ - failures: [], - data: newData, - }); - } + const onSave = (d: EditorData) => { + const newData = { + ...data, + ...d, }; + const newFails = props.validate(newData); + if (newFails) { + setState({ + failures: newFails, + data: newData, + }); + } else { + setState({ + failures: [], + data: newData, + }); + } + }; return (
@@ -317,27 +315,7 @@ export const ValidationBox: FC<{ Please correct the automation file manually and then continue! - - - - - + diff --git a/webapp/src/components/AutomationEditor/state.ts b/webapp/src/components/AutomationEditor/state.ts index 80ddb6c..f93a2a4 100644 --- a/webapp/src/components/AutomationEditor/state.ts +++ b/webapp/src/components/AutomationEditor/state.ts @@ -90,7 +90,7 @@ export const useAutomatioEditorState = ( return { validate: (data: any) => getFailures(data, v.AutomationData), updateTrigger: makeUpdate("trigger"), - updateSequence: makeUpdate("sequence"), + updateSequence: makeUpdate("action"), updateCondition: makeUpdate("condition"), saveAndUpdate, updateMetadata: ( @@ -107,7 +107,7 @@ export const useAutomatioEditorState = ( data: { ...state.data, tags, - metadata, + ...metadata, }, }); } @@ -140,16 +140,17 @@ export const useAutomatioEditorState = ( }; const genEditorData = (automation: AutomationData) => { - const { metadata, trigger, sequence, condition } = automation; + const { tags: rawTags, trigger, action, condition, ...metadata } = automation; - const tags: [string, string][] = Object.keys(automation.tags).map( - (tagName) => [tagName, automation.tags[tagName]] - ); + const tags: [string, string][] = Object.keys(rawTags).map((tagName) => [ + tagName, + rawTags[tagName], + ]); return { - metadata, + ...metadata, trigger, - sequence, + action, condition, tags, }; diff --git a/webapp/src/components/AutomationManager/Loaded/automationDB.ts b/webapp/src/components/AutomationManager/Loaded/automationDB.ts index a2aacf1..5aea70a 100644 --- a/webapp/src/components/AutomationManager/Loaded/automationDB.ts +++ b/webapp/src/components/AutomationManager/Loaded/automationDB.ts @@ -46,10 +46,10 @@ export const useAutomationDB = ( const auto = defaultAutomation(String(Date.now())); setNewAuto([ { - id: auto.metadata.id, + id: auto.id, entityId: "", - title: auto.metadata.alias ?? "", - description: auto.metadata.description ?? "", + title: auto.alias ?? "", + description: auto.description ?? "", state: "unregistered", tags: {}, issue: "New Automation", @@ -70,7 +70,7 @@ const genMapping = ( const configData: Record = configAutomations.reduce( (all, n) => ({ ...all, - [n.metadata.id]: n, + [n.id]: n, }), {} ); @@ -91,8 +91,8 @@ const genMapping = ( if (configData[autoId]) { found = configData[entityData.attributes.id]; - title = found.metadata.alias ?? title; - description = found.metadata.description ?? description; + title = found.alias ?? title; + description = found.description ?? description; delete configData[autoId]; } else { issue = "failed to find this automation in '/config' folder"; @@ -113,14 +113,14 @@ const genMapping = ( }); Object.values(configData).forEach((auto) => { - automatioinMap[auto.metadata.id] = [ + automatioinMap[auto.id] = [ { - id: auto.metadata.id, + id: auto.id, entityId: "", - title: auto.metadata.alias ?? "", - description: auto.metadata.description ?? "", + title: auto.alias ?? "", + description: auto.description ?? "", state: "unregistered", - tags: tagsDB.getTags(auto.metadata.id), + tags: tagsDB.getTags(auto.id), issue: "homeassistant did not load this automation, try to manually reload automations or restart homeassistant.", }, diff --git a/webapp/src/components/AutomationManager/Loaded/state.ts b/webapp/src/components/AutomationManager/Loaded/state.ts index 5c2e26b..6bffc2f 100644 --- a/webapp/src/components/AutomationManager/Loaded/state.ts +++ b/webapp/src/components/AutomationManager/Loaded/state.ts @@ -13,7 +13,7 @@ export type UseAutomationManagerStateArgs = { hassEntities: HassEntities; onUpdateTags: (aid: string, tags: Record) => void; onAutomationAdd: (auto: AutomationData) => void; - onAutomationUpdate: (aid: string, auto: AutomationData) => void; + onAutomationUpdate: (auto: AutomationData) => void; onAutomationStateChange: (eid: string, on: boolean) => void; onAutomationRun: (eid: string) => void; }; @@ -30,10 +30,12 @@ export const useAutomationManagerState = ({ const snackbr = useSnackbar(); const cookies = useAMSCookies(); const tagsDB = useTagDB( - configAutomations.map(({ metadata: { id }, tags }) => ({ - id, - tags, - })), + configAutomations + .filter((a) => typeof a === "object") + .map(({ id, tags = {} }) => ({ + id, + tags, + })), onUpdateTags ); const automationDB = useAutomationDB(hassEntities, configAutomations, tagsDB); @@ -91,13 +93,13 @@ export const useAutomationManagerState = ({ } } const auto = automationDB.addNew(); - methods.setSelectedAutomationId(auto.metadata.id, true); + methods.setSelectedAutomationId(auto.id, true); }, editorUpdateAutomation(auto: AutomationData) { if (methods.currentAutomationIsNew) { onAutomationAdd(auto); } else if (methods.currentAutomationId) { - onAutomationUpdate(methods.currentAutomationId, auto); + onAutomationUpdate(auto); } }, sideBarUpdateAutomation( @@ -109,16 +111,13 @@ export const useAutomationManagerState = ({ if (previousAuto && previousAuto[1]) { const previousAutoState = previousAuto[1]; if ( - previousAutoState.metadata.alias !== a.title || - previousAutoState.metadata.description !== a.description + previousAutoState.alias !== a.title || + previousAutoState.description !== a.description ) { - onAutomationUpdate(aid, { + onAutomationUpdate({ ...previousAutoState, - metadata: { - ...previousAutoState.metadata, - alias: a.title, - description: a.description, - }, + alias: a.title, + description: a.description, }); } } else { diff --git a/webapp/src/components/AutomationManager/automationGrouper.test.ts b/webapp/src/components/AutomationManager/automationGrouper.test.ts index a90a245..6cf88c4 100644 --- a/webapp/src/components/AutomationManager/automationGrouper.test.ts +++ b/webapp/src/components/AutomationManager/automationGrouper.test.ts @@ -4,41 +4,51 @@ import { AutomationManagerAuto } from "./types"; const automations: AutomationManagerAuto[] = [ createMockAuto({ - Room: "Living Room", - Type: "Lights", + tags: { + Room: "Living Room", + Type: "Lights", + }, }), createMockAuto({ - Room: "Living Room", - Type: "Climate", + tags: { + Room: "Living Room", + Type: "Climate", + }, }), createMockAuto({ - Room: "Kitchen", - Type: "Climate", + tags: { + Room: "Kitchen", + Type: "Climate", + }, }), createMockAuto({ - Type: "Climate", + tags: { + Type: "Climate", + }, }), createMockAuto({ - Room: "Living Room", + tags: { + Room: "Living Room", + }, }), createMockAuto({}), ].map((a) => ({ - title: a.metadata.alias ?? "", - entityId: "automation." + a.metadata.id, - description: a.metadata.description ?? "", + title: a.alias ?? "", + entityId: "automation." + a.id, + description: a.description ?? "", state: "on", tags: a.tags, - id: a.metadata.id, + id: a.id, isSelected: false, })); const bigList = bigMockAutoList.map((a) => ({ - entityId: "automation." + a.metadata.id, - title: a.metadata.alias ?? "", - description: a.metadata.description ?? "", + entityId: "automation." + a.id, + title: a.alias ?? "", + description: a.description ?? "", state: "on", tags: a.tags, - id: a.metadata.id, + id: a.id, isSelected: false, })); diff --git a/webapp/src/components/AutomationManager/index.css b/webapp/src/components/AutomationManager/index.css index 3eeea57..bfaca38 100644 --- a/webapp/src/components/AutomationManager/index.css +++ b/webapp/src/components/AutomationManager/index.css @@ -23,4 +23,22 @@ .automation-manager.loading .automation-manager--editor.loading { flex: 1; height: 100%; +} + + +.invalid-automation-modal-list { + display: flex; + max-height: 50vh; + overflow: auto; + flex-direction: column; +} + +.invalid-automation-modal-list li { + display: flex; + flex-direction: column; +} + +.invalid-automation-modal-list--errors ul { + max-height: 10vh; + overflow: auto; } \ No newline at end of file diff --git a/webapp/src/components/AutomationManager/index.stories.tsx b/webapp/src/components/AutomationManager/index.stories.tsx index 0b0939c..7ae308d 100644 --- a/webapp/src/components/AutomationManager/index.stories.tsx +++ b/webapp/src/components/AutomationManager/index.stories.tsx @@ -79,17 +79,17 @@ export const Empty = make({ }, }); const auto1 = createMockAuto({ - type: "button", + tags: { type: "button" }, }); export const One = make({ automations: [auto1], haProps: { loading: false, entities: { - [`automation.${auto1.metadata.id}`]: { - entity_id: `automation.${auto1.metadata.id}`, + [`automation.${auto1.id}`]: { + entity_id: `automation.${auto1.id}`, attributes: { - id: auto1.metadata.id, + id: auto1.id, }, context: { id: "", parent_id: null, user_id: null }, last_changed: "", @@ -105,11 +105,11 @@ export const MissingAutoInConfig = make({ haProps: { loading: false, entities: { - [`automation.${auto1.metadata.id}`]: { - entity_id: `automation.${auto1.metadata.id}`, + [`automation.${auto1.id}`]: { + entity_id: `automation.${auto1.id}`, attributes: { - id: auto1.metadata.id, - friendly_name: auto1.metadata.alias, + id: auto1.id, + friendly_name: auto1.alias, }, context: { id: "", parent_id: null, user_id: null }, last_changed: "", @@ -120,12 +120,22 @@ export const MissingAutoInConfig = make({ entitySource: {}, }, }); + +export const CrashingAutomations = make({ + haProps: { + loading: false, + entities: {}, + entitySource: {}, + }, + automations: [""] as any, +}); + export const BadAutomation = make({ haProps: { loading: false, entities: { - [`automation.${auto1.metadata.id}`]: { - entity_id: `automation.${auto1.metadata.id}`, + [`automation.${auto1.id}`]: { + entity_id: `automation.${auto1.id}`, attributes: { id: "test", }, @@ -140,12 +150,10 @@ export const BadAutomation = make({ automations: [ { tags: {}, - metadata: { - id: "test", - mode: "single", - alias: "Light.Tank_Day", - description: "", - }, + id: "test", + mode: "single", + alias: "Light.Tank_Day", + description: "", trigger: [ { platform: "sun", @@ -155,7 +163,7 @@ export const BadAutomation = make({ { whoAmI: "bad node is who" } as any, ], condition: [{ whoAmI: "bad node is who" } as any], - sequence: [ + action: [ { scene: "scene.light_day" } as any, { whoAmI: "bad node is who" } as any, { @@ -171,3 +179,40 @@ export const BadAutomation = make({ }, ], }); + +export const OneCrashingOneGoodAutomations = make({ + haProps: { + loading: false, + entities: { + [`automation.${auto1.id}`]: { + entity_id: `automation.${auto1.id}`, + attributes: { + id: auto1.id, + }, + context: { id: "", parent_id: null, user_id: null }, + last_changed: "", + last_updated: "", + state: "on", + }, + "1235": { + entity_id: `automation.1235`, + attributes: { + id: "1235", + }, + context: { id: "", parent_id: null, user_id: null }, + last_changed: "", + last_updated: "", + state: "on", + }, + }, + entitySource: {}, + }, + automations: [ + auto1, + { + id: "1235", + tags: {}, + } as any, + "" as any, + ], +}); diff --git a/webapp/src/components/AutomationManager/index.tsx b/webapp/src/components/AutomationManager/index.tsx index c1f6881..f7639af 100644 --- a/webapp/src/components/AutomationManager/index.tsx +++ b/webapp/src/components/AutomationManager/index.tsx @@ -1,6 +1,6 @@ import "./index.css"; -import { FC, useEffect, useState } from "react"; +import { FC, useEffect, useRef, useState } from "react"; import LinearProgress from "@mui/material/LinearProgress"; import Skeleton from "@mui/material/Skeleton"; @@ -9,6 +9,11 @@ import { HAEntitiesState } from "haService/HAEntities"; import { AutomationManagerLoaded } from "./Loaded"; import { Alert } from "@mui/material"; import { useSnackbar } from "notistack"; +import { ErrorBoundary } from "components/ErrorBoundary"; +import { getFailures } from "types/validators/helper"; +import * as av from "types/validators/autmation"; +import { useConfirm } from "material-ui-confirm"; +import InputYaml from "components/Inputs/Base/InputYaml"; export type AutomationManagerProps = { onAutomationStateChange: (eid: string, on: boolean) => void; @@ -28,6 +33,8 @@ export const AutomationManager: FC = ({ triggerAutomation, }) => { const snackbr = useSnackbar(); + const confirm = useConfirm(); + const validationsShown = useRef(false); const [isSaving, setIsSaving] = useState(false); useEffect(() => { @@ -35,6 +42,68 @@ export const AutomationManager: FC = ({ // eslint-disable-next-line }, []); + useEffect(() => { + if ( + api.state.automations.ready && + api.state.automations.ok && + !validationsShown.current + ) { + const configAutomationsValidated = api.state.automations.data.data.map( + (a) => { + const failures = getFailures(a, av.AutomationData); + return { + automation: a, + failures, + }; + } + ); + const invalidAutomations = configAutomationsValidated.filter( + ({ failures }) => failures !== null + ); + if (invalidAutomations.length > 0) { + validationsShown.current = true; + confirm({ + cancellationButtonProps: { + style: { display: "none" }, + }, + title: "Invalid Automations detected!", + content: ( + <> +
    + {invalidAutomations.map(({ automation, failures }, i) => ( +
  1. + Automation + {}} + /> + Errors + +
      + {failures && + failures.map((f, fi) => ( +
    • + {f.path}: {f.message.join(", ")} +
    • + ))} +
    +
    +
  2. + ))} +
+ + ), + }) + .then(console.info) + .catch(console.error); + } + } + }, [api.state.automations, validationsShown.current]); + // handle bad states if (!haEntities.ready && haEntities.error) { return ( @@ -75,78 +144,74 @@ export const AutomationManager: FC = ({ } // alias - const configAutomations = api.state.automations.data; + const hassEntities = haEntities.collection; + const configAutomations = api.state.automations.data; + return ( - { - await api.updateAutomation({ - index: configAutomations.totalItems + 1, - auto, - }); - refreshAutomations(); - }} - onAutomationDelete={(aid, eid) => { - const index = configAutomations.data.findIndex( - ({ metadata }) => metadata.id === aid - ); - let deleteSent = false; - if (index >= 0) { - api.removeAutomation({ - index, - }); - deleteSent = true; - } - const hassAuto = hassEntities[eid]; - if (hassAuto) { - forceDeleteAutomation(eid); - deleteSent = true; - } - if (!deleteSent) { - snackbr.enqueueSnackbar( - "Failed to delete automation, this may be resolved by a refresh or reboot of Home Assistant", - { - variant: "error", - } - ); - } - // refreshAutomations(); - }} - onAutomationUpdate={(aid, auto) => { - const index = configAutomations.data.findIndex( - ({ metadata }) => metadata.id === aid - ); - if (index >= 0) { - api.updateAutomation({ - index: configAutomations.data.findIndex( - ({ metadata }) => metadata.id === aid - ), - auto, - }); - refreshAutomations(); - } else { - snackbr.enqueueSnackbar( - "Failed to update automation, this may be resolved by a refresh or reboot of Home Assistant.", - { - variant: "error", - } - ); - } - }} - onUpdateTags={async (aid, t) => { - setIsSaving(true); - await api.updateTags({ - automation_id: aid, - tags: t, - }); - setIsSaving(false); + - {isSaving && } - + { + await api.updateAutomation(auto); + refreshAutomations(); + }} + onAutomationDelete={(aid, eid) => { + const autoToDelete = configAutomations.data.find( + ({ id }) => id === aid + ); + let deleteSent = false; + if (autoToDelete) { + api.removeAutomation(autoToDelete); + deleteSent = true; + } + const hassAuto = hassEntities[eid]; + if (hassAuto) { + forceDeleteAutomation(eid); + deleteSent = true; + } + if (!deleteSent) { + snackbr.enqueueSnackbar( + "Failed to delete automation, this may be resolved by a refresh or reboot of Home Assistant", + { + variant: "error", + } + ); + } + // refreshAutomations(); + }} + onAutomationUpdate={(auto) => { + api + .updateAutomation(auto) + .then(() => refreshAutomations()) + .catch(() => { + snackbr.enqueueSnackbar( + "Failed to update automation, this may be resolved by a refresh or reboot of Home Assistant.", + { + variant: "error", + } + ); + }); + }} + onUpdateTags={async (aid, t) => { + setIsSaving(true); + await api.updateTags({ + automation_id: aid, + tags: t, + }); + setIsSaving(false); + }} + > + {isSaving && } + + ); }; diff --git a/webapp/src/components/DAGGraph/elements/index.stories.tsx b/webapp/src/components/DAGGraph/elements/index.stories.tsx index 84bfcf3..a4b0019 100644 --- a/webapp/src/components/DAGGraph/elements/index.stories.tsx +++ b/webapp/src/components/DAGGraph/elements/index.stories.tsx @@ -53,7 +53,7 @@ const { make, componentMeta } = makeStory({ automation: { trigger: [], condition: [], - sequence: [], + action: [], }, }, }, @@ -74,7 +74,7 @@ export const Trigger = make({ }, ], condition: [], - sequence: [], + action: [], }, }); @@ -110,7 +110,7 @@ export const Conditions = make({ below: "15", }, ], - sequence: [], + action: [], }, }); @@ -151,7 +151,7 @@ export const FullAuto = make({ bad: "node", } as any, ], - sequence: [ + action: [ { condition: "and", conditions: [ @@ -269,7 +269,7 @@ export const ChooseAuto = make({ automation: { condition: [], trigger: [], - sequence: [ + action: [ { choose: [ { @@ -365,7 +365,7 @@ export const EmptyChooseAuto = make({ automation: { condition: [], trigger: [], - sequence: [ + action: [ { choose: [], default: [], @@ -378,7 +378,7 @@ export const RepeatAuto = make({ automation: { condition: [], trigger: [], - sequence: [ + action: [ { repeat: { while: 'states(lights.switch) == "on"', @@ -427,7 +427,7 @@ export const ParallelAuto = make({ automation: { condition: [], trigger: [], - sequence: [ + action: [ { parallel: [ { @@ -469,7 +469,7 @@ export const BadNodes = make({ { condition: "and" }, "text?", ] as any, - sequence: [ + action: [ { parallel: { bad: "me", @@ -486,7 +486,7 @@ export const IfElseNode = make({ automation: { condition: [], trigger: [], - sequence: [ + action: [ { if: [], else: [], @@ -508,7 +508,7 @@ export const TimeNodes = make({ platform: "time_pattern", }, ], - sequence: [ + action: [ { condition: "time", }, diff --git a/webapp/src/components/DAGGraph/elements/index.tsx b/webapp/src/components/DAGGraph/elements/index.tsx index 37c55be..1a0d525 100644 --- a/webapp/src/components/DAGGraph/elements/index.tsx +++ b/webapp/src/components/DAGGraph/elements/index.tsx @@ -63,7 +63,7 @@ export const useAutomationNodes = ( ); outputState.extend( - makeSequenceNodes(automation.sequence, { + makeSequenceNodes(automation.action, { ...args, state, dims, @@ -74,7 +74,7 @@ export const useAutomationNodes = ( dims, true ), - nodeId: `${dims.flipped}-sequence`, + nodeId: `${dims.flipped}-action`, nodeIndex: 2, lastNodeId: outputState.lastNodeId, }) @@ -98,7 +98,7 @@ export const makeSequenceNodes: ElementMaker = ( enabled: node.enabled ?? true, label: getDescriptionFromAutomationNode(node, namer, true), ...state.getIsClosedActions(nodeId, node), - ...stateUpdater.createNodeActions("sequence", nodeIndex, { + ...stateUpdater.createNodeActions("action", nodeIndex, { includeAdd: true, flipped: dims.flipped, }), @@ -153,7 +153,7 @@ export const makeSequenceNodes: ElementMaker = ( dims, { icon: , - onClick: () => stateUpdater.basic.sequence.addNode(null), + onClick: () => stateUpdater.basic.action.addNode(null), } ), true @@ -261,7 +261,7 @@ export const makeChooseeNodes = makeSpecialNodeMaker( nodeId: args.nodeId, position: pos, onClick: () => - args.stateUpdater.basic.sequence.updateNode( + args.stateUpdater.basic.action.updateNode( { ...node, choose: [ @@ -464,10 +464,10 @@ export const makeParallelNodes = makeSpecialNodeMaker( onClick: () => args.openModal({ allowedTypes: ["condition", "action"], - node: args.stateUpdater.basic.sequence.defaultNode, + node: args.stateUpdater.basic.action.defaultNode, saveBtnCreateText: true, update: (n) => - args.stateUpdater.basic.sequence.updateNode( + args.stateUpdater.basic.action.updateNode( { ...node, parallel: [...node.parallel, n], diff --git a/webapp/src/components/DAGGraph/index.tsx b/webapp/src/components/DAGGraph/index.tsx index 1c8a996..d6ad849 100644 --- a/webapp/src/components/DAGGraph/index.tsx +++ b/webapp/src/components/DAGGraph/index.tsx @@ -10,10 +10,10 @@ import { AutomationTrigger } from "types/automations/triggers"; import { AutomationCondition } from "types/automations/conditions"; export const DAGAutomationGraph: FC<{ - sequence: AutomationSequenceNode[]; + action: AutomationSequenceNode[]; trigger: AutomationTrigger[]; condition: AutomationCondition[]; - onSequenceUpdate: (s: AutomationSequenceNode[]) => void; + onActionUpdate: (s: AutomationSequenceNode[]) => void; onTriggerUpdate: (t: AutomationTrigger[]) => void; onConditionUpdate: (c: AutomationCondition[]) => void; isFlipped: boolean; @@ -24,9 +24,9 @@ export const DAGAutomationGraph: FC<{ useState(undefined); const updater = createUpdater({ openModal: setModalState, - sequence: { - data: props.sequence, - onUpdate: props.onSequenceUpdate, + action: { + data: props.action, + onUpdate: props.onActionUpdate, }, condition: { data: props.condition, @@ -39,7 +39,7 @@ export const DAGAutomationGraph: FC<{ }); const elementData = useAutomationNodes( { - sequence: props.sequence, + action: props.action, condition: props.condition, trigger: props.trigger, }, diff --git a/webapp/src/components/DAGGraph/nodes/CollectionNode/index.tsx b/webapp/src/components/DAGGraph/nodes/CollectionNode/index.tsx index 4e169dc..dda302d 100644 --- a/webapp/src/components/DAGGraph/nodes/CollectionNode/index.tsx +++ b/webapp/src/components/DAGGraph/nodes/CollectionNode/index.tsx @@ -10,7 +10,7 @@ export const CollectionNodeMaker = NodeManager.register( ...pre, color: (pre.collectionType === "condition" ? "blue" - : pre.collectionType === "sequence" + : pre.collectionType === "action" ? "green" : "red") as SequenceNodeColor, sequenceNode: node, diff --git a/webapp/src/components/DAGGraph/updater/index.ts b/webapp/src/components/DAGGraph/updater/index.ts index 7ef31d3..7d42640 100644 --- a/webapp/src/components/DAGGraph/updater/index.ts +++ b/webapp/src/components/DAGGraph/updater/index.ts @@ -93,13 +93,13 @@ export type DAGGraphChooseUpdater = ReturnType< DAGGraphUpdater["createChoosNodeUpdater"] >; export const createUpdater = ( - args: DAGUpdaterArgs<"sequence" | "condition" | "trigger"> + args: DAGUpdaterArgs<"action" | "condition" | "trigger"> ) => { const basic = { - sequence: createBasicUpdater("sequence", { + action: createBasicUpdater("action", { device_id: "", })({ - sequence: args.sequence, + action: args.action, openModal: args.openModal, }), trigger: createBasicUpdater("trigger", { @@ -179,7 +179,7 @@ export const createUpdater = ( }, createChoosNodeUpdater(i: number, j: number | "else") { const node = convertChooseActionToOrignal( - args.sequence.data[i] as ChooseAction + args.action.data[i] as ChooseAction ); if (j === "else") { return { @@ -189,10 +189,10 @@ export const createUpdater = ( data: [], onUpdate: console.warn, }, - sequence: { + action: { data: node.default ?? [], onUpdate: (upd) => - basic.sequence.updateNode( + basic.action.updateNode( { ...node, default: upd, @@ -210,7 +210,7 @@ export const createUpdater = ( } else { return { onRemove: () => - basic.sequence.updateNode( + basic.action.updateNode( { ...node, choose: [ @@ -225,7 +225,7 @@ export const createUpdater = ( condition: { data: node.choose[j].conditions, onUpdate: (upd: any) => - basic.sequence.updateNode( + basic.action.updateNode( { ...node, choose: [ @@ -240,10 +240,10 @@ export const createUpdater = ( i ), }, - sequence: { + action: { data: node.choose[j].sequence, onUpdate: (upd) => - basic.sequence.updateNode( + basic.action.updateNode( { ...node, choose: [ @@ -267,11 +267,11 @@ export const createUpdater = ( } }, createRepeatNodeUpdater(i: number) { - const { repeat, ...rest } = args.sequence.data[i] as RepeatAction; - const sequence = { + const { repeat, ...rest } = args.action.data[i] as RepeatAction; + const action = { data: repeat.sequence, onUpdate: (upd: AutomationNode[]) => - basic.sequence.updateNode( + basic.action.updateNode( { ...rest, repeat: { @@ -291,7 +291,7 @@ export const createUpdater = ( repeat.while ), onUpdate: (upd: any) => - basic.sequence.updateNode( + basic.action.updateNode( { ...rest, repeat: { @@ -303,7 +303,7 @@ export const createUpdater = ( ), }, trigger: createDummyUpdater(), - sequence, + action, }); } @@ -315,7 +315,7 @@ export const createUpdater = ( repeat.until ), onUpdate: (upd: any) => - basic.sequence.updateNode( + basic.action.updateNode( { ...rest, repeat: { @@ -327,7 +327,7 @@ export const createUpdater = ( ), }, trigger: createDummyUpdater(), - sequence, + action, }); } @@ -335,16 +335,16 @@ export const createUpdater = ( openModal: args.openModal, condition: createDummyUpdater(), trigger: createDummyUpdater(), - sequence, + action, }); }, createParallelNodeUpdater(i: number, j: number) { - const { parallel, ...rest } = args.sequence.data[i] as ParallelAction; + const { parallel, ...rest } = args.action.data[i] as ParallelAction; const child = parallel[j]; return { onRemove: () => - basic.sequence.updateNode( + basic.action.updateNode( { ...rest, parallel: [...parallel.slice(0, j), ...parallel.slice(j + 1)], @@ -355,10 +355,10 @@ export const createUpdater = ( openModal: args.openModal, condition: createDummyUpdater(), trigger: createDummyUpdater(), - sequence: { + action: { data: "sequence" in child ? child.sequence : [child], onUpdate(d) { - basic.sequence.updateNode( + basic.action.updateNode( { ...rest, parallel: [ @@ -383,12 +383,12 @@ export const createUpdaterFromAutomationData = ( onUpdate: (a: AutomationActionData) => void ): DAGGraphUpdater => createUpdater({ - sequence: { - data: auto.sequence, + action: { + data: auto.action, onUpdate: (s: AutomationSequenceNode[]) => onUpdate({ ...auto, - sequence: s, + action: s, }), }, condition: { diff --git a/webapp/src/components/ErrorBoundary/index.css b/webapp/src/components/ErrorBoundary/index.css index 077db8f..cea8e9d 100644 --- a/webapp/src/components/ErrorBoundary/index.css +++ b/webapp/src/components/ErrorBoundary/index.css @@ -1,7 +1,26 @@ .error-boundary { padding: 2em 5%; + height: calc(100vh - 4em); + width: calc(100vw-5%); + max-height: calc(100vh - 4em); + max-width: calc(100vw-5%); + overflow: auto; } h1, h2 { margin: 0; +} + +.error-boundary .error-boundary--stack, .error-boundary .error-boundary--context { + max-height: 25vh; + overflow: auto; +} + +.error-boundary--buttons { + width: 100%; + display: flex; + margin-top: 1em; + flex-direction: row; + justify-content: space-evenly; + align-items: center; } \ No newline at end of file diff --git a/webapp/src/components/ErrorBoundary/index.tsx b/webapp/src/components/ErrorBoundary/index.tsx index 8051c59..94157aa 100644 --- a/webapp/src/components/ErrorBoundary/index.tsx +++ b/webapp/src/components/ErrorBoundary/index.tsx @@ -1,48 +1,87 @@ import "./index.css"; import { Component, ErrorInfo, ReactNode } from "react"; +import Alert from "@mui/material/Alert"; +import { Button } from "components/Inputs/Buttons/Button"; -type State = { - hasError: false; -} | { - hasError: true, - error: any, - errorInfo?: ErrorInfo, +type State = + | { + hasError: false; + } + | { + hasError: true; + error: any; + errorInfo?: ErrorInfo; + }; +export class ErrorBoundary extends Component< + { + children: ReactNode; + additionalContext?: any; + }, + State +> { + state: State = { + hasError: false, + }; + + static getDerivedStateFromError(error: any): State { + return { error, hasError: true }; + } + + componentDidCatch(error: Error, errorInfo: ErrorInfo) { + this.setState({ + hasError: true, + error, + errorInfo, + }); + } + + render() { + if (this.state.hasError) { + return ( +
+

An Error has occured.

+ {String(this.state.error)} + {!!this.props.additionalContext && ( + <> +

Error Context

+ + {JSON.stringify(this.props.additionalContext, null, 4)} + + + )} +

Error Stack

+ + {JSON.stringify(this.state.error, null, 4)} +
+ {this.state.errorInfo && + this.state.errorInfo.componentStack.split("\n").map((s, i) => ( + <> + {s} +
+ + ))} +
+
+ + +
+
+ ); + } + + return <>{this.props.children}; + } } -export class ErrorBoundary extends Component<{ - children: ReactNode -}, State> { - - state: State = { - hasError: false - } - - static getDerivedStateFromError(error: any): State { - return { error, hasError: true, }; - } - - componentDidCatch(error: Error, errorInfo: ErrorInfo) { - this.setState({ - hasError: true, - error, - errorInfo, - }) - } - - render() { - if (this.state.hasError) { - return
-

An Error has occured.

-

{String(this.state.error)}

- {JSON.stringify(this.state.error, null, 4)} -
- {this.state.errorInfo && this.state.errorInfo.componentStack.split('\n').map((s, i) => <> - {s}
- )} -
- } - - return <> - {this.props.children} - ; - } -} \ No newline at end of file diff --git a/webapp/src/types/automations/index.ts b/webapp/src/types/automations/index.ts index c121328..f8b66ae 100644 --- a/webapp/src/types/automations/index.ts +++ b/webapp/src/types/automations/index.ts @@ -9,10 +9,11 @@ export type AutomationMetadata = st.Infer; export interface AutomationActionData { trigger: AutomationTrigger[]; condition: AutomationCondition[]; - sequence: AutomationSequenceNode[]; + action: AutomationSequenceNode[]; } -export interface AutomationData extends AutomationActionData { - metadata: AutomationMetadata; +export interface AutomationData + extends AutomationActionData, + AutomationMetadata { tags: Record; } export type AutomationSequenceNode = AutomationAction | AutomationCondition; diff --git a/webapp/src/types/validators/autmation.ts b/webapp/src/types/validators/autmation.ts index 99bf6de..c7f1864 100644 --- a/webapp/src/types/validators/autmation.ts +++ b/webapp/src/types/validators/autmation.ts @@ -1,11 +1,15 @@ -import * as st from 'superstruct' -import { AutomationMetadata } from './metadata' - +import * as st from "superstruct"; export const AutomationData = st.object({ - metadata: AutomationMetadata, - trigger: st.array(st.object()), - condition: st.array(st.object()), - sequence: st.array(st.object()), - tags: st.record(st.string(), st.string()), -}) \ No newline at end of file + id: st.string(), + alias: st.optional(st.string()), + description: st.optional(st.string()), + trigger_variables: st.optional( + st.nullable(st.record(st.string(), st.string())) + ), + mode: st.enums(["single", "restart", "queued", "parallel"]), + trigger: st.array(st.object()), + condition: st.array(st.object()), + action: st.array(st.object()), + tags: st.record(st.string(), st.string()), +}); diff --git a/webapp/src/types/validators/index.test.ts b/webapp/src/types/validators/index.test.ts index d99e966..5d5df37 100644 --- a/webapp/src/types/validators/index.test.ts +++ b/webapp/src/types/validators/index.test.ts @@ -11,7 +11,7 @@ test("superstructure is", () => { }); test("getFailures returns failures", () => { - const failures = getFailures({ metadata: {} }, AutomationData); + const failures = getFailures({}, AutomationData); expect(failures).toHaveLength(6); }); diff --git a/webapp/src/utils/AutomationState.ts b/webapp/src/utils/AutomationState.ts index 710426e..c763d06 100644 --- a/webapp/src/utils/AutomationState.ts +++ b/webapp/src/utils/AutomationState.ts @@ -1,40 +1,39 @@ import { AutomationData, AutomationSequenceNode } from "types/automations"; -import { AutomationTrigger } from '../types/automations/triggers'; +import { AutomationTrigger } from "../types/automations/triggers"; export type AumationStateEditor = ReturnType; -export type AutomationStateTriggerEditor = AumationStateEditor['triggers']; +export type AutomationStateTriggerEditor = AumationStateEditor["triggers"]; export const makeAumationStateEditor = ( - automation: AutomationData, - onUpdate: (a: AutomationData) => void, + automation: AutomationData, + onUpdate: (a: AutomationData) => void ) => ({ - onUpdate, - triggers: { - update: (i: number, t: AutomationTrigger) => onUpdate({ - ...automation, - trigger: automation.trigger - .slice(0, i) - .concat([t]) - .concat( - automation.trigger.slice(i + 1) - ) - }), - delete: (i: number) => onUpdate({ - ...automation, - trigger: automation.trigger - .slice(0, i) - .concat( - automation.trigger.slice(i + 1) - ) - }), - add: (t: AutomationTrigger) => onUpdate({ - ...automation, - trigger: automation.trigger - .concat([t]) - }), - }, - updateSequence: (s: AutomationSequenceNode[]) => onUpdate({ + onUpdate, + triggers: { + update: (i: number, t: AutomationTrigger) => + onUpdate({ ...automation, - sequence: s, - }) -}) \ No newline at end of file + trigger: automation.trigger + .slice(0, i) + .concat([t]) + .concat(automation.trigger.slice(i + 1)), + }), + delete: (i: number) => + onUpdate({ + ...automation, + trigger: automation.trigger + .slice(0, i) + .concat(automation.trigger.slice(i + 1)), + }), + add: (t: AutomationTrigger) => + onUpdate({ + ...automation, + trigger: automation.trigger.concat([t]), + }), + }, + updateSequence: (s: AutomationSequenceNode[]) => + onUpdate({ + ...automation, + action: s, + }), +}); diff --git a/webapp/src/utils/defaults.ts b/webapp/src/utils/defaults.ts index 1a47698..28b455a 100644 --- a/webapp/src/utils/defaults.ts +++ b/webapp/src/utils/defaults.ts @@ -63,14 +63,12 @@ export const getConditionDefaultValues = ( }; export const defaultAutomation = (id: string): AutomationData => ({ - metadata: { - id, - alias: "New Automation", - description: "", - mode: "single", - }, + id, + alias: "New Automation", + description: "", + mode: "single", tags: {}, trigger: [], - sequence: [], + action: [], condition: [], }); diff --git a/webapp/src/utils/mocks.ts b/webapp/src/utils/mocks.ts index 5658b9c..5e77117 100644 --- a/webapp/src/utils/mocks.ts +++ b/webapp/src/utils/mocks.ts @@ -1,506 +1,510 @@ -import { AutomationData } from 'types/automations'; +import { AutomationData } from "types/automations"; - -export const createMockAuto = (tags: Record = {}): AutomationData => ({ - metadata: { - id: Math.random().toString(36).slice(2, 15), - alias: "Random", - description: "Example Metadata", - trigger_variables: { - 'wowo': '!' - }, - mode: 'single', +export const createMockAuto = ({ + tags = {}, + id, +}: { + tags?: Record; + id?: string; +} = {}): AutomationData => ({ + id: id ?? `${Date.now()}-${Math.random().toString(36).slice(2, 15)}`, + alias: "Random", + description: "Example Metadata", + trigger_variables: { + wowo: "!", }, + mode: "single", tags, condition: [], trigger: [ { - "platform": "numeric_state", - "entity_id": "test", + platform: "numeric_state", + entity_id: "test", }, { - "platform": "homeassistant", - "event": "start", - } + platform: "homeassistant", + event: "start", + }, ], - sequence: [ + action: [ { - condition: 'and', + condition: "and", conditions: [ { - condition: 'numeric_state', - entity_id: 'sensor.temperature_kitchen', - below: '15', + condition: "numeric_state", + entity_id: "sensor.temperature_kitchen", + below: "15", }, { - condition: 'template', - value_template: 'states(switch.kitchen_light) == "on"' - } - ] + condition: "template", + value_template: 'states(switch.kitchen_light) == "on"', + }, + ], }, { alias: "Start Music In Kitchen", - service: 'media_player.play_media', + service: "media_player.play_media", target: { - entity_id: "media_player.kitchen_dot" + entity_id: "media_player.kitchen_dot", }, data: { media_content_id: "Good Morning", media_content_type: "SPOTIFY", - } - } - ] -}) - + }, + }, + ], +}); export const bigMockAutoList: AutomationData[] = [ - createMockAuto({ "Room": "Bathroom", "Type": "Lights", "NewDevice": "Yes", "Remote": "No", "Floor": "1" }), - createMockAuto({ "Room": "Bathroom", "Type": "Climate" }), - createMockAuto({ "Room": "Living Room", "Type": "Climate" }), - createMockAuto({ "Type": "Climate" }), - createMockAuto({ "Type": "Lights", "Routine": "Myself" }), - createMockAuto({ "Routine": "DNS", "Type": "SSL" }), - createMockAuto({ "Room": "Bedroom", "Type": "Lights", "Routine": "Baby" }), - createMockAuto({ "Room": "Office", "Type": "Lights" }), - createMockAuto({ "Room": "Office" }), + createMockAuto({ + tags: { + Room: "Bathroom", + Type: "Lights", + NewDevice: "Yes", + Remote: "No", + Floor: "1", + }, + }), + createMockAuto({ tags: { Room: "Bathroom", Type: "Climate" } }), + createMockAuto({ tags: { Room: "Living Room", Type: "Climate" } }), + createMockAuto({ tags: { Type: "Climate" } }), + createMockAuto({ tags: { Type: "Lights", Routine: "Myself" } }), + createMockAuto({ tags: { Routine: "DNS", Type: "SSL" } }), + createMockAuto({ + tags: { Room: "Bedroom", Type: "Lights", Routine: "Baby" }, + }), + createMockAuto({ tags: { Room: "Office", Type: "Lights" } }), + createMockAuto({ tags: { Room: "Office" } }), createMockAuto(), { - "metadata": { - "id": "1649947692702", - "alias": "Bed Remote", - "description": "", - "trigger_variables": null, - "mode": "single" - }, - "trigger": [ + id: "1649947692702", + alias: "Bed Remote", + description: "", + trigger_variables: null, + mode: "single", + trigger: [ { - "device_id": "asdasdasdas", - "domain": "zha", - "platform": "device", - "type": "remote_button_short_press", - "subtype": "turn_on", - "id": "turn_on" + device_id: "asdasdasdas", + domain: "zha", + platform: "device", + type: "remote_button_short_press", + subtype: "turn_on", + id: "turn_on", }, { - "device_id": "asdasdasdas", - "domain": "zha", - "platform": "device", - "type": "remote_button_short_press", - "subtype": "turn_off", - "id": "turn_off" + device_id: "asdasdasdas", + domain: "zha", + platform: "device", + type: "remote_button_short_press", + subtype: "turn_off", + id: "turn_off", }, { - "device_id": "asdasdasdas", - "domain": "zha", - "platform": "device", - "type": "remote_button_short_press", - "subtype": "dim_up", - "id": "dim_up" + device_id: "asdasdasdas", + domain: "zha", + platform: "device", + type: "remote_button_short_press", + subtype: "dim_up", + id: "dim_up", }, { - "device_id": "asdasdasdas", - "domain": "zha", - "platform": "device", - "type": "remote_button_short_press", - "subtype": "dim_down", - "id": "dim_down" + device_id: "asdasdasdas", + domain: "zha", + platform: "device", + type: "remote_button_short_press", + subtype: "dim_down", + id: "dim_down", }, { - "device_id": "asdasdasdas", - "domain": "zha", - "platform": "device", - "type": "remote_button_double_press", - "subtype": "turn_on", - "id": "up_dbclk" - } + device_id: "asdasdasdas", + domain: "zha", + platform: "device", + type: "remote_button_double_press", + subtype: "turn_on", + id: "up_dbclk", + }, ], - "condition": [], - "sequence": [ + condition: [], + action: [ { - "choose": [ + choose: [ { - "conditions": [ + conditions: [ { - "condition": "trigger", - "id": "turn_off" - } + condition: "trigger", + id: "turn_off", + }, ], - "sequence": [ + sequence: [ { - "type": "turn_off", - "device_id": "asdasdasdasdas", - "entity_id": "light.bulb_ari_lamp", - "domain": "light" - } - ] + type: "turn_off", + device_id: "asdasdasdasdas", + entity_id: "light.bulb_ari_lamp", + domain: "light", + }, + ], }, { - "conditions": [ + conditions: [ { - "condition": "trigger", - "id": "turn_on" - } + condition: "trigger", + id: "turn_on", + }, ], - "sequence": [ + sequence: [ { - "service": "light.turn_on", - "data": { - "color_temp": 153, - "brightness_pct": 100 + service: "light.turn_on", + data: { + color_temp: 153, + brightness_pct: 100, }, - "target": { - "device_id": "asdasdasdasdas" - } - } - ] - }, - { - "conditions": [ - { - "condition": "trigger", - "id": "dim_up" - } - ], - "sequence": [ - { - "device_id": "asdasdasdasdas", - "domain": "light", - "entity_id": "light.bulb_ari_lamp", - "type": "brightness_increase" - } - ] - }, - { - "conditions": [ - { - "condition": "trigger", - "id": "dim_down" - } - ], - "sequence": [ - { - "device_id": "asdasdasdasdas", - "domain": "light", - "entity_id": "light.bulb_ari_lamp", - "type": "brightness_decrease" - } - ] - }, - { - "conditions": [ - { - "condition": "trigger", - "id": "up_dbclk" - } - ], - "sequence": [ - { - "service": "light.turn_on", - "data": { - "color_temp": 500, - "brightness_pct": 100 + target: { + device_id: "asdasdasdasdas", }, - "target": { - "device_id": "asdasdasdasdas" - } - } - ] - } + }, + ], + }, + { + conditions: [ + { + condition: "trigger", + id: "dim_up", + }, + ], + sequence: [ + { + device_id: "asdasdasdasdas", + domain: "light", + entity_id: "light.bulb_ari_lamp", + type: "brightness_increase", + }, + ], + }, + { + conditions: [ + { + condition: "trigger", + id: "dim_down", + }, + ], + sequence: [ + { + device_id: "asdasdasdasdas", + domain: "light", + entity_id: "light.bulb_ari_lamp", + type: "brightness_decrease", + }, + ], + }, + { + conditions: [ + { + condition: "trigger", + id: "up_dbclk", + }, + ], + sequence: [ + { + service: "light.turn_on", + data: { + color_temp: 500, + brightness_pct: 100, + }, + target: { + device_id: "asdasdasdasdas", + }, + }, + ], + }, ], - "default": [] - } + default: [], + }, ], - "tags": { - "Type": "Remote", - "Room": "Bedroom" - } + tags: { + Type: "Remote", + Room: "Bedroom", + }, }, { - "metadata": { - "id": "1641617168123", - "alias": "Ensure On", - "description": "", - "trigger_variables": null, - "mode": "single" - }, - "trigger": [ + id: "1641617168123", + alias: "Ensure On", + description: "", + trigger_variables: null, + mode: "single", + trigger: [ { - "platform": "device", - "type": "turned_off", - "device_id": "tasdasdasdasdasdasda", - "entity_id": "switch.power_washer", - "domain": "switch" + platform: "device", + type: "turned_off", + device_id: "tasdasdasdasdasdasda", + entity_id: "switch.power_washer", + domain: "switch", }, { - "platform": "device", - "type": "turned_off", - "device_id": "dasdasdasdasdas", - "entity_id": "switch.plug_living_room_tv", - "domain": "switch" - } + platform: "device", + type: "turned_off", + device_id: "dasdasdasdasdas", + entity_id: "switch.plug_living_room_tv", + domain: "switch", + }, ], - "condition": [], - "sequence": [ + condition: [], + action: [ { - "type": "turn_on", - "device_id": "tasdasdasdasdasdasda", - "entity_id": "switch.power_washer", - "domain": "switch" + type: "turn_on", + device_id: "tasdasdasdasdasdasda", + entity_id: "switch.power_washer", + domain: "switch", }, { - "type": "turn_on", - "device_id": "dasdasdasdasdas", - "entity_id": "switch.plug_living_room_tv", - "domain": "switch" - } + type: "turn_on", + device_id: "dasdasdasdasdas", + entity_id: "switch.plug_living_room_tv", + domain: "switch", + }, ], - "tags": {} + tags: {}, }, { - "metadata": { - "id": "1649726828269", - "alias": "Climate Heat Mode Settings", - "description": "Ensures that the climate is always in sync with the house settings", - "trigger_variables": null, - "mode": "single" - }, - "trigger": [ + id: "1649726828269", + alias: "Climate Heat Mode Settings", + description: + "Ensures that the climate is always in sync with the house settings", + trigger_variables: null, + mode: "single", + trigger: [ { - "platform": "state", - "entity_id": "climate.main_floor", - "id": "main" + platform: "state", + entity_id: "climate.main_floor", + id: "main", }, { - "platform": "state", - "entity_id": "climate.second_floor", - "id": "second" + platform: "state", + entity_id: "climate.second_floor", + id: "second", }, { - "platform": "state", - "entity_id": "input_boolean.thermostats_house_is_heating", - "id": "setting" - } + platform: "state", + entity_id: "input_boolean.thermostats_house_is_heating", + id: "setting", + }, ], - "condition": [], - "sequence": [ + condition: [], + action: [ { - "choose": [ + choose: [ { - "conditions": [ + conditions: [ { - "condition": "trigger", - "id": "setting" - } + condition: "trigger", + id: "setting", + }, ], - "sequence": [ + sequence: [ { - "service": "climate.turn_off", - "data": {}, - "target": { - "device_id": [ + service: "climate.turn_off", + data: {}, + target: { + device_id: [ "d88dcfe82bc9a1c0f2b77b871848155e", - "ef2d47fdeef19f8984b85f92f2597f73" - ] - } - } - ] + "ef2d47fdeef19f8984b85f92f2597f73", + ], + }, + }, + ], }, { - "conditions": [ + conditions: [ { - "condition": "state", - "entity_id": "input_boolean.thermostats_house_is_heating", - "state": "on" - } + condition: "state", + entity_id: "input_boolean.thermostats_house_is_heating", + state: "on", + }, ], - "sequence": [ + sequence: [ { - "choose": [ + choose: [ { - "conditions": [ + conditions: [ { - "condition": "and", - "conditions": [ + condition: "and", + conditions: [ { - "condition": "template", - "value_template": "{{ trigger.to_state.state != 'heat' }}" + condition: "template", + value_template: + "{{ trigger.to_state.state != 'heat' }}", }, { - "condition": "template", - "value_template": "{{ trigger.to_state.state != 'off' }}" - } - ] - } + condition: "template", + value_template: + "{{ trigger.to_state.state != 'off' }}", + }, + ], + }, ], - "sequence": [ + sequence: [ { - "service": "climate.set_hvac_mode", - "data": { - "hvac_mode": "heat" + service: "climate.set_hvac_mode", + data: { + hvac_mode: "heat", }, - "target": { - "entity_id": "{{ trigger.entity_id }}" - } - } - ] - } - ] - } - ] - } + target: { + entity_id: "{{ trigger.entity_id }}", + }, + }, + ], + }, + ], + }, + ], + }, ], - "default": [ + default: [ { - "choose": [ + choose: [ { - "conditions": [ + conditions: [ { - "condition": "and", - "conditions": [ + condition: "and", + conditions: [ { - "condition": "template", - "value_template": "{{ trigger.to_state.state != 'cool' }}" + condition: "template", + value_template: + "{{ trigger.to_state.state != 'cool' }}", }, { - "condition": "template", - "value_template": "{{ trigger.to_state.state != 'off' }}" - } - ] - } + condition: "template", + value_template: "{{ trigger.to_state.state != 'off' }}", + }, + ], + }, ], - "sequence": [ + sequence: [ { - "service": "climate.set_hvac_mode", - "data": { - "hvac_mode": "cool" + service: "climate.set_hvac_mode", + data: { + hvac_mode: "cool", }, - "target": { - "entity_id": "{{ trigger.entity_id }}" - } - } - ] - } - ] - } - ] - } - ], - "tags": {} - }, - { - "metadata": { - "id": "1628024070687", - "alias": "Baby Light Setting", - "description": "Configures max/min light settings for the baby ", - "trigger_variables": null, - "mode": "single" - }, - "trigger": [ - { - "platform": "time", - "at": "21:00:00", - "id": "night" - }, - { - "platform": "time", - "at": "07:30:00", - "id": "day" - } - ], - "condition": [], - "sequence": [ - { - "choose": [ - { - "conditions": [ - { - "condition": "trigger", - "id": "night" - } + target: { + entity_id: "{{ trigger.entity_id }}", + }, + }, + ], + }, ], - "sequence": [ - { - "service": "zwave_js.set_config_parameter", - "data": { - "parameter": "5", - "value": "15" - } - } - ] }, - { - "conditions": [ - { - "condition": "trigger", - "id": "day" - } - ], - "sequence": [ - { - "service": "zwave_js.set_config_parameter", - "data": { - "parameter": "5", - "value": 100 - } - } - ] - } ], - "default": [] - } + }, ], - "tags": {} + tags: {}, }, { - "metadata": { - "id": "alarmanlage_an", - "alias": "alarmanlage_an (Uhrzeit)", - "mode": "single" - }, - tags: {}, - "trigger": [ + id: "1628024070687", + alias: "Baby Light Setting", + description: "Configures max/min light settings for the baby ", + trigger_variables: null, + mode: "single", + trigger: [ { - "entity_id": "sensor.time", - "platform": "state", - "to": "23:30" - } - ], - "condition": [ - { - "condition": "or", - "conditions": [ - { - "condition": "state", - "entity_id": "person.simon", - "state": "home" - }, - { - "condition": "state", - "entity_id": "person.leni", - "state": "home" - } - ] - } - ], - "sequence": [ - { - "service": "alarm_control_panel.alarm_arm_night", - "target": { - "entity_id": [ - "alarm_control_panel.alarmo" - ] - }, - "data": { - "code": "xxx" - } + platform: "time", + at: "21:00:00", + id: "night", }, { - "service": "alarm_control_panel.alarm_arm_away", - "data": {}, - "target": { - "entity_id": "alarm_control_panel.blink_home" - } - } + platform: "time", + at: "07:30:00", + id: "day", + }, ], - } -] \ No newline at end of file + condition: [], + action: [ + { + choose: [ + { + conditions: [ + { + condition: "trigger", + id: "night", + }, + ], + sequence: [ + { + service: "zwave_js.set_config_parameter", + data: { + parameter: "5", + value: "15", + }, + }, + ], + }, + { + conditions: [ + { + condition: "trigger", + id: "day", + }, + ], + sequence: [ + { + service: "zwave_js.set_config_parameter", + data: { + parameter: "5", + value: 100, + }, + }, + ], + }, + ], + default: [], + }, + ], + tags: {}, + }, + { + id: "alarmanlage_an", + alias: "alarmanlage_an (Uhrzeit)", + mode: "single", + tags: {}, + trigger: [ + { + entity_id: "sensor.time", + platform: "state", + to: "23:30", + }, + ], + condition: [ + { + condition: "or", + conditions: [ + { + condition: "state", + entity_id: "person.simon", + state: "home", + }, + { + condition: "state", + entity_id: "person.leni", + state: "home", + }, + ], + }, + ], + action: [ + { + service: "alarm_control_panel.alarm_arm_night", + target: { + entity_id: ["alarm_control_panel.alarmo"], + }, + data: { + code: "xxx", + }, + }, + { + service: "alarm_control_panel.alarm_arm_away", + data: {}, + target: { + entity_id: "alarm_control_panel.blink_home", + }, + }, + ], + }, +];