Merge branch 'feature/#31401776-operation-time-for-driller' of http://test.digitaldrilling.ru:8080/DDrilling/AsbCloudServer into feature/#31401776-operation-time-for-driller

This commit is contained in:
Olga Nemt 2024-04-02 17:28:45 +05:00
commit fad6c3a77b
162 changed files with 12035 additions and 3722 deletions

View File

@ -74,7 +74,7 @@ public class DailyReportDto : IId,
/// <summary>
/// Дата последнего обновления
/// </summary>
public DateTime? DateLastUpdate { get; set; }
public DateTimeOffset? DateLastUpdate { get; set; }
/// <summary>
/// Блок фактической траектории

View File

@ -1,4 +1,5 @@
using System;
using AsbCloudApp.Data.WellOperation;
namespace AsbCloudApp.Data
{

View File

@ -12,12 +12,12 @@ namespace AsbCloudApp.Data
/// Дата начала диапазона
/// </summary>
[Required]
public DateTime From { get; set; }
public DateTimeOffset From { get; set; }
/// <summary>
/// Дата окончания диапазона
/// </summary>
[Required]
public DateTime To { get; set; }
public DateTimeOffset To { get; set; }
}
}

View File

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using AsbCloudApp.Data.WellOperation;
namespace AsbCloudApp.Data.DetectedOperation;

View File

@ -21,6 +21,6 @@ namespace AsbCloudApp.Data.DrillTestReport
/// <summary>
/// Дата отчета
/// </summary>
public DateTime Date { get; set; } = DateTime.Now;
public DateTimeOffset Date { get; set; } = DateTimeOffset.Now;
}
}

View File

@ -24,6 +24,6 @@ namespace AsbCloudApp.Data.DrillTestReport
/// Дата и время
/// </summary>
[Required]
public DateTime DateTime { get; set; }
public DateTimeOffset DateTime { get; set; }
}
}

View File

@ -43,7 +43,7 @@ namespace AsbCloudApp.Data
/// дата загрузки
/// </summary>
[Required]
public DateTime UploadDate { get; set; }
public DateTimeOffset UploadDate { get; set; }
/// <summary>
/// размер в байтах

View File

@ -33,7 +33,7 @@ namespace AsbCloudApp.Data
/// Необязательно указывать в запросе на создание.
/// </summary>
[Required]
public DateTime DateCreated { get; set; }
public DateTimeOffset DateCreated { get; set; }
/// <summary>
/// Полезный комментарий

View File

@ -20,12 +20,12 @@ namespace AsbCloudApp.Data
/// <summary>
/// Дата начала ограничения
/// </summary>
public DateTime DateStart { get; set; }
public DateTimeOffset DateStart { get; set; }
/// <summary>
/// Дата окончания ограничения
/// </summary>
public DateTime DateEnd { get; set; }
public DateTimeOffset DateEnd { get; set; }
/// <summary>
/// Глубина начала ограничения

View File

@ -18,7 +18,7 @@ public class ManualDto : IId
/// <summary>
/// Дата загрузки
/// </summary>
public DateTime DateDownload { get; set; }
public DateTimeOffset DateDownload { get; set; }
/// <summary>
/// Id автора

View File

@ -36,7 +36,7 @@ namespace AsbCloudApp.Data
/// отметка времени замера
/// </summary>
[Required]
public DateTime Timestamp { get; set; }
public DateTimeOffset Timestamp { get; set; }
/// <summary>
/// данные замера

View File

@ -16,7 +16,7 @@ namespace AsbCloudApp.Data
/// дата появления события
/// </summary>
[Required]
public DateTime DateTime { get; set; }
public DateTimeOffset DateTime { get; set; }
/// <summary>
/// категория события

View File

@ -42,17 +42,17 @@ public class NotificationDto : IId
/// Дата регистрации уведомления
/// </summary>
[Required]
public DateTime RegistrationDate { get; set; }
public DateTimeOffset RegistrationDate { get; set; }
/// <summary>
/// Дата отправки уведомления
/// </summary>
public DateTime? SentDate { get; set; }
public DateTimeOffset? SentDate { get; set; }
/// <summary>
/// Дата прочтения уведомления
/// </summary>
public DateTime? ReadDate { get; set; }
public DateTimeOffset? ReadDate { get; set; }
/// <summary>
/// Состояние уведомления
@ -82,12 +82,12 @@ public class NotificationDto : IId
ReadDate = null;
break;
case 1:
SentDate = DateTime.UtcNow;
SentDate = DateTimeOffset.UtcNow;
ReadDate = null;
break;
case 2:
SentDate = DateTime.UtcNow;
ReadDate = DateTime.UtcNow;
SentDate = DateTimeOffset.UtcNow;
ReadDate = DateTimeOffset.UtcNow;
break;
}
}

View File

@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.Linq;
namespace AsbCloudApp.Data;
@ -9,4 +10,8 @@ namespace AsbCloudApp.Data;
public class ParserResultDto<TDto> : ValidationResultDto<IEnumerable<ValidationResultDto<TDto>>>
where TDto : class, IId
{
/// <summary>
/// Объекты полученные из файла
/// </summary>
public override IEnumerable<ValidationResultDto<TDto>> Item { get; set; } = Enumerable.Empty<ValidationResultDto<TDto>>();
}

View File

@ -44,7 +44,7 @@ public class ProcessMapReportDataSaubStatDto
/// на начало интервала
/// </para>
/// </summary>
public DateTime DateStart { get; set; }
public DateTimeOffset DateStart { get; set; }
/// <summary>
/// Режим бурения (Ротор/слайд/ручной)

View File

@ -44,7 +44,7 @@ public class ProcessMapReportWellDrillingDto
/// на начало интервала
/// </para>
/// </summary>
public DateTime DateStart { get; set; }
public DateTimeOffset DateStart { get; set; }
/// <summary>
/// Время мех бурения, ч

View File

@ -29,17 +29,17 @@ namespace AsbCloudApp.Data
/// <summary>
/// Дата формирования
/// </summary>
public DateTime Date { get; set; }
public DateTimeOffset Date { get; set; }
/// <summary>
/// Дата начала рапорта
/// </summary>
public DateTime Begin { get; set; }
public DateTimeOffset Begin { get; set; }
/// <summary>
/// Дата окончания рапорта
/// </summary>
public DateTime End { get; set; }
public DateTimeOffset End { get; set; }
/// <summary>
/// шаг между точками диаграммы

View File

@ -33,7 +33,7 @@ namespace AsbCloudApp.Data.SAUB
/// <summary>
/// отметка времени создания запроса
/// </summary>
public DateTime UploadDate { get; set; } = DateTime.Now;
public DateTimeOffset UploadDate { get; set; } = DateTimeOffset.Now;
/// <summary>
/// время в секундах актуальности этого запроса

View File

@ -15,7 +15,7 @@ namespace AsbCloudApp.Data.SAUB
/// <summary>
/// отметка времени
/// </summary>
public DateTime Date { get; set; }
public DateTimeOffset Date { get; set; }
/// <summary>
/// глубина забоя

View File

@ -10,7 +10,7 @@ namespace AsbCloudApp.Data.SAUB
/// <summary>
/// отметка времени
/// </summary>
public DateTime DateTime { get; set; }
public DateTimeOffset DateTime { get; set; }
/// <summary>
/// Наработка талевого каната с момента перетяжки каната, т*км

View File

@ -39,13 +39,13 @@ namespace AsbCloudApp.Data
/// Начало бурения
/// </summary>
[Required]
public DateTime DrillStart { get; set; }
public DateTimeOffset DrillStart { get; set; }
/// <summary>
/// Конец бурения
/// </summary>
[Required]
public DateTime DrillEnd { get; set; }
public DateTimeOffset DrillEnd { get; set; }
/// <summary>
/// Бурильщик

View File

@ -11,12 +11,12 @@ namespace AsbCloudApp.Data
/// <summary>
/// Дата и время начала
/// </summary>
public DateTime? Start { get; set; }
public DateTimeOffset? Start { get; set; }
/// <summary>
/// Дата и время окончания
/// </summary>
public DateTime? End { get; set; }
public DateTimeOffset? End { get; set; }
/// <summary>
/// Глубина, м

View File

@ -42,7 +42,7 @@ namespace AsbCloudApp.Data
/// дата прихода последней телеметрии
/// </summary>
[Required]
public DateTime LastTelemetryDate { get; set; }
public DateTimeOffset LastTelemetryDate { get; set; }
/// <summary>
/// Статистика по секциям

View File

@ -46,7 +46,7 @@ namespace AsbCloudApp.Data.Trajectory
/// <summary>
/// Дата загрузки
/// </summary>
public DateTime UpdateDate { get; set; }
public DateTimeOffset UpdateDate { get; set; }
/// <summary>
/// ИД пользователя

View File

@ -18,7 +18,7 @@ public class ValidationResultDto<T>
/// <summary>
/// Объект валидации
/// </summary>
public T Item { get; set; } = null!;
public virtual T Item { get; set; } = null!;
/// <summary>
/// Предупреждения

View File

@ -67,12 +67,12 @@ namespace AsbCloudApp.Data
/// <summary>
/// Дата/время первой операции
/// </summary>
public DateTime? StartDate { get; set; }
public DateTimeOffset? StartDate { get; set; }
/// <summary>
/// Дата/время кода приходили данные последний раз
/// </summary>
public DateTime LastTelemetryDate { get; set; }
public DateTimeOffset LastTelemetryDate { get; set; }
/// <summary>
/// ID телеметрии

View File

@ -82,14 +82,14 @@ namespace AsbCloudApp.Data
/// <para>Дата начала первой фактической операции</para>
/// <para>Используется как дата начала бурения</para>
/// </summary>
public DateTime? FirstFactOperationDateStart { get; set; }
public DateTimeOffset? FirstFactOperationDateStart { get; set; }
/// <summary>
/// <para>Дата окончания последней прогнозируемой операции</para>
/// <para>Если скважина завершена, то дата окончания последней фактической операции</para>
/// <para>Используется как прогноз окончания бурения</para>
/// </summary>
public DateTime? LastPredictOperationDateEnd { get; set; }
public DateTimeOffset? LastPredictOperationDateEnd { get; set; }
/// <summary>
/// Рейсовая скорость проходки, последнего рейса

View File

@ -1,6 +1,6 @@
using System.ComponentModel.DataAnnotations;
namespace AsbCloudApp.Data
namespace AsbCloudApp.Data.WellOperation
{
/// <summary>
/// DTO категория операции

View File

@ -0,0 +1,116 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace AsbCloudApp.Data.WellOperation;
public class WellOperationDto : ItemInfoDto,
IId,
IWellRelated,
IValidatableObject
{
/// <inheritdoc/>
[Required]
public int Id { get; set; }
/// <inheritdoc/>
[Required]
public int IdWell { get; set; }
/// <summary>
/// Id секции скважины
/// </summary>
public int IdWellSectionType { get; set; }
/// <summary>
/// 0 = план или 1 = факт или прогноз = 2
/// </summary>
[Required]
public int IdType { get; set; }
/// <summary>
/// id категории операции
/// </summary>
public int IdCategory { get; set; }
/// <summary>
/// Глубина на начало операции, м
/// </summary>
public double DepthStart { get; set; }
/// <summary>
/// Глубина после завершения операции, м
/// </summary>
[Required]
[Range(0, 50_000)]
public double DepthEnd { get; set; }
/// <summary>
/// Дата начала операции
/// </summary>
[Required]
public DateTimeOffset DateStart { get; set; }
/// <summary>
/// Продолжительность, часы
/// </summary>
public double DurationHours { get; set; }
/// <summary>
/// Наименование секции
/// </summary>
public string? WellSectionTypeCaption { get; set; }
/// <summary>
/// Наименование категории
/// </summary>
public string? OperationCategoryName { get; set; }
/// <summary>
/// id плановой операции для сопоставления
/// </summary>
public int? IdPlan { get; set; }
/// <summary>
/// Ключ родителя у категории
/// </summary>
public int? IdParentCategory { get; set; }
/// <summary>
/// дополнительная информация по операции
/// </summary>
[StringLength(8192)]
public string? CategoryInfo { get; set; }
/// <summary>
/// Кол-во дней от даты начала первой плановой (а если её нет, то фактической) операции
/// </summary>
[Required]
public double Day { get; set; }
/// <summary>
/// Кол-во часов НПВ от даты начала первой плановой (а если её нет, то фактической) операции
/// </summary>
[Required]
public double NptHours { get; set; }
/// <summary>
/// Полезный комментарий
/// </summary>
[StringLength(4096, ErrorMessage = "Комментарий не может быть длиннее 4096 символов")]
public string? Comment { get; set; }
/// <summary>
/// Валидация даты
/// </summary>
/// <param name="validationContext"></param>
/// <returns></returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var gtDate = new DateTimeOffset(2010, 1, 1, 0, 0, 0, TimeSpan.Zero);
if (DateStart <= gtDate)
yield return new ValidationResult(
$"{nameof(DateStart)}: DateStart не может быть меньше {gtDate}",
new[] { nameof(DateStart) });
}
}

