Merge pull request 'feature/change-log-refactoring' (#280) from feature/change-log-refactoring into dev

Reviewed-on: http://test.digitaldrilling.ru:8080/DDrilling/AsbCloudServer/pulls/280
This commit is contained in:
Никита Фролов 2024-06-05 15:53:25 +05:00
commit e6fdc56750
29 changed files with 602 additions and 416 deletions

View File

@ -6,12 +6,12 @@ namespace AsbCloudApp.Data;
/// <summary> /// <summary>
/// Часть записи описывающая изменение /// Часть записи описывающая изменение
/// </summary> /// </summary>
public abstract class ChangeLogAbstract public class ChangeLogDto<T> where T: IId
{ {
/// <summary> /// <summary>
/// ИД записи /// Запись
/// </summary> /// </summary>
public int Id { get; set; } public required T Item { get; set; }
/// <summary> /// <summary>
/// Автор /// Автор

View File

@ -5,13 +5,18 @@ using System.ComponentModel.DataAnnotations;
namespace AsbCloudApp.Data.ProcessMaps; namespace AsbCloudApp.Data.ProcessMaps;
/// <inheritdoc/> /// <inheritdoc/>
public abstract class ProcessMapPlanBaseDto : ChangeLogAbstract, IId, IWellRelated, IValidatableObject public abstract class ProcessMapPlanBaseDto : IId, IWellRelated, IValidatableObject
{ {
/// <summary> /// <summary>
/// Id скважины /// Id скважины
/// </summary> /// </summary>
public int IdWell { get; set; } public int IdWell { get; set; }
/// <summary>
/// Id записи
/// </summary>
public int Id { get; set; }
/// <summary> /// <summary>
/// Тип секции /// Тип секции
/// </summary> /// </summary>

View File

@ -1,4 +1,5 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Data.ProcessMaps;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -19,8 +20,8 @@ namespace AsbCloudApp.Extensions
/// <param name="items"></param> /// <param name="items"></param>
/// <param name="moment"></param> /// <param name="moment"></param>
/// <returns></returns> /// <returns></returns>
public static IEnumerable<T> WhereActualAtMoment<T>(this IEnumerable<T> items, DateTimeOffset moment) public static IEnumerable<ChangeLogDto<T>> WhereActualAtMoment<T>(this IEnumerable<ChangeLogDto<T>> items, DateTimeOffset moment)
where T : ChangeLogAbstract where T : IId
{ {
var actualItems = items var actualItems = items
.Where(item => item.Creation <= moment) .Where(item => item.Creation <= moment)

View File

@ -0,0 +1,62 @@
using AsbCloudApp.Data;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Repositories;
/// <summary>
/// Интерфейс для работы с объектами, содержащими историю изменений
/// </summary>
/// <typeparam name="TDto"></typeparam>
/// <typeparam name="TRequest"></typeparam>
public interface IChangeLogQueryBuilder<TDto, TRequest>
where TDto : IId
{
/// <summary>
/// Применение запроса
/// </summary>
/// <param name="request">Запрос</param>
/// <returns></returns>
IChangeLogQueryBuilderWithKnownTimezone<TDto, TRequest> ApplyRequest(TRequest request);
/// <summary>
/// Материализация записей
/// </summary>
/// <param name="offset"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<TDto>> GetData(TimeSpan offset, CancellationToken token);
/// <summary>
/// Материализация записей с историей
/// </summary>
/// <param name="offset"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<ChangeLogDto<TDto>>> GetChangeLogData(TimeSpan offset, CancellationToken token);
}
/// <summary>
/// Интерфейс для работы с объектами, содержащими историю изменений. С известной временной зоной
/// </summary>
/// <typeparam name="TDto"></typeparam>
/// <typeparam name="TRequest"></typeparam>
public interface IChangeLogQueryBuilderWithKnownTimezone<TDto, TRequest>: IChangeLogQueryBuilder<TDto, TRequest>
where TDto : IId
{
/// <summary>
/// Материализация записей. Временная зона определяется по запросу из последнего ApplyRequest
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<TDto>> GetData(CancellationToken token);
/// <summary>
/// Материализация записей с историей. Временная зона определяется по запросу из последнего ApplyRequest
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<ChangeLogDto<TDto>>> GetChangeLogData(CancellationToken token);
}

View File

@ -1,9 +1,9 @@
using System; using AsbCloudApp.Data;
using AsbCloudApp.Requests;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Requests;
namespace AsbCloudApp.Repositories; namespace AsbCloudApp.Repositories;
@ -11,41 +11,40 @@ namespace AsbCloudApp.Repositories;
/// Репозиторий для записей с историей /// Репозиторий для записей с историей
/// </summary> /// </summary>
public interface IChangeLogRepository<TDto, TRequest> public interface IChangeLogRepository<TDto, TRequest>
where TDto : ChangeLogAbstract where TDto : IId
where TRequest : ChangeLogBaseRequest
{ {
/// <summary> /// <summary>
/// Добавление записей /// Добавление записей
/// </summary> /// </summary>
/// <param name="idUser"></param> /// <param name="idUser">пользователь, который добавляет</param>
/// <param name="dtos"></param> /// <param name="dtos"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task<int> InsertRange(int idUser, IEnumerable<TDto> dtos, CancellationToken token); Task<int> InsertRange(int idUser, IEnumerable<TDto> dtos, CancellationToken token);
/// <summary> /// <summary>
/// Редактирование записей /// Редактирование записей
/// </summary> /// </summary>
/// <param name="idUser"></param> /// <param name="idUser">пользователь, который редактирует</param>
/// <param name="dtos"></param> /// <param name="dtos"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task<int> UpdateRange(int idUser, IEnumerable<TDto> dtos, CancellationToken token); Task<int> UpdateRange(int idUser, IEnumerable<TDto> dtos, CancellationToken token);
/// <summary> /// <summary>
/// Добавляет Dto у которых id == 0, изменяет dto у которых id != 0 /// Добавляет Dto у которых id == 0, изменяет dto у которых id != 0
/// </summary> /// </summary>
/// <param name="idUser"></param> /// <param name="idUser">пользователь, который редактирует или добавляет</param>
/// <param name="dtos"></param> /// <param name="dtos"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task<int> UpdateOrInsertRange(int idUser, IEnumerable<TDto> dtos, CancellationToken token); Task<int> UpdateOrInsertRange(int idUser, IEnumerable<TDto> dtos, CancellationToken token);
/// <summary> /// <summary>
/// Добавление записей с удалением старых (для импорта) /// Помечает записи как удаленные
/// </summary> /// </summary>
/// <param name="idUser"></param> /// <param name="idUser">пользователь, который чистит</param>
/// <param name="request"></param> /// <param name="request">Фильтр по свойствам конкретной сущности</param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task<int> Clear(int idUser, TRequest request, CancellationToken token); Task<int> Clear(int idUser, TRequest request, CancellationToken token);
@ -61,13 +60,13 @@ public interface IChangeLogRepository<TDto, TRequest>
Task<int> ClearAndInsertRange(int idUser, TRequest request, IEnumerable<TDto> dtos, CancellationToken token); Task<int> ClearAndInsertRange(int idUser, TRequest request, IEnumerable<TDto> dtos, CancellationToken token);
/// <summary> /// <summary>
/// Удаление записей /// Пометить записи как удаленные
/// </summary> /// </summary>
/// <param name="idUser"></param> /// <param name="idUser"></param>
/// <param name="ids"></param> /// <param name="ids"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task<int> DeleteRange(int idUser, IEnumerable<int> ids, CancellationToken token); Task<int> MarkAsDeleted(int idUser, IEnumerable<int> ids, CancellationToken token);
/// <summary> /// <summary>
/// Получение дат изменений записей /// Получение дат изменений записей
@ -78,19 +77,26 @@ public interface IChangeLogRepository<TDto, TRequest>
Task<IEnumerable<DateOnly>> GetDatesChange(TRequest request, CancellationToken token); Task<IEnumerable<DateOnly>> GetDatesChange(TRequest request, CancellationToken token);
/// <summary> /// <summary>
/// Получение журнала изменений /// Получение измененных записей за определенную дату
/// </summary> /// </summary>
/// <param name="request"></param> /// <param name="request"></param>
/// <param name="date">Фильтр по дате. Если null - вернет все</param> /// <param name="date">Фильтр по дате. Если null - вернет все записи, без привязки к дате</param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task<IEnumerable<TDto>> GetChangeLog(TRequest request, DateOnly? date, CancellationToken token); Task<IEnumerable<ChangeLogDto<TDto>>> GetChangeLogForDate(TRequest request, DateOnly? date, CancellationToken token);
/// <summary> /// <summary>
/// Получение записей по параметрам /// Получение текущих сейчас записей по параметрам
/// </summary> /// </summary>
/// <param name="request"></param> /// <param name="request"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task<IEnumerable<TDto>> Get(TRequest request, CancellationToken token); Task<IEnumerable<TDto>> GetCurrent(TRequest request, CancellationToken token);
/// <summary>
/// Получение объекта, реализующего интерфейс IChangeLogRepositoryBuilder
/// для последующих вызовов методов фильтрации по запросам
/// </summary>
/// <returns></returns>
IChangeLogQueryBuilder<TDto, TRequest> GetQueryBuilder(ChangeLogRequest request);
} }

View File

@ -1,14 +0,0 @@
using System;
namespace AsbCloudApp.Requests;
/// <summary>
/// Базовый запрос актуальных данных
/// </summary>
public class ChangeLogBaseRequest
{
/// <summary>
/// Дата/время на которую записи были актуальны. Если не задано, то возвращаются все данные без учета их актуальности
/// </summary>
public DateTimeOffset? Moment { get; set; }
}

View File

@ -0,0 +1,31 @@
using System;
namespace AsbCloudApp.Requests;
/// <summary>
/// Запрос изменений
/// </summary>
public class ChangeLogRequest
{
/// <summary>
/// Дата/время на которую записи были актуальны. Если не задано, то возвращаются все данные без учета их актуальности
/// </summary>
public DateTimeOffset? Moment { get; set; }
/// <summary>
/// Конструктор
/// </summary>
public ChangeLogRequest()
{
}
/// <summary>
/// Копирующий конструктор
/// </summary>
/// <param name="request"></param>
public ChangeLogRequest(ChangeLogRequest request)
{
Moment = request.Moment;
}
}

View File

@ -1,29 +1,39 @@
using System; using System;
using System.ComponentModel.DataAnnotations;
namespace AsbCloudApp.Requests; namespace AsbCloudApp.Requests;
/// <summary> /// <summary>
/// Запрос для получения РТК план /// Запрос для получения РТК план
/// </summary> /// </summary>
public class ProcessMapPlanBaseRequest: ChangeLogBaseRequest public class ProcessMapPlanBaseRequest
{ {
/// <summary>
/// Тип секции
/// </summary>
[Range(1, int.MaxValue, ErrorMessage = "Id секции - положительное число")]
public int? IdWellSectionType { get; set; }
/// <summary> /// <summary>
/// Вернуть данные, которые поменялись с указанной даты /// Вернуть данные, которые поменялись с указанной даты
/// </summary> /// </summary>
public DateTimeOffset? UpdateFrom { get; set; } public DateTimeOffset? UpdateFrom { get; set; }
/// <summary>
/// Конструктор
/// </summary>
public ProcessMapPlanBaseRequest()
{
}
/// <summary>
/// Копирующий конструктор
/// </summary>
/// <param name="request">Параметры запроса</param>
public ProcessMapPlanBaseRequest(ProcessMapPlanBaseRequest request)
{
UpdateFrom = request.UpdateFrom;
}
} }
/// <summary> /// <summary>
/// Запрос для получения РТК план по скважине /// Запрос для получения РТК план по скважине
/// </summary> /// </summary>
public class ProcessMapPlanBaseRequestWithWell: ProcessMapPlanBaseRequest public class ProcessMapPlanBaseRequestWithWell : ProcessMapPlanBaseRequest
{ {
/// <summary> /// <summary>
/// Запрос для получения РТК план по скважине /// Запрос для получения РТК план по скважине
@ -40,11 +50,9 @@ public class ProcessMapPlanBaseRequestWithWell: ProcessMapPlanBaseRequest
/// <param name="request"></param> /// <param name="request"></param>
/// <param name="idWell"></param> /// <param name="idWell"></param>
public ProcessMapPlanBaseRequestWithWell(ProcessMapPlanBaseRequest request, int idWell) public ProcessMapPlanBaseRequestWithWell(ProcessMapPlanBaseRequest request, int idWell)
: base(request)
{ {
IdWell=idWell; IdWell = idWell;
IdWellSectionType=request.IdWellSectionType;
UpdateFrom = request.UpdateFrom;
Moment = request.Moment;
} }
/// <summary> /// <summary>

View File

@ -1,24 +0,0 @@
using System;
namespace AsbCloudApp.Requests;
/// <summary>
/// Запрос для получения РТК план
/// </summary>
public class ProcessMapPlanRequest
{
/// <summary>
/// Идентификатор скважины
/// </summary>
public int IdWell { get; set; }
/// <summary>
/// Тип секции
/// </summary>
public int? IdWellSectionType { get; set; }
/// <summary>
/// Дата обновления
/// </summary>
public DateTimeOffset? UpdateFrom { get; set; }
}

View File

@ -86,4 +86,10 @@ public abstract class ChangeLogAbstract
/// </summary> /// </summary>
[Column("id_previous"), Comment("ИД состояния записи: \n0 - актуальная\n1 - замененная\n2 - удаленная")] [Column("id_previous"), Comment("ИД состояния записи: \n0 - актуальная\n1 - замененная\n2 - удаленная")]
public int? IdPrevious { get; set; } public int? IdPrevious { get; set; }
[ForeignKey(nameof(IdAuthor))]
public virtual User Author { get; set; } = null!;
[ForeignKey(nameof(IdEditor))]
public virtual User? Editor { get; set; }
} }

View File

@ -20,12 +20,6 @@ public abstract class ProcessMapPlanBase : ChangeLogAbstract, IId, IWellRelated
[ForeignKey(nameof(IdWell))] [ForeignKey(nameof(IdWell))]
public virtual Well Well { get; set; } = null!; public virtual Well Well { get; set; } = null!;
[ForeignKey(nameof(IdAuthor))]
public virtual User Author { get; set; } = null!;
[ForeignKey(nameof(IdEditor))]
public virtual User? Editor { get; set; } = null!;
[ForeignKey(nameof(IdWellSectionType))] [ForeignKey(nameof(IdWellSectionType))]
public virtual WellSectionType WellSectionType { get; set; } = null!; public virtual WellSectionType WellSectionType { get; set; } = null!;
} }

View File

@ -1,22 +1,22 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Data.DailyReport.Blocks.TimeBalance; using AsbCloudApp.Data.DailyReport.Blocks.TimeBalance;
using AsbCloudApp.Data.DetectedOperation;
using AsbCloudApp.Data.DrillTestReport; using AsbCloudApp.Data.DrillTestReport;
using AsbCloudApp.Data.Manuals; using AsbCloudApp.Data.Manuals;
using AsbCloudApp.Data.ProcessMaps; using AsbCloudApp.Data.ProcessMaps;
using AsbCloudApp.Data.SAUB; using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Data.Subsystems; using AsbCloudApp.Data.Subsystems;
using AsbCloudApp.Data.Trajectory; using AsbCloudApp.Data.Trajectory;
using AsbCloudApp.Data.WellOperationImport.Options;
using AsbCloudApp.Repositories; using AsbCloudApp.Repositories;
using AsbCloudApp.Requests; using AsbCloudApp.Requests;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudApp.Services.DailyReport; using AsbCloudApp.Services.DailyReport;
using AsbCloudApp.Services.Notifications; using AsbCloudApp.Services.Notifications;
using AsbCloudApp.Services.ProcessMaps;
using AsbCloudApp.Services.ProcessMaps.WellDrilling; using AsbCloudApp.Services.ProcessMaps.WellDrilling;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudDb.Model.DailyReports.Blocks.TimeBalance; using AsbCloudDb.Model.DailyReports.Blocks.TimeBalance;
using AsbCloudDb.Model.Manuals; using AsbCloudDb.Model.Manuals;
using AsbCloudDb.Model.ProcessMapPlan;
using AsbCloudDb.Model.ProcessMaps; using AsbCloudDb.Model.ProcessMaps;
using AsbCloudDb.Model.Trajectory; using AsbCloudDb.Model.Trajectory;
using AsbCloudDb.Model.WellSections; using AsbCloudDb.Model.WellSections;
@ -27,14 +27,15 @@ using AsbCloudInfrastructure.Services.DailyReport;
using AsbCloudInfrastructure.Services.DetectOperations; using AsbCloudInfrastructure.Services.DetectOperations;
using AsbCloudInfrastructure.Services.DrillingProgram; using AsbCloudInfrastructure.Services.DrillingProgram;
using AsbCloudInfrastructure.Services.DrillTestReport; using AsbCloudInfrastructure.Services.DrillTestReport;
using AsbCloudInfrastructure.Services.ProcessMapPlan.Export;
using AsbCloudInfrastructure.Services.ProcessMapPlan.Parser; using AsbCloudInfrastructure.Services.ProcessMapPlan.Parser;
using AsbCloudInfrastructure.Services.ProcessMaps;
using AsbCloudInfrastructure.Services.ProcessMaps.Report; using AsbCloudInfrastructure.Services.ProcessMaps.Report;
using AsbCloudInfrastructure.Services.SAUB; using AsbCloudInfrastructure.Services.SAUB;
using AsbCloudInfrastructure.Services.Subsystems; using AsbCloudInfrastructure.Services.Subsystems;
using AsbCloudInfrastructure.Services.Trajectory; using AsbCloudInfrastructure.Services.Trajectory;
using AsbCloudInfrastructure.Services.Trajectory.Export; using AsbCloudInfrastructure.Services.Trajectory.Export;
using AsbCloudInfrastructure.Services.Trajectory.Parser; using AsbCloudInfrastructure.Services.Trajectory.Parser;
using AsbCloudInfrastructure.Services.WellOperations.Factories;
using AsbCloudInfrastructure.Services.WellOperationService; using AsbCloudInfrastructure.Services.WellOperationService;
using Mapster; using Mapster;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
@ -42,9 +43,6 @@ using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using System; using System;
using AsbCloudApp.Data.DetectedOperation;
using AsbCloudInfrastructure.Services.ProcessMapPlan.Export;
using AsbCloudInfrastructure.Services.WellOperations.Factories;
namespace AsbCloudInfrastructure namespace AsbCloudInfrastructure
{ {
@ -56,15 +54,21 @@ namespace AsbCloudInfrastructure
.ForType<SetpointsRequestDto, SetpointsRequest>() .ForType<SetpointsRequestDto, SetpointsRequest>()
.Ignore(source => source.Author) .Ignore(source => source.Author)
.Ignore(source => source.Well); .Ignore(source => source.Well);
TypeAdapterConfig.GlobalSettings.Default.Config TypeAdapterConfig.GlobalSettings.Default.Config
.ForType<DetectedOperationDto, DetectedOperation>() .ForType<DetectedOperationDto, DetectedOperation>()
.Ignore(source => source.OperationCategory); .Ignore(source => source.OperationCategory);
TypeAdapterConfig.GlobalSettings.Default.Config TypeAdapterConfig.GlobalSettings.Default.Config
.ForType<ScheduleDto, Schedule>() .ForType<ScheduleDto, Schedule>()
.Ignore(source => source.Driller); .Ignore(source => source.Driller);
#pragma warning disable CS8603 // Possible null reference return.
TypeAdapterConfig.GlobalSettings.Default.Config
.ForType<ProcessMapPlanBaseDto, ProcessMapPlanBase>()
.Ignore(dst => dst.Author, dst => dst.Editor);
#pragma warning restore CS8603 // Possible null reference return.
TypeAdapterConfig.GlobalSettings.Default.Config TypeAdapterConfig.GlobalSettings.Default.Config
.ForType<DateTimeOffset, DateTime>() .ForType<DateTimeOffset, DateTime>()
.MapWith((source) => source.DateTime); .MapWith((source) => source.DateTime);
@ -127,6 +131,13 @@ namespace AsbCloudInfrastructure
{ {
Plan = src.WellDepthPlan Plan = src.WellDepthPlan
}); });
TypeAdapterConfig<ChangeLogAbstract, ChangeLogDto<ProcessMapPlanDrillingDto>>.NewConfig()
.Include<ProcessMapPlanDrilling, ChangeLogDto<ProcessMapPlanDrillingDto>>()
.Map(dest => dest, src => new ChangeLogDto<ProcessMapPlanDrillingDto>()
{
Item = src.Adapt<ProcessMapPlanDrillingDto>()
});
} }
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration) public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
@ -186,11 +197,11 @@ namespace AsbCloudInfrastructure
services.AddTransient< services.AddTransient<
IChangeLogRepository<ProcessMapPlanDrillingDto, ProcessMapPlanBaseRequestWithWell>, IChangeLogRepository<ProcessMapPlanDrillingDto, ProcessMapPlanBaseRequestWithWell>,
ProcessMapPlanBaseRepository<ProcessMapPlanDrillingDto, ProcessMapPlanDrilling>>(); ProcessMapPlanBaseRepository<ProcessMapPlanDrilling, ProcessMapPlanDrillingDto>>();
services.AddTransient< services.AddTransient<
IChangeLogRepository<ProcessMapPlanReamDto, ProcessMapPlanBaseRequestWithWell>, IChangeLogRepository<ProcessMapPlanReamDto, ProcessMapPlanBaseRequestWithWell>,
ProcessMapPlanBaseRepository<ProcessMapPlanReamDto, ProcessMapPlanReam>>(); ProcessMapPlanBaseRepository<ProcessMapPlanReam, ProcessMapPlanReamDto>>();
services.AddTransient<IProcessMapReportDrillingService, ProcessMapReportDrillingService>(); services.AddTransient<IProcessMapReportDrillingService, ProcessMapReportDrillingService>();
@ -293,7 +304,7 @@ namespace AsbCloudInfrastructure
services.AddTransient<TrajectoryFactManualParser>(); services.AddTransient<TrajectoryFactManualParser>();
services.AddTransient<ProcessMapPlanDrillingParser>(); services.AddTransient<ProcessMapPlanDrillingParser>();
services.AddTransient<ProcessMapPlanReamParser>(); services.AddTransient<ProcessMapPlanReamParser>();
services.AddTransient<TrajectoryPlanExportService>(); services.AddTransient<TrajectoryPlanExportService>();
services.AddTransient<TrajectoryFactManualExportService>(); services.AddTransient<TrajectoryFactManualExportService>();
services.AddTransient<TrajectoryFactNnbExportService>(); services.AddTransient<TrajectoryFactNnbExportService>();
@ -303,7 +314,7 @@ namespace AsbCloudInfrastructure
services.AddTransient<WellOperationParserFactory>(); services.AddTransient<WellOperationParserFactory>();
services.AddTransient<WellOperationExportServiceFactory>(); services.AddTransient<WellOperationExportServiceFactory>();
return services; return services;
} }
} }

