merge from dev

This commit is contained in:
ngfrolov 2023-12-01 09:16:22 +05:00
commit 149a036e85
Signed by untrusted user who does not match committer: ng.frolov
GPG Key ID: E99907A0357B29A7
193 changed files with 50745 additions and 6627 deletions

View File

@ -1,30 +0,0 @@
using System.Collections;
using System.Collections.Generic;
namespace AsbCloudApp.Data.AutogeneratedDailyReport;
/// <summary>
/// DTO авто-сгенерированного суточного отчёта
/// </summary>
public class AutoGeneratedDailyReportDto : AutoGeneratedDailyReportInfoDto
{
/// <summary>
/// Блок заголовка
/// </summary>
public HeadBlockDto Head { get; set; } = null!;
/// <summary>
/// Блок подсистем
/// </summary>
public IEnumerable<SubsystemRecordDto> Subsystems { get; set; } = null!;
/// <summary>
/// Блок ограничивающих параметров
/// </summary>
public IEnumerable<LimitingParameterRecordDto> LimitingParameters { get; set; } = null!;
/// <summary>
/// Баланс времени
/// </summary>
public IEnumerable<TimeBalanceRecordDto> TimeBalance { get; set; } = null!;
}

View File

@ -1,14 +0,0 @@
using System;
namespace AsbCloudApp.Data.AutogeneratedDailyReport;
/// <summary>
/// Базовая информация о суточном отчёте
/// </summary>
public class AutoGeneratedDailyReportInfoDto : ReportInfoDto
{
/// <summary>
/// Дата формирования отчёта
/// </summary>
public DateOnly ReportDate { get; set; }
}

View File

@ -1,37 +0,0 @@
namespace AsbCloudApp.Data.AutogeneratedDailyReport;
/// <summary>
/// Блок заголовка
/// </summary>
public class HeadBlockDto
{
/// <summary>
/// Название скважины
/// </summary>
public string Well { get; set; } = null!;
/// <summary>
/// Название куста
/// </summary>
public string Cluster { get; set; } = null!;
/// <summary>
/// Заказчик
/// </summary>
public string Customer { get; set; } = null!;
/// <summary>
/// Месторождение
/// </summary>
public string Deposit { get; set; } = null!;
/// <summary>
/// Глубина забоя на дату начала интервала
/// </summary>
public double DepthFrom { get; set; }
/// <summary>
/// Глубина забоя на дату окончания интервала
/// </summary>
public double DepthTo { get; set; }
}

View File

@ -1,27 +0,0 @@
namespace AsbCloudApp.Data.AutogeneratedDailyReport;
/// <summary>
/// Блок ограничивающих параметров
/// </summary>
public class LimitingParameterRecordDto
{
/// <summary>
/// Время использования, мин
/// </summary>
public double Hours { get; set; }
/// <summary>
/// Проходка, м
/// </summary>
public double Depth { get; set; }
/// <summary>
/// Название ограничивающего параметра
/// </summary>
public string NameFeedRegulator { get; set; } = null!;
/// <summary>
/// Процент по проходке, %
/// </summary>
public double PercentDepth { get; set; }
}

View File

@ -1,27 +0,0 @@
namespace AsbCloudApp.Data.AutogeneratedDailyReport;
/// <summary>
/// Блок подсистем
/// </summary>
public class SubsystemRecordDto
{
/// <summary>
/// Название подсистемы
/// </summary>
public string Name { get; set; } = null!;
/// <summary>
/// Использование, %
/// </summary>
public double KUsage { get; set; }
/// <summary>
/// Время работы, ч
/// </summary>
public double UsedTimeHours { get; set; }
/// <summary>
/// Проходка
/// </summary>
public double Depth { get; set; }
}

View File

@ -1,17 +0,0 @@
namespace AsbCloudApp.Data.AutogeneratedDailyReport;
/// <summary>
/// Баланс времени
/// </summary>
public class TimeBalanceRecordDto
{
/// <summary>
/// Название операции
/// </summary>
public string Name { get; set; } = null!;
/// <summary>
/// Продолжительность, часы
/// </summary>
public double DurationHours { get; set; }
}

View File

@ -180,12 +180,12 @@ namespace AsbCloudApp.Data
/// </summary>
protected void SetStatusComplete()
{
CountComplete++;
if (CurrentState is null)
return;
LastComplete = new(CurrentState);
CurrentState = null;
CountComplete++;
Trace.TraceInformation($"{WorkNameForTrace} state: completed");
}
@ -194,12 +194,12 @@ namespace AsbCloudApp.Data
/// </summary>
protected void SetLastError(string errorMessage)
{
CountErrors++;
if (CurrentState is null)
return;
LastError = new LastErrorInfo(CurrentState, errorMessage);
CurrentState = null;
CountErrors++;
Trace.TraceError($"{WorkNameForTrace} throw exception[{CountErrors}]: {errorMessage}");
}
}

View File