View File

@ -1,39 +0,0 @@
namespace AsbCloudApp.Data
{
/// Операция на скважине
public class WellOperationDataDto : IWellRelated
{
/// <inheritdoc/>
public int IdWell { get; set; }
/// <summary>
/// id секции скважины
/// </summary>
public int IdWellSectionType { get; set; }
/// <summary>
/// id категории операции
/// </summary>
public int IdCategory { get; set; }
/// <summary>
/// Глубина на начало операции, м
/// </summary>
public double DepthStart { get; set; }
/// <summary>
/// Продолжительность, часы
/// </summary>
public double DurationHours { get; set; }
/// <summary>
/// Наименование секции
/// </summary>
public string WellSectionTypeCaption { get; set; } = string.Empty;
/// <summary>
/// Наименование категории
/// </summary>
public string OperationCategoryName { get; set; } = string.Empty;
}
}

View File

@ -1,124 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace AsbCloudApp.Data
{
/// <summary>
/// Операции на скважине (заведенные пользователем)
/// </summary>
public class WellOperationDto : ItemInfoDto, IId, IWellRelated, IValidatableObject
{
/// <inheritdoc/>
[Required]
public int Id { get; set; }
/// <inheritdoc/>
[Required]
public int IdWell { get; set; }
/// <summary>
/// id секции скважины
/// </summary>
[Required]
public int IdWellSectionType { get; set; }
/// <summary>
/// название секции скважины
/// </summary>
public string? WellSectionTypeName { get; set; }
/// <summary>
/// id категории операции
/// </summary>
[Required]
[Range(5000, int.MaxValue)]
public int IdCategory { get; set; }
/// <summary>
/// id плановой операции для сопоставления
/// </summary>
public int? IdPlan { get; set; }
/// <summary>
/// название категории операции
/// </summary>
public string? CategoryName { get; set; }
/// <summary>
/// ключ родителя у категории
/// </summary>
public int? IdParentCategory { get; set; }
/// <summary>
/// дополнительная информация по операции
/// </summary>
[StringLength(8192)]
public string? CategoryInfo { get; set; }
/// <summary>
/// 0 = план или 1 = факт или прогноз = 2
/// </summary>
[Required]
public int IdType { get; set; }
/// <summary>
/// Глубина на начало операции, м
/// </summary>
[Required]
[Range(0, 50_000)]
public double DepthStart { get; set; }
/// <summary>
/// Глубина после завершения операции, м
/// </summary>
[Required]
[Range(0, 50_000)]
public double DepthEnd { get; set; }
/// <summary>
/// Кол-во дней от даты начала первой плановой (а если её нет, то фактической) операции
/// </summary>
[Required]
public double Day { get; set; }
/// <summary>
/// Кол-во часов НПВ от даты начала первой плановой (а если её нет, то фактической) операции
/// </summary>
[Required]
public double NptHours { get; set; }
/// <summary>
/// Дата начала операции
/// </summary>
[Required]
public DateTimeOffset DateStart { get; set; }
/// <summary>
/// Продолжительность, часы
/// </summary>
[Required]
[Range(0, 50)]
public double DurationHours { get; set; }
/// <summary>
/// Полезный комментарий
/// </summary>
[StringLength(4096, ErrorMessage = "Комментарий не может быть длиннее 4096 символов")]
public string? Comment { get; set; }
/// <summary>
/// Валидация даты
/// </summary>
/// <param name="validationContext"></param>
/// <returns></returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var gtDate = new DateTimeOffset(2010, 1, 1, 0, 0, 0, TimeSpan.Zero);
if (DateStart <= gtDate)
yield return new ValidationResult(
$"{nameof(DateStart)}: DateStart не может быть меньше {gtDate}",
new[] { nameof(DateStart) });
}
}
}

View File

@ -1,28 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace AsbCloudApp.Data
{
/// <summary>
/// класс, который хранит список плановых операций для сопоставления
/// и даты последней сопоставленной плановой операции
/// </summary>
#nullable enable
public class WellOperationPlanDto
{
/// <summary>
/// коллекция плановых операций
/// </summary>
[Required]
public IEnumerable<WellOperationDto> WellOperationsPlan { get; set; } = Enumerable.Empty<WellOperationDto>();
/// <summary>
/// дата последней сопоставленной плановой операции
/// </summary>
public DateTime? DateLastAssosiatedPlanOperation { get; set; }
}
}

View File

@ -1,5 +1,5 @@
using AsbCloudApp.Data;
using System.Collections.Generic;
using System.Collections.Generic;
using AsbCloudApp.Data.WellOperation;
namespace AsbCloudApp.Repositories
{

View File

@ -1,9 +1,9 @@
using AsbCloudApp.Data;
using AsbCloudApp.Requests;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data.WellOperation;
using AsbCloudApp.Requests;
namespace AsbCloudApp.Repositories
{
@ -17,24 +17,8 @@ namespace AsbCloudApp.Repositories
/// </summary>
/// <returns></returns>
IEnumerable<WellSectionTypeDto> GetSectionTypes();
/// <summary>
/// список плановых операций для сопоставления
/// <param name="idWell"></param>
/// <param name="currentDate"></param>
/// <param name="token"></param>
/// </summary>
/// <returns></returns>
Task<WellOperationPlanDto> GetOperationsPlanAsync(int idWell, DateTime? currentDate, CancellationToken token);
/// <summary>
/// дата/время первой операции по скважине
/// </summary>
/// <param name="idWell"></param>
/// <returns></returns>
DateTimeOffset? FirstOperationDate(int idWell);
/// <summary>
/// <summary>
/// Получить страницу списка операций
/// </summary>
/// <param name="request"></param>
@ -42,15 +26,7 @@ namespace AsbCloudApp.Repositories
/// <returns></returns>
Task<IEnumerable<WellOperationDto>> GetAsync(WellOperationRequest request, CancellationToken token);
/// <summary>
/// Получить список операций по запросу
/// </summary>
/// <param name="request"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<WellOperationDataDto>> GetAsync(WellsOperationRequest request, CancellationToken token);
/// <summary>
/// <summary>
/// Получить страницу списка операций
/// </summary>
/// <param name="request"></param>
@ -58,31 +34,22 @@ namespace AsbCloudApp.Repositories
/// <returns></returns>
Task<PaginationContainer<WellOperationDto>> GetPageAsync(WellOperationRequest request, CancellationToken token);
/// <summary>
/// Получить операцию по id
/// </summary>
/// <param name="id"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<WellOperationDto?> GetOrDefaultAsync(int id, CancellationToken token);
/// <summary>
/// <summary>
/// Получить статистику операции по скважине с группировкой по категориям
/// </summary>
/// <param name="request"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<WellGroupOpertionDto>> GetGroupOperationsStatAsync(
WellOperationRequest request,
CancellationToken token);
Task<IEnumerable<WellGroupOpertionDto>> GetGroupOperationsStatAsync(WellOperationRequest request, CancellationToken token);
/// <summary>
/// Добавить несколько операций за один раз
/// </summary>
/// <param name="wellOperationDtos"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> InsertRangeAsync(IEnumerable<WellOperationDto> wellOperationDtos, CancellationToken token);
/// <summary>
/// Добавить несколько операций
/// </summary>
/// <param name="dtos"></param>
/// <param name="deleteBeforeInsert"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> InsertRangeAsync(IEnumerable<WellOperationDto> dtos, bool deleteBeforeInsert, CancellationToken token);
/// <summary>
/// Обновить существующую операцию
@ -90,7 +57,7 @@ namespace AsbCloudApp.Repositories
/// <param name="dto"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> UpdateAsync(WellOperationDto dto, CancellationToken token);
Task<int> UpdateRangeAsync(IEnumerable<WellOperationDto> dtos, CancellationToken token);
/// <summary>
/// Удалить операции по id
@ -98,7 +65,7 @@ namespace AsbCloudApp.Repositories
/// <param name="ids"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> DeleteAsync(IEnumerable<int> ids, CancellationToken token);
Task<int> DeleteRangeAsync(IEnumerable<int> ids, CancellationToken token);
/// <summary>
/// Получить секции скважин из операций ГГД. Секцие поделены на плановые и фактические.
@ -115,24 +82,6 @@ namespace AsbCloudApp.Repositories
/// <param name="idType"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<DatesRangeDto?> GetDatesRangeAsync(int idWell, int idType, CancellationToken cancellationToken);
/// <summary>
/// Удаление полных дубликатов операций по всем скважинам
/// </summary>
/// <param name="onProgressCallback"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> RemoveDuplicates(Action<string, double?> onProgressCallback, CancellationToken token);
/// <summary>
/// Усечение пересекающейся последующей операции по дате и глубине забоя
/// </summary>
/// <param name="geDate">Фильтр по дате. Если хоть одна операция попадет в в фильтр, то будет обработана вся скважина, а не только эта операция</param>
/// <param name="leDate">Фильтр по дате. Если хоть одна операция попадет в в фильтр, то будет обработана вся скважина, а не только эта операция</param>
/// <param name="onProgressCallback"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> TrimOverlapping(DateTimeOffset? geDate, DateTimeOffset leDate, Action<string, double?> onProgressCallback, CancellationToken token);
}
Task<DatesRangeDto?> GetDatesRangeAsync(int idWell, int idType, CancellationToken cancellationToken);
}
}

View File

@ -0,0 +1,20 @@
namespace AsbCloudApp.Requests.ExportOptions;
/// <summary>
/// Параметры экспорта ГГД
/// </summary>
public class WellOperationExportRequest : WellRelatedExportRequest
{
/// <inheritdoc />
public WellOperationExportRequest(int idWell,
int idType)
: base(idWell)
{
IdType = idType;
}
/// <summary>
/// Тип операций
/// </summary>
public int IdType { get; }
}

View File

@ -33,12 +33,12 @@ namespace AsbCloudApp.Requests
/// <summary>
/// Дата начала периода
/// </summary>
public DateTime? Begin { get; set; }
public DateTimeOffset? Begin { get; set; }
/// <summary>
/// Дата окончания периода
/// </summary>
public DateTime? End { get; set; }
public DateTimeOffset? End { get; set; }
/// <summary>
/// Признак удаления

View File

@ -17,12 +17,12 @@ namespace AsbCloudApp.Requests
/// <summary>
/// Больше или равно дате
/// </summary>
public DateTime? GtDate { get; set; }
public DateTimeOffset? GtDate { get; set; }
/// <summary>
/// Меньше или равно дате
/// </summary>
public DateTime? LtDate { get; set; }
public DateTimeOffset? LtDate { get; set; }
/// <summary>
/// Больше или равно глубины забоя

View File

@ -17,12 +17,12 @@ namespace AsbCloudApp.Requests
/// <summary>
/// начальная дата
/// </summary>
public DateTime? Begin { get; set; }
public DateTimeOffset? Begin { get; set; }
/// <summary>
/// конечная дата
/// </summary>
public DateTime? End { get; set; }
public DateTimeOffset? End { get; set; }
/// <summary>
/// строка поиска

View File

@ -15,10 +15,10 @@ public class NotificationDeleteRequest
/// <summary>
/// Меньше или равно дате отправки
/// </summary>
public DateTime? LtSentDate { get; set; }
public DateTimeOffset? LtSentDate { get; set; }
/// <summary>
/// Меньше или равно дате прочтения
/// </summary>
public DateTime? LtReadDate { get; set; }
public DateTimeOffset? LtReadDate { get; set; }
}

View File

@ -0,0 +1,29 @@
using AsbCloudApp.Data;
namespace AsbCloudApp.Requests.ParserOptions;
/// <summary>
/// Параметры парсинга ГГД
/// </summary>
public class WellOperationParserRequest : WellRelatedParserRequest
{
/// <inheritdoc />
public WellOperationParserRequest(int idWell,
int idType,
SimpleTimezoneDto wellTimezone)
: base(idWell)
{
IdType = idType;
WellTimezone = wellTimezone;
}
/// <summary>
/// Тип операции
/// </summary>
public int IdType { get; }
/// <summary>
/// Часовой пояс в котором находится скважина
/// </summary>
public SimpleTimezoneDto WellTimezone { get; }
}

View File

@ -20,5 +20,5 @@ public class ProcessMapPlanRequest
/// <summary>
/// Дата обновления
/// </summary>
public DateTime? UpdateFrom { get; set; }
public DateTimeOffset? UpdateFrom { get; set; }
}

View File

