diff --git a/api/src/api/routes/automations.py b/api/src/api/routes/automations.py index 6868c47..de98e3f 100644 --- a/api/src/api/routes/automations.py +++ b/api/src/api/routes/automations.py @@ -5,6 +5,7 @@ from src.api.types import ( ListData, ListParams, UpdateAutoRequest, + UpdateTags, ) from src.automations.errors import FailedDeletion from src.automations.manager import AutomationManager @@ -29,6 +30,10 @@ def make_automation_router(automations: AutomationManager) -> APIRouter: def upsert_auto(body: UpdateAutoRequest): automations.update(body.index, body.data) + @router.post("/item/tags") + def update_tags(body: UpdateTags): + automations.update_tags(body.automation_id, body.data) + @router.delete("/item") def delete_auto(body: DeleteAutoRequest): try: diff --git a/api/src/api/types.py b/api/src/api/types.py index 42c6c45..060e3a9 100644 --- a/api/src/api/types.py +++ b/api/src/api/types.py @@ -1,4 +1,4 @@ -from typing import Generic, List, TypeVar +from typing import Dict, Generic, List, TypeVar from pydantic import BaseModel from pydantic.fields import Field @@ -25,5 +25,10 @@ class UpdateAutoRequest(BaseModel): data: ExtenededAutomationData +class UpdateTags(BaseModel): + automation_id: str = Field(description="Automation Id to update") + tags: Dict[str, str] + + class DeleteAutoRequest(BaseModel): index: int = Field(description="Index of the automation to update") diff --git a/api/src/automations/manager.py b/api/src/automations/manager.py index b2ff501..2a77a29 100644 --- a/api/src/automations/manager.py +++ b/api/src/automations/manager.py @@ -1,4 +1,4 @@ -from typing import Iterator, List, Optional +from typing import Dict, Iterator, List, Optional from src.automations.errors import FailedDeletion, InvalidAutomationFile from src.automations.types import AutomationData, ExtenededAutomationData @@ -24,7 +24,7 @@ class AutomationManager: break yield from load_automation(auto, tags.get(auto.get("id", ""), {})) - def get(self, index: int) -> Optional[AutomationData]: + def get(self, index: int) -> Optional[ExtenededAutomationData]: tags = self.hass_config.automation_tags if index >= 0: for i, auto in enumerate(self.hass_config.automations): @@ -51,6 +51,11 @@ class AutomationManager: self.hass_config.save_automations(automations) self.hass_config.save_tags(tags) + def update_tags(self, auto_id: str, tags: Dict[str, str]): + autos_tags = self.hass_config.automation_tags + autos_tags[auto_id] = tags + self.hass_config.save_tags(autos_tags) + def delete(self, index: int): automations: List[dict] = [] deleted = False diff --git a/api/tests/unittests/automations/test_manager.py b/api/tests/unittests/automations/test_manager.py index d6accd6..d45e3a7 100644 --- a/api/tests/unittests/automations/test_manager.py +++ b/api/tests/unittests/automations/test_manager.py @@ -100,3 +100,16 @@ class manager_tests(TestCase): self.assertEqual(manager.get_total_items(), 3) with self.assertRaises(FailedDeletion): manager.delete(10) + + def test_save_tags(self): + _, _, manager = get_dummy_automation_loader( + [ + ExtenededAutomationData(metadata=AutomationMetdata(id="test1")), + ExtenededAutomationData(metadata=AutomationMetdata(id="test2")), + ExtenededAutomationData(metadata=AutomationMetdata(id="test3")), + ], + automation_in_conifguration_mode="none", + ) + manager.update_tags("test1", {"room": "bathroom"}) + auto = manager.get(0) + assert auto.tags == {"room": "bathroom"} diff --git a/webapp/src/apiService/automations.ts b/webapp/src/apiService/automations.ts index 7d0ab10..646be0a 100644 --- a/webapp/src/apiService/automations.ts +++ b/webapp/src/apiService/automations.ts @@ -1,27 +1,46 @@ import { AutomationData } from "types/automations"; import { API } from "./base"; import { ListData, ListParams } from "./types"; -import { AUTOMTAION_LIST, AUTOMTAION_ITEM } from './paths'; - +import { + AUTOMTAION_LIST, + AUTOMTAION_ITEM, + AUTOMTAION_ITEM_TAGS, +} from "./paths"; export const makeAutomationAPI = (api: API) => ({ async list({ offset, limit }: ListParams) { const data = await api.makeCall, ListParams>({ path: AUTOMTAION_LIST, data: { - offset, limit, - } + offset, + limit, + }, }); return data; }, - async update({ index, auto }: { index: number, auto: AutomationData }) { + async update({ index, auto }: { index: number; auto: AutomationData }) { return await api.makeCall({ path: AUTOMTAION_ITEM, data: { index, - data: auto + data: auto, }, - }) + }); + }, + async updateTags({ + automation_id, + tags, + }: { + automation_id: string; + tags: Record; + }) { + return await api.makeCall({ + path: AUTOMTAION_ITEM_TAGS, + data: { + automation_id, + tags, + }, + }); }, async remove({ index }: { index: number }) { return await api.makeCall({ @@ -29,10 +48,9 @@ export const makeAutomationAPI = (api: API) => ({ path: AUTOMTAION_ITEM, data: { index, - } - }) - } + }, + }); + }, }); - export type AutomationAPI = ReturnType; diff --git a/webapp/src/apiService/core.ts b/webapp/src/apiService/core.ts index 90da799..e8c1920 100644 --- a/webapp/src/apiService/core.ts +++ b/webapp/src/apiService/core.ts @@ -1,15 +1,16 @@ -import { useEffect } from 'react'; -import { useDefaultApiState, makeReloadAutomations } from './util'; -import { AutomationAPI } from './automations'; +import { useEffect } from "react"; +import { useDefaultApiState, makeReloadAutomations } from "./util"; +import { AutomationAPI } from "./automations"; export type ApiService = ReturnType; -export const useAPIService = ( - automationAPI: AutomationAPI -) => { +export const useAPIService = (automationAPI: AutomationAPI) => { // state const [state, setState] = useDefaultApiState(); - const { reload, wrapCall } = makeReloadAutomations(automationAPI, state, setState); - + const { reload, wrapCall } = makeReloadAutomations( + automationAPI, + state, + setState + ); // initial load of autos useEffect(() => { @@ -21,5 +22,6 @@ export const useAPIService = ( state, removeAutomation: wrapCall(automationAPI.remove), updateAutomation: wrapCall(automationAPI.update), - } -} + updateTags: wrapCall(automationAPI.updateTags), + }; +}; diff --git a/webapp/src/apiService/mock.test.ts b/webapp/src/apiService/mock.test.ts index c430e44..dae0e91 100644 --- a/webapp/src/apiService/mock.test.ts +++ b/webapp/src/apiService/mock.test.ts @@ -1,57 +1,93 @@ -import { useMockAPI } from "./mock" +import { useMockAPI } from "./mock"; import { makeAutomationAPI } from "./automations"; -import { createMockAuto } from '../utils/mocks'; +import { createMockAuto } from "../utils/mocks"; +import { AutomationData } from "types/automations"; const fakeUseRef = (a: any) => ({ current: a }); -test('mock api uses initial autos for initial population -- empty', async () => { +test("mock api uses initial autos for initial population -- empty", async () => { const mockApi = makeAutomationAPI(useMockAPI([], fakeUseRef as any)); const data = await mockApi.list({ limit: 10, offset: 0 }); expect(data.ok).toBe(true); expect((data as any).data.data).toHaveLength(0); expect((data as any).data.totalItems).toBe(0); -}) +}); -test('mock api uses initial autos for initial population -- some data', async () => { - const initials = [ - createMockAuto(), - createMockAuto() - ]; +test("mock api uses initial autos for initial population -- some data", async () => { + const initials = [createMockAuto(), createMockAuto()]; const mockApi = makeAutomationAPI(useMockAPI(initials, fakeUseRef as any)); const data = await mockApi.list({ limit: 10, offset: 0 }); expect(data.ok).toBe(true); expect((data as any).data.data).toHaveLength(2); expect((data as any).data.totalItems).toBe(2); -}) +}); -test('populate mock api with 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({ index: 0, auto: 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({ index: 1, auto: 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); -}) +}); -test('delete/update data from mock api', async () => { - const mockApi = makeAutomationAPI(useMockAPI([ - createMockAuto(), - createMockAuto(), - createMockAuto(), - createMockAuto(), - createMockAuto(), - ], fakeUseRef as any)); - let data = (await mockApi.list({ limit: 10, offset: 0 }) as any).data.data; +test("delete/update data from mock api", async () => { + const mockApi = makeAutomationAPI( + useMockAPI( + [ + createMockAuto(), + createMockAuto(), + createMockAuto(), + createMockAuto(), + createMockAuto(), + ], + fakeUseRef as any + ) + ); + 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}) - data = (await mockApi.list({ limit: 10, offset: 0 }) as any).data.data; + await mockApi.update({ index: 0, auto: 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}) - data = (await mockApi.list({ limit: 10, offset: 0 }) as any).data.data; + await mockApi.remove({ index: 0 }); + data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data.data; expect(data[0].metadata.alias === "Bob is my uncle").toEqual(false); -}) +}); + +test("update tags from mock api", async () => { + const mockApi = makeAutomationAPI( + useMockAPI( + [ + createMockAuto(), + createMockAuto(), + createMockAuto(), + createMockAuto(), + createMockAuto(), + ], + fakeUseRef as any + ) + ); + let data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data + .data as AutomationData[]; + const autoId = data[0].metadata.id; + expect(data[0].tags).toStrictEqual({}); + mockApi.updateTags({ + automation_id: autoId, + tags: { + room: "bathroom", + type: "popup", + }, + }); + data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data + .data as AutomationData[]; + expect(data[0].metadata.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 e0f9077..eba7e95 100644 --- a/webapp/src/apiService/mock.ts +++ b/webapp/src/apiService/mock.ts @@ -1,33 +1,34 @@ -import { useRef } from 'react'; -import { AutomationData } from 'types/automations'; -import { API } from './base'; -import { AUTOMTAION_LIST, AUTOMTAION_ITEM } from './paths'; - +import { useRef } from "react"; +import { AutomationData } from "types/automations"; +import { API } from "./base"; +import { + AUTOMTAION_LIST, + AUTOMTAION_ITEM, + AUTOMTAION_ITEM_TAGS, +} from "./paths"; export const useMockAPI = ( initialAutos: AutomationData[] = [], - makeRef = useRef, + makeRef = useRef ): API => { const automationsRef = makeRef(initialAutos); return { - async makeCall({ - path, - method = "POST", - data = {} - }) { + async makeCall({ path, method = "POST", data = {} }) { // console.debug("[[mockCall]]", method, path, data); if (path === AUTOMTAION_LIST) { return { ok: true, - data: JSON.parse(JSON.stringify({ - totalItems: automationsRef.current.length, - params: { offset: 0, limit: 100 }, - data: automationsRef.current, - })) - } as any + data: JSON.parse( + JSON.stringify({ + totalItems: automationsRef.current.length, + params: { offset: 0, limit: 100 }, + data: automationsRef.current, + }) + ), + } as any; } if (path === AUTOMTAION_ITEM) { - if (method === 'POST') { + if (method === "POST") { const { index, data: auto } = data as any; if (index >= automationsRef.current.length) { automationsRef.current = [...automationsRef.current, auto]; @@ -35,29 +36,45 @@ export const useMockAPI = ( automationsRef.current = [ ...automationsRef.current.slice(0, index), auto, - ...automationsRef.current.slice(index + 1) + ...automationsRef.current.slice(index + 1), ]; } return { ok: true, - data: {} - } + data: {}, + }; } else if (method === "DELETE") { const { index } = data as any; automationsRef.current = [ ...automationsRef.current.slice(0, index), - ...automationsRef.current.slice(index + 1) + ...automationsRef.current.slice(index + 1), ]; return { ok: true, - data: {} + data: {}, + }; + } + } + if (path === AUTOMTAION_ITEM_TAGS) { + if (method === "POST") { + 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) { + automationsRef.current[i].tags = JSON.parse(JSON.stringify(tags)); + break; + } } + return { + ok: true, + data: {}, + }; } } return { ok: false, error: "PATH NOT FOUND " + method + ": " + path, - } - } - } -} + }; + }, + }; +}; diff --git a/webapp/src/apiService/paths.ts b/webapp/src/apiService/paths.ts index 64917cc..e5865c7 100644 --- a/webapp/src/apiService/paths.ts +++ b/webapp/src/apiService/paths.ts @@ -1,5 +1,4 @@ - - -export const AUTOMTAION_ROOT = '/' as const; +export const AUTOMTAION_ROOT = "/" as const; export const AUTOMTAION_LIST = `${AUTOMTAION_ROOT}list` as const; export const AUTOMTAION_ITEM = `${AUTOMTAION_ROOT}item` as const; +export const AUTOMTAION_ITEM_TAGS = `${AUTOMTAION_ITEM}/tags` as const; diff --git a/webapp/src/components/AutomationList/AutomationListBox.tsx b/webapp/src/components/AutomationList/AutomationListBox.tsx index fc005a1..66d2ccb 100644 --- a/webapp/src/components/AutomationList/AutomationListBox.tsx +++ b/webapp/src/components/AutomationList/AutomationListBox.tsx @@ -20,6 +20,7 @@ export type AutomationListBoxProps = { onSelectAutomation: (i: number) => void; onRemove: (i: number) => void; onAdd: () => void; + onUpdateTags: (id: string, tags: Record) => void; onUpdate: (a: AutomationData, i: number) => void; onLoadMore: (p: ListParams) => void; tagsDB: TagDB; @@ -62,14 +63,15 @@ const useAutomationListBoxState = () => { export const AutomationListBox: FC = ({ automations: { data: automations, - params: autoParams, + // params: autoParams, totalItems: totalAutomations, }, selected, onSelectAutomation, onAdd, onRemove, - onLoadMore, + // onLoadMore, + onUpdateTags, tagsDB, onUpdate, }) => { diff --git a/webapp/src/components/AutomationList/index.tsx b/webapp/src/components/AutomationList/index.tsx index cb75626..5a37315 100644 --- a/webapp/src/components/AutomationList/index.tsx +++ b/webapp/src/components/AutomationList/index.tsx @@ -21,6 +21,7 @@ import { ListData, ListParams } from "apiService/types"; interface AutomationListParams { automations: ListData; onUpdate: (i: number, auto: AutomationData) => void; + onUpdateTags: (id: string, tags: Record) => void; onAdd: (auto: AutomationData) => void; onRemove: (i: number) => void; onLoadMore: (p: ListParams) => void; @@ -58,6 +59,7 @@ export const AutomationList: FC = ({ automations, onLoadMore, onUpdate, + onUpdateTags, onAdd, onRemove, dims, @@ -96,6 +98,7 @@ export const AutomationList: FC = ({ onUpdate(i, a)} + onUpdateTags={onUpdateTags} onAdd={() => { onAdd(defaultAutomation(String(Date.now()))); setCurrent(automations.data.length); @@ -153,6 +156,16 @@ export const ConnectedAutomationList: FC = ({ }) => { const { reloadAutomations } = useHA(); const [saving, setSaving] = useState(false); + const updateTags = async (id: string, tags: Record) => { + const resp = await methods.updateTags({ + automation_id: id, + tags, + }); + setSaving(true); + await reloadAutomations(); + setSaving(false); + return resp; + }; const removeAutomation = async (args: any) => { const resp = await methods.removeAutomation(args); setSaving(true); @@ -187,6 +200,7 @@ export const ConnectedAutomationList: FC = ({ {}} onAdd={(auto) => updateAutomation({ auto, index: automations.data.totalItems + 1 })