diff --git a/commands/cat/dr_egeria.py b/commands/cat/dr_egeria.py index a1b7bf6b..6fcd10a0 100644 --- a/commands/cat/dr_egeria.py +++ b/commands/cat/dr_egeria.py @@ -60,12 +60,15 @@ help="Use Advanced usage level — shows additional attributes (default: Basic)") @click.option("--summary-only", is_flag=True, default=False, help="Only display the summary table and errors/warnings") @click.option("--debug", is_flag=True, default=False, help="Print each Egeria API request URL and body to the console") +@click.option("--local-only", is_flag=True, default=False, + help="Dashboard Sheet commands write the local JSON store only, not Egeria " + "(sets PYEGERIA_DASHBOARD_SHEETS_LOCAL_ONLY)") @logger.catch def process_markdown_file(input_file: str, output_folder: str, directive: str, do_validate: bool, do_process: bool, server: str, url: str, userid: str, user_pass: str, parse_summary: str, attribute_logs: str, advanced: bool, - summary_only: bool, debug: bool) -> None: + summary_only: bool, debug: bool, local_only: bool = False) -> None: """ Process a markdown file by parsing and executing Dr. Egeria md_commands. Write output to a new file. @@ -82,6 +85,8 @@ def process_markdown_file(input_file: str, output_folder: str, directive: str, # else: use --directive as-is (default "validate") usage_level = "Advanced" if advanced else "Basic" + if local_only: + os.environ["PYEGERIA_DASHBOARD_SHEETS_LOCAL_ONLY"] = "1" try: # Instantiate the client from pyegeria import EgeriaTech diff --git a/md_processing/dr_egeria.py b/md_processing/dr_egeria.py index a9cbc165..2fc47bf9 100644 --- a/md_processing/dr_egeria.py +++ b/md_processing/dr_egeria.py @@ -504,8 +504,8 @@ def reg(base, cls): reg("Update Saved Query", SavedQueryProcessor) reg("Link Saved Query to Results Set", SmartQueryLinkProcessor) - # Dashboard Sheets (local pyegeria-only records, not Egeria elements yet -- - # see OVERVIEW_REPORTING_MODEL.md SS10 for the planned Collection-subtype migration) + # Dashboard Sheets: written to Egeria 6.3 as Dashboard -> DisplayDataSchemaType -> DisplayDataContainer + # -> DisplayDataField placements, and to the local JSON store during the transition (dashboard_sheet.py) reg("Create Dashboard Sheet", CreateDashboardSheetProcessor) reg("Link Report to Dashboard Sheet", LinkReportToDashboardSheetProcessor) reg("Add Text on Dashboard Sheet", AddTextOnDashboardSheetProcessor) diff --git a/md_processing/v2/dashboard_sheet.py b/md_processing/v2/dashboard_sheet.py index a2223437..5dace9e2 100644 --- a/md_processing/v2/dashboard_sheet.py +++ b/md_processing/v2/dashboard_sheet.py @@ -1,37 +1,131 @@ """ Dashboard Sheet Processors for Dr.Egeria v2. -Handles `Create Dashboard Sheet` and `Link Report to Dashboard Sheet` -- the -first Dr.Egeria commands that manage a purely local, pyegeria-only record -(see pyegeria.view._output_dashboard_sheet_models.DashboardSheet) instead of -an Egeria element. No OMVS calls are made. - -Design: rather than bypass AsyncBaseCommandProcessor entirely, the base -class's Egeria-lookup primitives (fetch_element / resolve_element_guid) are -overridden to consult a local JSON store instead of Egeria -- so the -inherited create<->update upsert-transition, qualified-name derivation, -caching, and validate/display dry-run machinery all keep working, just -against local data. This is a first version: once Dashboard Sheet becomes a -real Egeria Collection subtype (see OVERVIEW_REPORTING_MODEL.md SS10 and the -"PLANNED" notes on the Dashboard Sheet Base / Report to Dashboard Sheet Link -Base Tinderbox bundles), these processors extend to call real OMVS methods -instead of the local store, without changing the compact command specs. - -Store: PYEGERIA_DASHBOARD_SHEETS_STORE (default ~/.pyegeria/dashboard_sheets.json), -a single JSON file loaded fresh and saved back on every command -- durable -across separate `dr_egeria` invocations, unlike dashboard_sheet_registry.py's -in-memory RUNTIME store (which is for app-level consumers reading a merged -CONFIG+RUNTIME view, not for this authoring path). +Handles `Create Dashboard Sheet`, `Link Report to Dashboard Sheet` and `Add Text on Dashboard Sheet`. The +commands keep their names and syntax. Since Egeria 6.3 (odpi/egeria#9432) they write each sheet into Egeria +as the element chain of the report-spec pipeline note v5.5 §8d / §10.6(c): + + Dashboard (Dashboard::; displayName = the heading) + --Schema--> DisplayDataSchemaType (DashboardSchema::) + --AttributeForSchema--> DisplayDataContainer (DashboardSheet::; the sheet) + --NestedSchemaAttribute(position)--> one DisplayDataField per placement + (DashboardPlacement::::::; + displayName ` / `, see placement_display_name) + + A REPORT placement: placementKind "report", span, presentationStyle; its Report is linked by + DataSetContent from the Dashboard (queryId = the placement's qualifiedName, queryType "placement"). + A TEXT placement: placementKind "text", markdownContent. + Every placement: ScopedBy from each Perspective it names; DataDescription to the ReportSpec it drills + into, when that spec has an element. + +DB-1 (owner, 2026-11-09): during the transition every command writes Egeria AND the local JSON store +(PYEGERIA_DASHBOARD_SHEETS_STORE, default ~/.pyegeria/dashboard_sheets.json). With the local-only switch +(`dr_egeria --local-only`, or PYEGERIA_DASHBOARD_SHEETS_LOCAL_ONLY=1), or with no Egeria connection, the store +alone is written and the command output says so. + +Every write is an upsert by qualifiedName: re-running a document changes nothing. Removing a placement +detaches its DataSetContent link and deletes its field; deleting a sheet deletes its chain. Neither ever +deletes a Report or a ReportSpec -- a sheet shows reports, it does not own them. + +`DashboardSheetEgeriaWriter` is the one implementation of the Egeria side. The processors use it, and so does +`python -m pyegeria.view.dashboards migrate` (which writes sheets from the JSON store without going through +markdown, so text placements round-trip byte for byte). """ +from __future__ import annotations + import os -from typing import Any, Dict, Optional +from dataclasses import dataclass, field +from typing import Any, Callable, Dict, List, Optional from loguru import logger from md_processing.v2.processors import AsyncBaseCommandProcessor -from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, Placement, DashboardSheetDict +from md_processing.v2.report import ( + REPORT_SPEC_QN_PREFIXES, _props_differ, find_element_by_qualified_name, + find_report_spec_element, upsert_dashboard_asset, +) +from pyegeria.core._exceptions import PyegeriaConnectionException, PyegeriaNotFoundException +from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, DashboardSheetDict, Placement + +LOCAL_ONLY_ENV = "PYEGERIA_DASHBOARD_SHEETS_LOCAL_ONLY" +PLANNED_PREFIX = "planned:" +PAGE_SIZE = 25 + +# ---------------------------------------------------------------------------- qualified names + +DASHBOARD_QN_PREFIX = "Dashboard::" +SCHEMA_QN_PREFIX = "DashboardSchema::" +SHEET_QN_PREFIX = "DashboardSheet::" +PLACEMENT_QN_PREFIX = "DashboardPlacement::" + + +def dashboard_qn(sheet_name: str) -> str: + return f"{DASHBOARD_QN_PREFIX}{sheet_name}" + + +def schema_type_qn(sheet_name: str) -> str: + return f"{SCHEMA_QN_PREFIX}{sheet_name}" + + +def sheet_container_qn(sheet_name: str) -> str: + return f"{SHEET_QN_PREFIX}{sheet_name}" + + +def placement_qn(sheet_name: str, position: int, placement_name: str) -> str: + return f"{PLACEMENT_QN_PREFIX}{sheet_name}::{position}::{placement_name}" + + +def sheet_name_from_dashboard_qn(qualified_name: str) -> Optional[str]: + if qualified_name and qualified_name.startswith(DASHBOARD_QN_PREFIX): + return qualified_name[len(DASHBOARD_QN_PREFIX):] + return None + + +# ---------------------------------------------------------------------------- perspectives (DB-2) + +# Today's sheets use the Overview keys; DB-2 (owner, 2026-11-09) maps them to the Trellis perspective names +# (pipeline note §10.8). The label stays the placement's display value; the mapping only picks the element +# that ScopedBy links to. +PERSPECTIVE_TRELLIS_NAMES = { + "governance": "Governance", + "steward": "Steward", + "owner": "Data Owner", + "consumer": "Consumer", + "builder": "App/AI Builder", + "privacy": "Privacy", + "security": "Security", + "architecture": "Architecture", + "engineer": "Data Expert", + "engineering": "Data Expert", + "community": "Community", + "financial": "Financial", + "admin": "Administration", +} + +# Where a Trellis name and the qualifiedName of the element Trellis actually creates differ. Checked live +# 2026-11-09 (read only, 12 Perspective:: elements): §10.8 calls it "Data Owner", the element is +# Perspective::Owner; "Admin" is Perspective::Administration. +PERSPECTIVE_QN_OVERRIDES = { + "Data Owner": "Perspective::Owner", + "Owner": "Perspective::Owner", + "Admin": "Perspective::Administration", +} + + +def perspective_qualified_name(label: str) -> str: + """The qualifiedName of the Trellis Perspective element a placement's perspective label maps to.""" + text = (label or "").strip() + if text.startswith("Perspective::"): + return text + trellis = PERSPECTIVE_TRELLIS_NAMES.get(text.lower()) + if trellis is None: + # Already a Trellis name ("Steward", "Data Expert", "App/AI Builder"); match it case-insensitively. + trellis = next((v for v in set(PERSPECTIVE_TRELLIS_NAMES.values()) if v.lower() == text.lower()), text) + return PERSPECTIVE_QN_OVERRIDES.get(trellis, f"Perspective::{trellis}") +# ---------------------------------------------------------------------------- helpers + def _default_store_path() -> str: return os.path.expanduser( os.getenv("PYEGERIA_DASHBOARD_SHEETS_STORE", "~/.pyegeria/dashboard_sheets.json") @@ -39,15 +133,9 @@ def _default_store_path() -> str: def _parse_placement_perspectives(attributes: Dict[str, Any]) -> list: - """Read "Placement Perspectives" (BACKLOG.md NEXT-19, egeria-workspaces-fs) - out of a command's parsed attributes -- a "Simple List"-style attribute, - which the base attribute-parsing pipeline may hand back either as an - already-split list or as a raw comma-separated string (both shapes seen - elsewhere for this attribute style, see _normalize_report_params's own - _to_string_list coercion in format_set_executor.py); tolerate either - rather than assume one. Shared by both LinkReportToDashboardSheetProcessor - and AddTextOnDashboardSheetProcessor so the parsing rule lives in one - place, not duplicated per processor.""" + """Read "Placement Perspectives" out of a command's parsed attributes -- a "Simple List"-style + attribute, which the base attribute-parsing pipeline may hand back either as an already-split list or + as a raw comma-separated string; tolerate either.""" value = attributes.get("Placement Perspectives", {}).get("value") or [] if isinstance(value, str): return [p.strip() for p in value.split(",") if p.strip()] @@ -60,45 +148,630 @@ def _load_store(path: str) -> DashboardSheetDict: return DashboardSheetDict() -def _sheet_to_element(sheet: DashboardSheet) -> Dict[str, Any]: - """Wrap a DashboardSheet in a minimal Egeria-elementHeader-shaped dict so - the inherited pipeline's generic `element.get('elementHeader', {})...` - patterns work unmodified against local data.""" +def _truthy(value: Optional[str]) -> bool: + return str(value or "").strip().lower() in ("1", "true", "yes", "on") + + +def _is_guid_like(value: Any) -> bool: + text = str(value or "").strip() + return bool(text) and not text.startswith(("(", "No ")) and " found" not in text + + +def placement_kind(placement: Placement) -> str: + return "text" if placement.content is not None else "report" + + +def placement_display_name(sheet_name: str, placement_name: str) -> str: + """A placement field's displayName: ` / `. + + Not the bare placement name: a REPORT placement is named after its Report, and Dr.Egeria resolves + `Report Name` by displayName across all types, so a field sharing the Report's displayName makes that + lookup ambiguous and the next `Link Report to Dashboard Sheet` fails. The bare name is kept in + additionalProperties `placementName` (and in the qualifiedName). + """ + return f"{sheet_name} / {placement_name}" + + +def field_placement_name(properties: Dict[str, Any]) -> str: + """The bare placement name of a DisplayDataField: `placementName`, else the qualifiedName's last part.""" + extra = properties.get("additionalProperties") or {} + if extra.get("placementName"): + return extra["placementName"] + qn = properties.get("qualifiedName") or "" + if qn.startswith(PLACEMENT_QN_PREFIX): + parts = qn[len(PLACEMENT_QN_PREFIX):].split("::", 2) + if len(parts) == 3: + return parts[2] + return properties.get("displayName") or "" + + +def placement_field_properties(sheet_name: str, position: int, placement: Placement, + qualified_name: Optional[str] = None) -> Dict[str, Any]: + """The DisplayDataField properties for one placement. + + The perspective labels and the drill-down spec name are also kept on the field (additionalProperties + `perspectives`, comma-separated, and `detailSpec`): the ScopedBy / DataDescription links carry the graph + meaning, but only when the element exists, and a label is not recoverable from the element it maps to + ("owner" and "Data Owner" both map to Perspective::Owner). The reader gives back the labels as written. + """ + extra: Dict[str, str] = {"placementName": placement.ref} + if placement.perspectives: + extra["perspectives"] = ",".join(placement.perspectives) + if placement.detail_spec: + extra["detailSpec"] = placement.detail_spec + kind = placement_kind(placement) return { - "elementHeader": {"guid": sheet.name, "type": {"typeName": "DashboardSheet"}}, - "properties": { - "qualifiedName": f"Dashboard::{sheet.name}", - "displayName": sheet.heading, - "description": sheet.description, - }, + "class": "DisplayDataFieldProperties", + "typeName": "DisplayDataField", + "qualifiedName": qualified_name or placement_qn(sheet_name, position, placement.ref), + "displayName": placement_display_name(sheet_name, placement.ref), + "placementKind": kind, + "span": placement.span, + "presentationStyle": placement.emphasis, + "markdownContent": placement.content if kind == "text" else None, + "additionalProperties": extra, } -class CreateDashboardSheetProcessor(AsyncBaseCommandProcessor): - """Processor for Create Dashboard Sheet (and its Update transition).""" +def _refuse_kind_clash(sheet_name: str, placement: Placement, existing_kind: str) -> None: + """Placements are matched by name within a sheet, so a report and a text placement cannot share a name: + the second would silently replace the first. Refuse, in words.""" + kind = placement_kind(placement) + if existing_kind != kind: + raise ValueError( + f"Dashboard Sheet '{sheet_name}' already has a {existing_kind} placement named '{placement.ref}'; a " + f"{kind} placement cannot share its name (placements are matched by name). Give it another name.") + + +def duplicate_placement_names(sheet: DashboardSheet) -> List[str]: + """Names used by more than one placement of a sheet (they would collapse into one placement).""" + seen, dups = set(), [] + for p in sheet.placements: + ref = p.get("ref") if isinstance(p, dict) else p.ref + if ref in seen and ref not in dups: + dups.append(ref) + seen.add(ref) + return dups + + +def _field_props_differ(desired: Dict[str, Any], current: Dict[str, Any]) -> bool: + """Like _props_differ, but a property set on the field and now unset also counts as a change (a + placement re-run without perspectives must clear them).""" + if _props_differ(desired, current): + return True + if desired.get("markdownContent") is None and current.get("markdownContent"): + return True + return False + + +@dataclass +class SheetChain: + """The GUIDs of one sheet's chain in Egeria. A guid starting `planned:` is one a dry run would create.""" + sheet_name: str + dashboard_guid: Optional[str] = None + schema_type_guid: Optional[str] = None + container_guid: Optional[str] = None + dashboard: Optional[Dict[str, Any]] = None + + +@dataclass +class FieldInfo: + guid: str + qualified_name: str + display_name: str # the bare placement name (field_placement_name), not the field's displayName + position: Optional[int] + properties: Dict[str, Any] = field(default_factory=dict) + + +# ---------------------------------------------------------------------------- the writer + +class DashboardSheetEgeriaWriter: + """Writes Dashboard Sheets into Egeria as the §8d element chain. The one implementation, used by the + Dr.Egeria processors and by migration. + + `notes` collects what a reader of the command output must know (a report or perspective with no + element, a link not written); `actions` records every write made, or with `dry_run=True` every write + that would be made ("create DisplayDataField DashboardPlacement::..."), with "unchanged ..." for elements + already as wanted. A dry run still reads Egeria (bounded, page size 25) but writes nothing. + """ - def derive_qualified_name(self, attributes: Optional[Dict[str, Any]] = None) -> str: - """Override the inherited Egeria-style qn_prefix/org/version qualified-name - derivation -- local records are keyed by their plain Display Name, - so that's what fetch_as_is()/resolve_element_guid() need to match against. + def __init__(self, client: Any, *, dry_run: bool = False): + self.client = client + self.dry_run = dry_run + self.notes: List[str] = [] + self.actions: List[str] = [] + self._perspective_cache: Dict[str, Optional[str]] = {} + self._planned = 0 + + # ------------------------------------------------------------ small primitives + + def _note(self, text: str) -> None: + if text not in self.notes: + self.notes.append(text) + + def _plan(self, what: str) -> str: + self._planned += 1 + return f"{PLANNED_PREFIX}{self._planned}:{what}" + + @staticmethod + def _is_planned(guid: Optional[str]) -> bool: + return bool(guid) and str(guid).startswith(PLANNED_PREFIX) + + async def _find(self, qualified_name: str) -> Optional[Dict[str, Any]]: + return await find_element_by_qualified_name(self.client, qualified_name) + + async def _related(self, guid: Optional[str], relationship: str, start_at_end: int = 1) -> List[Dict[str, Any]]: + """Every element related to `guid` by `relationship`, paged at 25. Only an empty page ends the read + (a short page is not the last page).""" + if not guid or self._is_planned(guid): + return [] + out: List[Dict[str, Any]] = [] + start = 0 + while True: + try: + page = await self.client.classification_manager._async_get_related_elements( + guid, relationship, start_at_end=start_at_end, start_from=start, page_size=PAGE_SIZE, + graph_query_depth=0) + except PyegeriaNotFoundException: + page = [] + items = [e for e in page if isinstance(e, dict) and e.get("elementHeader")] if isinstance(page, list) else [] + if not items: + return out + out.extend(items) + start += len(items) + + @staticmethod + def _guid(element: Dict[str, Any]) -> str: + return element["elementHeader"]["guid"] + + @staticmethod + def _type(element: Dict[str, Any]) -> str: + return ((element.get("elementHeader") or {}).get("type") or {}).get("typeName", "") + + @staticmethod + def _rel_props(element: Dict[str, Any]) -> Dict[str, Any]: + return ((element.get("relatedBy") or {}).get("relationshipProperties")) or {} + + def _created_guid(self, raw: Any, what: str) -> str: + if isinstance(raw, str) and raw.strip(): + return raw.strip() + if isinstance(raw, dict) and raw.get("guid"): + return raw["guid"] + raise ValueError(f"Egeria returned no GUID creating {what}: {raw!r}") + + async def _create_schema_element(self, kind: str, props: Dict[str, Any], anchor_guid: Optional[str]) -> str: + """Create a schema type (kind "type") or attribute, anchored to the Dashboard.""" + qn = props["qualifiedName"] + self.actions.append(f"create {props['typeName']} {qn}") + if self.dry_run: + return self._plan(qn) + body = {"class": "NewElementRequestBody", "isOwnAnchor": False, "anchorGUID": anchor_guid, + "properties": props} + maker = self.client.schema_maker + raw = await (maker._async_create_schema_type(body) if kind == "type" + else maker._async_create_schema_attribute(body)) + return self._created_guid(raw, qn) + + async def _update_schema_attribute(self, guid: str, props: Dict[str, Any]) -> None: + self.actions.append(f"update {props['typeName']} {props['qualifiedName']}") + if self.dry_run: + return + await self.client.schema_maker._async_update_schema_attribute( + guid, {"class": "UpdateElementRequestBody", "properties": props, "mergeUpdate": False}) + + # ------------------------------------------------------------ reading the chain (no writes) + + async def find_chain(self, sheet_name: str) -> SheetChain: + """The chain as it is in Egeria; any missing part is None.""" + chain = SheetChain(sheet_name=sheet_name) + dashboard = await self._find(dashboard_qn(sheet_name)) + if not dashboard: + return chain + chain.dashboard = dashboard + chain.dashboard_guid = self._guid(dashboard) + schema_types = [e for e in await self._related(chain.dashboard_guid, "Schema") + if self._type(e) == "DisplayDataSchemaType"] + if schema_types: + wanted = [e for e in schema_types if (e.get("properties") or {}).get("qualifiedName") + == schema_type_qn(sheet_name)] + chain.schema_type_guid = self._guid((wanted or schema_types)[0]) + containers = [e for e in await self._related(chain.schema_type_guid, "AttributeForSchema") + if self._type(e) == "DisplayDataContainer"] + wanted = [e for e in containers if (e.get("properties") or {}).get("qualifiedName") + == sheet_container_qn(sheet_name)] + if containers: + chain.container_guid = self._guid((wanted or containers)[0]) + return chain + + async def list_fields(self, container_guid: Optional[str]) -> List[FieldInfo]: + """The placements under a sheet container, in position order.""" + fields: List[FieldInfo] = [] + for e in await self._related(container_guid, "NestedSchemaAttribute"): + if self._type(e) != "DisplayDataField": + continue + props = e.get("properties") or {} + position = self._rel_props(e).get("position") + fields.append(FieldInfo(guid=self._guid(e), qualified_name=props.get("qualifiedName", ""), + display_name=field_placement_name(props), + position=int(position) if position is not None else None, + properties=props)) + fields.sort(key=lambda f: (f.position is None, f.position or 0)) + return fields + + # ------------------------------------------------------------ sheet + + async def ensure_sheet(self, sheet_name: str, heading: str, description: str = "", + family: Optional[str] = None, aliases: Optional[List[str]] = None) -> SheetChain: + """Create or update the Dashboard, its DisplayDataSchemaType and the sheet's DisplayDataContainer.""" + chain = await self.find_chain(sheet_name) + + # 1. the Dashboard asset -- through upsert_dashboard_asset, the same code as `Create Dashboard` + props: Dict[str, Any] = { + "class": "DashboardProperties", + "typeName": "Dashboard", + "qualifiedName": dashboard_qn(sheet_name), + "displayName": heading or sheet_name, + "description": description or None, + "aliases": list(aliases) if aliases else None, + "additionalProperties": {"family": family} if family else None, + } + if self.dry_run: + if chain.dashboard is None: + self.actions.append(f"create Dashboard {props['qualifiedName']}") + chain.dashboard_guid = self._plan(props["qualifiedName"]) + elif _props_differ(props, chain.dashboard.get("properties") or {}): + self.actions.append(f"update Dashboard {props['qualifiedName']}") + else: + self.actions.append(f"unchanged Dashboard {props['qualifiedName']}") + else: + guid, verb_word, _ = await upsert_dashboard_asset( + self.client, props["qualifiedName"], props, chain.dashboard, + create_body={"class": "NewElementRequestBody", "isOwnAnchor": True}) + chain.dashboard_guid = self._created_guid(guid, props["qualifiedName"]) + self.actions.append(f"{verb_word.lower()} Dashboard {props['qualifiedName']}") + + # 2. its DisplayDataSchemaType, linked by Schema + if chain.schema_type_guid is None: + st_props = {"class": "DisplayDataSchemaTypeProperties", "typeName": "DisplayDataSchemaType", + "qualifiedName": schema_type_qn(sheet_name), "displayName": f"{sheet_name} layout"} + existing = None if self._is_planned(chain.dashboard_guid) else await self._find(st_props["qualifiedName"]) + chain.schema_type_guid = (self._guid(existing) if existing + else await self._create_schema_element("type", st_props, chain.dashboard_guid)) + self.actions.append(f"link Schema {dashboard_qn(sheet_name)} -> {st_props['qualifiedName']}") + if not self.dry_run: + await self.client.schema_maker._async_link_schema(chain.dashboard_guid, chain.schema_type_guid) + else: + self.actions.append(f"unchanged DisplayDataSchemaType {schema_type_qn(sheet_name)}") + # found through the Schema link, so that link is in place too; itemised so a re-run's + # "unchanged" count matches the first run's change count + self.actions.append(f"unchanged Schema {dashboard_qn(sheet_name)} -> {schema_type_qn(sheet_name)}") + + # 3. the sheet's DisplayDataContainer, linked by AttributeForSchema (position 1) + if chain.container_guid is None: + c_props = {"class": "DisplayDataContainerProperties", "typeName": "DisplayDataContainer", + "qualifiedName": sheet_container_qn(sheet_name), "displayName": f"{sheet_name} sheet"} + existing = None if self._is_planned(chain.schema_type_guid) else await self._find(c_props["qualifiedName"]) + chain.container_guid = (self._guid(existing) if existing + else await self._create_schema_element("attribute", c_props, chain.dashboard_guid)) + self.actions.append(f"link AttributeForSchema {schema_type_qn(sheet_name)} -> {c_props['qualifiedName']} (position 1)") + if not self.dry_run: + await self.client.schema_maker._async_link_attribute_for_schema( + chain.schema_type_guid, chain.container_guid, + {"class": "NewRelationshipRequestBody", + "properties": {"class": "AttributeForSchemaProperties", "position": 1}}) + else: + self.actions.append(f"unchanged DisplayDataContainer {sheet_container_qn(sheet_name)}") + self.actions.append(f"unchanged AttributeForSchema {schema_type_qn(sheet_name)} -> " + f"{sheet_container_qn(sheet_name)}") + return chain + + # ------------------------------------------------------------ placements + + async def _resolve_report(self, report_name: str) -> Optional[str]: + """The GUID of the Report a placement shows: the one `Report` whose displayName is exactly + `report_name` (an exact, type-filtered lookup: 0.1 s live, where a contains-search took ~35 s), + else the Report whose qualifiedName it is. None if there + is none; two or more exact matches are a note, and no link. + + Not Dr.Egeria's `__async_get_guid__`: it tries a unique-name lookup first, which Egeria rejects + when the name is shared with an element of another type -- seen live 2026-11-09 for 'Term + Definition Completeness' and 'Governance Classification Coverage', both real Reports.""" + matches: List[str] = [] + start = 0 + while True: + try: + page = await self.client.classification_manager._async_get_elements_by_property_value( + report_name, ["displayName"], metadata_element_type="Report", + start_from=start, page_size=PAGE_SIZE, graph_query_depth=0) + except PyegeriaNotFoundException: + page = [] + items = [e for e in page if isinstance(e, dict) and e.get("elementHeader")] if isinstance(page, list) else [] + if not items: + break + matches += [self._guid(e) for e in items + if (e.get("properties") or {}).get("displayName") == report_name + and self._type(e) == "Report"] + start += len(items) + if len(matches) == 1: + return matches[0] + if len(matches) > 1: + self._note(f"{len(matches)} Reports are named '{report_name}' in Egeria: no report link was written " + f"for that placement. Give the placement's report a unique name.") + return None + element = await self._find(report_name) + if element and self._type(element) == "Report": + return self._guid(element) + return None - 2026-07-31: switched from the family-specific "Dashboard Sheet Name" - attribute to the universal "Display Name" -- Dashboard Sheet Base no - longer carries its own duplicate naming attribute.""" + async def _perspective_guid(self, label: str) -> Optional[str]: + qn = perspective_qualified_name(label) + if qn not in self._perspective_cache: + element = await self._find(qn) + self._perspective_cache[qn] = self._guid(element) if element else None + return self._perspective_cache[qn] + + async def upsert_placement(self, chain: SheetChain, placement: Placement, *, + position: Optional[int] = None, + report_guid: Optional[str] = None) -> str: + """Create or update one placement's DisplayDataField and its links. Found by name within the sheet + (a re-run with the same name updates in place; its qualifiedName and position never change).""" + sheet = chain.sheet_name + fields = await self.list_fields(chain.container_guid) + existing = next((f for f in fields if f.display_name == placement.ref), None) + + if existing: + _refuse_kind_clash(sheet, placement, existing.properties.get("placementKind") or "report") + pos = existing.position if existing.position is not None else (position or 0) + props = placement_field_properties(sheet, pos, placement, existing.qualified_name) + field_guid = existing.guid + if _field_props_differ(props, existing.properties): + await self._update_schema_attribute(field_guid, props) + else: + self.actions.append(f"unchanged DisplayDataField {existing.qualified_name}") + self.actions.append(f"unchanged NestedSchemaAttribute {sheet_container_qn(sheet)} -> " + f"{existing.qualified_name} (position {pos})") + else: + taken = [f.position for f in fields if f.position is not None] + if position is not None and position not in taken: + pos = position + else: # never reuse a taken position (after a removal, an index can equal one) + pos = max(taken) + 1 if taken else 1 + props = placement_field_properties(sheet, pos, placement) + found = None if self._is_planned(chain.container_guid) else await self._find(props["qualifiedName"]) + if found: + field_guid = self._guid(found) + if _field_props_differ(props, found.get("properties") or {}): + await self._update_schema_attribute(field_guid, props) + else: + field_guid = await self._create_schema_element("attribute", props, chain.dashboard_guid) + self.actions.append(f"link NestedSchemaAttribute {sheet_container_qn(sheet)} -> {props['qualifiedName']} (position {pos})") + if not self.dry_run: + await self.client.schema_maker._async_link_nested_schema_attribute( + chain.container_guid, field_guid, + {"class": "NewRelationshipRequestBody", + "properties": {"class": "NestedSchemaAttributeProperties", "position": pos}}) + + qn = props["qualifiedName"] + await self._sync_report_link(chain, placement, qn, report_guid) + await self._sync_perspectives(field_guid, placement) + await self._sync_detail_spec(field_guid, placement) + return field_guid + + async def _sync_report_link(self, chain: SheetChain, placement: Placement, qn: str, + report_guid: Optional[str]) -> None: + """DataSetContent Dashboard -> Report, queryId = the placement's qualifiedName.""" + binding: Dict[str, Any] = {"state": "unbound", "links": []} + if not self._is_planned(chain.dashboard_guid): + bindings = await self.client.asset_maker._async_get_placement_reports(chain.dashboard_guid, [qn]) + binding = (bindings or {}).get(qn) or binding + if placement_kind(placement) == "text": + if binding["links"]: + await self._detach_report(chain, qn, "the placement is text now") + return + if report_guid and not _is_guid_like(report_guid): + report_guid = None # "(Planned: ...)" or a not-found string from attribute resolution + if report_guid is None: + report_guid = await self._resolve_report(placement.ref) + if not report_guid: + self._note(f"Report '{placement.ref}' was not found in Egeria: placement '{placement.ref}' on sheet " + f"'{chain.sheet_name}' was written without its report link, and reads as missing until a " + f"Report with that name exists and the command is run again.") + if binding["links"]: + await self._detach_report(chain, qn, "its report is gone") + return + if binding.get("state") == "bound" and binding.get("report_guid") == report_guid: + self.actions.append(f"unchanged DataSetContent {dashboard_qn(chain.sheet_name)} -> {placement.ref} [{qn}]") + return + if binding["links"]: + await self._detach_report(chain, qn, "it showed a different report") + self.actions.append(f"link DataSetContent {dashboard_qn(chain.sheet_name)} -> Report '{placement.ref}' " + f"(queryId {qn})") + if not self.dry_run: + await self.client.asset_maker._async_link_placement_report(chain.dashboard_guid, report_guid, qn) + + async def _detach_report(self, chain: SheetChain, qn: str, why: str) -> None: + self.actions.append(f"detach DataSetContent for {qn} ({why})") + if not self.dry_run: + await self.client.asset_maker._async_detach_placement_report(chain.dashboard_guid, qn) + + async def _sync_perspectives(self, field_guid: str, placement: Placement) -> None: + """ScopedBy Perspective -> placement, one per label whose Trellis element exists. Never creates a + Perspective: a label with no element is written without that link, with a note.""" + wanted: Dict[str, str] = {} + for label in placement.perspectives: + guid = await self._perspective_guid(label) + if guid: + wanted[guid] = label + else: + self._note(f"Perspective '{label}' (as {perspective_qualified_name(label)}) does not exist in " + f"Egeria: placement '{placement.ref}' was written without that ScopedBy link. " + f"Perspectives are not created here.") + current = {self._guid(e) for e in await self._related(field_guid, "ScopedBy", start_at_end=2) + if self._type(e) == "Perspective"} + for guid in current - set(wanted): + self.actions.append(f"detach ScopedBy {guid} -> {placement.ref}") + if not self.dry_run: + await self.client.classification_manager._async_clear_scope_from_element(guid, field_guid) + for guid, label in wanted.items(): + if guid in current: + continue + self.actions.append(f"link ScopedBy {perspective_qualified_name(label)} -> {placement.ref}") + if not self.dry_run: + await self.client.classification_manager._async_add_scope_to_element(guid, field_guid) + + async def _sync_detail_spec(self, field_guid: str, placement: Placement) -> None: + """DataDescription placement -> the ReportSpec it drills into, when the spec has an element.""" + wanted: Optional[str] = None + if placement.detail_spec: + element = await find_report_spec_element(self.client, placement.detail_spec) + if element: + wanted = self._guid(element) + else: + self._note(f"Drill-down spec '{placement.detail_spec}' of placement '{placement.ref}' has no Egeria " + f"element (looked for {' and '.join(p + placement.detail_spec for p in REPORT_SPEC_QN_PREFIXES)}): " + f"no DataDescription link was written; the name is kept on the placement.") + current = {self._guid(e) for e in await self._related(field_guid, "DataDescription", start_at_end=1)} + for guid in current - ({wanted} if wanted else set()): + self.actions.append(f"detach DataDescription {placement.ref} -> {guid}") + if not self.dry_run: + await self.client.collection_manager._async_detach_data_description(field_guid, guid) + if wanted and wanted not in current: + self.actions.append(f"link DataDescription {placement.ref} -> {placement.detail_spec}") + if not self.dry_run: + await self.client.collection_manager._async_attach_data_description(field_guid, wanted) + + # ------------------------------------------------------------ whole sheets, removal + + async def write_sheet(self, sheet: DashboardSheet) -> SheetChain: + """Write a whole sheet (migration): the chain, then every placement at its 1-based position. + A sheet with two placements of one name is refused before anything is written: they would collapse + into one placement.""" + dups = duplicate_placement_names(sheet) + if dups: + raise ValueError(f"Dashboard Sheet '{sheet.name}' has more than one placement named " + f"{', '.join(repr(d) for d in dups)}; placements are matched by name, so they would " + f"collapse into one. Rename them in the store first. Nothing was written.") + chain = await self.ensure_sheet(sheet.name, sheet.heading, sheet.description, sheet.family, sheet.aliases) + for index, placement in enumerate(sheet.placements, start=1): + if isinstance(placement, dict): + placement = Placement(**placement) + await self.upsert_placement(chain, placement, position=index) + return chain + + async def remove_placement(self, sheet_name: str, placement_name: str) -> bool: + """Detach a placement's DataSetContent link and delete its field. Never deletes the Report. + False if the sheet or placement is not in Egeria.""" + chain = await self.find_chain(sheet_name) + fields = await self.list_fields(chain.container_guid) + target = next((f for f in fields if f.display_name == placement_name), None) + if not target: + return False + await self._detach_report(chain, target.qualified_name, "placement removed") + self.actions.append(f"delete DisplayDataField {target.qualified_name}") + if not self.dry_run: + await self.client.schema_maker._async_delete_schema_attribute(target.guid) + return True + + async def delete_sheet(self, sheet_name: str) -> bool: + """Delete a sheet's chain: each placement (link, then field), the container, the schema type, the + Dashboard. Reports and ReportSpecs are never deleted. False if the Dashboard is not in Egeria.""" + chain = await self.find_chain(sheet_name) + if not chain.dashboard_guid: + return False + for f in await self.list_fields(chain.container_guid): + await self._detach_report(chain, f.qualified_name, "sheet deleted") + self.actions.append(f"delete DisplayDataField {f.qualified_name}") + if not self.dry_run: + await self.client.schema_maker._async_delete_schema_attribute(f.guid) + if chain.container_guid: + self.actions.append(f"delete DisplayDataContainer {sheet_container_qn(sheet_name)}") + if not self.dry_run: + await self.client.schema_maker._async_delete_schema_attribute(chain.container_guid) + if chain.schema_type_guid: + self.actions.append(f"delete DisplayDataSchemaType {schema_type_qn(sheet_name)}") + if not self.dry_run: + await self.client.schema_maker._async_delete_schema_type(chain.schema_type_guid) + self.actions.append(f"delete Dashboard {dashboard_qn(sheet_name)}") + if not self.dry_run: + await self.client.asset_maker._async_delete_asset(chain.dashboard_guid) + return True + + +# ---------------------------------------------------------------------------- processors + +def local_only_reason(processor: AsyncBaseCommandProcessor) -> Optional[str]: + """Why this command writes the local store alone, or None when it writes Egeria too (DB-1).""" + if processor.context.get("dashboard_sheets_local_only"): + return "--local-only was given" + if _truthy(os.getenv(LOCAL_ONLY_ENV)): + return f"{LOCAL_ONLY_ENV} is set" + if processor.client is None: + return "there is no Egeria connection" + return None + + +def _egeria_section(writer: Optional[DashboardSheetEgeriaWriter], local_reason: Optional[str]) -> str: + if local_reason: + return f"\n- **Egeria**: not written ({local_reason}); the local store alone was written.\n" + lines = ["\n- **Egeria**: written"] + if writer is not None: + changed = [a for a in writer.actions if not a.startswith("unchanged")] + lines[0] += f" ({len(changed)} change(s))" if changed else " (no change: already as written)" + for note in writer.notes: + lines.append(f" - Note: {note}") + return "\n".join(lines) + "\n" + + +class _DashboardSheetProcessorMixin: + """Shared Egeria plumbing for the three sheet commands.""" + + async def _with_egeria(self, work: Callable[[DashboardSheetEgeriaWriter], Any]): + """Run `work` against Egeria unless the command is local-only. Returns (writer, local_reason). + An unreachable Egeria falls back to the store alone and says so; any other Egeria error fails the + command (and the store is then not written, so the two stay consistent).""" + reason = local_only_reason(self) + if reason: + return None, reason + writer = DashboardSheetEgeriaWriter(self.client) + try: + await work(writer) + except PyegeriaConnectionException as e: + return None, f"Egeria could not be reached ({e.__class__.__name__})" + for note in writer.notes: + self._add_warning(note) + return writer, None + + +class CreateDashboardSheetProcessor(_DashboardSheetProcessorMixin, AsyncBaseCommandProcessor): + """Processor for Create Dashboard Sheet (and its Update transition). + + The target is the Egeria Dashboard `Dashboard::` (or, local-only, the store record). + The Dashboard asset itself is written by `upsert_dashboard_asset`, the same code as `Create Dashboard`. + """ + + def derive_qualified_name(self, attributes: Optional[Dict[str, Any]] = None) -> str: if attributes is None: attributes = self.parsed_output.get("attributes", {}) - return attributes.get("Display Name", {}).get("value") or "" + name = attributes.get("Display Name", {}).get("value") or "" + return dashboard_qn(name) if name else "" - async def resolve_element_guid(self, name_or_guid: str, tech_type: Optional[str] = None) -> Optional[str]: - if not name_or_guid: + async def fetch_as_is(self) -> Optional[Dict[str, Any]]: + name = self.parsed_output.get("attributes", {}).get("Display Name", {}).get("value") + if not name: return None - sheets = _load_store(_default_store_path()) - return name_or_guid if name_or_guid in sheets else None - - async def fetch_element(self, guid: str) -> Optional[Dict[str, Any]]: - sheets = _load_store(_default_store_path()) - sheet = sheets.get(guid) - return _sheet_to_element(sheet) if sheet else None + if local_only_reason(self) is None: + try: + element = await find_element_by_qualified_name(self.client, dashboard_qn(name)) + except PyegeriaConnectionException: + element = None + if element: + return element + sheet = _load_store(_default_store_path()).get(name) + if sheet: + return {"elementHeader": {"guid": f"local:{sheet.name}", "type": {"typeName": "DashboardSheet"}}, + "properties": {"qualifiedName": dashboard_qn(sheet.name), "displayName": sheet.heading, + "description": sheet.description}} + return None async def apply_changes(self) -> str: attributes = self.parsed_output["attributes"] @@ -111,41 +784,57 @@ async def apply_changes(self) -> str: path = _default_store_path() sheets = _load_store(path) + aliases = list(sheets[name].aliases) if name in sheets else [] + + async def _work(writer: DashboardSheetEgeriaWriter): + chain = await writer.ensure_sheet(name, heading, description, family, aliases) + self.parsed_output["guid"] = chain.dashboard_guid + + writer, local_reason = await self._with_egeria(_work) + is_update = name in sheets sheets.upsert(name, DashboardSheet(name=name, heading=heading, description=description, family=family)) sheets.save_to_json(path) + if local_reason: + self.parsed_output["guid"] = name - self.parsed_output["guid"] = name verb_word = "Updated" if is_update else "Created" - logger.success(f"{verb_word} Dashboard Sheet '{name}' at {path}") + logger.success(f"{verb_word} Dashboard Sheet '{name}' (local store {path}; Egeria: " + f"{'not written, ' + local_reason if local_reason else 'written'})") return ( f"\n\n## {self.command.verb} Dashboard Sheet\n\n" f"{verb_word} Dashboard Sheet **{name}**\n\n" f"- **Heading**: {heading}\n" f"- **Description**: {description or '_(none)_'}\n" f"- **Family**: {family or '_(none)_'}\n" + f"- **Local store**: {path}" + f"{_egeria_section(writer, local_reason)}" ) -class LinkReportToDashboardSheetProcessor(AsyncBaseCommandProcessor): +async def _placement_chain(writer: DashboardSheetEgeriaWriter, sheet_name: str, + local_sheet: Optional[DashboardSheet]) -> SheetChain: + """The sheet's chain for a placement command. A sheet held only in the local store (made before its + commands wrote Egeria) is written to Egeria whole first, so the Egeria sheet is never a partial copy.""" + chain = await writer.find_chain(sheet_name) + if chain.container_guid: + return chain + if local_sheet is None: + raise ValueError(f"Dashboard Sheet '{sheet_name}' does not exist. Create it first with " + f"'Create Dashboard Sheet'.") + writer._note(f"Dashboard Sheet '{sheet_name}' was only in the local store; it was written to Egeria " + f"whole ({len(local_sheet.placements)} placement(s)) before this placement.") + return await writer.write_sheet(local_sheet) + + +class LinkReportToDashboardSheetProcessor(_DashboardSheetProcessorMixin, AsyncBaseCommandProcessor): """ - Processor for Link Report to Dashboard Sheet -- places a Report (a real - Egeria `Report` asset created via `Create Report`, carrying a Report Spec - reference plus its own default execution parameters) into a Dashboard - Sheet as an ordered Placement. The target Dashboard Sheet must already - exist (created via Create Dashboard Sheet). - - Hard cutover 2026-07-29: this used to place a bare Report Spec (FormatSet) - name directly -- switched to referencing a Report element by name instead, - since a Report Spec has no way to carry fixed/scoped parameters (see - egeria-workspaces-fs BACKLOG.md NEXT-14). `Report Name` is a Reference - Name-style attribute, so the base class's generic attribute-resolution - pipeline (step 5 of execute()) already resolves it against Egeria and - populates `.get("guid")` -- used here only for a best-effort "does this - Report actually exist yet" warning, not required for the placement - record itself (which still stores the plain name as `Placement.ref`, - resolved later by the consuming app, same as the old Report Spec-ref - scheme). + Processor for Link Report to Dashboard Sheet -- places a Report (an Egeria `Report` asset created via + `Create Report`) on a Dashboard Sheet as an ordered placement. In Egeria: a DisplayDataField with + placementKind "report", linked to the Report by the Dashboard's DataSetContent (queryId = the + placement's qualifiedName); ScopedBy to its perspectives; DataDescription to its drill-down spec. In the + local store: a Placement whose `ref` is the report's name. Re-running with the same Report Name + updates the placement in place. """ async def fetch_as_is(self) -> Optional[Dict[str, Any]]: @@ -154,6 +843,21 @@ async def fetch_as_is(self) -> Optional[Dict[str, Any]]: def supports_target_element_lookup(self) -> bool: return False + async def resolve_element_guid(self, name_or_guid: str, tech_type: Optional[str] = None) -> Optional[str]: + """`Report Name` is resolved first as the one Report with exactly that displayName (the writer's typed + lookup), then as before. Dr.Egeria's untyped lookup is refused by Egeria when another element type + shares the name (live 2026-11-09: 'Term Definition Completeness', 'Governance Classification + Coverage'), which failed this command at validation.""" + text = str(name_or_guid or "").strip() + if text and "(guid:" not in text and self.client is not None: + try: + guid = await DashboardSheetEgeriaWriter(self.client)._resolve_report(text) + except (AttributeError, PyegeriaConnectionException): + guid = None + if guid: + return guid + return await super().resolve_element_guid(name_or_guid, tech_type) + async def apply_changes(self) -> str: attributes = self.parsed_output["attributes"] sheet_name = attributes.get("Dashboard Sheet Name", {}).get("value") @@ -161,8 +865,6 @@ async def apply_changes(self) -> str: report_guid = attributes.get("Report Name", {}).get("guid") span = attributes.get("Placement Span", {}).get("value") or "1" emphasis = attributes.get("Placement Emphasis", {}).get("value") or "kpi" - # BACKLOG.md NEXT-19/NEXT-21 (egeria-workspaces-fs). "Placement Detail - # Spec" is a plain optional string, same pattern as report_name. perspectives = _parse_placement_perspectives(attributes) detail_spec = attributes.get("Placement Detail Spec", {}).get("value") or None @@ -171,33 +873,33 @@ async def apply_changes(self) -> str: if not report_name: raise ValueError("Report Name is required.") - if not report_guid: - self._add_warning( - f"Report '{report_name}' was not found in Egeria — the placement will be " - f"unresolved until a Report with that name exists (create one with 'Create Report')." - ) - path = _default_store_path() sheets = _load_store(path) sheet = sheets.get(sheet_name) - if not sheet: - raise ValueError( - f"Dashboard Sheet '{sheet_name}' does not exist. Create it first with 'Create Dashboard Sheet'." - ) + placement = Placement(ref=report_name, span=span, emphasis=emphasis, + perspectives=perspectives, detail_spec=detail_spec) - placement = Placement( - ref=report_name, span=span, emphasis=emphasis, - perspectives=perspectives, detail_spec=detail_spec, - ) - replaced = False - for i, p in enumerate(sheet.placements): - if p.ref == report_name: - sheet.placements[i] = placement - replaced = True - break - if not replaced: - sheet.placements.append(placement) + async def _work(writer: DashboardSheetEgeriaWriter): + chain = await _placement_chain(writer, sheet_name, sheet) + await writer.upsert_placement(chain, placement, report_guid=report_guid) + + writer, local_reason = await self._with_egeria(_work) + if local_reason and not report_guid: + self._add_warning( + f"Report '{report_name}' was not found in Egeria — the placement will be " + f"unresolved until a Report with that name exists (create one with 'Create Report')." + ) + if not sheet: + if local_reason: + raise ValueError(f"Dashboard Sheet '{sheet_name}' does not exist. Create it first with " + f"'Create Dashboard Sheet'.") + # Held in Egeria only (made elsewhere): start its local copy so the store stays a full fallback. + sheet = DashboardSheet(name=sheet_name, heading=sheet_name) + sheets[sheet_name] = sheet + sheet = sheets.get(sheet_name) + + replaced = _put_placement(sheet, placement) sheets.save_to_json(path) verb_word = "Updated placement of" if replaced else "Placed" logger.success(f"{verb_word} Report '{report_name}' in Dashboard Sheet '{sheet_name}'") @@ -211,18 +913,30 @@ async def apply_changes(self) -> str: f"\n\n## {self.command.verb} Report to Dashboard Sheet\n\n" f"{verb_word} **{report_name}** in Dashboard Sheet **{sheet_name}** " f"(span={span}, emphasis={emphasis}{extra_str})\n" + f"{_egeria_section(writer, local_reason)}" ) -class AddTextOnDashboardSheetProcessor(AsyncBaseCommandProcessor): +def _put_placement(sheet: DashboardSheet, placement: Placement) -> bool: + """Replace the placement with the same ref, or append it. True if replaced. A same-named placement of the + other kind (report vs text) is refused, as in Egeria.""" + for i, p in enumerate(sheet.placements): + if isinstance(p, dict): + p = Placement(**p) + if p.ref == placement.ref: + _refuse_kind_clash(sheet.name, placement, placement_kind(p)) + sheet.placements[i] = placement + return True + sheet.placements.append(placement) + return False + + +class AddTextOnDashboardSheetProcessor(_DashboardSheetProcessorMixin, AsyncBaseCommandProcessor): """ - Processor for Place Text on Dashboard Sheet -- places literal markdown - text (a section header, explanation, or caption) into a Dashboard Sheet - as an ordered Placement, alongside Report placements. Not an Egeria - element or relationship, and unlike Report placements, `Placement Name` - isn't a Reference Name-style attribute either -- there's nothing in - Egeria to resolve, it's purely the local replace-by-name key (same role - `Report Name` plays for a Report placement's `Placement.ref`). + Processor for Add Text on Dashboard Sheet -- places literal markdown text (a section header, + explanation or caption) on a Dashboard Sheet as an ordered placement, alongside report placements. In + Egeria: a DisplayDataField with placementKind "text" and markdownContent. `Placement Name` is the + placement's name (its displayName, and the local replace-by-name key). """ async def fetch_as_is(self) -> Optional[Dict[str, Any]]: @@ -238,10 +952,6 @@ async def apply_changes(self) -> str: content = attributes.get("MD Content", {}).get("value") span = attributes.get("Placement Span", {}).get("value") or "1" emphasis = attributes.get("Placement Emphasis", {}).get("value") or "kpi" - # BACKLOG.md NEXT-19 (egeria-workspaces-fs) -- a text placement (e.g. a - # section header) can be perspective-scoped too, not just a Report - # placement; no detail_spec here, a text block has no result to drill - # into. perspectives = _parse_placement_perspectives(attributes) if not sheet_name: @@ -254,24 +964,23 @@ async def apply_changes(self) -> str: path = _default_store_path() sheets = _load_store(path) sheet = sheets.get(sheet_name) - if not sheet: - raise ValueError( - f"Dashboard Sheet '{sheet_name}' does not exist. Create it first with 'Create Dashboard Sheet'." - ) + placement = Placement(ref=placement_name, span=span, emphasis=emphasis, content=content, + perspectives=perspectives) - placement = Placement( - ref=placement_name, span=span, emphasis=emphasis, content=content, - perspectives=perspectives, - ) - replaced = False - for i, p in enumerate(sheet.placements): - if p.ref == placement_name: - sheet.placements[i] = placement - replaced = True - break - if not replaced: - sheet.placements.append(placement) + async def _work(writer: DashboardSheetEgeriaWriter): + chain = await _placement_chain(writer, sheet_name, sheet) + await writer.upsert_placement(chain, placement) + + writer, local_reason = await self._with_egeria(_work) + if not sheet: + if local_reason: + raise ValueError(f"Dashboard Sheet '{sheet_name}' does not exist. Create it first with " + f"'Create Dashboard Sheet'.") + sheets[sheet_name] = DashboardSheet(name=sheet_name, heading=sheet_name) + sheet = sheets.get(sheet_name) + + replaced = _put_placement(sheet, placement) sheets.save_to_json(path) verb_word = "Updated" if replaced else "Placed" logger.success(f"{verb_word} text placement '{placement_name}' in Dashboard Sheet '{sheet_name}'") @@ -280,4 +989,14 @@ async def apply_changes(self) -> str: f"\n\n## {self.command.verb} Text on Dashboard Sheet\n\n" f"{verb_word} text placement **{placement_name}** in Dashboard Sheet **{sheet_name}** " f"(span={span}, emphasis={emphasis}{extra_str})\n" + f"{_egeria_section(writer, local_reason)}" ) + + +__all__ = [ + "AddTextOnDashboardSheetProcessor", "CreateDashboardSheetProcessor", "DashboardSheetEgeriaWriter", + "FieldInfo", "LinkReportToDashboardSheetProcessor", "LOCAL_ONLY_ENV", "PERSPECTIVE_QN_OVERRIDES", + "PERSPECTIVE_TRELLIS_NAMES", "SheetChain", "dashboard_qn", "field_placement_name", "local_only_reason", "perspective_qualified_name", + "placement_display_name", "placement_field_properties", "placement_kind", "placement_qn", "schema_type_qn", "sheet_container_qn", + "sheet_name_from_dashboard_qn", +] diff --git a/md_processing/v2/report.py b/md_processing/v2/report.py index f22613b6..f47fba4e 100644 --- a/md_processing/v2/report.py +++ b/md_processing/v2/report.py @@ -6,10 +6,11 @@ odpi/egeria-project.ai/types/2/0239-Reports) carrying a Report Spec reference plus optional default execution parameters (Output Format, Search String, and the rest of the same 22-attribute vocabulary -`View Report` already supports ad-hoc). Short-term design: everything -beyond the base Referenceable properties lands in `additionalProperties` --- no dedicated `ReportDefinition` subtype yet (see egeria-workspaces-fs -BACKLOG.md NEXT-14). `Link Report to Dashboard Sheet` then references a +`View Report` already supports ad-hoc). Egeria 6.3 (odpi/egeria#9432) gives +Report a typed `outputFormat`, one `reportParameters` JSON document and the +`ReportTypeInstance` link from its spec; all three are written. The older +`additionalProperties` keys are still written for one release, because +today's Portal reads them. `Link Report to Dashboard Sheet` then references a Report by its `Report Name` instead of a bare Report Spec name, giving a Dashboard Sheet placement a concrete, parameterized instance to run instead of an unparameterized template. @@ -35,11 +36,21 @@ from loguru import logger +from pyegeria.core._exceptions import PyegeriaNotFoundException + from md_processing.v2.processors import AsyncBaseCommandProcessor from md_processing.md_processing_utils.common_md_utils import ( set_create_body, set_element_prop_body, update_element_dictionary, ) +# Report specs are held in Egeria under two qualified-name prefixes (pipeline note v5.5 §7a hazard): +# `ReportSpec::` from Create Report Spec, and `ReportType::` from the older report-type content. +REPORT_SPEC_QN_PREFIXES = ("ReportSpec::", "ReportType::") + +# `Report Spec` / `Output Format` have typed homes; everything else in _REPORT_PARAM_ATTRS goes into the +# one reportParameters document. +_TYPED_REPORT_KEYS = {"reportSpec", "outputFormat"} + # The 22 report-execution-parameter attributes (same set View Report exposes # ad-hoc) -- short-term, all of these land in additionalProperties rather # than typed Report fields. camelCase keys distinguish them from anything a @@ -110,6 +121,47 @@ def _snake_to_camel(snake: str) -> str: return parts[0] + "".join(p[:1].upper() + p[1:] for p in parts[1:] if p) +def _camel_to_snake(camel: str) -> str: + """camelCase -> snake_case (`searchString` -> `search_string`, `asOfTime` -> `as_of_time`).""" + out = [] + for ch in camel: + if ch.isupper(): + out.append("_" + ch.lower()) + else: + out.append(ch) + return "".join(out).lstrip("_") + + +def report_parameters_document(attributes: Dict[str, Any]) -> Dict[str, Any]: + """The one parameter document a Report carries in Egeria 6.3's `reportParameters` (pipeline note §8d). + + Today's `Create Report` holds parameters three ways; they collapse into one JSON object of snake_case + parameter names, which is what a spec's declared `required_params`/`optional_params` use: + 1. the common find attributes (`Search String`, `Page Size`, ...), authoring sugar; + 2. the `Report Parameters` map, as typed; + 3. the `Analytic Parameters` map. + Later sources win on a clash. Attribute defaults the parser fills in (`Graph Query Depth`, ...) are not + written: only what the author wrote is pinned. Values that are JSON (`25`, `true`, `[...]`) are decoded, so `Page Size 25` + is the number 25, not the string "25". `Report Spec` and `Output Format` are not parameters: they have + their own typed homes (`ReportTypeInstance`, `outputFormat`). + """ + doc: Dict[str, Any] = {} + for canonical_name, key in _REPORT_PARAM_ATTRS.items(): + if key in _TYPED_REPORT_KEYS: + continue + attr = attributes.get(canonical_name, {}) + if attr.get("is_default"): + continue # a spec default the author did not write: the report spec decides, not a pinned value + value = attr.get("value") + if value is not None and value != "": + doc[_camel_to_snake(key)] = _coerce_analytic_value(value) + for attr in ("Report Parameters", "Analytic Parameters"): + value = attributes.get(attr, {}).get("value") + if isinstance(value, dict): + doc.update({str(k): _coerce_analytic_value(v) for k, v in value.items() if v is not None}) + return doc + + def _report_additional_properties(attributes: Dict[str, Any]) -> Dict[str, str]: """Merge the user's own 'Additional Properties' dict (if any) with the report-execution params, stringified (additionalProperties is @@ -169,27 +221,135 @@ def _report_additional_properties(attributes: Dict[str, Any]) -> Dict[str, str]: return merged +def _as_element(result: Any) -> Optional[Dict[str, Any]]: + """An element dict from a lookup, or None for any not-found answer (a string, an empty list, None).""" + if isinstance(result, dict) and result.get("elementHeader"): + return result + if isinstance(result, dict) and isinstance(result.get("element"), dict): + return result["element"] + return None + + +async def find_element_by_qualified_name(client: Any, qualified_name: str) -> Optional[Dict[str, Any]]: + """One bounded exact lookup by qualifiedName (classification-explorer `by-unique-name`). None if absent. + + Never a type-wide query: the unique-name endpoint returns at most one element. + """ + if not qualified_name: + return None + try: + result = await client.classification_manager._async_get_element_by_unique_name(qualified_name) + except PyegeriaNotFoundException: + return None + return _as_element(result) + + +async def find_report_spec_element(client: Any, spec_name: str) -> Optional[Dict[str, Any]]: + """The Egeria element for a report spec named `spec_name`, looked up under both prefixes. + + Tries the name as a qualified name first (a caller may give `ReportSpec::X` or `ReportType::X`), then + `ReportSpec::`, then `ReportType::` (§7a hazard: both exist live). None if no element holds + the spec -- a spec held only in pyegeria has none. + """ + if not spec_name: + return None + candidates = [spec_name] if spec_name.startswith(REPORT_SPEC_QN_PREFIXES) else [] + candidates += [f"{prefix}{spec_name}" for prefix in REPORT_SPEC_QN_PREFIXES] + for qn in candidates: + element = await find_element_by_qualified_name(client, qn) + if element: + return element + return None + + +def _props_differ(desired: Dict[str, Any], current: Dict[str, Any]) -> bool: + """True if any non-None desired property differs from the element's current value.""" + for key, value in desired.items(): + if key in ("class", "typeName") or value is None: + continue + if current.get(key) != value: + return True + return False + + +async def upsert_dashboard_asset(client: Any, qualified_name: str, props: Dict[str, Any], + existing: Optional[Dict[str, Any]], *, merge_update: bool = True, + create_body: Optional[Dict[str, Any]] = None, + filter_update: Any = None) -> tuple: + """Create or update an Egeria 6.3 `Dashboard` asset. Returns (guid, verb_word, body_sent). + + The one implementation of the Dashboard asset write, used by `Create Dashboard` (DashboardProcessor) + and by `Create Dashboard Sheet` / dashboard migration (dashboard_sheet.py). An existing Dashboard whose + properties already match is left alone (verb_word "Unchanged", nothing sent), so re-running a document + changes nothing. + """ + if existing: + guid = existing["elementHeader"]["guid"] + if not _props_differ(props, existing.get("properties") or {}): + return guid, "Unchanged", None + update_props = filter_update(props, merge_update) if filter_update else props + update_body = {"class": "UpdateElementRequestBody", "properties": update_props, + "mergeUpdate": merge_update} + await client._async_update_asset(guid, update_body) + return guid, "Updated", update_body + body = dict(create_body or {"class": "NewElementRequestBody"}) + body["properties"] = props + raw_guid = await client._async_create_asset(["DashboardProperties"], body) + return raw_guid, "Created", body + + +async def sync_report_type_instance(client: Any, report_guid: str, spec_name: str) -> Optional[str]: + """Link the Report to its spec's element by `ReportTypeInstance`; return a note when that cannot be done. + + - Spec element found (under `ReportSpec::` or `ReportType::`): link it if not already linked, and detach + links to any other report type (a report runs one spec). + - No element (a spec held only in pyegeria): nothing is written, and the note says so -- the report + still runs from pyegeria's own spec registry. + """ + spec_element = await find_report_spec_element(client, spec_name) + if not spec_element: + return (f"Report Spec '{spec_name}' has no Egeria element (looked for " + f"{' and '.join(p + spec_name for p in REPORT_SPEC_QN_PREFIXES)}): no ReportTypeInstance was " + f"written. The report still runs from pyegeria's own spec.") + spec_guid = spec_element["elementHeader"]["guid"] + current = await client.classification_manager._async_get_related_elements( + report_guid, "ReportTypeInstance", start_at_end=2, page_size=25, graph_query_depth=0) + linked = [e["elementHeader"]["guid"] for e in (current if isinstance(current, list) else []) + if isinstance(e, dict) and e.get("elementHeader")] + for other in linked: + if other != spec_guid: + await client.data_designer._async_detach_report_type_instance(other, report_guid) + if spec_guid not in linked: + await client.data_designer._async_link_report_type_instance(spec_guid, report_guid) + return None + + class ReportProcessor(AsyncBaseCommandProcessor): - """Processor for Create Report (and its Update transition).""" + """Processor for Create Report (and its Update transition). + + Egeria 6.3 (odpi/egeria#9432) writes, beside the additionalProperties keys today's Portal reads (kept + for one release): + - `reportParameters`: ONE JSON document (report_parameters_document), not three parameter homes; + - the typed `outputFormat`; + - `ReportTypeInstance` from the named spec's element, found under `ReportSpec::` or `ReportType::`; + a spec with no element gets a note saying no link was written, not silence. + """ async def apply_changes(self) -> str: attributes = self.parsed_output["attributes"] qualified_name = self.parsed_output.get("qualified_name") or self.derive_qualified_name(attributes) display_name = attributes.get("Display Name", {}).get("value") or qualified_name - if not attributes.get("Report Spec", {}).get("value"): + spec_name = attributes.get("Report Spec", {}).get("value") + if not spec_name: raise ValueError("Report Spec is required.") props = set_element_prop_body("Report", qualified_name, attributes) props["additionalProperties"] = _report_additional_properties(attributes) - # Egeria 6.3 (odpi/egeria#9432) gives Report typed outputFormat and reportParameters (a JSON - # string). Written as well as the additionalProperties keys above, which the Portal's - # local dashboards still read. props["outputFormat"] = attributes.get("Output Format", {}).get("value") - report_params = attributes.get("Report Parameters", {}).get("value") - if isinstance(report_params, dict) and report_params: - props["reportParameters"] = json.dumps( - {str(k): v for k, v in report_params.items() if v is not None}) + parameters = report_parameters_document(attributes) + if parameters: + props["reportParameters"] = json.dumps(parameters, sort_keys=True) props["deployedImplementationType"] = attributes.get("Deployed Implementation Type", {}).get("value") props["resourceName"] = attributes.get("Resource Name", {}).get("value") @@ -211,8 +371,13 @@ async def apply_changes(self) -> str: self.parsed_output["guid"] = guid update_element_dictionary(qualified_name, {"guid": guid, "display_name": display_name}) + note = await sync_report_type_instance(self.client, guid, spec_name) + if note: + self._add_warning(note) + logger.success(f"{verb_word} Report '{display_name}' with GUID {guid}") - return await self.render_result_markdown(guid) + result = await self.render_result_markdown(guid) + return f"{result}\n\n> {note}\n" if note else result class DashboardProcessor(AsyncBaseCommandProcessor): @@ -220,8 +385,8 @@ class DashboardProcessor(AsyncBaseCommandProcessor): (DataSet subtype, sibling of Report; odpi/egeria#9432). Same AssetMaker path as ReportProcessor. Its sheets and placements are DisplayDataContainers / DisplayDataFields (Schema Maker family); - Egeria has no separate DashboardPlacement type. The local `Create Dashboard Sheet` records - (dashboard_sheet.py) are unchanged by this command. + Egeria has no separate DashboardPlacement type. The asset write itself is `upsert_dashboard_asset`, + which `Create Dashboard Sheet` (dashboard_sheet.py) also uses for its Dashboard. """ async def apply_changes(self) -> str: @@ -237,24 +402,15 @@ async def apply_changes(self) -> str: props["refreshTimeInterval"] = attributes.get("Refresh Time Interval", {}).get("value") props["layoutStyle"] = attributes.get("Layout Style", {}).get("value") - if self.as_is_element: - guid = self.as_is_element["elementHeader"]["guid"] - merge_update = attributes.get("Merge Update", {}).get("value", True) - update_body = { - "class": "UpdateElementRequestBody", - "properties": self.filter_update_properties(props, merge_update), - "mergeUpdate": merge_update, - } - self.last_body = update_body - await self.client._async_update_asset(guid, update_body) - verb_word = "Updated" - else: - create_body = set_create_body("Dashboard", attributes) - create_body["properties"] = props - self.last_body = create_body - raw_guid = await self.client._async_create_asset(["DashboardProperties"], create_body) - guid = self.extract_guid_or_raise(raw_guid, "Create Dashboard") - verb_word = "Created" + guid, verb_word, body = await upsert_dashboard_asset( + self.client, qualified_name, props, self.as_is_element, + merge_update=attributes.get("Merge Update", {}).get("value", True), + create_body=set_create_body("Dashboard", attributes), + filter_update=self.filter_update_properties) + if body is not None: + self.last_body = body + if verb_word == "Created": + guid = self.extract_guid_or_raise(guid, "Create Dashboard") self.parsed_output["guid"] = guid update_element_dictionary(qualified_name, {"guid": guid, "display_name": display_name}) diff --git a/tests/micro-tests/dashboard_fake_egeria.py b/tests/micro-tests/dashboard_fake_egeria.py new file mode 100644 index 00000000..2d7ab7d1 --- /dev/null +++ b/tests/micro-tests/dashboard_fake_egeria.py @@ -0,0 +1,300 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the ODPi Egeria project. +""" +An in-memory Egeria for the dashboard-sheet tests: entities and relationships, answering the handful of +client calls the dashboard-sheet writer and reader make, with the response shapes checked live on +2026-11-09 (related elements come back as {elementHeader, relatedBy: {relationshipHeader, +relationshipProperties}, properties}). + +Every subclient name (schema_maker, asset_maker, classification_manager, ...) is this same object, as +EgeriaTech proxies them. Every write is recorded in `writes` as (method, *args) so tests can assert "the +second run wrote nothing" and "no Report was deleted". An unknown method raises AttributeError, so a call +the fake does not model fails loudly instead of silently succeeding. + +Not a test module (no test_ prefix); tests load it with load_fake(). +""" +from __future__ import annotations + +import importlib.util +import pathlib +import uuid +from typing import Any, Dict, List, Optional + +from pyegeria.omvs.asset_maker import resolve_placement_reports + +SUPERTYPES = { + "Dashboard": ["DataSet", "Asset", "Referenceable"], + "Report": ["DataSet", "Asset", "Referenceable"], + "ReportSpec": ["Collection", "Referenceable"], + "ReportType": ["Referenceable"], + "Perspective": ["Referenceable"], + "DisplayDataSchemaType": ["RootSchemaType", "ComplexSchemaType", "SchemaType", "Referenceable"], + "DisplayDataContainer": ["SchemaAttribute", "Referenceable"], + "DisplayDataField": ["SchemaAttribute", "Referenceable"], +} + +SUBCLIENTS = ("schema_maker", "asset_maker", "classification_manager", "collection_manager", "data_designer", + "collections", "class_mgr", "metadata_expert") + + +class FakeEgeria: + def __init__(self): + self.entities: Dict[str, Dict[str, Any]] = {} + self.relationships: List[Dict[str, Any]] = [] + self.writes: List[tuple] = [] + self._n = 0 + + def __getattr__(self, name): + if name in SUBCLIENTS: + return self + raise AttributeError(name) + + # ---------------------------------------------------------------- seeding / inspection + + def _new_guid(self) -> str: + self._n += 1 + return str(uuid.UUID(int=self._n)) + + def add_entity(self, type_name: str, qualified_name: str, display_name: Optional[str] = None, + **props) -> str: + guid = self._new_guid() + self.entities[guid] = {"type": type_name, "props": {"qualifiedName": qualified_name, + "displayName": display_name or qualified_name, + **props}} + return guid + + def by_qn(self, qualified_name: str) -> Optional[str]: + return next((g for g, e in self.entities.items() if e["props"].get("qualifiedName") == qualified_name), None) + + def of_type(self, type_name: str) -> List[str]: + return [g for g, e in self.entities.items() if e["type"] == type_name] + + def rels(self, type_name: str) -> List[Dict[str, Any]]: + return [r for r in self.relationships if r["type"] == type_name] + + def write_names(self) -> List[str]: + return [w[0] for w in self.writes] + + # ---------------------------------------------------------------- element shapes + + def _header(self, guid: str) -> Dict[str, Any]: + e = self.entities[guid] + return {"class": "ElementHeader", "guid": guid, + "type": {"typeName": e["type"], "superTypeNames": SUPERTYPES.get(e["type"], [])}} + + def element(self, guid: str) -> Dict[str, Any]: + e = self.entities[guid] + return {"class": "OpenMetadataRootElement", "elementHeader": self._header(guid), + "properties": {"typeName": e["type"], **{k: v for k, v in e["props"].items() if v is not None}}} + + def _related_shape(self, guid: str, rel: Dict[str, Any]) -> Dict[str, Any]: + out = self.element(guid) + out["relatedBy"] = {"relationshipHeader": {"guid": rel["guid"], "type": {"typeName": rel["type"]}}, + "relationshipProperties": {"typeName": rel["type"], **rel["props"]}} + return out + + # ---------------------------------------------------------------- reads + + async def _async_get_element_by_unique_name(self, name, property_name=None, **kwargs): + guid = self.by_qn(name) + return self.element(guid) if guid else "No elements found" + + async def _async_get_element_by_guid_(self, guid, **kwargs): + return self.element(guid) if guid in self.entities else "No elements found" + + async def __async_get_guid__(self, guid=None, display_name=None, property_name="qualifiedName", + qualified_name=None, tech_type=None, **kwargs): + if guid: + return guid + hits = [] + for g, e in self.entities.items(): + if tech_type and tech_type not in (e["type"], *SUPERTYPES.get(e["type"], [])): + continue + if e["props"].get("qualifiedName") == qualified_name or e["props"].get("displayName") == display_name: + hits.append(g) + if len(hits) > 1: + from pyegeria.core._exceptions import PyegeriaException + raise PyegeriaException(f"Multiple elements found for '{display_name}'") + return hits[0] if hits else "No elements found" + + async def _async_get_related_elements(self, element_guid, relationship_type=None, start_at_end=1, + start_from=0, page_size=0, **kwargs): + out = [] + for rel in self.relationships: + if relationship_type and rel["type"] != relationship_type: + continue + if start_at_end == 1 and rel["end1"] == element_guid: + out.append(self._related_shape(rel["end2"], rel)) + elif start_at_end == 2 and rel["end2"] == element_guid: + out.append(self._related_shape(rel["end1"], rel)) + page = out[start_from:start_from + page_size] if page_size else out[start_from:] + return page if page else "No elements found" + + async def _async_find_elements_by_property_value(self, property_value, property_names, metadata_element_type=None, + starts_with=True, start_from=0, page_size=0, **kwargs): + hits = [] + for g, e in self.entities.items(): + if metadata_element_type and e["type"] != metadata_element_type: + continue + for prop in property_names: + value = str(e["props"].get(prop) or "") + # live Egeria: starts_with=False is a contains match, not an exact one + if (value.startswith(property_value) if starts_with else property_value in value): + hits.append(self.element(g)) + break + page = hits[start_from:start_from + page_size] if page_size else hits[start_from:] + return page if page else "No elements found" + + async def _async_get_elements_by_property_value(self, property_value, property_names, metadata_element_type=None, + start_from=0, page_size=0, **kwargs): + """Exact match (classification-explorer by-exact-property-value).""" + hits = [self.element(g) for g, e in self.entities.items() + if (not metadata_element_type or e["type"] == metadata_element_type) + and any(e["props"].get(p) == property_value for p in property_names)] + page = hits[start_from:start_from + page_size] if page_size else hits[start_from:] + return page if page else "No elements found" + + async def _async_get_placement_reports(self, dashboard_guid, placement_qualified_names, **kwargs): + element = self.element(dashboard_guid) + links = [] + for rel in self.rels("DataSetContent"): + if rel["end1"] == dashboard_guid: + links.append({"relationshipHeader": {"guid": rel["guid"]}, + "relationshipProperties": rel["props"], + "relatedElement": self.element(rel["end2"])}) + if links: + element["dataSetContent"] = links + return resolve_placement_reports(element, placement_qualified_names) + + # ---------------------------------------------------------------- writes + + def _link(self, rel_type: str, end1: str, end2: str, props: Optional[Dict[str, Any]] = None) -> str: + assert end1 in self.entities and end2 in self.entities, (rel_type, end1, end2) + guid = self._new_guid() + clean = {k: v for k, v in (props or {}).items() if k not in ("class",) and v is not None} + self.relationships.append({"guid": guid, "type": rel_type, "end1": end1, "end2": end2, "props": clean}) + return guid + + def _unlink(self, rel_type: str, end1: str, end2: str) -> None: + self.relationships = [r for r in self.relationships + if not (r["type"] == rel_type and r["end1"] == end1 and r["end2"] == end2)] + + def _create(self, body: Dict[str, Any]) -> str: + props = dict(body["properties"]) + type_name = props.pop("typeName") + props.pop("class", None) + assert self.by_qn(props["qualifiedName"]) is None, f"duplicate qualifiedName {props['qualifiedName']}" + guid = self._new_guid() + self.entities[guid] = {"type": type_name, "props": props, "anchor": body.get("anchorGUID")} + return guid + + def _update(self, guid: str, body: Dict[str, Any]) -> None: + props = {k: v for k, v in body["properties"].items() if k not in ("class", "typeName")} + if body.get("mergeUpdate", True): + self.entities[guid]["props"].update({k: v for k, v in props.items() if v is not None}) + else: + self.entities[guid]["props"] = props + + def _delete(self, guid: str) -> None: + del self.entities[guid] + self.relationships = [r for r in self.relationships if guid not in (r["end1"], r["end2"])] + + async def _async_create_asset(self, prop_classes, body): + self.writes.append(("create_asset", body["properties"]["qualifiedName"])) + return self._create(body) + + async def _async_update_asset(self, guid, body): + self.writes.append(("update_asset", guid)) + self._update(guid, body) + + async def _async_delete_asset(self, guid, body=None): + self.writes.append(("delete_asset", self.entities[guid]["type"], guid)) + self._delete(guid) + + async def _async_create_schema_type(self, body): + self.writes.append(("create_schema_type", body["properties"]["qualifiedName"])) + return self._create(body) + + async def _async_create_schema_attribute(self, body): + self.writes.append(("create_schema_attribute", body["properties"]["qualifiedName"])) + return self._create(body) + + async def _async_update_schema_attribute(self, guid, body): + self.writes.append(("update_schema_attribute", guid)) + self._update(guid, body) + + async def _async_delete_schema_attribute(self, guid, body=None, cascade_delete=False): + self.writes.append(("delete_schema_attribute", self.entities[guid]["type"], guid)) + self._delete(guid) + + async def _async_delete_schema_type(self, guid, body=None, cascade_delete=False): + self.writes.append(("delete_schema_type", self.entities[guid]["type"], guid)) + self._delete(guid) + + async def _async_link_schema(self, element_guid, schema_type_guid, body=None): + self.writes.append(("link_schema", element_guid, schema_type_guid)) + return self._link("Schema", element_guid, schema_type_guid) + + async def _async_link_attribute_for_schema(self, schema_type_guid, attribute_guid, body=None): + self.writes.append(("link_attribute_for_schema", schema_type_guid, attribute_guid)) + return self._link("AttributeForSchema", schema_type_guid, attribute_guid, (body or {}).get("properties")) + + async def _async_link_nested_schema_attribute(self, parent_guid, child_guid, body=None): + self.writes.append(("link_nested_schema_attribute", parent_guid, child_guid)) + return self._link("NestedSchemaAttribute", parent_guid, child_guid, (body or {}).get("properties")) + + async def _async_link_placement_report(self, dashboard_guid, report_guid, placement_qualified_name, body=None): + self.writes.append(("link_placement_report", dashboard_guid, report_guid, placement_qualified_name)) + return self._link("DataSetContent", dashboard_guid, report_guid, + {"queryId": placement_qualified_name, "queryType": "placement"}) + + async def _async_detach_placement_report(self, dashboard_guid, placement_qualified_name, body=None): + self.writes.append(("detach_placement_report", dashboard_guid, placement_qualified_name)) + before = len(self.relationships) + self.relationships = [r for r in self.relationships + if not (r["type"] == "DataSetContent" and r["end1"] == dashboard_guid + and r["props"].get("queryId") == placement_qualified_name)] + return before - len(self.relationships) + + async def _async_add_scope_to_element(self, scoped_by_guid, element_guid, body=None): + self.writes.append(("add_scope", scoped_by_guid, element_guid)) + return self._link("ScopedBy", scoped_by_guid, element_guid) + + async def _async_clear_scope_from_element(self, scoped_by_guid, element_guid, body=None, cascade_delete=False): + self.writes.append(("clear_scope", scoped_by_guid, element_guid)) + self._unlink("ScopedBy", scoped_by_guid, element_guid) + + async def _async_attach_data_description(self, element_guid, collection_guid, body=None): + self.writes.append(("attach_data_description", element_guid, collection_guid)) + return self._link("DataDescription", element_guid, collection_guid) + + async def _async_detach_data_description(self, element_guid, collection_guid, body=None): + self.writes.append(("detach_data_description", element_guid, collection_guid)) + self._unlink("DataDescription", element_guid, collection_guid) + + async def _async_link_report_type_instance(self, report_type_guid, report_guid, body=None): + self.writes.append(("link_report_type_instance", report_type_guid, report_guid)) + return self._link("ReportTypeInstance", report_type_guid, report_guid) + + async def _async_detach_report_type_instance(self, report_type_guid, report_guid, body=None, + cascade_delete=False): + self.writes.append(("detach_report_type_instance", report_type_guid, report_guid)) + self._unlink("ReportTypeInstance", report_type_guid, report_guid) + + +# The 12 Perspective:: elements Trellis creates (checked live, read only, 2026-11-09). +TRELLIS_PERSPECTIVES = ["Financial", "Privacy", "Governance", "App/AI Builder", "Data Expert", "Architecture", + "Owner", "Community", "Consumer", "Administration", "Security", "Steward"] + + +def seed_perspectives(fake: FakeEgeria) -> None: + for name in TRELLIS_PERSPECTIVES: + fake.add_entity("Perspective", f"Perspective::{name}", f"{name.upper()}-PERSPECTIVE") + + +def load_fake(): + """Import this module by path (micro-tests is not an importable package name).""" + spec = importlib.util.spec_from_file_location("dashboard_fake_egeria", pathlib.Path(__file__)) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module diff --git a/tests/micro-tests/test_dashboard_sheets_in_egeria.py b/tests/micro-tests/test_dashboard_sheets_in_egeria.py new file mode 100644 index 00000000..9ba99323 --- /dev/null +++ b/tests/micro-tests/test_dashboard_sheets_in_egeria.py @@ -0,0 +1,477 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the ODPi Egeria project. +""" +Dashboard sheets held in Egeria (BRIEF RS-DASH PR-1, pipeline note v5.5 §8d / §10.6(c)). + +The three sheet commands keep their names and syntax and now write the Egeria 6.3 chain: +Dashboard -Schema-> DisplayDataSchemaType -AttributeForSchema-> DisplayDataContainer +-NestedSchemaAttribute(position)-> DisplayDataField per placement, plus DataSetContent (Dashboard -> Report, +queryId = the placement's qualifiedName), ScopedBy (Perspective -> placement) and DataDescription +(placement -> ReportSpec). DB-1: the local JSON store is written too. + +Every command goes through the real setup_dispatcher() / V2Dispatcher.dispatch() with an in-memory fake +Egeria (dashboard_fake_egeria.py), so command resolution, parsing and processor routing are the +production ones. No live server. +""" +import json +from typing import Any, Dict + +import pytest + +from md_processing.dr_egeria import setup_dispatcher +from md_processing.md_processing_utils.common_md_utils import clear_element_dictionary +from md_processing.v2.dashboard_sheet import ( + DashboardSheetEgeriaWriter, LOCAL_ONLY_ENV, perspective_qualified_name, +) +from md_processing.v2.extraction import DrECommand +from pyegeria.view._output_dashboard_sheet_models import DashboardSheetDict + +import importlib.util as _ilu +import pathlib as _pl + +_spec = _ilu.spec_from_file_location("dashboard_fake_egeria", _pl.Path(__file__).with_name("dashboard_fake_egeria.py")) +fake_egeria = _ilu.module_from_spec(_spec) +_spec.loader.exec_module(fake_egeria) + +SHEET = "glossary-health" + + +@pytest.fixture(autouse=True) +def _store(tmp_path, monkeypatch): + path = tmp_path / "dashboard_sheets.json" + monkeypatch.setenv("PYEGERIA_DASHBOARD_SHEETS_STORE", str(path)) + monkeypatch.delenv(LOCAL_ONLY_ENV, raising=False) + clear_element_dictionary() + yield path + clear_element_dictionary() + + +@pytest.fixture +def egeria(): + fake = fake_egeria.FakeEgeria() + fake_egeria.seed_perspectives(fake) + fake.add_entity("Report", "DeployedReport::Coco Terms Total", "Coco Terms Total") + fake.add_entity("Report", "DeployedReport::Coco Term Counts", "Coco Term Counts") + fake.add_entity("ReportSpec", "ReportSpec::Glossary-Term-Counts", "Glossary-Term-Counts") + return fake + + +def _command(verb: str, object_type: str, attributes: Dict[str, str]) -> DrECommand: + raw = f"## {verb} {object_type}\n" + "".join(f"### {k}\n{v}\n\n" for k, v in attributes.items()) + return DrECommand(verb=verb, object_type=object_type, attributes=attributes, raw_block=raw) + + +async def _run(client, verb, object_type, attributes): + dispatcher = setup_dispatcher(client) + context: Dict[str, Any] = {"directive": "process"} + result = await dispatcher.dispatch(_command(verb, object_type, attributes), context) + assert result["status"] == "success", result + return result + + +CREATE = {"Display Name": SHEET, "Dashboard Sheet Heading": "Glossary Health", + "Dashboard Sheet Description": "How complete and how used the glossaries are.", + "Dashboard Sheet Family": "Glossary Manager"} +TEXT = {"Dashboard Sheet Name": SHEET, "Placement Name": "Coverage header", + "MD Content": "**Coverage** - counts and definition completeness per glossary.", + "Placement Span": "full", "Placement Emphasis": "panel"} +LINK_1 = {"Dashboard Sheet Name": SHEET, "Report Name": "Coco Terms Total", "Placement Span": "1", + "Placement Emphasis": "kpi", "Placement Perspectives": "Steward, owner", + "Placement Detail Spec": "Glossary-Term-Counts"} +LINK_2 = {"Dashboard Sheet Name": SHEET, "Report Name": "Coco Term Counts", "Placement Span": "2", + "Placement Emphasis": "panel", "Placement Perspectives": "steward", + "Placement Detail Spec": "Glossary-With-Terms"} + + +async def _document(client): + await _run(client, "Create", "Dashboard Sheet", CREATE) + await _run(client, "Add", "Text on Dashboard Sheet", TEXT) + await _run(client, "Link", "Report to Dashboard Sheet", LINK_1) + return await _run(client, "Link", "Report to Dashboard Sheet", LINK_2) + + +def _fields(fake): + """(position, qualifiedName, props) for each placement, in position order.""" + out = [] + for rel in fake.rels("NestedSchemaAttribute"): + out.append((rel["props"]["position"], fake.entities[rel["end2"]]["props"])) + return sorted(out, key=lambda x: x[0]) + + +# ---------------------------------------------------------------------------- create + +@pytest.mark.asyncio +async def test_create_sheet_writes_dashboard_schema_and_container(egeria, _store): + result = await _run(egeria, "Create", "Dashboard Sheet", CREATE) + + dash = egeria.by_qn("Dashboard::glossary-health") + st = egeria.by_qn("DashboardSchema::glossary-health") + container = egeria.by_qn("DashboardSheet::glossary-health") + assert egeria.entities[dash]["type"] == "Dashboard" + assert egeria.entities[dash]["props"]["displayName"] == "Glossary Health" + assert egeria.entities[dash]["props"]["description"] == "How complete and how used the glossaries are." + assert egeria.entities[dash]["props"]["additionalProperties"] == {"family": "Glossary Manager"} + assert egeria.entities[st]["type"] == "DisplayDataSchemaType" + assert egeria.entities[container]["type"] == "DisplayDataContainer" + assert [(r["end1"], r["end2"]) for r in egeria.rels("Schema")] == [(dash, st)] + afs, = egeria.rels("AttributeForSchema") + assert (afs["end1"], afs["end2"], afs["props"]["position"]) == (st, container, 1) + # schema elements are anchored to the Dashboard + assert egeria.entities[st]["anchor"] == dash and egeria.entities[container]["anchor"] == dash + # DB-1: the local store is written too + sheets = DashboardSheetDict.load_from_json(str(_store)) + assert sheets[SHEET].heading == "Glossary Health" + assert "Egeria**: written" in result["output"] + + +@pytest.mark.asyncio +async def test_full_document_writes_the_10_6_chain(egeria): + result = await _document(egeria) + + fields = _fields(egeria) + assert [(pos, p["qualifiedName"]) for pos, p in fields] == [ + (1, "DashboardPlacement::glossary-health::1::Coverage header"), + (2, "DashboardPlacement::glossary-health::2::Coco Terms Total"), + (3, "DashboardPlacement::glossary-health::3::Coco Term Counts"), + ] + text, kpi, panel = (p for _, p in fields) + assert (text["placementKind"], text["span"], text["presentationStyle"]) == ("text", "full", "panel") + assert text["markdownContent"].startswith("**Coverage**") + assert (kpi["placementKind"], kpi["span"], kpi["presentationStyle"]) == ("report", "1", "kpi") + assert kpi.get("markdownContent") is None + assert kpi["additionalProperties"] == {"placementName": "Coco Terms Total", "perspectives": "Steward,owner", + "detailSpec": "Glossary-Term-Counts"} + # not the Report's own displayName: Dr.Egeria's untyped `Report Name` lookup must stay unambiguous + assert kpi["displayName"] == "glossary-health / Coco Terms Total" + + # DataSetContent: Dashboard -> Report, queryId = the placement's qualifiedName, for REPORT placements only + dash = egeria.by_qn("Dashboard::glossary-health") + dsc = {(r["end1"], egeria.entities[r["end2"]]["props"]["displayName"], r["props"]["queryId"], r["props"]["queryType"]) + for r in egeria.rels("DataSetContent")} + assert dsc == {(dash, "Coco Terms Total", kpi["qualifiedName"], "placement"), + (dash, "Coco Term Counts", panel["qualifiedName"], "placement")} + + # ScopedBy: Perspective -> placement; "owner" maps to the Trellis element Perspective::Owner (DB-2) + kpi_guid = egeria.by_qn(kpi["qualifiedName"]) + scopes = sorted(egeria.entities[r["end1"]]["props"]["qualifiedName"] + for r in egeria.rels("ScopedBy") if r["end2"] == kpi_guid) + assert scopes == ["Perspective::Owner", "Perspective::Steward"] + + # DataDescription: placement -> the ReportSpec element; a spec with no element is a note, not silence + dd = [(r["end1"], egeria.entities[r["end2"]]["props"]["qualifiedName"]) for r in egeria.rels("DataDescription")] + assert dd == [(kpi_guid, "ReportSpec::Glossary-Term-Counts")] + assert "Glossary-With-Terms" in result["output"] and "no DataDescription link" in result["output"] + + # membership is not anchoring: nothing created a Report or a Perspective + assert len(egeria.of_type("Report")) == 2 and len(egeria.of_type("Perspective")) == 12 + + +@pytest.mark.asyncio +async def test_rerunning_the_document_changes_nothing(egeria, _store): + await _document(egeria) + writes_after_first = list(egeria.writes) + store_after_first = _store.read_text() + + result = await _document(egeria) + + assert egeria.writes == writes_after_first, egeria.writes[len(writes_after_first):] + assert _store.read_text() == store_after_first + assert "no change" in result["output"] + + +@pytest.mark.asyncio +async def test_update_changes_only_what_changed(egeria): + await _document(egeria) + before = len(egeria.writes) + + await _run(egeria, "Link", "Report to Dashboard Sheet", {**LINK_2, "Placement Span": "full"}) + await _run(egeria, "Create", "Dashboard Sheet", {**CREATE, "Dashboard Sheet Heading": "Glossary Health v2"}) + + new = egeria.writes[before:] + assert [w[0] for w in new] == ["update_schema_attribute", "update_asset"] + panel = egeria.entities[egeria.by_qn("DashboardPlacement::glossary-health::3::Coco Term Counts")]["props"] + assert panel["span"] == "full" + assert egeria.entities[egeria.by_qn("Dashboard::glossary-health")]["props"]["displayName"] == "Glossary Health v2" + + +@pytest.mark.asyncio +async def test_update_clears_removed_perspectives(egeria): + await _document(egeria) + await _run(egeria, "Link", "Report to Dashboard Sheet", {**LINK_1, "Placement Perspectives": "Steward"}) + kpi_qn = "DashboardPlacement::glossary-health::2::Coco Terms Total" + kpi_guid = egeria.by_qn(kpi_qn) + scopes = [egeria.entities[r["end1"]]["props"]["qualifiedName"] for r in egeria.rels("ScopedBy") if r["end2"] == kpi_guid] + assert scopes == ["Perspective::Steward"] + assert egeria.entities[kpi_guid]["props"]["additionalProperties"]["perspectives"] == "Steward" + + +# ---------------------------------------------------------------------------- remove / delete + +@pytest.mark.asyncio +async def test_remove_placement_deletes_field_and_link_not_report(egeria): + await _document(egeria) + reports_before = set(egeria.of_type("Report")) + + writer = DashboardSheetEgeriaWriter(egeria) + assert await writer.remove_placement(SHEET, "Coco Terms Total") is True + + assert egeria.by_qn("DashboardPlacement::glossary-health::2::Coco Terms Total") is None + assert [r["props"]["queryId"] for r in egeria.rels("DataSetContent")] == [ + "DashboardPlacement::glossary-health::3::Coco Term Counts"] + assert set(egeria.of_type("Report")) == reports_before + assert not [w for w in egeria.writes if w[0] == "delete_asset"] + + # a placement added afterwards takes the next free position, never a taken one + await _run(egeria, "Link", "Report to Dashboard Sheet", LINK_1) + assert [pos for pos, _ in _fields(egeria)] == [1, 3, 4] + + +@pytest.mark.asyncio +async def test_delete_sheet_deletes_chain_only(egeria): + await _document(egeria) + keep = set(egeria.of_type("Report")) | set(egeria.of_type("ReportSpec")) | set(egeria.of_type("Perspective")) + + writer = DashboardSheetEgeriaWriter(egeria) + assert await writer.delete_sheet(SHEET) is True + + assert set(egeria.entities) == keep + assert not egeria.rels("DataSetContent") and not egeria.rels("ScopedBy") + deleted_types = sorted(w[1] for w in egeria.writes if w[0].startswith("delete")) + assert deleted_types == ["Dashboard", "DisplayDataContainer", "DisplayDataField", "DisplayDataField", + "DisplayDataField", "DisplayDataSchemaType"] + assert await DashboardSheetEgeriaWriter(egeria).delete_sheet(SHEET) is False + + +@pytest.mark.asyncio +async def test_dry_run_writes_nothing_and_lists_every_element(egeria): + from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, Placement + sheet = DashboardSheet(name="dry", heading="Dry", placements=[ + Placement(ref="Coco Terms Total", perspectives=["governance"]), + Placement(ref="Intro", content="hello", span="full", emphasis="panel")]) + writer = DashboardSheetEgeriaWriter(egeria, dry_run=True) + await writer.write_sheet(sheet) + + assert egeria.writes == [] + creates = [a for a in writer.actions if a.startswith("create")] + assert creates == ["create Dashboard Dashboard::dry", "create DisplayDataSchemaType DashboardSchema::dry", + "create DisplayDataContainer DashboardSheet::dry", + "create DisplayDataField DashboardPlacement::dry::1::Coco Terms Total", + "create DisplayDataField DashboardPlacement::dry::2::Intro"] + assert any(a.startswith("link DataSetContent") for a in writer.actions) + assert any(a.startswith("link ScopedBy Perspective::Governance") for a in writer.actions) + + +# ---------------------------------------------------------------------------- absences and local-only + +@pytest.mark.asyncio +async def test_missing_report_command_is_refused_as_today(egeria, _store): + """Dr.Egeria refuses `Link Report to Dashboard Sheet` for a Report it cannot find (unchanged): nothing is + written to Egeria or to the store.""" + await _run(egeria, "Create", "Dashboard Sheet", CREATE) + writes, store = list(egeria.writes), _store.read_text() + result = await setup_dispatcher(egeria).dispatch( + _command("Link", "Report to Dashboard Sheet", {**LINK_2, "Report Name": "No Such Report"}), + {"directive": "process"}) + assert result["status"] == "failure" + assert egeria.writes == writes and _store.read_text() == store + + +@pytest.mark.asyncio +async def test_missing_report_in_migration_is_written_without_link_and_said(egeria): + from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, Placement + writer = DashboardSheetEgeriaWriter(egeria) + await writer.write_sheet(DashboardSheet(name="m", heading="M", placements=[Placement(ref="No Such Report")])) + assert egeria.by_qn("DashboardPlacement::m::1::No Such Report") + assert not egeria.rels("DataSetContent") + assert any("reads as missing" in n for n in writer.notes) + + +@pytest.mark.asyncio +async def test_missing_perspective_is_written_without_link_and_said(egeria): + await _run(egeria, "Create", "Dashboard Sheet", CREATE) + result = await _run(egeria, "Link", "Report to Dashboard Sheet", + {**LINK_2, "Placement Perspectives": "Astrologer", "Placement Detail Spec": ""}) + assert not egeria.rels("ScopedBy") + assert "Perspective 'Astrologer'" in result["output"] and "not created here" in result["output"] + assert len(egeria.of_type("Perspective")) == 12 + + +@pytest.mark.asyncio +async def test_local_only_writes_store_alone_and_says_so(egeria, _store, monkeypatch): + monkeypatch.setenv(LOCAL_ONLY_ENV, "1") + result = await _document(egeria) + + assert egeria.writes == [] + assert "not written" in result["output"] and LOCAL_ONLY_ENV in result["output"] + sheets = DashboardSheetDict.load_from_json(str(_store)) + assert [p.ref for p in sheets[SHEET].placements] == ["Coverage header", "Coco Terms Total", "Coco Term Counts"] + + +@pytest.mark.asyncio +async def test_local_only_sheet_is_written_whole_on_next_egeria_command(egeria, monkeypatch): + monkeypatch.setenv(LOCAL_ONLY_ENV, "1") + await _run(egeria, "Create", "Dashboard Sheet", CREATE) + await _run(egeria, "Add", "Text on Dashboard Sheet", TEXT) + monkeypatch.delenv(LOCAL_ONLY_ENV) + + result = await _run(egeria, "Link", "Report to Dashboard Sheet", LINK_1) + + assert [p["additionalProperties"]["placementName"] for _, p in _fields(egeria)] == [ + "Coverage header", "Coco Terms Total"] + assert "only in the local store" in result["output"] + + +def test_perspective_mapping_db2(): + assert perspective_qualified_name("governance") == "Perspective::Governance" + assert perspective_qualified_name("owner") == "Perspective::Owner" # Trellis "Data Owner" + assert perspective_qualified_name("Data Owner") == "Perspective::Owner" + assert perspective_qualified_name("engineer") == "Perspective::Data Expert" + assert perspective_qualified_name("builder") == "Perspective::App/AI Builder" + assert perspective_qualified_name("data expert") == "Perspective::Data Expert" + assert perspective_qualified_name("Perspective::Steward") == "Perspective::Steward" + + +# ---------------------------------------------------------------------------- Create Report + +REPORT = {"Display Name": "Coco Glossaries", "Report Spec": "Glossary-With-Terms", "Output Format": "MD", + "Page Size": "25", "Search String": "Coco"} + + +def _report_props(fake): + guid = fake.by_qn(next(e["props"]["qualifiedName"] for e in fake.entities.values() + if e["props"].get("displayName") == "Coco Glossaries")) + return guid, fake.entities[guid]["props"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("prefix", ["ReportSpec::", "ReportType::"]) +async def test_create_report_writes_parameters_and_report_type_instance(prefix): + fake = fake_egeria.FakeEgeria() + spec_type = "ReportSpec" if prefix == "ReportSpec::" else "ReportType" + spec_guid = fake.add_entity(spec_type, f"{prefix}Glossary-With-Terms", "Glossary-With-Terms") + + result = await _run(fake, "Create", "Report", REPORT) + + report_guid, props = _report_props(fake) + assert props["outputFormat"] == "MD" + assert json.loads(props["reportParameters"]) == {"page_size": 25, "search_string": "Coco"} + assert props["additionalProperties"]["reportSpec"] == "Glossary-With-Terms" # kept one release + assert [(r["end1"], r["end2"]) for r in fake.rels("ReportTypeInstance")] == [(spec_guid, report_guid)] + assert "no ReportTypeInstance" not in result["output"] + + # re-run: the link is not duplicated + await _run(fake, "Create", "Report", REPORT) + assert len(fake.rels("ReportTypeInstance")) == 1 + + +@pytest.mark.asyncio +async def test_create_report_spec_without_element_says_so(): + fake = fake_egeria.FakeEgeria() + result = await _run(fake, "Create", "Report", REPORT) + assert not fake.rels("ReportTypeInstance") + assert "has no Egeria element" in result["output"] + assert "ReportSpec::Glossary-With-Terms and ReportType::Glossary-With-Terms" in result["output"] + + +@pytest.mark.asyncio +async def test_create_report_relinks_when_spec_changes(): + fake = fake_egeria.FakeEgeria() + old = fake.add_entity("ReportSpec", "ReportSpec::Glossary-With-Terms", "Glossary-With-Terms") + new = fake.add_entity("ReportSpec", "ReportSpec::Glossary-Term-Counts", "Glossary-Term-Counts") + await _run(fake, "Create", "Report", REPORT) + await _run(fake, "Create", "Report", {**REPORT, "Report Spec": "Glossary-Term-Counts"}) + report_guid, _ = _report_props(fake) + assert [(r["end1"], r["end2"]) for r in fake.rels("ReportTypeInstance")] == [(new, report_guid)] + assert old in fake.entities # a spec is never deleted + + +@pytest.mark.asyncio +async def test_report_found_when_its_name_is_shared_with_another_type(egeria): + """Live 2026-11-09: a Report whose displayName another element also has (and a longer Report name that + contains it) is still found -- exact displayName among Reports only.""" + from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, Placement + report = egeria.add_entity("Report", "X::Report::TDC", "Term Definition Completeness") + egeria.add_entity("Report", "X::Report::TDC-metric", "Term Definition Completeness Metric Report") + egeria.add_entity("GovernanceMetric", "X::Metric::TDC", "Term Definition Completeness") + writer = DashboardSheetEgeriaWriter(egeria) + await writer.write_sheet(DashboardSheet(name="s", heading="S", + placements=[Placement(ref="Term Definition Completeness")])) + assert [r["end2"] for r in egeria.rels("DataSetContent")] == [report] + assert writer.notes == [] + + +@pytest.mark.asyncio +async def test_two_reports_with_one_name_is_a_note_not_a_guess(egeria): + from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, Placement + egeria.add_entity("Report", "X::Report::1", "Twin") + egeria.add_entity("Report", "X::Report::2", "Twin") + writer = DashboardSheetEgeriaWriter(egeria) + await writer.write_sheet(DashboardSheet(name="s", heading="S", placements=[Placement(ref="Twin")])) + assert not egeria.rels("DataSetContent") + assert any("2 Reports are named 'Twin'" in n for n in writer.notes) + + +# ---------------------------------------------------------------------------- read-back P3s (2026-11-09) + +@pytest.mark.asyncio +async def test_migrate_after_removal_never_reuses_a_position(egeria): + from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, Placement + for name in ("A", "B", "C", "D"): + egeria.add_entity("Report", f"R::{name}", name) + writer = DashboardSheetEgeriaWriter(egeria) + await writer.write_sheet(DashboardSheet(name="p", heading="P", placements=[Placement(ref=n) for n in "ABC"])) + await writer.remove_placement("p", "B") + await writer.write_sheet(DashboardSheet(name="p", heading="P", placements=[Placement(ref=n) for n in "ACD"])) + positions = sorted((rel["props"]["position"], egeria.entities[rel["end2"]]["props"]["additionalProperties"]["placementName"]) + for rel in egeria.rels("NestedSchemaAttribute")) + assert positions == [(1, "A"), (3, "C"), (4, "D")] + + +@pytest.mark.asyncio +async def test_sheet_with_duplicate_placement_names_is_refused_before_any_write(egeria): + from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, Placement + sheet = DashboardSheet(name="dup", heading="Dup", placements=[ + Placement(ref="Coco Terms Total", emphasis="kpi"), Placement(ref="Coco Terms Total", emphasis="panel")]) + with pytest.raises(ValueError, match="more than one placement named 'Coco Terms Total'"): + await DashboardSheetEgeriaWriter(egeria).write_sheet(sheet) + assert egeria.writes == [] + + +@pytest.mark.asyncio +async def test_text_placement_cannot_take_a_report_placements_name(egeria, _store): + await _document(egeria) + writes, store = list(egeria.writes), _store.read_text() + result = await setup_dispatcher(egeria).dispatch( + _command("Add", "Text on Dashboard Sheet", {**TEXT, "Placement Name": "Coco Terms Total"}), + {"directive": "process"}) + assert result["status"] == "failure" + assert "already has a report placement named 'Coco Terms Total'" in json.dumps(result) + assert egeria.writes == writes and _store.read_text() == store + + +@pytest.mark.asyncio +async def test_link_command_finds_a_report_whose_name_another_type_shares(egeria): + """Dr.Egeria's untyped lookup is ambiguous here (and refused live); the command's typed lookup is not.""" + report = egeria.add_entity("Report", "X::Report::TDC", "Term Definition Completeness") + egeria.add_entity("GovernanceMetric", "X::Metric::TDC", "Term Definition Completeness") + await _run(egeria, "Create", "Dashboard Sheet", CREATE) + await _run(egeria, "Link", "Report to Dashboard Sheet", + {**LINK_2, "Report Name": "Term Definition Completeness", "Placement Detail Spec": ""}) + assert [r["end2"] for r in egeria.rels("DataSetContent")] == [report] + + +@pytest.mark.asyncio +async def test_rerun_itemises_every_unchanged_element_and_link(egeria): + """A re-run's 'unchanged' list itemises what the first run made, so the counts match (live step (a): 9).""" + from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, Placement + sheet = DashboardSheet(name="s", heading="S", placements=[Placement(ref="Coco Terms Total", span="full")]) + first = DashboardSheetEgeriaWriter(egeria) + await first.write_sheet(sheet) + second = DashboardSheetEgeriaWriter(egeria) + await second.write_sheet(sheet) + made = [a for a in first.actions if not a.startswith("unchanged")] + assert all(a.startswith("unchanged") for a in second.actions) + assert len(second.actions) == len(made) == 8 # 4 elements + Schema, AttributeForSchema, NestedSchemaAttribute, DataSetContent + kinds = sorted(a.split()[1] for a in second.actions) + assert kinds == sorted(["Dashboard", "DisplayDataSchemaType", "Schema", "DisplayDataContainer", + "AttributeForSchema", "DisplayDataField", "NestedSchemaAttribute", "DataSetContent"]) diff --git a/tests/micro-tests/test_dr_egeria_report_spec_types.py b/tests/micro-tests/test_dr_egeria_report_spec_types.py index d63b6a3a..e9e141cb 100644 --- a/tests/micro-tests/test_dr_egeria_report_spec_types.py +++ b/tests/micro-tests/test_dr_egeria_report_spec_types.py @@ -44,6 +44,7 @@ def __init__(self): super().__init__() self.data_designer = _Recorder() self.schema_maker = _Recorder() + self.classification_manager = _Recorder() def _processor(cls, verb, object_type, om_type, attributes, as_is=None):