@ -24,12 +24,12 @@ public class ReportParametersRequest: IValidatableObject
/// <summary>
/// Дата начала интервала
/// </summary>
public DateTime Begin { get; set; } = default;
public DateTimeOffset Begin { get; set; } = default;
/// <summary>
/// Дата окончания интервала
/// </summary>
public DateTime End { get; set; } = default;
public DateTimeOffset End { get; set; } = default;
/// <inheritdoc/>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
@ -37,7 +37,7 @@ public class ReportParametersRequest: IValidatableObject
if (End < Begin)
yield return new("End mast be less then begin");
if (Begin < new DateTime(2000, 1, 1))
if (Begin < new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero))
yield return new("Begin mast be > 2000-1-1");
}
}

View File

@ -9,7 +9,7 @@ namespace AsbCloudApp.Requests
/// </summary>
public class SubsystemRequest: RequestBase, IValidatableObject
{
private static readonly DateTime validationMinDate = new DateTime(2020,01,01,0,0,0,DateTimeKind.Utc);
private static readonly DateTimeOffset validationMinDate = new DateTimeOffset(2020,01,01,0,0,0, TimeSpan.Zero);
/// <summary>
/// идентификатор скважины

View File

@ -15,10 +15,10 @@ public class TrajectoryRequest : RequestBase
/// <summary>
/// Больше или равно дате
/// </summary>
public DateTime? GeDate { get; set; }
public DateTimeOffset? GeDate { get; set; }
/// <summary>
/// Меньше или равно дате
/// </summary>
public DateTime? LeDate { get; set; }
public DateTimeOffset? LeDate { get; set; }
}

View File

@ -1,112 +1,84 @@
using System;
using System.Collections.Generic;
namespace AsbCloudApp.Requests
namespace AsbCloudApp.Requests;
/// <summary>
/// Запрос получения ГГД
/// </summary>
public class WellOperationRequestBase : RequestBase
{
/// <summary>
/// параметры для запроса списка операций
/// </summary>
public class WellOperationRequestBase : RequestBase
{
/// <summary>
/// фильтр по дате начала операции
/// </summary>
public DateTime? GeDate { get; set; }
/// <summary>
/// Больше или равно дате начала операции
/// </summary>
public DateTimeOffset? GeDate { get; set; }
/// <summary>
/// фильтр по дате окончания операции
/// </summary>
public DateTime? LtDate { get; set; }
/// <summary>
/// Меньше или равно дате окончания операции
/// </summary>
public DateTimeOffset? LeDate { get; set; }
/// <summary>
/// фильтр. Больше или равно глубины скважины на начало операции.
/// </summary>
public double? GeDepth { get; set; }
/// <summary>
/// Больше или равно глубины скважины на начало операции.
/// </summary>
public double? GeDepth { get; set; }
/// <summary>
/// фильтр. Меньше или равно глубины скважины на конец операции.
/// </summary>
public double? LeDepth { get; set; }
/// <summary>
/// Меньше или равно глубины скважины на конец операции.
/// </summary>
public double? LeDepth { get; set; }
/// <summary>
/// фильтр по списку id категорий операции
/// </summary>
public IEnumerable<int>? OperationCategoryIds { get; set; }
/// <summary>
/// Идентификаторы категорий операции
/// </summary>
public IEnumerable<int>? OperationCategoryIds { get; set; }
/// <summary>
/// фильтр по план = 0, факт = 1
/// </summary>
public int? OperationType { get; set; }
/// <summary>
/// Тип операций
/// <list type="bullet">
/// <item>0 - плановая операция</item>
/// <item>1 - фактическая операция</item>
/// </list>
/// </summary>
public int? OperationType { get; set; }
/// <summary>
/// фильтр по списку id конструкций секции
/// </summary>
public IEnumerable<int>? SectionTypeIds { get; set; }
/// <summary>
/// Параметры для запроса списка операций.
/// Базовый конструктор
/// </summary>
public WellOperationRequestBase()
{ }
/// <summary>
/// Параметры для запроса списка операций.
/// Копирующий конструктор
/// </summary>
/// <param name="request"></param>
public WellOperationRequestBase(WellOperationRequestBase request)
{
GeDepth = request.GeDepth;
LeDepth = request.LeDepth;
GeDate = request.GeDate;
LtDate = request.LtDate;
OperationCategoryIds = request.OperationCategoryIds;
OperationType = request.OperationType;
SectionTypeIds = request.SectionTypeIds;
Skip = request.Skip;
Take = request.Take;
SortFields = request.SortFields;
}
}
/// <summary>
/// Параметры для запроса списка операций (с id скважины)
/// </summary>
public class WellOperationRequest : WellOperationRequestBase
{
/// <summary>
/// id скважины
/// </summary>
public int IdWell { get; set; }
/// <summary>
/// ctor
/// </summary>
public WellOperationRequest() { }
/// <summary>
/// копирующий конструктор
/// </summary>
/// <param name="request"></param>
/// <param name="idWell"></param>
public WellOperationRequest(WellOperationRequestBase request, int idWell)
:base(request)
{
IdWell = idWell;
}
}
/// <summary>
/// Параметры для запроса списка операций (с массивом id скважин)
/// </summary>
public class WellsOperationRequest : WellOperationRequestBase
{
/// <summary>
/// ids скважин
/// </summary>
public IEnumerable<int> IdsWell { get; set; } = null!;
}
/// <summary>
/// Идентификаторы конструкций секции
/// </summary>
public IEnumerable<int>? SectionTypeIds { get; set; }
}
/// <summary>
/// Запрос получения ГГД с идентификаторами скважин
/// </summary>
public class WellOperationRequest : WellOperationRequestBase
{
/// <inheritdoc />
public WellOperationRequest(IEnumerable<int> idsWell)
{
IdsWell = idsWell;
}
/// <inheritdoc />
public WellOperationRequest(WellOperationRequestBase request, IEnumerable<int> idsWell)
: this(idsWell)
{
GeDepth = request.GeDepth;
LeDepth = request.LeDepth;
GeDate = request.GeDate;
LeDate = request.LeDate;
OperationCategoryIds = request.OperationCategoryIds;
OperationType = request.OperationType;
SectionTypeIds = request.SectionTypeIds;
Skip = request.Skip;
Take = request.Take;
SortFields = request.SortFields;
}
/// <summary>
/// Идентификаторы скважин
/// </summary>
public IEnumerable<int>? IdsWell { get; }
}

View File

@ -42,12 +42,4 @@ public interface IDailyReportService
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<PaginationContainer<DailyReportDto>> GetAsync(int idWell, FileReportRequest request, CancellationToken cancellationToken);
/// <summary>
/// Получить диапазон дат по которым возможно сформировать суточный отчёты
/// </summary>
/// <param name="idWell"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<DatesRangeDto?> GetDatesRangeAsync(int idWell, CancellationToken cancellationToken);
}

View File

@ -3,12 +3,12 @@ using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Requests.ExportOptions;
namespace AsbCloudApp.Services;
namespace AsbCloudApp.Services.Export;
/// <summary>
/// Экспорт данных
/// </summary>
public interface IExportService<in TOptions>
public interface IExportService<in TOptions> : IExportService
where TOptions : IExportOptionsRequest
{
/// <summary>
@ -18,4 +18,12 @@ public interface IExportService<in TOptions>
/// <param name="token"></param>
/// <returns></returns>
Task<(string FileName, Stream File)> ExportAsync(TOptions options, CancellationToken token);
}
/// <summary>
/// Экспорт данных
/// </summary>
public interface IExportService
{
}

View File

@ -0,0 +1,20 @@
using AsbCloudApp.Requests.ExportOptions;
namespace AsbCloudApp.Services.Export;
/// <summary>
/// Фабрика создания сервисов для экспорта
/// </summary>
/// <typeparam name="TId"></typeparam>
public interface IExportServiceFactory<in TId>
where TId : struct
{
/// <summary>
/// Создать сервис экспорта
/// </summary>
/// <param name="id"></param>
/// <typeparam name="TOptions"></typeparam>
/// <returns></returns>
IExportService<TOptions> CreateExportService<TOptions>(TId id)
where TOptions : IExportOptionsRequest;
}

View File

@ -1,10 +1,10 @@
using System;
using AsbCloudApp.Data;
using AsbCloudApp.Data.DetectedOperation;
using AsbCloudApp.Requests;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data.WellOperation;
namespace AsbCloudApp.Services
{

View File

@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data.WellOperation;
namespace AsbCloudApp.Services
{

View File

@ -46,7 +46,7 @@ namespace AsbCloudApp.Services
/// <param name="stepSeconds"></param>
/// <param name="format"></param>
/// <returns></returns>
int GetReportPagesCount(int idWell, DateTime begin, DateTime end,
int GetReportPagesCount(int idWell, DateTimeOffset begin, DateTimeOffset end,
int stepSeconds, int format);
/// <summary>

View File

@ -19,7 +19,7 @@ namespace AsbCloudApp.Services
/// <param name="workTime"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<ScheduleDto>> GetAsync(int idWell, DateTime workTime, CancellationToken token);
Task<IEnumerable<ScheduleDto>> GetAsync(int idWell, DateTimeOffset workTime, CancellationToken token);
/// <summary>
/// получить бурильщика по idWell и времени
@ -28,7 +28,7 @@ namespace AsbCloudApp.Services
/// <param name="workTime"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<DrillerDto?> GetOrDefaultDrillerAsync(int idWell, DateTime workTime, CancellationToken token);
Task<DrillerDto?> GetOrDefaultDrillerAsync(int idWell, DateTimeOffset workTime, CancellationToken token);
/// <summary>
/// Получить расписание смен

View File

@ -1,7 +1,7 @@
using AsbCloudApp.Data;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data.WellOperation;
namespace AsbCloudApp.Services
{
@ -16,6 +16,6 @@ namespace AsbCloudApp.Services
/// <param name="idsWells"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<List<Dictionary<int, WellOperationDataDto>>> GetAsync(IEnumerable<int> idsWells, CancellationToken token);
Task<IEnumerable<Dictionary<int, WellOperationDto>>> GetAsync(IEnumerable<int> idsWells, CancellationToken token);
}
}

View File

@ -72,7 +72,7 @@ namespace AsbCloudApp.Services
/// </summary>
/// <param name="idWell"></param>
/// <returns></returns>
DateTime GetLastTelemetryDate(int idWell);
DateTimeOffset GetLastTelemetryDate(int idWell);
//TODO: выяснить и удалить отсюда
/// <summary>

View File

@ -49,7 +49,7 @@ public class NotificationService
var notification = new NotificationDto
{
IdUser = request.IdUser,
RegistrationDate = DateTime.UtcNow,
RegistrationDate = DateTimeOffset.UtcNow,
IdNotificationCategory = notificationCategory.Id,
Title = request.Title,
Message = request.Message,
@ -71,7 +71,7 @@ public class NotificationService
Console.WriteLine(ex.Message);
}
notification.SentDate = DateTime.UtcNow;
notification.SentDate = DateTimeOffset.UtcNow;
await notificationRepository.UpdateAsync(notification, cancellationToken);
}
@ -92,7 +92,7 @@ public class NotificationService
if(isRead && !notification.SentDate.HasValue)
throw new ArgumentInvalidException(nameof(isRead), "Уведомление не может быть прочитано");
notification.ReadDate = isRead ? DateTime.UtcNow : null;
notification.ReadDate = isRead ? DateTimeOffset.UtcNow : null;
await notificationRepository.UpdateAsync(notification,
cancellationToken);
@ -119,7 +119,7 @@ public class NotificationService
var tasks = notifications.Select(notification =>
{
notification.SentDate = DateTime.UtcNow;
notification.SentDate = DateTimeOffset.UtcNow;
return notificationRepository.UpdateAsync(notification, cancellationToken);
});

View File

@ -0,0 +1,23 @@
using AsbCloudApp.Data;
using AsbCloudApp.Requests.ParserOptions;
namespace AsbCloudApp.Services.Parsers;
/// <summary>
/// Фабрика для создания сервиса парсинга
/// </summary>
/// <typeparam name="TId"></typeparam>
/// <typeparam name="TDto"></typeparam>
public interface IParserFactory<in TId, TDto>
where TId : struct
where TDto : class, IId
{
/// <summary>
/// Создать парсер
/// </summary>
/// <param name="id"></param>
/// <typeparam name="TOptions"></typeparam>
/// <returns></returns>
IParserService<TDto, TOptions> CreateParser<TOptions>(TId id)
where TOptions : IParserOptionsRequest;
}

View File

@ -2,14 +2,14 @@ using System.IO;
using AsbCloudApp.Data;
using AsbCloudApp.Requests.ParserOptions;
namespace AsbCloudApp.Services;
namespace AsbCloudApp.Services.Parsers;
/// <summary>
/// Сервис парсинга
/// </summary>
/// <typeparam name="TDto"></typeparam>
/// <typeparam name="TOptions"></typeparam>
public interface IParserService<TDto, in TOptions>
public interface IParserService<TDto, in TOptions> : IParserService
where TDto : class, IId
where TOptions : IParserOptionsRequest
{
@ -26,4 +26,11 @@ public interface IParserService<TDto, in TOptions>
/// </summary>
/// <returns></returns>
Stream GetTemplateFile();
}
/// <summary>
/// Сервис парсинга
/// </summary>
public interface IParserService
{
}

View File

@ -1,20 +0,0 @@
using System.IO;
using AsbCloudApp.Data.WellOperationImport;
using AsbCloudApp.Data.WellOperationImport.Options;
namespace AsbCloudApp.Services.WellOperationImport;
/// <summary>
/// Парсинг операций из excel файла
/// </summary>
public interface IWellOperationExcelParser<in TOptions>
where TOptions : IWellOperationImportOptions
{
/// <summary>
/// Метод парсинга документа
/// </summary>
/// <param name="stream"></param>
/// <param name="options"></param>
/// <returns></returns>
SheetDto Parse(Stream stream, TOptions options);
}

View File

@ -1,19 +0,0 @@
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Services.WellOperationImport;
/// <summary>
/// Экспорт ГГД
/// </summary>
public interface IWellOperationExportService
{
/// <summary>
/// Скачать в excel
/// </summary>
/// <param name="idWell"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<Stream> ExportAsync(int idWell, CancellationToken cancellationToken);
}

View File

@ -1,20 +0,0 @@
using System.Collections.Generic;
using AsbCloudApp.Data;
using AsbCloudApp.Data.WellOperationImport;
namespace AsbCloudApp.Services.WellOperationImport;
/// <summary>
/// Импорт ГГД
/// </summary>
public interface IWellOperationImportService
{
/// <summary>
/// Загрузить из excel список операций
/// </summary>
/// <param name="idWell"></param>
/// <param name="idUser"></param>
/// <param name="idType"></param>
/// <param name="sheet"></param>
IEnumerable<WellOperationDto> Import(int idWell, int idUser, int idType, SheetDto sheet);
}

View File

@ -1,15 +0,0 @@
using System.IO;
namespace AsbCloudApp.Services.WellOperationImport;
/// <summary>
/// Сервис для получения шаблонов ГГД
/// </summary>
public interface IWellOperationImportTemplateService
{
/// <summary>
/// Скачать шаблон для заполнения
/// </summary>
/// <returns></returns>
Stream GetExcelTemplateStream();
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,32 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AsbCloudDb.Migrations
{
/// <inheritdoc />
public partial class Update_WellOperationCategory_IdConditioning : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "t_well_operation_category",
keyColumn: "id",
keyValue: 5007,
column: "name",
value: "Проработка");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "t_well_operation_category",
keyColumn: "id",
keyValue: 5007,
column: "name",
value: "Проработка перед наращиванием");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -18,7 +18,7 @@ public class DailyReport : IId
public int IdWell { get; set; }
[Column("date_last_update", TypeName = "timestamp with time zone"), Comment("Дата последнего обновления")]
public DateTime? DateLastUpdate { get; set; }
public DateTimeOffset? DateLastUpdate { get; set; }
[Column("date", TypeName = "date"), Comment("Дата формирования отчёта")]
public DateOnly Date { get; set; }

View File

@ -12,6 +12,6 @@ namespace AsbCloudDb.Model
/// <summary>
/// дата последнего обновления блока
/// </summary>
public DateTimeOffset LastUpdateDate { get; set; } = DateTimeOffset.Now;
public DateTimeOffset LastUpdateDate { get; set; } = DateTimeOffset.UtcNow;
}
}

