Update service che usa i repository
This commit is contained in:
@@ -0,0 +1,141 @@
|
||||
using EgwCoreLib.Utils;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MP.Data.DbModels.Utils;
|
||||
using NLog;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MP.Data.Repository.Utils
|
||||
{
|
||||
public class StatsCodeRepository : BaseRepository, IStatsCodeRepository
|
||||
{
|
||||
#region Public Constructors
|
||||
|
||||
public StatsCodeRepository(IDbContextFactory<MoonPro_UtilsContext> ctxFactory) : base(ctxFactory)
|
||||
{
|
||||
}
|
||||
|
||||
#endregion Public Constructors
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<List<StatsStatusCodeModel>> GetFiltAsync(DateTime dtStart, DateTime dtEnd)
|
||||
{
|
||||
await using var dbCtx = await CreateContextAsync();
|
||||
return await dbCtx
|
||||
.DbSetStatusCode
|
||||
.Where(x => x.Hour >= dtStart && x.Hour <= dtEnd)
|
||||
.AsNoTracking()
|
||||
.OrderBy(x => x.Hour)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DtUtils.Periodo> GetRangeAsync()
|
||||
{
|
||||
await using var dbCtx = await CreateContextAsync();
|
||||
DtUtils.Periodo answ = new DtUtils.Periodo(DtUtils.PeriodSet.Today);
|
||||
var query = dbCtx.DbSetStatusCode.AsQueryable();
|
||||
var minHour = await query.MinAsync(x => x.Hour);
|
||||
var maxHour = await query.MaxAsync(x => x.Hour);
|
||||
answ.Inizio = minHour;
|
||||
answ.Fine = maxHour;
|
||||
// ritorno!
|
||||
return answ;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<int> UpsertManyAsync(List<StatsStatusCodeModel> listRecords, bool removeOld)
|
||||
{
|
||||
if (listRecords == null || !listRecords.Any()) return 0;
|
||||
|
||||
int ans = 0;
|
||||
await using var dbCtx = await CreateContextAsync();
|
||||
await using var tx = await dbCtx.Database.BeginTransactionAsync();
|
||||
|
||||
try
|
||||
{
|
||||
// 1. Calcolo del range temporale della lista in arrivo per limitare la query di ricerca
|
||||
var minHour = listRecords.Min(x => x.Hour);
|
||||
var maxHour = listRecords.Max(x => x.Hour);
|
||||
|
||||
// 2. Se removeOld è true, manteniamo la logica originale (Eliminazione distruttiva)
|
||||
if (removeOld)
|
||||
{
|
||||
// uso direttamente ExecuteDelete quando in EFCore8...
|
||||
#if false
|
||||
await dbCtx
|
||||
.DbSetStatusCode
|
||||
.Where(x => x.Hour >= startDate && x.Hour <= endDate)
|
||||
.ExecuteDeleteAsync();
|
||||
#endif
|
||||
|
||||
var itemsToRemove = await dbCtx.DbSetStatusCode
|
||||
.Where(x => x.Hour >= minHour && x.Hour <= maxHour)
|
||||
.ToListAsync();
|
||||
if (itemsToRemove.Any())
|
||||
{
|
||||
dbCtx.DbSetStatusCode.RemoveRange(itemsToRemove);
|
||||
await dbCtx.SaveChangesAsync(); // Commit parziale per la cancellazione
|
||||
}
|
||||
}
|
||||
|
||||
// 3. LOGICA DI UPSERT (Merge)
|
||||
// Recuperiamo tutti i record esistenti nel database che cadono nello stesso range temporale
|
||||
// Questo ci permette di confrontare ciò che arriva con ciò che è già presente.
|
||||
var existingRecords = await dbCtx.DbSetStatusCode
|
||||
.Where(x => x.Hour >= minHour && x.Hour <= maxHour)
|
||||
.ToListAsync();
|
||||
|
||||
// Creiamo un dizionario per ricerca rapida O(1) basato sulla chiave univoca (Dest + Hour)
|
||||
// Usiamo una Tupla come chiave del dizionario
|
||||
var lookup = existingRecords.ToDictionary(
|
||||
x => (x.Destination, x.Type, x.Hour, x.StatusCode),
|
||||
x => x
|
||||
);
|
||||
|
||||
foreach (var incoming in listRecords)
|
||||
{
|
||||
var key = (incoming.Destination, incoming.Type, incoming.Hour, incoming.StatusCode);
|
||||
if (lookup.TryGetValue(key, out var existing))
|
||||
{
|
||||
// --- CASO: UPDATE ---
|
||||
existing.Count = incoming.Count;
|
||||
}
|
||||
else
|
||||
{
|
||||
// --- CASO: INSERT ---
|
||||
await dbCtx.DbSetStatusCode.AddAsync(incoming);
|
||||
}
|
||||
}
|
||||
// 4. Salvataggio finale
|
||||
ans = await dbCtx.SaveChangesAsync();
|
||||
|
||||
// Commit della transazione
|
||||
await tx.CommitAsync();
|
||||
|
||||
// Pulizia memoria per evitare che il ChangeTracker diventi troppo pesante nei loop lunghi
|
||||
dbCtx.ChangeTracker.Clear();
|
||||
|
||||
return ans;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await tx.RollbackAsync();
|
||||
Log.Error(ex, "Error during UpsertManyAsync");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion Public Methods
|
||||
|
||||
#region Protected Fields
|
||||
|
||||
protected static NLog.Logger Log = LogManager.GetCurrentClassLogger();
|
||||
|
||||
#endregion Protected Fields
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
using EgwCoreLib.Utils;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MP.Data.DbModels.Utils;
|
||||
using NLog;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MP.Data.Repository.Utils
|
||||
{
|
||||
public class StatsErrRepository : BaseRepository, IStatsErrRepository
|
||||
{
|
||||
#region Public Constructors
|
||||
|
||||
public StatsErrRepository(IDbContextFactory<MoonPro_UtilsContext> ctxFactory) : base(ctxFactory)
|
||||
{
|
||||
}
|
||||
|
||||
#endregion Public Constructors
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<List<StatsErrorModel>> GetFiltAsync(DateTime dtStart, DateTime dtEnd)
|
||||
{
|
||||
await using var dbCtx = await CreateContextAsync();
|
||||
return await dbCtx
|
||||
.DbSetStatsError
|
||||
.Where(x => x.Hour >= dtStart && x.Hour <= dtEnd)
|
||||
.AsNoTracking()
|
||||
.OrderBy(x => x.Hour)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DtUtils.Periodo> GetRangeAsync()
|
||||
{
|
||||
await using var dbCtx = await CreateContextAsync();
|
||||
DtUtils.Periodo answ = new DtUtils.Periodo(DtUtils.PeriodSet.Today);
|
||||
var query = dbCtx.DbSetStatsError.AsQueryable();
|
||||
var minHour = await query.MinAsync(x => x.Hour);
|
||||
var maxHour = await query.MaxAsync(x => x.Hour);
|
||||
answ.Inizio = minHour;
|
||||
answ.Fine = maxHour;
|
||||
// ritorno!
|
||||
return answ;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<int> UpsertManyAsync(List<StatsErrorModel> listRecords, bool removeOld)
|
||||
{
|
||||
if (listRecords == null || !listRecords.Any()) return 0;
|
||||
|
||||
int ans = 0;
|
||||
await using var dbCtx = await CreateContextAsync();
|
||||
await using var tx = await dbCtx.Database.BeginTransactionAsync();
|
||||
|
||||
try
|
||||
{
|
||||
// 1. Calcolo del range temporale della lista in arrivo per limitare la query di ricerca
|
||||
var minHour = listRecords.Min(x => x.Hour);
|
||||
var maxHour = listRecords.Max(x => x.Hour);
|
||||
|
||||
// 2. Se removeOld è true, manteniamo la logica originale (Eliminazione distruttiva)
|
||||
if (removeOld)
|
||||
{
|
||||
// uso direttamente ExecuteDelete quando in EFCore8...
|
||||
#if false
|
||||
await dbCtx
|
||||
.DbSetStatsError
|
||||
.Where(x => x.Hour >= startDate && x.Hour <= endDate)
|
||||
.ExecuteDeleteAsync();
|
||||
#endif
|
||||
|
||||
var itemsToRemove = await dbCtx.DbSetStatsError
|
||||
.Where(x => x.Hour >= minHour && x.Hour <= maxHour)
|
||||
.ToListAsync();
|
||||
if (itemsToRemove.Any())
|
||||
{
|
||||
dbCtx.DbSetStatsError.RemoveRange(itemsToRemove);
|
||||
await dbCtx.SaveChangesAsync(); // Commit parziale per la cancellazione
|
||||
}
|
||||
}
|
||||
|
||||
// 3. LOGICA DI UPSERT (Merge)
|
||||
// Recuperiamo tutti i record esistenti nel database che cadono nello stesso range temporale
|
||||
// Questo ci permette di confrontare ciò che arriva con ciò che è già presente.
|
||||
var existingRecords = await dbCtx.DbSetStatsError
|
||||
.Where(x => x.Hour >= minHour && x.Hour <= maxHour)
|
||||
.ToListAsync();
|
||||
|
||||
// Creiamo un dizionario per ricerca rapida O(1) basato sulla chiave univoca (Dest + Hour)
|
||||
// Usiamo una Tupla come chiave del dizionario
|
||||
var lookup = existingRecords.ToDictionary(
|
||||
x => (x.Destination, x.Type, x.Hour, x.ErrorMessage),
|
||||
x => x
|
||||
);
|
||||
|
||||
foreach (var incoming in listRecords)
|
||||
{
|
||||
var key = (incoming.Destination, incoming.Type, incoming.Hour, incoming.ErrorMessage);
|
||||
if (lookup.TryGetValue(key, out var existing))
|
||||
{
|
||||
// --- CASO: UPDATE ---
|
||||
existing.Count = incoming.Count;
|
||||
}
|
||||
else
|
||||
{
|
||||
// --- CASO: INSERT ---
|
||||
await dbCtx.DbSetStatsError.AddAsync(incoming);
|
||||
}
|
||||
}
|
||||
// 4. Salvataggio finale
|
||||
ans = await dbCtx.SaveChangesAsync();
|
||||
|
||||
// Commit della transazione
|
||||
await tx.CommitAsync();
|
||||
|
||||
// Pulizia memoria per evitare che il ChangeTracker diventi troppo pesante nei loop lunghi
|
||||
dbCtx.ChangeTracker.Clear();
|
||||
|
||||
return ans;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await tx.RollbackAsync();
|
||||
Log.Error(ex, "Error during UpsertManyAsync");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion Public Methods
|
||||
|
||||
#region Protected Fields
|
||||
|
||||
protected static NLog.Logger Log = LogManager.GetCurrentClassLogger();
|
||||
|
||||
#endregion Protected Fields
|
||||
}
|
||||
}
|
||||
@@ -20,13 +20,6 @@ namespace MP.Data.Services.Utils
|
||||
/// <param name="dtEnd">Data fine periodo</param>
|
||||
Task<List<StatsAggregatedModel>> GetFiltAsync(DateTime dtStart, DateTime dtEnd);
|
||||
|
||||
/// <summary>
|
||||
/// Restituisce un dizionario di elaborazioni di tipo Pareto su orizzonte settimanale
|
||||
/// Ogni elaborazione contiene Dictionary in forma pareto per una data statistica
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
Task<Dictionary<string, List<StatDataDTO>>> GetParetoStatsWeekAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Restituisce un dizionario di elaborazioni di tipo Pareto su orizzonte giornaliero
|
||||
/// Ogni elaborazione contiene Dictionary in forma pareto per una data statistica
|
||||
@@ -34,19 +27,19 @@ namespace MP.Data.Services.Utils
|
||||
/// <returns></returns>
|
||||
Task<Dictionary<string, List<StatDataDTO>>> GetParetoStatsDayAsync(int numDay);
|
||||
|
||||
/// <summary>
|
||||
/// Restituisce un dizionario di elaborazioni di tipo Pareto su orizzonte settimanale
|
||||
/// Ogni elaborazione contiene Dictionary in forma pareto per una data statistica
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
Task<Dictionary<string, List<StatDataDTO>>> GetParetoStatsWeekAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Recupera il range di periodi valido per le chiamate aggregate.
|
||||
/// Utilizza la cache automaticamente.
|
||||
/// </summary>
|
||||
Task<DtUtils.Periodo> GetRangeAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Inserisce o aggiorna in batch le statistiche aggregate nel database.
|
||||
/// Opzionalmente elimina i record precedenti nel periodo specificato.
|
||||
/// </summary>
|
||||
/// <param name="listRecords">Elenco dei record da inserire/aggiornare</param>
|
||||
/// <param name="removeOld">Se true elimina preventivamente i record nel periodo richiesto</param>
|
||||
Task<int> UpsertManyAsync(List<StatsAggregatedModel> listRecords, bool removeOld);
|
||||
/// <summary>
|
||||
/// Helper conversione dati aggregati in statistiche da inviare a ChartJS
|
||||
/// </summary>
|
||||
@@ -56,6 +49,14 @@ namespace MP.Data.Services.Utils
|
||||
/// <returns></returns>
|
||||
List<ChartSeriesDto> GetTimeSeriesData(List<StatsAggregatedModel> rawData, bool groupMach, bool getCount);
|
||||
|
||||
/// <summary>
|
||||
/// Inserisce o aggiorna in batch le statistiche aggregate nel database.
|
||||
/// Opzionalmente elimina i record precedenti nel periodo specificato.
|
||||
/// </summary>
|
||||
/// <param name="listRecords">Elenco dei record da inserire/aggiornare</param>
|
||||
/// <param name="removeOld">Se true elimina preventivamente i record nel periodo richiesto</param>
|
||||
Task<int> UpsertManyAsync(List<StatsAggregatedModel> listRecords, bool removeOld);
|
||||
|
||||
#endregion Public Methods
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using EgwCoreLib.Utils;
|
||||
using MP.Core.DTO;
|
||||
using MP.Data.DbModels.Utils;
|
||||
using MP.Data.DTO;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MP.Data.Services.Utils
|
||||
{
|
||||
public interface IStatsCodeService
|
||||
{
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>
|
||||
/// Recupera l'elenco delle statistiche StatusCode per un periodo specificato.
|
||||
/// Utilizza la cache automaticamente.
|
||||
/// </summary>
|
||||
/// <param name="dtStart">Data inizio periodo</param>
|
||||
/// <param name="dtEnd">Data fine periodo</param>
|
||||
Task<List<StatsStatusCodeModel>> GetFiltAsync(DateTime dtStart, DateTime dtEnd);
|
||||
|
||||
/// <summary>
|
||||
/// Restituisce un dizionario di elaborazioni di tipo Pareto su orizzonte giornaliero
|
||||
/// Ogni elaborazione contiene Dictionary in forma pareto per una data statistica
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
Task<Dictionary<string, List<StatDataDTO>>> GetParetoStatsDayAsync(int numDay);
|
||||
|
||||
/// <summary>
|
||||
/// Restituisce un dizionario di elaborazioni di tipo Pareto su orizzonte settimanale
|
||||
/// Ogni elaborazione contiene Dictionary in forma pareto per una data statistica
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
Task<Dictionary<string, List<StatDataDTO>>> GetParetoStatsWeekAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Recupera il range di periodi valido per le chiamate StatusCode.
|
||||
/// Utilizza la cache automaticamente.
|
||||
/// </summary>
|
||||
Task<DtUtils.Periodo> GetRangeAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Helper conversione dati aggregati in statistiche da inviare a ChartJS
|
||||
/// </summary>
|
||||
/// <param name="rawData"></param>
|
||||
/// <returns></returns>
|
||||
List<ChartSeriesDto> GetTimeSeriesData(List<StatsStatusCodeModel> rawData);
|
||||
|
||||
/// <summary>
|
||||
/// Inserisce o aggiorna in batch le statistiche StatusCode nel database.
|
||||
/// Opzionalmente elimina i record precedenti nel periodo specificato.
|
||||
/// </summary>
|
||||
/// <param name="listRecords">Elenco dei record da inserire/aggiornare</param>
|
||||
/// <param name="removeOld">Se true elimina preventivamente i record nel periodo richiesto</param>
|
||||
Task<int> UpsertManyAsync(List<StatsStatusCodeModel> listRecords, bool removeOld);
|
||||
|
||||
#endregion Public Methods
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using EgwCoreLib.Utils;
|
||||
using MP.Core.DTO;
|
||||
using MP.Data.DbModels.Utils;
|
||||
using MP.Data.DTO;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MP.Data.Services.Utils
|
||||
{
|
||||
public interface IStatsErrService
|
||||
{
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>
|
||||
/// Recupera l'elenco delle statistiche Error per un periodo specificato.
|
||||
/// Utilizza la cache automaticamente.
|
||||
/// </summary>
|
||||
/// <param name="dtStart">Data inizio periodo</param>
|
||||
/// <param name="dtEnd">Data fine periodo</param>
|
||||
Task<List<StatsErrorModel>> GetFiltAsync(DateTime dtStart, DateTime dtEnd);
|
||||
|
||||
/// <summary>
|
||||
/// Restituisce un dizionario di elaborazioni di tipo Pareto su orizzonte giornaliero
|
||||
/// Ogni elaborazione contiene Dictionary in forma pareto per una data statistica
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
Task<Dictionary<string, List<StatDataDTO>>> GetParetoStatsDayAsync(int numDay);
|
||||
|
||||
/// <summary>
|
||||
/// Restituisce un dizionario di elaborazioni di tipo Pareto su orizzonte settimanale
|
||||
/// Ogni elaborazione contiene Dictionary in forma pareto per una data statistica
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
Task<Dictionary<string, List<StatDataDTO>>> GetParetoStatsWeekAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Recupera il range di periodi valido per le chiamate Error.
|
||||
/// Utilizza la cache automaticamente.
|
||||
/// </summary>
|
||||
Task<DtUtils.Periodo> GetRangeAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Helper conversione dati aggregati in statistiche da inviare a ChartJS
|
||||
/// </summary>
|
||||
/// <param name="rawData"></param>
|
||||
/// <returns></returns>
|
||||
List<ChartSeriesDto> GetTimeSeriesData(List<StatsErrorModel> rawData);
|
||||
|
||||
/// <summary>
|
||||
/// Inserisce o aggiorna in batch le statistiche Error nel database.
|
||||
/// Opzionalmente elimina i record precedenti nel periodo specificato.
|
||||
/// </summary>
|
||||
/// <param name="listRecords">Elenco dei record da inserire/aggiornare</param>
|
||||
/// <param name="removeOld">Se true elimina preventivamente i record nel periodo richiesto</param>
|
||||
Task<int> UpsertManyAsync(List<StatsErrorModel> listRecords, bool removeOld);
|
||||
|
||||
#endregion Public Methods
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
using EgwCoreLib.Utils;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using MP.Core.DTO;
|
||||
using MP.Data.DbModels.Utils;
|
||||
using MP.Data.DTO;
|
||||
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
|
||||
{
|
||||
internal class StatsCodeService : BaseServ, IStatsCodeService
|
||||
{
|
||||
#region Public Constructors
|
||||
|
||||
public StatsCodeService(
|
||||
IConfiguration config,
|
||||
IConnectionMultiplexer redis,
|
||||
IStatsCodeRepository repo) : base(config, redis)
|
||||
{
|
||||
_className = "StatsStatusCode";
|
||||
_repo = repo;
|
||||
}
|
||||
|
||||
#endregion Public Constructors
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<List<StatsStatusCodeModel>> 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
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<Dictionary<string, List<StatDataDTO>>> GetParetoStatsDayAsync(int numDay)
|
||||
{
|
||||
return await TraceAsync($"{_className}.GetParetoStatsDayAsync", async (activity) =>
|
||||
{
|
||||
return await GetOrSetCacheAsync(
|
||||
$"{_redisBaseKey}:{_className}:ParetoDay",
|
||||
async () => await GetParetoDestAsync(numDay),
|
||||
LongCache
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<Dictionary<string, List<StatDataDTO>>> GetParetoStatsWeekAsync()
|
||||
{
|
||||
return await TraceAsync($"{_className}.GetParetoStatsWeekAsync", async (activity) =>
|
||||
{
|
||||
return await GetOrSetCacheAsync(
|
||||
$"{_redisBaseKey}:{_className}:ParetoWeek",
|
||||
async () => await GetParetoDataAsync(),
|
||||
LongCache
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DtUtils.Periodo> GetRangeAsync()
|
||||
{
|
||||
return await TraceAsync($"{_className}.GetRange", async (activity) =>
|
||||
{
|
||||
return await GetOrSetCacheAsync(
|
||||
$"{_redisBaseKey}:{_className}:Range",
|
||||
async () => await _repo.GetRangeAsync(),
|
||||
UltraFastCache
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public List<ChartSeriesDto> GetTimeSeriesData(List<StatsStatusCodeModel> rawData)
|
||||
{
|
||||
DateTime adesso = DateTime.Now;
|
||||
|
||||
List<ChartSeriesDto> series = new();
|
||||
series = rawData
|
||||
.GroupBy(s => new { s.Destination })
|
||||
.Select(group => new ChartSeriesDto
|
||||
{
|
||||
SeriesName = group.Key.Destination,
|
||||
DataPoints = group
|
||||
.OrderBy(p => p.Hour)
|
||||
.Select(p => new chartJsData.chartJsTSerie
|
||||
{
|
||||
x = p.Hour,
|
||||
y = p.Count / (p.Hour.Date.Equals(adesso.Date) ? adesso.TimeOfDay.TotalHours : 24)
|
||||
})
|
||||
.ToList()
|
||||
})
|
||||
.ToList();
|
||||
|
||||
return series;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<int> UpsertManyAsync(List<StatsStatusCodeModel> 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
|
||||
|
||||
/// <summary>
|
||||
/// metodo locale per recupero e trasformazione dati da includere con processo generare di tracking & cache
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
protected async Task<Dictionary<string, List<StatDataDTO>>> GetParetoDataAsync()
|
||||
{
|
||||
Dictionary<string, List<StatDataDTO>> result = new();
|
||||
DateTime oggi = DateTime.Today;
|
||||
int numDays = 7;
|
||||
var rawData = await GetFiltAsync(oggi.AddDays(-numDays), oggi);
|
||||
// calcolo le varie statistiche...
|
||||
var pDestRequest = rawData.GroupBy(x => x.Destination)
|
||||
.Select(g => new StatDataDTO
|
||||
{
|
||||
Label = g.Key,
|
||||
Value = g.Sum(x => x.Count) / numDays
|
||||
})
|
||||
.OrderByDescending(x => x.Value)
|
||||
.ToList();
|
||||
result.Add("Errors (#)", pDestRequest);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
protected async Task<Dictionary<string, List<StatDataDTO>>> GetParetoDestAsync(int numDay)
|
||||
{
|
||||
Dictionary<string, List<StatDataDTO>> result = new();
|
||||
DateTime adesso = DateTime.Now;
|
||||
DateTime start = DateTime.Today.AddDays(-numDay);
|
||||
var rawData = await GetFiltAsync(start, adesso);
|
||||
var numHour = adesso.Subtract(start).TotalHours;
|
||||
// calcolo le varie statistiche...
|
||||
var pDestRequest = rawData.GroupBy(x => x.Destination)
|
||||
.Select(g => new StatDataDTO
|
||||
{
|
||||
Label = g.Key,
|
||||
Value = g.Sum(x => x.Count) / numHour
|
||||
})
|
||||
.OrderByDescending(x => x.Value)
|
||||
.ToList();
|
||||
result.Add("Dest.Request (#/h)", pDestRequest);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
#endregion Protected Methods
|
||||
|
||||
#region Private Fields
|
||||
|
||||
private readonly string _className;
|
||||
private readonly IStatsCodeRepository _repo;
|
||||
|
||||
#endregion Private Fields
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
using EgwCoreLib.Utils;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using MP.Core.DTO;
|
||||
using MP.Data.DbModels.Utils;
|
||||
using MP.Data.DTO;
|
||||
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 StatsErrService : BaseServ, IStatsErrService
|
||||
{
|
||||
#region Public Constructors
|
||||
|
||||
public StatsErrService(
|
||||
IConfiguration config,
|
||||
IConnectionMultiplexer redis,
|
||||
IStatsErrRepository repo) : base(config, redis)
|
||||
{
|
||||
_className = "StatsErr";
|
||||
_repo = repo;
|
||||
}
|
||||
|
||||
#endregion Public Constructors
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<List<StatsErrorModel>> 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
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<Dictionary<string, List<StatDataDTO>>> GetParetoStatsDayAsync(int numDay)
|
||||
{
|
||||
return await TraceAsync($"{_className}.GetParetoStatsDayAsync", async (activity) =>
|
||||
{
|
||||
return await GetOrSetCacheAsync(
|
||||
$"{_redisBaseKey}:{_className}:ParetoDay",
|
||||
async () => await GetParetoDestAsync(numDay),
|
||||
LongCache
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<Dictionary<string, List<StatDataDTO>>> GetParetoStatsWeekAsync()
|
||||
{
|
||||
return await TraceAsync($"{_className}.GetParetoStatsWeekAsync", async (activity) =>
|
||||
{
|
||||
return await GetOrSetCacheAsync(
|
||||
$"{_redisBaseKey}:{_className}:ParetoWeek",
|
||||
async () => await GetParetoDataAsync(),
|
||||
LongCache
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DtUtils.Periodo> GetRangeAsync()
|
||||
{
|
||||
return await TraceAsync($"{_className}.GetRange", async (activity) =>
|
||||
{
|
||||
return await GetOrSetCacheAsync(
|
||||
$"{_redisBaseKey}:{_className}:Range",
|
||||
async () => await _repo.GetRangeAsync(),
|
||||
UltraFastCache
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public List<ChartSeriesDto> GetTimeSeriesData(List<StatsErrorModel> rawData)
|
||||
{
|
||||
DateTime adesso = DateTime.Now;
|
||||
|
||||
List<ChartSeriesDto> series = new();
|
||||
series = rawData
|
||||
.GroupBy(s => new { s.Destination })
|
||||
.Select(group => new ChartSeriesDto
|
||||
{
|
||||
SeriesName = group.Key.Destination,
|
||||
DataPoints = group
|
||||
.OrderBy(p => p.Hour)
|
||||
.Select(p => new chartJsData.chartJsTSerie
|
||||
{
|
||||
x = p.Hour,
|
||||
y = p.Count / (p.Hour.Date.Equals(adesso.Date) ? adesso.TimeOfDay.TotalHours : 24)
|
||||
})
|
||||
.ToList()
|
||||
})
|
||||
.ToList();
|
||||
|
||||
return series;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<int> UpsertManyAsync(List<StatsErrorModel> 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
|
||||
|
||||
/// <summary>
|
||||
/// metodo locale per recupero e trasformazione dati da includere con processo generare di tracking & cache
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
protected async Task<Dictionary<string, List<StatDataDTO>>> GetParetoDataAsync()
|
||||
{
|
||||
Dictionary<string, List<StatDataDTO>> result = new();
|
||||
DateTime oggi = DateTime.Today;
|
||||
int numDays = 7;
|
||||
var rawData = await GetFiltAsync(oggi.AddDays(-numDays), oggi);
|
||||
// calcolo le varie statistiche...
|
||||
var pDestRequest = rawData.GroupBy(x => x.Destination)
|
||||
.Select(g => new StatDataDTO
|
||||
{
|
||||
Label = g.Key,
|
||||
Value = g.Sum(x => x.Count) / numDays
|
||||
})
|
||||
.OrderByDescending(x => x.Value)
|
||||
.ToList();
|
||||
result.Add("Errors (#)", pDestRequest);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
protected async Task<Dictionary<string, List<StatDataDTO>>> GetParetoDestAsync(int numDay)
|
||||
{
|
||||
Dictionary<string, List<StatDataDTO>> result = new();
|
||||
DateTime adesso = DateTime.Now;
|
||||
DateTime start = DateTime.Today.AddDays(-numDay);
|
||||
var rawData = await GetFiltAsync(start, adesso);
|
||||
var numHour = adesso.Subtract(start).TotalHours;
|
||||
// calcolo le varie statistiche...
|
||||
var pDestRequest = rawData.GroupBy(x => x.Destination)
|
||||
.Select(g => new StatDataDTO
|
||||
{
|
||||
Label = g.Key,
|
||||
Value = g.Sum(x => x.Count) / numHour
|
||||
})
|
||||
.OrderByDescending(x => x.Value)
|
||||
.ToList();
|
||||
result.Add("Dest.Request (#/h)", pDestRequest);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
#endregion Protected Methods
|
||||
|
||||
#region Private Fields
|
||||
|
||||
private readonly string _className;
|
||||
private readonly IStatsErrRepository _repo;
|
||||
|
||||
#endregion Private Fields
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user