View File

@ -1,4 +1,5 @@
using AsbCloudApp.Exceptions; using AsbCloudApp.Data;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Repositories; using AsbCloudApp.Repositories;
using AsbCloudApp.Requests; using AsbCloudApp.Requests;
using AsbCloudDb.Model; using AsbCloudDb.Model;
@ -13,10 +14,9 @@ using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Repository; namespace AsbCloudInfrastructure.Repository;
public abstract class ChangeLogRepositoryAbstract<TDto, TEntity, TRequest> : IChangeLogRepository<TDto, TRequest> public abstract class ChangeLogRepositoryAbstract<TEntity, TDto, TRequest> : IChangeLogRepository<TDto, TRequest>
where TDto : AsbCloudApp.Data.ChangeLogAbstract where TDto : AsbCloudApp.Data.IId
where TEntity : ChangeLogAbstract where TEntity : ChangeLogAbstract
where TRequest : ChangeLogBaseRequest
{ {
protected readonly IAsbCloudDbContext db; protected readonly IAsbCloudDbContext db;
@ -25,6 +25,97 @@ public abstract class ChangeLogRepositoryAbstract<TDto, TEntity, TRequest> : ICh
this.db = db; this.db = db;
} }
private class ChangeLogQueryBuilder: IChangeLogQueryBuilder<TDto, TRequest>
{
protected readonly ChangeLogRepositoryAbstract<TEntity, TDto, TRequest> Repository;
protected IQueryable<TEntity> Query;
public ChangeLogQueryBuilder(
ChangeLogRepositoryAbstract<TEntity, TDto, TRequest> repository,
ChangeLogRequest request)
{
this.Repository = repository;
this.Query = repository.db.Set<TEntity>()
.Include(e => e.Author)
.Include(e => e.Editor);
if (request.Moment.HasValue)
{
var momentUtc = request.Moment.Value.ToUniversalTime();
this.Query = this.Query
.Where(e => e.Creation <= momentUtc)
.Where(e => e.Obsolete == null || e.Obsolete >= momentUtc);
}
}
public ChangeLogQueryBuilder(ChangeLogQueryBuilder builder)
{
Repository = builder.Repository;
Query = builder.Query;
}
public virtual IChangeLogQueryBuilderWithKnownTimezone<TDto, TRequest> ApplyRequest(TRequest request)
{
this.Query = Repository.BuildQuery(request, Query);
return new ChangeLogQueryBuilderWithKnownTimezone(this, request);
}
public async Task<IEnumerable<TDto>> GetData(TimeSpan offset, CancellationToken token)
{
var dtos = await this.Query.Select(e => Repository.Convert(e, offset))
.ToArrayAsync(token);
return dtos;
}
public async Task<IEnumerable<ChangeLogDto<TDto>>> GetChangeLogData(TimeSpan offset, CancellationToken token)
{
var dtos = await this.Query.Select(e => Repository.ConvertChangeLogDto(e, offset))
.ToArrayAsync(token);
return dtos;
}
}
private class ChangeLogQueryBuilderWithKnownTimezone: ChangeLogQueryBuilder, IChangeLogQueryBuilderWithKnownTimezone<TDto, TRequest>
{
TRequest request;
public ChangeLogQueryBuilderWithKnownTimezone(
ChangeLogQueryBuilder parentBuilder,
TRequest request)
:base(parentBuilder)
{
this.request = request;
}
public override IChangeLogQueryBuilderWithKnownTimezone<TDto, TRequest> ApplyRequest(TRequest request)
{
Query = Repository.BuildQuery(request, Query);
this.request = request;
return this;
}
public async Task<IEnumerable<TDto>> GetData(CancellationToken token)
{
TimeSpan timezoneOffset = Repository.GetTimezoneOffset(request);
var dtos = await this.GetData(timezoneOffset, token);
return dtos;
}
public async Task<IEnumerable<ChangeLogDto<TDto>>> GetChangeLogData(CancellationToken token)
{
TimeSpan timezoneOffset = Repository.GetTimezoneOffset(request);
var dtos = await this.GetChangeLogData(timezoneOffset, token);
return dtos;
}
}
public IChangeLogQueryBuilder<TDto, TRequest> GetQueryBuilder(ChangeLogRequest request)
{
var builder = new ChangeLogQueryBuilder(this, request);
return builder;
}
public async Task<int> InsertRange(int idUser, IEnumerable<TDto> dtos, CancellationToken token) public async Task<int> InsertRange(int idUser, IEnumerable<TDto> dtos, CancellationToken token)
{ {
var result = 0; var result = 0;
@ -133,6 +224,7 @@ public abstract class ChangeLogRepositoryAbstract<TDto, TEntity, TRequest> : ICh
public async Task<int> Clear(int idUser, TRequest request, CancellationToken token) public async Task<int> Clear(int idUser, TRequest request, CancellationToken token)
{ {
var updateTime = DateTimeOffset.UtcNow; var updateTime = DateTimeOffset.UtcNow;
var query = BuildQuery(request); var query = BuildQuery(request);
query = query.Where(e => e.Obsolete == null); query = query.Where(e => e.Obsolete == null);
@ -168,7 +260,7 @@ public abstract class ChangeLogRepositoryAbstract<TDto, TEntity, TRequest> : ICh
} }
} }
public async Task<int> DeleteRange(int idUser, IEnumerable<int> ids, CancellationToken token) public async Task<int> MarkAsDeleted(int idUser, IEnumerable<int> ids, CancellationToken token)
{ {
var updateTime = DateTimeOffset.UtcNow; var updateTime = DateTimeOffset.UtcNow;
var query = db.Set<TEntity>() var query = db.Set<TEntity>()
@ -217,7 +309,7 @@ public abstract class ChangeLogRepositoryAbstract<TDto, TEntity, TRequest> : ICh
return datesOnly; return datesOnly;
} }
public async Task<IEnumerable<TDto>> GetChangeLog(TRequest request, DateOnly? date, CancellationToken token) public async Task<IEnumerable<ChangeLogDto<TDto>>> GetChangeLogForDate(TRequest request, DateOnly? date, CancellationToken token)
{ {
var query = BuildQuery(request); var query = BuildQuery(request);
TimeSpan offset = GetTimezoneOffset(request); TimeSpan offset = GetTimezoneOffset(request);
@ -233,53 +325,72 @@ public abstract class ChangeLogRepositoryAbstract<TDto, TEntity, TRequest> : ICh
query = createdQuery.Union(editedQuery); query = createdQuery.Union(editedQuery);
} }
var dtos = await CreateChangeLogDto(query, offset, token);
return dtos;
}
public async Task<IEnumerable<ChangeLogDto<TDto>>> CreateChangeLogDto(IQueryable<TEntity> query, TimeSpan offset, CancellationToken token)
{
var entities = await query var entities = await query
.OrderBy(e => e.Creation) .OrderBy(e => e.Creation)
.ThenBy(e => e.Obsolete) .ThenBy(e => e.Obsolete)
.ThenBy(e => e.Id) .ThenBy(e => e.Id)
.ToListAsync(token); .ToListAsync(token);
var dtos = entities.Select(e => Convert(e, offset));
var dtos = entities.Select(e => ConvertChangeLogDto(e, offset));
return dtos; return dtos;
} }
public async Task<IEnumerable<TDto>> Get(TRequest request, CancellationToken token) public async Task<IEnumerable<TDto>> GetCurrent(TRequest request, CancellationToken token)
{ {
var query = BuildQuery(request); var changeLogRequest = new ChangeLogRequest()
var entities = await query {
.OrderBy(e => e.Creation) Moment = new DateTimeOffset(3000, 1, 1, 0, 0, 0, TimeSpan.Zero)
.ThenBy(e => e.Obsolete) };
.ThenBy(e => e.Id)
.ToArrayAsync(token); var builder = GetQueryBuilder(changeLogRequest)
.ApplyRequest(request);
var dtos = await builder.GetData(token);
TimeSpan offset = GetTimezoneOffset(request);
var dtos = entities.Select(e => Convert(e, offset));
return dtos; return dtos;
} }
protected abstract TimeSpan GetTimezoneOffset(TRequest request); protected abstract TimeSpan GetTimezoneOffset(TRequest request);
protected abstract IQueryable<TEntity> BuildQuery(TRequest request); private IQueryable<TEntity> BuildQuery(TRequest request) =>
BuildQuery(request, db.Set<TEntity>()
.Include(e => e.Author)
.Include(e => e.Editor));
protected abstract IQueryable<TEntity> BuildQuery(TRequest request, IQueryable<TEntity> query);
protected virtual TEntity Convert(TDto dto) protected virtual TEntity Convert(TDto dto)
{ {
var entity = dto.Adapt<TEntity>(); var entity = dto.Adapt<TEntity>();
entity.Creation = entity.Creation.ToUniversalTime(); entity.Creation = entity.Creation.ToUniversalTime();
if(entity.Obsolete.HasValue) if (entity.Obsolete.HasValue)
entity.Obsolete = entity.Obsolete.Value.ToUniversalTime(); entity.Obsolete = entity.Obsolete.Value.ToUniversalTime();
return entity; return entity;
} }
protected virtual ChangeLogDto<TDto> ConvertChangeLogDto(TEntity entity, TimeSpan offset)
{
var changeLogDto = entity.Adapt<ChangeLogDto<TDto>>();
changeLogDto.Creation = entity.Creation.ToOffset(offset);
if (entity.Obsolete.HasValue)
changeLogDto.Obsolete = entity.Obsolete.Value.ToOffset(offset);
changeLogDto.Item = Convert(entity, offset);
return changeLogDto;
}
protected virtual TDto Convert(TEntity entity, TimeSpan offset) protected virtual TDto Convert(TEntity entity, TimeSpan offset)
{ {
var dto = entity.Adapt<TDto>(); var dto = entity.Adapt<TDto>();
dto.Creation = entity.Creation.ToOffset(offset);
if (entity.Obsolete.HasValue)
dto.Obsolete = entity.Obsolete.Value.ToOffset(offset);
return dto; return dto;
} }
@ -303,4 +414,5 @@ public abstract class ChangeLogRepositoryAbstract<TDto, TEntity, TRequest> : ICh
if (pgException.SqlState == PostgresErrorCodes.ForeignKeyViolation) if (pgException.SqlState == PostgresErrorCodes.ForeignKeyViolation)
throw new ArgumentInvalidException("dtos", pgException.Message + "\r\n" + pgException.Detail); throw new ArgumentInvalidException("dtos", pgException.Message + "\r\n" + pgException.Detail);
} }
} }

