Skip to content

Commit

Permalink
Added historic calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
Breno RdV committed Jun 26, 2024
1 parent bc46c8a commit 488393d
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 30 deletions.
16 changes: 8 additions & 8 deletions Raccoon.Ninja.AzFn.DataApi/DataLatestHbA1cFunc.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,23 +30,23 @@ public async Task<IActionResult> RunAsync(
"%CosmosAggregateContainerName%",
Connection = "CosmosConnectionString",
SqlQuery =
"SELECT TOP 1 * FROM c WHERE c.docType = 1 and c.status = 1 and c.hbA1c.status = 1 ORDER BY c.createdAt DESC"
"SELECT TOP 1 * FROM c WHERE c.docType = 1 and c.full.status = 1 and c.full.hbA1c.status = 1 ORDER BY c.createdAt DESC"
)]
IEnumerable<StatisticDataPoint> latestSuccessCalculations, [CosmosDBInput(
IEnumerable<StatisticDataPointDocument> latestSuccessCalculations, [CosmosDBInput(
"%CosmosDatabaseName%",
"%CosmosAggregateContainerName%",
Connection = "CosmosConnectionString",
SqlQuery =
"SELECT TOP 1 * FROM c WHERE c.docType = 1 and c.status = 1 and c.hbA1c.status = 2 ORDER BY c.createdAt DESC"
"SELECT TOP 1 * FROM c WHERE c.docType = 1 and c.full.status = 1 and c.full.hbA1c.status = 2 ORDER BY c.createdAt DESC"
)]
IEnumerable<StatisticDataPoint> latestPartialSuccessCalculations)
IEnumerable<StatisticDataPointDocument> latestPartialSuccessCalculations)
{
_logger.LogInformation("Data Latest HbA1c API call received. Request by IP: {Ip}",
req.HttpContext.Connection.RemoteIpAddress);

StatisticDataPoint latestSuccessful = null;
StatisticDataPointDocument latestSuccessful = null;

StatisticDataPoint latestPartialSuccessful = null;
StatisticDataPointDocument latestPartialSuccessful = null;

try
{
Expand All @@ -62,8 +62,8 @@ public async Task<IActionResult> RunAsync(

return new OkObjectResult(new DataLatestHbA1CFuncResponse
{
LatestSuccessful = latestSuccessful?.ToLegacyHbA1cCalculation(),
LatestPartialSuccessful = latestPartialSuccessful?.ToLegacyHbA1cCalculation()
LatestSuccessful = latestSuccessful?.Full.ToLegacyHbA1cCalculation(),
LatestPartialSuccessful = latestPartialSuccessful?.Full.ToLegacyHbA1cCalculation()
});
}
catch (Exception e)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.Linq;
using Raccoon.Ninja.Domain.Core.Entities;
using Raccoon.Ninja.Extensions.MongoDb.ExtensionMethods;
using Raccoon.Ninja.Extensions.MongoDb.Models;
Expand All @@ -8,24 +9,33 @@ namespace Raccoon.Ninja.AzFn.ScheduledTasks.ExtensionMethods;
public static class ListExtensions
{
/// <summary>
/// Converts a list of native Nightscout MongoDB documents to a list of entities owned by
/// this repo (<see cref="GlucoseReading"/>).
/// Converts a list of native Nightscout MongoDB documents to a list of entities owned by
/// this repo (<see cref="GlucoseReading" />).
/// </summary>
/// <param name="documents">Documents that will be converted</param>
/// <param name="previousReading">Previous GlucoseReading. The value will be used to calculate the delta</param>
/// <returns>Converted list</returns>
public static IEnumerable<GlucoseReading> ToGlucoseReadings(this IList<NightScoutMongoDocument> documents, GlucoseReading previousReading)
public static IEnumerable<GlucoseReading> ToGlucoseReadings(this IList<NightScoutMongoDocument> documents,
GlucoseReading previousReading)
{
var previous = previousReading ?? new GlucoseReading();

foreach (var mongoDbDoc in documents)
{
var current = mongoDbDoc.ToGlucoseReading(previous.Value);

if (current is null) continue;

yield return current;
previous = current;
}
}

public static IList<GlucoseReading> GetLastDays(this IList<GlucoseReading> readings, int days)
{
var lastDate = readings.Max(r => r.ReadTimestampUtcAsDateTime);
var firstDate = lastDate.AddDays(-days);

return readings.Where(r => r.ReadTimestampUtcAsDateTime >= firstDate).ToList();
}
}
49 changes: 37 additions & 12 deletions Raccoon.Ninja.AzFn.ScheduledTasks/StatisticsCalculationFunc.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Linq;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using Raccoon.Ninja.AzFn.ScheduledTasks.ExtensionMethods;
using Raccoon.Ninja.Domain.Core.Calculators;
using Raccoon.Ninja.Domain.Core.Calculators.Abstractions;
using Raccoon.Ninja.Domain.Core.Converters;
Expand All @@ -28,7 +29,7 @@ public StatisticsCalculationFunc(ILogger<StatisticsCalculationFunc> logger)
"%CosmosAggregateContainerName%",
Connection = "CosmosConnectionString",
CreateIfNotExists = false)]
public StatisticDataPoint Run(
public StatisticDataPointDocument Run(
[TimerTrigger("0 0 0 * * *"
#if DEBUG
, RunOnStartup = true
Expand All @@ -41,14 +42,14 @@ public StatisticDataPoint Run(
Connection = "CosmosConnectionString",
SqlQuery = "SELECT TOP 33120 * FROM c ORDER BY c.readAt DESC"
)]
IEnumerable<GlucoseReading> readings,
IEnumerable<GlucoseReading> readingsFetcher,
[CosmosDBInput(
"%CosmosDatabaseName%",
"%CosmosAggregateContainerName%",
Connection = "CosmosConnectionString",
SqlQuery = "SELECT TOP 1 * FROM c WHERE c.docType = 1 and c.status = 1 ORDER BY c.createdAt DESC"
SqlQuery = "SELECT TOP 1 * FROM c WHERE c.docType = 1 and c.full.status = 1 ORDER BY c.createdAt DESC"
)]
IEnumerable<StatisticDataPoint> prevStatisticalDataPointFetch
IEnumerable<StatisticDataPointDocument> prevStatisticalDataPointFetch
)
{
var referenceDate = DateOnly.FromDateTime(DateTime.UtcNow);
Expand All @@ -59,18 +60,26 @@ IEnumerable<StatisticDataPoint> prevStatisticalDataPointFetch
{
var previousCalculations = prevStatisticalDataPointFetch.FirstOrDefault();

var sortedGlucoseValues = readings.ToSortedValueArray();

var chain = BaseCalculatorHandler.BuildChain();

var calculatedData = chain.Handle(new CalculationData
{
GlucoseValues = sortedGlucoseValues
});
var readings = readingsFetcher.ToList();

var result = EntityConverter.ToStatisticDataPoint(calculatedData, referenceDate, previousCalculations);
var fullResult = CalculateStatistics(readings, chain, referenceDate, previousCalculations?.Full);
var last30DaysResult = CalculateStatistics(readings.GetLastDays(3), chain, referenceDate,
previousCalculations?.Last30Days);
var last15DaysResult = CalculateStatistics(readings.GetLastDays(2), chain, referenceDate,
previousCalculations?.Last15Days);
var last7DaysResult = CalculateStatistics(readings.GetLastDays(1), chain, referenceDate,
previousCalculations?.Last7Days);

return result;
return new StatisticDataPointDocument
{
ReferenceDate = referenceDate,
Full = fullResult,
Last30Days = last30DaysResult,
Last15Days = last15DaysResult,
Last7Days = last7DaysResult
};
}
catch (Exception e)
{
Expand All @@ -83,4 +92,20 @@ IEnumerable<StatisticDataPoint> prevStatisticalDataPointFetch
_logger.LogTrace("Statistic data calculation for {ReferenceDate} finished!", referenceDate);
}
}

private StatisticDataPoint CalculateStatistics(
IEnumerable<GlucoseReading> readings,
BaseCalculatorHandler chain,
DateOnly referenceDate,
StatisticDataPoint previousCalculations)
{
var sortedGlucoseValues = readings.ToSortedValueArray();
var calculatedData = chain.Handle(new CalculationData
{
GlucoseValues = sortedGlucoseValues
});

var result = EntityConverter.ToStatisticDataPoint(calculatedData, referenceDate, previousCalculations);
return result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,6 @@ namespace Raccoon.Ninja.Domain.Core.Entities.StatisticalDataPoint;

public record StatisticDataPoint : BaseEntity
{
[JsonPropertyName("docType")]
public DocumentType DocType { get; init; } = DocumentType.StatisticalData;

[JsonPropertyName("referenceDate")]
public DateOnly ReferenceDate { get; init; }

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,25 @@
namespace Raccoon.Ninja.Domain.Core.Entities.StatisticalDataPoint;
using System.Text.Json.Serialization;
using Raccoon.Ninja.Domain.Core.Enums;

public record StatisticDataPointDocument();
namespace Raccoon.Ninja.Domain.Core.Entities.StatisticalDataPoint;

public record StatisticDataPointDocument : BaseControlledEntity
{
[JsonPropertyName("docType")]
public DocumentType DocType { get; init; } = DocumentType.StatisticalData;

[JsonPropertyName("referenceDate")]
public DateOnly ReferenceDate { get; init; }

[JsonPropertyName("full")]
public StatisticDataPoint Full { get; init; }

[JsonPropertyName("last30days")]
public StatisticDataPoint Last30Days { get; init; }

[JsonPropertyName("last15days")]
public StatisticDataPoint Last15Days { get; init; }

[JsonPropertyName("last7days")]
public StatisticDataPoint Last7Days { get; init; }
}

0 comments on commit 488393d

Please sign in to comment.