@ -1,64 +0,0 @@
namespace AsbCloudApp.Data.DailyReport
{
/// <summary>
/// блок КНБК
/// </summary>
public class BhaDto : ItemInfoDto
{
/// <summary>
/// КНБК описание
/// </summary>
public string BHADescription { get; set; } = string.Empty;
/// <summary>
/// Бурение с наращиваниями в инт. 2195-2763м. Время начала
/// </summary>
public string ExtensionDrillingOneBegin{ get; set; } = string.Empty;
/// <summary>
/// Бурение с наращиваниями в инт. 2195-2763м. Время окончания
/// </summary>
public string ExtensionDrillingOneFinish { get; set; } = string.Empty;
/// <summary>
/// Промывка. Время начала
/// </summary>
public string SluiceBegin { get; set; } = string.Empty;
/// <summary>
/// Промывка. Время окончания
/// </summary>
public string SluiceFinish { get; set; } = string.Empty;
/// <summary>
/// Подъем КНБК. Время начала
/// </summary>
public string ClimbBegin { get; set; } = string.Empty;
/// <summary>
/// Подъем КНБК. Время окончания
/// </summary>
public string ClimbFinish { get; set; } = string.Empty;
/// <summary>
/// Спуск КНБК. Время начала
/// </summary>
public string DescentBegin { get; set; } = string.Empty;
/// <summary>
/// Спуск КНБК. Время окончания
/// </summary>
public string DescentFinish { get; set; } = string.Empty;
/// <summary>
/// Бурение с наращиваниями в инт. 2763-2850м. Время начала
/// </summary>
public string ExtensionDrillingTwoBegin { get; set; } = string.Empty;
/// <summary>
/// Бурение с наращиваниями в инт. 2763-2850м. Время окончания
/// </summary>
public string ExtensionDrillingTwoFinish { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,27 @@
namespace AsbCloudApp.Data.DailyReport.Blocks;
/// <summary>
/// РТК
/// </summary>
public class ProcessMapWellDrillingRecordDto
{
/// <summary>
/// Режим бурения
/// </summary>
public string DrillingMode { get; set; } = null!;
/// <summary>
/// Мех. скорость
/// </summary>
public PlanFactDto<double?> Rop { get; set; } = new();
/// <summary>
/// Глубина ствола
/// </summary>
public double? WellBoreDepth { get; set; }
/// <summary>
/// Часы бурения
/// </summary>
public double MechDrillingHours { get; set; }
}

View File

@ -0,0 +1,32 @@
namespace AsbCloudApp.Data.DailyReport.Blocks;
/// <summary>
/// Блок с графиком работы
/// </summary>
public class ScheduleRecordDto
{
/// <summary>
/// Начало смены
/// </summary>
public TimeDto? ShiftStart { get; set; }
/// <summary>
/// Конец смены
/// </summary>
public TimeDto? ShiftEnd { get; set; }
/// <summary>
/// Имя бурильщика
/// </summary>
public string? Name { get; set; }
/// <summary>
/// Фамилия бурильщика
/// </summary>
public string? Surname { get; set; }
/// <summary>
/// Отчество бурильщика
/// </summary>
public string? Patronymic { get; set; }
}

View File

@ -0,0 +1,17 @@
namespace AsbCloudApp.Data.DailyReport.Blocks.Sign;
/// <summary>
/// Блок с подписями
/// </summary>
public class SignBlockDto : ItemInfoDto
{
/// <summary>
/// Подпись мастера буровой
/// </summary>
public SignRecordDto? DrillingMaster { get; set; }
/// <summary>
/// Подпись супервайзера
/// </summary>
public SignRecordDto? Supervisor { get; set; }
}

View File

@ -0,0 +1,28 @@
namespace AsbCloudApp.Data.DailyReport.Blocks.Sign;
/// <summary>
/// Подпись
/// </summary>
public class SignRecordDto
{
/// <summary>
/// Имя
/// </summary>
public string Name { get; set; } = null!;
/// <summary>
/// Фамилия
/// </summary>
public string Surname { get; set; } = null!;
/// <summary>
/// Отчество
/// </summary>
public string? Patronymic { get; set; }
/// <inheritdoc />
public override string ToString()
{
return $"{Surname} {Name} {Patronymic}";
}
}

View File

@ -0,0 +1,40 @@
using System.Collections.Generic;
using System.Linq;
namespace AsbCloudApp.Data.DailyReport.Blocks.Subsystems;
/// <summary>
/// Блок статистики работы подсистем
/// </summary>
public class SubsystemBlockDto : ItemInfoDto
{
/// <summary>
/// Длина ствола скважины
/// </summary>
public double? Wellbore { get; set; }
/// <summary>
/// Кол-во замеров за сутки
/// </summary>
public double? MeasurementsPerDay { get; set; }
/// <summary>
/// Общая плановая мех. скорость
/// </summary>
public double? TotalRopPlan { get; set; }
/// <summary>
/// Отклонение по ГГД, сут
/// </summary>
public double? TvgLagDays { get; set; }
/// <summary>
/// Рекомендации специалиста
/// </summary>
public string? Comment { get; set; }
/// <summary>
/// Подсистемы
/// </summary>
public IEnumerable<SubsystemRecordDto> Subsystems { get; set; } = Enumerable.Empty<SubsystemRecordDto>();
}

View File

@ -0,0 +1,25 @@
using System.ComponentModel.DataAnnotations;
namespace AsbCloudApp.Data.DailyReport.Blocks.Subsystems;
/// <summary>
/// Параметры наработки подсистемы
/// </summary>
public class SubsystemParametersDto
{
/// <summary>
/// Сумма изменения глубин при включенной подсистеме
/// </summary>
public double? SumDepthInterval { get; set; }
/// <summary>
/// Наработка подсистемы
/// </summary>
public double? UsedTimeHours { get; set; }
/// <summary>
/// Коэффициент использования
/// </summary>
[Range(0, 1)]
public double? KUsage { get; set; }
}

View File

@ -0,0 +1,22 @@
namespace AsbCloudApp.Data.DailyReport.Blocks.Subsystems;
/// <summary>
/// Модуль подсистемы
/// </summary>
public class SubsystemRecordDto
{
/// <summary>
/// Название подсистемы
/// </summary>
public string Name { get; set; } = null!;
/// <summary>
/// Использование подсистемы за сутки
/// </summary>
public SubsystemParametersDto? UsagePerDay { get; set; }
/// <summary>
/// Использование подсистемы за скважину
/// </summary>
public SubsystemParametersDto? UsagePerWell { get; set; }
}

View File

@ -0,0 +1,37 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace AsbCloudApp.Data.DailyReport.Blocks.TimeBalance;
/// <summary>
/// Блок с балансом времени
/// </summary>
public class TimeBalanceBlockDto : ItemInfoDto
{
/// <summary>
/// Идентификатор секции
/// </summary>
[Range(1, int.MaxValue)]
public int IdSection { get; set; }
/// <summary>
/// Название секции
/// </summary>
public string? SectionName { get; set; }
/// <summary>
/// Проходка скважины
/// </summary>
public PlanFactDto<double?> WellDepth { get; set; } = new();
/// <summary>
/// Кол-во наращиваний за сутки
/// </summary>
public double? WellOperationSlipsTimeCount { get; set; }
/// <summary>
/// Операции на скважине
/// </summary>
public IEnumerable<TimeBalanceRecordDto> WellOperations { get; set; } = Enumerable.Empty<TimeBalanceRecordDto>();
}

View File

@ -0,0 +1,35 @@
namespace AsbCloudApp.Data.DailyReport.Blocks.TimeBalance;
/// <summary>
/// Операции проводимые на скважине
/// </summary>
public class TimeBalanceRecordDto
{
/// <summary>
/// Мех. бурение - 1
/// Снятие замера, ориентирование - 2
/// Наращивание, выход на режим - 3
/// Промывка, проработка - 4
/// </summary>
public int IdWellOperation { get; set; }
/// <summary>
/// Продолжительность операции, ч
/// </summary>
public PlanFactDto<double?> DurationHours { get; set; } = new();
/// <summary>
/// Отклонение за секцию
/// </summary>
public double? DrillingDeviationPerSection { get; set; }
/// <summary>
/// Отклонение за сутки
/// </summary>
public double? DrillingDeviationPerDay { get; set; }
/// <summary>
/// Причина отклонения
/// </summary>
public string? ReasonDeviation { get; set; }
}

View File

@ -0,0 +1,27 @@
namespace AsbCloudApp.Data.DailyReport.Blocks;
/// <summary>
/// Блок с траекторией скважины
/// </summary>
public class TrajectoryBlockDto
{
/// <summary>
/// Глубина по стволу
/// </summary>
public double? WellboreDepth { get; set; }
/// <summary>
/// Глубина вертикальная
/// </summary>
public double? VerticalDepth { get; set; }
/// <summary>
/// Угол зенитный
/// </summary>
public double? ZenithAngle { get; set; }
/// <summary>
/// Азимут Географ.
/// </summary>
public double? AzimuthGeo { get; set; }
}

View File

@ -0,0 +1,20 @@
using System.Collections.Generic;
using System.Linq;
namespace AsbCloudApp.Data.DailyReport.Blocks.WellOperation;
/// <summary>
/// Блок с операциями проводимыми на скважине
/// </summary>
public class WellOperationBlockDto
{
/// <summary>
/// Продолжительность бурения за секцию
/// </summary>
public double SectionDrillingHours { get; set; }
/// <summary>
/// Операции проводимые на скважине
/// </summary>
public IEnumerable<WellOperationRecordDto> WellOperations { get; set; } = Enumerable.Empty<WellOperationRecordDto>();
}

View File

@ -0,0 +1,17 @@
namespace AsbCloudApp.Data.DailyReport.Blocks.WellOperation;
/// <summary>
/// Операция на скважине
/// </summary>
public class WellOperationRecordDto
{
/// <summary>
/// Название категории
/// </summary>
public string? CategoryName { get; set; }
/// <summary>
/// Продолжительность операции
/// </summary>
public double? DurationHours { get; set; }
}

View File

@ -1,45 +1,108 @@
using System;
using System.Collections.Generic;
using System.Linq;
using AsbCloudApp.Data.DailyReport.Blocks;
using AsbCloudApp.Data.DailyReport.Blocks.Sign;
using AsbCloudApp.Data.DailyReport.Blocks.Subsystems;
using AsbCloudApp.Data.DailyReport.Blocks.TimeBalance;
using AsbCloudApp.Data.DailyReport.Blocks.WellOperation;
namespace AsbCloudApp.Data.DailyReport
namespace AsbCloudApp.Data.DailyReport;
/// <summary>
/// Суточный отчёт
/// </summary>
public class DailyReportDto : IId,
IWellRelated
{
/// <summary>
/// Блоки для формирования суточного рапорта
/// </summary>
public class DailyReportDto
{
/// <summary>
/// дата отчёта
/// </summary>
public DateOnly StartDate { get; set; }
/// <inheritdoc/>
public int Id { get; set; }
/// <inheritdoc/>
public int IdWell { get; set; }
/// <summary>
/// блок заголовка
/// Название скважины
/// </summary>
public HeadDto Head { get; set; } = new();
public string WellCaption { get; set; } = null!;
/// <summary>
/// блок КНБК
/// Название типа скважины
/// </summary>
public BhaDto Bha { get; set; } = new();
public string? WellType { get; set; }
/// <summary>
/// блок безметражные работы
/// Название куста
/// </summary>
public NoDrillingDto NoDrilling { get; set; } = new();
public string? Cluster { get; set; }
/// <summary>
/// блок баланса времени
/// Заказчик
/// </summary>
public TimeBalanceDto TimeBalance { get; set; } = new();
public string? Customer { get; set; }
/// <summary>
/// блок САУБ
/// Подрядчик
/// </summary>
public SaubDto Saub { get; set; } = new();
public string? Contractor { get; set; }
/// <summary>
/// блок подписи
/// Месторождение
/// </summary>
public SignDto Sign { get; set; } = new();
}
public string? Deposit { get; set; }
/// <summary>
/// Глубина забоя на дату начала интервала
/// </summary>
public double? DepthStart { get; set; }
/// <summary>
/// Глубина забоя на дату окончания интервала
/// </summary>
public double? DepthEnd { get; set; }
/// <summary>
/// Дата формирования отчёта
/// </summary>
public DateTime Date { get; set; }
/// <summary>
/// Дата последнего обновления
/// </summary>
public DateTime? DateLastUpdate { get; set; }
/// <summary>
/// Блок фактической траектории
/// </summary>
public TrajectoryBlockDto TrajectoryBlock { get; set; } = null!;
/// <summary>
/// Фактические операции
/// </summary>
public WellOperationBlockDto FactWellOperationBlock { get; set; } = null!;
/// <summary>
/// Баланс времени
/// </summary>
public TimeBalanceBlockDto? TimeBalanceBlock { get; set; }
/// <summary>
/// Наработка подсистем
/// </summary>
public SubsystemBlockDto? SubsystemBlock { get; set; }
/// <summary>
/// Подпись
/// </summary>
public SignBlockDto? SignBlock { get; set; }
/// <summary>
/// Блок расписания
/// </summary>
public IEnumerable<ScheduleRecordDto> ScheduleBlock { get; set; } = Enumerable.Empty<ScheduleRecordDto>();
/// <summary>
/// РТК
/// </summary>
public IEnumerable<ProcessMapWellDrillingRecordDto> ProcessMapWellDrillingBlock { get; set; } = Enumerable.Empty<ProcessMapWellDrillingRecordDto>();
}

View File

@ -1,110 +0,0 @@
using System;
namespace AsbCloudApp.Data.DailyReport
{
/// <summary>
/// блок заголовка
/// </summary>
public class HeadDto : ItemInfoDto
{
/// <summary>
/// название скважины
/// </summary>
public string WellName { get; set; } = string.Empty;
/// <summary>
/// название куста
/// </summary>
public string ClusterName { get; set; } = string.Empty;
/// <summary>
/// заказчик
/// </summary>
public string Customer { get; set; } = string.Empty;
/// <summary>
/// подрядчик
/// </summary>
public string Contractor { get; set; } = string.Empty;
/// <summary>
/// дата рапорта
/// </summary>
public DateOnly ReportDate { get; set; }
/// <summary>
/// глубина забоя на дату начала интервала
/// </summary>
public double? WellDepthIntervalStartDate { get; set; }
/// <summary>
/// глубина забоя на дату окончания интервала
/// </summary>
public double? WellDepthIntervalFinishDate { get; set; }
/// <summary>
/// Глубина забоя по стволу на окончание отчетного периода
/// </summary>
public double? BottomholeDepth { get; set; }
/// <summary>
/// Глубина забоя по вертикали на дату окончания отчетного периода
/// </summary>
public double? VerticalDepth { get; set; }
/// <summary>
/// Зенитный угол на дату окончания отчетного периода
/// </summary>
public double? ZenithAngle { get; set; }
/// <summary>
/// Азимутальный угол на дату окончания отчетного периода
/// </summary>
public double? AzimuthAngle { get; set; }
/// <summary>
/// ФИО бурильщиков
/// </summary>
public string FirstDriller { get; set; } = string.Empty;
/// <summary>
/// ФИО бурильщиков
/// </summary>
public string SecondDriller { get; set; } = string.Empty;
/// <summary>
/// Время работы АПД
/// </summary>
public double? WorkTimeSAUB { get; set; }
/// <summary>
/// Время работы спин мастер
/// </summary>
public double? WorkTimeSpinMaster { get; set; }
/// <summary>
/// Время работы torqueMaster
/// </summary>
public double? WorkTimeTorkMaster { get; set; }
/// <summary>
/// количество метров пробуренных с включенным АПД
/// </summary>
public double? PenetrationSAUB { get; set; }
/// <summary>
/// количество метров пробуренных с включенным Спин мастер
/// </summary>
public double? PenetrationSpinMaster { get; set; }
/// <summary>
/// количество метров пробуренных с включенным torqueMaster
/// </summary>
public double? PenetrationTorkMaster { get; set; }
/// <summary>
/// Количество запусков МСЕ
/// </summary>
public int CountLaunchesMSE { get; set; }
}
}

View File

@ -1,29 +0,0 @@
namespace AsbCloudApp.Data.DailyReport
{
/// <summary>
/// блок безметражные работы
/// </summary>
public class NoDrillingDto : ItemInfoDto
{
/// <summary>
/// Нормативное время на одну операцию по подготовке ствола скважины к наращиванию
/// </summary>
public double? StandardTimeBarrelPreparation { get; set; }
/// <summary>
/// Нормативное время на одну операцию по наращиванию
/// </summary>
public double? StandardTimeExtension { get; set; }
/// <summary>
/// Фактическое время проработок при подготовке ствола скважины к наращиванию.
/// </summary>
public double? ActualTimeBarrelPreparation { get; set; }
/// <summary>
/// Фактическое время наращиваний
/// </summary>
public double? ActualTimeExtension { get; set; }
}
}

View File

@ -1,107 +0,0 @@
using System.Collections.Generic;
namespace AsbCloudApp.Data.DailyReport
{
/// <summary>
/// блок САУБ
/// </summary>
public class SaubDto : ItemInfoDto
{
/// <summary>
/// Режимы бурения в роторе
/// </summary>
public string RotorDrillingModes { get; set; } = string.Empty;
/// <summary>
/// режимы бурения в слайде
/// </summary>
public string SlideDrillingModes { get; set; } = string.Empty;
/// <summary>
/// Количество метров пробуренных в роторе за отчетный период
/// </summary>
public double? PenetrationInRotor { get; set; }
/// <summary>
/// Количество часов бурения в роторе за отчетный период
/// </summary>
public double? NumberDrillingHours { get; set; }
/// <summary>
/// средний диф перепад в роторе за отчетный период
/// </summary>
public double? AVGDiffDropRotor { get; set; }
/// <summary>
/// количество метров пробуренных в слайде за отчетный период
/// </summary>
public double? PenetrationInSlide { get; set; }
/// <summary>
/// время бурения в роторе за отчетный период
/// </summary>
public double? DrillingTimeInRotor { get; set; }
/// <summary>
/// средний диф. перепад в слайде за отчетный период
/// </summary>
public double? AVGDiffPressureSlide { get; set; }
/// <summary>
/// Плановая МСП за секцию
/// </summary>
public double? SectionROPPlan { get; set; }
/// <summary>
/// Общее время бурения за секцию
/// </summary>
public double? SectionDrillingTimeTotal { get; set; }
/// <summary>
/// Общая проходка за секцию
/// </summary>
public double? SectionPenetrationTotal { get; set; }
/// <summary>
/// Количество наращиваний за отчетный период
/// </summary>
public int ExtensionsCount { get; set; }
/// <summary>
/// Отклонение относительно ГГД
/// </summary>
public double? DeviationFromTVD { get; set; }
/// <summary>
/// указываются все причины, которые влияют на снижение МСП.
/// </summary>
public string DeclinesReasonsROP { get; set; } = string.Empty;
/// <summary>
/// Увеличение мех скорости за секцию %
/// </summary>
public string IncreaseSpeedSection { get; set; } = string.Empty;
/// <summary>
/// Увеличение мех скорости за сутки %
/// </summary>
public string IncreaseSpeedDay { get; set; } = string.Empty;
/// <summary>
/// Сокращение времени бурения за секцию, ч
/// </summary>
public string ReductionTimeDrilling { get; set; } = string.Empty;
/// <summary>
/// Ротор/Слайд %
/// </summary>
public string RotorSlidePercent { get; set; } = string.Empty;
/// <summary>
/// МСП
/// </summary>
public string MspSection { get; set; } = string.Empty;
}
}

View File

@ -1,19 +0,0 @@
namespace AsbCloudApp.Data.DailyReport
{
/// <summary>
/// блок подписи
/// </summary>
public class SignDto : ItemInfoDto
{
/// <summary>
/// ФИО Мастера буровой
/// </summary>
public string DrillingMaster { get; set; } = null!;
/// <summary>
/// ФИО супервайзера
/// </summary>
public string Supervisor { get; set; } = null!;
}
}

View File

@ -1,18 +0,0 @@
using System.Collections.Generic;
namespace AsbCloudApp.Data.DailyReport
{
/// <summary>
/// Блок баланса времени
/// </summary>
public class TimeBalanceDto : ItemInfoDto
{
/// <summary>
/// Статистика по операциям
/// </summary>
public Dictionary<int, double> OperationsStat { get; set; } = new Dictionary<int, double>();
}
}

View File

@ -92,7 +92,7 @@ public class ProcessMapReportWellDrillingDto
public double UsageFact { get; set; }
/// <summary>
/// Фактическая механическая скорость, м/ч
/// Механическая скорость, м/ч
/// </summary>
public double? Rop { get; set; }
public PlanFactDto<double?> Rop { get; set; }
}

View File

@ -0,0 +1,30 @@
using System;
namespace AsbCloudInfrastructure.Services.SAUB
{
/// <summary>
/// Статистика данных телеметрии
/// </summary>
public class TelemetryDataStatDto
{
/// <summary>
/// ID в БД
/// </summary>
public int IdTelemetry { get; set; }
/// <summary>
/// дата получения первых данных
/// </summary>
public DateTimeOffset DateFirst { get; set; }
/// <summary>
/// дата получения последних полученных данных
/// </summary>
public DateTimeOffset DateLast { get; set; }
/// <summary>
/// смещение часового пояса
/// </summary>
public double TimezoneOffsetHours { get; set; }
}
}

View File

@ -1,4 +1,4 @@
namespace AsbCloudApp.Data
namespace AsbCloudApp.Data.Trajectory
{

View File

@ -1,7 +1,7 @@
namespace AsbCloudApp.Data
namespace AsbCloudApp.Data.Trajectory
{
/// <summary>
/// Визуализация траектории 3D для посторения радиуса цели
/// Визуализация траектории 3D для построения радиуса цели
/// </summary>
public class TrajectoryCartesianPlanDto : TrajectoryCartesianFactDto
{

View File

@ -0,0 +1,53 @@
using System;
namespace AsbCloudApp.Data.Trajectory
{
/// <summary>
/// Базовая географическая траектория
/// </summary>
public abstract class TrajectoryGeoDto
{
/// <summary>
/// ИД строки с координатами
/// </summary>
public int Id { get; set; }
/// <summary>
/// Id скважины
/// </summary>
public int IdWell { get; set; }
/// <summary>
/// Глубина по стволу
/// </summary>
public double WellboreDepth { get; set; }
/// <summary>
/// Угол зенитный
/// </summary>
public double ZenithAngle { get; set; }
/// <summary>
/// Азимут Географ.
/// </summary>
public double AzimuthGeo { get; set; }
/// <summary>
/// Азимут Магнитный
/// </summary>
public double? AzimuthMagnetic { get; set; }
/// <summary>
/// Глубина вертикальная
/// </summary>
public double? VerticalDepth { get; set; }
/// <summary>
/// Дата загрузки
/// </summary>
public DateTime UpdateDate { get; set; }
/// <summary>
/// ИД пользователя
/// </summary>
public int IdUser { get; set; }
}
}

View File

@ -0,0 +1,15 @@
namespace AsbCloudApp.Data.Trajectory;
/// <summary>
/// Формирование данных по фактической географической траектории
/// </summary>
public class TrajectoryGeoFactDto : TrajectoryGeoDto
{
/// <summary>
/// Комментарии
/// </summary>
public string? Comment { get; set; }
}

View File

@ -0,0 +1,21 @@
using System;
namespace AsbCloudApp.Data.Trajectory
{
/// <summary>
/// Формирование данных по плановой географической траектории
/// </summary>
public class TrajectoryGeoPlanDto : TrajectoryGeoDto
{
/// <summary>
/// Радиус цели
/// </summary>
public double? Radius { get; set; }
/// <summary>
/// Комментарии
/// </summary>
public string? Comment { get; set; }
}
}

View File

@ -0,0 +1,25 @@
namespace AsbCloudApp.Data.Trajectory
{
/// <summary>
/// DTO объединяющее плановые и фактические значения траекторий
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="V"></typeparam>
public class TrajectoryPlanFactDto<T, V>
{
/// <summary>
/// Плановое значение
/// </summary>
public T? Plan { get; set; }
/// <summary>
/// Фактическое значение
/// </summary>
public V? FactManual { get; set; }
/// <summary>
/// Фактическое ннб-значение
/// </summary>
public V? FactNnb { get; set; }
}
}

View File

@ -1,45 +0,0 @@
namespace AsbCloudApp.Data;
/// <summary>
/// Базовая географическая траектория
/// </summary>
public abstract class TrajectoryGeoDto
{
/// <summary>
/// Id скважины
/// </summary>
public int IdWell { get; set; }
/// <summary>
/// Глубина по стволу
/// </summary>
public double WellboreDepth { get; set; }
/// <summary>
/// Угол зенитный
/// </summary>
public double ZenithAngle { get; set; }
/// <summary>
/// Азимут Географ.
/// </summary>
public double AzimuthGeo { get; set; }
/// <summary>
/// Азимут Магнитный
/// </summary>
public double? AzimuthMagnetic { get; set; }
/// <summary>
/// Глубина вертикальная
/// </summary>
public double? VerticalDepth { get; set; }
}
/// <summary>
/// Формирование данных по фактической географической траектории
/// </summary>
public class TrajectoryGeoFactDto : TrajectoryGeoDto
{ }

View File

@ -1,35 +0,0 @@
using System;
namespace AsbCloudApp.Data
{
/// <summary>
/// Формирование данных по плановой географической траектории
/// </summary>
public class TrajectoryGeoPlanDto: TrajectoryGeoDto
{
/// <summary>
/// ИД строки с координатами
/// </summary>
public int Id { get; set; }
/// <summary>
/// Дата загрузки
/// </summary>
public DateTime UpdateDate { get; set; }
/// <summary>
/// ИД пользователя
/// </summary>
public int IdUser { get; set; }
/// <summary>
/// Радиус цели
/// </summary>
public double? Radius { get; set; }
/// <summary>
/// Комментарии
/// </summary>
public string? Comment { get; set; }
}
}

View File

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data.DailyReport;
using AsbCloudApp.Requests;
using AsbCloudApp.Services;
namespace AsbCloudApp.Repositories;
/// <summary>
/// Суточные отчёты
/// </summary>
public interface IDailyReportRepository : ICrudRepository<DailyReportDto>
{
/// <summary>
/// Получить список суточный отчёт по скважине
/// </summary>
/// <param name="idWell"></param>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<DailyReportDto>> GetAsync(int idWell, FileReportRequest request, CancellationToken cancellationToken);
/// <summary>
/// Получить суточный отчёт
/// </summary>
/// <param name="idWell"></param>
/// <param name="date"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<DailyReportDto?> GetOrDefaultAsync(int idWell, DateTime date, CancellationToken cancellationToken);
}

View File

@ -20,15 +20,4 @@ public interface IHelpPageRepository : ICrudRepository<HelpPageDto>
Task<HelpPageDto?> GetOrDefaultByUrlPageAndIdCategoryAsync(string key,
int idCategory,
CancellationToken cancellationToken);
/// <summary>
/// Проверяет наличие справки для страницы
/// </summary>
/// <param name="key"></param>
/// <param name="idCategory"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<bool> IsExistingAsync(string key,
int idCategory,
CancellationToken cancellationToken);
}

View File

@ -1,5 +1,6 @@
using AsbCloudApp.Data;
using AsbCloudApp.Requests;
using AsbCloudInfrastructure.Services.SAUB;
using System;
using System.Collections.Generic;
@ -65,5 +66,11 @@ namespace AsbCloudApp.Repositories
/// <param name="idTelemetry"></param>
/// <returns></returns>
(TDto First, TDto Last)? GetOrDefaultFirstLast(int idTelemetry);
/// <summary>
/// статистика хранимой телеметрии по всем кешированым
/// </summary>
/// <returns></returns>
IEnumerable<TelemetryDataStatDto> GetStat();
}
}

View File

@ -1,4 +1,4 @@
using AsbCloudApp.Data;
using AsbCloudApp.Data.Trajectory;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@ -6,26 +6,27 @@ using System.Threading.Tasks;
namespace AsbCloudApp.Repositories
{
/// <summary>
/// CRUD для работы с плановой траекторией из клиента
/// CRUD-репозиторий для работы с траекторией из клиента (плановой и фактической)
/// </summary>
/// <returns></returns>
public interface ITrajectoryPlanRepository : ITrajectoryRepository<TrajectoryGeoPlanDto>
//TrajectoryGeoPlanDto
public interface ITrajectoryEditableRepository<T> : ITrajectoryRepository<T> where T : TrajectoryGeoDto
{
/// <summary>
/// Добавить строки с координатами по одной скважине. Если в коллекции координаты для разных скважин получаем exception.
/// </summary>
/// <param name="plannedTrajectoryRows"></param>
/// <param name="trajectoryRows"></param>
/// <param name="token"></param>
/// <returns>количество записанных строк или exception с описанием</returns>
Task<int> AddRangeAsync(IEnumerable<TrajectoryGeoPlanDto> plannedTrajectoryRows, CancellationToken token);
Task<int> AddRangeAsync(IEnumerable<T> trajectoryRows, CancellationToken token);
/// <summary>
/// Добавить одну строку с координатами
/// </summary>
/// <param name="plannedTrajectoryRow"></param>
/// <param name="trajectoryRow"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> AddAsync(TrajectoryGeoPlanDto plannedTrajectoryRow, CancellationToken token);
Task<int> AddAsync(T trajectoryRow, CancellationToken token);
/// <summary>
/// Обновить строку с координатами
@ -33,7 +34,7 @@ namespace AsbCloudApp.Repositories
/// <param name="row"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> UpdateAsync(TrajectoryGeoPlanDto row,
Task<int> UpdateAsync(T row,
CancellationToken token);
/// <summary>
@ -45,7 +46,7 @@ namespace AsbCloudApp.Repositories
Task<int> DeleteRangeAsync(IEnumerable<int> ids, CancellationToken token);
/// <summary>
/// Удалить всю плановую траекторию по ИД скважины
/// Удалить всю траекторию по ИД скважины
/// </summary>
/// <param name="idWell"></param>
/// <param name="token"></param>

View File

@ -1,16 +0,0 @@
using AsbCloudApp.Data;
using AsbCloudApp.Data.WITS;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Repositories
{
/// <summary>
/// CRUD для работы с фактической траекторией из клиента
/// </summary>
/// <returns></returns>
public interface ITrajectoryFactRepository : ITrajectoryRepository<TrajectoryGeoFactDto>
{
}
}

View File

@ -0,0 +1,23 @@
using AsbCloudApp.Data.Trajectory;
using AsbCloudApp.Requests;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Repositories
{
/// <summary>
/// репозиторий для работы с траекторией из ннб (фактической)
/// </summary>
/// <returns></returns>
public interface ITrajectoryNnbRepository : ITrajectoryRepository<TrajectoryGeoFactDto>
{
/// <summary>
/// получение списка траекторий по параметрам запроса
/// </summary>
/// <param name="trajectoryRequest">параметры запроса</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<TrajectoryGeoFactDto>> GetByRequestAsync(TrajectoryRequest trajectoryRequest, CancellationToken cancellationToken);
}
}

View File

@ -1,8 +1,5 @@
using AsbCloudApp.Data;
using System;
using AsbCloudApp.Data.Trajectory;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
@ -15,9 +12,9 @@ namespace AsbCloudApp.Repositories
where T : TrajectoryGeoDto
{
/// <summary>
/// Получить все добавленные по скважине координаты плановой траектории
/// Получить все добавленные по скважине координаты траектории
/// </summary>
/// <param name="idWell"></param>
/// <param name="idWell">ключ скважины</param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<T>> GetAsync(int idWell, CancellationToken token);

View File

@ -0,0 +1,24 @@
using System;
namespace AsbCloudApp.Requests;
/// <summary>
/// Запрос для получения фактической траектории
/// </summary>
public class TrajectoryRequest : RequestBase
{
/// <summary>
/// Идентификатор скважины
/// </summary>
public int IdWell { get; set; }
/// <summary>
/// Больше или равно дате
/// </summary>
public DateTime? GeDate { get; set; }
/// <summary>
/// Меньше или равно дате
/// </summary>
public DateTime? LeDate { get; set; }
}

View File

@ -1,44 +0,0 @@
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Data.AutogeneratedDailyReport;
using AsbCloudApp.Requests;
namespace AsbCloudApp.Services.AutoGeneratedDailyReports;
/// <summary>
/// Сервис для работы с авто-генерируемыми суточными отчётами
/// </summary>
public interface IAutoGeneratedDailyReportService
{
/// <summary>
/// Список файлов суточных отчётов
/// </summary>
/// <param name="idWell"></param>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<PaginationContainer<AutoGeneratedDailyReportInfoDto>> GetListAsync(int idWell,
FileReportRequest request,
CancellationToken cancellationToken);
/// <summary>
/// Генерация файла с отчётом
/// </summary>
/// <param name="idWell"></param>
/// <param name="reportDate"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<(string fileName, Stream stream)> GenerateAsync(int idWell, DateOnly reportDate,
CancellationToken cancellationToken);
/// <summary>
/// Получение диапазона дат
/// </summary>
/// <param name="idWell"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<DatesRangeDto?> GetDatesRangeAsync(int idWell, CancellationToken cancellationToken);
}

View File

@ -0,0 +1,21 @@
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Services.DailyReport;
/// <summary>
/// Сервис экспорта суточного отчёта
/// </summary>
public interface IDailyReportExportService
{
/// <summary>
/// Экспортировать
/// </summary>
/// <param name="idWell"></param>
/// <param name="dailyReportDateStart"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<(string FileName, Stream File)> ExportAsync(int idWell, DateTime dailyReportDateStart, CancellationToken cancellationToken);
}

View File

@ -0,0 +1,53 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Data.DailyReport;
using AsbCloudApp.Requests;
namespace AsbCloudApp.Services.DailyReport;
/// <summary>
/// Суточные отчёты
/// </summary>
public interface IDailyReportService
{
/// <summary>
/// Обновить или создать суточный отчёт
/// </summary>
/// <param name="dateDailyReport"></param>
/// <param name="idUser"></param>
/// <param name="editableBlock"></param>
/// <param name="cancellationToken"></param>
/// <param name="idWell"></param>
/// <returns></returns>
Task<int> UpdateOrInsertAsync<TBlock>(int idWell, DateTime dateDailyReport, int idUser, TBlock editableBlock,
CancellationToken cancellationToken)
where TBlock : ItemInfoDto;
/// <summary>
/// Получить сформированный суточный отчёт
/// </summary>
/// <param name="idWell"></param>
/// <param name="dateDailyReport"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<DailyReportDto> GetAsync(int idWell, DateTime dateDailyReport, CancellationToken cancellationToken);
/// <summary>
/// Получить список суточных отчётов по скважине
/// </summary>
/// <param name="idWell"></param>
/// <param name="request"></param>
/// <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

@ -1,55 +0,0 @@
using AsbCloudApp.Data;
using AsbCloudApp.Data.DailyReport;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Services
{
/// <summary>
/// Суточный рапорт (сводка)
/// </summary>
public interface IDailyReportService
{
/// <summary>
/// получить список сформированных рапортов по скважине за период времени
/// </summary>
/// <param name="idWell"></param>
/// <param name="begin"></param>
/// <param name="end"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<DailyReportDto>> GetListAsync(int idWell, DateOnly? begin, DateOnly? end, CancellationToken cancellationToken);
/// <summary>
/// Добавить новый рапорт
/// </summary>
/// <param name="idWell"></param>
/// <param name="startDate"></param>
/// <param name="idUser"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> AddAsync(int idWell, DateOnly startDate, int idUser, CancellationToken token);
/// <summary>
/// Сформировать файл рапорта
/// </summary>
/// <param name="idWell"></param>
/// <param name="date"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<Stream?> MakeReportAsync(int idWell, DateOnly date, CancellationToken token);
/// <summary>
/// изменить блок данных для суточного рапорта
/// </summary>
/// <param name="idWell"></param>
/// <param name="startDate"></param>
/// <param name="dto"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> UpdateBlockAsync(int idWell, DateOnly startDate, ItemInfoDto dto, CancellationToken token);
}
}

View File

@ -1,40 +0,0 @@
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Services
{
/// <summary>
/// Сервис загрузки и обработки плановой траектории из файла
/// </summary>
public interface IPlannedTrajectoryImportService
{
/// <summary>
/// скачать шаблон для заполнения плановой траектории
/// </summary>
/// <returns></returns>
Stream GetTemplateFile();
/// <summary>
/// Получить имя файла (исходя из названия скважины)
/// </summary>
/// <returns></returns>
Task<string> GetFileNameAsync(int idWell, CancellationToken token);
/// <summary>
/// загрузить текущую плановую траекторию в .xlsx
/// </summary>
/// <param name="idWell"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<Stream> ExportAsync(int idWell, CancellationToken token);
/// <summary>
/// импортировать из excel плановую траекторию
/// </summary>
/// <param name="idWell"></param>
/// <param name="idUser"></param>
/// <param name="stream"></param>
/// <param name="token"></param>
/// <param name="deleteBeforeImport">Очистить старые координаты перед импортом (если файл проходит валидацию)</param>
Task<int> ImportAsync(int idWell, int idUser, Stream stream, bool deleteBeforeImport, CancellationToken token);
}
}

View File

@ -1,5 +1,6 @@
using AsbCloudApp.Data;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@ -10,6 +11,15 @@ namespace AsbCloudApp.Services
/// </summary>
public interface IScheduleRepository : IRepositoryWellRelated<ScheduleDto>
{
/// <summary>
/// Получить расписание смен
/// </summary>
/// <param name="idWell"></param>
/// <param name="workTime"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<ScheduleDto>> GetAsync(int idWell, DateTime workTime, CancellationToken token);
/// <summary>
/// получить бурильщика по idWell и времени
/// </summary>

View File

@ -1,23 +0,0 @@
using AsbCloudApp.Data.Subsystems;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Services.Subsystems
{
// TODO: move this to repositories
/// <summary>
/// репозиторий получения подсистем
/// </summary>
public interface ISubsystemService
{
/// <summary>
/// получение списка подсистем. Если скважина указана, то получим только использованные в скважине подсистемы.
/// </summary>
/// <param name="idWell"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<SubsystemDto>?> GetSubsystemAsync(int? idWell, CancellationToken token);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,140 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace AsbCloudDb.Migrations
{
public partial class Update_DailyReport : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("Truncate table t_daily_report");
migrationBuilder.DropPrimaryKey(
name: "t_id_well_date_start_pk",
table: "t_daily_report");
migrationBuilder.DropColumn(
name: "start_date",
table: "t_daily_report");
migrationBuilder.DropColumn(
name: "info",
table: "t_daily_report");
migrationBuilder.AddColumn<int>(
name: "Id",
table: "t_daily_report",
type: "integer",
nullable: false,
defaultValue: 0)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
migrationBuilder.AddColumn<DateTime>(
name: "date",
table: "t_daily_report",
type: "timestamp with time zone",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified),
comment: "Дата формирования отчёта");
migrationBuilder.AddColumn<DateTime>(
name: "date_last_update",
table: "t_daily_report",
type: "timestamp with time zone",
nullable: true,
comment: "Дата последнего обновления");
migrationBuilder.AddColumn<string>(
name: "sign_block",
table: "t_daily_report",
type: "jsonb",
nullable: true,
comment: "Подпись");
migrationBuilder.AddColumn<string>(
name: "subsystem_block",
table: "t_daily_report",
type: "jsonb",
nullable: true,
comment: "Наработкой подсистем");
migrationBuilder.AddColumn<string>(
name: "time_balance_block",
table: "t_daily_report",
type: "jsonb",
nullable: true,
comment: "Баланс времени");
migrationBuilder.AddPrimaryKey(
name: "PK_t_daily_report",
table: "t_daily_report",
column: "Id");
migrationBuilder.CreateIndex(
name: "IX_t_daily_report_id_well_date",
table: "t_daily_report",
columns: new[] { "id_well", "date" },
unique: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("Truncate table t_daily_report");
migrationBuilder.DropPrimaryKey(
name: "PK_t_daily_report",
table: "t_daily_report");
migrationBuilder.DropIndex(
name: "IX_t_daily_report_id_well_date",
table: "t_daily_report");
migrationBuilder.DropColumn(
name: "Id",
table: "t_daily_report");
migrationBuilder.DropColumn(
name: "date",
table: "t_daily_report");
migrationBuilder.DropColumn(
name: "date_last_update",
table: "t_daily_report");
migrationBuilder.DropColumn(
name: "sign_block",
table: "t_daily_report");
migrationBuilder.DropColumn(
name: "subsystem_block",
table: "t_daily_report");
migrationBuilder.DropColumn(
name: "time_balance_block",
table: "t_daily_report");
migrationBuilder.AddColumn<DateOnly>(
name: "start_date",
table: "t_daily_report",
type: "date",
nullable: false,
defaultValue: new DateOnly(1, 1, 1),
comment: "Дата отчёта");
migrationBuilder.AddColumn<string>(
name: "info",
table: "t_daily_report",
type: "jsonb",
nullable: true,
comment: "Список параметров для отчёта");
migrationBuilder.AddPrimaryKey(
name: "t_id_well_date_start_pk",
table: "t_daily_report",
columns: new[] { "id_well", "start_date" });
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,64 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace AsbCloudDb.Migrations
{
public partial class Add_Fact_Trajectory_Table : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "t_trajectory_fact",
columns: table => new
{
id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
id_user = table.Column<int>(type: "integer", nullable: false, comment: "ID пользователя который внес/изменил запись"),
id_well = table.Column<int>(type: "integer", nullable: false, comment: "ID скважины"),
update_date = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Дата загрузки траектории"),
wellbore_depth = table.Column<double>(type: "double precision", nullable: false, comment: "Глубина по стволу"),
zenith_angle = table.Column<double>(type: "double precision", nullable: false, comment: "Угол зенитный"),
azimuth_geo = table.Column<double>(type: "double precision", nullable: false, comment: "Азимут Географ."),
azimuth_magnetic = table.Column<double>(type: "double precision", nullable: false, comment: "Азимут Магнитный"),
vertical_depth = table.Column<double>(type: "double precision", nullable: false, comment: "Глубина вертикальная"),
comment = table.Column<string>(type: "text", nullable: true, comment: "Комментарии")
},
constraints: table =>
{
table.PrimaryKey("PK_t_trajectory_fact", x => x.id);
table.ForeignKey(
name: "FK_t_trajectory_fact_t_user_id_user",
column: x => x.id_user,
principalTable: "t_user",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_t_trajectory_fact_t_well_id_well",
column: x => x.id_well,
principalTable: "t_well",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
},
comment: "Загрузка фактической траектории");
migrationBuilder.CreateIndex(
name: "IX_t_trajectory_fact_id_user",
table: "t_trajectory_fact",
column: "id_user");
migrationBuilder.CreateIndex(
name: "IX_t_trajectory_fact_id_well",
table: "t_trajectory_fact",
column: "id_well");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "t_trajectory_fact");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,94 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AsbCloudDb.Migrations
{
public partial class Add_New_WellOperationCategories : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.InsertData(
table: "t_well_operation_category",
columns: new[] { "id", "id_parent", "key_value_name", "key_value_units", "name" },
values: new object[,]
{
{ 4018, 3002, "dT", "мин", "Крепление" },
{ 5102, 4018, "dT", "мин", "Спуск пакера" },
{ 5103, 4011, "dT", "мин", "Запись гамма-каратожа" },
{ 5104, 4013, "dT", "мин", "Шаблонирование спуск БИ" },
{ 5105, 4018, "dT", "мин", "Сборка клин-отклонителя" },
{ 5106, 4018, "dT", "мин", "Ориентирование и посадка клина-отклонителя" },
{ 5107, 4018, "dT", "мин", "Протяжка подъемного патрубка подвески" },
{ 5108, 4018, "dT", "мин", "Подъем клина-отклонителя" },
{ 5109, 4018, "dT", "мин", "Стыковка стингера с хвостовиком основного ствола" },
{ 5110, 4018, "dT", "мин", "Ориентирование и установка стыковочного узла хвостовика" },
{ 5111, 4001, "МСП", "м/ч", "Бурение с отбором керна" },
{ 5112, 4018, "dT", "мин", "Работа пакером в обсадной колонне" }
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "t_well_operation_category",
keyColumn: "id",
keyValue: 4018);
migrationBuilder.DeleteData(
table: "t_well_operation_category",
keyColumn: "id",
keyValue: 5102);
migrationBuilder.DeleteData(
table: "t_well_operation_category",
keyColumn: "id",
keyValue: 5103);
migrationBuilder.DeleteData(
table: "t_well_operation_category",
keyColumn: "id",
keyValue: 5104);
migrationBuilder.DeleteData(
table: "t_well_operation_category",
keyColumn: "id",
keyValue: 5105);
migrationBuilder.DeleteData(
table: "t_well_operation_category",
keyColumn: "id",
keyValue: 5106);
migrationBuilder.DeleteData(
table: "t_well_operation_category",
keyColumn: "id",
keyValue: 5107);
migrationBuilder.DeleteData(
table: "t_well_operation_category",
keyColumn: "id",
keyValue: 5108);
migrationBuilder.DeleteData(
table: "t_well_operation_category",
keyColumn: "id",
keyValue: 5109);
migrationBuilder.DeleteData(
table: "t_well_operation_category",
keyColumn: "id",
keyValue: 5110);
migrationBuilder.DeleteData(
table: "t_well_operation_category",
keyColumn: "id",
keyValue: 5111);
migrationBuilder.DeleteData(
table: "t_well_operation_category",
keyColumn: "id",
keyValue: 5112);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,109 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AsbCloudDb.Migrations
{
public partial class Update_t_planned_trajectory : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_t_planned_trajectory_t_user_id_user",
table: "t_planned_trajectory");
migrationBuilder.DropForeignKey(
name: "FK_t_planned_trajectory_t_well_id_well",
table: "t_planned_trajectory");
migrationBuilder.DropPrimaryKey(
name: "PK_t_planned_trajectory",
table: "t_planned_trajectory");
migrationBuilder.RenameTable(
name: "t_planned_trajectory",
newName: "t_trajectory_planned");
migrationBuilder.RenameIndex(
name: "IX_t_planned_trajectory_id_well",
table: "t_trajectory_planned",
newName: "IX_t_trajectory_planned_id_well");
migrationBuilder.RenameIndex(
name: "IX_t_planned_trajectory_id_user",
table: "t_trajectory_planned",
newName: "IX_t_trajectory_planned_id_user");
migrationBuilder.AddPrimaryKey(
name: "PK_t_trajectory_planned",
table: "t_trajectory_planned",
column: "id");
migrationBuilder.AddForeignKey(
name: "FK_t_trajectory_planned_t_user_id_user",
table: "t_trajectory_planned",
column: "id_user",
principalTable: "t_user",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_t_trajectory_planned_t_well_id_well",
table: "t_trajectory_planned",
column: "id_well",
principalTable: "t_well",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_t_trajectory_planned_t_user_id_user",
table: "t_trajectory_planned");
migrationBuilder.DropForeignKey(
name: "FK_t_trajectory_planned_t_well_id_well",
table: "t_trajectory_planned");
migrationBuilder.DropPrimaryKey(
name: "PK_t_trajectory_planned",
table: "t_trajectory_planned");
migrationBuilder.RenameTable(
name: "t_trajectory_planned",
newName: "t_planned_trajectory");
migrationBuilder.RenameIndex(
name: "IX_t_trajectory_planned_id_well",
table: "t_planned_trajectory",
newName: "IX_t_planned_trajectory_id_well");
migrationBuilder.RenameIndex(
name: "IX_t_trajectory_planned_id_user",
table: "t_planned_trajectory",
newName: "IX_t_planned_trajectory_id_user");
migrationBuilder.AddPrimaryKey(
name: "PK_t_planned_trajectory",
table: "t_planned_trajectory",
column: "id");
migrationBuilder.AddForeignKey(
name: "FK_t_planned_trajectory_t_user_id_user",
table: "t_planned_trajectory",
column: "id_user",
principalTable: "t_user",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_t_planned_trajectory_t_well_id_well",
table: "t_planned_trajectory",
column: "id_well",
principalTable: "t_well",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,109 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AsbCloudDb.Migrations
{
public partial class Rename_t_trajectory_plan : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_t_trajectory_planned_t_user_id_user",
table: "t_trajectory_planned");
migrationBuilder.DropForeignKey(
name: "FK_t_trajectory_planned_t_well_id_well",
table: "t_trajectory_planned");
migrationBuilder.DropPrimaryKey(
name: "PK_t_trajectory_planned",
table: "t_trajectory_planned");
migrationBuilder.RenameTable(
name: "t_trajectory_planned",
newName: "t_trajectory_plan");
migrationBuilder.RenameIndex(
name: "IX_t_trajectory_planned_id_well",
table: "t_trajectory_plan",
newName: "IX_t_trajectory_plan_id_well");
migrationBuilder.RenameIndex(
name: "IX_t_trajectory_planned_id_user",
table: "t_trajectory_plan",
newName: "IX_t_trajectory_plan_id_user");
migrationBuilder.AddPrimaryKey(
name: "PK_t_trajectory_plan",
table: "t_trajectory_plan",
column: "id");
migrationBuilder.AddForeignKey(
name: "FK_t_trajectory_plan_t_user_id_user",
table: "t_trajectory_plan",
column: "id_user",
principalTable: "t_user",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_t_trajectory_plan_t_well_id_well",
table: "t_trajectory_plan",
column: "id_well",
principalTable: "t_well",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_t_trajectory_plan_t_user_id_user",
table: "t_trajectory_plan");
migrationBuilder.DropForeignKey(
name: "FK_t_trajectory_plan_t_well_id_well",
table: "t_trajectory_plan");
migrationBuilder.DropPrimaryKey(
name: "PK_t_trajectory_plan",
table: "t_trajectory_plan");
migrationBuilder.RenameTable(
name: "t_trajectory_plan",
newName: "t_trajectory_planned");
migrationBuilder.RenameIndex(
name: "IX_t_trajectory_plan_id_well",
table: "t_trajectory_planned",
newName: "IX_t_trajectory_planned_id_well");
migrationBuilder.RenameIndex(
name: "IX_t_trajectory_plan_id_user",
table: "t_trajectory_planned",
newName: "IX_t_trajectory_planned_id_user");
migrationBuilder.AddPrimaryKey(
name: "PK_t_trajectory_planned",
table: "t_trajectory_planned",
column: "id");
migrationBuilder.AddForeignKey(
name: "FK_t_trajectory_planned_t_user_id_user",
table: "t_trajectory_planned",
column: "id_user",
principalTable: "t_user",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_t_trajectory_planned_t_well_id_well",
table: "t_trajectory_planned",
column: "id_well",
principalTable: "t_well",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
}
}
}

View File

@ -262,7 +262,7 @@ namespace AsbCloudDb.Migrations
b.HasComment("Контакты");
});
modelBuilder.Entity("AsbCloudDb.Model.DailyReport.DailyReport", b =>
modelBuilder.Entity("AsbCloudDb.Model.DailyReports.DailyReport", b =>
{
b.Property<int>("IdWell")
.HasColumnType("integer")
@ -2416,76 +2416,6 @@ namespace AsbCloudDb.Migrations
});
});
modelBuilder.Entity("AsbCloudDb.Model.PlannedTrajectory", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasColumnName("id");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<double>("AzimuthGeo")
.HasColumnType("double precision")
.HasColumnName("azimuth_geo")
.HasComment("Азимут Географ.");
b.Property<double>("AzimuthMagnetic")
.HasColumnType("double precision")
.HasColumnName("azimuth_magnetic")
.HasComment("Азимут Магнитный");
b.Property<string>("Comment")
.HasColumnType("text")
.HasColumnName("comment")
.HasComment("Комментарии");
b.Property<int>("IdUser")
.HasColumnType("integer")
.HasColumnName("id_user")
.HasComment("ID пользователя который внес/изменил запись");
b.Property<int>("IdWell")
.HasColumnType("integer")
.HasColumnName("id_well")
.HasComment("ID скважины");
b.Property<double?>("Radius")
.HasColumnType("double precision")
.HasColumnName("radius")
.HasComment("Радиус цели");
b.Property<DateTimeOffset>("UpdateDate")
.HasColumnType("timestamp with time zone")
.HasColumnName("update_date")
.HasComment("Дата загрузки траектории");
b.Property<double>("VerticalDepth")
.HasColumnType("double precision")
.HasColumnName("vertical_depth")
.HasComment("Глубина вертикальная");
b.Property<double>("WellboreDepth")
.HasColumnType("double precision")
.HasColumnName("wellbore_depth")
.HasComment("Глубина по стволу");
b.Property<double>("ZenithAngle")
.HasColumnType("double precision")
.HasColumnName("zenith_angle")
.HasComment("Угол зенитный");
b.HasKey("Id");
b.HasIndex("IdUser");
b.HasIndex("IdWell");
b.ToTable("t_planned_trajectory");
b.HasComment("Загрузка плановой траектории");
});
modelBuilder.Entity("AsbCloudDb.Model.ProcessMaps.ProcessMapWellDrilling", b =>
{
b.Property<int>("Id")
@ -5185,6 +5115,141 @@ namespace AsbCloudDb.Migrations
b.HasComment("Наработка талевого каната");
});
modelBuilder.Entity("AsbCloudDb.Model.Trajectory.TrajectoryFact", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasColumnName("id");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<double>("AzimuthGeo")
.HasColumnType("double precision")
.HasColumnName("azimuth_geo")
.HasComment("Азимут Географ.");
b.Property<double>("AzimuthMagnetic")
.HasColumnType("double precision")
.HasColumnName("azimuth_magnetic")
.HasComment("Азимут Магнитный");
b.Property<string>("Comment")
.HasColumnType("text")
.HasColumnName("comment")
.HasComment("Комментарии");
b.Property<int>("IdUser")
.HasColumnType("integer")
.HasColumnName("id_user")
.HasComment("ID пользователя который внес/изменил запись");
b.Property<int>("IdWell")
.HasColumnType("integer")
.HasColumnName("id_well")
.HasComment("ID скважины");
b.Property<DateTimeOffset>("UpdateDate")
.HasColumnType("timestamp with time zone")
.HasColumnName("update_date")
.HasComment("Дата загрузки траектории");
b.Property<double>("VerticalDepth")
.HasColumnType("double precision")
.HasColumnName("vertical_depth")
.HasComment("Глубина вертикальная");
b.Property<double>("WellboreDepth")
.HasColumnType("double precision")
.HasColumnName("wellbore_depth")
.HasComment("Глубина по стволу");
b.Property<double>("ZenithAngle")
.HasColumnType("double precision")
.HasColumnName("zenith_angle")
.HasComment("Угол зенитный");
b.HasKey("Id");
b.HasIndex("IdUser");
b.HasIndex("IdWell");
b.ToTable("t_trajectory_fact");
b.HasComment("Загрузка фактической траектории");
});
modelBuilder.Entity("AsbCloudDb.Model.Trajectory.TrajectoryPlan", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasColumnName("id");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<double>("AzimuthGeo")
.HasColumnType("double precision")
.HasColumnName("azimuth_geo")
.HasComment("Азимут Географ.");
b.Property<double>("AzimuthMagnetic")
.HasColumnType("double precision")
.HasColumnName("azimuth_magnetic")
.HasComment("Азимут Магнитный");
b.Property<string>("Comment")
.HasColumnType("text")
.HasColumnName("comment")
.HasComment("Комментарии");
b.Property<int>("IdUser")
.HasColumnType("integer")
.HasColumnName("id_user")
.HasComment("ID пользователя который внес/изменил запись");
b.Property<int>("IdWell")
.HasColumnType("integer")
.HasColumnName("id_well")
.HasComment("ID скважины");
b.Property<double?>("Radius")
.HasColumnType("double precision")
.HasColumnName("radius")
.HasComment("Радиус цели");
b.Property<DateTimeOffset>("UpdateDate")
.HasColumnType("timestamp with time zone")
.HasColumnName("update_date")
.HasComment("Дата загрузки траектории");
b.Property<double>("VerticalDepth")
.HasColumnType("double precision")
.HasColumnName("vertical_depth")
.HasComment("Глубина вертикальная");
b.Property<double>("WellboreDepth")
.HasColumnType("double precision")
.HasColumnName("wellbore_depth")
.HasComment("Глубина по стволу");
b.Property<double>("ZenithAngle")
.HasColumnType("double precision")
.HasColumnName("zenith_angle")
.HasComment("Угол зенитный");
b.HasKey("Id");
b.HasIndex("IdUser");
b.HasIndex("IdWell");
b.ToTable("t_trajectory_plan");
b.HasComment("Загрузка плановой траектории");
});
modelBuilder.Entity("AsbCloudDb.Model.User", b =>
{
b.Property<int>("Id")
@ -5986,6 +6051,14 @@ namespace AsbCloudDb.Migrations
Name = "Спуск обсадной колонны"
},
new
{
Id = 4018,
IdParent = 3002,
KeyValueName = "dT",
KeyValueUnits = "мин",
Name = "Крепление"
},
new
{
Id = 4007,
IdParent = 3002,
@ -6872,6 +6945,94 @@ namespace AsbCloudDb.Migrations
KeyValueName = "dT",
KeyValueUnits = "мин",
Name = "Ремонт"
},
new
{
Id = 5102,
IdParent = 4018,
KeyValueName = "dT",
KeyValueUnits = "мин",
Name = "Спуск пакера"
},
new
{
Id = 5103,
IdParent = 4011,
KeyValueName = "dT",
KeyValueUnits = "мин",
Name = "Запись гамма-каратожа"
},
new
{
Id = 5104,
IdParent = 4013,
KeyValueName = "dT",
KeyValueUnits = "мин",
Name = "Шаблонирование спуск БИ"
},
new
{
Id = 5105,
IdParent = 4018,
KeyValueName = "dT",
KeyValueUnits = "мин",
Name = "Сборка клин-отклонителя"
},
new
{
Id = 5106,
IdParent = 4018,
KeyValueName = "dT",
KeyValueUnits = "мин",
Name = "Ориентирование и посадка клина-отклонителя"
},
new
{
Id = 5107,
IdParent = 4018,
KeyValueName = "dT",
KeyValueUnits = "мин",
Name = "Протяжка подъемного патрубка подвески"
},
new
{
Id = 5108,
IdParent = 4018,
KeyValueName = "dT",
KeyValueUnits = "мин",
Name = "Подъем клина-отклонителя"
},
new
{
Id = 5109,
IdParent = 4018,
KeyValueName = "dT",
KeyValueUnits = "мин",
Name = "Стыковка стингера с хвостовиком основного ствола"
},
new
{
Id = 5110,
IdParent = 4018,
KeyValueName = "dT",
KeyValueUnits = "мин",
Name = "Ориентирование и установка стыковочного узла хвостовика"
},
new
{
Id = 5111,
IdParent = 4001,
KeyValueName = "МСП",
KeyValueUnits = "м/ч",
Name = "Бурение с отбором керна"
},
new
{
Id = 5112,
IdParent = 4018,
KeyValueName = "dT",
KeyValueUnits = "мин",
Name = "Работа пакером в обсадной колонне"
});
});
@ -8177,25 +8338,6 @@ namespace AsbCloudDb.Migrations
b.Navigation("Well");
});
modelBuilder.Entity("AsbCloudDb.Model.PlannedTrajectory", b =>
{
b.HasOne("AsbCloudDb.Model.User", "User")
.WithMany()
.HasForeignKey("IdUser")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AsbCloudDb.Model.Well", "Well")
.WithMany()
.HasForeignKey("IdWell")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
b.Navigation("Well");
});
modelBuilder.Entity("AsbCloudDb.Model.ProcessMaps.ProcessMapWellDrilling", b =>
{
b.HasOne("AsbCloudDb.Model.User", "User")
@ -8503,6 +8645,44 @@ namespace AsbCloudDb.Migrations
b.Navigation("Telemetry");
});
modelBuilder.Entity("AsbCloudDb.Model.Trajectory.TrajectoryFact", b =>
{
b.HasOne("AsbCloudDb.Model.User", "User")
.WithMany()
.HasForeignKey("IdUser")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AsbCloudDb.Model.Well", "Well")
.WithMany()
.HasForeignKey("IdWell")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
b.Navigation("Well");
});
modelBuilder.Entity("AsbCloudDb.Model.Trajectory.TrajectoryPlan", b =>
{
b.HasOne("AsbCloudDb.Model.User", "User")
.WithMany()
.HasForeignKey("IdUser")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AsbCloudDb.Model.Well", "Well")
.WithMany()
.HasForeignKey("IdWell")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
b.Navigation("Well");
});
modelBuilder.Entity("AsbCloudDb.Model.User", b =>
{
b.HasOne("AsbCloudDb.Model.Company", "Company")

View File

@ -3,8 +3,10 @@ using AsbCloudDb.Model.Subsystems;
using Microsoft.EntityFrameworkCore;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudDb.Model.DailyReports;
using AsbCloudDb.Model.Manuals;
using AsbCloudDb.Model.ProcessMaps;
using AsbCloudDb.Model.Trajectory;
namespace AsbCloudDb.Model
{
@ -13,10 +15,10 @@ namespace AsbCloudDb.Model
public virtual DbSet<Cluster> Clusters => Set<Cluster>();
public virtual DbSet<Company> Companies => Set<Company>();
public virtual DbSet<CompanyType> CompaniesTypes => Set<CompanyType>();
public virtual DbSet<DailyReport.DailyReport> DailyReports => Set <DailyReport.DailyReport >();
public virtual DbSet<DailyReport> DailyReports => Set <DailyReport>();
public virtual DbSet<Deposit> Deposits => Set<Deposit>();
public virtual DbSet<DetectedOperation> DetectedOperations => Set<DetectedOperation>();
public virtual DbSet<PlannedTrajectory> PlannedTrajectories => Set<PlannedTrajectory>();
public virtual DbSet<TrajectoryPlan> TrajectoriesPlan => Set<TrajectoryPlan>();
public virtual DbSet<ProcessMapWellDrilling> ProcessMapWellDrillings => Set<ProcessMapWellDrilling>();
public virtual DbSet<ProcessMapWellReam> ProcessMapWellReams => Set<ProcessMapWellReam>();
public virtual DbSet<DrillingProgramPart> DrillingProgramParts => Set<DrillingProgramPart>();
@ -59,6 +61,7 @@ namespace AsbCloudDb.Model
public virtual DbSet<LimitingParameter> LimitingParameter => Set<LimitingParameter>();
public virtual DbSet<TelemetryWirelineRunOut> TelemetryWirelineRunOut => Set<TelemetryWirelineRunOut>();
public virtual DbSet<TrajectoryFact> TrajectoriesFact => Set<TrajectoryFact>();
// GTR WITS
public DbSet<WitsItemFloat> WitsItemFloat => Set<WitsItemFloat>();
@ -331,11 +334,18 @@ namespace AsbCloudDb.Model
.IsRequired();
});
modelBuilder.Entity<DailyReport.DailyReport >(entity =>
modelBuilder.Entity<DailyReport>(entity =>
{
entity.HasKey(e => new { e.IdWell, e.StartDate })
.HasName("t_id_well_date_start_pk");
entity.Property(e => e.Info)
entity.HasIndex(e => new { e.IdWell, e.Date })
.IsUnique();
entity.Property(e => e.SubsystemBlock)
.HasJsonConversion();
entity.Property(e => e.SignBlock)
.HasJsonConversion();
entity.Property(e => e.TimeBalanceBlock)
.HasJsonConversion();
});

View File

@ -1,61 +0,0 @@
namespace AsbCloudDb.Model.DailyReport
{
public class Bha : ItemInfo
{
/// <summary>
/// КНБК описание
/// </summary>
public string BHADescription { get; set; } = string.Empty;
/// <summary>
/// Бурение с наращиваниями в инт. 2195-2763м. Время начала
/// </summary>
public string ExtensionDrillingOneBegin { get; set; } = string.Empty;
/// <summary>
/// Бурение с наращиваниями в инт. 2195-2763м. Время окончания
/// </summary>
public string ExtensionDrillingOneFinish { get; set; } = string.Empty;
/// <summary>
/// Промывка. Время начала
/// </summary>
public string SluiceBegin { get; set; } = string.Empty;
/// <summary>
/// Промывка. Время окончания
/// </summary>
public string SluiceFinish { get; set; } = string.Empty;
/// <summary>
/// Подьем КНБК. Время начала
/// </summary>
public string ClimbBegin { get; set; } = string.Empty;
/// <summary>
/// Подьем КНБК. Время окончания
/// </summary>
public string ClimbFinish { get; set; } = string.Empty;
/// <summary>
/// Спуск КНБК. Время начала
/// </summary>
public string DescentBegin { get; set; } = string.Empty;
/// <summary>
/// Спуск КНБК. Время окончания
/// </summary>
public string DescentFinish { get; set; } = string.Empty;
/// <summary>
/// Бурение с наращиваниями в инт. 2763-2850м. Время начала
/// </summary>
public string ExtensionDrillingTwoBegin { get; set; } = string.Empty;
/// <summary>
/// Бурение с наращиваниями в инт. 2763-2850м. Время окончания
/// </summary>
public string ExtensionDrillingTwoFinish { get; set; } = string.Empty;
}
}

View File

@ -1,22 +0,0 @@
using Microsoft.EntityFrameworkCore;
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace AsbCloudDb.Model.DailyReport
{
[Table("t_daily_report"), Comment("Ежедневные отчёты")]
public class DailyReport
{
[Column("id_well"), Comment("ID скважины")]
public int IdWell { get; set; }
[Column("start_date", TypeName = "date"), Comment("Дата отчёта")]
public DateOnly StartDate { get; set; }
[Column("info", TypeName = "jsonb"), Comment("Список параметров для отчёта")]
public DailyReportInfo Info { get; set; } = null!;
[ForeignKey(nameof(IdWell))]
public virtual Well Well { get; set; } = null!;
}
}

View File

@ -1,13 +0,0 @@
using AsbCloudDb.Model.DailyReport;
namespace AsbCloudDb.Model
{
public class DailyReportInfo
{
public Head Head { get; set; } = null!;
public Bha Bha { get; set; } = new();
public NoDrilling NoDrilling { get; set; } = new();
public Saub Saub { get; set; } = new();
public Sign Sign { get; set; } = new();
}
}

View File

@ -1,110 +0,0 @@
using System;
using System.Text.Json.Serialization;
namespace AsbCloudDb.Model.DailyReport
{
public class Head : ItemInfo
{
/// <summary>
/// название скважины
/// </summary>
public string WellName { get; set; } = string.Empty;
/// <summary>
/// название куста
/// </summary>
public string ClusterName { get; set; } = string.Empty;
/// <summary>
/// заказчик
/// </summary>
public string Customer { get; set; } = string.Empty;
/// <summary>
/// подрядчик
/// </summary>
public string Contractor { get; set; } = string.Empty;
/// <summary>
/// дата рапорта
/// </summary>
[JsonConverter(typeof(DateOnlyJsonConverter))]
public DateOnly ReportDate { get; set; }
/// <summary>
/// глубина забоя на дату начала интервала
/// </summary>
public double? WellDepthIntervalStartDate { get; set; }
/// <summary>
/// глубина забоя на дату окончания интервала
/// </summary>
public double? WellDepthIntervalFinishDate { get; set; }
/// <summary>
/// Глубина забоя по стволу на окончание отчетного периода
/// </summary>
public double? BottomholeDepth { get; set; }
/// <summary>
/// Глубина забоя по вертикали на дату окончания отчетного периода
/// </summary>
public double? VerticalDepth { get; set; }
/// <summary>
/// Зенитный угол на дату окончания отчетного периода
/// </summary>
public double? ZenithAngle { get; set; }
/// <summary>
/// Азимутальный угол на дату окончания отчетного периода
/// </summary>
public double? AzimuthAngle { get; set; }
/// <summary>
/// ФИО бурильщиков
/// </summary>
public string FirstDriller { get; set; } = string.Empty;
/// <summary>
/// ФИО бурильщиков
/// </summary>
public string SecondDriller { get; set; } = string.Empty;
/// <summary>
/// Время работы АПД
/// </summary>
public double? WorkTimeSAUB { get; set; }
/// <summary>
/// Время работы спин мастер
/// </summary>
public double? WorkTimeSpinMaster { get; set; }
/// <summary>
/// Время работы torqueMaster
/// </summary>
public double? WorkTimeTorkMaster { get; set; }
/// <summary>
/// количество метров пробуренных с включенным АПД
/// </summary>
public double? PenetrationSAUB { get; set; }
/// <summary>
/// количество метров пробуренных с включенным Спин мастер
/// </summary>
public double? PenetrationSpinMaster { get; set; }
/// <summary>
/// количество метров пробуренных с включенным torqueMaster
/// </summary>
public double? PenetrationTorkMaster { get; set; }
/// <summary>
/// Количество запусков МСЕ
/// </summary>
public int CountLaunchesMSE { get; set; }
}
}

View File

@ -1,26 +0,0 @@
namespace AsbCloudDb.Model.DailyReport
{
public class NoDrilling : ItemInfo
{
/// <summary>
/// Нормативное время на одну операцию по подготовке ствола скважины к наращиванию
/// </summary>
public double? StandardTimeBarrelPreparation { get; set; }
/// <summary>
/// Нормативное время на одну операцию по наращиванию
/// </summary>
public double? StandardTimeExtension { get; set; }
/// <summary>
/// Фактическое время проработок при подготовке ствола скважины к наращиванию.
/// </summary>
public double? ActualTimeBarrelPreparation { get; set; }
/// <summary>
/// Фактическое время наращиваний
/// </summary>
public double? ActualTimeExtension { get; set; }
}
}

View File

@ -1,101 +0,0 @@
namespace AsbCloudDb.Model.DailyReport
{
public class Saub : ItemInfo
{
/// <summary>
/// Режимы бурения в роторе
/// </summary>
public string? RotorDrillingModes { get; set; }
/// <summary>
/// режимы бурения в слайде
/// </summary>
public string? SlideDrillingModes { get; set; }
/// <summary>
/// Количество метров пробуренных в роторе за отчетный период
/// </summary>
public double? PenetrationInRotor { get; set; }
/// <summary>
/// Количество часов бурения в роторе за отчетный период
/// </summary>
public double? NumberDrillingHours { get; set; }
/// <summary>
/// средний диф перепад в роторе за отчетный период
/// </summary>
public double? AVGDiffDropRotor { get; set; }
/// <summary>
/// количество метров пробуренных в слайде за отчетный период
/// </summary>
public double? PenetrationInSlide { get; set; }
/// <summary>
/// время бурения в роторе за отчетный период
/// </summary>
public double? DrillingTimeInRotor { get; set; }
/// <summary>
/// средний диф. перепад в слайде за отчетный период
/// </summary>
public double? AVGDiffPressureSlide { get; set; }
/// <summary>
/// Плановая МСП за секцию
/// </summary>
public double? SectionROPPlan { get; set; }
/// <summary>
/// Общее время бурения за секцию
/// </summary>
public double? SectionDrillingTimeTotal { get; set; }
/// <summary>
/// Общая проходка за секцию
/// </summary>
public double? SectionPenetrationTotal { get; set; }
/// <summary>
/// Количество наращиваний за отчетный период
/// </summary>
public int ExtensionsCount { get; set; }
/// <summary>
/// Отклонение относительно ГГД
/// </summary>
public double? DeviationFromTVD { get; set; }
/// <summary>
/// указываются все причины, которые влияют на снижение МСП.
/// </summary>
public string DeclinesReasonsROP { get; set; } = string.Empty;
/// <summary>
/// Увеличение мех скорости за секцию %
/// </summary>
public string IncreaseSpeedSection { get; set; } = string.Empty;
/// <summary>
/// Увеличение мех скорости за сутки %
/// </summary>
public string IncreaseSpeedDay { get; set; } = string.Empty;
/// <summary>
/// Сокращение времени бурения за секцию, ч
/// </summary>
public string ReductionTimeDrilling { get; set; } = string.Empty;
/// <summary>
/// Ротор/Слайд %
/// </summary>
public string RotorSlidePercent { get; set; } = string.Empty;
/// <summary>
/// МСП
/// </summary>
public string MspSection { get; set; } = string.Empty;
}
}

View File

@ -1,16 +0,0 @@
namespace AsbCloudDb.Model.DailyReport
{
public class Sign : ItemInfo
{
/// <summary>
/// ФИО Мастера буровой
/// </summary>
public string DrillingMaster { get; set; } = string.Empty;
/// <summary>
/// ФИО супервайзера
/// </summary>
public string Supervisor { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,8 @@
namespace AsbCloudDb.Model.DailyReports.Blocks.Sign;
public class SignBlock : ItemInfo
{
public SignRecord? DrillingMaster { get; set; }
public SignRecord? Supervisor { get; set; }
}

View File

@ -0,0 +1,10 @@
namespace AsbCloudDb.Model.DailyReports.Blocks.Sign;
public class SignRecord
{
public string Name { get; set; } = null!;
public string Surname { get; set; } = null!;
public string? Patronymic { get; set; }
}

View File

@ -0,0 +1,18 @@
using System.Collections.Generic;
namespace AsbCloudDb.Model.DailyReports.Blocks.Subsystem;
public class SubsystemBlock : ItemInfo
{
public double? Wellbore { get; set; }
public double? MeasurementsPerDay { get; set; }
public double? TvgLagDays { get; set; }
public double? TotalRopPlan { get; set; }
public string? Comment { get; set; }
public IEnumerable<SubsystemRecord>? Subsystems { get; set; }
}

View File

@ -0,0 +1,10 @@
namespace AsbCloudDb.Model.DailyReports.Blocks.Subsystem;
public class SubsystemParameters
{
public double? SumDepthInterval { get; set; }
public double? UsedTimeHours { get; set; }
public double? KUsage { get; set; }
}

View File

@ -0,0 +1,10 @@
namespace AsbCloudDb.Model.DailyReports.Blocks.Subsystem;
public class SubsystemRecord
{
public string Name { get; set; } = null!;
public SubsystemParameters? UsagePerDay { get; set; }
public SubsystemParameters? UsagePerWell { get; set; }
}

View File

@ -0,0 +1,18 @@
using System.Collections.Generic;
namespace AsbCloudDb.Model.DailyReports.Blocks.TimeBalance;
public class TimeBalanceBlock : ItemInfo
{
public int IdSection { get; set; }
public string? SectionName { get; set; }
public double? WellDepthPlan { get; set; }
public double WellDepthFact { get; set; }
public double? WellOperationSlipsTimeCount { get; set; }
public IEnumerable<TimeBalanceRecord>? WellOperations { get; set; }
}

View File

@ -0,0 +1,16 @@
namespace AsbCloudDb.Model.DailyReports.Blocks.TimeBalance;
public class TimeBalanceRecord
{
public int IdWellOperation { get; set; }
public double? DurationHoursPlan { get; set; }
public double? DurationHoursFact { get; set; }
public double? DrillingDeviationPerSection { get; set; }
public double? DrillingDeviationPerDay { get; set; }
public string? ReasonDeviation { get; set; }
}

View File

@ -0,0 +1,37 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using AsbCloudDb.Model.DailyReports.Blocks.Sign;
using AsbCloudDb.Model.DailyReports.Blocks.Subsystem;
using AsbCloudDb.Model.DailyReports.Blocks.TimeBalance;
using Microsoft.EntityFrameworkCore;
namespace AsbCloudDb.Model.DailyReports;
[Table("t_daily_report"), Comment("Ежедневные отчёты")]
public class DailyReport : IId
{
[Key]
public int Id { get; set; }
[Column("id_well"), Comment("ID скважины")]
public int IdWell { get; set; }
[Column("date_last_update", TypeName = "timestamp with time zone"), Comment("Дата последнего обновления")]
public DateTime? DateLastUpdate { get; set; }
[Column("date", TypeName = "timestamp with time zone"), Comment("Дата формирования отчёта")]
public DateTime Date { get; set; }
[Column("sign_block", TypeName = "jsonb"), Comment("Подпись")]
public SignBlock? SignBlock { get; set; }
[Column("time_balance_block", TypeName = "jsonb"), Comment("Баланс времени")]
public TimeBalanceBlock? TimeBalanceBlock { get; set; }
[Column("subsystem_block", TypeName = "jsonb"), Comment("Наработкой подсистем")]
public SubsystemBlock? SubsystemBlock { get; set; }
[ForeignKey(nameof(IdWell))]
public virtual Well Well { get; set; } = null!;
}

View File

@ -160,9 +160,7 @@
new (){ Id = 526, Name = "WellOperation.editCompletedWell", Description = "Разрешение на редактирование операций у завершенной скважины"},
new() { Id = 527, Name = "Manual.delete", Description = "Разрешение на удаление инструкций"},
new (){ Id = 528, Name="WellContact.delete", Description="Разрешение на удаление контакта"},
new (){ Id = 529, Name="DrillTestReport.get", Description="Разрешение на получение отчетов drill test"},
new (){ Id = 528, Name="WellContact.delete", Description="Разрешение на удаление контакта"}
};
}
}

View File

@ -7,8 +7,10 @@ using Microsoft.EntityFrameworkCore.Infrastructure;
using System;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudDb.Model.DailyReports;
using AsbCloudDb.Model.Manuals;
using AsbCloudDb.Model.ProcessMaps;
using AsbCloudDb.Model.Trajectory;
namespace AsbCloudDb.Model
{
@ -17,10 +19,10 @@ namespace AsbCloudDb.Model
DbSet<Cluster> Clusters { get; }
DbSet<Company> Companies { get; }
DbSet<CompanyType> CompaniesTypes { get; }
DbSet<DailyReport.DailyReport> DailyReports { get; }
DbSet<DailyReport> DailyReports { get; }
DbSet<Deposit> Deposits { get; }
DbSet<DetectedOperation> DetectedOperations { get; }
DbSet<PlannedTrajectory> PlannedTrajectories { get; }
DbSet<TrajectoryPlan> TrajectoriesPlan { get; }
DbSet<ProcessMapWellDrilling> ProcessMapWellDrillings { get; }
DbSet<ProcessMapWellReam> ProcessMapWellReams { get; }
DbSet<DrillingProgramPart> DrillingProgramParts { get; }
@ -77,6 +79,7 @@ namespace AsbCloudDb.Model
DbSet<ManualDirectory> ManualDirectories { get; }
DbSet<Contact> Contacts { get; }
DbSet<DrillTest> DrillTests { get; }
DbSet<TrajectoryFact> TrajectoriesFact { get; }
DatabaseFacade Database { get; }
Task<int> RefreshMaterializedViewAsync(string mwName, CancellationToken token);

View File

@ -3,10 +3,9 @@ using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace AsbCloudDb.Model
namespace AsbCloudDb.Model.Trajectory
{
[Table("t_planned_trajectory"), Comment("Загрузка плановой траектории")]
public class PlannedTrajectory : IId, IWellRelated
public abstract class Trajectory : IId, IWellRelated
{
[Column("id"), Key]
public int Id { get; set; }
@ -38,9 +37,6 @@ namespace AsbCloudDb.Model
[Column("comment"), Comment("Комментарии")]
public string? Comment { get; set; }
[Column("radius"), Comment("Радиус цели")]
public double? Radius { get; set; }
[ForeignKey(nameof(IdWell))]
public virtual Well Well { get; set; } = null!;

View File

@ -0,0 +1,10 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;
namespace AsbCloudDb.Model.Trajectory
{
[Table("t_trajectory_fact"), Comment("Загрузка фактической траектории")]
public class TrajectoryFact : Trajectory
{
}
}

View File

@ -0,0 +1,12 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;
namespace AsbCloudDb.Model.Trajectory
{
[Table("t_trajectory_plan"), Comment("Загрузка плановой траектории")]
public class TrajectoryPlan : Trajectory
{
[Column("radius"), Comment("Радиус цели")]
public double? Radius { get; set; }
}
}

View File

@ -253,6 +253,7 @@ namespace AsbCloudDb.Model
new () {Id = IdBuilding, IdParent = 3000, Name = "Наращивание", KeyValueName = "dT", KeyValueUnits = "мин" },
new () {Id = IdSPO , IdParent = 3001, Name = "СПО", KeyValueName = "dT", KeyValueUnits = "мин" },
new () {Id = IdCasingRunning, IdParent = 3002, Name = "Спуск обсадной колонны", KeyValueName = "dT", KeyValueUnits = "мин" },
new () {Id = 4018, IdParent = 3002, Name = "Крепление", KeyValueName = "dT", KeyValueUnits = "мин"},
new () {Id = IdCementing, IdParent = 3002, Name = "Цементирование", KeyValueName = "dT", KeyValueUnits = "мин" },
new () {Id = IdAuxiliaryWorkFastening, IdParent = 3002, Name = "Вспомогательные работы при креплении", KeyValueName = "dT", KeyValueUnits = "мин" },
new () {Id = IdAssemblyOrDisassemblyGIS, IdParent = 3003, Name = "Сборка/разборка приборов ГИС", KeyValueName = "dT", KeyValueUnits = "мин" },
@ -370,6 +371,17 @@ namespace AsbCloudDb.Model
new () {Id = 5099, IdParent = 4013, Name = "Подготовка ствола скважины. Перезапись ГК в интервале установки КО.", KeyValueName = "dT", KeyValueUnits = "мин" },
new () {Id = 5100, IdParent = 4013, Name = "Смена рабочего переводника ВСП", KeyValueName = "dT", KeyValueUnits = "мин" },
new () {Id = 5101, IdParent = 4014, Name = "Ремонт", KeyValueName = "dT", KeyValueUnits = "мин" },
new () {Id = 5102, IdParent = 4018, Name = "Спуск пакера", KeyValueName = "dT", KeyValueUnits = "мин"},
new () {Id = 5103, IdParent = 4011, Name = "Запись гамма-каратожа", KeyValueName = "dT", KeyValueUnits = "мин"},
new () {Id = 5104, IdParent = 4013, Name = "Шаблонирование спуск БИ", KeyValueName = "dT", KeyValueUnits = "мин"},
new () {Id = 5105, IdParent = 4018, Name = "Сборка клин-отклонителя", KeyValueName = "dT", KeyValueUnits = "мин"},
new () {Id = 5106, IdParent = 4018, Name = "Ориентирование и посадка клина-отклонителя", KeyValueName = "dT", KeyValueUnits = "мин"},
new () {Id = 5107, IdParent = 4018, Name = "Протяжка подъемного патрубка подвески", KeyValueName = "dT", KeyValueUnits = "мин"},
new () {Id = 5108, IdParent = 4018, Name = "Подъем клина-отклонителя", KeyValueName = "dT", KeyValueUnits = "мин"},
new () {Id = 5109, IdParent = 4018, Name = "Стыковка стингера с хвостовиком основного ствола", KeyValueName = "dT", KeyValueUnits = "мин"},
new () {Id = 5110, IdParent = 4018, Name = "Ориентирование и установка стыковочного узла хвостовика", KeyValueName = "dT", KeyValueUnits = "мин"},
new () {Id = 5111, IdParent = 4001, Name = "Бурение с отбором керна", KeyValueName = "МСП", KeyValueUnits = "м/ч"},
new () {Id = 5112, IdParent = 4018, Name = "Работа пакером в обсадной колонне", KeyValueName = "dT", KeyValueUnits = "мин"}
};
#endregion

View File

@ -15,7 +15,7 @@ sudo nano postgresql.conf
2. В postgres.conf найти запись listen_addresses и добавить туда ip standby-сервера
> listen_addresses = '*, <ip standby-сервера>'
> listen_addresses = 'localhost, <ip standby-сервера>'
3. Открыть клиент для работы с postgres
@ -75,7 +75,7 @@ sudo nano pg_hba.conf
5. Используя утилиту basebackup создать базовую резервную копию с правами владения postgres (либо любого пользователя с соответствующими разрешениями).
```
pg_basebackup -h <ip primary-сервера> -D /var/lib/postgresql/14/main/ -U replicator -P -v -R -X stream -C -S slaveslot1
pg_basebackup -h <ip primary-сервера> -D /var/lib/postgresql/15/main/ -U replicator -P -v -R -X stream -C -S slaveslot1
где: /var/lib/postgresql/15/main/ - каталог replica-сервера
```
@ -133,12 +133,12 @@ sudo -u postgres psql
1. Установить на primary-сервер pgpool2 и postgresql-14-pgpool2
```
apt-get -y install pgpool2 postgresql-15-pgpool2
apt -y install pgpool2 postgresql-15-pgpool2
```
2. Установить на standby-сервер только postgresql-14-pgpool2
```
apt-get -y install postgresql-15-pgpool2
apt -y install postgresql-15-pgpool2
```
### Далее все настройки выполнить на primary-сервере
3. Зайти на редактирование в конфигурационный файл pgpool2
@ -154,11 +154,12 @@ apt-get -y install postgresql-15-pgpool2
backend_hostname0 = '<ip primary-сервера>'
backend_port0 = '<порт primary-сервера>'
backend_weight0 = 0
backend_data_directory0 = '/var/lib/postgresql/14/main'
backend_data_directory0 = '/var/lib/postgresql/15/main'
___
backend_hostname1 = '<ip replica-сервера>'
backend_port1 = '<порт primary-сервера>'
backend_port1 = '<порт replica-сервера>'
backend_weight1 = 1
___
enable_pool_hba = on
log_statement = on

View File

@ -14,7 +14,10 @@
<None Remove="CommonLibs\Readme.md" />
<None Remove="Services\DailyReport\DailyReportTemplate.xlsx" />
<None Remove="Services\DrillTestReport\DrillTestReportTemplate.xlsx" />
<None Remove="Services\Trajectory\FactTrajectoryTemplate.xlsx" />
<None Remove="Services\Trajectory\NnbTrajectoryTemplate.xlsx" />
<None Remove="Services\Trajectory\PlannedTrajectoryTemplate.xlsx" />
<None Remove="Services\Trajectory\Templates\TrajectoryFactNnbTemplate.xlsx" />
<None Remove="Services\WellOperationService\ScheduleReportTemplate.xlsx" />
<None Remove="Services\WellOperationService\WellOperationImportTemplate.xlsx" />
<None Remove="Services\DailyReport\DailyReportBlocks\" />
@ -33,9 +36,10 @@
<EmbeddedResource Include="Services\DetectOperations\DetectOperations.xlsx" />
<EmbeddedResource Include="Services\DailyReport\DailyReportTemplate.xlsx" />
<EmbeddedResource Include="Services\DrillTestReport\DrillTestReportTemplate.xlsx" />
<EmbeddedResource Include="Services\Trajectory\PlannedTrajectoryTemplate.xlsx" />
<EmbeddedResource Include="Services\Trajectory\Templates\TrajectoryFactNnbTemplate.xlsx" />
<EmbeddedResource Include="Services\Trajectory\Templates\TrajectoryFactManualTemplate.xlsx" />
<EmbeddedResource Include="Services\Trajectory\Templates\TrajectoryPlanTemplate.xlsx" />
<EmbeddedResource Include="Services\WellOperationService\ScheduleReportTemplate.xlsx" />
<EmbeddedResource Include="Services\AutoGeneratedDailyReports\AutogeneratedDailyReportTemplate.xlsx" />
<EmbeddedResource Include="Services\WellOperationImport\Files\WellOperationImportTemplate.xlsx" />
<EmbeddedResource Include="Services\WellOperationImport\Files\Dictionaries\Operations.txt" />
<EmbeddedResource Include="Services\WellOperationImport\Files\Dictionaries\Sections.txt" />
@ -62,10 +66,6 @@
<ProjectReference Include="..\AsbCloudDb\AsbCloudDb.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Services\DailyReport\DailyReportBlocks\" />
</ItemGroup>
<ItemGroup>
<Reference Include="AsbWitsInfo">
<HintPath>CommonLibs\AsbWitsInfo.dll</HintPath>

View File

@ -31,6 +31,7 @@ public class BackgroundWorker : BackgroundService
/// Работа выполняемая в данный момент
/// </summary>
public Work? CurrentWork;
private bool isRuning;
/// <summary>
/// последние 16 завершившиеся с ошибкой
@ -54,6 +55,9 @@ public class BackgroundWorker : BackgroundService
protected override async Task ExecuteAsync(CancellationToken token)
{
if (isRuning)
return;
isRuning = true;
Trace.TraceInformation($"{GetType().Name} started");
while (!token.IsCancellationRequested && works.TryDequeue(out CurrentWork))
{
@ -82,6 +86,7 @@ public class BackgroundWorker : BackgroundService
Trace.TraceError(MainLoopLastException);
}
}
isRuning = false;
}
/// <summary>
@ -96,7 +101,7 @@ public class BackgroundWorker : BackgroundService
{
works.Enqueue(work);
if (ExecuteTask is null || ExecuteTask.IsCompleted)
StartAsync(CancellationToken.None).Wait();
StartAsync(CancellationToken.None);
}
/// <summary>

View File

@ -17,8 +17,8 @@ public class PeriodicBackgroundWorker : BackgroundService
private readonly TimeSpan executePeriod = TimeSpan.FromSeconds(10);
private readonly TimeSpan minDelay = TimeSpan.FromSeconds(1);
private readonly IServiceProvider serviceProvider;
private readonly List<WorkPeriodic> works = new(8);
private bool isRuning = false;
/// <summary>
/// Список периодических работ
@ -42,6 +42,9 @@ public class PeriodicBackgroundWorker : BackgroundService
protected override async Task ExecuteAsync(CancellationToken token)
{
if (isRuning)
return;
isRuning = true;
Trace.TraceInformation($"{GetType().Name} started");
while (!token.IsCancellationRequested)
{
@ -74,6 +77,7 @@ public class PeriodicBackgroundWorker : BackgroundService
Trace.TraceError(MainLoopLastException);
}
}
isRuning = false;
}
/// <summary>
@ -99,7 +103,7 @@ public class PeriodicBackgroundWorker : BackgroundService
var periodic = new WorkPeriodic(work, period);
works.Add(periodic);
if (ExecuteTask is null || ExecuteTask.IsCompleted)
StartAsync(CancellationToken.None).Wait();
StartAsync(CancellationToken.None);
}
private WorkPeriodic? GetNext()

View File

@ -9,7 +9,7 @@ using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
namespace AsbCloudInfrastructure.Background;
namespace AsbCloudInfrastructure.Background.PeriodicWorks;
public class WorkLimitingParameterCalc : Work
{

View File

@ -0,0 +1,127 @@
using AsbCloudDb.Model;
using AsbCloudDb.Model.Subsystems;
using AsbCloudInfrastructure.Services.Subsystems;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Background.PeriodicWorks;
public class WorkSubsystemAbfOperationTimeCalc : WorkSubsystemOperationTimeCalcAbstract
{
public WorkSubsystemAbfOperationTimeCalc()
: base("Subsystem automated bit feeding operation time calc")
{
Timeout = TimeSpan.FromMinutes(30);
}
protected override async Task<IEnumerable<SubsystemOperationTime>> OperationTimeAsync(int idTelemetry, DateTimeOffset geDate, IAsbCloudDbContext db, CancellationToken token)
{
static bool isSubsytemAkbRotor(short? mode) => mode == 1;
static bool isSubsytemAkbSlide(short? mode) => mode == 3;
static bool IsSubsystemMse(short? state) => (state & 1) > 0;
var query =
$"select tt.date, tt.mode, tt.well_depth, tt.mse_state " +
$"from ( " +
$" select " +
$" date, " +
$" mode, " +
$" mse_state, " +
$" well_depth, " +
$" lag(mode,1) over (order by date) as mode_lag, " +
$" lead(mode,1) over (order by date) as mode_lead " +
$" from t_telemetry_data_saub " +
$" where id_telemetry = {idTelemetry} and well_depth is not null and well_depth > 0 " +
$" order by date ) as tt " +
$"where (tt.mode_lag is null or (tt.mode != tt.mode_lag and tt.mode_lead != tt.mode_lag)) and tt.date >= '{geDate:u}' " +
$"order by tt.date;";
using var result = await ExecuteReaderAsync(db, query, token);
var subsystemsOperationTimes = new List<SubsystemOperationTime>();
var detectorRotor = new SubsystemDetector(idTelemetry, idSubsystemAPDRotor, isSubsytemAkbRotor, IsValid);
var detectorSlide = new SubsystemDetector(idTelemetry, idSubsystemAPDSlide, isSubsytemAkbSlide, IsValid);
var detectorMse = new SubsystemDetector(idTelemetry, idSubsystemMse, IsSubsystemMse, IsValid);
while (result.Read())
{
var mode = result.GetFieldValue<short?>(1);
var state = result.GetFieldValue<short?>(3);
var isAkbRotorEnable = isSubsytemAkbRotor(mode);
var isAkbSlideEnable = isSubsytemAkbSlide(mode);
var isMseEnable = IsSubsystemMse(state);
var date = result.GetFieldValue<DateTimeOffset>(0);
var depth = result.GetFieldValue<float>(2);
if (detectorRotor.TryDetect(mode, date, depth, out var detectedRotor))
subsystemsOperationTimes.Add(detectedRotor!);
if (detectorSlide.TryDetect(mode, date, depth, out var detectedSlide))
subsystemsOperationTimes.Add(detectedSlide!);
if (detectorMse.TryDetect(mode, date, depth, out var detectedMse))
subsystemsOperationTimes.Add(detectedMse!);
}
return subsystemsOperationTimes;
}
private static async Task<DbDataReader> ExecuteReaderAsync(IAsbCloudDbContext db, string query, CancellationToken token)
{
var connection = db.Database.GetDbConnection();
if (
connection?.State is null ||
connection.State == ConnectionState.Broken ||
connection.State == ConnectionState.Closed)
{
await db.Database.OpenConnectionAsync(token);
connection = db.Database.GetDbConnection();
}
using var command = connection.CreateCommand();
command.CommandText = query;
var result = await command.ExecuteReaderAsync(token);
return result;
}
private static bool IsValid(SubsystemOperationTime item)
{
var validateCode = GetValidateErrorCode(item);
if (validateCode != 0)
{
var str = System.Text.Json.JsonSerializer.Serialize(item);
Trace.TraceWarning($"Wrong({validateCode}) SubsystemOperationTime: {str}");
}
return validateCode == 0;
}
private static int GetValidateErrorCode(SubsystemOperationTime item)
{
if (item.DateStart > item.DateEnd)
return -1;
if ((item.DateEnd - item.DateStart).TotalHours > 48)
return -2;
if (item.DepthEnd < item.DepthStart)
return -3;
if (item.DepthEnd - item.DepthStart > 2000d)
return -4;
if (item.DepthEnd < 0d)
return -5;
if (item.DepthStart < 0d)
return -6;
if (item.DepthEnd > 24_0000d)
return -7;
if (item.DepthStart > 24_0000d)
return -8;
return 0;
}
}

View File

@ -0,0 +1,102 @@
using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Repositories;
using AsbCloudDb.Model;
using AsbCloudDb.Model.Subsystems;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Background.PeriodicWorks;
public abstract class WorkSubsystemOperationTimeCalcAbstract : Work
{
protected const int idSubsystemTorqueMaster = 65537;
protected const int idSubsystemSpinMaster = 65536;
protected const int idSubsystemAPDRotor = 11;
protected const int idSubsystemAPDSlide = 12;
protected const int idSubsystemMse = 2;
private static TimeSpan obsoleteTime = TimeSpan.FromDays(365 * 100);
public WorkSubsystemOperationTimeCalcAbstract(string workId)
: base(workId)
{
Timeout = TimeSpan.FromMinutes(30);
}
protected override async Task Action(string id, IServiceProvider services, Action<string, double?> onProgressCallback, CancellationToken token)
{
var db = services.GetRequiredService<IAsbCloudDbContext>();
db.Database.SetCommandTimeout(TimeSpan.FromMinutes(5));
var telemetryLastDetectedDates = await GetTelemetryLastDetectedDates(services, db, token);
var count = telemetryLastDetectedDates.Count();
var i = 0d;
foreach (var item in telemetryLastDetectedDates)
{
onProgressCallback($"Start handling telemetry: {item.IdTelemetry} from {item.DateDetectedLast}", i++ / count);
var newOperationsSaub = await OperationTimeAsync(item.IdTelemetry, item.DateDetectedLast, db, token);
if (newOperationsSaub.Any())
{
db.SubsystemOperationTimes.AddRange(newOperationsSaub);
await db.SaveChangesAsync(token);
}
}
obsoleteTime = TimeSpan.FromDays(3);
}
protected abstract Task<IEnumerable<SubsystemOperationTime>> OperationTimeAsync(int idTelemetry, DateTimeOffset geDate, IAsbCloudDbContext db, CancellationToken token);
private static async Task<IEnumerable<TelemetryDateLast>> GetTelemetryLastDetectedDates(IServiceProvider services, IAsbCloudDbContext db, CancellationToken token)
{
var telemetryDataCache = services.GetRequiredService<ITelemetryDataCache<TelemetryDataSaubDto>>();
var updatingTelemetries = telemetryDataCache.GetStat()
.Where(tstat => (DateTimeOffset.Now - tstat.DateLast) < obsoleteTime);
var telemetryIds = updatingTelemetries
.Select(t => t.IdTelemetry)
.ToArray();
IEnumerable<TelemetryDateLast> lastDetectedDates = await GetLastSubsystemOperationTimeAsync(db, token);
lastDetectedDates = lastDetectedDates
.Where(s => telemetryIds.Contains(s.IdTelemetry));
var result = updatingTelemetries.Select(tstat => new TelemetryDateLast
{
IdTelemetry = tstat.IdTelemetry,
DateDetectedLast = lastDetectedDates.FirstOrDefault(ldd => ldd.IdTelemetry == tstat.IdTelemetry)?.DateDetectedLast
?? DateTimeOffset.UnixEpoch,
DateTelemetryLast = tstat.DateLast
});
return result;
}
private static async Task<IEnumerable<TelemetryDateLast>> GetLastSubsystemOperationTimeAsync(IAsbCloudDbContext db, CancellationToken token)
{
var result = await db.SubsystemOperationTimes
.GroupBy(o => o.IdTelemetry)
.Select(g => new TelemetryDateLast
{
IdTelemetry = g.Key,
DateDetectedLast = g.Max(o => o.DateEnd)
})
.ToArrayAsync(token);
return result;
}
protected class TelemetryDateLast
{
public int IdTelemetry { get; set; }
public DateTimeOffset DateDetectedLast { get; set; }
public DateTimeOffset DateTelemetryLast { get; internal set; }
}
}

View File

@ -1,6 +1,7 @@
using AsbCloudDb.Model;
using AsbCloudDb.Model.Subsystems;
using AsbCloudInfrastructure.Background;
using AsbCloudInfrastructure.Services.Subsystems;
using AsbCloudInfrastructure.Services.Subsystems.Utils;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
@ -13,155 +14,26 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services.Subsystems;
namespace AsbCloudInfrastructure.Background.PeriodicWorks;
public class WorkSubsystemOperationTimeCalc : Work
public class WorkSubsystemOscillationOperationTimeCalc : WorkSubsystemOperationTimeCalcAbstract
{
private const int idSubsytemTorqueMaster = 65537;
private const int idSubsytemSpinMaster = 65536;
private const int idSubsystemAPDRotor = 11;
private const int idSubsystemAPDSlide = 12;
private const int idSubsytemMse = 2;
public WorkSubsystemOperationTimeCalc()
public WorkSubsystemOscillationOperationTimeCalc()
: base("Subsystem operation time calc")
{
Timeout = TimeSpan.FromMinutes(30);
}
protected override async Task Action(string id, IServiceProvider services, Action<string, double?> onProgressCallback, CancellationToken token)
{
using var db = services.GetRequiredService<IAsbCloudDbContext>();
db.Database.SetCommandTimeout(TimeSpan.FromMinutes(5));
var lastDetectedDates = await db.SubsystemOperationTimes
.GroupBy(o => o.IdTelemetry)
.Select(g => new
{
IdTelemetry = g.Key,
LastDate = g.Max(o => o.DateEnd)
})
.ToListAsync(token);
var telemetryIds = await db.Telemetries
.Where(t => t.Info != null && t.TimeZone != null)
.Select(t => t.Id)
.ToListAsync(token);
var telemetryLastDetectedDates = telemetryIds
.GroupJoin(lastDetectedDates,
t => t,
o => o.IdTelemetry,
(outer, inner) => new
{
IdTelemetry = outer,
inner.SingleOrDefault()?.LastDate,
})
.OrderByDescending(i => i.IdTelemetry);
var count = telemetryLastDetectedDates.Count();
var i = 0d;
foreach (var item in telemetryLastDetectedDates)
{
onProgressCallback($"Start handling telemetry: {item.IdTelemetry} from {item.LastDate}", i++ / count);
var newOperationsSaub = await OperationTimeSaubAsync(item.IdTelemetry, item.LastDate ?? DateTimeOffset.MinValue, db, token);
if (newOperationsSaub?.Any() == true)
{
db.SubsystemOperationTimes.AddRange(newOperationsSaub);
await db.SaveChangesAsync(token);
}
var newOperationsSpin = await OperationTimeSpinAsync(item.IdTelemetry, item.LastDate ?? DateTimeOffset.MinValue, db, token);
if (newOperationsSpin?.Any() == true)
{
db.SubsystemOperationTimes.AddRange(newOperationsSpin);
await db.SaveChangesAsync(token);
}
}
}
private static async Task<DbDataReader> ExecuteReaderAsync(IAsbCloudDbContext db, string query, CancellationToken token)
{
var connection = db.Database.GetDbConnection();
if (
connection?.State is null ||
connection.State == ConnectionState.Broken ||
connection.State == ConnectionState.Closed)
{
await db.Database.OpenConnectionAsync(token);
connection = db.Database.GetDbConnection();
}
using var command = connection.CreateCommand();
command.CommandText = query;
var result = await command.ExecuteReaderAsync(token);
return result;
}
private static async Task<IEnumerable<SubsystemOperationTime>> OperationTimeSaubAsync(int idTelemetry, DateTimeOffset begin, IAsbCloudDbContext db, CancellationToken token)
{
static bool isSubsytemAkbRotor(short? mode) => mode == 1;
static bool isSubsytemAkbSlide(short? mode) => mode == 3;
static bool IsSubsystemMse(short? state) => (state & 1) > 0;
var query =
$"select tt.date, tt.mode, tt.well_depth, tt.mse_state " +
$"from ( " +
$" select " +
$" date, " +
$" mode, " +
$" mse_state, " +
$" well_depth, " +
$" lag(mode,1) over (order by date) as mode_lag, " +
$" lead(mode,1) over (order by date) as mode_lead " +
$" from t_telemetry_data_saub " +
$" where id_telemetry = {idTelemetry} and well_depth is not null and well_depth > 0 " +
$" order by date ) as tt " +
$"where (tt.mode_lag is null or (tt.mode != tt.mode_lag and tt.mode_lead != tt.mode_lag)) and tt.date >= '{begin:u}' " +
$"order by tt.date;";
using var result = await ExecuteReaderAsync(db, query, token);
var subsystemsOperationTimes = new List<SubsystemOperationTime>();
var detectorRotor = new SubsystemDetector(idTelemetry, idSubsystemAPDRotor, isSubsytemAkbRotor, IsValid);
var detectorSlide = new SubsystemDetector(idTelemetry, idSubsystemAPDSlide, isSubsytemAkbSlide, IsValid);
var detectorMse = new SubsystemDetector(idTelemetry, idSubsytemMse, IsSubsystemMse, IsValid);
while (result.Read())
{
var mode = result.GetFieldValue<short?>(1);
var state = result.GetFieldValue<short?>(3);
var isAkbRotorEnable = isSubsytemAkbRotor(mode);
var isAkbSlideEnable = isSubsytemAkbSlide(mode);
var isMseEnable = IsSubsystemMse(state);
var date = result.GetFieldValue<DateTimeOffset>(0);
var depth = result.GetFieldValue<float>(2);
if (detectorRotor.TryDetect(mode, date, depth, out var detectedRotor))
subsystemsOperationTimes.Add(detectedRotor!);
if (detectorSlide.TryDetect(mode, date, depth, out var detectedSlide))
subsystemsOperationTimes.Add(detectedSlide!);
if (detectorMse.TryDetect(mode, date, depth, out var detectedMse))
subsystemsOperationTimes.Add(detectedMse!);
}
return subsystemsOperationTimes;
}
private static async Task<IEnumerable<SubsystemOperationTime>> OperationTimeSpinAsync(int idTelemetry, DateTimeOffset begin, IAsbCloudDbContext db, CancellationToken token)
protected override async Task<IEnumerable<SubsystemOperationTime>> OperationTimeAsync(int idTelemetry, DateTimeOffset geDate, IAsbCloudDbContext db, CancellationToken token)
{
static int? GetSubsytemId(short? mode, int? state)
{
// При изменении следующего кода сообщи в Vladimir.Sobolev@nedra.digital
if (state == 7 && (mode & 2) > 0)
return idSubsytemTorqueMaster;// демпфер
return idSubsystemTorqueMaster;// демпфер
if (state != 0 && state != 5 && state != 6 && state != 7)
return idSubsytemSpinMaster;// осцилляция
return idSubsystemSpinMaster;// осцилляция
return null;
}
@ -180,7 +52,7 @@ public class WorkSubsystemOperationTimeCalc : Work
$" state, " +
$" lag(state, 1) over (order by date) as state_lag " +
$" from t_telemetry_data_spin " +
$" where id_telemetry = {idTelemetry} and date >= '{begin:u}'" +
$" where id_telemetry = {idTelemetry} and date >= '{geDate:u}'" +
$" order by date ) as tspin " +
$"where mode_lag is null or state_lag is null or (mode != mode_lag and mode_lead != mode_lag) or state != state_lag " +
$"order by date;";
@ -239,6 +111,24 @@ public class WorkSubsystemOperationTimeCalc : Work
return subsystemsOperationTimes;
}
private static async Task<DbDataReader> ExecuteReaderAsync(IAsbCloudDbContext db, string query, CancellationToken token)
{
var connection = db.Database.GetDbConnection();
if (
connection?.State is null ||
connection.State == ConnectionState.Broken ||
connection.State == ConnectionState.Closed)
{
await db.Database.OpenConnectionAsync(token);
connection = db.Database.GetDbConnection();
}
using var command = connection.CreateCommand();
command.CommandText = query;
var result = await command.ExecuteReaderAsync(token);
return result;
}
private static bool IsValid(SubsystemOperationTime item)
{
var validateCode = GetValidateErrorCode(item);

View File

@ -4,7 +4,7 @@ using System;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Background
namespace AsbCloudInfrastructure.Background.PeriodicWorks
{
/// <summary>
/// Задача по удалению загруженных отчетов

View File

@ -1,15 +1,14 @@
using System;
using AsbCloudApp.Data;
using AsbCloudApp.Data.AutogeneratedDailyReport;
using AsbCloudApp.Data.DrillTestReport;
using AsbCloudApp.Data.Manuals;
using AsbCloudApp.Data.ProcessMaps;
using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Data.Subsystems;
using AsbCloudApp.Data.Trajectory;
using AsbCloudApp.Data.WellOperationImport.Options;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services;
using AsbCloudApp.Services.AutoGeneratedDailyReports;
using AsbCloudApp.Services.Notifications;
using AsbCloudApp.Services.ProcessMaps;
using AsbCloudApp.Services.ProcessMaps.WellDrilling;
@ -19,10 +18,10 @@ using AsbCloudDb.Model;
using AsbCloudDb.Model.Manuals;
using AsbCloudDb.Model.ProcessMaps;
using AsbCloudDb.Model.Subsystems;
using AsbCloudDb.Model.Trajectory;
using AsbCloudInfrastructure.Background;
using AsbCloudInfrastructure.Repository;
using AsbCloudInfrastructure.Services;
using AsbCloudInfrastructure.Services.AutoGeneratedDailyReports;
using AsbCloudInfrastructure.Services.DailyReport;
using AsbCloudInfrastructure.Services.DetectOperations;
using AsbCloudInfrastructure.Services.DrillingProgram;
@ -32,6 +31,8 @@ using AsbCloudInfrastructure.Services.ProcessMaps.WellDrilling;
using AsbCloudInfrastructure.Services.SAUB;
using AsbCloudInfrastructure.Services.Subsystems;
using AsbCloudInfrastructure.Services.Trajectory;
using AsbCloudInfrastructure.Services.Trajectory.Export;
using AsbCloudInfrastructure.Services.Trajectory.Import;
using AsbCloudInfrastructure.Services.WellOperationImport;
using AsbCloudInfrastructure.Services.WellOperationImport.FileParser;
using AsbCloudInfrastructure.Services.WellOperationService;
@ -40,21 +41,15 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using AsbCloudApp.Data.DailyReport.Blocks.TimeBalance;
using AsbCloudApp.Services.DailyReport;
using AsbCloudDb.Model.DailyReports.Blocks.TimeBalance;
namespace AsbCloudInfrastructure
{
public static class DependencyInjection
{
public static IAsbCloudDbContext MakeContext(string connectionString)
{
var options = new DbContextOptionsBuilder<AsbCloudDbContext>()
.UseNpgsql(connectionString)
.Options;
var context = new AsbCloudDbContext(options);
return context;
}
public static void MapsterSetup()
{
TypeAdapterConfig.GlobalSettings.Default.Config
@ -145,6 +140,22 @@ namespace AsbCloudInfrastructure
.Map(dest => dest.TopDriveSpeedLimitMax, src => src.TopDriveSpeed.LimitMax)
.Map(dest => dest.TopDriveTorquePlan, src => src.TopDriveTorque.Plan)
.Map(dest => dest.TopDriveTorqueLimitMax, src => src.TopDriveTorque.LimitMax);
TypeAdapterConfig.GlobalSettings.Default.Config
.ForType<TimeBalanceRecord, TimeBalanceRecordDto>()
.Map(dest => dest.DurationHours, src => new PlanFactDto<double?>()
{
Plan = src.DurationHoursPlan,
Fact = src.DurationHoursFact
});
TypeAdapterConfig.GlobalSettings.Default.Config
.ForType<TimeBalanceBlock, TimeBalanceBlockDto>()
.Map(dest => dest.WellDepth, src => new PlanFactDto<double?>()
{
Plan = src.WellDepthPlan
});
}
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
@ -190,7 +201,11 @@ namespace AsbCloudInfrastructure
services.AddTransient<IWellService, WellService>();
services.AddTransient<IWellOperationImportService, WellOperationImportService>();
services.AddTransient<IProcessMapReportWellDrillingExportService, ProcessMapReportWellDrillingExportService>();
services.AddTransient<IPlannedTrajectoryImportService, PlannedTrajectoryImportService>();
services.AddTransient<TrajectoryPlanExportService>();
services.AddTransient<TrajectoryFactManualExportService>();
services.AddTransient<TrajectoryFactNnbExportService>();
services.AddTransient<TrajectoryPlanParserService>();
services.AddTransient<TrajectoryFactManualParserService>();
services.AddTransient<IWellOperationRepository, WellOperationRepository>();
services.AddTransient<IDailyReportService, DailyReportService>();
services.AddTransient<IDetectedOperationService, DetectedOperationService>();
@ -253,17 +268,16 @@ namespace AsbCloudInfrastructure
services.AddTransient<ILimitingParameterRepository, LimitingParameterRepository>();
services.AddTransient<ITelemetryWirelineRunOutRepository, TelemetryWirelineRunOutRepository>();
services.AddTransient<IWellFinalDocumentsRepository, WellFinalDocumentsRepository>();
services.AddTransient<ITrajectoryPlanRepository, TrajectoryPlanRepository>();
services.AddTransient<ITrajectoryFactRepository, TrajectoryFactRepository>();
services.AddTransient<ITrajectoryEditableRepository<TrajectoryGeoPlanDto>, TrajectoryEditableRepository<TrajectoryPlan, TrajectoryGeoPlanDto>>();
services.AddTransient<ITrajectoryEditableRepository<TrajectoryGeoFactDto>, TrajectoryEditableRepository<TrajectoryFact, TrajectoryGeoFactDto>>();
services.AddTransient<ITrajectoryNnbRepository, TrajectoryNnbRepository>();
services.AddTransient<IFaqRepository, FaqRepository>();
services.AddTransient<ISlipsStatService, SlipsStatService>();
services.AddTransient<IWellContactService, WellContactService>();
services.AddTransient<ICrudRepository<WellSectionTypeDto>, CrudCacheRepositoryBase<WellSectionTypeDto,
WellSectionType>>();
// Subsystem service
services.AddTransient<ICrudRepository<SubsystemDto>, CrudCacheRepositoryBase<SubsystemDto, Subsystem>>();
services.AddTransient<ISubsystemService, SubsystemService>();
services.AddTransient<ICrudRepository<PermissionDto>, CrudCacheRepositoryBase<PermissionDto, Permission>>();
@ -279,8 +293,6 @@ namespace AsbCloudInfrastructure
services.AddTransient<IWitsRecordRepository<AsbCloudApp.Data.WITS.Record60Dto>, WitsRecordRepository<AsbCloudApp.Data.WITS.Record60Dto, AsbCloudDb.Model.WITS.Record60>>();
services.AddTransient<IWitsRecordRepository<AsbCloudApp.Data.WITS.Record61Dto>, WitsRecordRepository<AsbCloudApp.Data.WITS.Record61Dto, AsbCloudDb.Model.WITS.Record61>>();
services.AddTransient<IAutoGeneratedDailyReportService, AutoGeneratedDailyReportService>();
services.AddTransient<IReportMakerService<AutoGeneratedDailyReportDto>, AutoGeneratedDailyReportMakerService>();
services.AddTransient<IDrillTestReportService, DrillTestReportService>();
services.AddTransient<IReportMakerService<DrillTestReportDataDto>, DrillTestReportMakerService>();
@ -299,21 +311,11 @@ namespace AsbCloudInfrastructure
services.AddTransient<DetectedOperationExportService>();
services.AddTransient<IDailyReportService, DailyReportService>();
services.AddTransient<IDailyReportRepository, DailyReportRepository>();
services.AddTransient<IDailyReportExportService, DailyReportExportService>();
return services;
}
public static IServiceCollection AddTransientLazy<TService, TImplementation>(this IServiceCollection services)
where TService : class
where TImplementation : class, TService
=> services.AddTransient<TService, TImplementation>()
.AddTransient(provider => new Lazy<TService>(provider.GetRequiredService<TService>));
public static IServiceCollection AddTransientLazy<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory)
where TService : class
where TImplementation : class, TService
=> services.AddTransient<TService, TImplementation>(implementationFactory)
.AddTransient(provider => new Lazy<TService>(() => implementationFactory(provider)));
}
}

View File

@ -0,0 +1,91 @@
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 AsbCloudDb;
using AsbCloudDb.Model;
using AsbCloudDb.Model.DailyReports;
using Mapster;
using Microsoft.EntityFrameworkCore;
namespace AsbCloudInfrastructure.Repository;
public class DailyReportRepository : CrudRepositoryBase<DailyReportDto, DailyReport>,
IDailyReportRepository
{
public DailyReportRepository(IAsbCloudDbContext dbContext)
: base(dbContext)
{
}
public async Task<IEnumerable<DailyReportDto>> GetAsync(int idWell, FileReportRequest request, CancellationToken cancellationToken)
{
var skip = request.Skip ?? 0;
var take = request.Take ?? 10;
var query = GetQuery().Where(d => d.IdWell == idWell);
if (request.GeDate.HasValue)
{
var geDate = request.GeDate.Value.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
query = query.Where(d => d.Date >= geDate);
}
if (request.LeDate.HasValue)
{
var leDate = request.LeDate.Value.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
query = query.Where(d => d.Date <= leDate);
}
if (request.SortFields?.Any() == true)
{
query = query.SortBy(request.SortFields);
}
else
{
query = query.OrderBy(d => d.Date);
}
var entities = await query
.Skip(skip)
.Take(take)
.AsNoTracking()
.ToArrayAsync(cancellationToken);
var dtos = entities.Select(Convert);
return dtos;
}
public async Task<DailyReportDto?> GetOrDefaultAsync(int idWell, DateTime 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 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;
}
}

View File

@ -31,9 +31,4 @@ public class HelpPageRepository : CrudRepositoryBase<HelpPageDto, HelpPage>,
return helpPage.Adapt<HelpPageDto>();
}
public Task<bool> IsExistingAsync(string key, int idCategory, CancellationToken cancellationToken) =>
dbContext.HelpPages.AnyAsync(h => h.UrlPage == key &&
h.IdCategory == idCategory,
cancellationToken);
}

View File

@ -1,17 +1,19 @@
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Mapster;
namespace AsbCloudInfrastructure.Repository
{
public class ScheduleRepository : CrudWellRelatedRepositoryBase<ScheduleDto, Schedule>, IScheduleRepository
public class ScheduleRepository : CrudWellRelatedRepositoryBase<ScheduleDto, Schedule>,
IScheduleRepository
{
private readonly IWellService wellService;
@ -21,21 +23,26 @@ namespace AsbCloudInfrastructure.Repository
this.wellService = wellService;
}
public async Task<IEnumerable<ScheduleDto>> GetAsync(int idWell, DateTime workTime, CancellationToken token)
{
var entities = await BuildQuery(idWell, workTime)
.AsNoTracking()
.ToArrayAsync(token);
return entities.Select(Convert);
}
public async Task<DrillerDto?> GetOrDefaultDrillerAsync(int idWell, DateTime workTime, CancellationToken token)
{
var hoursOffset = wellService.GetTimezone(idWell).Hours;
var date = workTime.ToUtcDateTimeOffset(hoursOffset);
var entities = await GetQuery()
.Where(s => s.IdWell == idWell
&& s.DrillStart <= date
&& s.DrillEnd >= date)
.ToListAsync(token);
var entities = await BuildQuery(idWell, workTime)
.AsNoTracking()
.ToArrayAsync(token);
if (!entities.Any())
return null;
var remoteDate = date.ToRemoteDateTime(hoursOffset);
var hoursOffset = wellService.GetTimezone(idWell).Hours;
var remoteDate = workTime.ToUtcDateTimeOffset(hoursOffset).ToRemoteDateTime(hoursOffset);
var time = new TimeOnly(remoteDate.Hour, remoteDate.Minute, remoteDate.Second);
var entity = entities.FirstOrDefault(s =>
@ -46,6 +53,17 @@ namespace AsbCloudInfrastructure.Repository
return entity?.Driller.Adapt<DrillerDto>();
}
private IQueryable<Schedule> BuildQuery(int idWell, DateTime workTime)
{
var hoursOffset = wellService.GetTimezone(idWell).Hours;
var workTimeDateTime = workTime.ToUtcDateTimeOffset(hoursOffset);
return GetQuery().Where(s => s.IdWell == idWell
&& s.DrillStart <= workTimeDateTime
&& s.DrillEnd >= workTimeDateTime);
}
protected override Schedule Convert(ScheduleDto dto)
{
var hoursOffset = wellService.GetTimezone(dto.IdWell).Hours;

View File

@ -1,8 +1,9 @@
using AsbCloudApp.Data;
using AsbCloudApp.Data.Trajectory;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudDb.Model.Trajectory;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
@ -13,25 +14,31 @@ using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Repository
{
public class TrajectoryPlanRepository : ITrajectoryPlanRepository
/// <summary>
/// CRUD-репозиторий для работы с траекториями (плановыми и фактическими)
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <typeparam name="Tdto"></typeparam>
public class TrajectoryEditableRepository<TEntity, Tdto> : ITrajectoryEditableRepository<Tdto>
where TEntity : Trajectory
where Tdto : TrajectoryGeoDto
{
private readonly IAsbCloudDbContext db;
private readonly IWellService wellService;
public TrajectoryPlanRepository(IAsbCloudDbContext db, IWellService wellService)
public TrajectoryEditableRepository(IAsbCloudDbContext db, IWellService wellService)
{
this.db = db;
this.wellService = wellService;
}
/// <inheritdoc/>
public async Task<int> AddRangeAsync(IEnumerable<TrajectoryGeoPlanDto> plannedTrajectoryRows, CancellationToken token)
public async Task<int> AddRangeAsync(IEnumerable<Tdto> trajectoryRows, CancellationToken token)
{
var idWell = plannedTrajectoryRows.First().IdWell;
if (!plannedTrajectoryRows.All(r => r.IdWell == idWell))
throw new ArgumentInvalidException(nameof(plannedTrajectoryRows), "Все строки должны относиться к одной скважине");
var idWell = trajectoryRows.First().IdWell;
if (!trajectoryRows.All(r => r.IdWell == idWell))
throw new ArgumentInvalidException(nameof(trajectoryRows), "Все строки должны относиться к одной скважине");
var offsetHours = wellService.GetTimezone(idWell).Hours;
var entities = plannedTrajectoryRows
var entities = trajectoryRows
.Select(e =>
{
var entity = Convert(e, offsetHours);
@ -39,80 +46,75 @@ namespace AsbCloudInfrastructure.Repository
return entity;
});
db.PlannedTrajectories.AddRange(entities);
return await db.SaveChangesAsync(token)
.ConfigureAwait(false);
db.Set<TEntity>().AddRange(entities);
return await db.SaveChangesAsync(token);
}
/// <inheritdoc/>
public async Task<int> AddAsync(TrajectoryGeoPlanDto plannedTrajectoryRow, CancellationToken token)
public async Task<int> AddAsync(Tdto trajectoryRow, CancellationToken token)
{
var offsetHours = wellService.GetTimezone(plannedTrajectoryRow.IdWell).Hours;
var entity = Convert(plannedTrajectoryRow, offsetHours);
var offsetHours = wellService.GetTimezone(trajectoryRow.IdWell).Hours;
var entity = Convert(trajectoryRow, offsetHours);
entity.Id = 0;
db.PlannedTrajectories.Add(entity);
db.Set<TEntity>().Add(entity);
return await db.SaveChangesAsync(token)
.ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task<int> DeleteRangeAsync(IEnumerable<int> ids, CancellationToken token)
{
var query = db.PlannedTrajectories
var query = db.Set<TEntity>()
.Where(e => ids.Contains(e.Id));
db.PlannedTrajectories.RemoveRange(query);
db.Set<TEntity>().RemoveRange(query);
return await db.SaveChangesAsync(token)
.ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task<int> DeleteByIdWellAsync(int idWell, CancellationToken token)
{
var query = db.PlannedTrajectories
var query = db.Set<TEntity>()
.Where(e => e.IdWell == idWell);
db.PlannedTrajectories.RemoveRange(query);
db.Set<TEntity>().RemoveRange(query);
return await db.SaveChangesAsync(token)
.ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task<IEnumerable<TrajectoryGeoPlanDto>> GetAsync(int idWell, CancellationToken token)
public async Task<IEnumerable<Tdto>> GetAsync(int idWell, CancellationToken token)
{
var well = wellService.GetOrDefault(idWell)
?? throw new ArgumentInvalidException(nameof(idWell), "idWell doesn`t exist");
var offsetHours = well.Timezone.Hours;
var query = db.PlannedTrajectories
var query = db.Set<TEntity>()
.AsNoTracking()
.Where(x => x.IdWell == idWell);
.Where(x => x.IdWell == well.Id);
var entities = await query
.OrderBy(e => e.WellboreDepth)
.ToArrayAsync(token);
var result = entities
.Select(r => Convert(r, offsetHours));
return result;
}
/// <inheritdoc/>
public async Task<int> UpdateAsync(TrajectoryGeoPlanDto row, CancellationToken token)
public async Task<int> UpdateAsync(Tdto row, CancellationToken token)
{
var offsetHours = wellService.GetTimezone(row.IdWell).Hours;
var entity = Convert(row, offsetHours);
db.PlannedTrajectories.Update(entity);
db.Set<TEntity>().Update(entity);
return await db.SaveChangesAsync(token)
.ConfigureAwait(false);
}
private TrajectoryGeoPlanDto Convert(PlannedTrajectory entity, double offsetHours)
private static Tdto Convert(TEntity entity, double offsetHours)
{
var dto = entity.Adapt<TrajectoryGeoPlanDto>();
var dto = entity.Adapt<Tdto>();
dto.UpdateDate = entity.UpdateDate.ToRemoteDateTime(offsetHours);
return dto;
}
private PlannedTrajectory Convert(TrajectoryGeoPlanDto dto, double offsetHours)
private static TEntity Convert(Tdto dto, double offsetHours)
{
var entity = dto.Adapt<PlannedTrajectory>();
var entity = dto.Adapt<TEntity>();
entity.UpdateDate = DateTime.Now.ToUtcDateTimeOffset(offsetHours);
return entity;
}

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