147 lines
6.2 KiB
Python
147 lines
6.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Build a reusable automation-results dashboard from the canonical status registry."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import copy
|
|
import json
|
|
import shutil
|
|
import tempfile
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
from build_automations_calendar import WORKSHEET_NAME, attach_statuses, normalize, read_statuses, read_workflow_rows
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
DEFAULT_WORKBOOK = ROOT / "local/workflows.xlsx"
|
|
DEFAULT_STATUS = ROOT / "examples/status.example.json"
|
|
DEFAULT_OUTPUT = ROOT / "output/automations-results.html"
|
|
DEFAULT_TEMPLATE = ROOT / "templates/automations-results.template.html"
|
|
|
|
|
|
def load_raw_status(path: Path) -> tuple[dict, list[dict]]:
|
|
if not path.is_file():
|
|
return {}, []
|
|
payload = json.loads(path.read_text(encoding="utf-8-sig"))
|
|
records = payload.get("records", []) if isinstance(payload, dict) else payload
|
|
return payload if isinstance(payload, dict) else {}, [item for item in records if isinstance(item, dict)]
|
|
|
|
|
|
def build_view(automations: list[dict], evidence: list[dict]) -> tuple[list[dict], list[dict]]:
|
|
managed_keys = set()
|
|
managed = []
|
|
for automation in automations:
|
|
managed_keys.add(normalize(automation["name"]))
|
|
managed.append({
|
|
"id": automation["id"],
|
|
"name": automation["name"],
|
|
"machine": automation["machine"],
|
|
"project": automation["project"],
|
|
"opsSegment": automation["opsSegment"],
|
|
"location": automation["location"],
|
|
"automationStatus": automation["status"],
|
|
"run": automation["run"],
|
|
"scope": "managed",
|
|
})
|
|
|
|
collected = []
|
|
for index, record in enumerate(evidence, start=1):
|
|
names = [record.get("name", ""), *(record.get("aliases") or [])]
|
|
linked = any(normalize(str(name)) in managed_keys for name in names if name)
|
|
outcome = str(record.get("outcome", "unknown")).casefold()
|
|
if outcome not in {"success", "failure", "unknown"}:
|
|
outcome = "unknown"
|
|
collected.append({
|
|
"id": f"evidence-{index}",
|
|
"name": str(record.get("name") or "Unnamed result"),
|
|
"aliases": record.get("aliases") or [],
|
|
"outcome": outcome,
|
|
"lastRun": record.get("lastRun") or record.get("last_run"),
|
|
"detail": record.get("detail") or record.get("message") or "",
|
|
"source": record.get("source") or "unknown",
|
|
"linked": linked,
|
|
"scope": "evidence",
|
|
})
|
|
|
|
return managed, collected
|
|
|
|
|
|
def build_payload(workbook_path: Path, status_path: Path) -> dict:
|
|
base_automations, used_range = read_workflow_rows(workbook_path)
|
|
status_meta, evidence = load_raw_status(status_path)
|
|
current_automations = copy.deepcopy(base_automations)
|
|
attach_statuses(current_automations, read_statuses(status_path))
|
|
managed, collected = build_view(current_automations, evidence)
|
|
|
|
days = []
|
|
for snapshot in status_meta.get("history", []) if isinstance(status_meta, dict) else []:
|
|
if not isinstance(snapshot, dict) or not snapshot.get("date"):
|
|
continue
|
|
snapshot_automations = copy.deepcopy(base_automations)
|
|
snapshot_records = [item for item in snapshot.get("records", []) if isinstance(item, dict)]
|
|
snapshot_statuses = {}
|
|
for record in snapshot_records:
|
|
names = [record.get("name", ""), *(record.get("aliases") or [])]
|
|
for name in names:
|
|
if name:
|
|
snapshot_statuses[normalize(str(name))] = record
|
|
attach_statuses(snapshot_automations, snapshot_statuses)
|
|
snapshot_managed, snapshot_collected = build_view(snapshot_automations, snapshot_records)
|
|
days.append({
|
|
"date": str(snapshot["date"]),
|
|
"generatedAt": snapshot.get("generatedAt"),
|
|
"managed": snapshot_managed,
|
|
"evidence": snapshot_collected,
|
|
})
|
|
|
|
if not days:
|
|
days = [{"date": datetime.now().astimezone().date().isoformat(), "generatedAt": status_meta.get("generatedAt"), "managed": managed, "evidence": collected}]
|
|
days.sort(key=lambda item: item["date"], reverse=True)
|
|
days = days[:3]
|
|
|
|
return {
|
|
"generatedAt": datetime.now(timezone.utc).isoformat(),
|
|
"registryGeneratedAt": status_meta.get("generatedAt"),
|
|
"registryNote": status_meta.get("note", ""),
|
|
"workbook": "configured workbook",
|
|
"workbookRange": f"{WORKSHEET_NAME}!{used_range}",
|
|
"statusRegistry": "configured status registry",
|
|
"managed": managed,
|
|
"evidence": collected,
|
|
"days": days,
|
|
}
|
|
|
|
|
|
def write_dashboard(template_path: Path, output_path: Path, payload: dict) -> None:
|
|
template = template_path.read_text(encoding="utf-8")
|
|
if "__AUTOMATION_RESULTS_DATA__" not in template:
|
|
raise ValueError("Results template is missing __AUTOMATION_RESULTS_DATA__")
|
|
data = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
|
|
html = template.replace("__AUTOMATION_RESULTS_DATA__", data, 1)
|
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
with tempfile.NamedTemporaryFile("w", encoding="utf-8", delete=False, dir=output_path.parent, suffix=".tmp") as handle:
|
|
handle.write(html)
|
|
temp_path = Path(handle.name)
|
|
shutil.move(temp_path, output_path)
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--workbook", type=Path, default=DEFAULT_WORKBOOK)
|
|
parser.add_argument("--status", type=Path, default=DEFAULT_STATUS)
|
|
parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
|
|
parser.add_argument("--template", type=Path, default=DEFAULT_TEMPLATE)
|
|
args = parser.parse_args()
|
|
for label, path in (("Workbook", args.workbook), ("Status registry", args.status), ("Template", args.template)):
|
|
if not path.is_file():
|
|
parser.error(f"{label} not found: {path}")
|
|
payload = build_payload(args.workbook, args.status)
|
|
write_dashboard(args.template, args.output, payload)
|
|
print(f"Updated {args.output.resolve()} with {len(payload['managed'])} managed automations and {len(payload['evidence'])} evidence records")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|