diff --git a/AsbCloudApp/Repositories/IDataSaubStatRepository.cs b/AsbCloudApp/Repositories/IDataSaubStatRepository.cs index d0e3c5a7..b25675c7 100644 --- a/AsbCloudApp/Repositories/IDataSaubStatRepository.cs +++ b/AsbCloudApp/Repositories/IDataSaubStatRepository.cs @@ -1,4 +1,5 @@ using AsbCloudApp.Data; +using AsbCloudApp.Services; using System; using System.Collections.Generic; using System.Threading; @@ -9,7 +10,7 @@ namespace AsbCloudApp.Repositories /// /// Репозиторий работы с данными из таблицы t_data_daub_stat /// - public interface IDataSaubStatRepository + public interface IDataSaubStatRepository : ITelemetryDataEditorService { /// /// Получение записей по ключу телеметрии diff --git a/AsbCloudApp/Repositories/IDetectedOperationRepository.cs b/AsbCloudApp/Repositories/IDetectedOperationRepository.cs index c588a168..51a96966 100644 --- a/AsbCloudApp/Repositories/IDetectedOperationRepository.cs +++ b/AsbCloudApp/Repositories/IDetectedOperationRepository.cs @@ -1,18 +1,18 @@ -using System; +using AsbCloudApp.Data; using AsbCloudApp.Data.DetectedOperation; using AsbCloudApp.Requests; +using AsbCloudApp.Services; +using System; using System.Collections.Generic; -using System.Threading.Tasks; using System.Threading; -using AsbCloudApp.Data; -using AsbCloudApp.Data.WellOperation; +using System.Threading.Tasks; namespace AsbCloudApp.Repositories; /// /// Таблица автоматически определенных операций /// -public interface IDetectedOperationRepository +public interface IDetectedOperationRepository : ITelemetryDataEditorService { /// /// Добавление нескольких записей @@ -21,7 +21,7 @@ public interface IDetectedOperationRepository /// /// количество добавленных Task InsertRangeAsync(IEnumerable dtos, CancellationToken token); - + /// /// Обновить несколько записей /// @@ -37,7 +37,7 @@ public interface IDetectedOperationRepository /// /// Task DeleteRangeAsync(IEnumerable ids, CancellationToken token); - + /// /// Получить автоматически определенные операции по телеметрии /// @@ -60,7 +60,7 @@ public interface IDetectedOperationRepository /// /// Task> GetLastDetectedDatesAsync(CancellationToken token); - + /// /// Удалить операции /// diff --git a/AsbCloudApp/Repositories/IDrillTestRepository.cs b/AsbCloudApp/Repositories/IDrillTestRepository.cs index b7dce27b..d7b5d1b7 100644 --- a/AsbCloudApp/Repositories/IDrillTestRepository.cs +++ b/AsbCloudApp/Repositories/IDrillTestRepository.cs @@ -1,5 +1,6 @@ using AsbCloudApp.Data.SAUB; using AsbCloudApp.Requests; +using AsbCloudApp.Services; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -9,7 +10,7 @@ namespace AsbCloudApp.Repositories /// /// репозиторий по работе с данными drill_test /// - public interface IDrillTestRepository + public interface IDrillTestRepository : ITelemetryDataEditorService { /// /// Получить данные drill_test в соответствии с параметрами запроса diff --git a/AsbCloudApp/Repositories/IGtrRepository.cs b/AsbCloudApp/Repositories/IGtrRepository.cs index 7ed3df25..fcda4be2 100644 --- a/AsbCloudApp/Repositories/IGtrRepository.cs +++ b/AsbCloudApp/Repositories/IGtrRepository.cs @@ -5,13 +5,14 @@ using System.Threading; using System.Threading.Tasks; using AsbCloudApp.Requests; using AsbCloudApp.Data; +using AsbCloudApp.Services; namespace AsbCloudApp.Repositories { /// /// данные ГТИ /// - public interface IGtrRepository + public interface IGtrRepository : ITelemetryDataEditorService { /// /// добавить данные (для панели бурильщика) diff --git a/AsbCloudApp/Repositories/ILimitingParameterRepository.cs b/AsbCloudApp/Repositories/ILimitingParameterRepository.cs index 63706248..dcc2725a 100644 --- a/AsbCloudApp/Repositories/ILimitingParameterRepository.cs +++ b/AsbCloudApp/Repositories/ILimitingParameterRepository.cs @@ -1,15 +1,16 @@ using AsbCloudApp.Data; using AsbCloudApp.Requests; +using AsbCloudApp.Services; using System.Collections.Generic; -using System.Threading.Tasks; using System.Threading; +using System.Threading.Tasks; namespace AsbCloudApp.Repositories { /// /// Репозиторий по ограничивающим параметрам с фильтрацией /// - public interface ILimitingParameterRepository + public interface ILimitingParameterRepository : ITelemetryDataEditorService { /// /// Получение списка ограничивающих параметров по идентификатору скважины diff --git a/AsbCloudApp/Requests/TelemetryPartDeleteRequest.cs b/AsbCloudApp/Requests/TelemetryPartDeleteRequest.cs new file mode 100644 index 00000000..1ac2519f --- /dev/null +++ b/AsbCloudApp/Requests/TelemetryPartDeleteRequest.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; + +namespace AsbCloudApp.Requests; + +/// +/// Параметры запроса на удаление куска телеметрии +/// +public class TelemetryPartDeleteRequest : IValidatableObject +{ + /// + /// ключ телеметрии + /// + public int IdTelemetry { get; set; } + + /// + /// greater or equal then Date. Must be set one of GeDate or LeDate + /// + public DateTimeOffset? GeDate { get; set; } + + /// + /// less or equal then Date. Must be set one of GeDate or LeDate + /// + public DateTimeOffset? LeDate { get; set; } + + /// + /// Валидация входящих данных + /// + /// + /// + public IEnumerable Validate(ValidationContext validationContext) + { + if (IdTelemetry == 0) + yield return new ValidationResult($"IdTelemetry must be defined"); + if (!GeDate.HasValue && !LeDate.HasValue) + yield return new ValidationResult($"GeDate or LeDate must be defined"); + } +} diff --git a/AsbCloudApp/Services/IMessageService.cs b/AsbCloudApp/Services/IMessageService.cs index a461b3e8..0a6557ba 100644 --- a/AsbCloudApp/Services/IMessageService.cs +++ b/AsbCloudApp/Services/IMessageService.cs @@ -10,7 +10,7 @@ namespace AsbCloudApp.Services /// /// Сервис сообщений панели оператора /// - public interface IMessageService + public interface IMessageService : ITelemetryDataEditorService { /// /// Получить сообщения по параметрам diff --git a/AsbCloudApp/Services/ITelemetryDataEditorService.cs b/AsbCloudApp/Services/ITelemetryDataEditorService.cs new file mode 100644 index 00000000..d9d5df24 --- /dev/null +++ b/AsbCloudApp/Services/ITelemetryDataEditorService.cs @@ -0,0 +1,19 @@ +using AsbCloudApp.Requests; +using System.Threading; +using System.Threading.Tasks; + +namespace AsbCloudApp.Services; + +/// +/// Сервис по работе с данными телеметрии +/// +public interface ITelemetryDataEditorService +{ + /// + /// Удаление части телеметрии по запросу + /// + /// + /// + /// + Task DeleteAsync(TelemetryPartDeleteRequest request, CancellationToken token); +} diff --git a/AsbCloudApp/Services/ITelemetryDataService.cs b/AsbCloudApp/Services/ITelemetryDataService.cs index 6b42c490..f9e3c4d7 100644 --- a/AsbCloudApp/Services/ITelemetryDataService.cs +++ b/AsbCloudApp/Services/ITelemetryDataService.cs @@ -11,7 +11,7 @@ namespace AsbCloudApp.Services /// сервис данных тех. процесса /// /// - public interface ITelemetryDataService where TDto : ITelemetryData + public interface ITelemetryDataService : ITelemetryDataEditorService where TDto : ITelemetryData { /// diff --git a/AsbCloudApp/Services/IWitsRepository.cs b/AsbCloudApp/Services/IWitsRepository.cs index e9a81278..e6b409c1 100644 --- a/AsbCloudApp/Services/IWitsRepository.cs +++ b/AsbCloudApp/Services/IWitsRepository.cs @@ -1,4 +1,5 @@ using AsbCloudApp.Data; +using AsbCloudApp.Requests; using System; using System.Collections.Generic; using System.Threading; @@ -9,7 +10,7 @@ namespace AsbCloudApp.Services /// /// The wits record repository. /// - public interface IWitsRecordRepository + public interface IWitsRecordRepository : ITelemetryDataEditorService where TDto : ITelemetryData { /// diff --git a/AsbCloudInfrastructure/DependencyInjection.cs b/AsbCloudInfrastructure/DependencyInjection.cs index b539e561..9fbe1721 100644 --- a/AsbCloudInfrastructure/DependencyInjection.cs +++ b/AsbCloudInfrastructure/DependencyInjection.cs @@ -493,6 +493,8 @@ namespace AsbCloudInfrastructure services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); diff --git a/AsbCloudInfrastructure/Repository/DataSaubStatRepository.cs b/AsbCloudInfrastructure/Repository/DataSaubStatRepository.cs index 9d252647..d5159bf6 100644 --- a/AsbCloudInfrastructure/Repository/DataSaubStatRepository.cs +++ b/AsbCloudInfrastructure/Repository/DataSaubStatRepository.cs @@ -1,5 +1,6 @@ using AsbCloudApp.Data; using AsbCloudApp.Repositories; +using AsbCloudApp.Requests; using AsbCloudApp.Services; using AsbCloudDb.Model; using Mapster; @@ -81,5 +82,32 @@ namespace AsbCloudInfrastructure.Repository return entity; } + + private IQueryable BuildQuery(TelemetryPartDeleteRequest request) + { + var query = db.Set() + .Where(o => o.IdTelemetry == request.IdTelemetry); + + if (request.LeDate is not null) + { + var leDate = request.LeDate.Value.ToUniversalTime(); + query = query.Where(o => o.DateStart <= leDate); + } + + if (request.GeDate is not null) + { + var geDate = request.GeDate.Value.ToUniversalTime(); + query = query.Where(o => o.DateEnd >= geDate); + } + + return query; + } + + public async Task DeleteAsync(TelemetryPartDeleteRequest request, CancellationToken token) + { + var query = BuildQuery(request); + db.Set().RemoveRange(query); + return await db.SaveChangesAsync(token); + } } } diff --git a/AsbCloudInfrastructure/Repository/DetectedOperationRepository.cs b/AsbCloudInfrastructure/Repository/DetectedOperationRepository.cs index b788dbda..10889a3d 100644 --- a/AsbCloudInfrastructure/Repository/DetectedOperationRepository.cs +++ b/AsbCloudInfrastructure/Repository/DetectedOperationRepository.cs @@ -15,7 +15,8 @@ using AsbCloudApp.Data; namespace AsbCloudInfrastructure.Repository; -public class DetectedOperationRepository : CrudRepositoryBase, IDetectedOperationRepository +public class DetectedOperationRepository + : CrudRepositoryBase, IDetectedOperationRepository { private readonly ITelemetryService telemetryService; @@ -33,6 +34,13 @@ public class DetectedOperationRepository : CrudRepositoryBase DeleteAsync(TelemetryPartDeleteRequest request, CancellationToken token) + { + var query = BuildQuery(request); + dbContext.Set().RemoveRange(query); + return await dbContext.SaveChangesAsync(token); + } + public async Task> GetPageAsync(DetectedOperationByTelemetryRequest request, CancellationToken token) { var skip = request.Skip ?? 0; @@ -112,7 +120,27 @@ public class DetectedOperationRepository : CrudRepositoryBase BuildQuery(TelemetryPartDeleteRequest request) + { + var query = dbContext.Set() + .Where(o => o.IdTelemetry == request.IdTelemetry); + + if (request.LeDate is not null) + { + var leDate = request.LeDate.Value.ToUniversalTime(); + query = query.Where(o => o.DateStart <= leDate); + } + + if (request.GeDate is not null) + { + var geDate = request.GeDate.Value.ToUniversalTime(); + query = query.Where(o => o.DateEnd >= geDate); + } + + return query; + } + private static DetectedOperationDto Convert(DetectedOperation src, TimeSpan offset) { var dto = src.Adapt(); diff --git a/AsbCloudInfrastructure/Repository/DrillTestRepository.cs b/AsbCloudInfrastructure/Repository/DrillTestRepository.cs index ce27ff0f..a7bc82a0 100644 --- a/AsbCloudInfrastructure/Repository/DrillTestRepository.cs +++ b/AsbCloudInfrastructure/Repository/DrillTestRepository.cs @@ -84,5 +84,33 @@ namespace AsbCloudInfrastructure.Repository dto.TimeStampStart = dto.TimeStampStart.ToRemoteDateTime(dto.Telemetry?.TimeZone?.Hours ?? 0); return dto; } + + //TODO: Унифицировать модели данных телеметрии.Чтобы в будущем унифицировать репозитории данных телеметрии. + private IQueryable BuildQuery(TelemetryPartDeleteRequest request) + { + var query = db.Set() + .Where(o => o.IdTelemetry == request.IdTelemetry); + + if (request.LeDate is not null) + { + var leDate = request.LeDate.Value.ToUniversalTime(); + query = query.Where(o => o.TimeStampStart <= leDate); + } + + if (request.GeDate is not null) + { + var geDate = request.GeDate.Value.ToUniversalTime(); + query = query.Where(o => o.TimeStampStart >= geDate); + } + + return query; + } + + public async Task DeleteAsync(TelemetryPartDeleteRequest request, CancellationToken token) + { + var query = BuildQuery(request); + db.Set().RemoveRange(query); + return await db.SaveChangesAsync(token); + } } } diff --git a/AsbCloudInfrastructure/Repository/GtrWitsRepository.cs b/AsbCloudInfrastructure/Repository/GtrWitsRepository.cs index 94c89cb1..54b19e6b 100644 --- a/AsbCloudInfrastructure/Repository/GtrWitsRepository.cs +++ b/AsbCloudInfrastructure/Repository/GtrWitsRepository.cs @@ -1,9 +1,13 @@ +using AsbCloudApp.Data; using AsbCloudApp.Data.GTR; +using AsbCloudApp.Exceptions; using AsbCloudApp.Repositories; +using AsbCloudApp.Requests; using AsbCloudApp.Services; using AsbCloudDb; using AsbCloudDb.Model; using AsbCloudDb.Model.GTR; +using Mapster; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Concurrent; @@ -12,11 +16,6 @@ using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; -using AsbCloudApp.Exceptions; -using AsbCloudApp.Requests; -using Mapster; -using AsbCloudApp.Data; -using System.ComponentModel.DataAnnotations; namespace AsbCloudInfrastructure.Repository { @@ -87,7 +86,7 @@ namespace AsbCloudInfrastructure.Repository public async Task GetRangeAsync(int idWell, DateTimeOffset? geDate, DateTimeOffset? leDate, CancellationToken token) { var telemetry = telemetryService.GetOrDefaultTelemetryByIdWell(idWell); - + if (telemetry is null) return null; @@ -109,7 +108,7 @@ namespace AsbCloudInfrastructure.Repository }); var range = await groupedQuery.FirstOrDefaultAsync(token); - if (range is null) + if (range is null) return null; var result = new DatesRangeDto @@ -121,16 +120,16 @@ namespace AsbCloudInfrastructure.Repository } private async Task> GetAsync(int idWell, GtrRequest request, CancellationToken token) - where TEntity : WitsItemBase + where TEntity : WitsItemBase where TType : notnull { var telemetry = telemetryService.GetOrDefaultTelemetryByIdWell(idWell); - + if (telemetry is null) return Enumerable.Empty(); if (telemetry.TimeZone is null) - throw new ArgumentInvalidException(nameof(idWell),$"Telemetry id: {telemetry.Id} can't find timezone"); + throw new ArgumentInvalidException(nameof(idWell), $"Telemetry id: {telemetry.Id} can't find timezone"); var query = BuildQuery(telemetry.Id, request); @@ -147,7 +146,7 @@ namespace AsbCloudInfrastructure.Repository var interval = TimeSpan.FromSeconds(10); var timezoneOffset = TimeSpan.FromHours(telemetry.TimeZone.Hours); - + var dtos = entities .GroupBy(e => e.DateTime.Ticks / interval.Ticks) .Select(groupByInterval => @@ -166,9 +165,9 @@ namespace AsbCloudInfrastructure.Repository } private IQueryable BuildQuery(int idTelemetry, GtrRequest request) - where TEntity : WitsItemBase + where TEntity : WitsItemBase where TType : notnull - { + { var query = db.Set() .Where(e => e.IdTelemetry == idTelemetry); @@ -183,9 +182,9 @@ namespace AsbCloudInfrastructure.Repository else { var lastDate = query - .OrderBy(e=>e.DateTime) + .OrderBy(e => e.DateTime) .LastOrDefault() - ?.DateTime + ?.DateTime ?? DateTimeOffset.UtcNow; var dateBegin = lastDate.AddSeconds(-request.IntervalSec); var dateEnd = lastDate; @@ -329,10 +328,10 @@ namespace AsbCloudInfrastructure.Repository var dateTime = record.Date.ToUtcDateTimeOffset(timezoneHours); foreach (var item in record.Items) { - if (cacheTelemetryItems?.TryGetValue((record.Id, item.Key), out var cacheItem) == true) + if (cacheTelemetryItems?.TryGetValue((record.Id, item.Key), out var cacheItem) == true) if (Math.Abs((dateTime - cacheItem.Date).TotalSeconds) < 1) - continue; - + continue; + if (item.Value.Value is string valueString) { var entity = MakeEntity(record.Id, item.Key, idTelemetry, dateTime, valueString); @@ -362,14 +361,15 @@ namespace AsbCloudInfrastructure.Repository if (ints.Any()) await db.Database.ExecInsertOrIgnoreAsync(db.Set(), ints, token); } - catch(Exception ex) + catch (Exception ex) { Trace.TraceError("Exception while saving GTR Wits data", ex); } cache.AddOrUpdate(idTelemetry, (_) => MakeNewCache(dtos), - (_, oldItemsDictionary) => { + (_, oldItemsDictionary) => + { foreach (var record in dtos) foreach (var item in record.Items) { @@ -398,7 +398,8 @@ namespace AsbCloudInfrastructure.Repository { var items = dtos.SelectMany(record => record.Items.Select( - item => new WitsItemRecordDto { + item => new WitsItemRecordDto + { IdItem = item.Key, IdRecord = record.Id, Date = record.Date, @@ -409,7 +410,7 @@ namespace AsbCloudInfrastructure.Repository .GroupBy(item => (item.IdRecord, item.IdItem)); var pairs = groups.Select(group => new KeyValuePair<(int, int), WitsItemRecordDto>( - group.Key, + group.Key, group.OrderByDescending(item => item.Date).First())); return new ConcurrentDictionary<(int, int), WitsItemRecordDto>(pairs); @@ -439,6 +440,47 @@ namespace AsbCloudInfrastructure.Repository Value = (TValue)dto.Value.Value, }; + private IQueryable BuildQuery(TelemetryPartDeleteRequest request) + where TEntity : WitsItemBase + where TValue : notnull + { + var query = db.Set().Where(i => i.IdTelemetry == request.IdTelemetry); + + if (request.LeDate is not null) + { + var leDate = request.LeDate.Value.ToUniversalTime(); + query = query.Where(o => o.DateTime <= leDate); + } + + if (request.GeDate is not null) + { + var geDate = request.GeDate.Value.ToUniversalTime(); + query = query.Where(o => o.DateTime >= geDate); + } + + return query; + } + + public async Task DeleteAsync(TelemetryPartDeleteRequest request, CancellationToken token) + { + var result = 0; + result += await DeleteAsync(request, token); + result += await DeleteAsync(request, token); + result += await DeleteAsync(request, token); + + return result; + } + + private async Task DeleteAsync(TelemetryPartDeleteRequest request, CancellationToken token) + where TEntity : WitsItemBase + where TType : notnull + { + var query = BuildQuery(request); + db.Set().RemoveRange(query); + return await db.SaveChangesAsync(token); + } + + private class WitsRequest { public int IdTelemetry { get; set; } diff --git a/AsbCloudInfrastructure/Repository/LimitingParameterRepository.cs b/AsbCloudInfrastructure/Repository/LimitingParameterRepository.cs index 0ee3e574..858558df 100644 --- a/AsbCloudInfrastructure/Repository/LimitingParameterRepository.cs +++ b/AsbCloudInfrastructure/Repository/LimitingParameterRepository.cs @@ -17,10 +17,17 @@ namespace AsbCloudInfrastructure.Repository private readonly IAsbCloudDbContext context; public LimitingParameterRepository(IAsbCloudDbContext context) - { + { this.context = context; } + public async Task DeleteAsync(TelemetryPartDeleteRequest request, CancellationToken token) + { + var query = BuildQuery(request); + context.Set().RemoveRange(query); + return await context.SaveChangesAsync(token); + } + public async Task> GetLimitingParametersAsync(LimitingParameterRequest request, WellDto wellDto, CancellationToken token) { var timezoneOffset = wellDto.Timezone.Hours; @@ -74,6 +81,26 @@ namespace AsbCloudInfrastructure.Repository return query; } + + private IQueryable BuildQuery(TelemetryPartDeleteRequest request) + { + var query = context.Set() + .Where(o => o.IdTelemetry == request.IdTelemetry); + + if (request.LeDate is not null) + { + var leDate = request.LeDate.Value.ToUniversalTime(); + query = query.Where(o => o.DateStart <= leDate); + } + + if (request.GeDate is not null) + { + var geDate = request.GeDate.Value.ToUniversalTime(); + query = query.Where(o => o.DateEnd >= geDate); + } + + return query; + } } } diff --git a/AsbCloudInfrastructure/Repository/WitsRecordRepository.cs b/AsbCloudInfrastructure/Repository/WitsRecordRepository.cs index 9eca40bf..46ea461a 100644 --- a/AsbCloudInfrastructure/Repository/WitsRecordRepository.cs +++ b/AsbCloudInfrastructure/Repository/WitsRecordRepository.cs @@ -1,3 +1,4 @@ +using AsbCloudApp.Requests; using AsbCloudApp.Services; using AsbCloudDb.Model; using Mapster; @@ -20,7 +21,7 @@ namespace AsbCloudInfrastructure.Repository private readonly IAsbCloudDbContext db; private readonly ITelemetryService telemetryService; - private static readonly ConcurrentDictionary cache = new (); + private static readonly ConcurrentDictionary cache = new(); public WitsRecordRepository(IAsbCloudDbContext db, ITelemetryService telemetryService) { @@ -58,6 +59,33 @@ namespace AsbCloudInfrastructure.Repository return data.Select(d => Convert(d, timezoneHours)); } + private IQueryable BuildQuery(TelemetryPartDeleteRequest request) + { + var query = db.Set() + .Where(o => o.IdTelemetry == request.IdTelemetry); + + if (request.LeDate is not null) + { + var leDate = request.LeDate.Value.ToUniversalTime(); + query = query.Where(o => o.DateTime <= leDate); + } + + if (request.GeDate is not null) + { + var geDate = request.GeDate.Value.ToUniversalTime(); + query = query.Where(o => o.DateTime >= geDate); + } + + return query; + } + + public async Task DeleteAsync(TelemetryPartDeleteRequest request, CancellationToken token) + { + var query = BuildQuery(request); + dbset.RemoveRange(query); + return await db.SaveChangesAsync(token); + } + public TDto? GetLastOrDefault(int idTelemetry) => cache.GetValueOrDefault(idTelemetry); @@ -66,7 +94,7 @@ namespace AsbCloudInfrastructure.Repository if (!dtos.Any()) return; - cache.AddOrUpdate(idTelemetry, dtos.Last(), (_,_) => dtos.OrderBy(r => r.DateTime).Last()); + cache.AddOrUpdate(idTelemetry, dtos.Last(), (_, _) => dtos.OrderBy(r => r.DateTime).Last()); var timezoneHours = telemetryService.GetTimezone(idTelemetry).Hours; var entities = dtos @@ -81,7 +109,7 @@ namespace AsbCloudInfrastructure.Repository .Select(e => e.DateTime) .OrderBy(d => d) .ToArrayAsync(token); - + foreach (var entity in entities) { if (!existingEntities.Any(e => e == entity.DateTime)) @@ -101,9 +129,9 @@ namespace AsbCloudInfrastructure.Repository (dt.Millisecond + random.Next(1, 283)) % 1000, dt.Offset); dbset.Add(entity); - } + } } - + await db.SaveChangesAsync(token); } @@ -126,8 +154,8 @@ namespace AsbCloudInfrastructure.Repository { var entity = dto.Adapt(); entity.Recid = GetRecId(dto); - entity.IdTelemetry = idTelemetry; - entity.DateTime = dto.DateTime.ToUtcDateTimeOffset(timezoneHours); + entity.IdTelemetry = idTelemetry; + entity.DateTime = dto.DateTime.ToUtcDateTimeOffset(timezoneHours); return entity; } diff --git a/AsbCloudInfrastructure/Services/SAUB/MessageService.cs b/AsbCloudInfrastructure/Services/SAUB/MessageService.cs index f4edfc66..e19e6a54 100644 --- a/AsbCloudInfrastructure/Services/SAUB/MessageService.cs +++ b/AsbCloudInfrastructure/Services/SAUB/MessageService.cs @@ -96,7 +96,7 @@ namespace AsbCloudInfrastructure.Services.SAUB var allUsers = await memoryCache.GetOrCreateBasicAsync(db.Set(), token); var users = allUsers.Where(u => u.IdTelemetry == telemetry.Id); - var eventsDict = events.ToDictionary(x=>x.IdEvent, x => x); + var eventsDict = events.ToDictionary(x => x.IdEvent, x => x); var usersDict = users.ToDictionary(x => x.IdUser, x => x); var messagesDtoList = new List(); @@ -142,7 +142,7 @@ namespace AsbCloudInfrastructure.Services.SAUB return Task.CompletedTask; var telemetry = telemetryService.GetOrCreateTelemetryByUid(uid); - + foreach (var dto in dtos) { var entity = dto.Adapt(); @@ -154,6 +154,33 @@ namespace AsbCloudInfrastructure.Services.SAUB return db.SaveChangesAsync(token); } + + private IQueryable BuildQuery(TelemetryPartDeleteRequest request) + { + var query = db.Set() + .Where(o => o.IdTelemetry == request.IdTelemetry); + + if (request.GeDate is not null) + { + var geDate = request.GeDate.Value.ToUniversalTime(); + query = query.Where(o => o.DateTime <= geDate); + } + + if (request.LeDate is not null) + { + var leDate = request.LeDate.Value.ToUniversalTime(); + query = query.Where(o => o.DateTime >= leDate); + } + + return query; + } + + public async Task DeleteAsync(TelemetryPartDeleteRequest request, CancellationToken token) + { + var query = BuildQuery(request); + db.Set().RemoveRange(query); + return await db.SaveChangesAsync(token); + } } } diff --git a/AsbCloudInfrastructure/Services/SAUB/TelemetryDataBaseService.cs b/AsbCloudInfrastructure/Services/SAUB/TelemetryDataBaseService.cs index 88b11941..b3705109 100644 --- a/AsbCloudInfrastructure/Services/SAUB/TelemetryDataBaseService.cs +++ b/AsbCloudInfrastructure/Services/SAUB/TelemetryDataBaseService.cs @@ -1,6 +1,7 @@ using AsbCloudApp.Data; using AsbCloudApp.Exceptions; using AsbCloudApp.Repositories; +using AsbCloudApp.Requests; using AsbCloudApp.Services; using AsbCloudDb; using AsbCloudDb.Model; @@ -11,8 +12,6 @@ using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; -using AsbCloudApp.Requests; -using Mapster; namespace AsbCloudInfrastructure.Services.SAUB { @@ -160,12 +159,12 @@ namespace AsbCloudInfrastructure.Services.SAUB public async Task> GetByTelemetryAsync(int idTelemetry, TelemetryDataRequest request, CancellationToken token) { var timezone = telemetryService.GetTimezone(idTelemetry); - + var cache = telemetryDataCache.GetOrDefault(idTelemetry, request); - - if(cache is not null) + + if (cache is not null) return cache; - + var query = BuildQuery(idTelemetry, request); var entities = await query @@ -219,10 +218,30 @@ namespace AsbCloudInfrastructure.Services.SAUB return query; } + private IQueryable BuildQuery(TelemetryPartDeleteRequest request) + { + var query = db.Set() + .Where(o => o.IdTelemetry == request.IdTelemetry); + + if (request.GeDate is not null) + { + var geDate = request.GeDate.Value.ToUniversalTime(); + query = query.Where(o => o.DateTime <= geDate); + } + + if (request.LeDate is not null) + { + var leDate = request.LeDate.Value.ToUniversalTime(); + query = query.Where(o => o.DateTime >= leDate); + } + + return query; + } + /// public async Task GetRangeAsync(int idWell, DateTimeOffset geDate, DateTimeOffset? leDate, CancellationToken token) { - var telemetry = telemetryService.GetOrDefaultTelemetryByIdWell(idWell) + var telemetry = telemetryService.GetOrDefaultTelemetryByIdWell(idWell) ?? throw new ArgumentInvalidException(nameof(idWell), $"По скважине id:{idWell} нет телеметрии"); if ((DateTimeOffset.UtcNow - geDate) < TimeSpan.FromHours(12)) @@ -231,7 +250,7 @@ namespace AsbCloudInfrastructure.Services.SAUB var cachedRange = telemetryDataCache.GetOrDefaultCachedDataDateRange(telemetry.Id); if (cachedRange is not null) { - var datesRange = new DatesRangeDto {From = cachedRange.From, To = cachedRange.To }; + var datesRange = new DatesRangeDto { From = cachedRange.From, To = cachedRange.To }; if (geDate >= cachedRange.From) datesRange.From = geDate.ToOffset(cachedRange.From.Offset); @@ -246,7 +265,7 @@ namespace AsbCloudInfrastructure.Services.SAUB .Where(entity => entity.IdTelemetry == telemetry.Id) .Where(entity => entity.DateTime >= geDate.ToUniversalTime()); - if(leDate.HasValue) + if (leDate.HasValue) query = query.Where(entity => entity.DateTime <= leDate.Value.ToUniversalTime()); var groupQuery = query @@ -282,5 +301,11 @@ namespace AsbCloudInfrastructure.Services.SAUB protected abstract TEntity Convert(TDto src, double timezoneOffset); + public async Task DeleteAsync(TelemetryPartDeleteRequest request, CancellationToken token) + { + var query = BuildQuery(request); + db.Set().RemoveRange(query); + return await db.SaveChangesAsync(token); + } } } diff --git a/AsbCloudInfrastructure/Services/SAUB/TelemetryDataEditorService.cs b/AsbCloudInfrastructure/Services/SAUB/TelemetryDataEditorService.cs new file mode 100644 index 00000000..bcbf4c67 --- /dev/null +++ b/AsbCloudInfrastructure/Services/SAUB/TelemetryDataEditorService.cs @@ -0,0 +1,82 @@ +using AsbCloudApp.Data.SAUB; +using AsbCloudApp.Data.WITS; +using AsbCloudApp.Repositories; +using AsbCloudApp.Requests; +using AsbCloudApp.Services; +using System.Threading; +using System.Threading.Tasks; + +namespace AsbCloudInfrastructure.Services.SAUB +{ + /// + /// Сервис по работе с данными телеметрии + /// + public class TelemetryDataEditorService : ITelemetryDataEditorService + { + private readonly ITelemetryDataEditorService[] repositories; + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public TelemetryDataEditorService( + ITelemetryDataSaubService dataSaubService, + ITelemetryDataService dataSpinService, + IDataSaubStatRepository dataSaubStatRepository, + IMessageService messageService, + IDrillTestRepository drillTestRepository, + ILimitingParameterRepository limitingParameterRepository, + IDetectedOperationRepository detectedOperationRepository, + IWitsRecordRepository witsRecord1Repository, + IWitsRecordRepository witsRecord7Repository, + IWitsRecordRepository witsRecord8Repository, + IWitsRecordRepository witsRecord50Repository, + IWitsRecordRepository witsRecord60Repository, + IWitsRecordRepository witsRecord61Repository, + IGtrRepository gtrRepository + ) + { + repositories = + [ + dataSaubService, + dataSpinService, + dataSaubStatRepository, + messageService, + drillTestRepository, + limitingParameterRepository, + detectedOperationRepository, + witsRecord1Repository, + witsRecord7Repository, + witsRecord8Repository, + witsRecord50Repository, + witsRecord60Repository, + witsRecord61Repository, + gtrRepository, + ]; + } + + public async Task DeleteAsync(TelemetryPartDeleteRequest request, CancellationToken token) + { + var result = 0; + foreach (var repository in repositories) + { + result += await repository.DeleteAsync(request, token); + } + + return result; + } + } +} diff --git a/AsbCloudWebApi/Controllers/AdminTelemetryController.cs b/AsbCloudWebApi/Controllers/AdminTelemetryController.cs index 1275e2cd..2e9dad91 100644 --- a/AsbCloudWebApi/Controllers/AdminTelemetryController.cs +++ b/AsbCloudWebApi/Controllers/AdminTelemetryController.cs @@ -1,7 +1,10 @@ using AsbCloudApp.Data; +using AsbCloudApp.Requests; using AsbCloudApp.Services; using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using System; using System.Threading; using System.Threading.Tasks; @@ -16,12 +19,15 @@ namespace AsbCloudWebApi.Controllers public class AdminTelemetryController : CrudController> { private readonly ITelemetryService telemetryService; + private readonly ITelemetryDataEditorService telemetryEditorService; public AdminTelemetryController(ICrudRepository service, - ITelemetryService telemetryService) + ITelemetryService telemetryService, + ITelemetryDataEditorService telemetryEditorService) : base(service) { this.telemetryService = telemetryService; + this.telemetryEditorService = telemetryEditorService; } /// @@ -36,5 +42,22 @@ namespace AsbCloudWebApi.Controllers .ConfigureAwait(false); return Ok(count); } + + /// + /// Удаление куска телеметрии по запросу + /// + /// запрос + /// + /// + [HttpDelete("/part")] + [Permission] + [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] + [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)] + public async Task DeleteAsync([FromQuery] TelemetryPartDeleteRequest request,CancellationToken token) + { + var result = await telemetryEditorService.DeleteAsync(request, token); + + return Ok(result); + } } }