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
3 changes: 2 additions & 1 deletion AirAware.Tests/Controllers/ReadingControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using AirAware.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;

Expand All @@ -23,7 +24,7 @@ public ReadingControllerTests()
.Options;

_context = new AppDbContext(options);
_controller = new ReadingController();
_controller = new ReadingController(new Mock<ILogger<ReadingController>>().Object);
_mockCalculator = new Mock<IAqiCalculator>();
}

Expand Down
4 changes: 3 additions & 1 deletion AirAware.Tests/Controllers/StationControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
using AirAware.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;

namespace AirAware.Tests.Controllers;
Expand All @@ -20,7 +22,7 @@ public StationControllerTests()
.Options;

_context = new AppDbContext(options);
_controller = new StationController();
_controller = new StationController(new Mock<ILogger<StationController>>().Object);
}

public void Dispose()
Expand Down
57 changes: 48 additions & 9 deletions AirAware/Controllers/ReadingController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,25 @@ namespace AirAware.Controllers;
[Route("api/v1")]
public class ReadingController: ControllerBase
{
private readonly ILogger<ReadingController> _logger;

public ReadingController(ILogger<ReadingController> logger)
{
_logger = logger;
}

[HttpGet]
[Route("readings")]
public async Task<IActionResult> GetAsync([FromServices] AppDbContext context)
{
_logger.LogInformation("Fetching all readings");

var readings = await context
.Readings
.AsNoTracking()
.ToListAsync();

_logger.LogInformation("Retrieved {Count} readings", readings.Count);
return Ok(readings);
}

Expand All @@ -29,14 +40,21 @@ public async Task<IActionResult> GetByIdAsync(
[FromRoute] Guid id
)
{
_logger.LogInformation("Fetching reading with ID: {ReadingId}", id);

var reading = await context
.Readings
.AsNoTracking()
.FirstOrDefaultAsync(r => r.Id == id);

return reading == null
? NotFound()
: Ok(reading);
if (reading == null)
{
_logger.LogWarning("Reading with ID {ReadingId} not found", id);
return NotFound();
}

_logger.LogInformation("Successfully retrieved reading with ID: {ReadingId}", id);
return Ok(reading);
}

[HttpPost("readings")]
Expand All @@ -46,20 +64,29 @@ public async Task<IActionResult> PostAsync(
[FromBody] CreateReadingViewModel model
)
{
if (!ModelState.IsValid)
_logger.LogInformation("Creating new reading for station {StationId}", model.StationId);

if (!ModelState.IsValid)
{
_logger.LogWarning("Invalid model state for reading creation");
return BadRequest("Invalid data provided.");
}

var station = await context
.Stations
.AsNoTracking()
.FirstOrDefaultAsync(s => s.Id == model.StationId);

if (station == null)
if (station == null)
{
_logger.LogWarning("Station with ID {StationId} does not exist", model.StationId);
return BadRequest("Station with the provided ID does not exist.");
}

double? pm10 = model.Pm10;
if (!pm10.HasValue && !string.IsNullOrWhiteSpace(model.RawPayload))
{
_logger.LogDebug("Attempting to extract PM10 from raw payload");
try
{
using var doc = System.Text.Json.JsonDocument.Parse(model.RawPayload);
Expand All @@ -71,11 +98,13 @@ [FromBody] CreateReadingViewModel model
pm10 = val10b;
else if (root.TryGetProperty("pm10_atm", out var p10c) && p10c.TryGetDouble(out var val10c))
pm10 = val10c;
// add provider specific paths here

if (pm10.HasValue)
_logger.LogDebug("Extracted PM10 value: {Pm10}", pm10.Value);
}
catch
catch (Exception ex)
{
// parsing failed — ignore and continue (we already have pm25)
_logger.LogWarning(ex, "Failed to parse PM10 from raw payload");
}
}

Expand All @@ -91,8 +120,11 @@ [FromBody] CreateReadingViewModel model
{
await context.Readings.AddAsync(reading);
await context.SaveChangesAsync();

_logger.LogInformation("Reading {ReadingId} created successfully for station {StationId}", reading.Id, reading.StationId);

// compute AQI synchronously
_logger.LogDebug("Calculating AQI for reading {ReadingId}", reading.Id);
var (final, pm25Result, pm10Result) = aqiCalculator.Calculate(reading);

var aqiRecord = new AqiRecord
Expand All @@ -114,12 +146,19 @@ [FromBody] CreateReadingViewModel model
{
await context.AqiRecords.AddAsync(aqiRecord);
await context.SaveChangesAsync();
_logger.LogInformation("AQI record created for reading {ReadingId} with value {AqiValue} ({Category})",
reading.Id, aqiRecord.AqiValue, aqiRecord.Category);
}
else
{
_logger.LogDebug("AQI record already exists for reading {ReadingId}", reading.Id);
}

return Created($"api/v1/readings/{reading.Id}", new { reading, aqi = aqiRecord });
Copy link

Copilot AI Feb 13, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If an AQI record already exists for this ReadingId, the response still returns the newly computed aqiRecord instance, which may not match what’s persisted (and ignores existing). Consider returning existing when present (or overwriting it) so the API response reflects the stored data.

Copilot uses AI. Check for mistakes.
}
catch (Exception)
catch (Exception ex)
{
_logger.LogError(ex, "Error creating reading for station {StationId}", model.StationId);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
Expand Down
66 changes: 57 additions & 9 deletions AirAware/Controllers/StationController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,25 @@ namespace AirAware.Controllers;
[Route("api/v1")]
public class StationController: ControllerBase
{
private readonly ILogger<StationController> _logger;

public StationController(ILogger<StationController> logger)
{
_logger = logger;
}

[HttpGet]
[Route("stations")]
public async Task<IActionResult> GetAsync([FromServices] AppDbContext context)
{
_logger.LogInformation("Fetching all stations");

var stations = await context
.Stations
.AsNoTracking()
.ToListAsync();

_logger.LogInformation("Retrieved {Count} stations", stations.Count);
return Ok(stations);
}

Expand All @@ -28,14 +39,21 @@ public async Task<IActionResult> GetByIdAsync(
[FromRoute] Guid id
)
{
_logger.LogInformation("Fetching station with ID: {StationId}", id);

var station = await context
.Stations
.AsNoTracking()
.FirstOrDefaultAsync(s => s.Id == id);

return station == null
? NotFound()
: Ok(station);
if (station == null)
{
_logger.LogWarning("Station with ID {StationId} not found", id);
return NotFound();
}

_logger.LogInformation("Successfully retrieved station with ID: {StationId}", id);
return Ok(station);
}

[HttpPost("stations")]
Expand All @@ -44,8 +62,13 @@ public async Task<IActionResult> PostAsync(
[FromBody] CreateStationViewModel model
)
{
if (!ModelState.IsValid)
_logger.LogInformation("Creating new station: {StationName}", model.Name);

if (!ModelState.IsValid)
{
_logger.LogWarning("Invalid model state for station creation");
return BadRequest();
}

var station = new Station
{
Expand All @@ -60,10 +83,13 @@ [FromBody] CreateStationViewModel model
{
await context.Stations.AddAsync(station);
await context.SaveChangesAsync();

_logger.LogInformation("Station {StationId} created successfully: {StationName}", station.Id, station.Name);
return Created($"api/v1/stations/{station.Id}", station);
}
catch (Exception)
catch (Exception ex)
{
_logger.LogError(ex, "Error creating station: {StationName}", model.Name);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
Expand All @@ -76,15 +102,23 @@ public async Task<IActionResult> PutAsync(
[FromRoute] Guid id
)
{
if (!ModelState.IsValid)
_logger.LogInformation("Updating station with ID: {StationId}", id);

if (!ModelState.IsValid)
{
_logger.LogWarning("Invalid model state for station update");
return BadRequest();
}

var station = await context
.Stations
.FirstOrDefaultAsync(s => s.Id == id);

if (station == null)
{
_logger.LogWarning("Station with ID {StationId} not found for update", id);
return NotFound();
}

try
{
Expand All @@ -103,10 +137,12 @@ [FromRoute] Guid id

await context.SaveChangesAsync();

_logger.LogInformation("Station {StationId} updated successfully", id);
return Ok(station);
}
catch (Exception)
catch (Exception ex)
{
_logger.LogError(ex, "Error updating station {StationId}", id);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
Expand All @@ -118,9 +154,15 @@ public async Task<IActionResult> GetLatestAqiForStation(
[FromRoute] Guid id
)
{
_logger.LogInformation("Fetching latest AQI for station {StationId}", id);

// Ensure station exists
var station = await context.Stations.AsNoTracking().FirstOrDefaultAsync(s => s.Id == id);
if (station == null) return NotFound("Station not found.");
if (station == null)
{
_logger.LogWarning("Station {StationId} not found", id);
return NotFound("Station not found.");
}

// Get latest AQI record for this station, including its reading
var latest = await context.AqiRecords
Copy link

Copilot AI Feb 13, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The query starting here orders AqiRecords before a Join(...). Ordering is not guaranteed to be preserved through a join, so with the later FirstOrDefaultAsync() this can return a non-latest record. Apply the ordering after the join/selection (e.g., order by ar.Aqi.ComputedAt right before FirstOrDefaultAsync).

Copilot uses AI. Check for mistakes.
Expand All @@ -141,8 +183,14 @@ [FromRoute] Guid id
})
.FirstOrDefaultAsync();

if (latest == null) return NotFound("No AQI records for station.");
if (latest == null)
{
_logger.LogWarning("No AQI records found for station {StationId}", id);
return NotFound("No AQI records for station.");
}

_logger.LogInformation("Retrieved latest AQI for station {StationId}: {AqiValue} ({Category})",
id, latest.AqiValue, latest.Category);
return Ok(latest);
}
}
Loading