from datetime import datetime, timedelta, timezone from sqlalchemy import event from sqlalchemy.dialects import postgresql from central.app.audit import record_audit from central.app.blocked_products import upsert_blocker from central.app.control_plane import _blocker_breakdown_query, blocker_filter_summary, dashboard_summary, jobs_status_summary, list_blockers, list_installations, list_jobs from central.app.config import settings from central.app.events import record_event from central.app.models import Agent, AgentEnrollment, AgentRelease, AgentSnapshot, AuditEvent, BlockedProduct, Installation, Job, Tenant from central.app.panel_presentation import blocker_reason_label, blocker_type_label, fiscal_status_label, job_kind_label, job_status_label, priority_label from central.tests.test_control_plane import setup_db NOW = datetime(2026, 9, 22, 19, 0, tzinfo=timezone.utc) def test_operator_labels_are_ptbr_without_changing_internal_codes(): assert job_status_label("FAILED") == "Falhou" assert job_status_label("RUNNING") == "Executando" assert job_kind_label("SYNC_INCREMENTAL") == "Sincronização incremental" assert blocker_type_label("BLOCKED_MISSING_EVIDENCE") == "Evidência fiscal ausente" assert blocker_reason_label("INVALID_NCM") == "NCM inválido" assert priority_label("HIGH") == "Alta" assert fiscal_status_label("BLOCKED") == "Bloqueado" def _installation(session, index, *, health="ONLINE", coverage=80, blocked=0, version="1.0.0rc1"): tenant = Tenant(name=f"Client {index}") session.add(tenant) session.flush() agent = Agent(tenant_id=tenant.id, name=f"agent-{index}", token_hash=f"token-{index}".ljust(64, "x"), agent_version=version) session.add(agent) session.flush() last_seen = { "ONLINE": NOW - timedelta(seconds=10), "DEGRADED": NOW - timedelta(seconds=10), "OFFLINE": NOW - timedelta(hours=2), "FAILED": NOW - timedelta(seconds=10), "UNKNOWN": None, }[health] installation = Installation( agent_id=agent.id, tenant_id=tenant.id, installation_id=f"00000000-0000-4000-8000-{index:012d}", display_name=f"Installation {index}", hostname=f"server-{index}", last_seen_at=last_seen, last_status="FAILED" if health == "FAILED" else "IDLE", ) session.add(installation) session.flush() snapshot = AgentSnapshot( installation_id=installation.id, total_products=100, fiscally_complete=coverage, coverage_percent=coverage, safe_blocked=blocked, failed_products=1 if health == "FAILED" else 0, last_job_status="FAILED" if health == "DEGRADED" else "COMPLETED", agent_health=health, version_drift="OUTDATED" if version != "1.0.0rc1" else "CURRENT", ) session.add(snapshot) session.flush() return tenant, agent, installation, snapshot def _blocker(session, tenant, *, product, field="CFOP", blocker_type="BLOCKED_MISSING_EVIDENCE", index=0, installation_id=None): row = BlockedProduct( tenant_id=tenant.id, installation_id=installation_id, company=tenant.name, product_code=product, description=f"Product {product}", blocker_type=blocker_type, field=field, reason_code="INSUFFICIENT_EVIDENCE", evidence_summary={"source": "test"}, input_fingerprint=f"input-{index}", blocker_fingerprint=f"blocker-{index}", first_seen_at=NOW - timedelta(hours=3), last_seen_at=NOW - timedelta(minutes=20), retry_count=2, ) session.add(row) session.flush() return row def test_dashboard_reconciles_five_health_states_and_counts_distinct_safe_products(): session_factory = setup_db() with session_factory() as session: first, _, first_installation, _ = _installation(session, 1, health="ONLINE", blocked=2) second, _, second_installation, _ = _installation(session, 2, health="DEGRADED") _installation(session, 3, health="OFFLINE") _installation(session, 4, health="FAILED") _installation(session, 5, health="UNKNOWN") _blocker(session, first, product="P1", field="CFOP", index=1, installation_id=first_installation.id) _blocker(session, first, product="P1", field="NCM", index=2, installation_id=first_installation.id) _blocker(session, second, product="P2", field="ICMS", index=3, installation_id=second_installation.id) session.commit() summary = dashboard_summary(session, now=NOW) assert summary["health_counts"] == {"ONLINE": 1, "DEGRADED": 1, "OFFLINE": 1, "FAILED": 1, "UNKNOWN": 1} assert summary["agents_total"] == sum(summary["health_counts"].values()) assert summary["safe_blocked_products"] == 2 assert summary["open_blockers"] == 3 assert summary["open_blocker_breakdown"] == {"NCM": 1, "CEST": 0, "CFOP": 1, "ST": 0, "ICMS": 1, "CSOSN": 0, "PIS": 0, "COFINS": 0, "RTC": 0, "OTHER": 0} assert summary["online"] == 1 and summary["safe_blocked"] == 2 def test_installation_inventory_active_scope_excludes_inactive_and_revoked_but_keeps_history(): factory = setup_db() with factory() as session: active = _installation(session, 1)[2] inactive_tenant, _, _, _ = _installation(session, 2) inactive_tenant.active = False _, disabled_agent, _, _ = _installation(session, 3) disabled_agent.enabled = False tenant, revoked_agent, revoked, _ = _installation(session, 4, health="UNKNOWN") _, _, paused, _ = _installation(session, 5) paused.processing_enabled = False release = AgentRelease(version="test-inventory", platform="windows", architecture="x64", filename="test.exe", storage_path="test.exe", size_bytes=1, sha256="x" * 64) session.add(release) session.flush() session.add(AgentEnrollment(enrollment_uuid=revoked.installation_id, tenant_id=tenant.id, agent_id=revoked_agent.id, display_name="Histórico", release_id=release.id, status="REVOKED")) session.commit() current = list_installations(session, page_size=10, now=NOW) historical = list_installations(session, page_size=10, scope="all", now=NOW) unknown = list_installations(session, health="UNKNOWN", now=NOW) assert {row["installation_id"] for row in current["items"]} == {active.installation_id, paused.installation_id} assert current["total"] == 2 assert historical["total"] == 5 assert unknown["total"] == 0 assert {row["installation_id"]: row["operational_active"] for row in historical["items"]}[revoked.installation_id] is False def test_outdated_agent_filter_returns_only_outdated_active_installations(): factory = setup_db() with factory() as session: _, _, outdated, _ = _installation(session, 1, version="0.9.0") _, _, _, current_snapshot = _installation(session, 2, version=settings.agent_server_version) current_snapshot.version_drift = "CURRENT" _, disabled, _, _ = _installation(session, 3, version="0.9.0") disabled.enabled = False session.commit() result = list_installations(session, version="outdated", now=NOW) assert result["total"] == 1 assert result["items"][0]["installation_id"] == outdated.installation_id def test_dashboard_excludes_inactive_history_and_groups_repeated_blockers(): factory = setup_db() with factory() as session: tenant, agent, installation, snapshot = _installation(session, 1, health="ONLINE", coverage=74, blocked=26, version=settings.agent_server_version) snapshot.version_drift = "CURRENT" for index in range(26): _blocker(session, tenant, product=f"P{index:03}", field="NCM", index=index, installation_id=installation.id) session.add(Job(agent_id=agent.id, kind="REPROCESS_PRODUCTS", status="FAILED", error="erro real", created_at=NOW)) old_tenant, old_agent, old_installation, _ = _installation(session, 2, health="UNKNOWN", version="0.9.0") _blocker(session, old_tenant, product="HISTORICAL", field="CFOP", index=80, installation_id=old_installation.id) session.add(Job(agent_id=old_agent.id, kind="REPROCESS_ALL", status="FAILED", error="erro histórico", created_at=NOW)) release = AgentRelease(version="test-dashboard", platform="windows", architecture="x64", filename="test.exe", storage_path="test.exe", size_bytes=1, sha256="y" * 64) session.add(release) session.flush() session.add(AgentEnrollment(enrollment_uuid=old_installation.installation_id, tenant_id=old_tenant.id, agent_id=old_agent.id, display_name="Encerrada", release_id=release.id, status="REVOKED")) inactive_tenant, _, _, _ = _installation(session, 3, health="OFFLINE") inactive_tenant.active = False _, disabled_agent, _, _ = _installation(session, 4, health="FAILED") disabled_agent.enabled = False session.commit() summary = dashboard_summary(session, now=NOW) assert summary["agents_total"] == 1 assert summary["health_counts"] == {"ONLINE": 1, "DEGRADED": 0, "OFFLINE": 0, "FAILED": 0, "UNKNOWN": 0} assert summary["total_products"] == 100 assert summary["safe_blocked"] == 26 assert summary["open_blockers"] == 26 assert summary["safe_blocked_products"] == 26 assert summary["open_blocker_breakdown"]["NCM"] == 26 assert summary["open_blocker_breakdown"]["CFOP"] == 0 assert summary["failed_jobs"] == 1 fiscal_groups = [item for item in summary["attention_items"] if item.get("field") == "NCM"] assert len(fiscal_groups) == 1 assert fiscal_groups[0]["group_count"] == 26 assert fiscal_groups[0]["products_affected"] == 26 assert fiscal_groups[0]["link"].startswith("/blockers?") assert len(summary["attention_items"]) <= 10 assert all(item["client"] != "Client 2" for item in summary["attention_items"]) def test_blockers_and_jobs_keep_revoked_history_out_of_active_scope(): factory = setup_db() with factory() as session: tenant, agent, installation, _ = _installation(session, 1) current = _blocker(session, tenant, product="CURRENT", field="NCM", index=1, installation_id=installation.id) current.reason_code = "INVALID_NCM" resolved = _blocker(session, tenant, product="RESOLVED", field="NCM", index=2, installation_id=installation.id) resolved.resolved_at = NOW session.add(Job(agent_id=agent.id, kind="REPROCESS_PRODUCTS", status="FAILED", created_at=NOW, error="current")) old_tenant, old_agent, old_installation, _ = _installation(session, 2) _blocker(session, old_tenant, product="OLD", field="NCM", index=3, installation_id=old_installation.id) session.add(Job(agent_id=old_agent.id, kind="REPROCESS_ALL", status="FAILED", created_at=NOW, error="historical")) old_agent.enabled = False session.commit() assert list_blockers(session, field="NCM")["total"] == 1 assert list_blockers(session, field="NCM", reason_code="INVALID_NCM")["items"][0]["id"] == current.id assert list_blockers(session, field="NCM", scope="all")["total"] == 2 assert list_blockers(session, status="RESOLVED", scope="all")["items"][0]["id"] == resolved.id assert blocker_filter_summary(session)["open_blockers"] == 1 assert list_jobs(session, status="FAILED")["total"] == 1 assert list_jobs(session, status="FAILED", scope="all")["total"] == 2 def test_jobs_status_kpis_count_active_jobs_by_status_in_one_group(): factory = setup_db() with factory() as session: _, agent, _, _ = _installation(session, 1) _, disabled, _, _ = _installation(session, 2) disabled.enabled = False for status in ("PENDING", "RUNNING", "COMPLETED", "FAILED"): session.add(Job(agent_id=agent.id, kind="SYNC_INCREMENTAL", status=status, created_at=NOW)) session.add(Job(agent_id=disabled.id, kind="REPROCESS_ALL", status="FAILED", created_at=NOW)) session.commit() assert jobs_status_summary(session) == {"PENDING": 1, "RUNNING": 1, "COMPLETED": 1, "FAILED": 1} assert jobs_status_summary(session, scope="all")["FAILED"] == 2 def test_attention_groups_rank_high_priority_before_limiting_recent_low_priority(): factory = setup_db() with factory() as session: tenant, _, installation, _ = _installation(session, 1, version=settings.agent_server_version) high = _blocker(session, tenant, product="IMPORTANT", field="NCM", index=90, installation_id=installation.id) high.last_seen_at = NOW - timedelta(days=3) for index in range(12): low = _blocker(session, tenant, product=f"LOW-{index}", field="OTHER", blocker_type="UNMAPPED", index=index, installation_id=installation.id) low.reason_code = f"OTHER_{index}" low.last_seen_at = NOW - timedelta(minutes=index) session.commit() attention = dashboard_summary(session, now=NOW)["attention_items"] assert len(attention) <= 10 assert any(item.get("field") == "NCM" for item in attention) def test_dashboard_query_count_stays_bounded_with_many_blockers(): factory = setup_db() with factory() as session: tenant, _, installation, _ = _installation(session, 1, version=settings.agent_server_version) for index in range(130): _blocker(session, tenant, product=f"P-{index:03}", field="NCM", index=index, installation_id=installation.id) session.commit() statements = [] def count_statement(conn, cursor, statement, parameters, context, executemany): statements.append(statement) event.listen(session.bind, "before_cursor_execute", count_statement) try: summary = dashboard_summary(session, now=NOW) finally: event.remove(session.bind, "before_cursor_execute", count_statement) assert summary["open_blockers"] == 130 assert len(statements) <= 18 assert not any("SELECT" in sql.upper() and "LIMIT 130" in sql.upper() for sql in statements) def test_snapshot_coverage_exposes_unclassified_residual_and_overcount(): session_factory = setup_db() with session_factory() as session: tenant, agent, installation, snapshot = _installation(session, 1, coverage=80, blocked=1) snapshot.total_products = 100 snapshot.fiscally_complete = 96 snapshot.safe_blocked = 1 snapshot.failed_products = 1 session.commit() item = list_installations(session, page_size=5)["items"][0] assert item["unclassified_products"] == 2 assert item["coverage_overcount_products"] == 0 assert item["coverage_invariant_pass"] is True assert item["total_products"] == item["fiscally_complete"] + item["safe_blocked"] + item["failed_products"] + item["unclassified_products"] snapshot.fiscally_complete = 99 session.commit() inconsistent = list_installations(session, page_size=5)["items"][0] assert inconsistent["unclassified_products"] == 0 assert inconsistent["coverage_overcount_products"] == 1 assert inconsistent["coverage_invariant_pass"] is False def test_dashboard_coverage_totals_reconcile_and_keep_registry_metric_separate(): session_factory = setup_db() with session_factory() as session: tenant, _, installation, snapshot = _installation(session, 1, coverage=96, blocked=1) snapshot.total_products = 100 snapshot.fiscally_complete = 96 snapshot.safe_blocked = 1 snapshot.failed_products = 1 _blocker(session, tenant, product="P-OPEN", field="CFOP", index=91, installation_id=installation.id) session.commit() summary = dashboard_summary(session, now=NOW) assert summary["total_products"] == 100 assert summary["fiscally_complete"] == 96 assert summary["safe_blocked"] == 1 assert summary["failed_products"] == 1 assert summary["unclassified_products"] == 2 assert summary["coverage_overcount_products"] == 0 assert summary["coverage_invariant_pass"] is True assert summary["safe_blocked_products"] == 1 assert summary["total_products"] == summary["fiscally_complete"] + summary["safe_blocked"] + summary["failed_products"] + summary["unclassified_products"] def test_dashboard_marks_inconsistent_snapshot_partition_instead_of_clamping(): session_factory = setup_db() with session_factory() as session: _, _, _, snapshot = _installation(session, 1, coverage=100, blocked=2) snapshot.total_products = 10 snapshot.fiscally_complete = 9 snapshot.safe_blocked = 2 snapshot.failed_products = 0 session.commit() summary = dashboard_summary(session, now=NOW) assert summary["coverage_overcount_products"] == 1 assert summary["coverage_invariant_pass"] is False def test_attention_items_are_ranked_and_capped_at_ten(): session_factory = setup_db() with session_factory() as session: tenants = [] for index, health in enumerate(["FAILED"] * 2 + ["DEGRADED"] * 2 + ["OFFLINE"] * 2 + ["UNKNOWN"] * 2 + ["ONLINE"] * 4, 1): tenant = _installation(session, index, health=health, version="0.9.0" if index >= 9 else "1.0.0rc1")[0] tenants.append(tenant) for index, tenant in enumerate(tenants[8:10], 20): _blocker(session, tenant, product=f"P{index}", index=index) session.commit() items = dashboard_summary(session, now=NOW)["attention_items"] assert len(items) <= 10 assert [item["technical_health"] for item in items[:8]] == ["FAILED"] * 2 + ["DEGRADED"] * 2 + ["OFFLINE"] * 2 + ["UNKNOWN"] * 2 assert all({"client", "display_name", "hostname", "problem", "timestamp", "age", "link", "technical_health"} <= item.keys() for item in items) def test_installations_expose_separate_fiscal_and_technical_status_and_worst_sort(): session_factory = setup_db() with session_factory() as session: _installation(session, 1, coverage=90, blocked=0) _installation(session, 2, coverage=40, blocked=1, version="0.9.0") session.commit() result = list_installations(session, sort="worst_coverage", page_size=10, now=NOW) item = result["items"][0] assert item["display_name"] == "Installation 2" assert item["fiscal_completion_percent"] == 40 assert item["technical_health"] == "ONLINE" assert item["fiscal_status"] == "BLOCKED" assert item["version_drift"] == "OUTDATED" assert item["technical_ids"]["agent_id"] == item["agent_id"] def test_jobs_join_operational_identity_and_format_duration(): session_factory = setup_db() with session_factory() as session: tenant, agent, installation, _ = _installation(session, 1) session.add(Job(agent_id=agent.id, kind="REPROCESS_ALL", status="FAILED", created_at=NOW, started_at=NOW, finished_at=NOW + timedelta(seconds=194), error="failure")) session.commit() result = list_jobs(session, client="Client 1", search="server-1", page_size=10) item = result["items"][0] assert item["client"] == tenant.name assert item["display_name"] == installation.display_name assert item["hostname"] == installation.hostname assert item["job_id"] assert item["duration"] == "3 min 14 s" assert item["error"] == "failure" def test_blockers_filter_with_priority_age_and_stable_pagination(): session_factory = setup_db() with session_factory() as session: tenant, _, installation, _ = _installation(session, 1) critical = _blocker(session, tenant, product="P1", field="", blocker_type="TECHNICAL_FAILURE", index=1, installation_id=installation.id) _blocker(session, tenant, product="P2", field="CFOP", index=2, installation_id=installation.id) session.commit() result = list_blockers(session, client="Client 1", installation=installation.display_name, status="OPEN", search="P1", page=1, page_size=1) assert result["total"] == 1 assert result["items"][0]["id"] == critical.id assert result["items"][0]["priority"] == "CRITICAL" assert result["items"][0]["age"].startswith("há ") assert result["items"][0]["installation_id"] == installation.installation_id def test_blocker_detail_contains_context_events_jobs_and_resolution_audit(): session_factory = setup_db() with session_factory() as session: tenant, agent, installation, _ = _installation(session, 1) blocker = _blocker(session, tenant, product="P1", index=1, installation_id=installation.id) job = Job(agent_id=agent.id, kind="REPROCESS_ALL", status="FAILED", created_at=NOW, error="failed") session.add(job) session.flush() record_event(session, tenant_id=tenant.id, installation_id=installation.id, agent_id=agent.id, severity="ERROR", event_type="JOB_FAILED", message="job failed", blocker_id=blocker.id, job_id=job.id, occurred_at=NOW) record_audit(session, admin_user_id=None, tenant_id=tenant.id, action="RESOLVE_BLOCKER", target_type="blocker", target_id=str(blocker.id), context={"reason": "reviewed"}) session.commit() from central.app.control_plane import blocker_detail detail = blocker_detail(session, blocker.id) assert detail["client"] == tenant.name assert detail["installation"]["installation_id"] == installation.installation_id assert detail["evidence"]["source"] == "test" assert detail["related_events"][0]["job_id"] == job.id assert detail["related_jobs"][0]["job_id"] == job.id assert detail["resolution_audit"][0]["action"] == "RESOLVE_BLOCKER" def test_blockers_keep_exact_installation_identity_for_same_tenant(): session_factory = setup_db() with session_factory() as session: tenant = Tenant(name="Shared Client") session.add(tenant) session.flush() agent_a = Agent(tenant_id=tenant.id, name="agent-a", token_hash="token-a".ljust(64, "x")) agent_b = Agent(tenant_id=tenant.id, name="agent-b", token_hash="token-b".ljust(64, "x")) session.add_all([agent_a, agent_b]) session.flush() installation_a = Installation(agent_id=agent_a.id, tenant_id=tenant.id, installation_id="00000000-0000-4000-8000-000000000101", display_name="Store A", hostname="server-a") installation_b = Installation(agent_id=agent_b.id, tenant_id=tenant.id, installation_id="00000000-0000-4000-8000-000000000102", display_name="Store B", hostname="server-b") session.add_all([installation_a, installation_b]) session.flush() row_a = upsert_blocker(session, tenant.id, {"company": tenant.name, "product_code": "P-A", "field": "CFOP", "reason_code": "MISSING", "input_fingerprint": "a"}, installation_id=installation_a.id) row_b = upsert_blocker(session, tenant.id, {"company": tenant.name, "product_code": "P-B", "field": "CFOP", "reason_code": "MISSING", "input_fingerprint": "b"}, installation_id=installation_b.id) result_a = list_blockers(session, tenant_id=tenant.id, installation="Store A") result_b = list_blockers(session, tenant_id=tenant.id, installation="Store B") assert result_a["total"] == 1 and result_a["items"][0]["id"] == row_a.id assert result_a["items"][0]["installation_id"] == installation_a.installation_id assert result_b["total"] == 1 and result_b["items"][0]["id"] == row_b.id assert result_b["items"][0]["installation_id"] == installation_b.installation_id def test_legacy_tenant_blocker_has_no_fabricated_installation_context(): session_factory = setup_db() with session_factory() as session: tenant, _, installation, _ = _installation(session, 1) row = _blocker(session, tenant, product="LEGACY", index=99) result = list_blockers(session, tenant_id=tenant.id, scope="all") assert result["items"][0]["id"] == row.id assert result["items"][0]["installation_id"] is None from central.app.control_plane import blocker_detail detail = blocker_detail(session, row.id) assert detail["installation"]["installation_id"] is None assert detail["server"]["hostname"] is None assert installation.hostname == "server-1" def test_dashboard_uses_sql_aggregates_for_operational_totals(): session_factory = setup_db() with session_factory() as session: tenant, _, _, _ = _installation(session, 1) _blocker(session, tenant, product="P1", index=101) statements = [] event.listen(session.bind, "before_cursor_execute", lambda conn, cursor, statement, parameters, context, executemany: statements.append(statement)) dashboard_summary(session, now=NOW) assert any("COUNT" in statement.upper() and "BLOCKED_PRODUCTS" in statement.upper() for statement in statements) assert any("DISTINCT" in statement.upper() and "BLOCKED_PRODUCTS" in statement.upper() for statement in statements) def test_health_filter_is_paginated_in_sql_and_counts_all_matches(): session_factory = setup_db() with session_factory() as session: for index in range(1, 4): _installation(session, index, health="ONLINE") statements = [] event.listen(session.bind, "before_cursor_execute", lambda conn, cursor, statement, parameters, context, executemany: statements.append(statement)) result = list_installations(session, health="ONLINE", page=2, page_size=1, now=NOW) assert result["total"] == 3 assert len(result["items"]) == 1 assert any("LIMIT" in statement.upper() and "INSTALLATIONS" in statement.upper() for statement in statements) def test_worst_coverage_sort_uses_the_displayed_derived_percentage(): session_factory = setup_db() with session_factory() as session: _, _, first, first_snapshot = _installation(session, 1, coverage=80) _, _, second, second_snapshot = _installation(session, 2, coverage=20) first_snapshot.coverage_percent = 10 second_snapshot.coverage_percent = 90 session.commit() result = list_installations(session, sort="worst_coverage", page_size=10, now=NOW) assert result["items"][0]["installation_id"] == second.installation_id assert result["items"][0]["fiscal_completion_percent"] == 20 assert first.installation_id != second.installation_id def test_worst_coverage_sort_cannot_disagree_with_one_decimal_display(): session_factory = setup_db() with session_factory() as session: _, _, first, first_snapshot = _installation(session, 1, coverage=0) _, _, second, second_snapshot = _installation(session, 2, coverage=0) first_snapshot.total_products = 79 first_snapshot.fiscally_complete = 5 second_snapshot.total_products = 16 second_snapshot.fiscally_complete = 1 session.commit() result = list_installations(session, sort="worst_coverage", page_size=10, now=NOW) displayed = [item["fiscal_completion_percent"] for item in result["items"]] assert displayed == sorted(displayed) assert displayed == [6.3, 6.3] assert {item["installation_id"] for item in result["items"]} == {first.installation_id, second.installation_id} def test_lowercase_required_blocker_field_reaches_attention_candidates(): session_factory = setup_db() with session_factory() as session: tenant, _, installation, _ = _installation(session, 1) _blocker(session, tenant, product="LOWER", field="cfop", index=120, installation_id=installation.id) attention = dashboard_summary(session, now=NOW)["attention_items"] assert any(item.get("field") == "CFOP" and item["link"].startswith("/blockers?scope=active") for item in attention) def test_blocker_breakdown_query_groups_on_same_postgres_expression(): from sqlalchemy import select query = select(BlockedProduct, Tenant).join(Tenant, Tenant.id == BlockedProduct.tenant_id) sql = str(_blocker_breakdown_query(query).compile(dialect=postgresql.dialect())) assert "GROUP BY blocked_products.field" in sql assert "GROUP BY coalesce" not in sql def test_remaining_technical_enums_have_human_labels(): from central.app.panel_presentation import health_reason_label assert blocker_reason_label("INVALID_NCM") == "NCM inválido" assert blocker_reason_label("LEGACY_NCM") == "NCM legado" assert blocker_type_label("BLOCKED_MISSING_EVIDENCE") == "Evidência fiscal ausente" assert health_reason_label("last heartbeat exceeds 300s") == "Sem heartbeat recente" assert health_reason_label("persistent technical failure") == "Falha técnica persistente" assert blocker_reason_label("SOMETHING_NEW") == "Something new" # unknown codes degrade readably, never crash def test_rtc_status_view_is_discreet_and_optional(): from central.app.panel_presentation import rtc_status_view assert rtc_status_view(None) is None and rtc_status_view({"coverage": {}}) is None assert rtc_status_view({"fiscal_context": {"rtc_enabled": False}})["label"] == "Desativada" on = rtc_status_view({"fiscal_context": {"rtc_enabled": True, "rtc_supported": True, "rtc_catalog_valid": True}}) assert on["label"] == "Ativa" and on["enabled"] and on["catalog_valid"] assert blocker_type_label("RTC_CST_MISSING") == "CST IBS/CBS ausente no catálogo" and blocker_type_label("COFINS_RATE_INVALID") == "Alíquota COFINS inválida" assert blocker_type_label("PIS_CST_INCIDENCE_MISMATCH") == "CST PIS incompatível com a incidência"