Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions src/graphql_api/schema/resolvers/analytics.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@
_TIMELINE_MAX_DAYS = 366


def _as_float(value):
"""Converte métricas numeric do Postgres (Decimal no asyncpg) para float; None passa.

O Float do graphql-core 3.3 rejeita Decimal ("Float cannot represent non numeric value").
"""
return None if value is None else float(value)


def _extract_facets(response: dict, field_name: str) -> list[dict]:
"""Extract facet counts for a given field from a Typesense response."""
for fc in response.get("facet_counts", []):
Expand Down Expand Up @@ -164,11 +172,11 @@ async def agency_analytics(
agency_key=row["agency_key"] or "",
agency_name=row.get("agency_name"),
article_count=int(row["article_count"] or 0),
avg_sentiment_score=row.get("avg_sentiment_score"),
pct_positive=row.get("pct_positive"),
pct_negative=row.get("pct_negative"),
avg_readability_flesch=row.get("avg_readability_flesch"),
avg_word_count=row.get("avg_word_count"),
avg_sentiment_score=_as_float(row.get("avg_sentiment_score")),
pct_positive=_as_float(row.get("pct_positive")),
pct_negative=_as_float(row.get("pct_negative")),
avg_readability_flesch=_as_float(row.get("avg_readability_flesch")),
avg_word_count=_as_float(row.get("avg_word_count")),
top_themes=[],
)
for row in rows
Expand Down
49 changes: 49 additions & 0 deletions tests/resolvers/test_analytics.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,55 @@ async def test_invalid_range_returns_error():


class TestAgencyAnalytics:
@pytest.mark.asyncio
async def test_metricas_numeric_do_postgres_serializam_como_float(self):
"""asyncpg devolve AVG(numeric) como Decimal; o GraphQL Float não aceita Decimal."""
from decimal import Decimal

mock_pg = AsyncMock()
mock_pg.agency_analytics = AsyncMock(return_value=[
{
"period": "2026-09",
"agency_key": "saude",
"agency_name": "Ministério da Saúde",
"article_count": 120,
"avg_sentiment_score": Decimal("0.7485"),
"pct_positive": Decimal("0.6800000000000000"),
"pct_negative": Decimal("0.0500000000000000"),
"avg_readability_flesch": Decimal("33.5"),
"avg_word_count": Decimal("410.25"),
},
{
"period": "2026-10",
"agency_key": "saude",
"agency_name": "Ministério da Saúde",
"article_count": 10,
"avg_sentiment_score": None,
"pct_positive": None,
"pct_negative": None,
"avg_readability_flesch": None,
"avg_word_count": None,
},
])
query = """
query {
agencyAnalytics(agencies: ["saude"] dateFrom: "2026-09-01" dateTo: "2026-10-31" granularity: MONTH) {
avgSentimentScore pctPositive pctNegative avgReadabilityFlesch avgWordCount
}
}
"""
result = await test_schema.execute(query, context_value=FakeContext(postgres_ds=mock_pg))
assert result.errors is None
first, second = result.data["agencyAnalytics"]
assert first == {
"avgSentimentScore": 0.7485,
"pctPositive": 0.68,
"pctNegative": 0.05,
"avgReadabilityFlesch": 33.5,
"avgWordCount": 410.25,
}
assert all(v is None for v in second.values())

@pytest.mark.asyncio
async def test_retorna_metricas_por_periodo(self):
mock_pg = AsyncMock()
Expand Down
Loading