View File

@ -9,45 +9,31 @@ using System.Linq;
namespace AsbCloudInfrastructure.Repository; namespace AsbCloudInfrastructure.Repository;
public class ProcessMapPlanBaseRepository<TDto, TEntity> : ChangeLogRepositoryAbstract<TDto, TEntity, ProcessMapPlanBaseRequestWithWell> public class ProcessMapPlanBaseRepository<TEntity, TDto> : ChangeLogRepositoryAbstract<TEntity, TDto, ProcessMapPlanBaseRequestWithWell>
where TDto : ProcessMapPlanBaseDto where TDto : ProcessMapPlanBaseDto
where TEntity : ProcessMapPlanBase where TEntity : ProcessMapPlanBase
{ {
private readonly IWellService wellService; private readonly IWellService wellService;
public ProcessMapPlanBaseRepository(IAsbCloudDbContext context, IWellService wellService) public ProcessMapPlanBaseRepository(IAsbCloudDbContext context, IWellService wellService)
: base(context) : base(context)
{ {
this.wellService = wellService; this.wellService = wellService;
} }
protected override IQueryable<TEntity> BuildQuery(ProcessMapPlanBaseRequestWithWell request) protected override IQueryable<TEntity> BuildQuery(ProcessMapPlanBaseRequestWithWell request, IQueryable<TEntity> query)
{ {
var query = db query = query
.Set<TEntity>()
.Include(e => e.Author)
.Include(e => e.Editor)
.Include(e => e.Well) .Include(e => e.Well)
.Include(e => e.WellSectionType) .Include(e => e.WellSectionType)
.Where(e => e.IdWell == request.IdWell); .Where(e => e.IdWell == request.IdWell);
if (request.IdWellSectionType.HasValue)
query = query.Where(e => e.IdWellSectionType == request.IdWellSectionType);
if (request.UpdateFrom.HasValue) if (request.UpdateFrom.HasValue)
{ {
var from = request.UpdateFrom.Value.ToUniversalTime(); var from = request.UpdateFrom.Value.ToUniversalTime();
query = query.Where(e => e.Creation >= from || e.Obsolete >= from); query = query.Where(e => e.Creation >= from || e.Obsolete >= from);
} }
if (request.Moment.HasValue)
{
var moment = request.Moment.Value.ToUniversalTime();
query = query
.Where(e => e.Creation <= moment)
.Where(e => e.Obsolete == null || e.Obsolete >= moment);
}
return query; return query;
} }
@ -68,8 +54,6 @@ public class ProcessMapPlanBaseRepository<TDto, TEntity> : ChangeLogRepositoryAb
protected override TEntity Convert(TDto dto) protected override TEntity Convert(TDto dto)
{ {
var entity = base.Convert(dto); var entity = base.Convert(dto);
entity.Author = null;
entity.Editor = null;
return entity; return entity;
} }
} }

