Skip to content

Commit 3f3a548

Browse files
fix: No Results Error Handling
2 parents 9e19c55 + dd0aefe commit 3f3a548

File tree

3 files changed

+52
-19
lines changed

3 files changed

+52
-19
lines changed

src/api/api/api_routes.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import asyncio
22
import json
33
import logging
4+
import math
45
import os
56
from fastapi import APIRouter, Request
67
from fastapi.responses import JSONResponse, StreamingResponse
@@ -74,6 +75,12 @@ async def fetch_chart_data_with_filters(chart_filters: ChartFilters):
7475
"FetchChartDataWithFiltersSuccess",
7576
{"status": "success", "filters": chart_filters.model_dump()}
7677
)
78+
# Sanitize the response to handle NaN and Infinity values
79+
for record in response:
80+
if isinstance(record.get("chart_value"), list):
81+
for item in record["chart_value"]:
82+
if isinstance(item.get("value"), float) and (math.isnan(item["value"]) or math.isinf(item["value"])):
83+
item["value"] = None
7784
return JSONResponse(content=response)
7885
except Exception as e:
7986
logger.exception("Error in fetch_chart_data_with_filters: %s", str(e))

src/api/common/database/sqldb_service.py

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -235,11 +235,10 @@ async def fetch_chart_data(chart_filters: ChartFilters = ''):
235235
# charts pt1
236236
nested_json1 = (
237237
df.groupby(['id', 'chart_name', 'chart_type']).apply(
238-
lambda x: x[['name', 'value', 'unit_of_measurement']].to_dict(orient='records'), include_groups=False).reset_index(
239-
name='chart_value')
238+
lambda x: x[['name', 'value', 'unit_of_measurement']].to_dict(orient='records'), include_groups=False).reset_index()
240239
)
240+
nested_json1.columns = ['id', 'chart_name', 'chart_type', 'chart_value']
241241
result1 = nested_json1.to_dict(orient='records')
242-
243242
sql_stmt = f'''SELECT TOP 1 WITH TIES
244243
mined_topic as name, 'TOPICS' as id, 'Trending Topics' as chart_name, 'table' as chart_type,
245244
lower(sentiment) as average_sentiment,
@@ -258,12 +257,17 @@ async def fetch_chart_data(chart_filters: ChartFilters = ''):
258257
df = pd.DataFrame(rows, columns=column_names)
259258

260259
# charts pt2
261-
nested_json2 = (
262-
df.groupby(['id', 'chart_name', 'chart_type']).apply(
263-
lambda x: x[['name', 'call_frequency', 'average_sentiment']].to_dict(orient='records'), include_groups=False).reset_index(
264-
name='chart_value')
265-
)
266-
result2 = nested_json2.to_dict(orient='records')
260+
if not df.empty:
261+
nested_json2 = (
262+
df.groupby(['id', 'chart_name', 'chart_type']).apply(
263+
lambda x: x[['name', 'call_frequency', 'average_sentiment']].to_dict(orient='records'),
264+
include_groups=False
265+
).reset_index()
266+
)
267+
nested_json2.columns = ['id', 'chart_name', 'chart_type', 'chart_value']
268+
result2 = nested_json2.to_dict(orient='records')
269+
else:
270+
result2 = []
267271

268272
where_clause = where_clause.replace('mined_topic', 'topic')
269273
sql_stmt = f'''select top 15 key_phrase as text,
@@ -293,15 +297,19 @@ async def fetch_chart_data(chart_filters: ChartFilters = ''):
293297

294298
df = df.head(15)
295299

296-
nested_json3 = (
297-
df.groupby(['id', 'chart_name', 'chart_type']).apply(
298-
lambda x: x[['text', 'size', 'average_sentiment']].to_dict(orient='records'), include_groups=False).reset_index(
299-
name='chart_value')
300-
)
301-
result3 = nested_json3.to_dict(orient='records')
300+
if not df.empty:
301+
nested_json3 = (
302+
df.groupby(['id', 'chart_name', 'chart_type']).apply(
303+
lambda x: x[['text', 'size', 'average_sentiment']].to_dict(orient='records'),
304+
include_groups=False
305+
).reset_index()
306+
)
307+
nested_json3.columns = ['id', 'chart_name', 'chart_type', 'chart_value']
308+
result3 = nested_json3.to_dict(orient='records')
309+
else:
310+
result3 = []
302311

303312
final_result = result1 + result2 + result3
304-
305313
return final_result
306314

307315
finally:

src/tests/api/api/test_api_routes.py

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,16 @@ def test_fetch_filter_data_basic(create_test_client):
4343
def test_fetch_chart_data_with_filters_basic(create_test_client):
4444
with patch("api.api_routes.ChartService") as MockChartService:
4545
mock_instance = MockChartService.return_value
46-
mock_instance.fetch_chart_data_with_filters = AsyncMock(return_value={"filtered": True})
46+
mock_instance.fetch_chart_data_with_filters = AsyncMock(return_value=[
47+
{
48+
"id": "TOTAL_CALLS",
49+
"chart_name": "Total Calls",
50+
"chart_type": "card",
51+
"chart_value": [
52+
{"name": "Total Calls", "value": float("nan"), "unit_of_measurement": ""}
53+
]
54+
}
55+
])
4756

4857
client = create_test_client()
4958
payload = {
@@ -54,9 +63,18 @@ def test_fetch_chart_data_with_filters_basic(create_test_client):
5463
}
5564
}
5665
response = client.post("/fetchChartDataWithFilters", json=payload)
57-
66+
expected = [
67+
{
68+
"id": "TOTAL_CALLS",
69+
"chart_name": "Total Calls",
70+
"chart_type": "card",
71+
"chart_value": [
72+
{"name": "Total Calls", "value": None, "unit_of_measurement": ""}
73+
]
74+
}
75+
]
5876
assert response.status_code == 200
59-
assert response.json() == {"filtered": True}
77+
assert response.json() == expected
6078

6179
def test_fetch_chart_data_with_filters_error(create_test_client):
6280
with patch("api.api_routes.ChartService") as MockChartService:

0 commit comments

Comments
 (0)