using EgwCoreLib.Utils; using Microsoft.Extensions.Configuration; using MP.Core.DTO; using MP.Data.DbModels.Utils; using MP.Data.Repository.Utils; using StackExchange.Redis; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MP.Data.Services.Utils { public class StatsAggrService : BaseServ, IStatsAggrService { #region Public Constructors public StatsAggrService( IConfiguration config, IConnectionMultiplexer redis, IStatsAggrRepository repo) : base(config, redis) { _className = "StatsAggr"; _repo = repo; } #endregion Public Constructors #region Public Methods /// public async Task> GetFiltAsync(DateTime dtStart, DateTime dtEnd) { return await TraceAsync($"{_className}.GetFilt", async (activity) => { return await GetOrSetCacheAsync( $"{_redisBaseKey}:{_className}:DT:{dtStart:yyyyMMdd}:{dtEnd:yyyyMMdd}", async () => await _repo.GetFiltAsync(dtStart, dtEnd), UltraLongCache ); }); } /// public async Task>> GetParetoStatsWeekAsync() { return await TraceAsync($"{_className}.GetDailyParetoStats", async (activity) => { return await GetOrSetCacheAsync( $"{_redisBaseKey}:{_className}:ParetoWeek", async () => await GetParetoDataAsync(), LongCache ); }); } /// public async Task GetRangeAsync() { return await TraceAsync($"{_className}.GetRange", async (activity) => { return await GetOrSetCacheAsync( $"{_redisBaseKey}:{_className}:Range", async () => await _repo.GetRangeAsync(), UltraFastCache ); }); } /// public async Task UpsertManyAsync(List listRecords, bool removeOld) { return await TraceAsync($"{_className}.UpsertMany", async (activity) => { string operation = "UpsertMany"; var success = await _repo.UpsertManyAsync(listRecords, removeOld); activity?.SetTag("db.operation", operation); if (success > 0) { await ClearCacheAsync($"{_redisBaseKey}:{_className}:*"); } return success; }); } #endregion Public Methods #region Protected Methods /// /// metodo locale per recupero e trasformazione dati da includere con processo generare di tracking & cache /// /// protected async Task>> GetParetoDataAsync() { Dictionary> result = new(); DateTime oggi = DateTime.Today; var rawData = await GetFiltAsync(oggi.AddDays(-7), oggi); // calcolo le varie statistiche... var pDestRequest = rawData.GroupBy(x => x.Destination) .Select(g => new StatDataDTO { Label = g.Key, Value = g.Sum(x => x.RequestCount) }) .OrderByDescending(x => x.Value) .ToList(); result.Add("Dest.Request (#)", pDestRequest); var pDestDuration = rawData.GroupBy(x => x.Destination) .Select(g => new StatDataDTO { Label = g.Key, Value = g.Sum(x => x.RequestCount * x.AvgDuration) }) .OrderByDescending(x => x.Value) .ToList(); result.Add("Dest.Duration (ms)", pDestDuration); return result; } #endregion Protected Methods #region Private Fields private readonly string _className; private readonly IStatsAggrRepository _repo; #endregion Private Fields } }