View File

@ -19,7 +19,7 @@ public class WellCompositeRepository : IWellCompositeRepository
private readonly IChangeLogRepository<ProcessMapPlanDrillingDto, ProcessMapPlanBaseRequestWithWell> processMapPlanDrillingRepository; private readonly IChangeLogRepository<ProcessMapPlanDrillingDto, ProcessMapPlanBaseRequestWithWell> processMapPlanDrillingRepository;
public WellCompositeRepository( public WellCompositeRepository(
IAsbCloudDbContext db, IAsbCloudDbContext db,
IChangeLogRepository<ProcessMapPlanDrillingDto, ProcessMapPlanBaseRequestWithWell> processMapPlanDrillingRepository) IChangeLogRepository<ProcessMapPlanDrillingDto, ProcessMapPlanBaseRequestWithWell> processMapPlanDrillingRepository)
{ {
this.db = db; this.db = db;
@ -51,17 +51,9 @@ public class WellCompositeRepository : IWellCompositeRepository
} }
/// <inheritdoc/> /// <inheritdoc/>
public async Task<IEnumerable<ProcessMapPlanDrillingDto>> GetCompositeProcessMap(int idWell, CancellationToken token) public Task<IEnumerable<ProcessMapPlanDrillingDto>> GetCompositeProcessMap(int idWell, CancellationToken token)
{ {
var dtos = await GetAsync(idWell, token); throw new NotImplementedException();
var requests = dtos.Select(x => new ProcessMapPlanRequest {
IdWell = x.IdWellSrc,
IdWellSectionType = x.IdWellSectionType
});
//var result = await processMapPlanDrillingRepository.GetAsync(requests, token);
return Enumerable.Empty<ProcessMapPlanDrillingDto>();
} }
private static WellComposite Convert(int idWell, WellCompositeDto dto) private static WellComposite Convert(int idWell, WellCompositeDto dto)

View File

@ -43,7 +43,7 @@ public class WorkOperationDetection: Work
var telemetryId = telemetryIds[i]; var telemetryId = telemetryIds[i];
var beginDate = lastDetectedDates.TryGetValue(telemetryId, out var date) ? date : (DateTimeOffset?)null; var beginDate = lastDetectedDates.TryGetValue(telemetryId, out var date) ? date : (DateTimeOffset?)null;
onProgressCallback($"Start detecting telemetry: {telemetryId} from {beginDate}", i / telemetryIds.Length); onProgressCallback($"Start detecting telemetry: {telemetryId} from {beginDate}", i / telemetryIds.Length);
var detectedOperations = await detectedOperationService.DetectOperationsAsync(telemetryId, beginDate, token); var detectedOperations = await detectedOperationService.DetectOperationsAsync(telemetryId, beginDate, token);

View File

@ -1,38 +1,34 @@
using System; using AsbCloudApp.Data.ProcessMaps;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Repositories; using AsbCloudApp.Repositories;
using AsbCloudApp.Requests; using AsbCloudApp.Requests;
using AsbCloudApp.Requests.ExportOptions; using AsbCloudApp.Requests.ExportOptions;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services.ExcelServices; using AsbCloudInfrastructure.Services.ExcelServices;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services.ProcessMapPlan.Export; namespace AsbCloudInfrastructure.Services.ProcessMapPlan.Export;
public abstract class ProcessMapPlanExportService<TDto> : ExportExcelService<TDto, WellRelatedExportRequest> public abstract class ProcessMapPlanExportService<TDto> : ExportExcelService<TDto, WellRelatedExportRequest>
where TDto : ChangeLogAbstract where TDto : ProcessMapPlanBaseDto
{ {
protected readonly IWellService wellService; protected readonly IWellService wellService;
private readonly IChangeLogRepository<TDto, ProcessMapPlanBaseRequestWithWell> processMapPlanRepository; private readonly IChangeLogRepository<TDto, ProcessMapPlanBaseRequestWithWell> processMapPlanRepository;
protected ProcessMapPlanExportService(IChangeLogRepository<TDto, ProcessMapPlanBaseRequestWithWell> processMapPlanRepository, protected ProcessMapPlanExportService(IChangeLogRepository<TDto, ProcessMapPlanBaseRequestWithWell> processMapPlanRepository,
IWellService wellService) IWellService wellService)
{ {
this.processMapPlanRepository = processMapPlanRepository; this.processMapPlanRepository = processMapPlanRepository;
this.wellService = wellService; this.wellService = wellService;
} }
protected override async Task<IEnumerable<TDto>> GetDtosAsync(WellRelatedExportRequest options, CancellationToken token) protected override async Task<IEnumerable<TDto>> GetDtosAsync(WellRelatedExportRequest options, CancellationToken token)
{ {
var request = new ProcessMapPlanBaseRequestWithWell(options.IdWell) var request = new ProcessMapPlanBaseRequestWithWell(options.IdWell);
{
Moment = DateTimeOffset.UtcNow var dtos = await processMapPlanRepository.GetCurrent(request, token);
}; return dtos;
}
var dtos = await processMapPlanRepository.Get(request, token);
return dtos;
}
} }

View File

@ -1,5 +1,3 @@
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data.ProcessMaps; using AsbCloudApp.Data.ProcessMaps;
using AsbCloudApp.Repositories; using AsbCloudApp.Repositories;
using AsbCloudApp.Requests; using AsbCloudApp.Requests;
@ -7,24 +5,26 @@ using AsbCloudApp.Requests.ExportOptions;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services.ExcelServices.Templates; using AsbCloudInfrastructure.Services.ExcelServices.Templates;
using AsbCloudInfrastructure.Services.ExcelServices.Templates.ProcessMapPlanTemplates; using AsbCloudInfrastructure.Services.ExcelServices.Templates.ProcessMapPlanTemplates;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services.ProcessMapPlan.Export; namespace AsbCloudInfrastructure.Services.ProcessMapPlan.Export;
public class ProcessMapPlanReamExportService : ProcessMapPlanExportService<ProcessMapPlanReamDto> public class ProcessMapPlanReamExportService : ProcessMapPlanExportService<ProcessMapPlanReamDto>
{ {
protected override ITemplateParameters TemplateParameters => new ProcessMapPlanReamTemplate(); protected override ITemplateParameters TemplateParameters => new ProcessMapPlanReamTemplate();
public ProcessMapPlanReamExportService( public ProcessMapPlanReamExportService(
IChangeLogRepository<ProcessMapPlanReamDto, ProcessMapPlanBaseRequestWithWell> processMapPlanRepository, IChangeLogRepository<ProcessMapPlanReamDto, ProcessMapPlanBaseRequestWithWell> processMapPlanRepository,
IWellService wellService) IWellService wellService)
: base(processMapPlanRepository, wellService) : base(processMapPlanRepository, wellService)
{ {
} }
protected override async Task<string> BuildFileNameAsync(WellRelatedExportRequest options, CancellationToken token)
{
var caption = await wellService.GetWellCaptionByIdAsync(options.IdWell, token);
return $"{caption}_РТК_План_проработка.xlsx"; protected override async Task<string> BuildFileNameAsync(WellRelatedExportRequest options, CancellationToken token)
} {
var caption = await wellService.GetWellCaptionByIdAsync(options.IdWell, token);
return $"{caption}_РТК_План_проработка.xlsx";
}
} }

View File

@ -1,6 +1,7 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Data.ProcessMaps; using AsbCloudApp.Data.ProcessMaps;
using AsbCloudApp.Data.ProcessMaps.Report; using AsbCloudApp.Data.ProcessMaps.Report;
using AsbCloudApp.Data.WellOperation;
using AsbCloudApp.Exceptions; using AsbCloudApp.Exceptions;
using AsbCloudApp.Extensions; using AsbCloudApp.Extensions;
using AsbCloudApp.Repositories; using AsbCloudApp.Repositories;
@ -13,7 +14,6 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsbCloudApp.Data.WellOperation;
namespace AsbCloudInfrastructure.Services.ProcessMaps.Report; namespace AsbCloudInfrastructure.Services.ProcessMaps.Report;
@ -48,13 +48,13 @@ public class ProcessMapReportDrillingService : IProcessMapReportDrillingService
return Enumerable.Empty<ProcessMapReportDataSaubStatDto>(); return Enumerable.Empty<ProcessMapReportDataSaubStatDto>();
var requestProcessMapPlan = new ProcessMapPlanBaseRequestWithWell(idWell); var requestProcessMapPlan = new ProcessMapPlanBaseRequestWithWell(idWell);
var processMapPlanWellDrillings = await processMapPlanBaseRepository.Get(requestProcessMapPlan, token); var changeLogProcessMaps = await processMapPlanBaseRepository.GetChangeLogForDate(requestProcessMapPlan, null, token);
if (!processMapPlanWellDrillings.Any()) if (!changeLogProcessMaps.Any())
return Enumerable.Empty<ProcessMapReportDataSaubStatDto>(); return Enumerable.Empty<ProcessMapReportDataSaubStatDto>();
var geDepth = processMapPlanWellDrillings.Min(p => p.DepthStart); var geDepth = changeLogProcessMaps.Min(p => p.Item.DepthStart);
var leDepth = processMapPlanWellDrillings.Max(p => p.DepthEnd); var leDepth = changeLogProcessMaps.Max(p => p.Item.DepthEnd);
var requestWellOperationFact = new WellOperationRequest(new[] { idWell }) var requestWellOperationFact = new WellOperationRequest(new[] { idWell })
{ {
@ -85,10 +85,10 @@ public class ProcessMapReportDrillingService : IProcessMapReportDrillingService
var wellSectionTypes = wellOperationRepository.GetSectionTypes(); var wellSectionTypes = wellOperationRepository.GetSectionTypes();
var result = CalcByIntervals( var result = CalcByIntervals(
request, request,
processMapPlanWellDrillings, changeLogProcessMaps,
dataSaubStats, dataSaubStats,
orderedWellOperations, orderedWellOperations,
wellOperationCategories, wellOperationCategories,
wellSectionTypes); wellSectionTypes);
@ -97,7 +97,7 @@ public class ProcessMapReportDrillingService : IProcessMapReportDrillingService
private static IEnumerable<ProcessMapReportDataSaubStatDto> CalcByIntervals( private static IEnumerable<ProcessMapReportDataSaubStatDto> CalcByIntervals(
DataSaubStatRequest request, DataSaubStatRequest request,
IEnumerable<ProcessMapPlanDrillingDto> processMapPlanWellDrillings, IEnumerable<ChangeLogDto<ProcessMapPlanDrillingDto>> changeLogProcessMaps,
Span<DataSaubStatDto> dataSaubStats, Span<DataSaubStatDto> dataSaubStats,
IEnumerable<WellOperationDto> wellOperations, IEnumerable<WellOperationDto> wellOperations,
IEnumerable<WellOperationCategoryDto> wellOperationCategories, IEnumerable<WellOperationCategoryDto> wellOperationCategories,
@ -115,23 +115,24 @@ public class ProcessMapReportDrillingService : IProcessMapReportDrillingService
int GetSection(DataSaubStatDto data) int GetSection(DataSaubStatDto data)
{ {
if(lastFoundIndex < orderedWellOperations.Length - 1) if (lastFoundIndex < orderedWellOperations.Length - 1)
{ {
lastFoundIndex = Array.FindIndex(orderedWellOperations, lastFoundIndex, o => o.DateStart > data.DateStart) - 1; lastFoundIndex = Array.FindIndex(orderedWellOperations, lastFoundIndex, o => o.DateStart > data.DateStart) - 1;
lastFoundIndex = lastFoundIndex < 0 ? orderedWellOperations.Length - 1 : lastFoundIndex; lastFoundIndex = lastFoundIndex < 0 ? orderedWellOperations.Length - 1 : lastFoundIndex;
} }
var operation = orderedWellOperations[lastFoundIndex]; var operation = orderedWellOperations[lastFoundIndex];
return operation.IdWellSectionType; return operation.IdWellSectionType;
} }
ProcessMapPlanDrillingDto? GetProcessMapPlan(int idWellSectionType, DataSaubStatDto data) ProcessMapPlanDrillingDto? GetProcessMapPlan(int idWellSectionType, DataSaubStatDto data)
=> processMapPlanWellDrillings => changeLogProcessMaps
.Where(p => p.IdWellSectionType == idWellSectionType) .Where(p => p.Item.IdWellSectionType == idWellSectionType)
.Where(p => p.DepthStart <= data.DepthStart) .Where(p => p.Item.DepthStart <= data.DepthStart)
.Where(p => p.DepthEnd >= data.DepthStart) .Where(p => p.Item.DepthEnd >= data.DepthStart)
.Where(p => IsModeMatchOperationCategory(p.IdMode, data.IdCategory)) .Where(p => IsModeMatchOperationCategory(p.Item.IdMode, data.IdCategory))
.WhereActualAtMoment(data.DateStart) .WhereActualAtMoment(data.DateStart)
.Select(p => p.Item)
.FirstOrDefault(); .FirstOrDefault();
var idWellSectionType = GetSection(firstElemInInterval); var idWellSectionType = GetSection(firstElemInInterval);
@ -168,7 +169,7 @@ public class ProcessMapReportDrillingService : IProcessMapReportDrillingService
var elem = CalcStat(processMapPlan, span, wellOperationCategoryName, wellSectionType); var elem = CalcStat(processMapPlan, span, wellOperationCategoryName, wellSectionType);
if (elem is not null) if (elem is not null)
list.Add(elem); list.Add(elem);
} }
} }
return list; return list;
@ -333,7 +334,7 @@ public class ProcessMapReportDrillingService : IProcessMapReportDrillingService
SetpointUsagePressure: sumDiffDepthByPressure * 100 / diffDepthTotal, SetpointUsagePressure: sumDiffDepthByPressure * 100 / diffDepthTotal,
SetpointUsageAxialLoad: sumDiffDepthByAxialLoad * 100 / diffDepthTotal, SetpointUsageAxialLoad: sumDiffDepthByAxialLoad * 100 / diffDepthTotal,
SetpointUsageRotorTorque: sumDiffDepthByRotorTorque * 100 / diffDepthTotal, SetpointUsageRotorTorque: sumDiffDepthByRotorTorque * 100 / diffDepthTotal,
SetpointUsageRopPlan: sumDiffDepthByRopPlan * 100/ diffDepthTotal, SetpointUsageRopPlan: sumDiffDepthByRopPlan * 100 / diffDepthTotal,
DrilledTime: drilledTime DrilledTime: drilledTime
); );
} }