View File

@ -15,8 +15,8 @@ public class Manual : IId
[Column("name"), Comment("Название")]
public string Name { get; set; } = null!;
[Column("date_download"), Comment("Дата загрузки")]
public DateTime DateDownload { get; set; }
[Column("date_download", TypeName = "timestamp with time zone"), Comment("Дата загрузки")]
public DateTimeOffset DateDownload { get; set; }
[Column("id_directory"), Comment("Id директории")]
public int IdDirectory { get; set; }

View File

@ -25,13 +25,13 @@ public class Notification : IId
public string Message { get; set; } = null!;
[Column("registration_date"), Comment("Дата регистрации уведомления")]
public DateTime RegistrationDate { get; set; }
public DateTimeOffset RegistrationDate { get; set; }
[Column("sent_date"), Comment("Дата отправки уведомления")]
public DateTime? SentDate { get; set; }
public DateTimeOffset? SentDate { get; set; }
[Column("read_date"), Comment("Дата прочтения уведомления")]
public DateTime? ReadDate { get; set; }
public DateTimeOffset? ReadDate { get; set; }
[Column("id_transport_type"), Comment("Id типа доставки уведомления")]
public int IdTransportType { get; set; }

View File

@ -67,23 +67,6 @@ namespace AsbCloudDb.Model
[JsonIgnore]
[ForeignKey(nameof(IdPlan))]
public virtual WellOperation? OperationPlan { get; set; } = null!;
public bool IsSame(WellOperation other)
{
var isSame = IdWell == other.IdWell &&
IdWellSectionType == other.IdWellSectionType &&
IdCategory == other.IdCategory &&
IdType == other.IdType &&
IdPlan == other.IdPlan &&
DepthStart == other.DepthStart &&
DepthEnd == other.DepthEnd &&
DateStart == other.DateStart &&
DurationHours == other.DurationHours &&
CategoryInfo == other.CategoryInfo &&
Comment == other.Comment;
return isSame;
}
}
}

View File

@ -154,9 +154,9 @@ namespace AsbCloudDb.Model
/// </summary>
public const int IdFlashingBeforeConnection = 5005;
/// <summary>
/// Проработка перед наращиванием
/// Проработка
/// </summary>
public const int IdDevelopment = 5007;
public const int IdConditioning = 5007;
/// <summary>
/// Шаблонировка во время бурения
/// </summary>
@ -278,7 +278,7 @@ namespace AsbCloudDb.Model
new () {Id = IdStaticSurveying, IdParent = 4002, Name = "Замер ЗТС (запись MWD)", KeyValueName = "dT", KeyValueUnits = "мин" },
new () {Id = IdFlashingBeforeConnection, IdParent = 4003, Name = "Промывка перед наращиванием", KeyValueName = "dT", KeyValueUnits = "мин" },
new () {Id = 5006, IdParent = 4003, Name = "Проработка во время бурения", KeyValueName = "dT", KeyValueUnits = "мин" },
new () {Id = IdDevelopment, IdParent = 4003, Name = "Проработка перед наращиванием", KeyValueName = "dT", KeyValueUnits = "мин" },
new () {Id = IdConditioning, IdParent = 4003, Name = "Проработка", KeyValueName = "dT", KeyValueUnits = "мин" },
new () {Id = IdTemplatingWhileDrilling, IdParent = 4003, Name = "Шаблонировка во время бурения", KeyValueName = "dT", KeyValueUnits = "мин" },
new () {Id = IdTemplating, IdParent = 4003, Name = "Шаблонировка перед наращиванием", KeyValueName = "dT", KeyValueUnits = "мин" },
new () {Id = 5010, IdParent = 4004, Name = "Наращивание", KeyValueName = "dT", KeyValueUnits = "мин" },

View File

@ -45,11 +45,9 @@
<EmbeddedResource Include="Services\Trajectory\Templates\TrajectoryFactManualTemplate.xlsx" />
<EmbeddedResource Include="Services\Trajectory\Templates\TrajectoryPlanTemplate.xlsx" />
<EmbeddedResource Include="Services\WellOperationService\ScheduleReportTemplate.xlsx" />
<EmbeddedResource Include="Services\WellOperationImport\Files\WellOperationImportTemplate.xlsx" />
<EmbeddedResource Include="Services\WellOperationImport\Files\Dictionaries\Operations.txt" />
<EmbeddedResource Include="Services\WellOperationImport\Files\Dictionaries\Sections.txt" />
<EmbeddedResource Include="Services\WellOperationImport\Files\Dictionaries\OperationAttributes.txt" />
<EmbeddedResource Include="Services\ProcessMaps\Report\ProcessMapReportTemplate.xlsx" />
<EmbeddedResource Include="Services\WellOperations\Templates\WellOperationFactTemplate.xlsx" />
<EmbeddedResource Include="Services\WellOperations\Templates\WellOperationPlanTemplate.xlsx" />
</ItemGroup>
<ItemGroup>
@ -77,4 +75,5 @@
<HintPath>CommonLibs\AsbWitsInfo.dll</HintPath>
</Reference>
</ItemGroup>
</Project>

View File

@ -27,7 +27,7 @@ namespace AsbCloudInfrastructure.Background
await notificationService.SendAsync(notification, token);
notification.SentDate = DateTime.UtcNow;
notification.SentDate = DateTimeOffset.UtcNow;
await notificationRepository.UpdateAsync(notification, token);
}

View File

@ -14,7 +14,6 @@ using AsbCloudApp.Services.DailyReport;
using AsbCloudApp.Services.Notifications;
using AsbCloudApp.Services.ProcessMaps;
using AsbCloudApp.Services.ProcessMaps.WellDrilling;
using AsbCloudApp.Services.WellOperationImport;
using AsbCloudDb.Model;
using AsbCloudDb.Model.DailyReports.Blocks.TimeBalance;
using AsbCloudDb.Model.Manuals;
@ -36,8 +35,6 @@ using AsbCloudInfrastructure.Services.Subsystems;
using AsbCloudInfrastructure.Services.Trajectory;
using AsbCloudInfrastructure.Services.Trajectory.Export;
using AsbCloudInfrastructure.Services.Trajectory.Parser;
using AsbCloudInfrastructure.Services.WellOperationImport;
using AsbCloudInfrastructure.Services.WellOperationImport.FileParser;
using AsbCloudInfrastructure.Services.WellOperationService;
using Mapster;
using Microsoft.EntityFrameworkCore;
@ -46,6 +43,7 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using AsbCloudInfrastructure.Services.ProcessMapPlan.Export;
using AsbCloudInfrastructure.Services.WellOperations.Factories;
namespace AsbCloudInfrastructure
{
@ -160,7 +158,6 @@ namespace AsbCloudInfrastructure
services.AddTransient<ITelemetryUserService, TelemetryUserService>();
services.AddTransient<ITimezoneService, TimezoneService>();
services.AddScoped<IWellService, WellService>();
services.AddTransient<IWellOperationImportService, WellOperationImportService>();
services.AddTransient<IProcessMapReportDrillingExportService, ProcessMapReportDataSaubStatExportService>();
services.AddTransient<IWellOperationRepository, WellOperationRepository>();
services.AddTransient<IDailyReportService, DailyReportService>();
@ -270,13 +267,6 @@ namespace AsbCloudInfrastructure
services.AddTransient<IWellboreService, WellboreService>();
services.AddTransient<IWellOperationExportService, WellOperationExportService>();
services.AddTransient<IWellOperationImportService, WellOperationImportService>();
services.AddTransient<IWellOperationImportTemplateService, WellOperationImportTemplateService>();
services.AddTransient<IWellOperationExcelParser<WellOperationImportDefaultOptionsDto>, WellOperationDefaultExcelParser>();
services.AddTransient<IWellOperationExcelParser<WellOperationImportGazpromKhantosOptionsDto>, WellOperationGazpromKhantosExcelParser>();
services.AddTransient<DetectedOperationExportService>();
services.AddTransient<IDailyReportService, DailyReportService>();
@ -300,6 +290,9 @@ namespace AsbCloudInfrastructure
services.AddTransient<ProcessMapPlanDrillingExportService>();
services.AddTransient<ProcessMapPlanReamExportService>();
services.AddTransient<WellOperationParserFactory>();
services.AddTransient<WellOperationExportServiceFactory>();
return services;
}

View File

@ -7,6 +7,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace AsbCloudInfrastructure.Repository
{
@ -86,7 +87,7 @@ namespace AsbCloudInfrastructure.Repository
entity.Id = 0;
return entity;
});
var entries = new List<Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry>(items.Count());
var entries = new List<EntityEntry>(items.Count());
foreach (var entity in entities)
{
var entry = dbSet.Add(entity);
@ -114,6 +115,27 @@ namespace AsbCloudInfrastructure.Repository
entry.State = EntityState.Detached;
return entry.Entity.Id;
}
public virtual async Task<int> UpdateRangeAsync(IEnumerable<TDto> dtos, CancellationToken token)
{
if (!dtos.Any())
return 0;
var ids = dtos.Select(d => d.Id);
var countExistingEntities = await dbSet
.Where(d => ids.Contains(d.Id))
.CountAsync(token);
if (ids.Count() > countExistingEntities)
return ICrudRepository<TDto>.ErrorIdNotFound;
var entities = dtos.Select(Convert);
var entries = entities.Select(entity => dbSet.Update(entity)).Cast<EntityEntry>().ToList();
var affected = await dbContext.SaveChangesAsync(token);
entries.ForEach(e => e.State = EntityState.Detached);
return affected;
}
/// <inheritdoc/>
public virtual Task<int> DeleteAsync(int id, CancellationToken token)
@ -129,6 +151,25 @@ namespace AsbCloudInfrastructure.Repository
return affected;
}
public virtual async Task<int> DeleteRangeAsync(IEnumerable<int> ids, CancellationToken token)
{
if (!ids.Any())
return 0;
var countExistingEntities = await dbSet
.Where(d => ids.Contains(d.Id))
.CountAsync(token);
if (ids.Count() > countExistingEntities)
return ICrudRepository<TDto>.ErrorIdNotFound;
var entities = dbContext.Set<TEntity>().Where(e => ids.Contains(e.Id));
var entries = entities.Select(entity => dbSet.Remove(entity)).Cast<EntityEntry>().ToList();
var affected = await dbContext.SaveChangesAsync(token);
entries.ForEach(e => e.State = EntityState.Detached);
return affected;
}
protected virtual TDto Convert(TEntity src) => src.Adapt<TDto>();
protected virtual TEntity Convert(TDto src) => src.Adapt<TEntity>();

