DD.WellWorkover.Cloud/AsbCloudInfrastructure/Repository/DetectedOperationRepository.cs

202 lines
6.6 KiB
C#
Raw Normal View History

2024-02-08 11:38:25 +05:00
using AsbCloudApp.Data.DetectedOperation;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Repositories;
using AsbCloudApp.Requests;
using AsbCloudApp.Services;
using AsbCloudDb;
using AsbCloudDb.Model;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Repository;
public class DetectedOperationRepository : CrudRepositoryBase<DetectedOperationDto, DetectedOperation>,
IDetectedOperationRepository
2024-02-08 11:38:25 +05:00
{
private readonly ITelemetryService telemetryService;
public DetectedOperationRepository(IAsbCloudDbContext context,
2024-02-08 11:38:25 +05:00
ITelemetryService telemetryService)
: base(context)
2024-02-08 11:38:25 +05:00
{
this.telemetryService = telemetryService;
}
public async Task<int> Delete(int idUser, DetectedOperationByTelemetryRequest request, CancellationToken token)
{
var query = BuildQuery(request);
dbContext.Set<DetectedOperation>().RemoveRange(query);
return await dbContext.SaveChangesAsync(token);
2024-02-08 11:38:25 +05:00
}
public async Task<int> DeleteRange(int idUser, IEnumerable<int> ids, CancellationToken token)
{
var query = dbContext.Set<DetectedOperation>()
2024-02-08 11:38:25 +05:00
.Where(e => ids.Contains( e.Id));
dbContext.Set<DetectedOperation>()
2024-02-08 11:38:25 +05:00
.RemoveRange(query);
return await dbContext.SaveChangesAsync(token);
2024-02-08 11:38:25 +05:00
}
public async Task<IDictionary<int, DateTimeOffset>> GetLastDetectedDatesAsync(CancellationToken token) =>
await dbContext.Set<DetectedOperation>()
.GroupBy(o => o.IdTelemetry)
.Select(g => new
{
IdTelemetry = g.Key,
LastDate = g.Max(o => o.DateEnd)
})
.ToDictionaryAsync(x => x.IdTelemetry, x => x.LastDate, token);
2024-02-08 11:38:25 +05:00
public async Task<IEnumerable<DetectedOperationDto>> Get(DetectedOperationByTelemetryRequest request, CancellationToken token)
{
var query = BuildQuery(request)
.Include(o => o.OperationCategory);
var entities = await query.ToArrayAsync(token);
var dtos = entities.Select(Convert);
2024-02-08 11:38:25 +05:00
return dtos;
}
public async Task<int> Insert(int? idUser, IEnumerable<DetectedOperationDto> dtos, CancellationToken token)
{
if(!dtos.Any())
return 0;
var entities = dtos.Select(Convert);
var dbset = dbContext.Set<DetectedOperation>();
2024-02-08 11:38:25 +05:00
foreach(var entity in entities)
{
entity.Id = default;
dbset.Add(entity);
}
return await dbContext.SaveChangesWithExceptionHandling(token);
2024-02-08 11:38:25 +05:00
}
public async Task<int> Update(int idUser, IEnumerable<DetectedOperationDto> dtos, CancellationToken token)
{
if (!dtos.Any())
return 0;
var ids = dtos
.Select(o => o.Id)
.Distinct()
.ToArray();
if (ids.Any(id => id == default))
throw new ArgumentInvalidException(nameof(dtos), "Все записи должны иметь Id");
if (ids.Length != dtos.Count())
throw new ArgumentInvalidException(nameof(dtos), "Все записи должны иметь уникальные Id");
var dbSet = dbContext.Set<DetectedOperation>();
2024-02-08 11:38:25 +05:00
var existingEntitiesCount = await dbSet
.Where(o => ids.Contains(o.Id))
.CountAsync(token);
if (ids.Length != existingEntitiesCount)
throw new ArgumentInvalidException(nameof(dtos), "Все записи должны существовать в БД");
var entities = dtos
.Select(Convert)
.ToArray();
var entries = new Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<DetectedOperation>[entities.Length];
for(var i = 0; i < entities.Length; i++)
entries[i] = dbSet.Update(entities[i]);
var result = await dbContext.SaveChangesWithExceptionHandling(token);
2024-02-08 11:38:25 +05:00
for (var i = 0; i < entries.Length; i++)
entries[i].State = EntityState.Detached;
return result;
}
public async Task<int> UpdateOrInsert(int idUser, IEnumerable<DetectedOperationDto> dtos, CancellationToken token)
{
var result = 0;
var itemsToInsert = dtos.Where(e => e.Id == 0);
if (itemsToInsert.Any())
result += await Insert(idUser, itemsToInsert, token);
var itemsToUpdate = dtos.Where(e => e.Id != 0);
if (itemsToUpdate.Any())
result += await Update(idUser, itemsToUpdate, token);
return result;
}
private IQueryable<DetectedOperation> BuildQuery(DetectedOperationByTelemetryRequest request)
{
var query = dbContext.Set<DetectedOperation>()
2024-02-08 11:38:25 +05:00
.Where(o => o.IdTelemetry == request.IdTelemetry);
if (request.IdsCategories.Any())
query = query.Where(o => request.IdsCategories.Contains(o.IdCategory));
if (request.GeDepthStart is not null)
query = query.Where(o => o.DepthStart >= request.GeDepthStart);
if (request.LeDepthEnd is not null)
query = query.Where(o => o.DepthEnd <= request.LeDepthEnd);
if (request.GeDateStart is not null)
{
var geDate = request.GeDateStart.Value.ToUniversalTime();
query = query.Where(o => o.DateStart >= geDate);
}
if (request.LeDateEnd is not null)
{
var leDate = request.LeDateEnd.Value.ToUniversalTime();
query = query.Where(o => o.DateEnd <= leDate);
}
if (request.SortFields?.Any() == true)
{
query = query.SortBy(request.SortFields);
}
else
query = query
.OrderBy(o => o.DateStart)
.ThenBy(o => o.DepthStart);
if (request.Skip.HasValue)
query = query.Skip((int)request.Skip);
if (request.Take.HasValue)
query = query.Take((int)request.Take);
return query;
}
protected override DetectedOperationDto Convert(DetectedOperation src)
2024-02-08 11:38:25 +05:00
{
var timezone = telemetryService.GetTimezone(src.IdTelemetry);
var dto = src.Adapt<DetectedOperationDto>();
dto.DateStart = src.DateStart.ToOffset(timezone.Offset);
dto.DateEnd = src.DateEnd.ToOffset(timezone.Offset);
2024-02-08 11:38:25 +05:00
return dto;
}
protected override DetectedOperation Convert(DetectedOperationDto src)
2024-02-08 11:38:25 +05:00
{
var entity = src.Adapt<DetectedOperation>();
entity.DateStart = src.DateStart.ToUniversalTime();
entity.DateEnd = src.DateEnd.ToUniversalTime();
2024-02-08 11:38:25 +05:00
return entity;
}
}