View File

@ -43,14 +43,11 @@ public class WellInfoService
var wellsIds = activeWells.Select(w => w.Id); var wellsIds = activeWells.Select(w => w.Id);
var processMapPlanWellDrillingRequests = wellsIds.Select(id => new ProcessMapPlanBaseRequestWithWell(id) var processMapPlanWellDrillingRequests = wellsIds.Select(id => new ProcessMapPlanBaseRequestWithWell(id));
{
Moment = DateTimeOffset.UtcNow.AddDays(1)
});
var processMapPlanWellDrillings = new List<ProcessMapPlanDrillingDto>(); var processMapPlanWellDrillings = new List<ProcessMapPlanDrillingDto>();
foreach (var processMapPlanWellDrillingRequest in processMapPlanWellDrillingRequests) foreach (var processMapPlanWellDrillingRequest in processMapPlanWellDrillingRequests)
{ {
var processMaps = await processMapPlanWellDrillingRepository.Get(processMapPlanWellDrillingRequest, token); var processMaps = await processMapPlanWellDrillingRepository.GetCurrent(processMapPlanWellDrillingRequest, token);
processMapPlanWellDrillings.AddRange(processMaps); processMapPlanWellDrillings.AddRange(processMaps);
} }
@ -100,14 +97,14 @@ public class WellInfoService
int? idSection = wellLastFactSection?.Id; int? idSection = wellLastFactSection?.Id;
ProcessMapPlanDrillingDto? processMapPlanWellDrilling = null; ProcessMapPlanDrillingDto? processMapPlanWellDrilling = null;
if(idSection.HasValue && currentDepth.HasValue) if (idSection.HasValue && currentDepth.HasValue)
{ {
processMapPlanWellDrilling = wellProcessMaps processMapPlanWellDrilling = wellProcessMaps
.Where(p => p.IdWellSectionType == idSection) .Where(p => p.IdWellSectionType == idSection)
.Where(p => p.DepthStart <= currentDepth.Value && p.DepthEnd >= currentDepth.Value) .Where(p => p.DepthStart <= currentDepth.Value && p.DepthEnd >= currentDepth.Value)
.FirstOrDefault(); .FirstOrDefault();
} }
else if(currentDepth.HasValue) else if (currentDepth.HasValue)
{ {
processMapPlanWellDrilling = wellProcessMaps.FirstOrDefault(p => p.DepthStart <= currentDepth.Value && p.DepthEnd >= currentDepth.Value); processMapPlanWellDrilling = wellProcessMaps.FirstOrDefault(p => p.DepthStart <= currentDepth.Value && p.DepthEnd >= currentDepth.Value);
} }

View File

@ -31,10 +31,10 @@ namespace AsbCloudInfrastructure
var backgroundWorker = provider.GetRequiredService<PeriodicBackgroundWorker>(); var backgroundWorker = provider.GetRequiredService<PeriodicBackgroundWorker>();
backgroundWorker.Add<WorkToDeleteOldReports>(TimeSpan.FromDays(1)); backgroundWorker.Add<WorkToDeleteOldReports>(TimeSpan.FromDays(1));
backgroundWorker.Add<WellInfoService.WorkWellInfoUpdate>(TimeSpan.FromMinutes(30)); backgroundWorker.Add<WellInfoService.WorkWellInfoUpdate>(TimeSpan.FromMinutes(30));
backgroundWorker.Add<WorkOperationDetection>(TimeSpan.FromMinutes(15)); backgroundWorker.Add<WorkOperationDetection>(TimeSpan.FromMinutes(0));
backgroundWorker.Add<WorkDataSaubStat>(TimeSpan.FromMinutes(15)); backgroundWorker.Add<WorkDataSaubStat>(TimeSpan.FromMinutes(0));
backgroundWorker.Add<WorkLimitingParameterCalc>(TimeSpan.FromMinutes(30)); backgroundWorker.Add<WorkLimitingParameterCalc>(TimeSpan.FromMinutes(0));
backgroundWorker.Add(MakeMemoryMonitoringWork(), TimeSpan.FromMinutes(1)); backgroundWorker.Add(MakeMemoryMonitoringWork(), TimeSpan.FromMinutes(0));
var notificationBackgroundWorker = provider.GetRequiredService<NotificationBackgroundWorker>(); var notificationBackgroundWorker = provider.GetRequiredService<NotificationBackgroundWorker>();
} }

View File

@ -5,15 +5,15 @@ using Refit;
namespace AsbCloudWebApi.IntegrationTests.Clients; namespace AsbCloudWebApi.IntegrationTests.Clients;
public interface IProcessMapPlanDrillingClient public interface IProcessMapPlanDrillingClient<TDto> where TDto : ProcessMapPlanBaseDto
{ {
private const string BaseRoute = "/api/well/{idWell}/ProcessMapPlanDrilling"; private const string BaseRoute = "/api/well/{idWell}/ProcessMapPlanDrilling";
[Post(BaseRoute)] [Post(BaseRoute)]
Task<IApiResponse<int>> InsertRange(int idWell, [Body] IEnumerable<ProcessMapPlanDrillingDto> dtos); Task<IApiResponse<int>> InsertRange(int idWell, [Body] IEnumerable<TDto> dtos);
[Post($"{BaseRoute}/replace")] [Post($"{BaseRoute}/replace")]
Task<IApiResponse<int>> ClearAndInsertRange(int idWell, [Body] IEnumerable<ProcessMapPlanDrillingDto> dtos); Task<IApiResponse<int>> ClearAndInsertRange(int idWell, [Body] IEnumerable<TDto> dtos);
[Delete(BaseRoute)] [Delete(BaseRoute)]
Task<IApiResponse<int>> DeleteRange(int idWell, [Body] IEnumerable<int> ids); Task<IApiResponse<int>> DeleteRange(int idWell, [Body] IEnumerable<int> ids);
@ -22,18 +22,24 @@ public interface IProcessMapPlanDrillingClient
Task<IApiResponse<int>> Clear(int idWell); Task<IApiResponse<int>> Clear(int idWell);
[Get(BaseRoute)] [Get(BaseRoute)]
Task<IApiResponse<IEnumerable<ProcessMapPlanDrillingDto>>> Get(int idWell, ProcessMapPlanBaseRequest request); Task<IApiResponse<IEnumerable<TDto>>> Get(int idWell);
[Get($"{BaseRoute}/changeLog")] [Get($"{BaseRoute}/changelogByMoment")]
Task<IApiResponse<IEnumerable<ProcessMapPlanDrillingDto>>> GetChangeLog(int idWell, DateOnly? date); Task<IApiResponse<IEnumerable<ChangeLogDto<TDto>>>> Get(int idWell, DateTimeOffset? moment);
[Get("/api/telemetry/{uid}/ProcessMapPlanDrilling")]
Task<IApiResponse<IEnumerable<ChangeLogDto<TDto>>>> Get(string uid, DateTimeOffset? updateFrom);
[Get($"{BaseRoute}/changeLogForDate")]
Task<IApiResponse<IEnumerable<TDto>>> GetChangeLog(int idWell, DateOnly? date);
[Get($"{BaseRoute}/dates")] [Get($"{BaseRoute}/dates")]
Task<IApiResponse<IEnumerable<DateOnly>>> GetDatesChange(int idWell); Task<IApiResponse<IEnumerable<DateOnly>>> GetDatesChange(int idWell);
[Put(BaseRoute)] [Put(BaseRoute)]
Task<IApiResponse<int>> UpdateOrInsertRange(int idWell, IEnumerable<ProcessMapPlanDrillingDto> dtos); Task<IApiResponse<int>> UpdateOrInsertRange(int idWell, IEnumerable<TDto> dtos);
[Multipart] [Multipart]
[Post(BaseRoute + "/parse")] [Post(BaseRoute + "/parse")]
Task<IApiResponse<ParserResultDto<ProcessMapPlanDrillingDto>>> Parse(int idWell, [AliasAs("file")] StreamPart stream); Task<IApiResponse<ParserResultDto<TDto>>> Parse(int idWell, [AliasAs("file")] StreamPart stream);
} }

View File

