From a391eae7c501aa31a1e34a739bd3d9b5b7837141 Mon Sep 17 00:00:00 2001 From: Ari Date: Thu, 18 Aug 2022 10:50:11 -0400 Subject: [PATCH] sync'd up --- webapp/src/App.tsx | 25 +++- webapp/src/apiService/automations.ts | 10 +- webapp/src/apiService/base.ts | 36 +++-- webapp/src/apiService/core.ts | 1 + webapp/src/apiService/mock.ts | 24 ++- webapp/src/apiService/types.ts | 27 ++-- webapp/src/apiService/util.ts | 4 +- .../AutomationEditor/AutoInfoBox.tsx | 7 +- .../src/components/AutomationEditor/index.tsx | 8 +- .../src/components/AutomationEditor/state.ts | 65 +++++---- .../AutomationManager/Loaded/automationDB.ts | 16 +- .../AutomationManager/Loaded/state.ts | 18 ++- .../AutomationManager/index.stories.tsx | 8 +- .../components/AutomationManager/index.tsx | 138 +++++++++++++----- webapp/src/routes/automation.tsx | 63 ++++---- webapp/src/types/automations/index.ts | 9 +- webapp/src/types/validators/autmation.ts | 21 ++- webapp/src/types/validators/metadata.ts | 3 + webapp/src/utils/defaults.ts | 7 +- 19 files changed, 320 insertions(+), 170 deletions(-) diff --git a/webapp/src/App.tsx b/webapp/src/App.tsx index 3486724..3c7b0d2 100644 --- a/webapp/src/App.tsx +++ b/webapp/src/App.tsx @@ -1,20 +1,31 @@ -import './App.css'; +import "./App.css"; import { Routes, Route, BrowserRouter } from "react-router-dom"; -import { AutomationRoute } from 'routes/automation'; -import { useConnectedApiService } from 'apiService'; -import { ErrorBoundary } from 'components/ErrorBoundary'; +import { AutomationRoute } from "routes/automation"; +import { useConnectedApiService } from "apiService"; +import { ErrorBoundary } from "components/ErrorBoundary"; import { CookiesProvider } from "react-cookie"; +import { Page } from "components/Page"; + +const ConnectedAutomationRoute = () => { + const api = useConnectedApiService(); + return ; +}; function App() { - const api = useConnectedApiService(); - return (
- } /> + + + + } + /> diff --git a/webapp/src/apiService/automations.ts b/webapp/src/apiService/automations.ts index df5cb74..25f9f7d 100644 --- a/webapp/src/apiService/automations.ts +++ b/webapp/src/apiService/automations.ts @@ -1,4 +1,4 @@ -import { AutomationData } from "types/automations"; +import { AutomationData, BareAutomationData } from "types/automations"; import { API } from "./base"; import { ListData, ListParams } from "./types"; import { @@ -20,6 +20,14 @@ export const makeAutomationAPI = (api: API) => ({ }, async update(auto: AutomationData) { return await api.makeCall({ + method: "PUT", + path: AUTOMTAION_ITEM, + data: auto, + }); + }, + async create(auto: BareAutomationData) { + return await api.makeCall({ + method: "POST", path: AUTOMTAION_ITEM, data: auto, }); diff --git a/webapp/src/apiService/base.ts b/webapp/src/apiService/base.ts index 361ec1e..e87047e 100644 --- a/webapp/src/apiService/base.ts +++ b/webapp/src/apiService/base.ts @@ -1,22 +1,20 @@ -import { APIRequest, APIResponse } from './types'; +import { APIRequest, APIResponse } from "./types"; export interface API { - makeCall: (req: APIRequest) => Promise>; + makeCall: ( + req: APIRequest + ) => Promise>; } export const makeRemoteAPI = (baseURL: string): API => ({ - async makeCall({ - path, - method = "POST", - data = {} - }) { + async makeCall({ path, method = "POST", data = {} }) { try { const payload: RequestInit = { method, headers: { - "Content-Type": "application/json" + "Content-Type": "application/json", }, }; - if (method !== 'GET') { + if (method !== "GET") { payload["body"] = JSON.stringify(data); } const reply = await fetch(baseURL + path, payload); @@ -25,27 +23,27 @@ export const makeRemoteAPI = (baseURL: string): API => ({ response = { ok: true, data: await reply.json(), - } + }; } else { response = { ok: false, error: await reply.text(), - } - console.error(response) + }; + console.error(response); } - return response + return response; } catch (err) { - console.error(err) - let error = String(err) + console.error(err); + let error = String(err); if (err instanceof Error) { - error += ` ${err.stack}` + error += ` ${err.stack}`; } return { ok: false, error, - } + }; } - } -}) + }, +}); diff --git a/webapp/src/apiService/core.ts b/webapp/src/apiService/core.ts index e8c1920..fc98f19 100644 --- a/webapp/src/apiService/core.ts +++ b/webapp/src/apiService/core.ts @@ -22,6 +22,7 @@ export const useAPIService = (automationAPI: AutomationAPI) => { state, removeAutomation: wrapCall(automationAPI.remove), updateAutomation: wrapCall(automationAPI.update), + createAutomation: wrapCall(automationAPI.create), updateTags: wrapCall(automationAPI.updateTags), }; }; diff --git a/webapp/src/apiService/mock.ts b/webapp/src/apiService/mock.ts index 4899175..41eba76 100644 --- a/webapp/src/apiService/mock.ts +++ b/webapp/src/apiService/mock.ts @@ -1,5 +1,5 @@ import { useRef } from "react"; -import { AutomationData } from "types/automations"; +import { AutomationData, BareAutomationData } from "types/automations"; import { API } from "./base"; import { AUTOMTAION_LIST, @@ -35,13 +35,16 @@ export const useMockAPI = ( } as any; } if (path === AUTOMTAION_ITEM) { - if (method === "POST") { + if (method === "PUT") { const auto = data as AutomationData; const index = automationsRef.current.findIndex( ({ id }) => auto.id === id ); if (index < 0) { - automationsRef.current = [...automationsRef.current, auto]; + return { + ok: false, + error: "Not Found", + }; } else { automationsRef.current = [ ...automationsRef.current.slice(0, index), @@ -62,6 +65,21 @@ export const useMockAPI = ( ok: true, data: {}, }; + } else if (method === "POST") { + const auto = data as BareAutomationData; + automationsRef.current = [ + ...automationsRef.current, + { + ...auto, + source_file: "automation.yaml", + source_file_type: "list", + configuration_key: "automation", + }, + ]; + return { + ok: true, + data: {}, + }; } } if (path === AUTOMTAION_ITEM_TAGS) { diff --git a/webapp/src/apiService/types.ts b/webapp/src/apiService/types.ts index 1793950..09e8431 100644 --- a/webapp/src/apiService/types.ts +++ b/webapp/src/apiService/types.ts @@ -1,26 +1,29 @@ import { AutomationData } from "types/automations"; - export interface ListParams { offset: number; limit: number; } export type APIRequest = { path: string; - method?: "POST" | "DELETE" | "GET", + method?: "POST" | "DELETE" | "GET" | "PUT"; data?: D; }; -export type APIResponse = { - ok: true; - data: D; -} | { - ok: false; - error: string; -} -export type Errorable = ({ ready: true } & APIResponse) | { - ready: false; -} +export type APIResponse = + | { + ok: true; + data: D; + } + | { + ok: false; + error: string; + }; +export type Errorable = + | ({ ready: true } & APIResponse) + | { + ready: false; + }; export interface ListData { params: ListParams; totalItems: number; diff --git a/webapp/src/apiService/util.ts b/webapp/src/apiService/util.ts index 9d39a08..0214a60 100644 --- a/webapp/src/apiService/util.ts +++ b/webapp/src/apiService/util.ts @@ -27,10 +27,10 @@ export const makeReloadAutomations = ( }); }; const wrapCall = Promise>(fcn: Call) => { - return async (args: Parameters[0]): Promise> => { + return async (args: Parameters[0]) => { const resp = await fcn(args); await reload(); - return resp; + return resp as ReturnType; }; }; return { diff --git a/webapp/src/components/AutomationEditor/AutoInfoBox.tsx b/webapp/src/components/AutomationEditor/AutoInfoBox.tsx index 8ba5be7..de254d0 100644 --- a/webapp/src/components/AutomationEditor/AutoInfoBox.tsx +++ b/webapp/src/components/AutomationEditor/AutoInfoBox.tsx @@ -1,5 +1,8 @@ import "./AutoInfoBox.css"; -import { AutomationMetadata } from "types/automations"; +import { + AutomationMetadata, + AutomationShortumationMetadata, +} from "types/automations"; import { InputList } from "components/Inputs/InputList"; import InputText from "components/Inputs/Base/InputText"; import { FC, ReactNode, useRef, useState } from "react"; @@ -9,7 +12,7 @@ import { TagDB } from "components/AutomationManager/TagDB"; import { ButtonIcon } from "components/Icons/ButtonIcons"; export interface AutoInfoBoxProps { - metadata: AutomationMetadata; + metadata: AutomationMetadata & Partial; tags: Array<[string, string]>; onUpdate: (m: AutomationMetadata, tags: Array<[string, string]>) => void; tagDB: TagDB; diff --git a/webapp/src/components/AutomationEditor/index.tsx b/webapp/src/components/AutomationEditor/index.tsx index 2a97077..f7e7824 100644 --- a/webapp/src/components/AutomationEditor/index.tsx +++ b/webapp/src/components/AutomationEditor/index.tsx @@ -26,16 +26,16 @@ import { DAGAutomationGraph } from "components/DAGGraph"; import { InputList } from "components/Inputs/InputList"; import { InputTextView } from "components/Inputs/InputTextView"; -import { AutomationData } from "types/automations"; +import { AutomationData, BareAutomationData } from "types/automations"; import { MiniFailure } from "types/validators/helper"; import { AutoInfoBox } from "./AutoInfoBox"; import { useAutomatioEditorState, EditorData } from "./state"; interface Props { - automation?: AutomationData; + automation?: AutomationData | BareAutomationData; dims: DAGDims; - onUpdate: (auto: AutomationData) => void; + onUpdate: (auto: AutomationData | BareAutomationData) => void; onTrigger: () => void; onDelete: () => void; tagDB: TagDB; @@ -215,7 +215,7 @@ export const AutomationEditor: FC = ({ diff --git a/webapp/src/components/AutomationEditor/state.ts b/webapp/src/components/AutomationEditor/state.ts index f93a2a4..01e594d 100644 --- a/webapp/src/components/AutomationEditor/state.ts +++ b/webapp/src/components/AutomationEditor/state.ts @@ -1,8 +1,11 @@ import { useState, useEffect } from "react"; -import { AutomationData, AutomationMetadata } from "types/automations"; +import { + AutomationData, + AutomationMetadata, + BareAutomationData, +} from "types/automations"; import * as v from "types/validators/autmation"; -import { getFailures } from "types/validators/helper"; -import { MiniFailure } from "../../types/validators/helper"; +import { getFailures, MiniFailure } from "types/validators/helper"; export type EditorData = ReturnType; export type EditorState = @@ -26,12 +29,18 @@ export type EditorState = export type EditorStatus = EditorState["status"]; export const useAutomatioEditorState = ( - automation: AutomationData | undefined, - onSave: (a: AutomationData) => void + automation: AutomationData | BareAutomationData | undefined, + onSave: (a: AutomationData | BareAutomationData) => void ) => { + // state const [state, update] = useState({ status: "loading", }); + + // helpers + const validate = (data: any) => { + return getFailures(data, v.AutomationData); + }; const makeUpdate = (name: K) => (data: D) => @@ -69,26 +78,9 @@ export const useAutomatioEditorState = ( } }; - useEffect(() => { - if (automation) { - const failures = getFailures(automation, v.AutomationData); - if (failures) { - update({ - status: "invalid", - failures, - data: genEditorData(automation), - }); - } else { - update({ - status: "unchanged", - data: genEditorData(automation), - }); - } - } - }, [automation]); - - return { - validate: (data: any) => getFailures(data, v.AutomationData), + // pub methods + const methods = { + validate, updateTrigger: makeUpdate("trigger"), updateSequence: makeUpdate("action"), updateCondition: makeUpdate("condition"), @@ -137,9 +129,30 @@ export const useAutomatioEditorState = ( return state; }, }; + + // effects + useEffect(() => { + if (automation) { + const failures = validate(automation); + if (failures) { + update({ + status: "invalid", + failures, + data: genEditorData(automation), + }); + } else { + update({ + status: "unchanged", + data: genEditorData(automation), + }); + } + } + }, [automation]); + + return methods; }; -const genEditorData = (automation: AutomationData) => { +const genEditorData = (automation: AutomationData | BareAutomationData) => { const { tags: rawTags, trigger, action, condition, ...metadata } = automation; const tags: [string, string][] = Object.keys(rawTags).map((tagName) => [ diff --git a/webapp/src/components/AutomationManager/Loaded/automationDB.ts b/webapp/src/components/AutomationManager/Loaded/automationDB.ts index c071ce7..ebe9bd6 100644 --- a/webapp/src/components/AutomationManager/Loaded/automationDB.ts +++ b/webapp/src/components/AutomationManager/Loaded/automationDB.ts @@ -1,6 +1,6 @@ import { HassEntities } from "home-assistant-js-websocket"; import { useEffect, useState } from "react"; -import { AutomationData } from "types/automations"; +import { AutomationData, BareAutomationData } from "types/automations"; import { defaultAutomation } from "utils/defaults"; import { TagDB } from "../TagDB"; import { AutomationManagerAuto } from "../types"; @@ -12,7 +12,9 @@ export const useAutomationDB = ( ) => { const autoMap = genMapping(haEntities, configAutomations, tagsDB); const [newAuto, setNewAuto] = - useState(null); + useState< + null | [AutomationManagerAuto, AutomationData | BareAutomationData] + >(null); useEffect(() => { if (newAuto && autoMap[newAuto[0].id]) { @@ -30,7 +32,9 @@ export const useAutomationDB = ( }, getAutomationData( autoId: string - ): null | [AutomationManagerAuto, AutomationData | null] { + ): + | null + | [AutomationManagerAuto, AutomationData | BareAutomationData | null] { if (newAuto && newAuto[0].id === autoId) { return newAuto; } @@ -54,9 +58,9 @@ export const useAutomationDB = ( tags: {}, issue: "New Automation", isNew: true, - source_file: auto.source_file, - source_file_type: auto.source_file_type, - configuration_key: auto.configuration_key, + source_file: "n/a", + source_file_type: "n/a", + configuration_key: "n/a", }, auto, ]); diff --git a/webapp/src/components/AutomationManager/Loaded/state.ts b/webapp/src/components/AutomationManager/Loaded/state.ts index 6bffc2f..74cbca4 100644 --- a/webapp/src/components/AutomationManager/Loaded/state.ts +++ b/webapp/src/components/AutomationManager/Loaded/state.ts @@ -1,7 +1,7 @@ import { HassEntities } from "home-assistant-js-websocket"; import { useState } from "react"; import { useCookies } from "react-cookie"; -import { AutomationData } from "types/automations"; +import { AutomationData, BareAutomationData } from "types/automations"; import { useTagDB } from "../TagDB"; import { useAutomationDB } from "./automationDB"; import { useConfirm } from "material-ui-confirm"; @@ -12,7 +12,7 @@ export type UseAutomationManagerStateArgs = { configAutomations: AutomationData[]; hassEntities: HassEntities; onUpdateTags: (aid: string, tags: Record) => void; - onAutomationAdd: (auto: AutomationData) => void; + onAutomationAdd: (auto: BareAutomationData) => void; onAutomationUpdate: (auto: AutomationData) => void; onAutomationStateChange: (eid: string, on: boolean) => void; onAutomationRun: (eid: string) => void; @@ -68,7 +68,7 @@ export const useAutomationManagerState = ({ get tagsDB() { return tagsDB; }, - get currentAutomation(): AutomationData | null { + get currentAutomation(): AutomationData | BareAutomationData | null { return currentAutomation === null ? null : currentAutomation[1]; }, get currentAutomationIsNew() { @@ -95,11 +95,11 @@ export const useAutomationManagerState = ({ const auto = automationDB.addNew(); methods.setSelectedAutomationId(auto.id, true); }, - editorUpdateAutomation(auto: AutomationData) { + editorUpdateAutomation(auto: AutomationData | BareAutomationData) { if (methods.currentAutomationIsNew) { onAutomationAdd(auto); } else if (methods.currentAutomationId) { - onAutomationUpdate(auto); + onAutomationUpdate(auto as AutomationData); } }, sideBarUpdateAutomation( @@ -108,7 +108,13 @@ export const useAutomationManagerState = ({ eid: string ) { const previousAuto = automationDB.getAutomationData(aid); - if (previousAuto && previousAuto[1]) { + if ( + previousAuto && + previousAuto[1] && + "configuration_key" in previousAuto[1] && + "source_file" in previousAuto[1] && + "source_file_type" in previousAuto[1] + ) { const previousAutoState = previousAuto[1]; if ( previousAutoState.alias !== a.title || diff --git a/webapp/src/components/AutomationManager/index.stories.tsx b/webapp/src/components/AutomationManager/index.stories.tsx index 41c1c9b..99b4c06 100644 --- a/webapp/src/components/AutomationManager/index.stories.tsx +++ b/webapp/src/components/AutomationManager/index.stories.tsx @@ -19,10 +19,10 @@ const { make, componentMeta } = makeStory({ {}} - triggerAutomation={() => {}} - forceDeleteAutomation={() => {}} - onAutomationStateChange={(eid, on) => { + refreshAutomations={async () => {}} + triggerAutomation={async () => {}} + forceDeleteAutomation={async () => {}} + onAutomationStateChange={async (eid, on) => { if (!haEntities.loading && !haEntities.error) { setHAE({ ...haEntities, diff --git a/webapp/src/components/AutomationManager/index.tsx b/webapp/src/components/AutomationManager/index.tsx index 3c09206..34a73d2 100644 --- a/webapp/src/components/AutomationManager/index.tsx +++ b/webapp/src/components/AutomationManager/index.tsx @@ -14,12 +14,13 @@ 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"; +import { APIResponse } from "apiService/types"; export type AutomationManagerProps = { - onAutomationStateChange: (eid: string, on: boolean) => void; - refreshAutomations: () => void; - forceDeleteAutomation: (eid: string) => void; - triggerAutomation: (eid: string) => void; + onAutomationStateChange: (eid: string, on: boolean) => Promise; + refreshAutomations: () => Promise; + forceDeleteAutomation: (eid: string) => Promise; + triggerAutomation: (eid: string) => Promise; haEntities: HAEntitiesState; api: ApiService; }; @@ -27,16 +28,78 @@ export type AutomationManagerProps = { export const AutomationManager: FC = ({ api, haEntities, - onAutomationStateChange, - refreshAutomations, - forceDeleteAutomation, - triggerAutomation, + onAutomationStateChange: _onAutomationStateChange, + refreshAutomations: _refreshAutomations, + forceDeleteAutomation: _forceDeleteAutomation, + triggerAutomation: _triggerAutomation, }) => { const snackbr = useSnackbar(); const confirm = useConfirm(); const validationsShown = useRef(false); - const [isSaving, setIsSaving] = useState(false); + const [isSaving, setIsSaving] = useState([]); + // helpers + function wrapPromise( + name: string, + errorMessage: string, + makePromise: () => Promise + ) { + setIsSaving(isSaving.concat([name])); + return makePromise() + .then((resp) => { + setIsSaving(isSaving.filter((k) => k !== name)); + return resp; + }) + .catch((err) => { + console.error(err); + snackbr.enqueueSnackbar(errorMessage.replace("{{err}}", String(err)), { + variant: "error", + }); + setIsSaving(isSaving.filter((k) => k !== name)); + }); + } + const wrapApiPromise = ( + name: string, + errorMessage: string, + makePromise: () => Promise> + ) => { + wrapPromise(name, errorMessage, makePromise).then((resp) => { + if (resp) { + if (resp.ok) { + refreshAutomations(); + } else { + snackbr.enqueueSnackbar(errorMessage.replace("{{err}}", resp.error), { + variant: "error", + }); + } + } + }); + }; + + const onAutomationStateChange = (eid: string, on: boolean) => + wrapPromise( + "changing automation state", + 'failed to toggle autonation due to "{{err}}"', + () => _onAutomationStateChange(eid, on) + ); + const refreshAutomations = () => + wrapPromise( + "refreshing automations", + 'failed refreshing automations due to "{{err}}"', + () => _refreshAutomations() + ); + const forceDeleteAutomation = (eid: string) => + wrapPromise("deleting automations", 'failed delete due to "{{err}}"', () => + _forceDeleteAutomation(eid) + ); + const triggerAutomation = (eid: string) => + wrapPromise( + "triggering automations", + 'failed trigger due to "{{err}}"', + () => _triggerAutomation(eid) + ); + + // effects useEffect(() => { refreshAutomations(); // eslint-disable-next-line @@ -144,7 +207,6 @@ export const AutomationManager: FC = ({ } // alias - const hassEntities = haEntities.collection; const configAutomations = api.state.automations.data; @@ -155,15 +217,24 @@ export const AutomationManager: FC = ({ hassEntities, }} > + {isSaving.length > 0 && ( + <> + {isSaving.join(" and ")}... + + + )} { - await api.updateAutomation(auto); - refreshAutomations(); - }} + onAutomationAdd={(auto) => + wrapApiPromise( + "adding automation", + "Failed to create automation, recieved error: {{err}}!", + () => api.createAutomation(auto) as any + ) + } onAutomationDelete={(aid, eid) => { const autoToDelete = configAutomations.data.find( ({ id }) => id === aid @@ -188,30 +259,25 @@ export const AutomationManager: FC = ({ } // 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", - } - ); - }); - }} + onAutomationUpdate={(auto) => + wrapApiPromise( + "updating automation", + "Failed to update automation, recieved error: {{err}}!", + () => api.updateAutomation(auto) as any + ) + } onUpdateTags={async (aid, t) => { - setIsSaving(true); - await api.updateTags({ - automation_id: aid, - tags: t, - }); - setIsSaving(false); + wrapApiPromise( + "updating tags", + "Failed to update tags, recieved error: {{err}}!", + () => + api.updateTags({ + automation_id: aid, + tags: t, + }) as any + ); }} - > - {isSaving && } - + /> ); }; diff --git a/webapp/src/routes/automation.tsx b/webapp/src/routes/automation.tsx index a0ce084..e6689ff 100644 --- a/webapp/src/routes/automation.tsx +++ b/webapp/src/routes/automation.tsx @@ -1,5 +1,4 @@ import { ApiService } from "apiService/core"; -import { Page } from "components/Page"; import { FC } from "react"; import { useHA } from "haService"; import { AutomationManager } from "components/AutomationManager"; @@ -7,38 +6,36 @@ import { AutomationManager } from "components/AutomationManager"; export const AutomationRoute: FC<{ api: ApiService }> = ({ api }) => { const ha = useHA(); return ( - - ha.callService("automation", "reload")} - triggerAutomation={(entity_id) => - ha.callService( - "automation", - "trigger", - {}, - { - entity_id, - } - ) - } - forceDeleteAutomation={(eid) => - ha.callHA({ + ha.callService("automation", "reload")} + triggerAutomation={(entity_id) => + ha.callService( + "automation", + "trigger", + {}, + { + entity_id, + } + ) + } + forceDeleteAutomation={(eid) => + ha.callHA({ + entity_id: eid, + type: "config/entity_registry/remove", + }) + } + onAutomationStateChange={(eid, on) => + ha.callService( + "automation", + on ? "turn_on" : "turn_off", + {}, + { entity_id: eid, - type: "config/entity_registry/remove", - }) - } - onAutomationStateChange={(eid, on) => { - ha.callService( - "automation", - on ? "turn_on" : "turn_off", - {}, - { - entity_id: eid, - } - ); - }} - haEntities={ha.entities} - /> - + } + ) + } + haEntities={ha.entities} + /> ); }; diff --git a/webapp/src/types/automations/index.ts b/webapp/src/types/automations/index.ts index f8b66ae..ee1c1eb 100644 --- a/webapp/src/types/automations/index.ts +++ b/webapp/src/types/automations/index.ts @@ -6,16 +6,23 @@ import { AutomationTrigger, TriggerType } from "./triggers"; import * as mv from "types/validators/metadata"; export type AutomationMetadata = st.Infer; +export type AutomationShortumationMetadata = st.Infer< + typeof mv.AutomationShortumationMetadata +>; export interface AutomationActionData { trigger: AutomationTrigger[]; condition: AutomationCondition[]; action: AutomationSequenceNode[]; } -export interface AutomationData +export interface BareAutomationData extends AutomationActionData, AutomationMetadata { tags: Record; } +export interface AutomationData + extends BareAutomationData, + AutomationShortumationMetadata {} + export type AutomationSequenceNode = AutomationAction | AutomationCondition; export type AutomationNodeMapping = { trigger: AutomationTrigger; diff --git a/webapp/src/types/validators/autmation.ts b/webapp/src/types/validators/autmation.ts index 88c0ea2..e70d31d 100644 --- a/webapp/src/types/validators/autmation.ts +++ b/webapp/src/types/validators/autmation.ts @@ -10,9 +10,24 @@ export const AutomationData = st.object({ mode: st.enums(["single", "restart", "queued", "parallel"]), tags: st.record(st.string(), st.string()), - source_file: st.string(), - source_file_type: st.string(), - configuration_key: st.string(), + source_file: st.optional(st.string()), + source_file_type: st.optional(st.string()), + configuration_key: st.optional(st.string()), + + trigger: st.array(st.object()), + condition: st.array(st.object()), + action: st.array(st.object()), +}); + +export const BareAutomationData = st.object({ + 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"]), + tags: st.record(st.string(), st.string()), trigger: st.array(st.object()), condition: st.array(st.object()), diff --git a/webapp/src/types/validators/metadata.ts b/webapp/src/types/validators/metadata.ts index 9763c09..51d8293 100644 --- a/webapp/src/types/validators/metadata.ts +++ b/webapp/src/types/validators/metadata.ts @@ -8,6 +8,9 @@ export const AutomationMetadata = st.object({ st.nullable(st.record(st.string(), st.string())) ), mode: st.enums(["single", "restart", "queued", "parallel"]), +}); + +export const AutomationShortumationMetadata = st.object({ source_file: st.string(), source_file_type: st.string(), configuration_key: st.string(), diff --git a/webapp/src/utils/defaults.ts b/webapp/src/utils/defaults.ts index 0b60321..372fb7b 100644 --- a/webapp/src/utils/defaults.ts +++ b/webapp/src/utils/defaults.ts @@ -8,7 +8,7 @@ import { TriggerCondition, ZoneCondition, } from "types/automations/conditions"; -import { AutomationData } from "types/automations"; +import { BareAutomationData } from "types/automations"; export const getConditionDefaultValues = ( condition: AutomationCondition["condition"] @@ -62,14 +62,11 @@ export const getConditionDefaultValues = ( } as any; }; -export const defaultAutomation = (id: string): AutomationData => ({ +export const defaultAutomation = (id: string): BareAutomationData => ({ id, alias: "New Automation", description: "", mode: "single", - source_file: "automation.yaml", - source_file_type: "list", - configuration_key: "automation", tags: {}, trigger: [], action: [],