View File

@ -1,80 +1,85 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data.DailyReport;
using AsbCloudApp.Data.DailyReport.Blocks.Sign;
using AsbCloudApp.Data.DailyReport.Blocks.Subsystems;
using AsbCloudApp.Data.DailyReport.Blocks.TimeBalance;
using AsbCloudApp.Repositories;
using AsbCloudApp.Requests;
using AsbCloudApp.Services;
using AsbCloudDb;
using AsbCloudDb.Model;
using AsbCloudDb.Model.DailyReports;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Repository;
public class DailyReportRepository : CrudRepositoryBase<DailyReportDto, DailyReport>,
IDailyReportRepository
IDailyReportRepository
{
public DailyReportRepository(IAsbCloudDbContext dbContext)
: base(dbContext)
{
}
private IWellService wellService;
public async Task<IEnumerable<DailyReportDto>> GetAsync(int idWell, FileReportRequest request, CancellationToken cancellationToken)
{
var skip = request.Skip ?? 0;
var take = request.Take ?? 10;
public DailyReportRepository(IAsbCloudDbContext dbContext, IWellService wellService)
: base(dbContext)
{
this.wellService = wellService;
}
var query = GetQuery().Where(d => d.IdWell == idWell);
public async Task<IEnumerable<DailyReportDto>> GetAsync(int idWell, FileReportRequest request, CancellationToken cancellationToken)
{
var skip = request.Skip ?? 0;
var take = request.Take ?? 10;
if (request.GeDate.HasValue)
query = query.Where(d => d.Date >= request.GeDate.Value);
if (request.LeDate.HasValue)
query = query.Where(d => d.Date <= request.LeDate.Value);
var query = GetQuery().Where(d => d.IdWell == idWell);
query = request.SortFields?.Any() == true ?
query.SortBy(request.SortFields) :
query.OrderBy(d => d.Date);
if (request.GeDate.HasValue)
query = query.Where(d => d.Date >= request.GeDate.Value);
var entities = await query
.Skip(skip)
.Take(take)
.AsNoTracking()
.ToArrayAsync(cancellationToken);
if (request.LeDate.HasValue)
query = query.Where(d => d.Date <= request.LeDate.Value);
var dtos = entities.Select(Convert);
query = request.SortFields?.Any() == true ?
query.SortBy(request.SortFields) :
query.OrderBy(d => d.Date);
return dtos;
}
var entities = await query
.Skip(skip)
.Take(take)
.AsNoTracking()
.ToArrayAsync(cancellationToken);
public async Task<DailyReportDto?> GetOrDefaultAsync(int idWell, DateOnly date, CancellationToken cancellationToken)
{
var entity = await GetQuery()
.AsNoTracking()
.SingleOrDefaultAsync(d => d.IdWell == idWell && d.Date == date, cancellationToken);
var timezoneOffset = wellService.GetTimezone(idWell).Offset;
var dtos = entities.Select(entity => Convert(entity, timezoneOffset));
return entity is null ? null : Convert(entity);
}
return dtos;
}
protected override DailyReportDto Convert(DailyReport src)
{
var dto = new DailyReportDto
{
Id = src.Id,
IdWell = src.IdWell,
DateLastUpdate = src.DateLastUpdate,
Date = src.Date,
SignBlock = src.SignBlock?.Adapt<SignBlockDto>(),
TimeBalanceBlock = src.TimeBalanceBlock?.Adapt<TimeBalanceBlockDto>(),
SubsystemBlock = src.SubsystemBlock?.Adapt<SubsystemBlockDto>()
};
return dto;
}
public async Task<DailyReportDto?> GetOrDefaultAsync(int idWell, DateOnly date, CancellationToken cancellationToken)
{
var entity = await GetQuery()
.AsNoTracking()
.SingleOrDefaultAsync(d => d.IdWell == idWell && d.Date == date, cancellationToken);
return entity is null ? null : Convert(entity);
}
protected DailyReportDto Convert(DailyReport src, TimeSpan timezoneOffset)
{
var dto = new DailyReportDto
{
Id = src.Id,
IdWell = src.IdWell,
DateLastUpdate = src.DateLastUpdate?.ToOffset(timezoneOffset),
Date = src.Date,
SignBlock = src.SignBlock?.Adapt<SignBlockDto>(),
TimeBalanceBlock = src.TimeBalanceBlock?.Adapt<TimeBalanceBlockDto>(),
SubsystemBlock = src.SubsystemBlock?.Adapt<SubsystemBlockDto>()
};
return dto;
}
}

View File

@ -4,6 +4,7 @@ using AsbCloudApp.Services;
using AsbCloudDb.Model;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@ -111,7 +112,8 @@ namespace AsbCloudInfrastructure.Repository
{
var dto = well.Adapt<WellDto>();
dto.WellType = well.WellType.Caption;
dto.LastTelemetryDate = wellService.GetLastTelemetryDate(well.Id);
dto.LastTelemetryDate = wellService.GetLastTelemetryDate(well.Id)
.ToOffset(TimeSpan.FromHours(well.Timezone.Hours));
dto.Cluster = gCluster.Key.Caption;
dto.Deposit = gDeposit.Key.Caption;
return dto;

View File

@ -36,9 +36,6 @@ namespace AsbCloudInfrastructure.Repository
var query = dbSetConfigured
.Where(e => e.IdWell == request.IdWell);
double timezoneOffsetHours = query.FirstOrDefault()
?.Well.Timezone.Hours ?? 5d;
if (request.IdCategory is not null)
query = query.Where(x => x.IdCategory == request.IdCategory);
@ -53,13 +50,13 @@ namespace AsbCloudInfrastructure.Repository
if (request.Begin is not null)
{
var beginUtc = request.Begin.Value.ToUtcDateTimeOffset(timezoneOffsetHours);
var beginUtc = request.Begin.Value.ToUniversalTime();
query = query.Where(e => e.UploadDate >= beginUtc);
}
if (request.End is not null)
{
var endUtc = request.End.Value.ToUtcDateTimeOffset(timezoneOffsetHours);
var endUtc = request.End.Value.ToUniversalTime();
query = query.Where(e => e.UploadDate <= endUtc);
}
@ -184,7 +181,7 @@ namespace AsbCloudInfrastructure.Repository
var newFileMark = fileMarkDto.Adapt<FileMark>();
newFileMark.Id = default;
newFileMark.DateCreated = DateTime.UtcNow;
newFileMark.DateCreated = DateTimeOffset.UtcNow;
newFileMark.IdUser = idUser;
newFileMark.User = null!;
@ -244,7 +241,7 @@ namespace AsbCloudInfrastructure.Repository
IdAuthor = newItem.IdAuthor,
IdCategory = newItem.IdCategory,
Name = newItem.Name,
UploadDate = DateTime.UtcNow,
UploadDate = DateTimeOffset.UtcNow,
IsDeleted = false,
Size = newItem.Size,
};
@ -278,11 +275,11 @@ namespace AsbCloudInfrastructure.Repository
private static FileInfoDto Convert(FileInfo entity, double timezoneOffset)
{
var dto = entity.Adapt<FileInfoDto>();
dto.UploadDate = entity.UploadDate.ToRemoteDateTime(timezoneOffset);
dto.UploadDate = entity.UploadDate.ToOffset(TimeSpan.FromHours(timezoneOffset));
dto.FileMarks = entity.FileMarks.Select(m =>
{
var mark = m.Adapt<FileMarkDto>();
mark.DateCreated = m.DateCreated.ToRemoteDateTime(timezoneOffset);
mark.DateCreated = m.DateCreated.ToOffset(TimeSpan.FromHours(timezoneOffset));
return mark;
});
return dto;

View File

@ -39,8 +39,8 @@ namespace AsbCloudInfrastructure.Repository
IdWell = request.IdWell,
IdTelemetry = x.IdTelemetry,
IdFeedRegulator = x.IdFeedRegulator,
DateStart = DateTime.SpecifyKind(x.DateStart.UtcDateTime + timezoneSpan, DateTimeKind.Unspecified),
DateEnd = DateTime.SpecifyKind(x.DateEnd.UtcDateTime + timezoneSpan, DateTimeKind.Unspecified),
DateStart = x.DateStart.ToOffset(timezoneSpan),
DateEnd = x.DateEnd.ToOffset(timezoneSpan),
DepthStart = x.DepthStart,
DepthEnd = x.DepthEnd
});
@ -56,13 +56,13 @@ namespace AsbCloudInfrastructure.Repository
if (request.GtDate.HasValue)
{
var gtDate = request.GtDate.Value.ToUtcDateTimeOffset(timezoneHours);
var gtDate = request.GtDate.Value.ToUniversalTime();
query = query.Where(x => x.DateEnd >= gtDate);
}
if (request.LtDate.HasValue)
{
var ltDate = request.LtDate.Value.ToUtcDateTimeOffset(timezoneHours);
var ltDate = request.LtDate.Value.ToUniversalTime();
query = query.Where(x => x.DateStart <= ltDate);
}

View File

@ -110,10 +110,10 @@ public class NotificationRepository : CrudRepositoryBase<NotificationDto, Notifi
query = query.Where(n => n.IdNotificationCategory == request.IdCategory.Value);
if (request.LtSentDate.HasValue)
query = query.Where(n => n.SentDate <= request.LtSentDate.Value);
query = query.Where(n => n.SentDate <= request.LtSentDate.Value.ToUniversalTime());
if (request.LtReadDate.HasValue)
query = query.Where(n => n.ReadDate <= request.LtReadDate.Value);
query = query.Where(n => n.ReadDate <= request.LtReadDate.Value.ToUniversalTime());
dbContext.Notifications.RemoveRange(query);

View File