@ -12,20 +12,18 @@ using Xunit;
using AsbCloudApp.Data.ProcessMaps; using AsbCloudApp.Data.ProcessMaps;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudApp.Data.User; using AsbCloudApp.Data.User;
using AsbCloudApp.Data;
namespace AsbCloudWebApi.IntegrationTests.Controllers.ProcessMapPlan; namespace AsbCloudWebApi.IntegrationTests.Controllers.ProcessMapPlan;
public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest public class ProcessMapPlanDrillingControllerTest : BaseIntegrationTest
{ {
private const int IdWell = 1; private const int IdWell = 1;
private readonly ProcessMapPlanDrillingDto dto = new (){ private readonly ProcessMapPlanDrillingDto dto = new()
{
Id = 0, Id = 0,
Creation = new(),
Obsolete = null,
IdState = 0,
IdPrevious = null,
IdWell = IdWell, IdWell = IdWell,
Section = "Кондуктор", Section = "Кондуктор",
IdWellSectionType = 3, IdWellSectionType = 3,
@ -48,7 +46,7 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
UsageSpin = 14, UsageSpin = 14,
Comment = "это тестовая запись", Comment = "это тестовая запись",
}; };
private readonly ProcessMapPlanDrilling entity = new () private readonly ProcessMapPlanDrilling entity = new()
{ {
Id = 0, Id = 0,
IdAuthor = 1, IdAuthor = 1,
@ -80,12 +78,12 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
Comment = "это тестовая запись", Comment = "это тестовая запись",
}; };
private IProcessMapPlanDrillingClient client; private IProcessMapPlanDrillingClient<ProcessMapPlanDrillingDto> client;
public ProcessMapPlanDrillingControllerTest(WebAppFactoryFixture factory) : base(factory) public ProcessMapPlanDrillingControllerTest(WebAppFactoryFixture factory) : base(factory)
{ {
dbContext.CleanupDbSet<ProcessMapPlanDrilling>(); dbContext.CleanupDbSet<ProcessMapPlanDrilling>();
client = factory.GetAuthorizedHttpClient<IProcessMapPlanDrillingClient>(string.Empty); client = factory.GetAuthorizedHttpClient<IProcessMapPlanDrillingClient<ProcessMapPlanDrillingDto>>(string.Empty);
} }
[Fact] [Fact]
@ -96,7 +94,7 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
//act //act
var response = await client.InsertRange(dto.IdWell, new[] { expected }); var response = await client.InsertRange(dto.IdWell, new[] { expected });
//assert //assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(1, response.Content); Assert.Equal(1, response.Content);
@ -110,17 +108,14 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
Assert.NotNull(entity); Assert.NotNull(entity);
var actual = entity.Adapt<ProcessMapPlanDrillingDto>(); var actual = entity.Adapt<ChangeLogDto<ProcessMapPlanDrillingDto>>();
Assert.Equal(ProcessMapPlanBase.IdStateActual, actual.IdState); Assert.Equal(ProcessMapPlanBase.IdStateActual, actual.IdState);
var excludeProps = new[] { var excludeProps = new[] {
nameof(ProcessMapPlanDrillingDto.Id), nameof(ProcessMapPlanDrillingDto.Id),
nameof(ProcessMapPlanDrillingDto.IdState),
nameof(ProcessMapPlanDrillingDto.Author),
nameof(ProcessMapPlanDrillingDto.Creation),
nameof(ProcessMapPlanDrillingDto.Section) nameof(ProcessMapPlanDrillingDto.Section)
}; };
MatchHelper.Match(expected, actual, excludeProps); MatchHelper.Match(expected, actual.Item, excludeProps);
} }
[Fact] [Fact]
@ -150,19 +145,19 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
//assert //assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
} }
[Fact] [Fact]
public async Task ClearAndInsertRange_returns_success() public async Task ClearAndInsertRange_returns_success()
{ {
// arrange // arrange
var dbset = dbContext.Set<ProcessMapPlanDrilling>(); var dbset = dbContext.Set<ProcessMapPlanDrilling>();
var entry = dbset.Add(entity); var entry = dbset.Add(entity);
dbContext.SaveChanges(); dbContext.SaveChanges();
entry.State = EntityState.Detached; entry.State = EntityState.Detached;
var startTime = DateTimeOffset.UtcNow; var startTime = DateTimeOffset.UtcNow;
// act // act
var result = await client.ClearAndInsertRange(entity.IdWell, new ProcessMapPlanDrillingDto[] { dto }); var result = await client.ClearAndInsertRange(entity.IdWell, new ProcessMapPlanDrillingDto[] { dto });
@ -221,7 +216,6 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
dtoUpdate.TopDriveSpeedLimitMax++; dtoUpdate.TopDriveSpeedLimitMax++;
dtoUpdate.TopDriveTorquePlan++; dtoUpdate.TopDriveTorquePlan++;
dtoUpdate.TopDriveTorqueLimitMax++; dtoUpdate.TopDriveTorqueLimitMax++;
dtoUpdate.Author = user;
var dtoInsert = dtoUpdate.Adapt<ProcessMapPlanDrillingDto>(); var dtoInsert = dtoUpdate.Adapt<ProcessMapPlanDrillingDto>();
dtoInsert.Id = 0; dtoInsert.Id = 0;
@ -239,7 +233,6 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
dtoInsert.TopDriveSpeedLimitMax++; dtoInsert.TopDriveSpeedLimitMax++;
dtoInsert.TopDriveTorquePlan++; dtoInsert.TopDriveTorquePlan++;
dtoInsert.TopDriveTorqueLimitMax++; dtoInsert.TopDriveTorqueLimitMax++;
dtoInsert.Author = user;
// act // act
var result = await client.UpdateOrInsertRange(entity.IdWell, new ProcessMapPlanDrillingDto[] { dtoUpdate, dtoInsert }); var result = await client.UpdateOrInsertRange(entity.IdWell, new ProcessMapPlanDrillingDto[] { dtoUpdate, dtoInsert });
@ -283,13 +276,13 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
{ {
//arrange //arrange
var dbset = dbContext.Set<ProcessMapPlanDrilling>(); var dbset = dbContext.Set<ProcessMapPlanDrilling>();
var entry = dbset.Add(entity); var entry = dbset.Add(entity);
dbContext.SaveChanges(); dbContext.SaveChanges();
entry.State = EntityState.Detached; entry.State = EntityState.Detached;
var startTime = DateTimeOffset.UtcNow; var startTime = DateTimeOffset.UtcNow;
//act //act
var response = await client.DeleteRange(dto.IdWell, new[] { entry.Entity.Id }); var response = await client.DeleteRange(dto.IdWell, new[] { entry.Entity.Id });
@ -346,7 +339,7 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
{ {
//arrange //arrange
var dbset = dbContext.Set<ProcessMapPlanDrilling>(); var dbset = dbContext.Set<ProcessMapPlanDrilling>();
var entity2 = entity.Adapt<ProcessMapPlanDrilling>(); var entity2 = entity.Adapt<ProcessMapPlanDrilling>();
entity2.Creation = entity.Creation.AddDays(1); entity2.Creation = entity.Creation.AddDays(1);
dbset.Add(entity); dbset.Add(entity);
@ -367,40 +360,13 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
Assert.Equal(2, response.Content.Count()); Assert.Equal(2, response.Content.Count());
Assert.All(response.Content, d => dates.Contains(d)); Assert.All(response.Content, d => dates.Contains(d));
} }
[Fact]
public async Task Get_all_returns_success()
{
//arrange
var dbset = dbContext.Set<ProcessMapPlanDrilling>();
dbset.Add(entity);
var entityDeleted = entity.Adapt<ProcessMapPlanDrilling>();
entityDeleted.Creation = entity.Creation.AddDays(-1);
entityDeleted.Obsolete = entity.Creation;
entityDeleted.IdState = ProcessMapPlanBase.IdStateDeleted;
entityDeleted.IdEditor = 1;
dbset.Add(entityDeleted);
dbContext.SaveChanges();
//act
var request = new ProcessMapPlanBaseRequest();
var response = await client.Get(dto.IdWell, request);
//assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
Assert.Equal(2, response.Content.Count());
}
[Fact] [Fact]
public async Task Get_actual_returns_success() public async Task Get_actual_returns_success()
{ {
//arrange //arrange
var dbset = dbContext.Set<ProcessMapPlanDrilling>(); var dbset = dbContext.Set<ProcessMapPlanDrilling>();
dbset.Add(entity); dbset.Add(entity);
var entityDeleted = entity.Adapt<ProcessMapPlanDrilling>(); var entityDeleted = entity.Adapt<ProcessMapPlanDrilling>();
@ -413,11 +379,7 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
dbContext.SaveChanges(); dbContext.SaveChanges();
//act var response = await client.Get(dto.IdWell);
var request = new ProcessMapPlanBaseRequest {
Moment = new DateTimeOffset(3000, 1, 1, 0, 0, 0, 0, TimeSpan.Zero)
};
var response = await client.Get(dto.IdWell, request);
//assert //assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -425,12 +387,12 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
Assert.Single(response.Content); Assert.Single(response.Content);
var actual = response.Content.First()!; var actual = response.Content.First()!;
Assert.NotNull(actual.Section);
Assert.NotEmpty(actual.Section);
var expected = entity.Adapt<ProcessMapPlanDrillingDto>()!; var expected = entity.Adapt<ProcessMapPlanDrillingDto>()!;
var excludeProps = new[] { var excludeProps = new[] {
nameof(ProcessMapPlanDrillingDto.Id), nameof(ProcessMapPlanDrillingDto.Id),
nameof(ProcessMapPlanDrillingDto.Author),
nameof(ProcessMapPlanDrillingDto.Creation),
}; };
MatchHelper.Match(expected, actual, excludeProps); MatchHelper.Match(expected, actual, excludeProps);
} }
@ -440,7 +402,7 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
{ {
//arrange //arrange
var dbset = dbContext.Set<ProcessMapPlanDrilling>(); var dbset = dbContext.Set<ProcessMapPlanDrilling>();
var now = DateTimeOffset.UtcNow; var now = DateTimeOffset.UtcNow;
var entityDeleted = entity.Adapt<ProcessMapPlanDrilling>(); var entityDeleted = entity.Adapt<ProcessMapPlanDrilling>();
entityDeleted.Creation = now; entityDeleted.Creation = now;
@ -461,11 +423,7 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
dbContext.SaveChanges(); dbContext.SaveChanges();
//act //act
var request = new ProcessMapPlanBaseRequest var response = await client.Get(dto.IdWell, now.AddMinutes(0.5));
{
Moment = now.AddMinutes(0.5),
};
var response = await client.Get(dto.IdWell, request);
//assert //assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -474,49 +432,33 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
} }
[Fact] [Fact]
public async Task Get_section_returns_success() public async Task Get_by_updated_from_returns_success()
{ {
//arrange //arrange
var dbset = dbContext.Set<ProcessMapPlanDrilling>(); var dbset = dbContext.Set<ProcessMapPlanDrilling>();
dbset.Add(entity); dbset.Add(entity);
var entity2 = entity.Adapt<ProcessMapPlanDrilling>(); var entity2 = entity.Adapt<ProcessMapPlanDrilling>();
entity2.IdWellSectionType = 2; entity2.Obsolete = DateTimeOffset.UtcNow;
entity2.Comment = "IdWellSectionType = 2";
dbset.Add(entity2); dbset.Add(entity2);
dbContext.SaveChanges(); dbContext.SaveChanges();
//act //act
var request = new ProcessMapPlanBaseRequest var response = await client.Get(Defaults.RemoteUid, DateTimeOffset.UtcNow.AddHours(-1));
{
IdWellSectionType = 2,
};
var response = await client.Get(dto.IdWell, request);
//assert //assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content); Assert.NotNull(response.Content);
Assert.Single(response.Content); Assert.Equal(2, response.Content.Count());
var actual = response.Content.First()!;
var expected = entity2.Adapt<ProcessMapPlanDrillingDto>()!;
var excludeProps = new[] {
nameof(ProcessMapPlanDrillingDto.Id),
nameof(ProcessMapPlanDrillingDto.Author),
nameof(ProcessMapPlanDrillingDto.Creation),
};
MatchHelper.Match(expected, actual, excludeProps);
} }
[Fact] [Fact]
public async Task Get_updated_returns_success() public async Task Get_updated_returns_success()
{ {
//arrange //arrange
var dbset = dbContext.Set<ProcessMapPlanDrilling>(); var dbset = dbContext.Set<ProcessMapPlanDrilling>();
dbset.Add(entity); dbset.Add(entity);
var entity2 = entity.Adapt<ProcessMapPlanDrilling>(); var entity2 = entity.Adapt<ProcessMapPlanDrilling>();
@ -540,7 +482,7 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
{ {
UpdateFrom = updateFrom, UpdateFrom = updateFrom,
}; };
var response = await client.Get(dto.IdWell, request); var response = await client.Get(dto.IdWell);
//assert //assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@ -553,8 +495,6 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
var expected = entity2.Adapt<ProcessMapPlanDrillingDto>(); var expected = entity2.Adapt<ProcessMapPlanDrillingDto>();
var excludeProps = new[] { var excludeProps = new[] {
nameof(ProcessMapPlanDrillingDto.Id), nameof(ProcessMapPlanDrillingDto.Id),
nameof(ProcessMapPlanDrillingDto.Author),
nameof(ProcessMapPlanDrillingDto.Creation),
}; };
MatchHelper.Match(expected, actual, excludeProps); MatchHelper.Match(expected, actual, excludeProps);
} }
@ -567,19 +507,19 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
var stream = Assembly.GetExecutingAssembly().GetFileCopyStream(fileName); var stream = Assembly.GetExecutingAssembly().GetFileCopyStream(fileName);
var streamPart = new StreamPart(stream, fileName, "application/octet-stream"); var streamPart = new StreamPart(stream, fileName, "application/octet-stream");
//act //act
var response = await client.Parse(IdWell, streamPart); var response = await client.Parse(IdWell, streamPart);
//assert //assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var parserResult = response.Content; var parserResult = response.Content;
Assert.NotNull(parserResult); Assert.NotNull(parserResult);
Assert.Single(parserResult.Item); Assert.Single(parserResult.Item);
Assert.True(parserResult.IsValid); Assert.True(parserResult.IsValid);
var row = parserResult.Item.First(); var row = parserResult.Item.First();
var dtoActual = row.Item; var dtoActual = row.Item;
@ -595,23 +535,23 @@ public class ProcessMapPlanDrillingControllerTest: BaseIntegrationTest
//arrange //arrange
const string fileName = "ProcessMapPlanDrillingInvalid.xlsx"; const string fileName = "ProcessMapPlanDrillingInvalid.xlsx";
var stream = Assembly.GetExecutingAssembly().GetFileCopyStream(fileName); var stream = Assembly.GetExecutingAssembly().GetFileCopyStream(fileName);
var streamPart = new StreamPart(stream, fileName, "application/octet-stream"); var streamPart = new StreamPart(stream, fileName, "application/octet-stream");
//act //act
var response = await client.Parse(IdWell, streamPart); var response = await client.Parse(IdWell, streamPart);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var parserResult = response.Content; var parserResult = response.Content;
Assert.NotNull(parserResult); Assert.NotNull(parserResult);
Assert.False(parserResult.IsValid); Assert.False(parserResult.IsValid);
Assert.Single(parserResult.Warnings); Assert.Single(parserResult.Warnings);
Assert.Single(parserResult.Item); Assert.Single(parserResult.Item);
var row = parserResult.Item.First(); var row = parserResult.Item.First();
Assert.False(row.IsValid); Assert.False(row.IsValid);
Assert.Equal(2, row.Warnings.Count()); Assert.Equal(2, row.Warnings.Count());
} }

View File

@ -11,6 +11,8 @@ namespace AsbCloudWebApi.IntegrationTests.Data
Hours = 1 Hours = 1
}; };
public const string RemoteUid = "555-555-555";
public static Deposit[] Deposits => new Deposit[] public static Deposit[] Deposits => new Deposit[]
{ {
new() new()
@ -39,7 +41,7 @@ namespace AsbCloudWebApi.IntegrationTests.Data
Timezone = Timezone, Timezone = Timezone,
Telemetry = new Telemetry Telemetry = new Telemetry
{ {
RemoteUid = "555-555-555", RemoteUid = RemoteUid,
TimeZone = Timezone TimeZone = Timezone
}, },
RelationCompaniesWells = new RelationCompanyWell[] RelationCompaniesWells = new RelationCompanyWell[]

View File

@ -1,21 +1,17 @@
using System; using AsbCloudApp.Data;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Data.ProcessMaps; using AsbCloudApp.Data.ProcessMaps;
using AsbCloudApp.Data.WellOperation; using AsbCloudApp.Data.WellOperation;
using AsbCloudApp.Repositories; using AsbCloudApp.Repositories;
using AsbCloudApp.Requests; using AsbCloudApp.Requests;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Repository;
using AsbCloudInfrastructure.Services.ProcessMaps;
using AsbCloudInfrastructure.Services.ProcessMaps.Report; using AsbCloudInfrastructure.Services.ProcessMaps.Report;
using DocumentFormat.OpenXml.Bibliography;
using DocumentFormat.OpenXml.Spreadsheet;
using NSubstitute; using NSubstitute;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit; using Xunit;
namespace AsbCloudWebApi.Tests.Services.ProcessMaps; namespace AsbCloudWebApi.Tests.Services.ProcessMaps;
@ -24,27 +20,27 @@ public class ProcessMapReportDataSaubStatServiceTest
{ {
private IWellService wellService private IWellService wellService
= Substitute.For<IWellService>(); = Substitute.For<IWellService>();
private IChangeLogRepository<ProcessMapPlanDrillingDto, ProcessMapPlanBaseRequestWithWell> processMapPlanBaseRepository private IChangeLogRepository<ProcessMapPlanDrillingDto, ProcessMapPlanBaseRequestWithWell> processMapPlanBaseRepository
= Substitute.For<IChangeLogRepository<ProcessMapPlanDrillingDto, ProcessMapPlanBaseRequestWithWell>>(); = Substitute.For<IChangeLogRepository<ProcessMapPlanDrillingDto, ProcessMapPlanBaseRequestWithWell>>();
private IWellOperationRepository wellOperationRepository private IWellOperationRepository wellOperationRepository
= Substitute.For<IWellOperationRepository>(); = Substitute.For<IWellOperationRepository>();
private IWellOperationCategoryRepository wellOperationCategoryRepository private IWellOperationCategoryRepository wellOperationCategoryRepository
= Substitute.For<IWellOperationCategoryRepository>(); = Substitute.For<IWellOperationCategoryRepository>();
private IDataSaubStatRepository dataSaubStatRepository private IDataSaubStatRepository dataSaubStatRepository
= Substitute.For<IDataSaubStatRepository>(); = Substitute.For<IDataSaubStatRepository>();
private ProcessMapReportDrillingService service; private ProcessMapReportDrillingService service;
private readonly static SimpleTimezoneDto timezone = new() { Hours = 2 }; private readonly static SimpleTimezoneDto timezone = new() { Hours = 2 };
private static readonly DateTimeOffset dateStart = new (2024, 01, 01, 00, 11, 11, timezone.Offset); private static readonly DateTimeOffset dateStart = new(2024, 01, 01, 00, 11, 11, timezone.Offset);
private readonly static WellDto well = new() private readonly static WellDto well = new()
{ {
Id = 1, Id = 1,
IdTelemetry = 1, IdTelemetry = 1,
Timezone = timezone Timezone = timezone
@ -52,7 +48,7 @@ public class ProcessMapReportDataSaubStatServiceTest
private readonly static IEnumerable<ProcessMapPlanDrillingDto> processMapPlan = new List<ProcessMapPlanDrillingDto>() private readonly static IEnumerable<ProcessMapPlanDrillingDto> processMapPlan = new List<ProcessMapPlanDrillingDto>()
{ {
new() { new() {
DepthStart = 0, DepthStart = 0,
DepthEnd = 100, DepthEnd = 100,
IdMode = 1, IdMode = 1,
IdWell = well.Id, IdWell = well.Id,
@ -136,6 +132,12 @@ public class ProcessMapReportDataSaubStatServiceTest
Comment = "s", Comment = "s",
}, },
}; };
private readonly static IEnumerable<ChangeLogDto<ProcessMapPlanDrillingDto>> processMapPlanChangeLog = processMapPlan.Select(p => new ChangeLogDto<ProcessMapPlanDrillingDto>()
{
Item = p,
});
private readonly static IEnumerable<WellOperationDto> operations = new List<WellOperationDto>() private readonly static IEnumerable<WellOperationDto> operations = new List<WellOperationDto>()
{ {
new() new()
@ -253,15 +255,18 @@ public class ProcessMapReportDataSaubStatServiceTest
HasOscillation = false, HasOscillation = false,
} }
}; };
public ProcessMapReportDataSaubStatServiceTest() public ProcessMapReportDataSaubStatServiceTest()
{ {
wellService.GetOrDefaultAsync(Arg.Any<int>(), Arg.Any<CancellationToken>()) wellService.GetOrDefaultAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(well); .Returns(well);
processMapPlanBaseRepository.Get(Arg.Any<ProcessMapPlanBaseRequestWithWell>(), Arg.Any<CancellationToken>()) processMapPlanBaseRepository.GetCurrent(Arg.Any<ProcessMapPlanBaseRequestWithWell>(), Arg.Any<CancellationToken>())
.Returns(processMapPlan); .Returns(processMapPlan);
processMapPlanBaseRepository.GetChangeLogForDate(Arg.Any<ProcessMapPlanBaseRequestWithWell>(), null, Arg.Any<CancellationToken>())
.Returns(processMapPlanChangeLog);
wellOperationRepository.GetAsync(Arg.Any<WellOperationRequest>(), Arg.Any<CancellationToken>()) wellOperationRepository.GetAsync(Arg.Any<WellOperationRequest>(), Arg.Any<CancellationToken>())
.Returns(operations); .Returns(operations);

View File

@ -1,23 +1,24 @@
using AsbCloudApp.Repositories; using AsbCloudApp.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using Microsoft.AspNetCore.Http;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Requests;
using System;
using System.IO;
using AsbCloudApp.Services;
using System.Linq;
using AsbCloudApp.Data;
using AsbCloudApp.Requests.ParserOptions;
using AsbCloudApp.Data.ProcessMaps; using AsbCloudApp.Data.ProcessMaps;
using System.ComponentModel.DataAnnotations; using AsbCloudApp.Exceptions;
using AsbCloudApp.Repositories;
using AsbCloudApp.Requests;
using AsbCloudApp.Requests.ExportOptions; using AsbCloudApp.Requests.ExportOptions;
using AsbCloudApp.Requests.ParserOptions;
using AsbCloudApp.Services;
using AsbCloudApp.Services.Export; using AsbCloudApp.Services.Export;
using AsbCloudApp.Services.Parsers; using AsbCloudApp.Services.Parsers;
using AsbCloudDb.Model.ProcessMapPlan;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers.ProcessMaps; namespace AsbCloudWebApi.Controllers.ProcessMaps;
@ -27,22 +28,26 @@ namespace AsbCloudWebApi.Controllers.ProcessMaps;
[ApiController] [ApiController]
[Route("api/well/{idWell}/[controller]")] [Route("api/well/{idWell}/[controller]")]
[Authorize] [Authorize]
public abstract class ProcessMapPlanBaseController<TDto> : ControllerBase public abstract class ProcessMapPlanBaseController<TEntity, TDto> : ControllerBase
where TEntity : ProcessMapPlanBase
where TDto : ProcessMapPlanBaseDto where TDto : ProcessMapPlanBaseDto
{ {
private readonly IChangeLogRepository<TDto, ProcessMapPlanBaseRequestWithWell> repository; private readonly IChangeLogRepository<TDto, ProcessMapPlanBaseRequestWithWell> repository;
private readonly IWellService wellService; private readonly IWellService wellService;
private readonly IParserService<TDto, WellRelatedParserRequest> parserService; private readonly IParserService<TDto, WellRelatedParserRequest> parserService;
private readonly ITelemetryService telemetryService;
private readonly IExportService<WellRelatedExportRequest> processMapPlanExportService; private readonly IExportService<WellRelatedExportRequest> processMapPlanExportService;
protected ProcessMapPlanBaseController(IChangeLogRepository<TDto, ProcessMapPlanBaseRequestWithWell> repository, protected ProcessMapPlanBaseController(IChangeLogRepository<TDto, ProcessMapPlanBaseRequestWithWell> repository,
IWellService wellService, IWellService wellService,
IParserService<TDto, WellRelatedParserRequest> parserService, IParserService<TDto, WellRelatedParserRequest> parserService,
IExportService<WellRelatedExportRequest> processMapPlanExportService) IExportService<WellRelatedExportRequest> processMapPlanExportService,
ITelemetryService telemetryService)
{ {
this.repository = repository; this.repository = repository;
this.wellService = wellService; this.wellService = wellService;
this.parserService = parserService; this.parserService = parserService;
this.telemetryService = telemetryService;
this.processMapPlanExportService = processMapPlanExportService; this.processMapPlanExportService = processMapPlanExportService;
} }
@ -58,7 +63,7 @@ public abstract class ProcessMapPlanBaseController<TDto> : ControllerBase
[HttpPost] [HttpPost]
[ProducesResponseType(typeof(int), StatusCodes.Status200OK)] [ProducesResponseType(typeof(int), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> InsertRange([FromRoute][Range(0,int.MaxValue)] int idWell, IEnumerable<TDto> dtos, CancellationToken token) public async Task<IActionResult> InsertRange([FromRoute][Range(0, int.MaxValue)] int idWell, IEnumerable<TDto> dtos, CancellationToken token)
{ {
var idUser = await AssertUserHasAccessToWell(idWell, token); var idUser = await AssertUserHasAccessToWell(idWell, token);
@ -92,7 +97,7 @@ public abstract class ProcessMapPlanBaseController<TDto> : ControllerBase
} }
/// <summary> /// <summary>
/// Удаление /// Пометить записи как удаленные
/// </summary> /// </summary>
/// <param name="idWell"></param> /// <param name="idWell"></param>
/// <param name="ids"></param> /// <param name="ids"></param>
@ -101,11 +106,11 @@ public abstract class ProcessMapPlanBaseController<TDto> : ControllerBase
[HttpDelete] [HttpDelete]
[ProducesResponseType(typeof(int), StatusCodes.Status200OK)] [ProducesResponseType(typeof(int), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> DeleteRange([FromRoute] int idWell, IEnumerable<int> ids, CancellationToken token) public async Task<IActionResult> MarkAsDeleted([FromRoute] int idWell, IEnumerable<int> ids, CancellationToken token)
{ {
var idUser = await AssertUserHasAccessToWell(idWell, token); var idUser = await AssertUserHasAccessToWell(idWell, token);
var result = await repository.DeleteRange(idUser, ids, token); var result = await repository.MarkAsDeleted(idUser, ids, token);
return Ok(result); return Ok(result);
} }
@ -128,21 +133,78 @@ public abstract class ProcessMapPlanBaseController<TDto> : ControllerBase
} }
/// <summary> /// <summary>
/// Получение /// Получение текущих записей по параметрам
/// </summary> /// </summary>
/// <param name="idWell"></param> /// <param name="idWell"></param>
/// <param name="request"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
[HttpGet] [HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)]
public async Task<ActionResult<IEnumerable<TDto>>> Get([FromRoute] int idWell, [FromQuery] ProcessMapPlanBaseRequest request, CancellationToken token) public async Task<ActionResult<IEnumerable<TDto>>> GetCurrent([FromRoute] int idWell, CancellationToken token)
{ {
await AssertUserHasAccessToWell(idWell, token); await AssertUserHasAccessToWell(idWell, token);
var serviceRequest = new ProcessMapPlanBaseRequestWithWell(request, idWell); var serviceRequest = new ProcessMapPlanBaseRequestWithWell(idWell);
var result = await repository.Get(serviceRequest, token);
var result = await repository.GetCurrent(serviceRequest, token);
return Ok(result);
}
/// <summary>
/// Получение измененных записей за определенную дату по ключу скважины
/// </summary>
/// <param name="idWell"></param>
/// <param name="moment"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet("changelogByMoment")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)]
public async Task<ActionResult<IEnumerable<ChangeLogDto<TDto>>>> GetChangeLogByMoment([FromRoute] int idWell, DateTimeOffset? moment, CancellationToken token)
{
await AssertUserHasAccessToWell(idWell, token);
var dataRequest = new ProcessMapPlanBaseRequestWithWell(idWell);
var changeLogRequest = new ChangeLogRequest()
{
Moment = moment
};
var builder = repository
.GetQueryBuilder(changeLogRequest)
.ApplyRequest(dataRequest);
var dtos = await builder.GetChangeLogData(token);
return Ok(dtos);
}
/// <summary>
/// Получение записей за определенную дату по uid
/// </summary>
/// <param name="uid"></param>
/// <param name="updateFrom"></param>
/// <param name="token"></param>
/// <returns></returns>
[AllowAnonymous]
[HttpGet("/api/telemetry/{uid}/[controller]")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)]
public async Task<ActionResult<IEnumerable<ChangeLogDto<TDto>>>> GetByUid(string uid, DateTimeOffset? updateFrom, CancellationToken token)
{
var idWell = telemetryService.GetIdWellByTelemetryUid(uid) ?? -1;
if (idWell < 0)
return this.ValidationBadRequest(nameof(uid), "Скважина по uid не найдена");
var serviceRequest = new ProcessMapPlanBaseRequestWithWell(idWell)
{
UpdateFrom = updateFrom,
};
var result = await repository.GetChangeLogForDate(serviceRequest, null, token);
return Ok(result); return Ok(result);
} }
@ -153,15 +215,15 @@ public abstract class ProcessMapPlanBaseController<TDto> : ControllerBase
/// <param name="date"></param> /// <param name="date"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
[HttpGet("changeLog")] [HttpGet("changeLogForDate")]
[ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)]
public async Task<ActionResult<IEnumerable<TDto>>> GetChangeLog([FromRoute] int idWell, [FromQuery] DateOnly? date, CancellationToken token) public async Task<ActionResult<IEnumerable<ChangeLogDto<TDto>>>> GetChangeLogForDate([FromRoute] int idWell, [FromQuery] DateOnly? date, CancellationToken token)
{ {
await AssertUserHasAccessToWell(idWell, token); await AssertUserHasAccessToWell(idWell, token);
var serviceRequest = new ProcessMapPlanBaseRequestWithWell(idWell); var serviceRequest = new ProcessMapPlanBaseRequestWithWell(idWell);
var result = await repository.GetChangeLog(serviceRequest, date, token); var result = await repository.GetChangeLogForDate(serviceRequest, date, token);
return Ok(result); return Ok(result);
} }
@ -197,7 +259,7 @@ public abstract class ProcessMapPlanBaseController<TDto> : ControllerBase
{ {
if (!dtos.Any()) if (!dtos.Any())
return NoContent(); return NoContent();
var idUser = await AssertUserHasAccessToWell(idWell, token); var idUser = await AssertUserHasAccessToWell(idWell, token);
foreach (var dto in dtos) foreach (var dto in dtos)
@ -218,7 +280,7 @@ public abstract class ProcessMapPlanBaseController<TDto> : ControllerBase
[ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)]
public async Task<ActionResult<ParserResultDto<TDto>>> Parse(int idWell, public async Task<ActionResult<ParserResultDto<TDto>>> Parse(int idWell,
[Required] IFormFile file, [Required] IFormFile file,
CancellationToken token) CancellationToken token)
{ {
await AssertUserHasAccessToWell(idWell, token); await AssertUserHasAccessToWell(idWell, token);
@ -229,7 +291,7 @@ public abstract class ProcessMapPlanBaseController<TDto> : ControllerBase
{ {
var options = new WellRelatedParserRequest(idWell); var options = new WellRelatedParserRequest(idWell);
var dto = parserService.Parse(stream, options); var dto = parserService.Parse(stream, options);
return Ok(dto); return Ok(dto);
} }
catch (FileFormatException ex) catch (FileFormatException ex)
@ -271,7 +333,7 @@ public abstract class ProcessMapPlanBaseController<TDto> : ControllerBase
throw new ForbidException("Нет доступа к скважине"); throw new ForbidException("Нет доступа к скважине");
return idUser; return idUser;
} }
/// <summary> /// <summary>
/// Формируем excel файл с текущими строками РТК /// Формируем excel файл с текущими строками РТК
/// </summary> /// </summary>

View File

@ -2,6 +2,7 @@
using AsbCloudApp.Repositories; using AsbCloudApp.Repositories;
using AsbCloudApp.Requests; using AsbCloudApp.Requests;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model.ProcessMaps;
using AsbCloudInfrastructure.Services.ProcessMapPlan.Export; using AsbCloudInfrastructure.Services.ProcessMapPlan.Export;
using AsbCloudInfrastructure.Services.ProcessMapPlan.Parser; using AsbCloudInfrastructure.Services.ProcessMapPlan.Parser;
@ -10,13 +11,14 @@ namespace AsbCloudWebApi.Controllers.ProcessMaps;
/// <summary> /// <summary>
/// РТК план бурения /// РТК план бурения
/// </summary> /// </summary>
public class ProcessMapPlanDrillingController : ProcessMapPlanBaseController<ProcessMapPlanDrillingDto> public class ProcessMapPlanDrillingController : ProcessMapPlanBaseController<ProcessMapPlanDrilling, ProcessMapPlanDrillingDto>
{ {
public ProcessMapPlanDrillingController(IChangeLogRepository<ProcessMapPlanDrillingDto, ProcessMapPlanBaseRequestWithWell> repository, public ProcessMapPlanDrillingController(IChangeLogRepository<ProcessMapPlanDrillingDto, ProcessMapPlanBaseRequestWithWell> repository,
IWellService wellService, IWellService wellService,
ProcessMapPlanDrillingParser parserService, ProcessMapPlanDrillingParser parserService,
ITelemetryService telemetryService,
ProcessMapPlanDrillingExportService processMapPlanExportService) ProcessMapPlanDrillingExportService processMapPlanExportService)
: base(repository, wellService, parserService, processMapPlanExportService) : base(repository, wellService, parserService, processMapPlanExportService, telemetryService)
{ {
} }

View File

@ -2,6 +2,7 @@
using AsbCloudApp.Repositories; using AsbCloudApp.Repositories;
using AsbCloudApp.Requests; using AsbCloudApp.Requests;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model.ProcessMaps;
using AsbCloudInfrastructure.Services.ProcessMapPlan.Export; using AsbCloudInfrastructure.Services.ProcessMapPlan.Export;
using AsbCloudInfrastructure.Services.ProcessMapPlan.Parser; using AsbCloudInfrastructure.Services.ProcessMapPlan.Parser;
@ -10,13 +11,14 @@ namespace AsbCloudWebApi.Controllers.ProcessMaps;
/// <summary> /// <summary>
/// РТК план проработка /// РТК план проработка
/// </summary> /// </summary>
public class ProcessMapPlanReamController : ProcessMapPlanBaseController<ProcessMapPlanReamDto> public class ProcessMapPlanReamController : ProcessMapPlanBaseController<ProcessMapPlanReam, ProcessMapPlanReamDto>
{ {
public ProcessMapPlanReamController(IChangeLogRepository<ProcessMapPlanReamDto, ProcessMapPlanBaseRequestWithWell> repository, public ProcessMapPlanReamController(IChangeLogRepository<ProcessMapPlanReamDto, ProcessMapPlanBaseRequestWithWell> repository,
IWellService wellService, IWellService wellService,
ProcessMapPlanReamParser parserService, ProcessMapPlanReamParser parserService,
ITelemetryService telemetryService,
ProcessMapPlanReamExportService processMapPlanExportService) ProcessMapPlanReamExportService processMapPlanExportService)
: base(repository, wellService, parserService, processMapPlanExportService) : base(repository, wellService, parserService, processMapPlanExportService, telemetryService)
{ {
} }

View File

@ -1,25 +1,24 @@
using AsbCloudApp.Data.GTR; using AsbCloudApp.Data.GTR;
using AsbCloudApp.IntegrationEvents;
using AsbCloudApp.IntegrationEvents.Interfaces;
using AsbCloudApp.Repositories; using AsbCloudApp.Repositories;
using AsbCloudApp.Services.Notifications;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services; using AsbCloudInfrastructure.Services;
using AsbCloudInfrastructure.Services.Email;
using AsbCloudWebApi.SignalR;
using AsbCloudWebApi.SignalR.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsbCloudApp.IntegrationEvents;
using AsbCloudApp.IntegrationEvents.Interfaces;
using AsbCloudApp.Services.Notifications;
using AsbCloudInfrastructure.Services.Email;
using AsbCloudWebApi.SignalR;
using AsbCloudWebApi.SignalR.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.OpenApi.Any;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace AsbCloudWebApi namespace AsbCloudWebApi
{ {