@ -24,7 +24,7 @@ namespace AsbCloudInfrastructure.Repository
this.wellService = wellService;
}
public async Task<IEnumerable<ScheduleDto>> GetAsync(int idWell, DateTime workTime, CancellationToken token)
public async Task<IEnumerable<ScheduleDto>> GetAsync(int idWell, DateTimeOffset workTime, CancellationToken token)
{
var entities = await BuildQuery(idWell, workTime)
.AsNoTracking()
@ -33,7 +33,7 @@ namespace AsbCloudInfrastructure.Repository
return entities.Select(Convert);
}
public async Task<DrillerDto?> GetOrDefaultDrillerAsync(int idWell, DateTime workTime, CancellationToken token)
public async Task<DrillerDto?> GetOrDefaultDrillerAsync(int idWell, DateTimeOffset workTime, CancellationToken token)
{
var entities = await BuildQuery(idWell, workTime)
.AsNoTracking()
@ -43,8 +43,7 @@ namespace AsbCloudInfrastructure.Repository
return null;
var hoursOffset = wellService.GetTimezone(idWell).Hours;
var remoteDate = workTime.ToUtcDateTimeOffset(hoursOffset).ToRemoteDateTime(hoursOffset);
var time = new TimeOnly(remoteDate.Hour, remoteDate.Minute, remoteDate.Second);
var time = new TimeOnly(workTime.Hour, workTime.Minute, workTime.Second);
var entity = entities.FirstOrDefault(s =>
s.ShiftStart > s.ShiftEnd ^
@ -69,11 +68,11 @@ namespace AsbCloudInfrastructure.Repository
}
private IQueryable<Schedule> BuildQuery(int idWell, DateTime workTime)
private IQueryable<Schedule> BuildQuery(int idWell, DateTimeOffset workTime)
{
var hoursOffset = wellService.GetTimezone(idWell).Hours;
var workTimeDateTime = workTime.ToUtcDateTimeOffset(hoursOffset);
var workTimeDateTime = workTime.ToUniversalTime();
return GetQuery().Where(s => s.IdWell == idWell
&& s.DrillStart <= workTimeDateTime
@ -82,19 +81,20 @@ namespace AsbCloudInfrastructure.Repository
protected override Schedule Convert(ScheduleDto dto)
{
var hoursOffset = wellService.GetTimezone(dto.IdWell).Hours;
var entity = base.Convert(dto);
entity.DrillStart = dto.DrillStart.ToUtcDateTimeOffset(hoursOffset);
entity.DrillEnd = dto.DrillEnd.ToUtcDateTimeOffset(hoursOffset);
entity.DrillStart = dto.DrillStart.ToUniversalTime();
entity.DrillEnd = dto.DrillEnd.ToUniversalTime();
return entity;
}
protected override ScheduleDto Convert(Schedule entity)
{
var hoursOffset = wellService.GetTimezone(entity.IdWell).Hours;
var timeSpan = TimeSpan.FromHours(hoursOffset);
var dto = base.Convert(entity);
dto.DrillStart = entity.DrillStart.ToRemoteDateTime(hoursOffset);
dto.DrillEnd = entity.DrillEnd.ToRemoteDateTime(hoursOffset);
dto.DrillStart = entity.DrillStart.ToOffset(timeSpan);
dto.DrillEnd = entity.DrillEnd.ToOffset(timeSpan);
return dto;
}
}

View File

@ -50,15 +50,14 @@ namespace AsbCloudInfrastructure.Repository
{
var result = base.Convert(src);
var timezoneOffsetHours = wellService.GetTimezone(src.IdWell).Hours;
result.UploadDate = src.UploadDate.ToRemoteDateTime(timezoneOffsetHours);
result.UploadDate = src.UploadDate.ToOffset(TimeSpan.FromHours(timezoneOffsetHours));
return result;
}
protected override SetpointsRequest Convert(SetpointsRequestDto src)
{
var result = base.Convert(src);
var timezoneOffsetHours = wellService.GetTimezone(src.IdWell).Hours;
result.UploadDate = src.UploadDate.ToUtcDateTimeOffset(timezoneOffsetHours);
result.UploadDate = src.UploadDate.ToUniversalTime();
return result;
}
}

View File

@ -5,6 +5,7 @@ using AsbCloudApp.Services;
using AsbCloudDb.Model;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@ -93,14 +94,14 @@ namespace AsbCloudInfrastructure.Repository
{
var entity = dto.Adapt<TelemetryWirelineRunOut>();
entity.IdTelemetry = idTelemetry;
entity.DateTime = dto.DateTime.ToUtcDateTimeOffset(timezoneOffset);
entity.DateTime = dto.DateTime.ToUniversalTime();
return entity;
}
private static TelemetryWirelineRunOutDto Convert(TelemetryWirelineRunOut entity, WellDto well, double timezoneOffset)
{
var dto = entity.Adapt<TelemetryWirelineRunOutDto>();
dto.DateTime = entity.DateTime.ToRemoteDateTime(timezoneOffset);
dto.DateTime = entity.DateTime.ToOffset(TimeSpan.FromHours(timezoneOffset));
dto.WellInfo = well;
return dto;
}

View File

@ -37,11 +37,10 @@ namespace AsbCloudInfrastructure.Repository
if (!trajectoryRows.All(r => r.IdWell == idWell))
throw new ArgumentInvalidException(nameof(trajectoryRows), "Все строки должны относиться к одной скважине");
var offsetHours = wellService.GetTimezone(idWell).Hours;
var entities = trajectoryRows
.Select(e =>
{
var entity = Convert(e, offsetHours);
var entity = Convert(e);
entity.Id = 0;
return entity;
});
@ -52,8 +51,7 @@ namespace AsbCloudInfrastructure.Repository
public async Task<int> AddAsync(Tdto trajectoryRow, CancellationToken token)
{
var offsetHours = wellService.GetTimezone(trajectoryRow.IdWell).Hours;
var entity = Convert(trajectoryRow, offsetHours);
var entity = Convert(trajectoryRow);
entity.Id = 0;
db.Set<TEntity>().Add(entity);
return await db.SaveChangesAsync(token)
@ -98,8 +96,7 @@ namespace AsbCloudInfrastructure.Repository
public async Task<int> UpdateAsync(Tdto row, CancellationToken token)
{
var offsetHours = wellService.GetTimezone(row.IdWell).Hours;
var entity = Convert(row, offsetHours);
var entity = Convert(row);
db.Set<TEntity>().Update(entity);
return await db.SaveChangesAsync(token)
.ConfigureAwait(false);
@ -108,14 +105,14 @@ namespace AsbCloudInfrastructure.Repository
private static Tdto Convert(TEntity entity, double offsetHours)
{
var dto = entity.Adapt<Tdto>();
dto.UpdateDate = entity.UpdateDate.ToRemoteDateTime(offsetHours);
dto.UpdateDate = entity.UpdateDate.ToOffset(TimeSpan.FromHours(offsetHours));
return dto;
}
private static TEntity Convert(Tdto dto, double offsetHours)
private static TEntity Convert(Tdto dto)
{
var entity = dto.Adapt<TEntity>();
entity.UpdateDate = DateTime.Now.ToUtcDateTimeOffset(offsetHours);
entity.UpdateDate = DateTimeOffset.UtcNow;
return entity;
}
}

View File

@ -38,13 +38,13 @@ namespace AsbCloudInfrastructure.Repository
if (request.GeDate.HasValue)
{
var geDate = request.GeDate.Value.ToUtcDateTimeOffset(timezone.Hours);
var geDate = request.GeDate.Value.ToUniversalTime();
query = query.Where(r => r.DateTime >= geDate);
}
if (request.LeDate.HasValue)
{
var leDate = request.LeDate.Value.ToUtcDateTimeOffset(timezone.Hours);
var leDate = request.LeDate.Value.ToUniversalTime();
query = query.Where(r => r.DateTime <= leDate);
}

View File

@ -1,11 +1,10 @@
using AsbCloudApp.Data;
using AsbCloudApp.Repositories;
using AsbCloudApp.Repositories;
using AsbCloudDb.Model;
using Mapster;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using AsbCloudApp.Data.WellOperation;
namespace AsbCloudInfrastructure.Repository;

File diff suppressed because it is too large Load Diff

View File

@ -13,6 +13,7 @@ using AsbCloudApp.Data.DailyReport.Blocks.Sign;
using AsbCloudApp.Data.DailyReport.Blocks.Subsystems;
using AsbCloudApp.Data.DailyReport.Blocks.TimeBalance;
using AsbCloudApp.Data.DailyReport.Blocks.WellOperation;
using AsbCloudApp.Data.WellOperation;
using AsbCloudApp.Requests;
using AsbCloudApp.Services.DailyReport;
using AsbCloudApp.Services.ProcessMaps.WellDrilling;
@ -83,7 +84,7 @@ public class DailyReportService : IDailyReportService
editableBlock.IdUser = idUser;
editableBlock.LastUpdateDate = DateTime.UtcNow;
dailyReport.DateLastUpdate = DateTime.UtcNow;
dailyReport.DateLastUpdate = DateTimeOffset.UtcNow;
if (dailyReport.Id == 0)
return await dailyReportRepository.InsertAsync(dailyReport, cancellationToken);
@ -106,15 +107,15 @@ public class DailyReportService : IDailyReportService
IdWell = well.Id
};
var geDate = dailyReport.Date.ToDateTime(TimeOnly.MinValue, DateTimeKind.Unspecified);
var ltDate = dailyReport.Date.AddDays(1).ToDateTime(TimeOnly.MinValue, DateTimeKind.Unspecified);
var factOperationRequest = new WellOperationRequest
{
IdWell = idWell,
var offsetHours = wellService.GetTimezone(dailyReport.IdWell).Hours;
var geDate = new DateTimeOffset(dailyReport.Date, TimeOnly.MinValue, TimeSpan.FromHours(offsetHours));
var leDate = new DateTimeOffset(dailyReport.Date.AddDays(1), TimeOnly.MinValue, TimeSpan.FromHours(offsetHours));
var factOperationRequest = new WellOperationRequest(new []{ idWell })
{
OperationType = WellOperation.IdOperationTypeFact,
GeDate = geDate,
LtDate = ltDate
LeDate = leDate
};
var factWellOperations = (await wellOperationRepository.GetAsync(factOperationRequest, cancellationToken))
@ -130,12 +131,12 @@ public class DailyReportService : IDailyReportService
dailyReport.DepthStart = factWellOperations.FirstOrDefault()?.DepthStart;
dailyReport.DepthEnd = factWellOperations.LastOrDefault()?.DepthEnd;
await UpdateTimeBalanceBlockAsync(dailyReport, factWellOperations, cancellationToken);
await UpdateSubsystemBlockAsync(dailyReport, cancellationToken);
await UpdateTimeBalanceBlockAsync(dailyReport, factWellOperations, geDate, leDate, cancellationToken);
await UpdateSubsystemBlockAsync(dailyReport, geDate, leDate, cancellationToken);
await AddTrajectoryBlockAsync(dailyReport, cancellationToken);
await AddScheduleBlockAsync(dailyReport, cancellationToken);
await AddProcessMapWellDrillingBlockAsync(dailyReport, cancellationToken);
await AddTrajectoryBlockAsync(dailyReport, geDate, leDate, cancellationToken);
await AddScheduleBlockAsync(dailyReport, geDate, cancellationToken);
await AddProcessMapWellDrillingBlockAsync(dailyReport, geDate, leDate, cancellationToken);
AddFactWellOperationBlock(dailyReport, factWellOperations);
@ -152,46 +153,43 @@ public class DailyReportService : IDailyReportService
Items = Enumerable.Empty<DailyReportDto>()
};
var datesRange = await GetDatesRangeAsync(idWell, cancellationToken);
var datesRange = await wellOperationRepository.GetDatesRangeAsync(idWell, WellOperation.IdOperationTypeFact, cancellationToken);
if (datesRange is null)
return result;
var dailyReports = new List<DailyReportDto>();
if (request.GeDate.HasValue)
{
var startDate = new DateTime(request.GeDate.Value.Year, request.GeDate.Value.Month,
request.GeDate.Value.Day);
TimeSpan offset = wellService.GetTimezone(idWell).Offset;
if (startDate.Date >= datesRange.From.Date)
if (request.GeDate.HasValue)
{
var startDate = new DateTimeOffset(request.GeDate.Value, TimeOnly.MinValue, offset);
if (startDate >= datesRange.From)
datesRange.From = startDate;
}
if (request.LeDate.HasValue)
{
var finishDate = new DateTime(request.LeDate.Value.Year, request.LeDate.Value.Month,
request.LeDate.Value.Day);
var finishDate = new DateTimeOffset(request.LeDate.Value, TimeOnly.MinValue, offset);
if (finishDate.Date <= datesRange.To.Date)
if (finishDate <= datesRange.To)
datesRange.To = finishDate;
}
if (datesRange.From.AddDays(result.Skip) <= datesRange.To)
result.Count = (int)(Math.Ceiling((datesRange.To - DateTime.UnixEpoch).TotalDays) -
Math.Floor((datesRange.From - DateTime.UnixEpoch).TotalDays)) + 1;
result.Count = (int)(Math.Ceiling((datesRange.To - DateTimeOffset.UnixEpoch).TotalDays)
- Math.Floor((datesRange.From - DateTimeOffset.UnixEpoch).TotalDays));
var existingDailyReports = await dailyReportRepository.GetAsync(idWell, request, cancellationToken);
var geDateFactWellOperation = datesRange.From.AddDays(result.Skip);
var ltDateFactWellOperation = geDateFactWellOperation.AddDays(result.Take);
var leDateFactWellOperation = geDateFactWellOperation.AddDays(result.Take);
var factWellOperationRequest = new WellOperationRequest
var factWellOperationRequest = new WellOperationRequest(new[] { idWell })
{
IdWell = idWell,
OperationType = WellOperation.IdOperationTypeFact,
GeDate = geDateFactWellOperation,
LtDate = ltDateFactWellOperation
LeDate = leDateFactWellOperation
};
var factWellOperations = await wellOperationRepository.GetAsync(factWellOperationRequest, cancellationToken);
@ -200,7 +198,7 @@ public class DailyReportService : IDailyReportService
{
for (var day = result.Skip; day - result.Skip < result.Take && datesRange.To.AddDays(-day) >= datesRange.From; day++)
{
var dateDailyReport = DateOnly.FromDateTime(datesRange.To.AddDays(-day));
var dateDailyReport = DateOnly.FromDateTime(datesRange.To.AddDays(-day).DateTime);
AddDailyReport(dateDailyReport);
}
@ -209,7 +207,7 @@ public class DailyReportService : IDailyReportService
{
for (var day = result.Skip; day - result.Skip < result.Take && datesRange.From.AddDays(day) <= datesRange.To; day++)
{
var dateDailyReport = DateOnly.FromDateTime(datesRange.From.AddDays(day));
var dateDailyReport = DateOnly.FromDateTime(datesRange.From.AddDays(day).DateTime);
AddDailyReport(dateDailyReport);
}
@ -228,11 +226,11 @@ public class DailyReportService : IDailyReportService
IdWell = idWell
};
var geDate = date.ToDateTime(TimeOnly.MinValue, DateTimeKind.Unspecified);
var leDate = date.AddDays(1).ToDateTime(TimeOnly.MinValue, DateTimeKind.Unspecified);
var geDate = new DateTimeOffset(date, TimeOnly.MinValue, offset);
var leDate = new DateTimeOffset(date.AddDays(1), TimeOnly.MinValue, offset);
var factWellOperationPerDay = factWellOperations.Where(o => o.DateStart.Date >= geDate &&
o.DateStart.Date <= leDate);
var factWellOperationPerDay = factWellOperations.Where(o => o.DateStart >= geDate &&
o.DateStart <= leDate);
AddFactWellOperationBlock(dailyReport, factWellOperationPerDay);
@ -240,36 +238,8 @@ public class DailyReportService : IDailyReportService
}
}
public async Task<DatesRangeDto?> GetDatesRangeAsync(int idWell, CancellationToken cancellationToken)
{
var timezone = wellService.GetTimezone(idWell);
var currentDate = DateTimeOffset.UtcNow.ToRemoteDateTime(timezone.Hours);
var factOperationDatesRange = await wellOperationRepository.GetDatesRangeAsync(idWell, WellOperation.IdOperationTypeFact,
cancellationToken);
if (factOperationDatesRange is null)
return null;
var from = (factOperationDatesRange.From.AddDays(1) <= DateTime.UtcNow ?
factOperationDatesRange.From :
currentDate.AddDays(-1))
.Date;
var to = (factOperationDatesRange.To.AddDays(1) <= DateTime.UtcNow ?
factOperationDatesRange.To :
currentDate.AddDays(-1))
.Date;
return new DatesRangeDto
{
From = from,
To = to
};
}
private async Task UpdateTimeBalanceBlockAsync(DailyReportDto dailyReport, IEnumerable<WellOperationDto> factWellOperations,
CancellationToken cancellationToken)
DateTimeOffset geDateStart, DateTimeOffset leDateEnd, CancellationToken cancellationToken)
{
const int idWellOperationSlipsTime = 5011;
@ -278,10 +248,7 @@ public class DailyReportService : IDailyReportService
dailyReport.TimeBalanceBlock.SectionName = wellOperationRepository.GetSectionTypes()
.FirstOrDefault(s => s.Id == dailyReport.TimeBalanceBlock.IdSection)?.Caption;
var geDateStart = dailyReport.Date.ToDateTime(TimeOnly.MinValue, DateTimeKind.Unspecified);
var leDateEnd = dailyReport.Date.AddDays(1).ToDateTime(TimeOnly.MinValue, DateTimeKind.Unspecified);
dailyReport.TimeBalanceBlock.WellOperationSlipsTimeCount = (await detectedOperationService.GetAsync(
dailyReport.TimeBalanceBlock.WellOperationSlipsTimeCount = (await detectedOperationService.GetAsync(
new DetectedOperationByWellRequest
{
IdsCategories = new[] { idWellOperationSlipsTime },
@ -296,11 +263,9 @@ public class DailyReportService : IDailyReportService
}
}
private async Task AddTrajectoryBlockAsync(DailyReportDto dailyReport, CancellationToken cancellationToken)
private async Task AddTrajectoryBlockAsync(DailyReportDto dailyReport,
DateTimeOffset geDate, DateTimeOffset leDate, CancellationToken cancellationToken)
{
var geDate = dailyReport.Date.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
var leDate = dailyReport.Date.AddDays(1).ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
var trajectory = (await trajectoryFactNnbRepository.GetByRequestAsync(new TrajectoryRequest
{
IdWell = dailyReport.IdWell,
@ -317,11 +282,9 @@ public class DailyReportService : IDailyReportService
};
}
private async Task AddScheduleBlockAsync(DailyReportDto dailyReport, CancellationToken cancellationToken)
private async Task AddScheduleBlockAsync(DailyReportDto dailyReport, DateTimeOffset workDate, CancellationToken cancellationToken)
{
var workDate = dailyReport.Date.ToDateTime(TimeOnly.MinValue, DateTimeKind.Unspecified);
dailyReport.ScheduleBlock = (await scheduleRepository.GetAsync(dailyReport.IdWell, workDate, cancellationToken))
dailyReport.ScheduleBlock = (await scheduleRepository.GetAsync(dailyReport.IdWell, workDate, cancellationToken))
.Select(s => new ScheduleRecordDto
{
ShiftStart = s.ShiftStart,
@ -332,7 +295,8 @@ public class DailyReportService : IDailyReportService
});
}
private async Task UpdateSubsystemBlockAsync(DailyReportDto dailyReport, CancellationToken cancellationToken)
private async Task UpdateSubsystemBlockAsync(DailyReportDto dailyReport,
DateTimeOffset geDate, DateTimeOffset leDate, CancellationToken cancellationToken)
{
dailyReport.SubsystemBlock ??= new SubsystemBlockDto();
@ -344,9 +308,6 @@ public class DailyReportService : IDailyReportService
{
IdWell = dailyReport.IdWell
}, cancellationToken);
var geDate = dailyReport.Date.ToDateTime(TimeOnly.MinValue, DateTimeKind.Unspecified);
var leDate = dailyReport.Date.AddDays(1).ToDateTime(TimeOnly.MinValue, DateTimeKind.Unspecified);
var subsystemsStatPerDay = await subsystemService.GetStatAsync(new SubsystemRequest
{
@ -370,11 +331,9 @@ public class DailyReportService : IDailyReportService
}
}
private async Task AddProcessMapWellDrillingBlockAsync(DailyReportDto dailyReport, CancellationToken cancellationToken)
private async Task AddProcessMapWellDrillingBlockAsync(DailyReportDto dailyReport,
DateTimeOffset geDate, DateTimeOffset leDate, CancellationToken cancellationToken)
{
var geDate = dailyReport.Date.ToDateTime(TimeOnly.MinValue, DateTimeKind.Unspecified);
var leDate = dailyReport.Date.AddDays(1).ToDateTime(TimeOnly.MinValue, DateTimeKind.Unspecified);
var request = new DataSaubStatRequest();
dailyReport.ProcessMapWellDrillingBlock = (await processMapReportDrillingService.GetAsync(dailyReport.IdWell, request,
cancellationToken)).Where(p => p.DateStart >= geDate && p.DateStart <= leDate)
@ -401,7 +360,7 @@ public class DailyReportService : IDailyReportService
WellOperations = factWellOperations.GroupBy(o => o.IdCategory)
.Select(g => new WellOperationRecordDto
{
CategoryName = g.First().CategoryName,
CategoryName = g.First().OperationCategoryName,
DurationHours = g.Sum(o => o.DurationHours)
}),
@ -413,13 +372,12 @@ public class DailyReportService : IDailyReportService
private async Task<bool> IsDateDailyReportInRangeAsync(int idWell, DateOnly dateDailyReport, CancellationToken cancellationToken)
{
var datesRange = await GetDatesRangeAsync(idWell, cancellationToken);
var datesRange = await wellOperationRepository.GetDatesRangeAsync(idWell, WellOperation.IdOperationTypeFact, cancellationToken);
if (datesRange is null)
return false;
var from = DateOnly.FromDateTime(datesRange.From);
var to = DateOnly.FromDateTime(datesRange.To);
var from = DateOnly.FromDateTime(datesRange.From.DateTime);
var to = DateOnly.FromDateTime(datesRange.To.DateTime);
return dateDailyReport >= from && dateDailyReport <= to;
}

View File

@ -13,6 +13,7 @@ using Microsoft.AspNetCore.Http.Extensions;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Services;
using AsbCloudApp.Data;
using AsbCloudApp.Data.WellOperation;
using AsbCloudInfrastructure.Services.DetectOperations.Detectors;
namespace AsbCloudInfrastructure.Services.DetectOperations;

View File

@ -10,8 +10,8 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data.WellOperation;
using AsbCloudInfrastructure.Services.DetectOperations.Detectors;
using AsbCloudInfrastructure.Services.SAUB;
namespace AsbCloudInfrastructure.Services.DetectOperations;
@ -20,6 +20,7 @@ public class DetectedOperationService : IDetectedOperationService
private readonly IDetectedOperationRepository operationRepository;
private readonly IWellOperationCategoryRepository wellOperationCategoryRepository;
private readonly IWellService wellService;
private readonly ITelemetryService telemetryService;
private readonly IRepositoryWellRelated<OperationValueDto> operationValueRepository;
private readonly IScheduleRepository scheduleRepository;
private readonly ITelemetryDataSaubService telemetryDataSaubService;
@ -28,12 +29,14 @@ public class DetectedOperationService : IDetectedOperationService
new DetectorDrilling(),
new DetectorSlipsTime(),
new DetectorFlashing(),
new DetectorConditioning(),
};
public DetectedOperationService(
IDetectedOperationRepository operationRepository,
IWellOperationCategoryRepository wellOperationCategoryRepository,
IWellService wellService,
ITelemetryService telemetryService,
IRepositoryWellRelated<OperationValueDto> operationValueRepository,
IScheduleRepository scheduleRepository,
ITelemetryDataSaubService telemetryDataSaubService)
@ -41,6 +44,7 @@ public class DetectedOperationService : IDetectedOperationService
this.operationRepository = operationRepository;
this.wellOperationCategoryRepository = wellOperationCategoryRepository;
this.wellService = wellService;
this.telemetryService = telemetryService;
this.operationValueRepository = operationValueRepository;
this.scheduleRepository = scheduleRepository;
this.telemetryDataSaubService = telemetryDataSaubService;
@ -143,6 +147,7 @@ public class DetectedOperationService : IDetectedOperationService
const int minOperationLength = 5;
const int maxDetectorsInterpolationFrameLength = 30;
const int gap = maxDetectorsInterpolationFrameLength + minOperationLength;
var timezone = telemetryService.GetTimezone(idTelemetry);
while (true)
{
@ -153,13 +158,12 @@ public class DetectedOperationService : IDetectedOperationService
Order = 0
};
var detectableTelemetries = (await telemetryDataSaubService.GetByTelemetryAsync(idTelemetry, request, token))
var dtos = await telemetryDataSaubService.GetByTelemetryAsync(idTelemetry, request, token);
var detectableTelemetries = dtos
.Where(t => t.BlockPosition >= 0)
.Select(t => t as TelemetryNewDataSaubDto)
.Where (t => t is not null)
.Select(t => new DetectableTelemetry
{
DateTime = t.DateTime,
DateTime = new DateTimeOffset(t.DateTime, timezone.Offset),
IdUser = t.IdUser,
Mode = t.Mode,
WellDepth = t.WellDepth,
@ -269,8 +273,8 @@ public class DetectedOperationService : IDetectedOperationService
dto.OperationValue = operationValues.FirstOrDefault(v => v.IdOperationCategory == dto.IdCategory
&& v.DepthStart <= dto.DepthStart
&& v.DepthEnd > dto.DepthStart);
var dateStart = dto.DateStart;
var dateStart = dto.DateStart.ToUniversalTime();
var timeStart = new TimeDto(dateStart);
var driller = schedules.FirstOrDefault(s =>
s.DrillStart <= dateStart &&

View File

@ -0,0 +1,55 @@
using AsbCloudApp.Data.DetectedOperation;
using AsbCloudDb.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services.DetectOperations.Detectors
{
public class DetectorConditioning : DetectorAbstract
{
protected override double CalcValue(DetectableTelemetry[] telemetry, int begin, int end) =>
CalcDeltaMinutes(telemetry, begin, end);
protected override bool DetectBegin(DetectableTelemetry[] telemetry, int position, DetectedOperationDto? previousOperation)
{
var currentPoint = telemetry[position];
if (currentPoint.Pressure < 10)
return false;
if (currentPoint.RotorSpeed <= 8)
return false;
var delta = currentPoint.WellDepth - currentPoint.BitDepth;
if (delta < 0.03d)
return false;
if (currentPoint.BitDepth < 150)
return false;
return true;
}
protected override int DetectEnd(DetectableTelemetry[] telemetry, int position, DetectedOperationDto? previousOperation)
{
var currentPoint = telemetry[position];
if (currentPoint.Pressure < 10)
return IdReasonOfEnd_PressureIsLo;
if (currentPoint.RotorSpeed <=8)
return IdReasonOfEnd_RotorSpeedIsHi;
if ((currentPoint.WellDepth - currentPoint.BitDepth) < 0.03d)
return IdReasonOfEnd_DeltaWellDepthAndBithDepthIsLo;
if (currentPoint.BitDepth < 150)
return IdReasonOfEnd_BithDepthIsLo;
return IdReasonOfEnd_NotDetected;
}
protected override (int IdCategory, IDictionary<string, object> ExtraData) GetSpecificInformation(DetectableTelemetry[] telemetry, int begin, int end)
{
return (WellOperationCategory.IdConditioning, new Dictionary<string, object>());
}
}
}

View File

@ -23,7 +23,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations.Detectors
return false;
var delta = currentPoint.WellDepth - currentPoint.BitDepth;
if (delta < 0.03d)
if (delta < 0.01d)
return false;
if (currentPoint.RotorSpeed > 8)
@ -47,7 +47,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations.Detectors
if (currentPoint.Pressure < 10)
return IdReasonOfEnd_PressureIsLo;
if ((currentPoint.WellDepth - currentPoint.BitDepth) < 0.03d)
if ((currentPoint.WellDepth - currentPoint.BitDepth) < 0.01d)
return IdReasonOfEnd_DeltaWellDepthAndBithDepthIsLo;
if (currentPoint.RotorSpeed > 8)
return IdReasonOfEnd_RotorSpeedIsHi;

View File

@ -13,13 +13,13 @@
Признак начала операции =
( давление >= 10 атм ) И
( обороты ротора <= 8 об/мин) И
( расстояние от долота до забоя >= 0.03 м) И
( расстояние от долота до забоя >= 0.01 м) И
( глубина забоя не изменяется) И
( глубина долота >= 150 м);
Признак окончания операции =
( давление < 10 атм ) ИЛИ
( расстояние от долота до забоя < 0.03 м ) ИЛИ
( расстояние от долота до забоя < 0.01 м ) ИЛИ
( обороты ротора > 8 об/мин) ИЛИ
( глубина долота < 150 м);

View File

@ -0,0 +1,29 @@
# Алгоритм определения проработки
## Описание
Проработка операция, во время которой производится подъем или спуск бурильного инструмента с вращением и циркуляцией. Следующей операцией после проработки будет либо шаблонировка (аналогично проработке, но БЕЗ вращением и циркуляции), либо разгрузка инструмента в клинья (снижение веса на крюке) наращивание или отворот бурильного инструмента.
Проработка определяется как время между:
- начало подъема/спуска бурильного инструмента с циркуляцией и вращением;
- разгрузкой инструмента на клинья (остается только вес крюкоблока и ВСП). При этом давление менее 20 атм. ЛИБО
- начало подъема/спуска бурильного инструмента с циркуляцией, НО БЕЗ вращения
Разделяется два вида проработки:
1. перед наращиванием - соотношение глубины забоя и глубины долота <= 30 метров;
2. при спуско-подъёмных операциях (СПО)соотношение глубины забоя - глубины долота > 30 метров.
## Метод определения
Признак начала операции =
( давление >= 10 атм ) И
( обороты ротора > 8 об/мин ) И
( расстояние от долота до забоя >= 0.03м ) И
( глубина долота >= 150м);
Признак окончания операции =
( обороты ротора <= 8 об/мин ) ИЛИ
( давление < 10 атм ) ИЛИ
( расстояние от долота до забоя < 0.03м ) ИЛИ
( глубина долота < 150м);
## Ключевой параметр
Продолжительность операции.

View File

@ -49,7 +49,7 @@ namespace AsbCloudInfrastructure.Services.DrillTestReport
well.Deposit ?? "-",
well.Cluster ?? "-",
well.Caption ?? "-"),
Date = DateTime.Now,
Date = DateTimeOffset.Now,
};
var fileName = string.Format("Drill_test_{0}.xlsx", dto.TimeStampStart.ToString("dd.mm.yyyy_HH_MM_ss"));
@ -78,15 +78,15 @@ namespace AsbCloudInfrastructure.Services.DrillTestReport
var dtos = await drillTestRepository.GetAllAsync(telemetry.Id, request, cancellationToken);
foreach (var dto in dtos)
{
var remoteDateTime = dto.TimeStampStart.ToRemoteDateTime(timezone.Hours);
var remoteDateTime = dto.TimeStampStart.ToOffset(TimeSpan.FromHours(timezone.Hours));
reports.Add(new DrillTestReportInfoDto
{
FileName = string.Format("Drill_test_{0}", dto.TimeStampStart.DateTime),
FileName = string.Format("Drill_test_{0}", remoteDateTime),
DrillDepth = (dto.Params
.Where(p => p.DepthDrillStep.HasValue)
.Sum(x => x.DepthDrillStep) ?? 0) + dto.DepthStart,
DateTime = dto.TimeStampStart.DateTime,
DateTime = remoteDateTime,
Id = dto.Id,
});
}

View File

@ -480,7 +480,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
IdWell = fileEntity.IdWell,
Name = fileEntity.Name,
Size = fileEntity.Size,
UploadDate = fileEntity.UploadDate.ToRemoteDateTime(timezoneOffset),
UploadDate = fileEntity.UploadDate.ToOffset(TimeSpan.FromHours(timezoneOffset)),
};
var marks = fileEntity.FileMarks?.Where(m => !m.IsDeleted);
@ -489,7 +489,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
part.File.FileMarks = marks.Select(m =>
{
var mark = m.Adapt<FileMarkDto>();
mark.DateCreated = m.DateCreated.ToRemoteDateTime(timezoneOffset);
mark.DateCreated = m.DateCreated.ToOffset(TimeSpan.FromHours(timezoneOffset));
return mark;
});
var hasReject = marks.Any(m => m.IdMarkType == idMarkTypeReject);

View File

@ -11,7 +11,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
{
private const string directionDirectorPositionName = "Руководитель направления по ТСБ";
private readonly DateTime totalDate;
private readonly DateTimeOffset totalDate;
private readonly FileMarkDto? acceptDirectionDirector;
private readonly List<FileMarkDto> acceptsOthers;
private readonly WellDto well;
@ -157,7 +157,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Left);
}
private static string FormatDate(DateTime dateTime)
private static string FormatDate(DateTimeOffset dateTime)
=> $"{dateTime.Day:00}.{dateTime.Month:00}.{dateTime.Year:00}";
}

View File

@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Requests.ExportOptions;
using AsbCloudApp.Services.Export;
using AsbCloudInfrastructure.Services.ExcelServices.Templates;
using ClosedXML.Excel;
using Mapster;
namespace AsbCloudInfrastructure.Services.ExcelServices;
public abstract class ExcelExportService<TDto, TOptions, TTemplate> : IExportService<TOptions>
where TOptions : IExportOptionsRequest
where TTemplate : class, ITemplateParameters, new()
{
protected TTemplate TemplateParameters => new();
protected abstract Task<string> BuildFileNameAsync(TOptions options, CancellationToken token);
protected abstract Task<IEnumerable<TDto>> GetDtosAsync(TOptions options, CancellationToken token);
public async Task<(string FileName, Stream File)> ExportAsync(TOptions options, CancellationToken token)
{
var dtos = await GetDtosAsync(options, token);
var fileName = await BuildFileNameAsync(options, token);
var file = BuildFile(dtos);
return (fileName, file);
}
private Stream BuildFile(IEnumerable<TDto> dtos)
{
using var template = GetTemplateFile();
using var workbook = new XLWorkbook(template);
AddDtosToWorkbook(workbook, dtos);
var memoryStream = new MemoryStream();
workbook.SaveAs(memoryStream, new SaveOptions { });
memoryStream.Seek(0, SeekOrigin.Begin);
return memoryStream;
}
private void AddDtosToWorkbook(XLWorkbook workbook, IEnumerable<TDto> dtos)
{
var dtosToArray = dtos.ToArray();
if (!dtosToArray.Any())
return;
var sheet = workbook.GetWorksheet(TemplateParameters.SheetName);
for (var i = 0; i < dtosToArray.Length; i++)
{
var row = sheet.Row(1 + i + TemplateParameters.HeaderRowsCount);
AddRow(row, dtosToArray[i]);
}
}
private void AddRow(IXLRow xlRow, TDto dto)
{
var properties = dto.Adapt<IDictionary<string, object>>();
foreach (var (name, cellValue) in properties)
{
if (TemplateParameters.Cells.TryGetValue(name, out var cell))
xlRow.Cell(cell.ColumnNumber).SetCellValue(cellValue);
}
}
private Stream GetTemplateFile() =>
Assembly.GetExecutingAssembly().GetTemplateCopyStream(TemplateParameters.FileName)
?? throw new ArgumentNullException($"Файл '{TemplateParameters.FileName}' не найден");
}

View File

@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Reflection;
using AsbCloudApp.Data;
using AsbCloudApp.Requests.ParserOptions;
using AsbCloudApp.Services.Parsers;
using AsbCloudInfrastructure.Services.ExcelServices.Templates;
using ClosedXML.Excel;
using Mapster;
namespace AsbCloudInfrastructure.Services.ExcelServices;
public abstract class ExcelParser<TDto, TOptions, TTemplate> : IParserService<TDto, TOptions>
where TDto : class, IValidatableObject, IId
where TOptions : IParserOptionsRequest
where TTemplate : class, ITemplateParameters, new()
{
protected TTemplate TemplateParameters => new();
public virtual ParserResultDto<TDto> Parse(Stream file, TOptions options)
{
using var workbook = new XLWorkbook(file);
var sheet = workbook.GetWorksheet(TemplateParameters.SheetName);
var dtos = ParseExcelSheet(sheet);
return dtos;
}
public virtual Stream GetTemplateFile() =>
Assembly.GetExecutingAssembly().GetTemplateCopyStream(TemplateParameters.FileName)
?? throw new ArgumentNullException($"Файл '{TemplateParameters.FileName}' не найден");
protected virtual IDictionary<string, object?> ParseRow(IXLRow xlRow)
{
var cells = TemplateParameters.Cells.ToDictionary(x => x.Key, x =>
{
var columnNumber = x.Value.ColumnNumber;
var xlCell = xlRow.Cell(columnNumber);
var cellValue = x.Value.GetValueFromCell(xlCell);
return cellValue;
});
return cells;
}
protected virtual TDto BuildDto(IDictionary<string, object?> row, int rowNumber)
{
var dto = row.Adapt<TDto>();
return dto;
}
private ValidationResultDto<TDto> Validate(TDto dto, int rowNumber)
{
var validationResults = new List<ValidationResult>();
var isValid = dto.Validate(validationResults);
if (isValid)
{
var validDto = new ValidationResultDto<TDto>
{
Item = dto
};
return validDto;
}
var columnsDict = TemplateParameters.Cells.ToDictionary(x => x.Key, x => x.Value.ColumnNumber);
var invalidDto = new ValidationResultDto<TDto>
{
Item = dto,
Warnings = validationResults
.SelectMany(v => v.MemberNames
.Where(columnsDict.ContainsKey)
.Select(m =>
{
var columnNumber = columnsDict[m];
var errorMessage = v.ErrorMessage;
var warningMessage = string.Format(XLExtentions.ProblemDetailsTemplate,
TemplateParameters.SheetName,
rowNumber,
columnNumber,
errorMessage);
var warning = new ValidationResult(warningMessage, new[] { m });
return warning;
}))
};
return invalidDto;
}
protected virtual ParserResultDto<TDto> ParseExcelSheet(IXLWorksheet sheet)
{
var count = sheet.RowsUsed().Count() - TemplateParameters.HeaderRowsCount;
if (count <= 0)
return new ParserResultDto<TDto>();
var valiationResults = new List<ValidationResultDto<TDto>>(count);
var warnings = new List<ValidationResult>();
for (var i = 0; i < count; i++)
{
var xlRow = sheet.Row(1 + i + TemplateParameters.HeaderRowsCount);
var rowNumber = xlRow.RowNumber();
try
{
var row = ParseRow(xlRow);
var dto = BuildDto(row, rowNumber);
var validationResult = Validate(dto, rowNumber);
valiationResults.Add(validationResult);
}
catch (FileFormatException ex)
{
var warning = new ValidationResult(ex.Message);
warnings.Add(warning);
}
}
var parserResult = new ParserResultDto<TDto>
{
Item = valiationResults
};
if (warnings.Any())
parserResult.Warnings = warnings;
return parserResult;
}
}

View File

@ -0,0 +1,23 @@
using System.ComponentModel.DataAnnotations;
using System.IO;
using AsbCloudApp.Data;
using AsbCloudApp.Requests.ParserOptions;
using AsbCloudInfrastructure.Services.ExcelServices.Templates;
namespace AsbCloudInfrastructure.Services.ExcelServices;
public abstract class ExcelWellRelatedParser<TDto, TOptions, TTemplate> : ExcelParser<TDto, TOptions, TTemplate>
where TDto : class, IValidatableObject, IId, IWellRelated
where TOptions : WellRelatedParserRequest
where TTemplate : class, ITemplateParameters, new()
{
public override ParserResultDto<TDto> Parse(Stream file, TOptions options)
{
var result = base.Parse(file, options);
foreach (var dto in result.Item)
dto.Item.IdWell = options.IdWell;
return result;
}
}

Some files were not shown because too many files have changed in this diff Show More