diff --git a/AsbCloudApp/Data/ClusterDto.cs b/AsbCloudApp/Data/ClusterDto.cs index 895d3501..1f2eb2c7 100644 --- a/AsbCloudApp/Data/ClusterDto.cs +++ b/AsbCloudApp/Data/ClusterDto.cs @@ -8,6 +8,7 @@ namespace AsbCloudApp.Data public string Caption { get; set; } public double? Latitude { get; set; } public double? Longitude { get; set; } + public SimpleTimezoneDto Timezone { get; set; } public int? IdDeposit { get; set; } public DepositBaseDto Deposit { get; set; } public IEnumerable Wells { get; set; } diff --git a/AsbCloudApp/Data/DepositDto.cs b/AsbCloudApp/Data/DepositDto.cs index 71d59f9c..be0200fd 100644 --- a/AsbCloudApp/Data/DepositDto.cs +++ b/AsbCloudApp/Data/DepositDto.cs @@ -8,6 +8,7 @@ namespace AsbCloudApp.Data public string Caption { get; set; } public double? Latitude { get; set; } public double? Longitude { get; set; } + public SimpleTimezoneDto Timezone { get; set; } } public class DepositDto : DepositBaseDto diff --git a/AsbCloudApp/Data/DrillFlowChartDto.cs b/AsbCloudApp/Data/DrillFlowChartDto.cs index 96095fe9..55e14919 100644 --- a/AsbCloudApp/Data/DrillFlowChartDto.cs +++ b/AsbCloudApp/Data/DrillFlowChartDto.cs @@ -3,7 +3,7 @@ using System; namespace AsbCloudApp.Data { /// - /// ( ) + /// ( ) /// public class DrillFlowChartDto : IId { diff --git a/AsbCloudApp/Data/IMapPoint.cs b/AsbCloudApp/Data/IMapPoint.cs index fe2798ca..4ab08239 100644 --- a/AsbCloudApp/Data/IMapPoint.cs +++ b/AsbCloudApp/Data/IMapPoint.cs @@ -4,5 +4,6 @@ { double? Latitude { get; set; } double? Longitude { get; set; } + SimpleTimezoneDto Timezone { get; set; } } } diff --git a/AsbCloudApp/Data/PaginationContainer.cs b/AsbCloudApp/Data/PaginationContainer.cs index ba33eaf3..49d49d6a 100644 --- a/AsbCloudApp/Data/PaginationContainer.cs +++ b/AsbCloudApp/Data/PaginationContainer.cs @@ -19,7 +19,7 @@ namespace AsbCloudApp.Data } /// - /// Кол-во записей пропущеных с начала таблицы в запросе от api + /// Кол-во записей пропущенных с начала таблицы в запросе от api /// public int Skip { get; set; } diff --git a/AsbCloudApp/Data/TelemetryTimeZoneDto.cs b/AsbCloudApp/Data/SimpleTimezoneDto.cs similarity index 66% rename from AsbCloudApp/Data/TelemetryTimeZoneDto.cs rename to AsbCloudApp/Data/SimpleTimezoneDto.cs index b8cd7e2b..32a8ff9e 100644 --- a/AsbCloudApp/Data/TelemetryTimeZoneDto.cs +++ b/AsbCloudApp/Data/SimpleTimezoneDto.cs @@ -1,16 +1,16 @@ namespace AsbCloudApp.Data { - public class TelemetryTimeZoneDto + public class SimpleTimezoneDto { public double Hours { get; set; } - public string TimeZoneId { get; set; } + public string TimezoneId { get; set; } public bool IsOverride { get; set; } public override bool Equals(object obj) { - if(obj is TelemetryTimeZoneDto tTimeZone + if(obj is SimpleTimezoneDto tTimeZone && tTimeZone.Hours == Hours - && tTimeZone.TimeZoneId == TimeZoneId + && tTimeZone.TimezoneId == TimezoneId && tTimeZone.IsOverride == IsOverride) return true; return false; @@ -18,7 +18,7 @@ namespace AsbCloudApp.Data public override int GetHashCode() => Hours.GetHashCode() - | TimeZoneId.GetHashCode() + | TimezoneId.GetHashCode() | IsOverride.GetHashCode(); } } \ No newline at end of file diff --git a/AsbCloudApp/Data/TelemetryDataSaubDto.cs b/AsbCloudApp/Data/TelemetryDataSaubDto.cs index 7099ddab..0d669253 100644 --- a/AsbCloudApp/Data/TelemetryDataSaubDto.cs +++ b/AsbCloudApp/Data/TelemetryDataSaubDto.cs @@ -38,7 +38,7 @@ namespace AsbCloudApp.Data public float? WellDepth { get; set; } /// - /// Глубина долта + /// Глубина долота /// public float? BitDepth { get; set; } @@ -83,12 +83,12 @@ namespace AsbCloudApp.Data public float? BlockSpeedSpDevelop { get; set; } /// - /// Давтение + /// Давление /// public float? Pressure { get; set; } /// - /// Давтение при холостом ходе. + /// Давление при холостом ходе. /// public float? PressureIdle { get; set; } diff --git a/AsbCloudApp/Data/WellDto.cs b/AsbCloudApp/Data/WellDto.cs index f3843eaa..0eac356d 100644 --- a/AsbCloudApp/Data/WellDto.cs +++ b/AsbCloudApp/Data/WellDto.cs @@ -8,12 +8,13 @@ namespace AsbCloudApp.Data public int Id { get; set; } public double? Latitude { get; set; } public double? Longitude { get; set; } + public SimpleTimezoneDto Timezone { get; set; } public string WellType { get; set; } public int IdWellType { get; set; } public int? IdCluster { get; set; } /// - /// 0 - незвестно, + /// 0 - неизвестно, /// 1 - в работе, /// 2 - завершена /// diff --git a/AsbCloudApp/Services/IMessageService.cs b/AsbCloudApp/Services/IMessageService.cs index 9b4221c9..1a2536f2 100644 --- a/AsbCloudApp/Services/IMessageService.cs +++ b/AsbCloudApp/Services/IMessageService.cs @@ -11,10 +11,9 @@ namespace AsbCloudApp.Services Task> GetMessagesAsync(int idWell, IEnumerable categoryids = default, DateTime begin = default, DateTime end = default, string searchString = default, - int skip = 0, int take = 32, bool isUtc = true, - CancellationToken token = default); - Task GetMessagesDatesRangeAsync(int idWell, bool isUtc, + int skip = 0, int take = 32, CancellationToken token = default); + Task InsertAsync(string uid, IEnumerable dtos, CancellationToken token); } diff --git a/AsbCloudApp/Services/IReportService.cs b/AsbCloudApp/Services/IReportService.cs index 258195d5..b900e877 100644 --- a/AsbCloudApp/Services/IReportService.cs +++ b/AsbCloudApp/Services/IReportService.cs @@ -14,8 +14,7 @@ namespace AsbCloudApp.Services Action handleReportProgress); int GetReportPagesCount(int idWell, DateTime begin, DateTime end, int stepSeconds, int format); - Task GetReportsDatesRangeAsync(int idWell, bool isUtc, - CancellationToken token = default); - Task> GetAllReportsByWellAsync(int idWell, CancellationToken token); + DatesRangeDto GetDatesRangeOrDefault(int idWell); + Task> GetAllReportsByWellAsync(int idWell, CancellationToken token); } } diff --git a/AsbCloudApp/Services/ITelemetryAnalyticsService.cs b/AsbCloudApp/Services/ITelemetryAnalyticsService.cs index 2580e3b3..d621901f 100644 --- a/AsbCloudApp/Services/ITelemetryAnalyticsService.cs +++ b/AsbCloudApp/Services/ITelemetryAnalyticsService.cs @@ -24,7 +24,7 @@ namespace AsbCloudApp.Services int intervalHoursTimestamp, int workBeginTimestamp, CancellationToken token = default); Task AnalyzeAndSaveTelemetriesAsync(CancellationToken token = default); - Task GetOperationsDateRangeAsync(int idWell, bool isUtc, + Task GetOperationsDateRangeAsync(int idWell, CancellationToken token = default); } } diff --git a/AsbCloudApp/Services/ITelemetryDataService.cs b/AsbCloudApp/Services/ITelemetryDataService.cs index 6cb8228f..3e34e202 100644 --- a/AsbCloudApp/Services/ITelemetryDataService.cs +++ b/AsbCloudApp/Services/ITelemetryDataService.cs @@ -10,9 +10,8 @@ namespace AsbCloudApp.Services { Task> GetAsync(int idWell, DateTime dateBegin = default, double intervalSec = 600d, - int approxPointsCount = 1024, bool isUtc = false, CancellationToken token = default); - Task GetDataDatesRangeAsync(int idWell, bool isUtc = false, - CancellationToken token = default); + int approxPointsCount = 1024, CancellationToken token = default); + Task UpdateDataAsync(string uid, IEnumerable dtos, CancellationToken token = default); } } \ No newline at end of file diff --git a/AsbCloudApp/Services/ITelemetryService.cs b/AsbCloudApp/Services/ITelemetryService.cs index 266306b8..2d42d53d 100644 --- a/AsbCloudApp/Services/ITelemetryService.cs +++ b/AsbCloudApp/Services/ITelemetryService.cs @@ -8,22 +8,17 @@ namespace AsbCloudApp.Services { public interface ITelemetryService { - ITimeZoneService TimeZoneService { get; } + ITimezoneService TimeZoneService { get; } ITelemetryTracker TelemetryTracker { get; } int? GetIdWellByTelemetryUid(string uid); int GetOrCreateTelemetryIdByUid(string uid); - double GetTimezoneOffset(int idTelemetry); - Task GetTimeZoneOffsetAsync(int idTelemetry, CancellationToken token); + SimpleTimezoneDto GetTimezone(int idTelemetry); IEnumerable GetTransmittingTelemetries(); - DateTimeOffset GetLastTelemetryDate(string telemetryUid); - DateTimeOffset GetLastTelemetryDate(int telemetryId); + DateTime GetLastTelemetryDate(int idTelemetry, bool useUtc = false); int? GetIdTelemetryByIdWell(int idWell); - + DatesRangeDto GetDatesRange(int idTelemetry); Task UpdateInfoAsync(string uid, TelemetryInfoDto info, CancellationToken token); - Task DatesRangeToTelemetryTimeZoneAsync(int telemetryId, DatesRangeDto result, - CancellationToken token); - - Task UpdateTimeZoneAsync(string uid, TelemetryTimeZoneDto telemetryTimeZoneInfo, CancellationToken token); + Task UpdateTimezoneAsync(string uid, SimpleTimezoneDto telemetryTimeZoneInfo, CancellationToken token); /// /// Слить данные телеметрии в одну @@ -32,8 +27,6 @@ namespace AsbCloudApp.Services /// новая /// Task MergeAsync(int from, int to, CancellationToken token); - void SaveRequestDate(string uid, DateTimeOffset remoteDate); - Task GetDatesRangeAsync(int idWell, bool isUtc, CancellationToken token = default); } } \ No newline at end of file diff --git a/AsbCloudApp/Services/ITimeZoneService.cs b/AsbCloudApp/Services/ITimeZoneService.cs index 4997a9f4..5836e665 100644 --- a/AsbCloudApp/Services/ITimeZoneService.cs +++ b/AsbCloudApp/Services/ITimeZoneService.cs @@ -1,11 +1,13 @@ -using System; +using AsbCloudApp.Data; +using System; using System.Threading; using System.Threading.Tasks; namespace AsbCloudApp.Services { - public interface ITimeZoneService + public interface ITimezoneService { - Task GetByCoordinatesAsync(double latitude, double longitude, CancellationToken token); + SimpleTimezoneDto GetByCoordinates(double latitude, double longitude); + Task GetByCoordinatesAsync(double latitude, double longitude, CancellationToken token); } } \ No newline at end of file diff --git a/AsbCloudApp/Services/IWellService.cs b/AsbCloudApp/Services/IWellService.cs index c8ee6ae5..346b878f 100644 --- a/AsbCloudApp/Services/IWellService.cs +++ b/AsbCloudApp/Services/IWellService.cs @@ -19,6 +19,8 @@ namespace AsbCloudApp.Services string GetStateText(int state); DateTimeOffset GetLastTelemetryDate(int idWell); Task> GetClusterWellsIdsAsync(int idWell, CancellationToken token); - double? GetTimeZoneOffset(int idWell); + SimpleTimezoneDto GetTimezone(int idWell); + DatesRangeDto GetDatesRange(int idWell); + void EnshureTimezonesIsSet(); } } diff --git a/AsbCloudDb/EFExtentions.cs b/AsbCloudDb/EFExtentions.cs index 9a0b88c3..a799fa0a 100644 --- a/AsbCloudDb/EFExtentions.cs +++ b/AsbCloudDb/EFExtentions.cs @@ -125,6 +125,7 @@ namespace AsbCloudDb { string vStr => $"'{vStr}'", DateTime vDate => $"'{FormatDateValue(vDate)}'", + DateTimeOffset vDate => $"'{FormatDateValue(vDate.UtcDateTime)}'", IFormattable vFormattable=> FormatFormattableValue(vFormattable), _ => System.Text.Json.JsonSerializer.Serialize(v), }; diff --git a/AsbCloudDb/Migrations/20211116080138_Add_Telemetry_TimeZone.Designer.cs b/AsbCloudDb/Migrations/20211116080138_Add_Telemetry_TimeZone.Designer.cs index fad65af7..c2a8e3e5 100644 --- a/AsbCloudDb/Migrations/20211116080138_Add_Telemetry_TimeZone.Designer.cs +++ b/AsbCloudDb/Migrations/20211116080138_Add_Telemetry_TimeZone.Designer.cs @@ -770,7 +770,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TelemetryTimeZone") + b.Property("TelemetryTimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Migrations/20211116080138_Add_Telemetry_TimeZone.cs b/AsbCloudDb/Migrations/20211116080138_Add_Telemetry_TimeZone.cs index e1fa38f3..b62c4dfa 100644 --- a/AsbCloudDb/Migrations/20211116080138_Add_Telemetry_TimeZone.cs +++ b/AsbCloudDb/Migrations/20211116080138_Add_Telemetry_TimeZone.cs @@ -7,7 +7,7 @@ namespace AsbCloudDb.Migrations { protected override void Up(MigrationBuilder migrationBuilder) { - migrationBuilder.AddColumn( + migrationBuilder.AddColumn( name: "timezone", table: "t_telemetry", type: "jsonb", diff --git a/AsbCloudDb/Migrations/20211123130153_Add_UserRoles_Permissions.Designer.cs b/AsbCloudDb/Migrations/20211123130153_Add_UserRoles_Permissions.Designer.cs index 86311db6..c70e66e7 100644 --- a/AsbCloudDb/Migrations/20211123130153_Add_UserRoles_Permissions.Designer.cs +++ b/AsbCloudDb/Migrations/20211123130153_Add_UserRoles_Permissions.Designer.cs @@ -853,7 +853,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TelemetryTimeZone") + b.Property("TelemetryTimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Migrations/20211124111523_AddSetpoints.Designer.cs b/AsbCloudDb/Migrations/20211124111523_AddSetpoints.Designer.cs index 24e4cb99..1a388d7e 100644 --- a/AsbCloudDb/Migrations/20211124111523_AddSetpoints.Designer.cs +++ b/AsbCloudDb/Migrations/20211124111523_AddSetpoints.Designer.cs @@ -824,7 +824,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TelemetryTimeZone") + b.Property("TelemetryTimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Migrations/20211129122956_Fixed_Role_Permissions_Value.Designer.cs b/AsbCloudDb/Migrations/20211129122956_Fixed_Role_Permissions_Value.Designer.cs index 40be714d..8cbcfe57 100644 --- a/AsbCloudDb/Migrations/20211129122956_Fixed_Role_Permissions_Value.Designer.cs +++ b/AsbCloudDb/Migrations/20211129122956_Fixed_Role_Permissions_Value.Designer.cs @@ -854,7 +854,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TelemetryTimeZone") + b.Property("TelemetryTimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Migrations/20211130121716_Renamed_Permissions_Tables.Designer.cs b/AsbCloudDb/Migrations/20211130121716_Renamed_Permissions_Tables.Designer.cs index 3b844b61..9473c406 100644 --- a/AsbCloudDb/Migrations/20211130121716_Renamed_Permissions_Tables.Designer.cs +++ b/AsbCloudDb/Migrations/20211130121716_Renamed_Permissions_Tables.Designer.cs @@ -854,7 +854,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TelemetryTimeZone") + b.Property("TelemetryTimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Migrations/20211130122321_Renamed_PermissionCollections.Designer.cs b/AsbCloudDb/Migrations/20211130122321_Renamed_PermissionCollections.Designer.cs index eda61f14..22ee1aec 100644 --- a/AsbCloudDb/Migrations/20211130122321_Renamed_PermissionCollections.Designer.cs +++ b/AsbCloudDb/Migrations/20211130122321_Renamed_PermissionCollections.Designer.cs @@ -854,7 +854,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TelemetryTimeZone") + b.Property("TelemetryTimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Migrations/20211201105010_Renamed_Permission_Role_Files.Designer.cs b/AsbCloudDb/Migrations/20211201105010_Renamed_Permission_Role_Files.Designer.cs index 6c7e51c7..c6d5d8d0 100644 --- a/AsbCloudDb/Migrations/20211201105010_Renamed_Permission_Role_Files.Designer.cs +++ b/AsbCloudDb/Migrations/20211201105010_Renamed_Permission_Role_Files.Designer.cs @@ -854,7 +854,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TelemetryTimeZone") + b.Property("TelemetryTimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Migrations/20211202064227_RenameTable_WellComposite.Designer.cs b/AsbCloudDb/Migrations/20211202064227_RenameTable_WellComposite.Designer.cs index 160a8025..5333a57f 100644 --- a/AsbCloudDb/Migrations/20211202064227_RenameTable_WellComposite.Designer.cs +++ b/AsbCloudDb/Migrations/20211202064227_RenameTable_WellComposite.Designer.cs @@ -824,7 +824,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TelemetryTimeZone") + b.Property("TelemetryTimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Migrations/20211208103008_Update_operations_list.Designer.cs b/AsbCloudDb/Migrations/20211208103008_Update_operations_list.Designer.cs index c441531a..193ec0aa 100644 --- a/AsbCloudDb/Migrations/20211208103008_Update_operations_list.Designer.cs +++ b/AsbCloudDb/Migrations/20211208103008_Update_operations_list.Designer.cs @@ -908,7 +908,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TelemetryTimeZone") + b.Property("TelemetryTimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Migrations/20211210074746_Rename_Permissions_fields.Designer.cs b/AsbCloudDb/Migrations/20211210074746_Rename_Permissions_fields.Designer.cs index 2a78133e..57af6c50 100644 --- a/AsbCloudDb/Migrations/20211210074746_Rename_Permissions_fields.Designer.cs +++ b/AsbCloudDb/Migrations/20211210074746_Rename_Permissions_fields.Designer.cs @@ -908,7 +908,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TelemetryTimeZone") + b.Property("TelemetryTimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Migrations/20211215111416_RemovedPermissionValues.Designer.cs b/AsbCloudDb/Migrations/20211215111416_RemovedPermissionValues.Designer.cs index 4b66c451..3493499c 100644 --- a/AsbCloudDb/Migrations/20211215111416_RemovedPermissionValues.Designer.cs +++ b/AsbCloudDb/Migrations/20211215111416_RemovedPermissionValues.Designer.cs @@ -908,7 +908,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TelemetryTimeZone") + b.Property("TelemetryTimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Migrations/20211216072650_RemovedIdFromPermissionRelations.Designer.cs b/AsbCloudDb/Migrations/20211216072650_RemovedIdFromPermissionRelations.Designer.cs index d25622b2..3a2973a3 100644 --- a/AsbCloudDb/Migrations/20211216072650_RemovedIdFromPermissionRelations.Designer.cs +++ b/AsbCloudDb/Migrations/20211216072650_RemovedIdFromPermissionRelations.Designer.cs @@ -899,7 +899,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TelemetryTimeZone") + b.Property("TelemetryTimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Migrations/20211217104347_RenameDocsCategories.Designer.cs b/AsbCloudDb/Migrations/20211217104347_RenameDocsCategories.Designer.cs index fed6e886..f107284b 100644 --- a/AsbCloudDb/Migrations/20211217104347_RenameDocsCategories.Designer.cs +++ b/AsbCloudDb/Migrations/20211217104347_RenameDocsCategories.Designer.cs @@ -902,7 +902,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TelemetryTimeZone") + b.Property("TelemetryTimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Migrations/20211222105725_AddedNewSectionTypes.Designer.cs b/AsbCloudDb/Migrations/20211222105725_AddedNewSectionTypes.Designer.cs index 8f20d5ec..b948f8c4 100644 --- a/AsbCloudDb/Migrations/20211222105725_AddedNewSectionTypes.Designer.cs +++ b/AsbCloudDb/Migrations/20211222105725_AddedNewSectionTypes.Designer.cs @@ -893,7 +893,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TelemetryTimeZone") + b.Property("TelemetryTimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Migrations/20211222141707_Reorder_SectionsTypes_to_keep_existing_operations.Designer.cs b/AsbCloudDb/Migrations/20211222141707_Reorder_SectionsTypes_to_keep_existing_operations.Designer.cs index 48394a18..2f8da1f6 100644 --- a/AsbCloudDb/Migrations/20211222141707_Reorder_SectionsTypes_to_keep_existing_operations.Designer.cs +++ b/AsbCloudDb/Migrations/20211222141707_Reorder_SectionsTypes_to_keep_existing_operations.Designer.cs @@ -893,7 +893,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TelemetryTimeZone") + b.Property("TelemetryTimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Migrations/20211227053852_Specify_type_for_datetime_props.Designer.cs b/AsbCloudDb/Migrations/20211227053852_Specify_type_for_datetime_props.Designer.cs index d2506dca..da7fc1e0 100644 --- a/AsbCloudDb/Migrations/20211227053852_Specify_type_for_datetime_props.Designer.cs +++ b/AsbCloudDb/Migrations/20211227053852_Specify_type_for_datetime_props.Designer.cs @@ -893,7 +893,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TelemetryTimeZone") + b.Property("TelemetryTimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Migrations/20211230054224_Fix_spelling_of_defaults.Designer.cs b/AsbCloudDb/Migrations/20211230054224_Fix_spelling_of_defaults.Designer.cs index e77fe70e..ae743ee1 100644 --- a/AsbCloudDb/Migrations/20211230054224_Fix_spelling_of_defaults.Designer.cs +++ b/AsbCloudDb/Migrations/20211230054224_Fix_spelling_of_defaults.Designer.cs @@ -896,7 +896,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TelemetryTimeZone") + b.Property("TelemetryTimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Migrations/20220102073023_Add_timeZone_to_IMapPoint.Designer.cs b/AsbCloudDb/Migrations/20220102073023_Add_timeZone_to_IMapPoint.Designer.cs index e90e6eb0..e851974a 100644 --- a/AsbCloudDb/Migrations/20220102073023_Add_timeZone_to_IMapPoint.Designer.cs +++ b/AsbCloudDb/Migrations/20220102073023_Add_timeZone_to_IMapPoint.Designer.cs @@ -54,7 +54,7 @@ namespace AsbCloudDb.Migrations .HasColumnType("double precision") .HasColumnName("longitude"); - b.Property("TimeZone") + b.Property("TimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); @@ -161,7 +161,7 @@ namespace AsbCloudDb.Migrations .HasColumnType("double precision") .HasColumnName("longitude"); - b.Property("TimeZone") + b.Property("TimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); @@ -906,7 +906,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TimeZone") + b.Property("TimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); @@ -1836,7 +1836,7 @@ namespace AsbCloudDb.Migrations .HasColumnType("double precision") .HasColumnName("longitude"); - b.Property("TimeZone") + b.Property("TimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Migrations/20220102073023_Add_timeZone_to_IMapPoint.cs b/AsbCloudDb/Migrations/20220102073023_Add_timeZone_to_IMapPoint.cs index 67438588..f4974199 100644 --- a/AsbCloudDb/Migrations/20220102073023_Add_timeZone_to_IMapPoint.cs +++ b/AsbCloudDb/Migrations/20220102073023_Add_timeZone_to_IMapPoint.cs @@ -9,21 +9,21 @@ namespace AsbCloudDb.Migrations { protected override void Up(MigrationBuilder migrationBuilder) { - migrationBuilder.AddColumn( + migrationBuilder.AddColumn( name: "timezone", table: "t_well", type: "jsonb", nullable: true, comment: "Смещение часового пояса от UTC"); - migrationBuilder.AddColumn( + migrationBuilder.AddColumn( name: "timezone", table: "t_deposit", type: "jsonb", nullable: true, comment: "Смещение часового пояса от UTC"); - migrationBuilder.AddColumn( + migrationBuilder.AddColumn( name: "timezone", table: "t_cluster", type: "jsonb", diff --git a/AsbCloudDb/Migrations/20220105123412_Fix_Spelling.Designer.cs b/AsbCloudDb/Migrations/20220105123412_Fix_Spelling.Designer.cs new file mode 100644 index 00000000..b389222e --- /dev/null +++ b/AsbCloudDb/Migrations/20220105123412_Fix_Spelling.Designer.cs @@ -0,0 +1,3095 @@ +// +using System; +using System.Collections.Generic; +using AsbCloudDb.Model; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace AsbCloudDb.Migrations +{ + [DbContext(typeof(AsbCloudDbContext))] + [Migration("20220105123412_Fix_Spelling")] + partial class Fix_Spelling + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .UseCollation("Russian_Russia.1251") + .HasAnnotation("ProductVersion", "6.0.1") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "adminpack"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("AsbCloudDb.Model.Cluster", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Caption") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("caption") + .HasComment("Название"); + + b.Property("IdDeposit") + .HasColumnType("integer") + .HasColumnName("id_deposit"); + + b.Property("Latitude") + .HasColumnType("double precision") + .HasColumnName("latitude"); + + b.Property("Longitude") + .HasColumnType("double precision") + .HasColumnName("longitude"); + + b.Property("Timezone") + .HasColumnType("jsonb") + .HasColumnName("timezone") + .HasComment("Смещение часового пояса от UTC"); + + b.HasKey("Id"); + + b.HasIndex("IdDeposit"); + + b.ToTable("t_cluster"); + + b.HasComment("Кусты"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.Company", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Caption") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("caption"); + + b.Property("IdCompanyType") + .HasMaxLength(255) + .HasColumnType("integer") + .HasColumnName("id_company_type") + .HasComment("вид деятельности"); + + b.HasKey("Id"); + + b.HasIndex("IdCompanyType"); + + b.ToTable("t_company"); + + b.HasData( + new + { + Id = 1, + Caption = "ООО \"АСБ\"", + IdCompanyType = 3 + }); + }); + + modelBuilder.Entity("AsbCloudDb.Model.CompanyType", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Caption") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("caption"); + + b.HasKey("Id"); + + b.ToTable("t_company_type"); + + b.HasData( + new + { + Id = 1, + Caption = "Недрапользователь" + }, + new + { + Id = 2, + Caption = "Буровой подрядчик" + }, + new + { + Id = 3, + Caption = "Сервис автоматизации бурения" + }); + }); + + modelBuilder.Entity("AsbCloudDb.Model.Deposit", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Caption") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("caption"); + + b.Property("Latitude") + .HasColumnType("double precision") + .HasColumnName("latitude"); + + b.Property("Longitude") + .HasColumnType("double precision") + .HasColumnName("longitude"); + + b.Property("Timezone") + .HasColumnType("jsonb") + .HasColumnName("timezone") + .HasComment("Смещение часового пояса от UTC"); + + b.HasKey("Id"); + + b.ToTable("t_deposit"); + + b.HasComment("Месторождение"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.DrillFlowChart", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AxialLoadMax") + .HasColumnType("double precision") + .HasColumnName("axial_load_max") + .HasComment("Максимальная нагрузка"); + + b.Property("AxialLoadMin") + .HasColumnType("double precision") + .HasColumnName("axial_load_min") + .HasComment("Минимальная нагрузка"); + + b.Property("DepthEnd") + .HasColumnType("double precision") + .HasColumnName("depth_end") + .HasComment("Глубина окончания интервала"); + + b.Property("DepthStart") + .HasColumnType("double precision") + .HasColumnName("depth_start") + .HasComment("Стартовая глубина"); + + b.Property("FlowMax") + .HasColumnType("double precision") + .HasColumnName("flow_max") + .HasComment("Максимальный расход"); + + b.Property("FlowMin") + .HasColumnType("double precision") + .HasColumnName("flow_min") + .HasComment("Минимальный расход"); + + b.Property("IdWell") + .HasColumnType("integer") + .HasColumnName("well_id") + .HasComment("Id скважины"); + + b.Property("IdWellOperationCategory") + .HasColumnType("integer") + .HasColumnName("id_operation_category") + .HasComment("Id типа операции"); + + b.Property("LastUpdate") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_update") + .HasComment("Дата последнего изменения"); + + b.Property("PressureMax") + .HasColumnType("double precision") + .HasColumnName("pressure_max") + .HasComment("Максимальное давление"); + + b.Property("PressureMin") + .HasColumnType("double precision") + .HasColumnName("pressure_min") + .HasComment("Минимальное давление"); + + b.Property("RotorSpeedMax") + .HasColumnType("double precision") + .HasColumnName("rotor_speed_max") + .HasComment("Максимальные обороты на ВСП"); + + b.Property("RotorSpeedMin") + .HasColumnType("double precision") + .HasColumnName("rotor_speed_min") + .HasComment("Минимальные обороты на ВСП"); + + b.Property("RotorTorqueMax") + .HasColumnType("double precision") + .HasColumnName("rotor_torque_max") + .HasComment("Максимальный момент на ВСП"); + + b.Property("RotorTorqueMin") + .HasColumnType("double precision") + .HasColumnName("rotor_torque_min") + .HasComment("Минимальный момент на ВСП"); + + b.HasKey("Id"); + + b.HasIndex("IdWell"); + + b.HasIndex("IdWellOperationCategory"); + + b.ToTable("t_drill_flow_chart"); + + b.HasComment("Параметры коридоров бурения (диапазоны параметров бурения)"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.DrillParams", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AxialLoadAvg") + .HasColumnType("double precision") + .HasColumnName("axial_load_avg") + .HasComment("Средняя нагрузка"); + + b.Property("AxialLoadMax") + .HasColumnType("double precision") + .HasColumnName("axial_load_max") + .HasComment("Максимальная нагрузка"); + + b.Property("AxialLoadMin") + .HasColumnType("double precision") + .HasColumnName("axial_load_min") + .HasComment("Минимальная нагрузка"); + + b.Property("DepthEnd") + .HasColumnType("double precision") + .HasColumnName("depth_end") + .HasComment("Глубина окончания интервала"); + + b.Property("DepthStart") + .HasColumnType("double precision") + .HasColumnName("depth_start") + .HasComment("Стартовая глубина"); + + b.Property("FlowAvg") + .HasColumnType("double precision") + .HasColumnName("flow_avg") + .HasComment("Средний расход"); + + b.Property("FlowMax") + .HasColumnType("double precision") + .HasColumnName("flow_max") + .HasComment("Максимальный расход"); + + b.Property("FlowMin") + .HasColumnType("double precision") + .HasColumnName("flow_min") + .HasComment("Минимальный расход"); + + b.Property("IdWell") + .HasColumnType("integer") + .HasColumnName("well_id") + .HasComment("Id скважины"); + + b.Property("IdWellSectionType") + .HasColumnType("integer") + .HasColumnName("id_wellsection_type") + .HasComment("Id с типом секции скважины"); + + b.Property("PressureAvg") + .HasColumnType("double precision") + .HasColumnName("pressure_avg") + .HasComment("Среднее давление"); + + b.Property("PressureMax") + .HasColumnType("double precision") + .HasColumnName("pressure_max") + .HasComment("Максимальное давление"); + + b.Property("PressureMin") + .HasColumnType("double precision") + .HasColumnName("pressure_min") + .HasComment("Минимальное давление"); + + b.Property("RotorSpeedAvg") + .HasColumnType("double precision") + .HasColumnName("rotor_speed_avg") + .HasComment("Средние обороты на ВСП"); + + b.Property("RotorSpeedMax") + .HasColumnType("double precision") + .HasColumnName("rotor_speed_max") + .HasComment("Максимальные обороты на ВСП"); + + b.Property("RotorSpeedMin") + .HasColumnType("double precision") + .HasColumnName("rotor_speed_min") + .HasComment("Минимальные обороты на ВСП"); + + b.Property("RotorTorqueAvg") + .HasColumnType("double precision") + .HasColumnName("rotor_torque_avg") + .HasComment("Средний момент на ВСП"); + + b.Property("RotorTorqueMax") + .HasColumnType("double precision") + .HasColumnName("rotor_torque_max") + .HasComment("Максимальный момент на ВСП"); + + b.Property("RotorTorqueMin") + .HasColumnType("double precision") + .HasColumnName("rotor_torque_min") + .HasComment("Минимальный момент на ВСП"); + + b.HasKey("Id"); + + b.HasIndex("IdWell"); + + b.HasIndex("IdWellSectionType"); + + b.ToTable("t_drill_params"); + + b.HasComment("Режим бурения в секции (диапазоны параметров бурения)"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.FileCategory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .HasColumnType("text") + .HasColumnName("name") + .HasComment("Название категории"); + + b.Property("ShortName") + .HasColumnType("text") + .HasColumnName("short_name") + .HasComment("Короткое название категории"); + + b.HasKey("Id"); + + b.ToTable("t_file_category"); + + b.HasComment("Категории файлов"); + + b.HasData( + new + { + Id = 1, + Name = "Растворный сервис", + ShortName = "fluidService" + }, + new + { + Id = 2, + Name = "Цементирование", + ShortName = "cement" + }, + new + { + Id = 3, + Name = "ННБ", + ShortName = "nnb" + }, + new + { + Id = 4, + Name = "ГТИ", + ShortName = "gti" + }, + new + { + Id = 5, + Name = "Документы по скважине", + ShortName = "wellDocuments" + }, + new + { + Id = 6, + Name = "Супервайзер", + ShortName = "supervisor" + }, + new + { + Id = 7, + Name = "Мастер", + ShortName = "master" + }, + new + { + Id = 8, + Name = "Долотный сервис", + ShortName = "toolService" + }, + new + { + Id = 9, + Name = "Буровой подрядчик", + ShortName = "drillService" + }, + new + { + Id = 10, + Name = "Сервис по заканчиванию скважины", + ShortName = "closingService" + }, + new + { + Id = 12, + Name = "Рапорт", + ShortName = "report" + }, + new + { + Id = 13, + Name = "Программа бурения, части", + ShortName = "ПБч" + }, + new + { + Id = 14, + Name = "Программа бурения", + ShortName = "ПБ" + }); + }); + + modelBuilder.Entity("AsbCloudDb.Model.FileInfo", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("IdAuthor") + .HasColumnType("integer") + .HasColumnName("id_author") + .HasComment("Id пользователя, загрузившего файл"); + + b.Property("IdCategory") + .HasColumnType("integer") + .HasColumnName("id_category") + .HasComment("id категории файла"); + + b.Property("IdWell") + .HasColumnType("integer") + .HasColumnName("id_well") + .HasComment("id скважины"); + + b.Property("IsDeleted") + .HasColumnType("boolean") + .HasColumnName("is_deleted") + .HasComment("Удален ли файл"); + + b.Property("Name") + .HasColumnType("text") + .HasColumnName("name") + .HasComment("Название файла"); + + b.Property("PublishInfo") + .HasColumnType("jsonb") + .HasColumnName("publish_info") + .HasComment("Информация о файле в облаке"); + + b.Property("Size") + .HasColumnType("bigint") + .HasColumnName("file_size") + .HasComment("Размер файла"); + + b.Property("UploadDate") + .HasColumnType("timestamp with time zone") + .HasColumnName("date"); + + b.HasKey("Id"); + + b.HasIndex("IdAuthor"); + + b.HasIndex("IdCategory"); + + b.HasIndex("IdWell"); + + b.ToTable("t_file_info"); + + b.HasComment("Файлы всех категорий"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.FileMark", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Comment") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("comment") + .HasComment("Комментарий"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created") + .HasComment("Дата совершенного действия"); + + b.Property("IdFile") + .HasColumnType("integer") + .HasColumnName("id_file") + .HasComment("id файла"); + + b.Property("IdMarkType") + .HasColumnType("integer") + .HasColumnName("id_mark_type") + .HasComment("0 - Согласован"); + + b.Property("IdUser") + .HasColumnType("integer") + .HasColumnName("id_user") + .HasComment("id пользователя"); + + b.Property("IsDeleted") + .HasColumnType("boolean") + .HasColumnName("is_deleted") + .HasComment("Помечен ли файл как удаленный"); + + b.HasKey("Id"); + + b.HasIndex("IdFile"); + + b.HasIndex("IdUser"); + + b.ToTable("t_file_mark"); + + b.HasComment("Действия с файлами."); + }); + + modelBuilder.Entity("AsbCloudDb.Model.Measure", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Data") + .HasColumnType("jsonb") + .HasColumnName("data") + .HasComment("Данные таблицы последних данных"); + + b.Property("IdCategory") + .HasColumnType("integer") + .HasColumnName("id_category") + .HasComment("id категории"); + + b.Property("IdWell") + .HasColumnType("integer") + .HasColumnName("id_well") + .HasComment("id скважины"); + + b.Property("IsDeleted") + .HasColumnType("boolean") + .HasColumnName("is_deleted") + .HasComment("Пометка удаленным"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone") + .HasColumnName("timestamp") + .HasComment("время добавления"); + + b.HasKey("Id"); + + b.HasIndex("IdCategory"); + + b.HasIndex("IdWell"); + + b.ToTable("t_measure"); + + b.HasComment("Таблица c данными для вкладки 'Последние данные'"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.MeasureCategory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .HasColumnType("text") + .HasColumnName("name") + .HasComment("Название категории"); + + b.Property("ShortName") + .HasColumnType("text") + .HasColumnName("short_name") + .HasComment("Короткое название категории"); + + b.HasKey("Id"); + + b.ToTable("t_measure_category"); + + b.HasComment("Категория последних данных"); + + b.HasData( + new + { + Id = 1, + Name = "Показатели бурового раствора", + ShortName = "Раствор" + }, + new + { + Id = 2, + Name = "Шламограмма", + ShortName = "Шламограмма" + }, + new + { + Id = 3, + Name = "ННБ", + ShortName = "ННБ" + }); + }); + + modelBuilder.Entity("AsbCloudDb.Model.Permission", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Description") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("description") + .HasComment("Краткое описание"); + + b.Property("Name") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name") + .HasComment("Название"); + + b.HasKey("Id"); + + b.ToTable("t_permission"); + + b.HasComment("Разрешения на доступ к данным"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.RelationCompanyWell", b => + { + b.Property("IdCompany") + .HasColumnType("integer") + .HasColumnName("id_company"); + + b.Property("IdWell") + .HasColumnType("integer") + .HasColumnName("id_well"); + + b.HasKey("IdCompany", "IdWell"); + + b.HasIndex("IdWell"); + + b.ToTable("t_relation_company_well"); + + b.HasComment("отношение скважин и компаний"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.RelationUserRolePermission", b => + { + b.Property("IdUserRole") + .HasColumnType("integer") + .HasColumnName("id_user_role"); + + b.Property("IdPermission") + .HasColumnType("integer") + .HasColumnName("id_permission"); + + b.HasKey("IdUserRole", "IdPermission"); + + b.HasIndex("IdPermission"); + + b.ToTable("t_relation_user_role_permission"); + + b.HasComment("Отношение ролей пользователей и разрешений доступа"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.RelationUserUserRole", b => + { + b.Property("IdUser") + .HasColumnType("integer") + .HasColumnName("id_user"); + + b.Property("IdUserRole") + .HasColumnType("integer") + .HasColumnName("id_user_role"); + + b.HasKey("IdUser", "IdUserRole"); + + b.HasIndex("IdUserRole"); + + b.ToTable("t_relation_user_user_role"); + + b.HasComment("Отношение пользователей и ролей"); + + b.HasData( + new + { + IdUser = 1, + IdUserRole = 2 + }); + }); + + modelBuilder.Entity("AsbCloudDb.Model.ReportProperty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Begin") + .HasColumnType("timestamp with time zone") + .HasColumnName("begin"); + + b.Property("End") + .HasColumnType("timestamp with time zone") + .HasColumnName("end") + .HasComment("timestamp with time zone"); + + b.Property("Format") + .HasColumnType("integer") + .HasColumnName("format") + .HasComment("Формат отчета"); + + b.Property("IdFile") + .HasColumnType("integer") + .HasColumnName("id_file") + .HasComment("id файла-родителя"); + + b.Property("IdWell") + .HasColumnType("integer") + .HasColumnName("id_well") + .HasComment("id скважины"); + + b.Property("Step") + .HasColumnType("integer") + .HasColumnName("step") + .HasComment("размер шага в секундах"); + + b.HasKey("Id"); + + b.HasIndex("IdFile"); + + b.HasIndex("IdWell"); + + b.ToTable("t_report_property"); + + b.HasComment("Отчеты с данными по буровым"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.SetpointsRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Comment") + .HasColumnType("text") + .HasColumnName("comment") + .HasComment("комментарий для оператора"); + + b.Property("IdAuthor") + .HasColumnType("integer") + .HasColumnName("id_author") + .HasComment("Id пользователя, загрузившего файл"); + + b.Property("IdState") + .HasColumnType("integer") + .HasColumnName("id_state") + .HasComment("0: неизвестно, 1:ожидает отправки, 2: отправлено, 3: принято оператором, 4: отклонено оператором, 5: устарело"); + + b.Property("IdWell") + .HasColumnType("integer") + .HasColumnName("id_well") + .HasComment("id скважины"); + + b.Property("ObsolescenceSec") + .HasColumnType("integer") + .HasColumnName("obsolescence") + .HasComment("сек. до устаревания"); + + b.Property>("Setpoints") + .HasColumnType("jsonb") + .HasColumnName("setpoint_set") + .HasComment("Набор уставок"); + + b.Property("UploadDate") + .HasColumnType("timestamp with time zone") + .HasColumnName("date"); + + b.HasKey("Id"); + + b.HasIndex("IdAuthor"); + + b.HasIndex("IdWell"); + + b.ToTable("t_setpoints_rquest"); + + b.HasComment("Запросы на изменение уставок панели оператора"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.Telemetry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Info") + .HasColumnType("jsonb") + .HasColumnName("info") + .HasComment("Информация с панели о скважине"); + + b.Property("RemoteUid") + .HasColumnType("text") + .HasColumnName("remote_uid") + .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); + + b.Property("TimeZone") + .HasColumnType("jsonb") + .HasColumnName("timezone") + .HasComment("Смещение часового пояса от UTC"); + + b.HasKey("Id"); + + b.HasIndex(new[] { "RemoteUid" }, "t_telemetry_remote_uid_index"); + + b.ToTable("t_telemetry"); + + b.HasComment("таблица привязки телеметрии от комплектов к конкретной скважине."); + }); + + modelBuilder.Entity("AsbCloudDb.Model.TelemetryAnalysis", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DurationSec") + .HasColumnType("integer") + .HasColumnName("duration_sec") + .HasComment("Кол-во секунд после предыдущей операции"); + + b.Property("IdOperation") + .HasColumnType("integer") + .HasColumnName("id_operation"); + + b.Property("IdTelemetry") + .HasColumnType("integer") + .HasColumnName("id_telemetry"); + + b.Property("IsBitPositionDecreasing") + .HasColumnType("boolean") + .HasColumnName("is_bit_position_decreasing") + .HasComment("Долото поднимается"); + + b.Property("IsBitPositionIncreasing") + .HasColumnType("boolean") + .HasColumnName("is_bit_position_increasing") + .HasComment("Долото спускается"); + + b.Property("IsBitPositionLt20") + .HasColumnType("boolean") + .HasColumnName("is_bit_posision_lt_20") + .HasComment("Положение долота меньше 20м"); + + b.Property("IsBlockPositionDecreasing") + .HasColumnType("boolean") + .HasColumnName("is_block_posision_decresing") + .HasComment("Талевый блок поднимается"); + + b.Property("IsBlockPositionIncreasing") + .HasColumnType("boolean") + .HasColumnName("is_block_posision_incresing") + .HasComment("Талевый блок спускается"); + + b.Property("IsHookWeightLt3") + .HasColumnType("boolean") + .HasColumnName("is_hook_weight_lt_3") + .HasComment("Вес на крюке менее 3т"); + + b.Property("IsHookWeightNotChanges") + .HasColumnType("boolean") + .HasColumnName("is_hook_weight_not_changes") + .HasComment("Вес на крюке не меняется"); + + b.Property("IsPressureGt20") + .HasColumnType("boolean") + .HasColumnName("is_pressure_gt_20") + .HasComment("Давление более 20"); + + b.Property("IsPressureLt20") + .HasColumnType("boolean") + .HasColumnName("is_pressure_lt_20") + .HasComment("Давление менее 20"); + + b.Property("IsRotorSpeedGt5") + .HasColumnType("boolean") + .HasColumnName("is_rotor_speed_gt_3") + .HasComment("Обороты ротора выше 3"); + + b.Property("IsRotorSpeedLt5") + .HasColumnType("boolean") + .HasColumnName("is_rotor_speed_lt_3") + .HasComment("Обороты ротора ниже 3"); + + b.Property("IsWellDepthDecreasing") + .HasColumnType("boolean") + .HasColumnName("is_well_depth_decreasing") + .HasComment("Глубина забоя не увеличивается"); + + b.Property("IsWellDepthIncreasing") + .HasColumnType("boolean") + .HasColumnName("is_well_depth_increasing") + .HasComment("Глубина забоя увеличивается"); + + b.Property("OperationEndDepth") + .HasColumnType("double precision") + .HasColumnName("operation_end_depth") + .HasComment("Глубина, на которой закончилась операция"); + + b.Property("OperationStartDepth") + .HasColumnType("double precision") + .HasColumnName("operation_start_depth") + .HasComment("Глубина, на которой началась операция"); + + b.Property("UnixDate") + .HasColumnType("bigint") + .HasColumnName("unix_date") + .HasComment("Unix timestamp для Linq запросов с вычислением дат"); + + b.HasKey("Id"); + + b.HasIndex("IdOperation"); + + b.HasIndex("IdTelemetry"); + + b.ToTable("t_telemetry_analysis"); + + b.HasComment("События на скважине"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.TelemetryDataSaub", b => + { + b.Property("IdTelemetry") + .HasColumnType("integer") + .HasColumnName("id_telemetry"); + + b.Property("Date") + .HasColumnType("timestamp with time zone") + .HasColumnName("date") + .HasComment("'2021-10-19 18:23:54+05'"); + + b.Property("AxialLoad") + .HasColumnType("real") + .HasColumnName("axial_load") + .HasComment("Осевая нагрузка"); + + b.Property("AxialLoadLimitMax") + .HasColumnType("real") + .HasColumnName("axial_load_limit_max") + .HasComment("Осевая нагрузка. Аварийная макс."); + + b.Property("AxialLoadSp") + .HasColumnType("real") + .HasColumnName("axial_load_sp") + .HasComment("Осевая нагрузка. Задание"); + + b.Property("BitDepth") + .HasColumnType("real") + .HasColumnName("bit_depth") + .HasComment("Положение инструмента"); + + b.Property("BlockPosition") + .HasColumnType("real") + .HasColumnName("block_position") + .HasComment("Высота талевого блока"); + + b.Property("BlockPositionMax") + .HasColumnType("real") + .HasColumnName("block_position_max") + .HasComment("Талевый блок. Макс положение"); + + b.Property("BlockPositionMin") + .HasColumnType("real") + .HasColumnName("block_position_min") + .HasComment("Талевый блок. Мин положение"); + + b.Property("BlockSpeed") + .HasColumnType("real") + .HasColumnName("block_speed") + .HasComment("Скорость талевого блока"); + + b.Property("BlockSpeedSp") + .HasColumnType("real") + .HasColumnName("block_speed_sp") + .HasComment("Скорости талевого блока. Задание"); + + b.Property("BlockSpeedSpDevelop") + .HasColumnType("real") + .HasColumnName("block_speed_sp_develop") + .HasComment("Талевый блок. Задание скорости для проработки"); + + b.Property("BlockSpeedSpRotor") + .HasColumnType("real") + .HasColumnName("block_speed_sp_rotor") + .HasComment("Талевый блок. Задание скорости для роторного бурения"); + + b.Property("BlockSpeedSpSlide") + .HasColumnType("real") + .HasColumnName("block_speed_sp_slide") + .HasComment("Талевый блок. Задание скорости для режима слайда"); + + b.Property("Flow") + .HasColumnType("real") + .HasColumnName("flow") + .HasComment("Расход"); + + b.Property("FlowDeltaLimitMax") + .HasColumnType("real") + .HasColumnName("flow_delta_limit_max") + .HasComment("Расход. Аварийный макс."); + + b.Property("FlowIdle") + .HasColumnType("real") + .HasColumnName("flow_idle") + .HasComment("Расход. Холостой ход"); + + b.Property("HookWeight") + .HasColumnType("real") + .HasColumnName("hook_weight") + .HasComment("Вес на крюке"); + + b.Property("HookWeightIdle") + .HasColumnType("real") + .HasColumnName("hook_weight_idle") + .HasComment("Вес на крюке. Холостой ход"); + + b.Property("HookWeightLimitMax") + .HasColumnType("real") + .HasColumnName("hook_weight_limit_max") + .HasComment("Вес на крюке. Затяжка"); + + b.Property("HookWeightLimitMin") + .HasColumnType("real") + .HasColumnName("hook_weight_limit_min") + .HasComment("Вес на крюке. Посадка"); + + b.Property("IdFeedRegulator") + .HasColumnType("smallint") + .HasColumnName("id_feed_regulator") + .HasComment("Текущий критерий бурения"); + + b.Property("IdUser") + .HasColumnType("integer") + .HasColumnName("id_user") + .HasComment("Пользователь САУБ"); + + b.Property("Mode") + .HasColumnType("smallint") + .HasColumnName("mode") + .HasComment("Режим САУБ"); + + b.Property("MseState") + .HasColumnType("smallint") + .HasColumnName("mse_state") + .HasComment("Текущее состояние работы MSE"); + + b.Property("Pressure") + .HasColumnType("real") + .HasColumnName("pressure") + .HasComment("Давление"); + + b.Property("PressureDeltaLimitMax") + .HasColumnType("real") + .HasColumnName("pressure_delta_limit_max") + .HasComment("Давление дифф. Аварийное макс."); + + b.Property("PressureIdle") + .HasColumnType("real") + .HasColumnName("pressure_idle") + .HasComment("Давление. Холостой ход"); + + b.Property("PressureSp") + .HasColumnType("real") + .HasColumnName("pressure_sp") + .HasComment("Давление. Задание"); + + b.Property("PressureSpDevelop") + .HasColumnType("real") + .HasColumnName("pressure_sp_develop") + .HasComment("Давление. Задание для проработки"); + + b.Property("PressureSpRotor") + .HasColumnType("real") + .HasColumnName("pressure_sp_rotor") + .HasComment("Давление. Задание для роторного бурения"); + + b.Property("PressureSpSlide") + .HasColumnType("real") + .HasColumnName("pressure_sp_slide") + .HasComment("Давление. Задание для режима слайда"); + + b.Property("RotorSpeed") + .HasColumnType("real") + .HasColumnName("rotor_speed") + .HasComment("Обороты ротора"); + + b.Property("RotorTorque") + .HasColumnType("real") + .HasColumnName("rotor_torque") + .HasComment("Момент на роторе"); + + b.Property("RotorTorqueIdle") + .HasColumnType("real") + .HasColumnName("rotor_torque_idle") + .HasComment("Момент на роторе. Холостой ход"); + + b.Property("RotorTorqueLimitMax") + .HasColumnType("real") + .HasColumnName("rotor_torque_limit_max") + .HasComment("Момент на роторе. Аварийный макс."); + + b.Property("RotorTorqueSp") + .HasColumnType("real") + .HasColumnName("rotor_torque_sp") + .HasComment("Момент на роторе. Задание"); + + b.Property("WellDepth") + .HasColumnType("real") + .HasColumnName("well_depth") + .HasComment("Глубина забоя"); + + b.HasKey("IdTelemetry", "Date"); + + b.ToTable("t_telemetry_data_saub"); + + b.HasComment("набор основных данных по SAUB"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.TelemetryDataSpin", b => + { + b.Property("IdTelemetry") + .HasColumnType("integer") + .HasColumnName("id_telemetry"); + + b.Property("Date") + .HasColumnType("timestamp with time zone") + .HasColumnName("date") + .HasComment("'2021-10-19 18:23:54+05'"); + + b.Property("BreakAngleK") + .HasColumnType("real") + .HasColumnName("break_angle_k") + .HasComment("Коэффициент для расчёта за какой угол нужно тормозить"); + + b.Property("BreakAngleLeft") + .HasColumnType("real") + .HasColumnName("break_angle_left") + .HasComment("Угол торможения влево при работе по моменту"); + + b.Property("EncoderResolution") + .HasColumnType("real") + .HasColumnName("encoder_resolution") + .HasComment("Разрешение энкодера"); + + b.Property("Mode") + .HasColumnType("smallint") + .HasColumnName("mode") + .HasComment("Выбранный режим управления"); + + b.Property("PidMuxTorqueLeftLimit") + .HasColumnType("real") + .HasColumnName("pid_mux_torque_left_limit") + .HasComment(" Момент при котором определяется ехать назад по моменту или по скорости"); + + b.Property("PositionRight") + .HasColumnType("real") + .HasColumnName("position_right") + .HasComment("Крайний правый угол осцилляции"); + + b.Property("PositionZero") + .HasColumnType("real") + .HasColumnName("position_zero") + .HasComment("Нулевая позиция осцилляции"); + + b.Property("Ratio") + .HasColumnType("real") + .HasColumnName("ratio") + .HasComment(" Коэффициент редукции редуктора"); + + b.Property("ReverseKTorque") + .HasColumnType("real") + .HasColumnName("reverse_k_torque") + .HasComment("Коэффициент на который умножается момент, для того чтобы система поняла что мы движемся в обратную сторону"); + + b.Property("ReverseSpeedSpZeroTime") + .HasColumnType("smallint") + .HasColumnName("reverse_speed_sp_zero_time") + .HasComment("Время выдачи сигнала нулевой скорости на при смене направления"); + + b.Property("RevolsLeftLimit") + .HasColumnType("real") + .HasColumnName("revols_left_limit") + .HasComment("Ограничение числа оборотов влево"); + + b.Property("RevolsLeftTotal") + .HasColumnType("real") + .HasColumnName("revols_left_total") + .HasComment("Суммарное количество оборотов влево"); + + b.Property("RevolsRightLimit") + .HasColumnType("real") + .HasColumnName("revols_right_limit") + .HasComment("Ограничение числа оборотов вправо"); + + b.Property("RevolsRightTotal") + .HasColumnType("real") + .HasColumnName("revols_right_total") + .HasComment("Суммарное количество оборотов вправо"); + + b.Property("RotorTorqueAvg") + .HasColumnType("real") + .HasColumnName("rotor_torque_avg") + .HasComment("Момент в роторе средний"); + + b.Property("SpeedLeftSp") + .HasColumnType("real") + .HasColumnName("speed_left_sp") + .HasComment("Заданная скорость вращения влево"); + + b.Property("SpeedRightSp") + .HasColumnType("real") + .HasColumnName("speed_right_sp") + .HasComment("Заданная скорость вращения вправо"); + + b.Property("State") + .HasColumnType("smallint") + .HasColumnName("state") + .HasComment("Переменная этапа"); + + b.Property("TopDriveSpeed") + .HasColumnType("real") + .HasColumnName("top_drive_speed") + .HasComment("Скорость СВП"); + + b.Property("TopDriveSpeedErr") + .HasColumnType("smallint") + .HasColumnName("top_drive_speed_err"); + + b.Property("TopDriveSpeedMax") + .HasColumnType("real") + .HasColumnName("top_drive_speed_max") + .HasComment("верхний предел"); + + b.Property("TopDriveSpeedMin") + .HasColumnType("real") + .HasColumnName("top_drive_speed_min") + .HasComment("нижний предел"); + + b.Property("TopDriveSpeedOffset") + .HasColumnType("real") + .HasColumnName("top_drive_speed_offset") + .HasComment("смещение"); + + b.Property("TopDriveSpeedSpFrom") + .HasColumnType("real") + .HasColumnName("top_drive_speed_sp_from") + .HasComment("Заданная скорость c СВП"); + + b.Property("TopDriveSpeedSpFromErr") + .HasColumnType("smallint") + .HasColumnName("top_drive_speed_sp_from_err"); + + b.Property("TopDriveSpeedSpFromMax") + .HasColumnType("real") + .HasColumnName("top_drive_speed_sp_from_max"); + + b.Property("TopDriveSpeedSpFromMin") + .HasColumnType("real") + .HasColumnName("top_drive_speed_sp_from_min"); + + b.Property("TopDriveSpeedSpFromOffset") + .HasColumnType("real") + .HasColumnName("top_drive_speed_sp_from_offset"); + + b.Property("TopDriveSpeedSpTo") + .HasColumnType("real") + .HasColumnName("top_drive_speed_sp_to") + .HasComment("Задание скорости на СВП"); + + b.Property("TopDriveSpeedSpToErr") + .HasColumnType("smallint") + .HasColumnName("top_drive_speed_sp_to_err"); + + b.Property("TopDriveSpeedSpToMax") + .HasColumnType("real") + .HasColumnName("top_drive_speed_sp_to_max"); + + b.Property("TopDriveSpeedSpToMin") + .HasColumnType("real") + .HasColumnName("top_drive_speed_sp_to_min"); + + b.Property("TopDriveSpeedSpToOffset") + .HasColumnType("real") + .HasColumnName("top_drive_speed_sp_to_offset"); + + b.Property("TopDriveTorque") + .HasColumnType("real") + .HasColumnName("top_drive_torque") + .HasComment("Момент СВП"); + + b.Property("TopDriveTorqueErr") + .HasColumnType("smallint") + .HasColumnName("top_drive_torque_err"); + + b.Property("TopDriveTorqueMax") + .HasColumnType("real") + .HasColumnName("top_drive_torque_max"); + + b.Property("TopDriveTorqueMin") + .HasColumnType("real") + .HasColumnName("top_drive_torque_min"); + + b.Property("TopDriveTorqueOffset") + .HasColumnType("real") + .HasColumnName("top_drive_torque_offset"); + + b.Property("TopDriveTorqueSpFrom") + .HasColumnType("real") + .HasColumnName("top_drive_torque_sp_from") + .HasComment("Заданный момент c СВП"); + + b.Property("TopDriveTorqueSpFromErr") + .HasColumnType("smallint") + .HasColumnName("top_drive_torque_sp_from_err"); + + b.Property("TopDriveTorqueSpFromMax") + .HasColumnType("real") + .HasColumnName("top_drive_torque_sp_from_max"); + + b.Property("TopDriveTorqueSpFromMin") + .HasColumnType("real") + .HasColumnName("top_drive_torque_sp_from_min"); + + b.Property("TopDriveTorqueSpFromOffset") + .HasColumnType("real") + .HasColumnName("top_drive_torque_sp_from_offset"); + + b.Property("TopDriveTorqueSpTo") + .HasColumnType("real") + .HasColumnName("top_drive_torque_sp_to") + .HasComment("Задание момента на СВП"); + + b.Property("TopDriveTorqueSpToErr") + .HasColumnType("smallint") + .HasColumnName("top_drive_torque_sp_to_err"); + + b.Property("TopDriveTorqueSpToMax") + .HasColumnType("real") + .HasColumnName("top_drive_torque_sp_to_max"); + + b.Property("TopDriveTorqueSpToMin") + .HasColumnType("real") + .HasColumnName("top_drive_torque_sp_to_min"); + + b.Property("TopDriveTorqueSpToOffset") + .HasColumnType("real") + .HasColumnName("top_drive_torque_sp_to_offset"); + + b.Property("TorqueLeftLimit") + .HasColumnType("real") + .HasColumnName("torque_left_limit") + .HasComment("Ограничение крутящего момента влево"); + + b.Property("TorqueRampTime") + .HasColumnType("real") + .HasColumnName("torque_ramp_time") + .HasComment("Время нарастания момента"); + + b.Property("TorqueRightLimit") + .HasColumnType("real") + .HasColumnName("torque_right_limit") + .HasComment("Ограничение крутящего момента вправо"); + + b.Property("TorqueStarting") + .HasColumnType("real") + .HasColumnName("torque_starting") + .HasComment("Страгивающий момент"); + + b.Property("TurnLeftOnceByAngle") + .HasColumnType("real") + .HasColumnName("turn_left_once_by_angle") + .HasComment("Доворот по градусам единожды влево"); + + b.Property("TurnLeftOnceByRevols") + .HasColumnType("real") + .HasColumnName("turn_left_once_by_revols") + .HasComment("Доворот по оборотам единожды влево"); + + b.Property("TurnLeftOnceByTorque") + .HasColumnType("real") + .HasColumnName("turn_left_once_by_torque") + .HasComment("Доворот по моменту единожды влево"); + + b.Property("TurnRightOnceByAngle") + .HasColumnType("real") + .HasColumnName("turn_right_once_by_angle") + .HasComment("Доворот по градусам единожды вправо"); + + b.Property("TurnRightOnceByRevols") + .HasColumnType("real") + .HasColumnName("turn_right_once_by_revols") + .HasComment("Доворот по оборотам единожды вправо"); + + b.Property("TurnRightOnceByTorque") + .HasColumnType("real") + .HasColumnName("turn_right_once_by_torque") + .HasComment("Доворот по моменту единожды вправо"); + + b.Property("UnlockBySectorOut") + .HasColumnType("real") + .HasColumnName("unlock_by_sector_out") + .HasComment(" Градус отклонения от сектора для автоматического сброса блокировки"); + + b.Property("Ver") + .HasColumnType("real") + .HasColumnName("ver") + .HasComment("Версия ПО ПЛК"); + + b.Property("W2800") + .HasColumnType("smallint") + .HasColumnName("w2800") + .HasComment("Установка нуля энкодера"); + + b.Property("W2808") + .HasColumnType("smallint") + .HasColumnName("w2808") + .HasComment("Неисправность энкодера"); + + b.Property("W2810") + .HasColumnType("smallint") + .HasColumnName("w2810") + .HasComment(" автоматический сброс блокировки"); + + b.HasKey("IdTelemetry", "Date"); + + b.ToTable("t_telemetry_data_spin"); + + b.HasComment("набор основных данных по SpinMaster"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.TelemetryEvent", b => + { + b.Property("IdTelemetry") + .HasColumnType("integer") + .HasColumnName("id_telemetry"); + + b.Property("IdEvent") + .HasColumnType("integer") + .HasColumnName("id_event"); + + b.Property("IdCategory") + .HasColumnType("integer") + .HasColumnName("id_category"); + + b.Property("MessageTemplate") + .HasColumnType("text") + .HasColumnName("message_template"); + + b.HasKey("IdTelemetry", "IdEvent"); + + b.ToTable("t_telemetry_event"); + + b.HasComment("Справочник событий. События формируют сообщения. Разделено по версиям посылок от телеметрии."); + }); + + modelBuilder.Entity("AsbCloudDb.Model.TelemetryMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Arg0") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("arg0") + .HasComment("Аргумент №0 для вставки в шаблон сообщения"); + + b.Property("Arg1") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("arg1"); + + b.Property("Arg2") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("arg2"); + + b.Property("Arg3") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("arg3"); + + b.Property("Date") + .HasColumnType("timestamp with time zone") + .HasColumnName("date"); + + b.Property("IdEvent") + .HasColumnType("integer") + .HasColumnName("id_event"); + + b.Property("IdTelemetry") + .HasColumnType("integer") + .HasColumnName("id_telemetry"); + + b.Property("IdTelemetryUser") + .HasColumnType("integer") + .HasColumnName("id_telemetry_user") + .HasComment("Пользователь панели отправляющей телеметрию. не пользователь облака."); + + b.Property("WellDepth") + .HasColumnType("double precision") + .HasColumnName("well_depth"); + + b.HasKey("Id"); + + b.HasIndex("IdTelemetry"); + + b.ToTable("t_telemetry_message"); + + b.HasComment("Сообщения на буровых"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.TelemetryUser", b => + { + b.Property("IdTelemetry") + .HasColumnType("integer") + .HasColumnName("id_telemetry"); + + b.Property("IdUser") + .HasColumnType("integer") + .HasColumnName("id_user"); + + b.Property("Level") + .HasColumnType("integer") + .HasColumnName("level"); + + b.Property("Name") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name"); + + b.Property("Patronymic") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("patronymic"); + + b.Property("Surname") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("surname"); + + b.HasKey("IdTelemetry", "IdUser"); + + b.ToTable("t_telemetry_user"); + + b.HasComment("Пользователи панели САУБ. Для сообщений."); + }); + + modelBuilder.Entity("AsbCloudDb.Model.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Email") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("email") + .HasComment("должность"); + + b.Property("IdCompany") + .HasColumnType("integer") + .HasColumnName("id_company"); + + b.Property("IdState") + .HasColumnType("smallint") + .HasColumnName("state") + .HasComment("состояние:\n100 - удален"); + + b.Property("Login") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("login"); + + b.Property("Name") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name") + .HasComment("имя"); + + b.Property("PasswordHash") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("password_hash") + .HasComment("соленый хэш пароля.\nпервые 5 символов - соль"); + + b.Property("Patronymic") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("patronymic") + .HasComment("отчество"); + + b.Property("Phone") + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("phone") + .HasComment("номер телефона"); + + b.Property("Position") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("position") + .HasComment("email"); + + b.Property("Surname") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("surname") + .HasComment("фамилия"); + + b.HasKey("Id"); + + b.HasIndex("IdCompany"); + + b.HasIndex("Login") + .IsUnique(); + + b.ToTable("t_user"); + + b.HasComment("Пользователи облака"); + + b.HasData( + new + { + Id = 1, + IdCompany = 1, + Login = "dev", + Name = "Разработчик", + PasswordHash = "Vlcj|4fa529103dde7ff72cfe76185f344d4aa87931f8e1b2044e8a7739947c3d18923464eaad93843e4f809c5e126d013072" + }); + }); + + modelBuilder.Entity("AsbCloudDb.Model.UserRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Caption") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("caption") + .HasComment("Название"); + + b.Property("IdParent") + .HasColumnType("integer") + .HasColumnName("id_parent") + .HasComment("От какой роли унаследована данная роль"); + + b.Property("IdType") + .HasColumnType("integer") + .HasColumnName("id_type") + .HasComment("0-роль из стандартной матрицы, \n1-специальная роль для какого-либо пользователя"); + + b.HasKey("Id"); + + b.ToTable("t_user_role"); + + b.HasComment("Роли пользователей в системе"); + + b.HasData( + new + { + Id = 1, + Caption = "Администратор", + IdType = 0 + }, + new + { + Id = 2, + Caption = "Пользователь", + IdType = 0 + }); + }); + + modelBuilder.Entity("AsbCloudDb.Model.Well", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Caption") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("caption"); + + b.Property("IdCluster") + .HasColumnType("integer") + .HasColumnName("id_cluster"); + + b.Property("IdState") + .HasColumnType("integer") + .HasColumnName("state") + .HasComment("0 - неизвестно, 1 - в работе, 2 - завершена"); + + b.Property("IdTelemetry") + .HasColumnType("integer") + .HasColumnName("id_telemetry"); + + b.Property("IdWellType") + .HasColumnType("integer") + .HasColumnName("id_well_type"); + + b.Property("Latitude") + .HasColumnType("double precision") + .HasColumnName("latitude"); + + b.Property("Longitude") + .HasColumnType("double precision") + .HasColumnName("longitude"); + + b.Property("Timezone") + .HasColumnType("jsonb") + .HasColumnName("timezone") + .HasComment("Смещение часового пояса от UTC"); + + b.HasKey("Id"); + + b.HasIndex("IdCluster"); + + b.HasIndex("IdTelemetry") + .IsUnique(); + + b.HasIndex("IdWellType"); + + b.ToTable("t_well"); + + b.HasComment("скважины"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.WellComposite", b => + { + b.Property("IdWell") + .HasColumnType("integer") + .HasColumnName("id_well") + .HasComment("Id скважины получателя"); + + b.Property("IdWellSrc") + .HasColumnType("integer") + .HasColumnName("id_well_src") + .HasComment("Id скважины композита"); + + b.Property("IdWellSectionType") + .HasColumnType("integer") + .HasColumnName("id_well_section_type") + .HasComment("Id тип секции композита"); + + b.HasKey("IdWell", "IdWellSrc", "IdWellSectionType"); + + b.HasIndex("IdWellSectionType"); + + b.HasIndex("IdWellSrc"); + + b.ToTable("t_well_composite"); + + b.HasComment("Композитная скважина"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.WellOperation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CategoryInfo") + .HasColumnType("text") + .HasColumnName("category_info") + .HasComment("Доп. информация к выбраной категории"); + + b.Property("Comment") + .HasColumnType("text") + .HasColumnName("comment") + .HasComment("Комментарий"); + + b.Property("DateStart") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_start") + .HasComment("Дата начала операции"); + + b.Property("DepthEnd") + .HasColumnType("double precision") + .HasColumnName("depth_end") + .HasComment("Глубина после завершения операции, м"); + + b.Property("DepthStart") + .HasColumnType("double precision") + .HasColumnName("depth_start") + .HasComment("Глубина на начало операции, м"); + + b.Property("DurationHours") + .HasColumnType("double precision") + .HasColumnName("duration_hours") + .HasComment("Продолжительность, часы"); + + b.Property("IdCategory") + .HasColumnType("integer") + .HasColumnName("id_category") + .HasComment("Id категории операции"); + + b.Property("IdType") + .HasColumnType("integer") + .HasColumnName("id_type") + .HasComment("0 = План или 1 = Факт"); + + b.Property("IdWell") + .HasColumnType("integer") + .HasColumnName("id_well") + .HasComment("Id скважины"); + + b.Property("IdWellSectionType") + .HasColumnType("integer") + .HasColumnName("id_well_section_type") + .HasComment("Id тип секции скважины"); + + b.HasKey("Id"); + + b.HasIndex("DateStart"); + + b.HasIndex("DepthEnd"); + + b.HasIndex("IdCategory"); + + b.HasIndex("IdWell"); + + b.HasIndex("IdWellSectionType"); + + b.ToTable("t_well_operation"); + + b.HasComment("Данные по операциям на скважине"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.WellOperationCategory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Code") + .HasColumnType("integer") + .HasColumnName("code") + .HasComment("Код операции"); + + b.Property("Name") + .HasColumnType("text") + .HasColumnName("name") + .HasComment("Название категории операции"); + + b.HasKey("Id"); + + b.ToTable("t_well_operation_category"); + + b.HasComment("Справочник операций на скважине"); + + b.HasData( + new + { + Id = 1, + Code = 0, + Name = "Невозможно определить операцию" + }, + new + { + Id = 2, + Code = 0, + Name = "Роторное бурение" + }, + new + { + Id = 3, + Code = 0, + Name = "Слайдирование" + }, + new + { + Id = 4, + Code = 0, + Name = "Подъем с проработкой" + }, + new + { + Id = 5, + Code = 0, + Name = "Спуск с проработкой" + }, + new + { + Id = 6, + Code = 0, + Name = "Подъем с промывкой" + }, + new + { + Id = 7, + Code = 0, + Name = "Спуск с промывкой" + }, + new + { + Id = 8, + Code = 0, + Name = "Спуск в скважину" + }, + new + { + Id = 9, + Code = 0, + Name = "Спуск с вращением" + }, + new + { + Id = 10, + Code = 0, + Name = "Подъем из скважины" + }, + new + { + Id = 11, + Code = 0, + Name = "Подъем с вращением" + }, + new + { + Id = 12, + Code = 0, + Name = "Промывка в покое" + }, + new + { + Id = 13, + Code = 0, + Name = "Промывка с вращением" + }, + new + { + Id = 14, + Code = 0, + Name = "Удержание в клиньях" + }, + new + { + Id = 15, + Code = 0, + Name = "Неподвижное состояние" + }, + new + { + Id = 16, + Code = 0, + Name = "Вращение без циркуляции" + }, + new + { + Id = 17, + Code = 0, + Name = "На поверхности" + }, + new + { + Id = 1001, + Code = 0, + Name = "Бурение" + }, + new + { + Id = 1002, + Code = 0, + Name = "ГИС" + }, + new + { + Id = 1003, + Code = 0, + Name = "ГФР" + }, + new + { + Id = 1004, + Code = 0, + Name = "Монтаж ПВО" + }, + new + { + Id = 1005, + Code = 0, + Name = "Демонтаж ПВО" + }, + new + { + Id = 1006, + Code = 0, + Name = "Установка ФА" + }, + new + { + Id = 1007, + Code = 0, + Name = "Оборудование устья" + }, + new + { + Id = 1008, + Code = 0, + Name = "ОЗЦ" + }, + new + { + Id = 1011, + Code = 0, + Name = "Начало цикла строительства скважины" + }, + new + { + Id = 1012, + Code = 0, + Name = "Окончание цикла строительства скважины" + }, + new + { + Id = 1013, + Code = 0, + Name = "Опрессовка ПВО" + }, + new + { + Id = 1014, + Code = 0, + Name = "Опрессовка Ц.К." + }, + new + { + Id = 1015, + Code = 0, + Name = "Опрессовка ВЗД" + }, + new + { + Id = 1016, + Code = 0, + Name = "Перевод скв на другой тип промывочной жидкости" + }, + new + { + Id = 1017, + Code = 0, + Name = "Перезапись каротажа" + }, + new + { + Id = 1018, + Code = 0, + Name = "Перетяжка талевого каната" + }, + new + { + Id = 1019, + Code = 0, + Name = "Наращивание, промывка" + }, + new + { + Id = 1020, + Code = 0, + Name = "Подъем инструмента" + }, + new + { + Id = 1021, + Code = 0, + Name = "Подъем инструмента с промывкой" + }, + new + { + Id = 1022, + Code = 0, + Name = "Обратная проработка" + }, + new + { + Id = 1023, + Code = 0, + Name = "Сборка инструмента с мостков" + }, + new + { + Id = 1024, + Code = 0, + Name = "Подготовительные работы" + }, + new + { + Id = 1025, + Code = 0, + Name = "Сборка КНБК" + }, + new + { + Id = 1026, + Code = 0, + Name = "Разборка КНБК" + }, + new + { + Id = 1027, + Code = 0, + Name = "Промывка" + }, + new + { + Id = 1028, + Code = 0, + Name = "Промежуточная промывка" + }, + new + { + Id = 1029, + Code = 0, + Name = "Прокачка пачек" + }, + new + { + Id = 1030, + Code = 0, + Name = "Разбуривание тех.оснастки" + }, + new + { + Id = 1031, + Code = 0, + Name = "Ремонт" + }, + new + { + Id = 1032, + Code = 0, + Name = "Спуск инструмента" + }, + new + { + Id = 1033, + Code = 0, + Name = "Спуск инструмента с промывкой" + }, + new + { + Id = 1034, + Code = 0, + Name = "Прямая проработка" + }, + new + { + Id = 1035, + Code = 0, + Name = "Принудительная проработка" + }, + new + { + Id = 1037, + Code = 0, + Name = "Тех СПО-подъем" + }, + new + { + Id = 1038, + Code = 0, + Name = "Тех СПО-спуск" + }, + new + { + Id = 1039, + Code = 0, + Name = "Техническое обслуживание" + }, + new + { + Id = 1040, + Code = 0, + Name = "Цементаж" + }, + new + { + Id = 1041, + Code = 0, + Name = "Шаблонировка ствола" + }, + new + { + Id = 1042, + Code = 0, + Name = "Геологическое осложнение" + }, + new + { + Id = 1043, + Code = 0, + Name = "НПВ" + }, + new + { + Id = 1044, + Code = 0, + Name = "ВМР" + }, + new + { + Id = 1045, + Code = 0, + Name = "Прочее" + }, + new + { + Id = 1046, + Code = 0, + Name = "Спуск КНБК" + }, + new + { + Id = 1047, + Code = 0, + Name = "Подъем КНБК" + }, + new + { + Id = 1048, + Code = 0, + Name = "Спуск ОК" + }, + new + { + Id = 1050, + Code = 0, + Name = "Промывка при спуске ОК" + }, + new + { + Id = 1051, + Code = 0, + Name = "Замер ТС" + }, + new + { + Id = 1052, + Code = 0, + Name = "Тех. отстой" + }, + new + { + Id = 1053, + Code = 0, + Name = "Циркуляция и Обработка БР" + }, + new + { + Id = 1054, + Code = 0, + Name = "Срезка ствола" + }, + new + { + Id = 1055, + Code = 0, + Name = "Вспомогательные работы" + }); + }); + + modelBuilder.Entity("AsbCloudDb.Model.WellSectionType", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Caption") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("caption") + .HasComment("Название"); + + b.HasKey("Id"); + + b.ToTable("t_well_section_type"); + + b.HasComment("конструкция секции скважины"); + + b.HasData( + new + { + Id = 1, + Caption = "Пилотный ствол" + }, + new + { + Id = 2, + Caption = "Направление" + }, + new + { + Id = 3, + Caption = "Кондуктор" + }, + new + { + Id = 4, + Caption = "Эксплуатационная колонна" + }, + new + { + Id = 5, + Caption = "Транспортный ствол" + }, + new + { + Id = 6, + Caption = "Хвостовик" + }, + new + { + Id = 7, + Caption = "Пилотный ствол 2" + }, + new + { + Id = 8, + Caption = "Направление 2" + }, + new + { + Id = 9, + Caption = "Кондуктор 2" + }, + new + { + Id = 10, + Caption = "Эксплуатационная колонна 2" + }, + new + { + Id = 11, + Caption = "Транспортный ствол 2" + }, + new + { + Id = 12, + Caption = "Хвостовик 2" + }, + new + { + Id = 13, + Caption = "Пилотный ствол 3" + }, + new + { + Id = 14, + Caption = "Направление 3" + }, + new + { + Id = 15, + Caption = "Кондуктор 3" + }, + new + { + Id = 16, + Caption = "Эксплуатационная колонна 3" + }, + new + { + Id = 17, + Caption = "Транспортный ствол 3" + }, + new + { + Id = 18, + Caption = "Хвостовик 3" + }, + new + { + Id = 19, + Caption = "Пилотный ствол 4" + }, + new + { + Id = 20, + Caption = "Направление 4" + }, + new + { + Id = 21, + Caption = "Кондуктор 4" + }, + new + { + Id = 22, + Caption = "Эксплуатационная колонна 4" + }, + new + { + Id = 23, + Caption = "Транспортный ствол 4" + }, + new + { + Id = 24, + Caption = "Хвостовик 4" + }, + new + { + Id = 25, + Caption = "Пилотный ствол 5" + }, + new + { + Id = 26, + Caption = "Направление 5" + }, + new + { + Id = 27, + Caption = "Кондуктор 5" + }, + new + { + Id = 28, + Caption = "Эксплуатационная колонна 5" + }, + new + { + Id = 29, + Caption = "Транспортный ствол 5" + }, + new + { + Id = 30, + Caption = "Хвостовик 5" + }); + }); + + modelBuilder.Entity("AsbCloudDb.Model.WellType", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Caption") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("caption") + .HasComment("Название"); + + b.HasKey("Id"); + + b.ToTable("t_well_type"); + + b.HasComment("конструкция скважины"); + + b.HasData( + new + { + Id = 1, + Caption = "Наклонно-направленная" + }, + new + { + Id = 2, + Caption = "Горизонтальная" + }); + }); + + modelBuilder.Entity("AsbCloudDb.Model.Cluster", b => + { + b.HasOne("AsbCloudDb.Model.Deposit", "Deposit") + .WithMany("Clusters") + .HasForeignKey("IdDeposit") + .HasConstraintName("t_cluster_t_deposit_id_fk"); + + b.Navigation("Deposit"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.Company", b => + { + b.HasOne("AsbCloudDb.Model.CompanyType", "CompanyType") + .WithMany("Companies") + .HasForeignKey("IdCompanyType") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("CompanyType"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.DrillFlowChart", b => + { + b.HasOne("AsbCloudDb.Model.Well", "Well") + .WithMany() + .HasForeignKey("IdWell") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Well"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.DrillParams", b => + { + b.HasOne("AsbCloudDb.Model.Well", "Well") + .WithMany() + .HasForeignKey("IdWell") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AsbCloudDb.Model.WellSectionType", "WellSectionType") + .WithMany("DrillParamsCollection") + .HasForeignKey("IdWellSectionType") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("t_drill_params_t_well_section_type_id_fk"); + + b.Navigation("Well"); + + b.Navigation("WellSectionType"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.FileInfo", b => + { + b.HasOne("AsbCloudDb.Model.User", "Author") + .WithMany("Files") + .HasForeignKey("IdAuthor"); + + b.HasOne("AsbCloudDb.Model.FileCategory", "FileCategory") + .WithMany() + .HasForeignKey("IdCategory") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AsbCloudDb.Model.Well", "Well") + .WithMany() + .HasForeignKey("IdWell") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Author"); + + b.Navigation("FileCategory"); + + b.Navigation("Well"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.FileMark", b => + { + b.HasOne("AsbCloudDb.Model.FileInfo", "FileInfo") + .WithMany("FileMarks") + .HasForeignKey("IdFile") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("t_file_mark_t_file_info_fk"); + + b.HasOne("AsbCloudDb.Model.User", "User") + .WithMany("FileMarks") + .HasForeignKey("IdUser") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("t_user_t_file_mark_fk"); + + b.Navigation("FileInfo"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.Measure", b => + { + b.HasOne("AsbCloudDb.Model.MeasureCategory", "Category") + .WithMany("Measures") + .HasForeignKey("IdCategory") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AsbCloudDb.Model.Well", "Well") + .WithMany() + .HasForeignKey("IdWell") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Category"); + + b.Navigation("Well"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.RelationCompanyWell", b => + { + b.HasOne("AsbCloudDb.Model.Company", "Company") + .WithMany("RelationCompaniesWells") + .HasForeignKey("IdCompany") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("t_relation_company_well_t_company_id_fk"); + + b.HasOne("AsbCloudDb.Model.Well", "Well") + .WithMany("RelationCompaniesWells") + .HasForeignKey("IdWell") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("t_relation_company_well_t_well_id_fk"); + + b.Navigation("Company"); + + b.Navigation("Well"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.RelationUserRolePermission", b => + { + b.HasOne("AsbCloudDb.Model.Permission", "Permission") + .WithMany("RelationUserRolePermissions") + .HasForeignKey("IdPermission") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AsbCloudDb.Model.UserRole", "UserRole") + .WithMany("RelationUserRolePermissions") + .HasForeignKey("IdUserRole") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("UserRole"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.RelationUserUserRole", b => + { + b.HasOne("AsbCloudDb.Model.User", "User") + .WithMany("RelationUsersUserRoles") + .HasForeignKey("IdUser") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AsbCloudDb.Model.UserRole", "UserRole") + .WithMany("RelationUsersUserRoles") + .HasForeignKey("IdUserRole") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + + b.Navigation("UserRole"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.ReportProperty", b => + { + b.HasOne("AsbCloudDb.Model.FileInfo", "File") + .WithMany() + .HasForeignKey("IdFile") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AsbCloudDb.Model.Well", "Well") + .WithMany() + .HasForeignKey("IdWell") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("File"); + + b.Navigation("Well"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.SetpointsRequest", b => + { + b.HasOne("AsbCloudDb.Model.User", "Author") + .WithMany() + .HasForeignKey("IdAuthor") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AsbCloudDb.Model.Well", "Well") + .WithMany() + .HasForeignKey("IdWell") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Author"); + + b.Navigation("Well"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.TelemetryAnalysis", b => + { + b.HasOne("AsbCloudDb.Model.WellOperationCategory", "Operation") + .WithMany("Analysis") + .HasForeignKey("IdOperation") + .OnDelete(DeleteBehavior.SetNull) + .IsRequired() + .HasConstraintName("t_analysis_t_operation_id_fk"); + + b.HasOne("AsbCloudDb.Model.Telemetry", "Telemetry") + .WithMany("Analysis") + .HasForeignKey("IdTelemetry") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("t_analysis_t_telemetry_id_fk"); + + b.Navigation("Operation"); + + b.Navigation("Telemetry"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.TelemetryDataSaub", b => + { + b.HasOne("AsbCloudDb.Model.Telemetry", "Telemetry") + .WithMany("DataSaub") + .HasForeignKey("IdTelemetry") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("t_telemetry_data_saub_t_telemetry_id_fk"); + + b.Navigation("Telemetry"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.TelemetryDataSpin", b => + { + b.HasOne("AsbCloudDb.Model.Telemetry", "Telemetry") + .WithMany("DataSpin") + .HasForeignKey("IdTelemetry") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("t_telemetry_data_spin_t_telemetry_id_fk"); + + b.Navigation("Telemetry"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.TelemetryEvent", b => + { + b.HasOne("AsbCloudDb.Model.Telemetry", "Telemetry") + .WithMany("Events") + .HasForeignKey("IdTelemetry") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("t_event_t_telemetry_id_fk"); + + b.Navigation("Telemetry"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.TelemetryMessage", b => + { + b.HasOne("AsbCloudDb.Model.Telemetry", "Telemetry") + .WithMany("Messages") + .HasForeignKey("IdTelemetry") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("t_messages_t_telemetry_id_fk"); + + b.Navigation("Telemetry"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.TelemetryUser", b => + { + b.HasOne("AsbCloudDb.Model.Telemetry", "Telemetry") + .WithMany("Users") + .HasForeignKey("IdTelemetry") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("t_telemetry_user_t_telemetry_id_fk"); + + b.Navigation("Telemetry"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.User", b => + { + b.HasOne("AsbCloudDb.Model.Company", "Company") + .WithMany("Users") + .HasForeignKey("IdCompany") + .OnDelete(DeleteBehavior.SetNull) + .HasConstraintName("t_user_t_company_id_fk"); + + b.Navigation("Company"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.Well", b => + { + b.HasOne("AsbCloudDb.Model.Cluster", "Cluster") + .WithMany("Wells") + .HasForeignKey("IdCluster") + .HasConstraintName("t_well_t_cluster_id_fk"); + + b.HasOne("AsbCloudDb.Model.Telemetry", "Telemetry") + .WithOne("Well") + .HasForeignKey("AsbCloudDb.Model.Well", "IdTelemetry") + .OnDelete(DeleteBehavior.SetNull) + .HasConstraintName("t_well_t_telemetry_id_fk"); + + b.HasOne("AsbCloudDb.Model.WellType", "WellType") + .WithMany("Wells") + .HasForeignKey("IdWellType"); + + b.Navigation("Cluster"); + + b.Navigation("Telemetry"); + + b.Navigation("WellType"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.WellComposite", b => + { + b.HasOne("AsbCloudDb.Model.Well", "Well") + .WithMany("WellComposites") + .HasForeignKey("IdWell") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("t_well_сomposite_t_well_id_fk"); + + b.HasOne("AsbCloudDb.Model.WellSectionType", "WellSectionType") + .WithMany("WellComposites") + .HasForeignKey("IdWellSectionType") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("t_well_сomposite_t_well_section_type_id_fk"); + + b.HasOne("AsbCloudDb.Model.Well", "WellSrc") + .WithMany("WellCompositeSrcs") + .HasForeignKey("IdWellSrc") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("t_well_сomposite_src_t_well_id_fk"); + + b.Navigation("Well"); + + b.Navigation("WellSectionType"); + + b.Navigation("WellSrc"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.WellOperation", b => + { + b.HasOne("AsbCloudDb.Model.WellOperationCategory", "OperationCategory") + .WithMany() + .HasForeignKey("IdCategory") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AsbCloudDb.Model.Well", "Well") + .WithMany("WellOperations") + .HasForeignKey("IdWell") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AsbCloudDb.Model.WellSectionType", "WellSectionType") + .WithMany("WellOperations") + .HasForeignKey("IdWellSectionType") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("OperationCategory"); + + b.Navigation("Well"); + + b.Navigation("WellSectionType"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.Cluster", b => + { + b.Navigation("Wells"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.Company", b => + { + b.Navigation("RelationCompaniesWells"); + + b.Navigation("Users"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.CompanyType", b => + { + b.Navigation("Companies"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.Deposit", b => + { + b.Navigation("Clusters"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.FileInfo", b => + { + b.Navigation("FileMarks"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.MeasureCategory", b => + { + b.Navigation("Measures"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.Permission", b => + { + b.Navigation("RelationUserRolePermissions"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.Telemetry", b => + { + b.Navigation("Analysis"); + + b.Navigation("DataSaub"); + + b.Navigation("DataSpin"); + + b.Navigation("Events"); + + b.Navigation("Messages"); + + b.Navigation("Users"); + + b.Navigation("Well"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.User", b => + { + b.Navigation("FileMarks"); + + b.Navigation("Files"); + + b.Navigation("RelationUsersUserRoles"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.UserRole", b => + { + b.Navigation("RelationUserRolePermissions"); + + b.Navigation("RelationUsersUserRoles"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.Well", b => + { + b.Navigation("RelationCompaniesWells"); + + b.Navigation("WellCompositeSrcs"); + + b.Navigation("WellComposites"); + + b.Navigation("WellOperations"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.WellOperationCategory", b => + { + b.Navigation("Analysis"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.WellSectionType", b => + { + b.Navigation("DrillParamsCollection"); + + b.Navigation("WellComposites"); + + b.Navigation("WellOperations"); + }); + + modelBuilder.Entity("AsbCloudDb.Model.WellType", b => + { + b.Navigation("Wells"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/AsbCloudDb/Migrations/20220105123412_Fix_Spelling.cs b/AsbCloudDb/Migrations/20220105123412_Fix_Spelling.cs new file mode 100644 index 00000000..213ac96b --- /dev/null +++ b/AsbCloudDb/Migrations/20220105123412_Fix_Spelling.cs @@ -0,0 +1,177 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace AsbCloudDb.Migrations +{ + public partial class Fix_Spelling : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterTable( + name: "t_drill_flow_chart", + comment: "Параметры коридоров бурения (диапазоны параметров бурения)", + oldComment: "Параметры корридоров бурения (диапазоны параметров бурения)"); + + migrationBuilder.AlterColumn( + name: "torque_starting", + table: "t_telemetry_data_spin", + type: "real", + nullable: true, + comment: "Страгивающий момент", + oldClrType: typeof(float), + oldType: "real", + oldNullable: true, + oldComment: " Страгивающий момент"); + + migrationBuilder.AlterColumn( + name: "rotor_torque_avg", + table: "t_telemetry_data_spin", + type: "real", + nullable: true, + comment: "Момент в роторе средний", + oldClrType: typeof(float), + oldType: "real", + oldNullable: true, + oldComment: " Момент в роторе средний"); + + migrationBuilder.AlterColumn( + name: "ratio", + table: "t_telemetry_data_spin", + type: "real", + nullable: true, + comment: " Коэффициент редукции редуктора", + oldClrType: typeof(float), + oldType: "real", + oldNullable: true, + oldComment: " Коэффициент редукции редектора"); + + migrationBuilder.AlterColumn( + name: "position_zero", + table: "t_telemetry_data_spin", + type: "real", + nullable: true, + comment: "Нулевая позиция осцилляции", + oldClrType: typeof(float), + oldType: "real", + oldNullable: true, + oldComment: "Нулевая позиция осциляции"); + + migrationBuilder.AlterColumn( + name: "position_right", + table: "t_telemetry_data_spin", + type: "real", + nullable: true, + comment: "Крайний правый угол осцилляции", + oldClrType: typeof(float), + oldType: "real", + oldNullable: true, + oldComment: "Крайний правый угол осциляции"); + + migrationBuilder.AlterColumn( + name: "encoder_resolution", + table: "t_telemetry_data_spin", + type: "real", + nullable: true, + comment: "Разрешение энкодера", + oldClrType: typeof(float), + oldType: "real", + oldNullable: true, + oldComment: " Разрешение энкодера"); + + migrationBuilder.AlterColumn( + name: "is_pressure_gt_20", + table: "t_telemetry_analysis", + type: "boolean", + nullable: false, + comment: "Давление более 20", + oldClrType: typeof(bool), + oldType: "boolean", + oldComment: "Давоение более 20"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterTable( + name: "t_drill_flow_chart", + comment: "Параметры корридоров бурения (диапазоны параметров бурения)", + oldComment: "Параметры коридоров бурения (диапазоны параметров бурения)"); + + migrationBuilder.AlterColumn( + name: "torque_starting", + table: "t_telemetry_data_spin", + type: "real", + nullable: true, + comment: " Страгивающий момент", + oldClrType: typeof(float), + oldType: "real", + oldNullable: true, + oldComment: "Страгивающий момент"); + + migrationBuilder.AlterColumn( + name: "rotor_torque_avg", + table: "t_telemetry_data_spin", + type: "real", + nullable: true, + comment: " Момент в роторе средний", + oldClrType: typeof(float), + oldType: "real", + oldNullable: true, + oldComment: "Момент в роторе средний"); + + migrationBuilder.AlterColumn( + name: "ratio", + table: "t_telemetry_data_spin", + type: "real", + nullable: true, + comment: " Коэффициент редукции редектора", + oldClrType: typeof(float), + oldType: "real", + oldNullable: true, + oldComment: " Коэффициент редукции редуктора"); + + migrationBuilder.AlterColumn( + name: "position_zero", + table: "t_telemetry_data_spin", + type: "real", + nullable: true, + comment: "Нулевая позиция осциляции", + oldClrType: typeof(float), + oldType: "real", + oldNullable: true, + oldComment: "Нулевая позиция осцилляции"); + + migrationBuilder.AlterColumn( + name: "position_right", + table: "t_telemetry_data_spin", + type: "real", + nullable: true, + comment: "Крайний правый угол осциляции", + oldClrType: typeof(float), + oldType: "real", + oldNullable: true, + oldComment: "Крайний правый угол осцилляции"); + + migrationBuilder.AlterColumn( + name: "encoder_resolution", + table: "t_telemetry_data_spin", + type: "real", + nullable: true, + comment: " Разрешение энкодера", + oldClrType: typeof(float), + oldType: "real", + oldNullable: true, + oldComment: "Разрешение энкодера"); + + migrationBuilder.AlterColumn( + name: "is_pressure_gt_20", + table: "t_telemetry_analysis", + type: "boolean", + nullable: false, + comment: "Давоение более 20", + oldClrType: typeof(bool), + oldType: "boolean", + oldComment: "Давление более 20"); + } + } +} diff --git a/AsbCloudDb/Migrations/AsbCloudDbContextModelSnapshot.cs b/AsbCloudDb/Migrations/AsbCloudDbContextModelSnapshot.cs index 5275136b..02e9b53d 100644 --- a/AsbCloudDb/Migrations/AsbCloudDbContextModelSnapshot.cs +++ b/AsbCloudDb/Migrations/AsbCloudDbContextModelSnapshot.cs @@ -52,7 +52,7 @@ namespace AsbCloudDb.Migrations .HasColumnType("double precision") .HasColumnName("longitude"); - b.Property("TimeZone") + b.Property("Timezone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); @@ -159,7 +159,7 @@ namespace AsbCloudDb.Migrations .HasColumnType("double precision") .HasColumnName("longitude"); - b.Property("TimeZone") + b.Property("Timezone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); @@ -263,7 +263,7 @@ namespace AsbCloudDb.Migrations b.ToTable("t_drill_flow_chart"); - b.HasComment("Параметры корридоров бурения (диапазоны параметров бурения)"); + b.HasComment("Параметры коридоров бурения (диапазоны параметров бурения)"); }); modelBuilder.Entity("AsbCloudDb.Model.DrillParams", b => @@ -904,7 +904,7 @@ namespace AsbCloudDb.Migrations .HasColumnName("remote_uid") .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); - b.Property("TimeZone") + b.Property("TimeZone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); @@ -978,7 +978,7 @@ namespace AsbCloudDb.Migrations b.Property("IsPressureGt20") .HasColumnType("boolean") .HasColumnName("is_pressure_gt_20") - .HasComment("Давоение более 20"); + .HasComment("Давление более 20"); b.Property("IsPressureLt20") .HasColumnType("boolean") @@ -1253,7 +1253,7 @@ namespace AsbCloudDb.Migrations b.Property("EncoderResolution") .HasColumnType("real") .HasColumnName("encoder_resolution") - .HasComment(" Разрешение энкодера"); + .HasComment("Разрешение энкодера"); b.Property("Mode") .HasColumnType("smallint") @@ -1268,17 +1268,17 @@ namespace AsbCloudDb.Migrations b.Property("PositionRight") .HasColumnType("real") .HasColumnName("position_right") - .HasComment("Крайний правый угол осциляции"); + .HasComment("Крайний правый угол осцилляции"); b.Property("PositionZero") .HasColumnType("real") .HasColumnName("position_zero") - .HasComment("Нулевая позиция осциляции"); + .HasComment("Нулевая позиция осцилляции"); b.Property("Ratio") .HasColumnType("real") .HasColumnName("ratio") - .HasComment(" Коэффициент редукции редектора"); + .HasComment(" Коэффициент редукции редуктора"); b.Property("ReverseKTorque") .HasColumnType("real") @@ -1313,7 +1313,7 @@ namespace AsbCloudDb.Migrations b.Property("RotorTorqueAvg") .HasColumnType("real") .HasColumnName("rotor_torque_avg") - .HasComment(" Момент в роторе средний"); + .HasComment("Момент в роторе средний"); b.Property("SpeedLeftSp") .HasColumnType("real") @@ -1477,7 +1477,7 @@ namespace AsbCloudDb.Migrations b.Property("TorqueStarting") .HasColumnType("real") .HasColumnName("torque_starting") - .HasComment(" Страгивающий момент"); + .HasComment("Страгивающий момент"); b.Property("TurnLeftOnceByAngle") .HasColumnType("real") @@ -1834,7 +1834,7 @@ namespace AsbCloudDb.Migrations .HasColumnType("double precision") .HasColumnName("longitude"); - b.Property("TimeZone") + b.Property("Timezone") .HasColumnType("jsonb") .HasColumnName("timezone") .HasComment("Смещение часового пояса от UTC"); diff --git a/AsbCloudDb/Model/Cluster.cs b/AsbCloudDb/Model/Cluster.cs index 1115319f..3cc7ffcc 100644 --- a/AsbCloudDb/Model/Cluster.cs +++ b/AsbCloudDb/Model/Cluster.cs @@ -40,6 +40,6 @@ namespace AsbCloudDb.Model public double? Longitude { get; set; } [Column("timezone", TypeName = "jsonb"), Comment("Смещение часового пояса от UTC")] - public SimpleTimeZone TimeZone { get; set; } + public SimpleTimezone Timezone { get; set; } } } diff --git a/AsbCloudDb/Model/Deposit.cs b/AsbCloudDb/Model/Deposit.cs index 08a083ba..95488c16 100644 --- a/AsbCloudDb/Model/Deposit.cs +++ b/AsbCloudDb/Model/Deposit.cs @@ -33,6 +33,6 @@ namespace AsbCloudDb.Model public double? Longitude { get; set; } [Column("timezone", TypeName = "jsonb"), Comment("Смещение часового пояса от UTC")] - public SimpleTimeZone TimeZone { get; set; } + public SimpleTimezone Timezone { get; set; } } } diff --git a/AsbCloudDb/Model/DrillFlowChart.cs b/AsbCloudDb/Model/DrillFlowChart.cs index 4fa0b78f..72535aa2 100644 --- a/AsbCloudDb/Model/DrillFlowChart.cs +++ b/AsbCloudDb/Model/DrillFlowChart.cs @@ -6,7 +6,7 @@ using System.Text.Json.Serialization; namespace AsbCloudDb.Model { - [Table("t_drill_flow_chart"), Comment("Параметры корридоров бурения (диапазоны параметров бурения)")] + [Table("t_drill_flow_chart"), Comment("Параметры коридоров бурения (диапазоны параметров бурения)")] public class DrillFlowChart : IId { [Key] diff --git a/AsbCloudDb/Model/IMapPoint.cs b/AsbCloudDb/Model/IMapPoint.cs index 31c6a0e7..a4083a3a 100644 --- a/AsbCloudDb/Model/IMapPoint.cs +++ b/AsbCloudDb/Model/IMapPoint.cs @@ -6,6 +6,6 @@ double? Longitude { get; set; } - SimpleTimeZone TimeZone { get; set; } + SimpleTimezone Timezone { get; set; } } } diff --git a/AsbCloudDb/Model/SimpleTimeZone.cs b/AsbCloudDb/Model/SimpleTimeZone.cs index f99c01c3..7d7d693e 100644 --- a/AsbCloudDb/Model/SimpleTimeZone.cs +++ b/AsbCloudDb/Model/SimpleTimeZone.cs @@ -1,6 +1,6 @@ namespace AsbCloudDb.Model { - public class SimpleTimeZone + public class SimpleTimezone { public double Hours { get; set; } public string TimeZoneId { get; set; } diff --git a/AsbCloudDb/Model/Telemetry.cs b/AsbCloudDb/Model/Telemetry.cs index a1f41d97..de598306 100644 --- a/AsbCloudDb/Model/Telemetry.cs +++ b/AsbCloudDb/Model/Telemetry.cs @@ -28,7 +28,7 @@ namespace AsbCloudDb.Model public TelemetryInfo Info { get; set; } [Column("timezone", TypeName = "jsonb"), Comment("Смещение часового пояса от UTC")] - public SimpleTimeZone TimeZone { get; set; } + public SimpleTimezone TimeZone { get; set; } [InverseProperty(nameof(Model.Well.Telemetry))] public virtual Well Well { get; set; } diff --git a/AsbCloudDb/Model/TelemetryAnalysis.cs b/AsbCloudDb/Model/TelemetryAnalysis.cs index 28d4918f..81230c30 100644 --- a/AsbCloudDb/Model/TelemetryAnalysis.cs +++ b/AsbCloudDb/Model/TelemetryAnalysis.cs @@ -71,7 +71,7 @@ namespace AsbCloudDb.Model [Column("is_pressure_lt_20"), Comment("Давление менее 20")] public bool IsPressureLt20 { get; set; } - [Column("is_pressure_gt_20"), Comment("Давоение более 20")] + [Column("is_pressure_gt_20"), Comment("Давление более 20")] public bool IsPressureGt20 { get; set; } [Column("is_hook_weight_not_changes"), Comment("Вес на крюке не меняется")] diff --git a/AsbCloudDb/Model/TelemetryDataSpin.cs b/AsbCloudDb/Model/TelemetryDataSpin.cs index 1fdfd41b..344acd2b 100644 --- a/AsbCloudDb/Model/TelemetryDataSpin.cs +++ b/AsbCloudDb/Model/TelemetryDataSpin.cs @@ -62,13 +62,13 @@ namespace AsbCloudDb.Model public float? TopDriveTorqueSpToMax { get; set; } [Column("top_drive_torque_sp_to_offset")] public float? TopDriveTorqueSpToOffset { get; set; } - [Column("torque_starting"), Comment(" Страгивающий момент")] + [Column("torque_starting"), Comment("Страгивающий момент")] public float? TorqueStarting { get; set; } - [Column("rotor_torque_avg"), Comment(" Момент в роторе средний")] + [Column("rotor_torque_avg"), Comment("Момент в роторе средний")] public float? RotorTorqueAvg { get; set; } - [Column("encoder_resolution"), Comment(" Разрешение энкодера")] + [Column("encoder_resolution"), Comment("Разрешение энкодера")] public float? EncoderResolution { get; set; } - [Column("ratio"), Comment(" Коэффициент редукции редектора")] + [Column("ratio"), Comment(" Коэффициент редукции редуктора")] public float? Ratio { get; set; } [Column("torque_right_limit"), Comment("Ограничение крутящего момента вправо")] public float? TorqueRightLimit { get; set; } @@ -102,9 +102,9 @@ namespace AsbCloudDb.Model public float? BreakAngleK { get; set; } [Column("reverse_k_torque"), Comment("Коэффициент на который умножается момент, для того чтобы система поняла что мы движемся в обратную сторону")] public float? ReverseKTorque { get; set; } - [Column("position_zero"), Comment("Нулевая позиция осциляции")] + [Column("position_zero"), Comment("Нулевая позиция осцилляции")] public float? PositionZero { get; set; } - [Column("position_right"), Comment("Крайний правый угол осциляции")] + [Column("position_right"), Comment("Крайний правый угол осцилляции")] public float? PositionRight { get; set; } [Column("torque_ramp_time"), Comment("Время нарастания момента")] public float? TorqueRampTime { get; set; } diff --git a/AsbCloudDb/Model/Well.cs b/AsbCloudDb/Model/Well.cs index 8c84765b..45c65c17 100644 --- a/AsbCloudDb/Model/Well.cs +++ b/AsbCloudDb/Model/Well.cs @@ -38,7 +38,7 @@ namespace AsbCloudDb.Model public double? Longitude { get; set; } [Column("timezone", TypeName = "jsonb"), Comment("Смещение часового пояса от UTC")] - public SimpleTimeZone TimeZone { get; set; } + public SimpleTimezone Timezone { get; set; } [ForeignKey(nameof(IdWellType))] [InverseProperty(nameof(Model.WellType.Wells))] diff --git a/AsbCloudDb/Readme.md b/AsbCloudDb/Readme.md index 3523b5f2..5685a59e 100644 --- a/AsbCloudDb/Readme.md +++ b/AsbCloudDb/Readme.md @@ -17,10 +17,10 @@ dotnet ef migrations add --project AsbCloudDb ``` ## Откатить миграцию ``` -dotnet ef migrations remvoe --project AsbCloudDb +dotnet ef migrations remove --project AsbCloudDb ``` \ - Name of migration class. -После создания миграции обязательно прочитать сгенерированый код. +После создания миграции обязательно прочитать генерированный код. ## Применить миграции При старте проекта применяются автоматически @@ -45,7 +45,7 @@ CREATE DATABASE postgres; create schema public; ``` -### Step 2. Innit timescaledb and prepare DB to restore +### Step 2. Init timescaledb and prepare DB to restore ``` CREATE EXTENSION IF NOT EXISTS timescaledb; SELECT timescaledb_pre_restore(); @@ -60,7 +60,7 @@ OR psql: ``` \! pg_restore -Fc -d postgres dump_2021-11-26.bak ``` -Then 'exit resore mode' psql: +Then 'exit restore mode' psql: ``` SELECT timescaledb_post_restore(); ``` \ No newline at end of file diff --git a/AsbCloudInfrastructure/CommonLibs/AsbSaubReport.deps.json b/AsbCloudInfrastructure/CommonLibs/AsbSaubReport.deps.json index 91ea443c..7242b363 100644 --- a/AsbCloudInfrastructure/CommonLibs/AsbSaubReport.deps.json +++ b/AsbCloudInfrastructure/CommonLibs/AsbSaubReport.deps.json @@ -1,11 +1,11 @@ { "runtimeTarget": { - "name": ".NETCoreApp,Version=v5.0", + "name": ".NETCoreApp,Version=v6.0", "signature": "" }, "compilationOptions": {}, "targets": { - ".NETCoreApp,Version=v5.0": { + ".NETCoreApp,Version=v6.0": { "AsbSaubReport/1.0.0": { "runtime": { "AsbSaubReport.dll": {} diff --git a/AsbCloudInfrastructure/CommonLibs/AsbSaubReport.dll b/AsbCloudInfrastructure/CommonLibs/AsbSaubReport.dll index 22e17f9a..d3910e63 100644 Binary files a/AsbCloudInfrastructure/CommonLibs/AsbSaubReport.dll and b/AsbCloudInfrastructure/CommonLibs/AsbSaubReport.dll differ diff --git a/AsbCloudInfrastructure/CommonLibs/AsbSaubReportLas.deps.json b/AsbCloudInfrastructure/CommonLibs/AsbSaubReportLas.deps.json index c0fa340e..50ba6522 100644 --- a/AsbCloudInfrastructure/CommonLibs/AsbSaubReportLas.deps.json +++ b/AsbCloudInfrastructure/CommonLibs/AsbSaubReportLas.deps.json @@ -1,11 +1,11 @@ { "runtimeTarget": { - "name": ".NETCoreApp,Version=v5.0", + "name": ".NETCoreApp,Version=v6.0", "signature": "" }, "compilationOptions": {}, "targets": { - ".NETCoreApp,Version=v5.0": { + ".NETCoreApp,Version=v6.0": { "AsbSaubReportLas/1.0.0": { "dependencies": { "AsbSaubReport": "1.0.0" diff --git a/AsbCloudInfrastructure/CommonLibs/AsbSaubReportLas.dll b/AsbCloudInfrastructure/CommonLibs/AsbSaubReportLas.dll index f5209559..c37b4902 100644 Binary files a/AsbCloudInfrastructure/CommonLibs/AsbSaubReportLas.dll and b/AsbCloudInfrastructure/CommonLibs/AsbSaubReportLas.dll differ diff --git a/AsbCloudInfrastructure/CommonLibs/AsbSaubReportPdf.deps.json b/AsbCloudInfrastructure/CommonLibs/AsbSaubReportPdf.deps.json index f1011029..cacd26cd 100644 --- a/AsbCloudInfrastructure/CommonLibs/AsbSaubReportPdf.deps.json +++ b/AsbCloudInfrastructure/CommonLibs/AsbSaubReportPdf.deps.json @@ -1,53 +1,25 @@ { "runtimeTarget": { - "name": ".NETCoreApp,Version=v5.0", + "name": ".NETCoreApp,Version=v6.0", "signature": "" }, "compilationOptions": {}, "targets": { - ".NETCoreApp,Version=v5.0": { + ".NETCoreApp,Version=v6.0": { "AsbSaubReportPdf/1.0.0": { "dependencies": { "AsbSaubReport": "1.0.0", - "itext7": "7.1.15" + "itext7": "7.2.0" }, "runtime": { "AsbSaubReportPdf.dll": {} } }, - "Common.Logging/3.4.1": { + "itext7/7.2.0": { "dependencies": { - "Common.Logging.Core": "3.4.1", - "Microsoft.CSharp": "4.0.1", - "System.Collections": "4.3.0", - "System.Diagnostics.Debug": "4.3.0", - "System.Globalization": "4.3.0", - "System.Reflection.TypeExtensions": "4.1.0", - "System.Runtime.Extensions": "4.3.0", - "System.Threading": "4.3.0" - }, - "runtime": { - "lib/netstandard1.3/Common.Logging.dll": { - "assemblyVersion": "3.4.1.0", - "fileVersion": "3.4.0.0" - } - } - }, - "Common.Logging.Core/3.4.1": { - "dependencies": { - "Microsoft.CSharp": "4.0.1" - }, - "runtime": { - "lib/netstandard1.0/Common.Logging.Core.dll": { - "assemblyVersion": "3.4.1.0", - "fileVersion": "3.4.0.0" - } - } - }, - "itext7/7.1.15": { - "dependencies": { - "Common.Logging": "3.4.1", + "Microsoft.DotNet.PlatformAbstractions": "1.1.0", "Microsoft.Extensions.DependencyModel": "1.1.0", + "Microsoft.Extensions.Logging": "5.0.0", "Portable.BouncyCastle": "1.8.9", "System.Collections.NonGeneric": "4.3.0", "System.Diagnostics.Process": "4.3.0", @@ -58,44 +30,56 @@ "System.Text.Encoding.CodePages": "4.3.0", "System.Threading.Thread": "4.3.0", "System.Threading.ThreadPool": "4.3.0", - "System.Xml.XmlDocument": "4.3.0" + "System.Xml.XmlDocument": "4.3.0", + "itext7.commons": "7.2.0" }, "runtime": { "lib/netstandard2.0/itext.barcodes.dll": { - "assemblyVersion": "7.1.15.0", - "fileVersion": "7.1.15.0" + "assemblyVersion": "7.2.0.0", + "fileVersion": "7.2.0.0" }, "lib/netstandard2.0/itext.forms.dll": { - "assemblyVersion": "7.1.15.0", - "fileVersion": "7.1.15.0" + "assemblyVersion": "7.2.0.0", + "fileVersion": "7.2.0.0" }, "lib/netstandard2.0/itext.io.dll": { - "assemblyVersion": "7.1.15.0", - "fileVersion": "7.1.15.0" + "assemblyVersion": "7.2.0.0", + "fileVersion": "7.2.0.0" }, "lib/netstandard2.0/itext.kernel.dll": { - "assemblyVersion": "7.1.15.0", - "fileVersion": "7.1.15.0" + "assemblyVersion": "7.2.0.0", + "fileVersion": "7.2.0.0" }, "lib/netstandard2.0/itext.layout.dll": { - "assemblyVersion": "7.1.15.0", - "fileVersion": "7.1.15.0" + "assemblyVersion": "7.2.0.0", + "fileVersion": "7.2.0.0" }, "lib/netstandard2.0/itext.pdfa.dll": { - "assemblyVersion": "7.1.15.0", - "fileVersion": "7.1.15.0" + "assemblyVersion": "7.2.0.0", + "fileVersion": "7.2.0.0" }, "lib/netstandard2.0/itext.sign.dll": { - "assemblyVersion": "7.1.15.0", - "fileVersion": "7.1.15.0" + "assemblyVersion": "7.2.0.0", + "fileVersion": "7.2.0.0" }, "lib/netstandard2.0/itext.styledxmlparser.dll": { - "assemblyVersion": "7.1.15.0", - "fileVersion": "7.1.15.0" + "assemblyVersion": "7.2.0.0", + "fileVersion": "7.2.0.0" }, "lib/netstandard2.0/itext.svg.dll": { - "assemblyVersion": "7.1.15.0", - "fileVersion": "7.1.15.0" + "assemblyVersion": "7.2.0.0", + "fileVersion": "7.2.0.0" + } + } + }, + "itext7.commons/7.2.0": { + "dependencies": { + "Microsoft.Extensions.Logging": "5.0.0" + }, + "runtime": { + "lib/netstandard2.0/itext.commons.dll": { + "assemblyVersion": "7.2.0.0", + "fileVersion": "7.2.0.0" } } }, @@ -137,6 +121,25 @@ } } }, + "Microsoft.Extensions.DependencyInjection/5.0.0": { + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "5.0.0" + }, + "runtime": { + "lib/net5.0/Microsoft.Extensions.DependencyInjection.dll": { + "assemblyVersion": "5.0.0.0", + "fileVersion": "5.0.20.51904" + } + } + }, + "Microsoft.Extensions.DependencyInjection.Abstractions/5.0.0": { + "runtime": { + "lib/netstandard2.0/Microsoft.Extensions.DependencyInjection.Abstractions.dll": { + "assemblyVersion": "5.0.0.0", + "fileVersion": "5.0.20.51904" + } + } + }, "Microsoft.Extensions.DependencyModel/1.1.0": { "dependencies": { "Microsoft.DotNet.PlatformAbstractions": "1.1.0", @@ -152,6 +155,48 @@ } } }, + "Microsoft.Extensions.Logging/5.0.0": { + "dependencies": { + "Microsoft.Extensions.DependencyInjection": "5.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "5.0.0", + "Microsoft.Extensions.Logging.Abstractions": "5.0.0", + "Microsoft.Extensions.Options": "5.0.0" + }, + "runtime": { + "lib/netstandard2.1/Microsoft.Extensions.Logging.dll": { + "assemblyVersion": "5.0.0.0", + "fileVersion": "5.0.20.51904" + } + } + }, + "Microsoft.Extensions.Logging.Abstractions/5.0.0": { + "runtime": { + "lib/netstandard2.0/Microsoft.Extensions.Logging.Abstractions.dll": { + "assemblyVersion": "5.0.0.0", + "fileVersion": "5.0.20.51904" + } + } + }, + "Microsoft.Extensions.Options/5.0.0": { + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "5.0.0", + "Microsoft.Extensions.Primitives": "5.0.0" + }, + "runtime": { + "lib/net5.0/Microsoft.Extensions.Options.dll": { + "assemblyVersion": "5.0.0.0", + "fileVersion": "5.0.20.51904" + } + } + }, + "Microsoft.Extensions.Primitives/5.0.0": { + "runtime": { + "lib/netcoreapp3.0/Microsoft.Extensions.Primitives.dll": { + "assemblyVersion": "5.0.0.0", + "fileVersion": "5.0.20.51904" + } + } + }, "Microsoft.NETCore.Platforms/1.1.0": {}, "Microsoft.NETCore.Targets/1.1.0": {}, "Microsoft.Win32.Primitives/4.3.0": { @@ -757,26 +802,19 @@ "serviceable": false, "sha512": "" }, - "Common.Logging/3.4.1": { + "itext7/7.2.0": { "type": "package", "serviceable": true, - "sha512": "sha512-5eZ/vgEOqzLg4PypZqnJ+wMhhgHyckicbZY4iDxqQ4FtOz0CpdYZ0xQ78aszMzeAJZiLLb5VdR9tPfunVQLz6g==", - "path": "common.logging/3.4.1", - "hashPath": "common.logging.3.4.1.nupkg.sha512" + "sha512": "sha512-1MkQiUY0pCevnKWrY/le7BiW/oV/9CLwB2jGD6xfs0tepE5eU5BTSlabgYq7oWZP8OB7KXoGySMqP+Ugj6MeOA==", + "path": "itext7/7.2.0", + "hashPath": "itext7.7.2.0.nupkg.sha512" }, - "Common.Logging.Core/3.4.1": { + "itext7.commons/7.2.0": { "type": "package", "serviceable": true, - "sha512": "sha512-wLHldZHvxsSD6Ahonfj00/SkfHfKqO+YT6jsUwVm8Rch1REL9IArHAcSLXxYxYfu5/4ydGtmXvOtaH3AkVPu0A==", - "path": "common.logging.core/3.4.1", - "hashPath": "common.logging.core.3.4.1.nupkg.sha512" - }, - "itext7/7.1.15": { - "type": "package", - "serviceable": true, - "sha512": "sha512-BJKdScf6C7LlHB5pV5fr0qHGbrPLX1yl+1R1qHroRZxtyTVFMeZ9gPV6IOsmgTRLr2ee9hUXHbb8/ZqKB4pqiA==", - "path": "itext7/7.1.15", - "hashPath": "itext7.7.1.15.nupkg.sha512" + "sha512": "sha512-bfysIirFpBOTc/mSfElJMOy9D/I2LTLeL0uae7xNgV4Vv7P2HF2n2/CJRTe9iZFsL3r8JdH0hd+eusnt0BjA8w==", + "path": "itext7.commons/7.2.0", + "hashPath": "itext7.commons.7.2.0.nupkg.sha512" }, "Microsoft.CSharp/4.0.1": { "type": "package", @@ -792,6 +830,20 @@ "path": "microsoft.dotnet.platformabstractions/1.1.0", "hashPath": "microsoft.dotnet.platformabstractions.1.1.0.nupkg.sha512" }, + "Microsoft.Extensions.DependencyInjection/5.0.0": { + "type": "package", + "serviceable": true, + "sha512": "sha512-Rc2kb/p3Ze6cP6rhFC3PJRdWGbLvSHZc0ev7YlyeU6FmHciDMLrhoVoTUEzKPhN5ZjFgKF1Cf5fOz8mCMIkvpA==", + "path": "microsoft.extensions.dependencyinjection/5.0.0", + "hashPath": "microsoft.extensions.dependencyinjection.5.0.0.nupkg.sha512" + }, + "Microsoft.Extensions.DependencyInjection.Abstractions/5.0.0": { + "type": "package", + "serviceable": true, + "sha512": "sha512-ORj7Zh81gC69TyvmcUm9tSzytcy8AVousi+IVRAI8nLieQjOFryRusSFh7+aLk16FN9pQNqJAiMd7BTKINK0kA==", + "path": "microsoft.extensions.dependencyinjection.abstractions/5.0.0", + "hashPath": "microsoft.extensions.dependencyinjection.abstractions.5.0.0.nupkg.sha512" + }, "Microsoft.Extensions.DependencyModel/1.1.0": { "type": "package", "serviceable": true, @@ -799,6 +851,34 @@ "path": "microsoft.extensions.dependencymodel/1.1.0", "hashPath": "microsoft.extensions.dependencymodel.1.1.0.nupkg.sha512" }, + "Microsoft.Extensions.Logging/5.0.0": { + "type": "package", + "serviceable": true, + "sha512": "sha512-MgOwK6tPzB6YNH21wssJcw/2MKwee8b2gI7SllYfn6rvTpIrVvVS5HAjSU2vqSku1fwqRvWP0MdIi14qjd93Aw==", + "path": "microsoft.extensions.logging/5.0.0", + "hashPath": "microsoft.extensions.logging.5.0.0.nupkg.sha512" + }, + "Microsoft.Extensions.Logging.Abstractions/5.0.0": { + "type": "package", + "serviceable": true, + "sha512": "sha512-NxP6ahFcBnnSfwNBi2KH2Oz8Xl5Sm2krjId/jRR3I7teFphwiUoUeZPwTNA21EX+5PtjqmyAvKaOeBXcJjcH/w==", + "path": "microsoft.extensions.logging.abstractions/5.0.0", + "hashPath": "microsoft.extensions.logging.abstractions.5.0.0.nupkg.sha512" + }, + "Microsoft.Extensions.Options/5.0.0": { + "type": "package", + "serviceable": true, + "sha512": "sha512-CBvR92TCJ5uBIdd9/HzDSrxYak+0W/3+yxrNg8Qm6Bmrkh5L+nu6m3WeazQehcZ5q1/6dDA7J5YdQjim0165zg==", + "path": "microsoft.extensions.options/5.0.0", + "hashPath": "microsoft.extensions.options.5.0.0.nupkg.sha512" + }, + "Microsoft.Extensions.Primitives/5.0.0": { + "type": "package", + "serviceable": true, + "sha512": "sha512-cI/VWn9G1fghXrNDagX9nYaaB/nokkZn0HYAawGaELQrl8InSezfe9OnfPZLcJq3esXxygh3hkq2c3qoV3SDyQ==", + "path": "microsoft.extensions.primitives/5.0.0", + "hashPath": "microsoft.extensions.primitives.5.0.0.nupkg.sha512" + }, "Microsoft.NETCore.Platforms/1.1.0": { "type": "package", "serviceable": true, @@ -830,7 +910,7 @@ "Newtonsoft.Json/9.0.1": { "type": "package", "serviceable": true, - "sha512": "sha512-U82mHQSKaIk+lpSVCbWYKNavmNH1i5xrExDEquU1i6I5pV6UMOqRnJRSlKO3cMPfcpp0RgDY+8jUXHdQ4IfXvw==", + "sha512": "sha512-2okXpTRwUcgQb06put5LwwCjtgoFo74zkPksjcvOpnIjx7TagGW5IoBCAA4luZx1+tfiIhoNqoiI7Y7zwWGyKA==", "path": "newtonsoft.json/9.0.1", "hashPath": "newtonsoft.json.9.0.1.nupkg.sha512" }, @@ -1145,7 +1225,7 @@ "System.Runtime.InteropServices.RuntimeInformation/4.0.0": { "type": "package", "serviceable": true, - "sha512": "sha512-hWPhJxc453RCa8Z29O91EmfGeZIHX1ZH2A8L6lYQVSaKzku2DfArSfMEb1/MYYzPQRJZeu0c9dmYeJKxW5Fgng==", + "sha512": "sha512-Ri015my90h3AB/BsbvEpq1foEPoPBBa9L8b7fu1VE4eA1NMeMe5iZ6guLjoWB+XGQr1u/rEwtXobqofjFBsAgA==", "path": "system.runtime.interopservices.runtimeinformation/4.0.0", "hashPath": "system.runtime.interopservices.runtimeinformation.4.0.0.nupkg.sha512" }, diff --git a/AsbCloudInfrastructure/CommonLibs/AsbSaubReportPdf.dll b/AsbCloudInfrastructure/CommonLibs/AsbSaubReportPdf.dll index ce32a3d4..15988963 100644 Binary files a/AsbCloudInfrastructure/CommonLibs/AsbSaubReportPdf.dll and b/AsbCloudInfrastructure/CommonLibs/AsbSaubReportPdf.dll differ diff --git a/AsbCloudInfrastructure/CommonLibs/ref/AsbSaubReportLas.dll b/AsbCloudInfrastructure/CommonLibs/ref/AsbSaubReportLas.dll index 5f40dc30..0a7a5b00 100644 Binary files a/AsbCloudInfrastructure/CommonLibs/ref/AsbSaubReportLas.dll and b/AsbCloudInfrastructure/CommonLibs/ref/AsbSaubReportLas.dll differ diff --git a/AsbCloudInfrastructure/CommonLibs/ref/AsbSaubReportPdf.dll b/AsbCloudInfrastructure/CommonLibs/ref/AsbSaubReportPdf.dll index ac44aab6..36d4e2d2 100644 Binary files a/AsbCloudInfrastructure/CommonLibs/ref/AsbSaubReportPdf.dll and b/AsbCloudInfrastructure/CommonLibs/ref/AsbSaubReportPdf.dll differ diff --git a/AsbCloudInfrastructure/DateTimeExtentions.cs b/AsbCloudInfrastructure/DateTimeExtentions.cs index 5e9f1423..5c562399 100644 --- a/AsbCloudInfrastructure/DateTimeExtentions.cs +++ b/AsbCloudInfrastructure/DateTimeExtentions.cs @@ -12,10 +12,10 @@ namespace AsbCloudInfrastructure var dateUtc = date.Kind switch { DateTimeKind.Local => date.ToUniversalTime(), - DateTimeKind.Unspecified => date.AddHours(-remoteTimezoneOffsetHours), + DateTimeKind.Unspecified => DateTime.SpecifyKind(date.AddHours(-remoteTimezoneOffsetHours), DateTimeKind.Utc), _ => date, }; - return new DateTimeOffset(dateUtc); + return new DateTimeOffset( dateUtc); } public static DateTime ToRemoteDateTime(this DateTimeOffset date, double remoteTimezoneOffsetHours) diff --git a/AsbCloudInfrastructure/DependencyInjection.cs b/AsbCloudInfrastructure/DependencyInjection.cs index 7eef6f57..c5fb77e1 100644 --- a/AsbCloudInfrastructure/DependencyInjection.cs +++ b/AsbCloudInfrastructure/DependencyInjection.cs @@ -5,6 +5,7 @@ using AsbCloudInfrastructure.Services; using AsbCloudInfrastructure.Services.Analysis; using AsbCloudInfrastructure.Services.Cache; using AsbCloudInfrastructure.Services.WellOperationService; +using Mapster; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -25,6 +26,13 @@ namespace AsbCloudInfrastructure public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration) { + TypeAdapterConfig.GlobalSettings.Default.Config + .ForType() + .MapWith((source) => source.DateTime); + TypeAdapterConfig.GlobalSettings.Default.Config + .ForType() + .MapWith((source) => source == default ? new DateTime(0,DateTimeKind.Utc) : source ); + services.AddDbContext(options => options.UseNpgsql(configuration.GetConnectionString("DefaultConnection"))); @@ -54,7 +62,7 @@ namespace AsbCloudInfrastructure services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); diff --git a/AsbCloudInfrastructure/ReportDataSourcePgCloud.cs b/AsbCloudInfrastructure/ReportDataSourcePgCloud.cs index 7c88a057..f428d4eb 100644 --- a/AsbCloudInfrastructure/ReportDataSourcePgCloud.cs +++ b/AsbCloudInfrastructure/ReportDataSourcePgCloud.cs @@ -16,6 +16,7 @@ namespace AsbCloudInfrastructure private readonly Dictionary events; private readonly Dictionary users; + private readonly double timezoneOffset; private readonly Dictionary categories = new Dictionary { {1, "Авария"}, @@ -26,6 +27,7 @@ namespace AsbCloudInfrastructure public ReportDataSourcePgCloud(AsbCloudDbContext context, int idWell) { this.context = context; + var well = context.Wells .Include(w => w.Cluster) .ThenInclude(c => c.Deposit) @@ -46,15 +48,17 @@ namespace AsbCloudInfrastructure .Where(u => u.IdTelemetry == idTelemetry) .ToDictionary(u => u.IdUser, u => u); + timezoneOffset = well?.Telemetry?.Info?.TimeZoneOffsetTotalHours ?? well.Timezone?.Hours ?? 5.0; + info = new WellInfoReport { - Deposit = well?.Cluster?.Deposit?.Caption, - Cluster = well?.Cluster?.Caption, - Well = well?.Caption, - Customer = well?.RelationCompaniesWells.FirstOrDefault(c => c.Company.IdCompanyType == 1)?.Company.Caption, - DrillingStartDate = well?.Telemetry?.Info?.DrillingStartDate ?? default, - TimeZoneId = well?.Telemetry?.Info?.TimeZoneId ?? default, - TimeZoneOffsetTotalHours = well?.Telemetry?.Info?.TimeZoneOffsetTotalHours ?? default, + Deposit = well.Cluster?.Deposit?.Caption, + Cluster = well.Cluster?.Caption, + Well = well.Caption, + Customer = well.RelationCompaniesWells.FirstOrDefault(c => c.Company.IdCompanyType == 1)?.Company.Caption, + DrillingStartDate = well.Telemetry?.Info?.DrillingStartDate.ToRemoteDateTime(timezoneOffset) ?? default, + TimeZoneId = well.Telemetry?.Info?.TimeZoneId ?? well.Timezone?.TimeZoneId ?? default, + TimeZoneOffsetTotalHours = timezoneOffset, }; } @@ -74,8 +78,8 @@ namespace AsbCloudInfrastructure var result = new AnalyzeResult { - MinDate = dataStat?.min.DateTime ?? messagesStat?.min.DateTime ?? default, - MaxDate = dataStat?.max.DateTime ?? messagesStat?.max.DateTime ?? default, + MinDate = dataStat?.min.UtcDateTime ?? messagesStat?.min.UtcDateTime ?? default, + MaxDate = dataStat?.max.UtcDateTime ?? messagesStat?.max.UtcDateTime ?? default, MessagesCount = messagesStat?.count ?? 0, }; @@ -83,57 +87,67 @@ namespace AsbCloudInfrastructure } public IQueryable GetDataSaubItems(DateTime begin, DateTime end) - => from item in context.TelemetryDataSaub - where item.IdTelemetry == idTelemetry - && item.Date >= begin - && item.Date <= end - orderby item.Date - select new DataSaubReport - { - //Id = item.Id, - Date = item.Date.DateTime, - Mode = item.Mode, - WellDepth = item.WellDepth, - BitDepth = item.BitDepth, - BlockPosition = item.BlockPosition, - BlockSpeed = item.BlockSpeed, - BlockSpeedSp = item.BlockSpeedSp, - BlockSpeedSpDevelop = item.BlockSpeedSpDevelop, - Pressure = item.Pressure, - PressureSp = item.PressureSp, - AxialLoad = item.AxialLoad, - AxialLoadSp = item.AxialLoadSp, - AxialLoadLimitMax = item.AxialLoadLimitMax, - HookWeight = item.HookWeight, - RotorTorque = item.RotorTorque, - RotorTorqueSp = item.RotorTorqueSp, - RotorSpeed = item.RotorSpeed, - Flow = item.Flow, - PressureSpDevelop = item.PressureSpDevelop, - }; + { + var beginUtc = begin.ToUtcDateTimeOffset(timezoneOffset); + var endUtc = end.ToUtcDateTimeOffset(timezoneOffset); + + var query = context.TelemetryDataSaub + .Where(d => d.IdTelemetry == idTelemetry + && d.Date >= beginUtc + && d.Date <= endUtc) + .OrderBy(d => d.Date) + .Select(d => new DataSaubReport { + Date = d.Date.DateTime.AddHours(timezoneOffset), + Mode = d.Mode, + WellDepth = d.WellDepth, + BitDepth = d.BitDepth, + BlockPosition = d.BlockPosition, + BlockSpeed = d.BlockSpeed, + BlockSpeedSp = d.BlockSpeedSp, + BlockSpeedSpDevelop = d.BlockSpeedSpDevelop, + Pressure = d.Pressure, + PressureSp = d.PressureSp, + AxialLoad = d.AxialLoad, + AxialLoadSp = d.AxialLoadSp, + AxialLoadLimitMax = d.AxialLoadLimitMax, + HookWeight = d.HookWeight, + RotorTorque = d.RotorTorque, + RotorTorqueSp = d.RotorTorqueSp, + RotorSpeed = d.RotorSpeed, + Flow = d.Flow, + PressureSpDevelop = d.PressureSpDevelop, + }); + return query; + } public IQueryable GetMessages(DateTime begin, DateTime end) - => from item in context.TelemetryMessages - where item.IdTelemetry == idTelemetry - && item.Date >= begin - && item.Date <= end - orderby item.Date - select new MessageReport - { - Id = item.Id, - Date = item.Date.DateTime, - Category = events.GetValueOrDefault(item.IdEvent) == null - ? $"" - : categories[events[item.IdEvent].IdCategory], - User = item.IdTelemetryUser == null - ? "" - : users.GetValueOrDefault((int)item.IdTelemetryUser) == null - ? $"User id{item.IdTelemetryUser}" - : users[(int)item.IdTelemetryUser].MakeDisplayName(), - Text = events.GetValueOrDefault(item.IdEvent) == null - ? $"Стбытие {item.IdEvent} {item.Arg0} {item.Arg1} {item.Arg2} {item.Arg3}" - : events[item.IdEvent].MakeMessageText(item) - }; + { + var beginUtc = begin.ToUtcDateTimeOffset(timezoneOffset); + var endUtc = end.ToUtcDateTimeOffset(timezoneOffset); + + var query = from item in context.TelemetryMessages + where item.IdTelemetry == idTelemetry + && item.Date >= beginUtc + && item.Date <= endUtc + orderby item.Date + select new MessageReport + { + Id = item.Id, + Date = item.Date.DateTime, + Category = events.GetValueOrDefault(item.IdEvent) == null + ? $"" + : categories[events[item.IdEvent].IdCategory], + User = item.IdTelemetryUser == null + ? "" + : users.GetValueOrDefault((int)item.IdTelemetryUser) == null + ? $"User id{item.IdTelemetryUser}" + : users[(int)item.IdTelemetryUser].MakeDisplayName(), + Text = events.GetValueOrDefault(item.IdEvent) == null + ? $"Событие {item.IdEvent} {item.Arg0} {item.Arg1} {item.Arg2} {item.Arg3}" + : events[item.IdEvent].MakeMessageText(item) + }; + return query; + } public WellInfoReport GetWellInfo() => info; diff --git a/AsbCloudInfrastructure/Services/Analysis/TelemetryAnalyticsBackgroundService.cs b/AsbCloudInfrastructure/Services/Analysis/TelemetryAnalyticsBackgroundService.cs index 43bb80f0..bb4452fe 100644 --- a/AsbCloudInfrastructure/Services/Analysis/TelemetryAnalyticsBackgroundService.cs +++ b/AsbCloudInfrastructure/Services/Analysis/TelemetryAnalyticsBackgroundService.cs @@ -40,8 +40,8 @@ namespace AsbCloudInfrastructure.Services.Analysis try { using var context = new AsbCloudDbContext(options); - var timeZoneService = new TimeZoneService(); - var telemetryService = new TelemetryService(context, telemetryTracker, timeZoneService, cacheDb); + var timezoneService = new TimezoneService(); + var telemetryService = new TelemetryService(context, telemetryTracker, timezoneService, cacheDb); var analyticsService = new TelemetryAnalyticsService(context, telemetryService, cacheDb); diff --git a/AsbCloudInfrastructure/Services/Analysis/TelemetryAnalyticsService.cs b/AsbCloudInfrastructure/Services/Analysis/TelemetryAnalyticsService.cs index 25e20bc1..c875656a 100644 --- a/AsbCloudInfrastructure/Services/Analysis/TelemetryAnalyticsService.cs +++ b/AsbCloudInfrastructure/Services/Analysis/TelemetryAnalyticsService.cs @@ -33,13 +33,14 @@ namespace AsbCloudInfrastructure.Services.Analysis public async Task> GetWellDepthToDayAsync(int idWell, CancellationToken token = default) { - var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell); + var idTelemetry = telemetryService.GetIdTelemetryByIdWell(idWell); - if (telemetryId is null) + if (idTelemetry is null) return null; + var timezone = telemetryService.GetTimezone((int)idTelemetry); var depthToTimeData = (from d in db.TelemetryDataSaub - where d.IdTelemetry == telemetryId + where d.IdTelemetry == idTelemetry select new { d.WellDepth, @@ -56,7 +57,7 @@ namespace AsbCloudInfrastructure.Services.Analysis { WellDepth = d.WellDepth ?? 0.0, BitDepth = d.BitDepth ?? 0.0, - Date = d.Date + Date = d.Date.ToRemoteDateTime(timezone.Hours), }).AsNoTracking().ToListAsync(token).ConfigureAwait(false); } @@ -70,11 +71,11 @@ namespace AsbCloudInfrastructure.Services.Analysis if (telemetryId is null) return null; - var timezoneOffset = telemetryService.GetTimezoneOffset((int)telemetryId); + var timezone = telemetryService.GetTimezone((int)telemetryId); var drillingPeriodsInfo = await db.TelemetryDataSaub .Where(t => t.IdTelemetry == telemetryId) - .GroupBy(t => Math.Floor((((t.Date.DayOfYear * 24 + t.Date.Hour) * 60 + t.Date.Minute) * 60 + t.Date.Second + timezoneOffset - shiftStartSec) / intervalSeconds)) + .GroupBy(t => Math.Floor((((t.Date.DayOfYear * 24 + t.Date.Hour) * 60 + t.Date.Minute) * 60 + t.Date.Second + timezone.Hours - shiftStartSec) / intervalSeconds)) .Select(g => new { WellDepthMin = g.Min(t => t.WellDepth), WellDepthMax = g.Max(t => t.WellDepth), @@ -86,7 +87,7 @@ namespace AsbCloudInfrastructure.Services.Analysis var wellDepthToIntervalData = drillingPeriodsInfo.Select(d => new WellDepthToIntervalDto { - IntervalStartDate = d.DateMin, + IntervalStartDate = d.DateMin.ToRemoteDateTime(timezone.Hours), IntervalDepthProgress = (d.WellDepthMax - d.WellDepthMin) ?? 0.0 // / (d.DateMax - d.DateMin).TotalHours, }).OrderBy(d => d.IntervalStartDate).ToList(); @@ -201,7 +202,7 @@ namespace AsbCloudInfrastructure.Services.Analysis if (telemetryId is null) return null; - var timezoneOffset = telemetryService.GetTimezoneOffset((int)telemetryId); + var timezone = telemetryService.GetTimezone((int)telemetryId); // Get'n'Group all operations only by start date and by name (if there were several operations in interval). // Without dividing these operations duration by given interval @@ -210,7 +211,7 @@ namespace AsbCloudInfrastructure.Services.Analysis join o in db.WellOperationCategories on a.IdOperation equals o.Id group a by new { - Interval = Math.Floor((a.UnixDate - workBeginSeconds + timezoneOffset) / intervalSeconds), + Interval = Math.Floor((a.UnixDate - workBeginSeconds + timezone.Hours) / intervalSeconds), o.Name } into g select new @@ -223,17 +224,15 @@ namespace AsbCloudInfrastructure.Services.Analysis .ToListAsync(token) .ConfigureAwait(false); - var groupedOperationsList = new List(); - if (operations is not null && operations.Any()) { var operations = ops.Select(o => (o.IntervalStart, o.OperationName, o.OperationDuration)); var splittedOperationsByInterval = DivideOperationsByIntervalLength(operations, intervalSeconds); // divides good - groupedOperationsList = UniteOperationsInDto(splittedOperationsByInterval, intervalSeconds).ToList(); // unites not good + groupedOperationsList = UniteOperationsInDto(splittedOperationsByInterval, intervalSeconds, timezone.Hours).ToList(); // unites not good } return groupedOperationsList; @@ -300,16 +299,17 @@ namespace AsbCloudInfrastructure.Services.Analysis } } - public async Task GetOperationsDateRangeAsync(int idWell, bool isUtc, - CancellationToken token = default) + public async Task GetOperationsDateRangeAsync(int idWell, CancellationToken token = default) { - var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell); + var idTelemetry = telemetryService.GetIdTelemetryByIdWell(idWell); - if (telemetryId is null) + if (idTelemetry is null) return null; + var timezone = telemetryService.GetTimezone((int)idTelemetry); + var datesRange = await (from d in db.TelemetryAnalysis - where d.IdTelemetry == telemetryId + where d.IdTelemetry == idTelemetry select d.UnixDate).DefaultIfEmpty() .GroupBy(g => true) .AsNoTracking() @@ -323,18 +323,12 @@ namespace AsbCloudInfrastructure.Services.Analysis var result = new DatesRangeDto { - From = DateTimeOffset.FromUnixTimeSeconds(datesRange.From).DateTime, - To = datesRange.To == default + From = DateTimeOffset.FromUnixTimeSeconds(datesRange.From).ToRemoteDateTime(timezone.Hours), + To = (datesRange.To == default ? DateTime.MaxValue - : DateTimeOffset.FromUnixTimeSeconds(datesRange.To).DateTime + : DateTimeOffset.FromUnixTimeSeconds(datesRange.To)).ToRemoteDateTime(timezone.Hours), }; - if (isUtc) - return result; - - result = await telemetryService.DatesRangeToTelemetryTimeZoneAsync((int)telemetryId, result, token) - .ConfigureAwait(false); - return result; } @@ -347,7 +341,7 @@ namespace AsbCloudInfrastructure.Services.Analysis .LastOrDefaultAsync(token) .ConfigureAwait(false); - DateTime lastAnalysisDate = default; + DateTime lastAnalysisDate = new DateTime(0, DateTimeKind.Utc); if(lastAnalysisInDb is not null) lastAnalysisDate = DateTime.UnixEpoch.AddSeconds(lastAnalysisInDb.DurationSec + lastAnalysisInDb.UnixDate); @@ -396,7 +390,7 @@ namespace AsbCloudInfrastructure.Services.Analysis operationDurationTimeCounter += OperationDuration; } else - { // if operation duration overflows current interval it shoud be divided into 2 or more parts for this and next intervals + { // if operation duration overflows current interval it should be divided into 2 or more parts for this and next intervals var remainingIntervalTime = intervalSeconds - operationDurationTimeCounter; splittedOperationsByInterval.Add((IntervalStart, OperationName, remainingIntervalTime)); // first part of long operation @@ -432,13 +426,14 @@ namespace AsbCloudInfrastructure.Services.Analysis } private static IEnumerable UniteOperationsInDto( - IEnumerable<(long IntervalStart, string OperationName, int OperationDuration)> operations, int intervalSeconds) + IEnumerable<(long IntervalStart, string OperationName, int OperationDuration)> operations, int intervalSeconds, double timezoneOffset) { var groupedOperationsList = new List(); var groupedOperationsObj = new TelemetryOperationInfoDto { - IntervalBegin = DateTimeOffset.FromUnixTimeSeconds(operations.First().IntervalStart), + IntervalBegin = DateTimeOffset.FromUnixTimeSeconds(operations.First().IntervalStart) + .ToRemoteDateTime(timezoneOffset), Operations = new List() }; @@ -461,7 +456,8 @@ namespace AsbCloudInfrastructure.Services.Analysis intervalEndDate = IntervalStart + intervalSeconds; groupedOperationsObj = new TelemetryOperationInfoDto { - IntervalBegin = DateTimeOffset.FromUnixTimeSeconds(IntervalStart), + IntervalBegin = DateTimeOffset.FromUnixTimeSeconds(IntervalStart) + .ToRemoteDateTime(timezoneOffset), Operations = new List() }; diff --git a/AsbCloudInfrastructure/Services/Cache/CacheTable.cs b/AsbCloudInfrastructure/Services/Cache/CacheTable.cs index b1932283..a0170e17 100644 --- a/AsbCloudInfrastructure/Services/Cache/CacheTable.cs +++ b/AsbCloudInfrastructure/Services/Cache/CacheTable.cs @@ -309,7 +309,7 @@ namespace AsbCloudInfrastructure.Services.Cache { foreach (var entity in entities) { - if (dbSet.Contains(entity)) // TODO: это очень ммедленно + if (dbSet.Contains(entity)) // TODO: это очень медленно dbSet.Update(entity); else dbSet.Add(entity); diff --git a/AsbCloudInfrastructure/Services/ClusterService.cs b/AsbCloudInfrastructure/Services/ClusterService.cs index e22eed2c..7f73525d 100644 --- a/AsbCloudInfrastructure/Services/ClusterService.cs +++ b/AsbCloudInfrastructure/Services/ClusterService.cs @@ -148,7 +148,7 @@ namespace AsbCloudInfrastructure.Services Wells = gCluster.Select(well => { var dto = well.Adapt(); dto.WellType = well.WellType?.Caption; - dto.LastTelemetryDate = wellService.GetLastTelemetryDate(well.Id); + dto.LastTelemetryDate = wellService.GetLastTelemetryDate(well.Id).DateTime; dto.Cluster = gCluster.Key.Caption; dto.Deposit = gDeposit.Key.Caption; return dto; diff --git a/AsbCloudInfrastructure/Services/DrillFlowChartService.cs b/AsbCloudInfrastructure/Services/DrillFlowChartService.cs index 6164038d..365942f9 100644 --- a/AsbCloudInfrastructure/Services/DrillFlowChartService.cs +++ b/AsbCloudInfrastructure/Services/DrillFlowChartService.cs @@ -15,36 +15,42 @@ namespace AsbCloudInfrastructure.Services IDrillFlowChartService { private readonly IAsbCloudDbContext db; + private readonly IWellService wellService; - public DrillFlowChartService(IAsbCloudDbContext context) + public DrillFlowChartService(IAsbCloudDbContext context, IWellService wellService) : base(context) { this.db = context; + this.wellService = wellService; } public async Task> GetAllAsync(int idWell, DateTime updateFrom, CancellationToken token = default) { + var timezone = wellService.GetTimezone(idWell); + var updateFromUtc = updateFrom.ToUtcDateTimeOffset(timezone.Hours); var entities = await (from p in db.DrillFlowChart where p.IdWell == idWell && - p.LastUpdate > updateFrom + p.LastUpdate > updateFromUtc orderby p.DepthStart, p.Id select p) .ToListAsync(token) .ConfigureAwait(false); - var dto = entities.Adapt(); - return dto; + var dtos = entities.Select(entity => { + var dto = entity.Adapt(); + dto.LastUpdate = entity.LastUpdate.ToRemoteDateTime(timezone.Hours); + return dto; + }); + return dtos; } public async Task InsertAsync(int idWell, DrillFlowChartDto dto, CancellationToken token = default) { dto.IdWell = idWell; - dto.LastUpdate = DateTime.Now; - + dto.LastUpdate = DateTime.UtcNow; var result = await base.InsertAsync(dto, token).ConfigureAwait(false); - return result; } @@ -54,7 +60,7 @@ namespace AsbCloudInfrastructure.Services foreach (var dto in dtos) { dto.IdWell = idWell; - dto.LastUpdate = DateTime.Now; + dto.LastUpdate = DateTime.UtcNow; } var result = await base.InsertRangeAsync(dtos, token).ConfigureAwait(false); diff --git a/AsbCloudInfrastructure/Services/DrillingProgramService.cs b/AsbCloudInfrastructure/Services/DrillingProgramService.cs index c22c9f7c..dd0bc4f1 100644 --- a/AsbCloudInfrastructure/Services/DrillingProgramService.cs +++ b/AsbCloudInfrastructure/Services/DrillingProgramService.cs @@ -164,7 +164,7 @@ namespace AsbCloudInfrastructure.Services newSheetName = sheetSrc.Name; suffix = $"_{index++}"; if (newSheetName.Length + suffix.Length >= 31) - newSheetName = newSheetName.Substring(0, (31 - suffix.Length)); + newSheetName = newSheetName[..(31 - suffix.Length)]; newSheetName += suffix; } diff --git a/AsbCloudInfrastructure/Services/FileService.cs b/AsbCloudInfrastructure/Services/FileService.cs index 6c02152f..d82ac230 100644 --- a/AsbCloudInfrastructure/Services/FileService.cs +++ b/AsbCloudInfrastructure/Services/FileService.cs @@ -28,7 +28,8 @@ namespace AsbCloudInfrastructure.Services .ThenInclude(u => u.Company) .ThenInclude(c => c.CompanyType) .Include(f => f.FileMarks) - .ThenInclude(m => m.User); + .ThenInclude(m => m.User) + .Include(f=>f.Well); } public async Task GetSharedUrlAsync(int idFileInfo, int idUser, IFileShareService fileShareService, @@ -75,7 +76,7 @@ namespace AsbCloudInfrastructure.Services IdAuthor = idUser, IdCategory = idCategory, Name = destinationFileName, - UploadDate = DateTime.Now, + UploadDate = DateTime.UtcNow, IsDeleted = false, Size = sysFileInfo.Length, }; @@ -87,8 +88,7 @@ namespace AsbCloudInfrastructure.Services Directory.CreateDirectory(Path.GetDirectoryName(filePath)); File.Move(srcFilePath, filePath); - var dto = entry.Entity.Adapt(); - return dto; + return await GetInfoAsync(entry.Entity.Id, token); } public async Task SaveAsync(int idWell, int? idUser, int idCategory, @@ -101,7 +101,7 @@ namespace AsbCloudInfrastructure.Services IdAuthor = idUser, IdCategory = idCategory, Name = Path.GetFileName(fileFullName), - UploadDate = DateTime.Now, + UploadDate = DateTime.UtcNow, IsDeleted = false, Size = fileStream?.Length ?? 0 }; @@ -116,9 +116,8 @@ namespace AsbCloudInfrastructure.Services using var newfileStream = new FileStream(filePath, FileMode.Create); await fileStream.CopyToAsync(newfileStream, token).ConfigureAwait(false); - - var dto = entry.Entity.Adapt(); - return dto; + + return await GetInfoAsync(entry.Entity.Id, token); } private string MakeFilePath(int idWell, int idCategory, string fileFullName, int fileId) @@ -136,7 +135,7 @@ namespace AsbCloudInfrastructure.Services .ToListAsync(token) .ConfigureAwait(false); - var dtos = entities.Adapt(); + var dtos = entities.Select(e => Convert(e)); return dtos; } @@ -157,11 +156,28 @@ namespace AsbCloudInfrastructure.Services if (!string.IsNullOrEmpty(fileName)) query = query.Where(e => e.Name.ToLower().Contains(fileName.ToLower())); + var firstFile = await query.FirstOrDefaultAsync(token); + if (firstFile is null) + return new PaginationContainer() + { + Skip = skip, + Take = take, + Count = 0, + }; + + var timezoneOffset = firstFile.Well.Timezone?.Hours ?? 5; + if (begin != default) - query = query.Where(e => e.UploadDate >= begin); + { + var beginUtc = begin.ToUtcDateTimeOffset(timezoneOffset); + query = query.Where(e => e.UploadDate >= beginUtc); + } if (end != default) - query = query.Where(e => e.UploadDate <= end); + { + var endUtc = end.ToUtcDateTimeOffset(timezoneOffset); + query = query.Where(e => e.UploadDate <= endUtc); + } var count = await query.CountAsync(token).ConfigureAwait(false); @@ -185,8 +201,7 @@ namespace AsbCloudInfrastructure.Services .Take(take).AsNoTracking().ToListAsync(token) .ConfigureAwait(false); - var dtos = entities.Adapt(); - + var dtos = entities.Select(e => Convert(e, timezoneOffset)); result.Items.AddRange(dtos); return result; } @@ -202,7 +217,7 @@ namespace AsbCloudInfrastructure.Services if (entity is null) return null; - var dto = entity.Adapt(); + var dto = Convert(entity); return dto; } @@ -259,10 +274,29 @@ namespace AsbCloudInfrastructure.Services var entity = await dbSetConfigured .FirstOrDefaultAsync(f => f.FileMarks.Any(m => m.Id == idMark), token) .ConfigureAwait(false); - var dto = entity.Adapt(); + + FileInfoDto dto = Convert(entity); return dto; } + private static FileInfoDto Convert(AsbCloudDb.Model.FileInfo entity) + { + var timezoneOffset = entity.Well.Timezone?.Hours ?? 5; + return Convert(entity, timezoneOffset); + } + + private static FileInfoDto Convert(AsbCloudDb.Model.FileInfo entity, double timezoneOffset) + { + var dto = entity.Adapt(); + dto.UploadDate = entity.UploadDate.ToRemoteDateTime(timezoneOffset); + dto.FileMarks = entity.FileMarks.Select(m => + { + var mark = m.Adapt(); + mark.DateCreated = m.DateCreated.ToRemoteDateTime(timezoneOffset); + return mark; + }); + return dto; + } public async Task CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token) { var fileMark = await db.FileMarks @@ -278,7 +312,7 @@ namespace AsbCloudInfrastructure.Services var newFileMark = fileMarkDto.Adapt(); newFileMark.Id = default; - newFileMark.DateCreated = DateTime.Now; + newFileMark.DateCreated = DateTime.UtcNow; newFileMark.IdUser = idUser; db.FileMarks.Add(newFileMark); @@ -303,7 +337,7 @@ namespace AsbCloudInfrastructure.Services fileInfo.PublishInfo = new FilePublishInfo() { IdPublisher = idUser, - Date = DateTime.Now, + Date = DateTime.UtcNow, WebStorageFileUrl = weblink }; diff --git a/AsbCloudInfrastructure/Services/MeasureService.cs b/AsbCloudInfrastructure/Services/MeasureService.cs index ed5c0108..8424e6c5 100644 --- a/AsbCloudInfrastructure/Services/MeasureService.cs +++ b/AsbCloudInfrastructure/Services/MeasureService.cs @@ -15,11 +15,13 @@ namespace AsbCloudInfrastructure.Services public class MeasureService : IMeasureService { private readonly IAsbCloudDbContext db; + private readonly IWellService wellService; private readonly CacheTable cacheCategories; - public MeasureService(IAsbCloudDbContext db, Cache.CacheDb cacheDb) + public MeasureService(IAsbCloudDbContext db, Cache.CacheDb cacheDb, IWellService wellService) { this.db = db; + this.wellService = wellService; cacheCategories = cacheDb.GetCachedTable((DbContext)db); } @@ -43,8 +45,12 @@ namespace AsbCloudInfrastructure.Services .FirstOrDefaultAsync(token) .ConfigureAwait(false); - var dtos = entity?.Adapt((d, s) => d.CategoryName = s.Category?.Name); - return dtos; + var timezone = wellService.GetTimezone(idWell); + var dto = entity?.Adapt((d, s) => { + d.CategoryName = s.Category?.Name; + d.Timestamp = s.Timestamp.ToRemoteDateTime(timezone.Hours); + }); + return dto; } public async Task> GetHisoryAsync(int idWell, int? idCategory = null, CancellationToken token = default) @@ -61,41 +67,50 @@ namespace AsbCloudInfrastructure.Services .ToListAsync(token) .ConfigureAwait(false); - var dtos = entities.Adapt((d, s) => d.CategoryName = s.Category?.Name); + var timezone = wellService.GetTimezone(idWell); + var dtos = entities.Adapt((d, s) => { + d.CategoryName = s.Category?.Name; + d.Timestamp = s.Timestamp.ToRemoteDateTime(timezone.Hours); + }); return dtos; } - public Task InsertAsync(int idWell, MeasureDto data, CancellationToken token) + public Task InsertAsync(int idWell, MeasureDto dto, CancellationToken token) { - if (data.IdCategory < 1) - throw new ArgumentException("wrong idCategory", nameof(data)); - if (data.Data is null) - throw new ArgumentException("data.data is not optional", nameof(data)); - var entity = data.Adapt(); + if (dto.IdCategory < 1) + throw new ArgumentException("wrong idCategory", nameof(dto)); + if (dto.Data is null) + throw new ArgumentException("data.data is not optional", nameof(dto)); + var timezone = wellService.GetTimezone(idWell); + var entity = dto.Adapt(); entity.IdWell = idWell; + entity.Timestamp = dto.Timestamp.ToUtcDateTimeOffset(timezone.Hours); db.Measures.Add(entity); return db.SaveChangesAsync(token); } - public async Task UpdateAsync(int idWell, MeasureDto data, CancellationToken token) + public async Task UpdateAsync(int idWell, MeasureDto dto, CancellationToken token) { - if (data.Id < 1) - throw new ArgumentException("wrong id", nameof(data)); - if (data.IdCategory < 1) - throw new ArgumentException("wrong idCategory", nameof(data)); - if (data.Data is null) - throw new ArgumentException("data.data is not optional", nameof(data)); + if (dto.Id < 1) + throw new ArgumentException("wrong id", nameof(dto)); + if (dto.IdCategory < 1) + throw new ArgumentException("wrong idCategory", nameof(dto)); + if (dto.Data is null) + throw new ArgumentException("data.data is not optional", nameof(dto)); var entity = await db.Measures - .Where(m => m.Id == data.Id && !m.IsDeleted) + .Where(m => m.Id == dto.Id && !m.IsDeleted) .FirstOrDefaultAsync(token) .ConfigureAwait(false); + if (entity is null) - throw new ArgumentException("id doesn't exist", nameof(data)); + throw new ArgumentException("id doesn't exist", nameof(dto)); + + var timezone = wellService.GetTimezone(idWell); entity.IdWell = idWell; - entity.Timestamp = data.Timestamp; - entity.Data = (RawData)data.Data; + entity.Timestamp = dto.Timestamp.ToUtcDateTimeOffset(timezone.Hours); + entity.Data = (RawData)dto.Data; return await db.SaveChangesAsync(token).ConfigureAwait(false); } diff --git a/AsbCloudInfrastructure/Services/MessageService.cs b/AsbCloudInfrastructure/Services/MessageService.cs index c815ceba..fc130abd 100644 --- a/AsbCloudInfrastructure/Services/MessageService.cs +++ b/AsbCloudInfrastructure/Services/MessageService.cs @@ -35,7 +35,6 @@ namespace AsbCloudInfrastructure.Services string searchString = default, int skip = 0, int take = 32, - bool isUtc = true, CancellationToken token = default) { var idTelemetry = telemetryService.GetIdTelemetryByIdWell(idWell); @@ -68,18 +67,17 @@ namespace AsbCloudInfrastructure.Services query = query.OrderByDescending(m => m.Date); - var timeZoneOffset = (await telemetryService.GetTimeZoneOffsetAsync(idTelemetry??default, token) - .ConfigureAwait(false)) ?? 0; + var timezone = telemetryService.GetTimezone(idTelemetry??default); if (begin != default) { - var beginUtc = telemetryService.TimeZoneService.DateToUtc(begin, timeZoneOffset); + var beginUtc = begin.ToUtcDateTimeOffset(timezone.Hours); query = query.Where(m => m.Date >= beginUtc); } if (end != default) { - var endUtc = telemetryService.TimeZoneService.DateToUtc(end, timeZoneOffset); + var endUtc = end.ToUtcDateTimeOffset(timezone.Hours); query = query.Where(m => m.Date <= endUtc); } @@ -109,9 +107,7 @@ namespace AsbCloudInfrastructure.Services WellDepth = message.WellDepth }; - messageDto.Date = isUtc - ? message.Date.UtcDateTime - : telemetryService.TimeZoneService.DateToTimeZone(message.Date, timeZoneOffset); + messageDto.Date = message.Date.ToRemoteDateTime(timezone.Hours); if (message.IdTelemetryUser is not null) { @@ -137,11 +133,6 @@ namespace AsbCloudInfrastructure.Services return result; } - [Obsolete("Use telemetryService.GetDatesRangeAsync instead", false)] - public Task GetMessagesDatesRangeAsync(int idWell, bool isUtc, - CancellationToken token = default) - => telemetryService.GetDatesRangeAsync(idWell, isUtc, token); - public Task InsertAsync(string uid, IEnumerable dtos, CancellationToken token = default) { @@ -149,10 +140,10 @@ namespace AsbCloudInfrastructure.Services return null; var telemetryId = telemetryService.GetOrCreateTelemetryIdByUid(uid); - var timeZoneOffset = telemetryService.GetTimezoneOffset(telemetryId); + var timezone = telemetryService.GetTimezone(telemetryId); var maxDateDto = dtos.Max(m => m.Date); - var maxDateUtc = maxDateDto.ToUtcDateTimeOffset(timeZoneOffset); + var maxDateUtc = maxDateDto.ToUtcDateTimeOffset(timezone.Hours); telemetryService.SaveRequestDate(uid, maxDateDto); foreach (var dto in dtos) @@ -160,7 +151,7 @@ namespace AsbCloudInfrastructure.Services var entity = dto.Adapt(); entity.Id = 0; entity.IdTelemetry = telemetryId; - entity.Date = dto.Date.ToUtcDateTimeOffset(timeZoneOffset); + entity.Date = dto.Date.ToUtcDateTimeOffset(timezone.Hours); db.TelemetryMessages.Add(entity); } diff --git a/AsbCloudInfrastructure/Services/ReportService.cs b/AsbCloudInfrastructure/Services/ReportService.cs index b81f6acf..20986967 100644 --- a/AsbCloudInfrastructure/Services/ReportService.cs +++ b/AsbCloudInfrastructure/Services/ReportService.cs @@ -19,17 +19,17 @@ namespace AsbCloudInfrastructure.Services private readonly IAsbCloudDbContext db; private readonly string connectionString; private readonly ITelemetryService telemetryService; - //private readonly IFileService fileService; private readonly IReportsBackgroundQueue queue; + private readonly IWellService wellService; public ReportService(IAsbCloudDbContext db, IConfiguration configuration, ITelemetryService telemetryService, - IReportsBackgroundQueue queue) + IReportsBackgroundQueue queue, IWellService wellService) { this.db = db; this.connectionString = configuration.GetConnectionString("DefaultConnection"); + this.wellService = wellService; this.telemetryService = telemetryService; - //this.fileService = fileService; this.queue = queue; ReportCategoryId = db.FileCategories.AsNoTracking() .FirstOrDefault(c => @@ -41,6 +41,12 @@ namespace AsbCloudInfrastructure.Services public int CreateReport(int idWell, int idUser, int stepSeconds, int format, DateTime begin, DateTime end, Action progressHandler) { + var timezoneOffset = wellService.GetTimezone(idWell).Hours; + var beginUtc = begin.ToUtcDateTimeOffset(timezoneOffset); + var endUtc = end.ToUtcDateTimeOffset(timezoneOffset); + var beginRemote = begin.ToTimeZoneOffsetHours(timezoneOffset); + var endRemote = end.ToTimeZoneOffsetHours(timezoneOffset); + var newReportId = queue.EnqueueTask((id) => { var optionsBuilder = new DbContextOptionsBuilder(); @@ -49,7 +55,7 @@ namespace AsbCloudInfrastructure.Services using var context = new AsbCloudDbContext(optionsBuilder.Options); - var generator = GetReportGenerator(idWell, begin, end, stepSeconds, format, context); + var generator = GetReportGenerator(idWell, beginRemote, endRemote, stepSeconds, format, context); var reportFileName = Path.Combine(tempDir, generator.GetReportDefaultFileName()); var totalPages = generator.GetPagesCount(); @@ -58,7 +64,7 @@ namespace AsbCloudInfrastructure.Services progressHandler.Invoke(e.Adapt(), id); }; generator.Make(reportFileName); - + var fileService = new FileService(context); var fileInfo = fileService.MoveAsync(idWell, idUser, ReportCategoryId, reportFileName, reportFileName).Result; @@ -75,8 +81,8 @@ namespace AsbCloudInfrastructure.Services { IdWell = idWell, IdFile = fileInfo.Id, - Begin = begin, - End = end, + Begin = beginUtc, + End = endUtc, Step = stepSeconds, Format = format }; @@ -93,77 +99,56 @@ namespace AsbCloudInfrastructure.Services public int GetReportPagesCount(int idWell, DateTime begin, DateTime end, int stepSeconds, int format) { - var generator = GetReportGenerator(idWell, begin, end, stepSeconds, format, (AsbCloudDbContext)db); - return generator.GetPagesCount(); + var timezoneOffset = wellService.GetTimezone(idWell).Hours; + var beginRemote = begin.ToTimeZoneOffsetHours(timezoneOffset); + var endRemote = end.ToTimeZoneOffsetHours(timezoneOffset); + + var generator = GetReportGenerator(idWell, beginRemote, endRemote, stepSeconds, format, (AsbCloudDbContext)db); + var pagesCount = generator.GetPagesCount(); + return pagesCount; } - public async Task GetReportsDatesRangeAsync(int idWell, bool isUtc, - CancellationToken token = default) + public DatesRangeDto GetDatesRangeOrDefault(int idWell) { - var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell); - - if (telemetryId is null) + var idTelemetry = telemetryService.GetIdTelemetryByIdWell(idWell); + if(idTelemetry is null) return null; - - var datesRange = await (from d in db.TelemetryDataSaub - where d.IdTelemetry == telemetryId - select d.Date).Union( - from m in db.TelemetryMessages - where m.IdTelemetry == telemetryId - select m.Date).DefaultIfEmpty() - .GroupBy(g => true) - .AsNoTracking() - .Select(g => new - { - From = g.Min(), - To = g.Max() - }).OrderBy(gr => gr.From) - .FirstOrDefaultAsync(token) - .ConfigureAwait(false); - - var result = new DatesRangeDto - { - From = datesRange.From, - To = datesRange.To.Year == 1 ? DateTime.MaxValue : datesRange.To - }; - - if (isUtc) - return result; - - result = await telemetryService.DatesRangeToTelemetryTimeZoneAsync((int)telemetryId, result, token) - .ConfigureAwait(false); - - return result; + var range = telemetryService.GetDatesRange((int)idTelemetry); + return range; } - public Task> GetAllReportsByWellAsync(int idWell, CancellationToken token) => - (from r in db.ReportProperties.Include(r => r.File) - where r.IdWell == idWell - select new ReportPropertiesDto - { - Id = r.Id, - Name = r.File.Name, - File = new FileInfoDto - { - Id = r.File.Id, - Author = null, - IdAuthor = r.File.IdAuthor ?? 0, - IdCategory = r.File.IdCategory, - IdWell = r.File.IdWell, - Name = r.File.Name, - Size = r.File.Size, - UploadDate = r.File.UploadDate, - }, - IdWell = r.IdWell, - Date = r.File.UploadDate, - Begin = r.Begin, - End = r.End, - Step = r.Step, - Format = r.Format == 0 ? ".pdf" : ".las" - }) - .OrderBy(o => o.Date) + public async Task> GetAllReportsByWellAsync(int idWell, CancellationToken token) + { + var timezoneOffset = wellService.GetTimezone(idWell).Hours; + var propertiesQuery = db.ReportProperties.Include(r => r.File) + .Where(p => p.IdWell == idWell) + .OrderBy(o => o.File.UploadDate) .AsNoTracking() - .Take(1024).ToListAsync(token); + .Take(1024); + var properties = await propertiesQuery.ToListAsync(token); + return properties.Select(p => new ReportPropertiesDto + { + Id = p.Id, + Name = p.File.Name, + File = new FileInfoDto + { + Id = p.File.Id, + Author = null, + IdAuthor = p.File.IdAuthor ?? 0, + IdCategory = p.File.IdCategory, + IdWell = p.File.IdWell, + Name = p.File.Name, + Size = p.File.Size, + UploadDate = p.File.UploadDate.ToRemoteDateTime(timezoneOffset), + }, + IdWell = p.IdWell, + Date = p.File.UploadDate.ToRemoteDateTime(timezoneOffset), + Begin = p.Begin.ToRemoteDateTime(timezoneOffset), + End = p.End.ToRemoteDateTime(timezoneOffset), + Step = p.Step, + Format = p.Format == 0 ? ".pdf" : ".las" + }); + } private static IReportGenerator GetReportGenerator(int idWell, DateTime begin, DateTime end, int stepSeconds, int format, AsbCloudDbContext context) diff --git a/AsbCloudInfrastructure/Services/TelemetryDataBaseService.cs b/AsbCloudInfrastructure/Services/TelemetryDataBaseService.cs index 289593d7..5de1ba70 100644 --- a/AsbCloudInfrastructure/Services/TelemetryDataBaseService.cs +++ b/AsbCloudInfrastructure/Services/TelemetryDataBaseService.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services { - public abstract class TelemetryDataBaseService : ITelemetryDataService, IConverter + public abstract class TelemetryDataBaseService : ITelemetryDataService where TDto : AsbCloudApp.Data.ITelemetryData where TModel : class, AsbCloudDb.Model.ITelemetryData { @@ -41,7 +41,6 @@ namespace AsbCloudInfrastructure.Services return 0; var idTelemetry = telemetryService.GetOrCreateTelemetryIdByUid(uid); - var lastTelemetryDate = telemetryService.GetLastTelemetryDate(uid); var dtosList = dtos.OrderBy(d => d.Date).ToList(); var dtoMinDate = dtosList.First().Date; @@ -57,11 +56,10 @@ namespace AsbCloudInfrastructure.Services dtosList.Remove(duplicate); } - var timeZoneOffset = (await telemetryService.GetTimeZoneOffsetAsync(idTelemetry, token)) ?? 0; + var timezone = telemetryService.GetTimezone(idTelemetry); var entities = dtosList.Select(dto => { - var entity = Convert(dto); - entity.Date = dto.Date.ToUtcDateTimeOffset(timeZoneOffset); + var entity = Convert(dto, timezone.Hours); entity.IdTelemetry = idTelemetry; return entity; }); @@ -91,7 +89,7 @@ namespace AsbCloudInfrastructure.Services public virtual async Task> GetAsync(int idWell, DateTime dateBegin = default, double intervalSec = 600d, - int approxPointsCount = 1024, bool isUtc = false, CancellationToken token = default) + int approxPointsCount = 1024, CancellationToken token = default) { var well = cacheWells.FirstOrDefault(w => w.Id == idWell); if (well?.IdTelemetry is null) @@ -99,20 +97,19 @@ namespace AsbCloudInfrastructure.Services var idTelemetry = well?.IdTelemetry ?? default; - var timeZoneOffset = (await telemetryService.GetTimeZoneOffsetAsync(idTelemetry, token)) ?? 0d; + var timezone = telemetryService.GetTimezone(idTelemetry); var filterByDateEnd = dateBegin != default; DateTimeOffset dateBeginUtc; if (dateBegin == default) { - dateBeginUtc = telemetryService.GetLastTelemetryDate(idTelemetry) - .UtcDateTime; + dateBeginUtc = telemetryService.GetLastTelemetryDate(idTelemetry, true); if (dateBeginUtc != default) dateBeginUtc = dateBeginUtc.AddSeconds(-intervalSec); } else { - dateBeginUtc = dateBegin.ToUtcDateTimeOffset(timeZoneOffset); + dateBeginUtc = dateBegin.ToUtcDateTimeOffset(timezone.Hours); } if (dateBeginUtc == default) @@ -126,7 +123,7 @@ namespace AsbCloudInfrastructure.Services && d.Date >= dateBeginUtc); if (filterByDateEnd) - query = query.Where(d => d.Date < dateEnd); + query = query.Where(d => d.Date <= dateEnd); var fullDataCount = await query.CountAsync(token) .ConfigureAwait(false); @@ -166,27 +163,13 @@ namespace AsbCloudInfrastructure.Services .ToListAsync(token) .ConfigureAwait(false); - var dtos = entities.Select(e => Convert(e)); - - if (isUtc) - return dtos; - - dtos = dtos.Select(d => - { - d.Date = d.Date.ToTimeZoneOffsetHours(timeZoneOffset); - return d; - }); - + var dtos = entities.Select(e => Convert(e, timezone.Hours)); + return dtos; } - [Obsolete("Use telemetryService.GetDatesRangeAsync instead", false)] - public virtual Task GetDataDatesRangeAsync(int idWell, bool isUtc, - CancellationToken token = default) - => telemetryService.GetDatesRangeAsync(idWell, isUtc, token); + public abstract TDto Convert(TModel src, double timezoneOffset); - public abstract TDto Convert(TModel src); - - public abstract TModel Convert(TDto src); + public abstract TModel Convert(TDto src, double timezoneOffset); } } diff --git a/AsbCloudInfrastructure/Services/TelemetryDataSaubService.cs b/AsbCloudInfrastructure/Services/TelemetryDataSaubService.cs index 5ac438c9..7a3dd68a 100644 --- a/AsbCloudInfrastructure/Services/TelemetryDataSaubService.cs +++ b/AsbCloudInfrastructure/Services/TelemetryDataSaubService.cs @@ -15,21 +15,23 @@ namespace AsbCloudInfrastructure.Services :base(db, telemetryService, cacheDb) {} - public override TelemetryDataSaub Convert(TelemetryDataSaubDto src) + public override TelemetryDataSaub Convert(TelemetryDataSaubDto src, double timezoneOffset) { var entity = src.Adapt(); var telemetryUser = cacheTelemetryUsers? .FirstOrDefault(u => u.IdTelemetry == src.IdTelemetry && (u.Name == src.User || u.Surname == src.User)); entity.IdUser = telemetryUser?.IdUser; + entity.Date = src.Date.ToUtcDateTimeOffset(timezoneOffset); return entity; } - public override TelemetryDataSaubDto Convert(TelemetryDataSaub src) + public override TelemetryDataSaubDto Convert(TelemetryDataSaub src, double timezoneOffset) { var dto = src.Adapt(); var telemetryUser = cacheTelemetryUsers? .FirstOrDefault(u => u.IdTelemetry == src.IdTelemetry && u.IdUser == src.IdUser); dto.User = telemetryUser?.MakeDisplayName(); + dto.Date = src.Date.ToRemoteDateTime(timezoneOffset); return dto; } } diff --git a/AsbCloudInfrastructure/Services/TelemetryDataSpinService.cs b/AsbCloudInfrastructure/Services/TelemetryDataSpinService.cs index 86ce23b5..11f5b4f9 100644 --- a/AsbCloudInfrastructure/Services/TelemetryDataSpinService.cs +++ b/AsbCloudInfrastructure/Services/TelemetryDataSpinService.cs @@ -15,15 +15,17 @@ namespace AsbCloudInfrastructure.Services : base(db, telemetryService, cacheDb) { } - public override TelemetryDataSpin Convert(TelemetryDataSpinDto src) + public override TelemetryDataSpin Convert(TelemetryDataSpinDto src, double timezoneOffset) { var entity = src.Adapt(); + entity.Date = src.Date.ToUtcDateTimeOffset(timezoneOffset); return entity; } - public override TelemetryDataSpinDto Convert(TelemetryDataSpin src) + public override TelemetryDataSpinDto Convert(TelemetryDataSpin src, double timezoneOffset) { var dto = src.Adapt(); + dto.Date = src.Date.ToRemoteDateTime(timezoneOffset); return dto; } } diff --git a/AsbCloudInfrastructure/Services/TelemetryService.cs b/AsbCloudInfrastructure/Services/TelemetryService.cs index 1ffb1048..fd745d4b 100644 --- a/AsbCloudInfrastructure/Services/TelemetryService.cs +++ b/AsbCloudInfrastructure/Services/TelemetryService.cs @@ -19,15 +19,15 @@ namespace AsbCloudInfrastructure.Services private readonly CacheTable cacheWells;//TODO: use wellService instead of this private readonly IAsbCloudDbContext db; private readonly ITelemetryTracker telemetryTracker; - private readonly ITimeZoneService timeZoneService; + private readonly ITimezoneService timezoneService; - public ITimeZoneService TimeZoneService => timeZoneService; + public ITimezoneService TimeZoneService => timezoneService; public ITelemetryTracker TelemetryTracker => telemetryTracker; public TelemetryService( IAsbCloudDbContext db, ITelemetryTracker telemetryTracker, - ITimeZoneService timeZoneService, + ITimezoneService timezoneService, CacheDb cacheDb) { cacheTelemetry = cacheDb.GetCachedTable((AsbCloudDbContext)db); @@ -39,7 +39,7 @@ namespace AsbCloudInfrastructure.Services nameof(Well.WellType)); this.db = db; this.telemetryTracker = telemetryTracker; - this.timeZoneService = timeZoneService; + this.timezoneService = timezoneService; } public IEnumerable GetTransmittingTelemetries() @@ -58,45 +58,40 @@ namespace AsbCloudInfrastructure.Services public void SaveRequestDate(string uid, DateTimeOffset remoteDate) => telemetryTracker.SaveRequestDate(uid, remoteDate); - public DateTimeOffset GetLastTelemetryDate(string telemetryUid) => - telemetryTracker.GetLastTelemetryDateByUid(telemetryUid); - - public DateTimeOffset GetLastTelemetryDate(int telemetryId) + public DateTime GetLastTelemetryDate(int idTelemetry, bool useUtc = false) { var lastTelemetryDate = DateTimeOffset.MinValue; - var telemetry = cacheTelemetry.FirstOrDefault(t => t.Id == telemetryId); + var telemetry = cacheTelemetry.FirstOrDefault(t => t.Id == idTelemetry); if (telemetry is null) - return lastTelemetryDate; + throw new Exception($"Telemetry id:{idTelemetry} does not exist"); var uid = telemetry.RemoteUid; + var timzone = GetTimezone(idTelemetry); - lastTelemetryDate = GetLastTelemetryDate(uid); - return lastTelemetryDate; + lastTelemetryDate = telemetryTracker.GetLastTelemetryDateByUid(uid); + + if (useUtc) + return lastTelemetryDate.UtcDateTime; + + return lastTelemetryDate.ToRemoteDateTime(timzone.Hours); } - public virtual async Task GetDatesRangeAsync( - int idWell, - bool isUtc, - CancellationToken token = default) + public DatesRangeDto GetDatesRange(int idTelemetry) { - var telemetryId = GetIdTelemetryByIdWell(idWell); - if (telemetryId is null) - return null; - - var telemetry = await cacheTelemetry.FirstOrDefaultAsync(t => t.Id == telemetryId, token) - .ConfigureAwait(false); + var telemetry = cacheTelemetry.FirstOrDefault(t => t.Id == idTelemetry); + if (telemetry is null) + throw new Exception($"Telemetry id:{idTelemetry} does not exist"); var dto = TelemetryTracker.GetTelemetryDateRangeByUid(telemetry.RemoteUid); + if (dto is null) + throw new Exception($"Telemetry id:{idTelemetry} has no data"); - if (isUtc) - return dto; - - dto = await DatesRangeToTelemetryTimeZoneAsync((int)telemetryId, dto, token) - .ConfigureAwait(false); + var timezone = GetTimezone((int)idTelemetry); + dto.From = dto.From.ToTimeZoneOffsetHours(timezone.Hours); + dto.To = dto.To.ToTimeZoneOffsetHours(timezone.Hours); return dto; - } public int GetOrCreateTelemetryIdByUid(string uid) @@ -113,7 +108,7 @@ namespace AsbCloudInfrastructure.Services if (!string.IsNullOrEmpty(info.TimeZoneId) && telemetry.TimeZone?.IsOverride != true) - telemetry.TimeZone = new TelemetryTimeZone() + telemetry.TimeZone = new SimpleTimezone() { Hours = info.TimeZoneOffsetTotalHours, TimeZoneId = info.TimeZoneId @@ -123,73 +118,43 @@ namespace AsbCloudInfrastructure.Services .ConfigureAwait(false); } - public double GetTimezoneOffset(int idTelemetry) => - cacheTelemetry.FirstOrDefault(t => t.Id == idTelemetry).Info?.TimeZoneOffsetTotalHours ?? 0d; - - public async Task GetTimeZoneOffsetAsync(int idTelemetry, CancellationToken token) + public SimpleTimezoneDto GetTimezone(int idTelemetry) { - var telemetry = - await cacheTelemetry.FirstOrDefaultAsync(t => t.Id == idTelemetry, token); + var telemetry = cacheTelemetry.FirstOrDefault(t => t.Id == idTelemetry); - if (!string.IsNullOrEmpty(telemetry.TimeZone?.TimeZoneId)) - return telemetry.TimeZone.Hours; + if (telemetry is null) + throw new Exception($"Telemetry id: {idTelemetry} does not exist."); - if (!string.IsNullOrEmpty(telemetry.Info?.TimeZoneId)) + if (telemetry.TimeZone is not null) + return telemetry.TimeZone.Adapt(); + + if (telemetry.Info is not null) { - telemetry.TimeZone = new TelemetryTimeZone + telemetry.TimeZone = new SimpleTimezone { Hours = telemetry.Info.TimeZoneOffsetTotalHours, IsOverride = false, TimeZoneId = telemetry.Info.TimeZoneId, }; - } - else - { - var well = await cacheWells.FirstOrDefaultAsync(t => t.IdTelemetry == telemetry.Id, token) - .ConfigureAwait(false); - - if (well is null) - return null; - - var coordinates = await GetWellCoordinatesAsync(well.Id, token); - - if (coordinates is null) - return null; - - var requestedTimeZone = await timeZoneService.GetByCoordinatesAsync(coordinates.Value.latitude, coordinates.Value.longitude, token) - .ConfigureAwait(false); - - if (requestedTimeZone is null) - return null; - - telemetry.TimeZone = requestedTimeZone.Adapt(); + cacheTelemetry.Upsert(telemetry); + return telemetry.TimeZone.Adapt(); } - await cacheTelemetry.UpsertAsync(telemetry, token).ConfigureAwait(false); - - return telemetry.TimeZone.Hours; - } - - public async Task DatesRangeToTelemetryTimeZoneAsync(int idTelemetry, DatesRangeDto range, - CancellationToken token) - { - var offset = await GetTimeZoneOffsetAsync(idTelemetry, token); - - if (offset is null) - return range; - - return new DatesRangeDto() + if (telemetry.Well?.Timezone is not null) { - From = range.From.ToTimeZoneOffsetHours(offset ?? default), - To = range.To.ToTimeZoneOffsetHours(offset ?? default), - }; + telemetry.TimeZone = telemetry.Well.Timezone; + cacheTelemetry.Upsert(telemetry); + return telemetry.TimeZone.Adapt(); + } + + throw new Exception($"Telemetry id: {idTelemetry} can't find timezone."); } - public async Task UpdateTimeZoneAsync(string uid, TelemetryTimeZoneDto timeZoneInfo, + public async Task UpdateTimezoneAsync(string uid, SimpleTimezoneDto timeone, CancellationToken token) { var telemetry = GetOrCreateTelemetryByUid(uid); - var newTelemetryTimeZone = timeZoneInfo.Adapt(); + var newTelemetryTimeZone = timeone.Adapt(); if (newTelemetryTimeZone?.Equals(telemetry.TimeZone) == true) return; await cacheTelemetry.UpsertAsync(telemetry, token) @@ -202,29 +167,6 @@ namespace AsbCloudInfrastructure.Services return well?.IdTelemetry; } - private async Task<(double latitude, double longitude)?> GetWellCoordinatesAsync(int idWell, - CancellationToken token) - { - var well = await cacheWells.FirstOrDefaultAsync(w => w.Id == idWell, token) - .ConfigureAwait(false); - - if (well is null) - return null; - - var latitude = well.Latitude ?? - well.Cluster?.Latitude ?? - well.Cluster?.Deposit?.Latitude; - - var longitude = well.Longitude ?? - well.Cluster?.Longitude ?? - well.Cluster?.Deposit?.Longitude; - - if (latitude is not null && longitude is not null) - return ((double)latitude, (double)longitude); - - return null; - } - private Well GetWellByTelemetryUid(string uid) { var tele = cacheTelemetry.FirstOrDefault(t => t.RemoteUid == uid); diff --git a/AsbCloudInfrastructure/Services/TelemetryTracker.cs b/AsbCloudInfrastructure/Services/TelemetryTracker.cs index 1808dea4..c05f2995 100644 --- a/AsbCloudInfrastructure/Services/TelemetryTracker.cs +++ b/AsbCloudInfrastructure/Services/TelemetryTracker.cs @@ -28,12 +28,12 @@ namespace AsbCloudInfrastructure.Services /// /// Дата первых данных в БД /// - public DateTimeOffset TelemetryDateMin { get; set; } + public DateTimeOffset TelemetryDateUtcMin { get; set; } /// /// Дата последних данных в БД /// - public DateTimeOffset TelemetryDateMax { get; set; } + public DateTimeOffset TelemetryDateUtcMax { get; set; } } @@ -56,8 +56,8 @@ namespace AsbCloudInfrastructure.Services keyValuePairs[telemetry.RemoteUid] = new TrackerStat { RemoteUid = telemetry.RemoteUid, - TelemetryDateMin = date, - TelemetryDateMax = date, + TelemetryDateUtcMin = date, + TelemetryDateUtcMax = date, LastTimeServer = date, }; } @@ -88,8 +88,8 @@ namespace AsbCloudInfrastructure.Services foreach (var oldReq in oldRequests) { var telemetryStat = telemetriesStats.GetOrAdd(oldReq.Uid, (uid) => new TrackerStat { RemoteUid = uid }); - telemetryStat.TelemetryDateMin = oldReq.DateMin; - telemetryStat.TelemetryDateMax = oldReq.DateMax; + telemetryStat.TelemetryDateUtcMin = oldReq.DateMin; + telemetryStat.TelemetryDateUtcMax = oldReq.DateMax; telemetryStat.LastTimeServer = oldReq.DateMax; } }).ContinueWith((t) => @@ -118,25 +118,25 @@ namespace AsbCloudInfrastructure.Services { var stat = telemetriesStats.GetOrAdd(uid, _ => new TrackerStat { RemoteUid = uid, - TelemetryDateMin = remoteDate} + TelemetryDateUtcMin = remoteDate} ); stat.LastTimeServer = DateTime.Now; - if(stat.TelemetryDateMax.ToUniversalTime() < remoteDate.ToUniversalTime()) - stat.TelemetryDateMax = remoteDate; + if(stat.TelemetryDateUtcMax.ToUniversalTime() < remoteDate.ToUniversalTime()) + stat.TelemetryDateUtcMax = remoteDate; } public DateTimeOffset GetLastTelemetryDateByUid(string uid) => - telemetriesStats.GetValueOrDefault(uid)?.TelemetryDateMax ?? default; + telemetriesStats.GetValueOrDefault(uid)?.TelemetryDateUtcMax ?? default; public DatesRangeDto GetTelemetryDateRangeByUid(string uid) { var stat = telemetriesStats.GetValueOrDefault(uid); var range = new DatesRangeDto { - From = stat?.TelemetryDateMin.UtcDateTime ?? default, - To = stat?.TelemetryDateMax.UtcDateTime ?? default, + From = stat?.TelemetryDateUtcMin.UtcDateTime ?? default, + To = stat?.TelemetryDateUtcMax.UtcDateTime ?? default, }; return range; } diff --git a/AsbCloudInfrastructure/Services/TimeZoneService.cs b/AsbCloudInfrastructure/Services/TimeZoneService.cs index 6400b044..0b52aa86 100644 --- a/AsbCloudInfrastructure/Services/TimeZoneService.cs +++ b/AsbCloudInfrastructure/Services/TimeZoneService.cs @@ -8,7 +8,7 @@ using System; namespace AsbCloudInfrastructure.Services { - public class TimeZoneService : ITimeZoneService + public class TimezoneService : ITimezoneService { private class TimeZoneInfo { @@ -25,16 +25,19 @@ namespace AsbCloudInfrastructure.Services public string Time { get; set; } } - private const string timeZoneApiUrl = "http://api.geonames.org/timezoneJSON"; + private const string timezoneApiUrl = "http://api.geonames.org/timezoneJSON"; private const string timezoneApiUserName = "asbautodrilling"; - public async Task GetByCoordinatesAsync(double latitude, double longitude, CancellationToken token) + public SimpleTimezoneDto GetByCoordinates(double latitude, double longitude) + => GetByCoordinatesAsync(latitude, longitude, default).Result; + + public async Task GetByCoordinatesAsync(double latitude, double longitude, CancellationToken token) { var lat = latitude.ToString(System.Globalization.CultureInfo.InvariantCulture); var lng = longitude.ToString(System.Globalization.CultureInfo.InvariantCulture); var url = - $"{timeZoneApiUrl}?lat={lat}&lng={lng}&username={timezoneApiUserName}"; + $"{timezoneApiUrl}?lat={lat}&lng={lng}&username={timezoneApiUserName}"; using var client = new HttpClient(); @@ -51,13 +54,13 @@ namespace AsbCloudInfrastructure.Services { PropertyNameCaseInsensitive = true }; - var timeZoneInfo = JsonSerializer.Deserialize(responseJson, options); + var timezoneInfo = JsonSerializer.Deserialize(responseJson, options); - return new TelemetryTimeZoneDto + return new SimpleTimezoneDto { - Hours = timeZoneInfo.DstOffset, + Hours = timezoneInfo.DstOffset, IsOverride = false, - TimeZoneId = timeZoneInfo.TimezoneId, + TimezoneId = timezoneInfo.TimezoneId, }; } diff --git a/AsbCloudInfrastructure/Services/WellOperationService/OperationsStatService.cs b/AsbCloudInfrastructure/Services/WellOperationService/OperationsStatService.cs index 4ec0ddd9..480aaebb 100644 --- a/AsbCloudInfrastructure/Services/WellOperationService/OperationsStatService.cs +++ b/AsbCloudInfrastructure/Services/WellOperationService/OperationsStatService.cs @@ -143,7 +143,8 @@ namespace AsbCloudInfrastructure.Services.WellOperationService var statsList = clusterWellsIds.Select(clusterWellId => { var currentWellOps = operations.Where(o => o.IdWell == clusterWellId); - var stat = CalcStat(currentWellOps); + var timezoneOffsetH = wellService.GetTimezone(clusterWellId).Hours; + var stat = CalcStat(currentWellOps, timezoneOffsetH); return stat; }).Where(c => c is not null); @@ -161,8 +162,7 @@ namespace AsbCloudInfrastructure.Services.WellOperationService private async Task CalcStatWellAsync(Well well, CancellationToken token = default) { - var wellType = await cacheWellType.FirstOrDefaultAsync(t => t.Id == well.IdWellType, token); - + var wellType = await cacheWellType.FirstOrDefaultAsync(t => t.Id == well.IdWellType, token); var statWellDto = new StatWellDto() { Id = well.Id, @@ -170,7 +170,7 @@ namespace AsbCloudInfrastructure.Services.WellOperationService WellType = wellType?.Caption ?? "", IdState = well.IdState, State = wellService.GetStateText(well.IdState), - LastTelemetryDate = wellService.GetLastTelemetryDate(well.Id), + LastTelemetryDate = wellService.GetLastTelemetryDate(well.Id).DateTime, }; statWellDto.Companies = await wellService.GetCompaniesAsync(well.Id, token); @@ -185,13 +185,14 @@ namespace AsbCloudInfrastructure.Services.WellOperationService if (!wellOperations.Any()) return statWellDto; - statWellDto.Sections = CalcSectionsStats(wellOperations); - statWellDto.Total = GetStatTotal(wellOperations, well.IdState); + var timezoneOffsetH = wellService.GetTimezone(well.Id).Hours; + statWellDto.Sections = CalcSectionsStats(wellOperations, timezoneOffsetH); + statWellDto.Total = GetStatTotal(wellOperations, well.IdState, timezoneOffsetH); return statWellDto; } - private IEnumerable CalcSectionsStats(IEnumerable operations) + private IEnumerable CalcSectionsStats(IEnumerable operations, double timezoneOffsetH) { var sectionTypeIds = operations .Select(o => o.IdWellSectionType) @@ -211,8 +212,8 @@ namespace AsbCloudInfrastructure.Services.WellOperationService { Id = id, Caption = sectionType.Caption, - Plan = CalcSectionStat(operationsPlan, id), - Fact = CalcSectionStat(operationsFact, id), + Plan = CalcSectionStat(operationsPlan, id, timezoneOffsetH), + Fact = CalcSectionStat(operationsFact, id, timezoneOffsetH), }; sections.Add(section); } @@ -220,42 +221,42 @@ namespace AsbCloudInfrastructure.Services.WellOperationService } private static PlanFactBase GetStatTotal(IEnumerable operations, - int idWellState) + int idWellState, double timezoneOffsetH) { var operationsPlan = operations.Where(o => o.IdType == idOperationTypePlan); var operationsFact = operations.Where(o => o.IdType == idOperationTypeFact); - var factEnd = CalcStat(operationsFact); + var factEnd = CalcStat(operationsFact, timezoneOffsetH); if (idWellState != 2) factEnd.End = null; var section = new PlanFactBase { - Plan = CalcStat(operationsPlan), + Plan = CalcStat(operationsPlan, timezoneOffsetH), Fact = factEnd, }; return section; } - private static StatOperationsDto CalcSectionStat(IEnumerable operations, int idSectionType) + private static StatOperationsDto CalcSectionStat(IEnumerable operations, int idSectionType, double timezoneOffsetH) { var sectionOperations = operations .Where(o => o.IdWellSectionType == idSectionType) .OrderBy(o => o.DateStart) .ThenBy(o => o.DepthStart); - return CalcStat(sectionOperations); + return CalcStat(sectionOperations, timezoneOffsetH); } - private static StatOperationsDto CalcStat(IEnumerable operations) + private static StatOperationsDto CalcStat(IEnumerable operations, double timezoneOffsetH) { if (!operations.Any()) return null; - var races = GetCompleteRaces(operations); + var races = GetCompleteRaces(operations, timezoneOffsetH); var section = new StatOperationsDto { - Start = operations.FirstOrDefault()?.DateStart, - End = operations.Max(o => o.DateStart.AddHours(o.DurationHours)), + Start = operations.FirstOrDefault()?.DateStart.ToRemoteDateTime(timezoneOffsetH), + End = operations.Max(o => o.DateStart.ToRemoteDateTime(timezoneOffsetH).AddHours(o.DurationHours)), WellDepthStart = operations.Min(o => o.DepthStart), WellDepthEnd = operations.Max(o => o.DepthStart), Rop = CalcROP(operations), @@ -297,7 +298,7 @@ namespace AsbCloudInfrastructure.Services.WellOperationService return depth / (dHours + double.Epsilon); } - private static IEnumerable GetCompleteRaces(IEnumerable operations) + private static IEnumerable GetCompleteRaces(IEnumerable operations, double timezoneOffsetH) { var races = new List(); var iterator = operations @@ -309,7 +310,7 @@ namespace AsbCloudInfrastructure.Services.WellOperationService { var race = new Race { - StartDate = iterator.Current.DateStart.AddHours(iterator.Current.DurationHours), + StartDate = iterator.Current.DateStart.ToRemoteDateTime(timezoneOffsetH).AddHours(iterator.Current.DurationHours), StartWellDepth = iterator.Current.DepthStart, Operations = new List(10), }; @@ -321,7 +322,7 @@ namespace AsbCloudInfrastructure.Services.WellOperationService } if (iterator.Current.IdCategory == idOperationBhaDisassembly) { - race.EndDate = iterator.Current.DateStart; + race.EndDate = iterator.Current.DateStart.ToRemoteDateTime(timezoneOffsetH); race.EndWellDepth = iterator.Current.DepthStart; races.Add(race); break; diff --git a/AsbCloudInfrastructure/Services/WellOperationService/WellOperationImportService.cs b/AsbCloudInfrastructure/Services/WellOperationService/WellOperationImportService.cs index 60507aa8..5576323c 100644 --- a/AsbCloudInfrastructure/Services/WellOperationService/WellOperationImportService.cs +++ b/AsbCloudInfrastructure/Services/WellOperationService/WellOperationImportService.cs @@ -35,7 +35,7 @@ namespace AsbCloudInfrastructure.Services.WellOperationService private static readonly TimeSpan drillingDurationLimitMax = TimeSpan.FromDays(366); private readonly IAsbCloudDbContext db; - + private readonly IWellService wellService; private List categories = null; public List Categories { @@ -65,9 +65,10 @@ namespace AsbCloudInfrastructure.Services.WellOperationService } } - public WellOperationImportService(IAsbCloudDbContext db) + public WellOperationImportService(IAsbCloudDbContext db, IWellService wellService) { this.db = db; + this.wellService = wellService; } public void Import(int idWell, Stream stream, bool deleteWellOperationsBeforeImport = false) @@ -93,7 +94,9 @@ namespace AsbCloudInfrastructure.Services.WellOperationService if (!operations.Any()) return null; - return MakeExelFileStream(operations); + var timezone = wellService.GetTimezone(idWell); + + return MakeExelFileStream(operations, timezone.Hours); } public Stream GetExcelTemplateStream() { @@ -102,12 +105,12 @@ namespace AsbCloudInfrastructure.Services.WellOperationService return stream; } - private Stream MakeExelFileStream(IEnumerable operations) + private Stream MakeExelFileStream(IEnumerable operations, double timezoneOffset) { using Stream ecxelTemplateStream = GetExcelTemplateStream(); using var workbook = new XLWorkbook(ecxelTemplateStream, XLEventTracking.Disabled); - AddOperationsToWorkbook(workbook, operations); + AddOperationsToWorkbook(workbook, operations, timezoneOffset); MemoryStream memoryStream = new MemoryStream(); workbook.SaveAs(memoryStream, new SaveOptions { }); @@ -115,53 +118,61 @@ namespace AsbCloudInfrastructure.Services.WellOperationService return memoryStream; } - private static void AddOperationsToWorkbook(XLWorkbook workbook, IEnumerable operations) + private static void AddOperationsToWorkbook(XLWorkbook workbook, IEnumerable operations, double timezoneOffset) { var planOperations = operations.Where(o => o.IdType == 0); if (planOperations.Any()) { var sheetPlan = workbook.Worksheets.FirstOrDefault(ws => ws.Name == sheetNamePlan); - AddOperationsToSheet(sheetPlan, planOperations); + AddOperationsToSheet(sheetPlan, planOperations, timezoneOffset); } var factOperations = operations.Where(o => o.IdType == 1); if (factOperations.Any()) { var sheetFact = workbook.Worksheets.FirstOrDefault(ws => ws.Name == sheetNameFact); - AddOperationsToSheet(sheetFact, factOperations); + AddOperationsToSheet(sheetFact, factOperations, timezoneOffset); } } - private static void AddOperationsToSheet(IXLWorksheet sheet, IEnumerable operations) + private static void AddOperationsToSheet(IXLWorksheet sheet, IEnumerable operations, double timezoneOffset) { var operationsList = operations.ToList(); for (int i = 0; i < operationsList.Count; i++) { var row = sheet.Row(1 + i + headerRowsCount); - AddOperationToRow(row, operationsList[i]); + AddOperationToRow(row, operationsList[i], timezoneOffset); } } - private static void AddOperationToRow(IXLRow row, WellOperation operation) + private static void AddOperationToRow(IXLRow row, WellOperation operation, double timezoneOffset) { row.Cell(columnSection).Value = operation.WellSectionType?.Caption; row.Cell(columnCategory).Value = operation.OperationCategory?.Name; row.Cell(columnCategoryInfo).Value = operation.CategoryInfo; row.Cell(columnDepthStart).Value = operation.DepthStart; row.Cell(columnDepthEnd).Value = operation.DepthEnd; - row.Cell(columnDate).Value = operation.DateStart; + row.Cell(columnDate).Value = operation.DateStart.ToRemoteDateTime(timezoneOffset); row.Cell(columnDuration).Value = operation.DurationHours; row.Cell(columnComment).Value = operation.Comment; } private void SaveOperations(int idWell, IEnumerable operations, bool deleteWellOperationsBeforeImport = false) { + var timezone = wellService.GetTimezone(idWell); + var transaction = db.Database.BeginTransaction(); try { if (deleteWellOperationsBeforeImport) db.WellOperations.RemoveRange(db.WellOperations.Where(o => o.IdWell == idWell)); - db.WellOperations.AddRange(operations.Adapt()); + var entities = operations.Select(o => { + var entity = o.Adapt(); + entity.IdWell = idWell; + entity.DateStart = o.DateStart.ToUtcDateTimeOffset(timezone.Hours); + return entity; + }); + db.WellOperations.AddRange(entities); db.SaveChanges(); transaction.Commit(); } @@ -204,7 +215,7 @@ namespace AsbCloudInfrastructure.Services.WellOperationService { if (sheet.RangeUsed().RangeAddress.LastAddress.ColumnNumber < 7) - throw new FileFormatException($"Лист {sheet.Name} содержит меньшее количество столбцев."); + throw new FileFormatException($"Лист {sheet.Name} содержит меньшее количество столбцов."); var count = sheet.RowsUsed().Count() - headerRowsCount; diff --git a/AsbCloudInfrastructure/Services/WellOperationService/WellOperationImportTemplate.xlsx b/AsbCloudInfrastructure/Services/WellOperationService/WellOperationImportTemplate.xlsx index 31b8273e..394321d5 100644 Binary files a/AsbCloudInfrastructure/Services/WellOperationService/WellOperationImportTemplate.xlsx and b/AsbCloudInfrastructure/Services/WellOperationService/WellOperationImportTemplate.xlsx differ diff --git a/AsbCloudInfrastructure/Services/WellOperationService/WellOperationService.cs b/AsbCloudInfrastructure/Services/WellOperationService/WellOperationService.cs index 37482077..6de4a701 100644 --- a/AsbCloudInfrastructure/Services/WellOperationService/WellOperationService.cs +++ b/AsbCloudInfrastructure/Services/WellOperationService/WellOperationService.cs @@ -52,13 +52,13 @@ namespace AsbCloudInfrastructure.Services.WellOperationService int take = 32, CancellationToken token = default) { + var timezone = wellService.GetTimezone(idWell); + var query = db.WellOperations .Include(s => s.WellSectionType) .Include(s => s.OperationCategory) .Where(s => s.IdWell == idWell); - var timeZoneOffset = await wellService.GetTimeZoneOffsetAsync(idWell,token); - if (operationType != default) query = query.Where(e => e.IdType == (int)operationType); @@ -76,12 +76,15 @@ namespace AsbCloudInfrastructure.Services.WellOperationService if (begin != default) { - query = query.Where(e => e.DateStart >= begin); + var beginOffset = begin.ToUtcDateTimeOffset(timezone.Hours); + query = query.Where(e => e.DateStart >= beginOffset); } if (end != default) { - query = query.Where(e => e.DateStart <= end); + + var endOffset = end.ToUtcDateTimeOffset(timezone.Hours); + query = query.Where(e => e.DateStart <= endOffset); } var result = new PaginationContainer @@ -102,11 +105,12 @@ namespace AsbCloudInfrastructure.Services.WellOperationService var entities = await query.Take(take).AsNoTracking() .ToListAsync(token).ConfigureAwait(false); - foreach (var item in entities) + foreach (var entity in entities) { - var dto = item.Adapt(); - dto.WellSectionTypeName = item.WellSectionType.Caption; - dto.CategoryName = item.OperationCategory.Name; + var dto = entity.Adapt(); + dto.WellSectionTypeName = entity.WellSectionType.Caption; + dto.DateStart = entity.DateStart.ToRemoteDateTime(timezone.Hours); + dto.CategoryName = entity.OperationCategory.Name; result.Items.Add(dto); } @@ -116,6 +120,7 @@ namespace AsbCloudInfrastructure.Services.WellOperationService public async Task GetAsync(int id, CancellationToken token = default) { + var entity = await db.WellOperations .Include(s => s.WellSectionType) .Include(s => s.OperationCategory) @@ -125,8 +130,11 @@ namespace AsbCloudInfrastructure.Services.WellOperationService if (entity is null) return null; + var timezone = wellService.GetTimezone(entity.IdWell); + var dto = entity.Adapt(); dto.WellSectionTypeName = entity.WellSectionType.Caption; + dto.DateStart = entity.DateStart.ToRemoteDateTime(timezone.Hours); dto.CategoryName = entity.OperationCategory.Name; return dto; } @@ -135,10 +143,12 @@ namespace AsbCloudInfrastructure.Services.WellOperationService IEnumerable wellOperationDtos, CancellationToken token = default) { - foreach (var operationDto in wellOperationDtos) + var timezone = wellService.GetTimezone(idWell); + foreach (var dto in wellOperationDtos) { - var entity = operationDto.Adapt(); + var entity = dto.Adapt(); entity.Id = default; + entity.DateStart = dto.DateStart.ToUtcDateTimeOffset(timezone.Hours); entity.IdWell = idWell; db.WellOperations.Add(entity); } @@ -148,11 +158,12 @@ namespace AsbCloudInfrastructure.Services.WellOperationService } public async Task UpdateAsync(int idWell, int idOperation, - WellOperationDto item, CancellationToken token = default) + WellOperationDto dto, CancellationToken token = default) { - var entity = item.Adapt(); + var timezone = wellService.GetTimezone(idWell); + var entity = dto.Adapt(); entity.Id = idOperation; - entity.IdWell = idWell; + entity.DateStart = dto.DateStart.ToUtcDateTimeOffset(timezone.Hours); db.WellOperations.Update(entity); return await db.SaveChangesAsync(token) .ConfigureAwait(false); diff --git a/AsbCloudInfrastructure/Services/WellService.cs b/AsbCloudInfrastructure/Services/WellService.cs index 77e081bb..a9fae71a 100644 --- a/AsbCloudInfrastructure/Services/WellService.cs +++ b/AsbCloudInfrastructure/Services/WellService.cs @@ -5,7 +5,6 @@ using AsbCloudInfrastructure.Services.Cache; using Mapster; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -28,13 +27,15 @@ namespace AsbCloudInfrastructure.Services private readonly ITelemetryService telemetryService; private readonly CacheTable cacheRelationCompaniesWells; private readonly CacheTable cacheCompanyWellTypes; + private readonly ITimezoneService timezoneService; public ITelemetryService TelemetryService => telemetryService; - public WellService(IAsbCloudDbContext db, CacheDb cacheDb, ITelemetryService telemetryService) + public WellService(IAsbCloudDbContext db, CacheDb cacheDb, ITelemetryService telemetryService, ITimezoneService timezoneService) :base(db, cacheDb) { this.telemetryService = telemetryService; + this.timezoneService = timezoneService; cacheRelationCompaniesWells = cacheDb.GetCachedTable((AsbCloudDbContext)db, nameof(RelationCompanyWell.Company), nameof(RelationCompanyWell.Well)); cacheCompanyWellTypes = cacheDb.GetCachedTable((AsbCloudDbContext)db); Includes.Add($"{nameof(Well.Cluster)}.{nameof(Cluster.Deposit)}"); @@ -60,7 +61,7 @@ namespace AsbCloudInfrastructure.Services .WhereAsync(r => r.IdCompany == idCompany, token); var wellsIds = relations.Select(r => r.IdWell); - var wells = await Cache.WhereAsync(w => wellsIds.Contains(w.Id)); + var wells = await Cache.WhereAsync(w => wellsIds.Contains(w.Id), token); var dtos = wells.Select(Convert); return dtos; @@ -179,17 +180,21 @@ namespace AsbCloudInfrastructure.Services protected override Well Convert(WellDto dto) { var entity = dto.Adapt(typeAdapterConfig); - //dto.WellType = entity.WellType?.Caption; - //dto.Cluster = entity.Cluster?.Caption; - //dto.Deposit = entity.Cluster?.Deposit?.Caption; - //dto.LastTelemetryDate = GetLastTelemetryDate(entity.Id); - //dto.Companies = GetCompanies(entity.Id); + if (dto.Timezone is null) + entity.Timezone = GetTimezone(dto.Id).Adapt(); return entity; } protected override WellDto Convert(Well entity) { + if (entity is null) + return null; + var dto = base.Convert(entity); + + if (entity.Timezone is null) + dto.Timezone = GetTimezone(entity); + dto.WellType = entity.WellType?.Caption; dto.Cluster = entity.Cluster?.Caption; dto.Deposit = entity.Cluster?.Deposit?.Caption; @@ -206,25 +211,105 @@ namespace AsbCloudInfrastructure.Services return dto; } - public DateTimeOffset DateToUtc(int idWell, DateTime date) + public void EnshureTimezonesIsSet() { - var GetTimeZoneOffset(int idWell) + var wells = Cache.Where(w => w.Timezone is null).ToList(); + foreach (var well in wells) + well.Timezone = GetTimezone(well).Adapt(); + var wellsWithTz = wells.Where(w => w.Timezone is not null); + if (wellsWithTz.Any()) + { + var adaptedWells = wellsWithTz.Adapt().Select(Convert); + Cache.Upsert(adaptedWells); + } } - public DateTime DateToTimeZone(DateTimeOffset date, double remoteTimezoneOffsetHours); - - public double? GetTimeZoneOffset(int idWell) + public SimpleTimezoneDto GetTimezone(int idWell) { - // TODO: Add timeZoneOffset into Db.Well. - var idTelemetry = telemetryService.GetIdTelemetryByIdWell(idWell); - if (idTelemetry is not null) + var well = Cache.FirstOrDefault(c => c.Id == idWell); + if (well == null) + throw new ArgumentException($"idWell: {idWell} does not exist.", nameof(idWell)); + return GetTimezone(well); + } + + private SimpleTimezoneDto GetTimezone(Well well) + { + if (well == null) + throw new ArgumentNullException(nameof(well)); + + if (well.Timezone is not null) + return well.Timezone.Adapt(); + + if (well.Telemetry is not null) { - var timeZoneOffset = telemetryService.GetTimeZoneOffset((int)idTelemetry); - if (timeZoneOffset is not null) - return timeZoneOffset; + var timezone = telemetryService.GetTimezone(well.Telemetry.Id); + if (timezone is not null) + { + well.Timezone = timezone.Adapt(); + return timezone; + } } - Trace.WriteLine("No timeZoneOffset"); - return null; + + var point = GetCoordinates(well); + if (point is not null) + { + if (point.Timezone is not null) + { + well.Timezone = point.Timezone; + return point.Timezone.Adapt(); + } + + if (point.Latitude is not null & point.Longitude is not null) + { + var timezone = timezoneService.GetByCoordinates((double)point.Latitude, (double)point.Longitude); + if (timezone is not null) + { + well.Timezone = timezone.Adapt(); + return timezone; + } + } + } + + throw new Exception($"Can't find timezone for well {well.Caption} id: {well.Id}"); + } + + private static AsbCloudDb.Model.IMapPoint GetCoordinates(Well well) + { + if(well is null) + throw new ArgumentNullException(nameof(well)); + + if (well.Latitude is not null & well.Longitude is not null) + return well; + + if (well.Cluster is null) + throw new Exception($"Can't find coordinates of well {well.Caption} id: {well.Id}"); + + var cluster = well.Cluster; + + if (cluster.Latitude is not null & cluster.Longitude is not null) + return cluster; + + if (cluster.Deposit is null) + throw new Exception($"Can't find coordinates of well by cluster {cluster.Caption} id: {cluster.Id}"); + + var deposit = cluster.Deposit; + + if (deposit.Latitude is not null & deposit.Longitude is not null) + return deposit; + + throw new Exception($"Can't find coordinates of well by deposit {deposit.Caption} id: {deposit.Id}"); + } + + public DatesRangeDto GetDatesRange(int idWell) + { + var well = Cache.FirstOrDefault(w => w.Id == idWell); + if (well is null) + throw new Exception($"Well id: {idWell} does not exist."); + + if (well.IdTelemetry is null) + throw new Exception($"Well id: {idWell} does not contain telemetry."); + + return telemetryService.GetDatesRange((int)well.IdTelemetry); } } } diff --git a/AsbCloudWebApi/Controllers/AdminWellController.cs b/AsbCloudWebApi/Controllers/AdminWellController.cs index 94a5739b..f1a211ef 100644 --- a/AsbCloudWebApi/Controllers/AdminWellController.cs +++ b/AsbCloudWebApi/Controllers/AdminWellController.cs @@ -13,8 +13,14 @@ namespace AsbCloudWebApi.Controllers public AdminWellController(IWellService service) :base(service) { - service.Includes.Add("Telemetry"); + service.Includes.Add("Telemetry"); } + [HttpPost("EnshureTimezonesIsSet")] + public IActionResult EnsureTimestamps() + { + ((IWellService)service).EnshureTimezonesIsSet(); + return Ok(); + } } } diff --git a/AsbCloudWebApi/Controllers/DrillFlowChartController.cs b/AsbCloudWebApi/Controllers/DrillFlowChartController.cs index 6b17dbcd..adaccda4 100644 --- a/AsbCloudWebApi/Controllers/DrillFlowChartController.cs +++ b/AsbCloudWebApi/Controllers/DrillFlowChartController.cs @@ -10,7 +10,7 @@ using Microsoft.AspNetCore.Authorization; namespace AsbCloudWebApi.Controllers { /// - /// Контроллер для корридоров бурения на панели + /// Контроллер для коридоров бурения на панели /// [ApiController] [Authorize] @@ -29,12 +29,12 @@ namespace AsbCloudWebApi.Controllers } /// - /// Возвращает все значения для корридоров бурения по id скважины + /// Возвращает все значения для коридоров бурения по id скважины /// /// id скважины /// Дата, с которой следует искать новые параметры /// Токен отмены задачи - /// Список параметров для корридоров бурения + /// Список параметров для коридоров бурения [HttpGet] [Route("api/well/{idWell}/drillFlowChart")] [ProducesResponseType(typeof(IEnumerable), (int) System.Net.HttpStatusCode.OK)] @@ -54,12 +54,12 @@ namespace AsbCloudWebApi.Controllers } /// - /// Возвращает все значения для корридоров бурения по uid панели + /// Возвращает все значения для коридоров бурения по uid панели /// /// uid панели /// Дата, с которой следует искать новые параметры /// Токен отмены задачи - /// Список параметров для корридоров бурения + /// Список параметров для коридоров бурения [HttpGet] [Route("api/telemetry/{uid}/drillFlowChart")] [AllowAnonymous] @@ -77,10 +77,10 @@ namespace AsbCloudWebApi.Controllers } /// - /// Сохраняет значения для корридоров бурения + /// Сохраняет значения для коридоров бурения /// /// id скважины - /// Параметры корридоров бурения + /// Параметры коридоров бурения /// Токен отмены задачи /// [HttpPost] @@ -101,10 +101,10 @@ namespace AsbCloudWebApi.Controllers } /// - /// Добавляет массив объектов корридоров бурения + /// Добавляет массив объектов коридоров бурения /// /// id скважины - /// Массив объектов параметров корридоров бурения + /// Массив объектов параметров коридоров бурения /// Токен отмены задачи /// [HttpPost] @@ -126,10 +126,10 @@ namespace AsbCloudWebApi.Controllers } /// - /// Изменяет значения выбранного корридора бурения + /// Изменяет значения выбранного коридора бурения /// /// id скважины - /// Параметры корридоров бурения + /// Параметры коридоров бурения /// Токен отмены задачи /// [HttpPut] @@ -151,10 +151,10 @@ namespace AsbCloudWebApi.Controllers } /// - /// Удаляет значения выбранного корридора бурения + /// Удаляет значения выбранного коридора бурения /// /// id скважины - /// Id объекта корридоров бурения + /// Id объекта коридоров бурения /// Токен отмены задачи /// [HttpDelete] diff --git a/AsbCloudWebApi/Controllers/DrillParamsController.cs b/AsbCloudWebApi/Controllers/DrillParamsController.cs index 5cdc53dd..297e54c4 100644 --- a/AsbCloudWebApi/Controllers/DrillParamsController.cs +++ b/AsbCloudWebApi/Controllers/DrillParamsController.cs @@ -25,7 +25,7 @@ namespace AsbCloudWebApi.Controllers } /// - /// Возвращает автоматически расчитанные значения для режимов бурения + /// Возвращает автоматически рассчитанные значения для режимов бурения /// /// id скважины /// Стартовая глубина diff --git a/AsbCloudWebApi/Controllers/DrillingProgramController.cs b/AsbCloudWebApi/Controllers/DrillingProgramController.cs index 84d985bd..7be00083 100644 --- a/AsbCloudWebApi/Controllers/DrillingProgramController.cs +++ b/AsbCloudWebApi/Controllers/DrillingProgramController.cs @@ -84,7 +84,7 @@ namespace AsbCloudWebApi.Controllers } /// - /// Создает метку для файла входящего в проргамму бурения + /// Создает метку для файла входящего в программу бурения /// /// id скважины /// метка файла @@ -109,7 +109,7 @@ namespace AsbCloudWebApi.Controllers } /// - /// Помечает метку у файла входящего, в проргамму бурения, как удаленную + /// Помечает метку у файла входящего, в программу бурения, как удаленную /// /// id скважины /// id метки diff --git a/AsbCloudWebApi/Controllers/MessageController.cs b/AsbCloudWebApi/Controllers/MessageController.cs index 1638106e..8c9c06c5 100644 --- a/AsbCloudWebApi/Controllers/MessageController.cs +++ b/AsbCloudWebApi/Controllers/MessageController.cs @@ -31,7 +31,6 @@ namespace AsbCloudWebApi.Controllers /// для пагинации кол-во записей пропустить /// для пагинации кол-во записей /// Строка поиска - /// Даты в формате UTC или часового пояса скважины /// Токен для отмены задачи /// список сообщений по скважине [HttpGet] @@ -40,7 +39,6 @@ namespace AsbCloudWebApi.Controllers [FromQuery] IEnumerable categoryids = default, DateTime begin = default, DateTime end = default, string searchString = default, - bool isUtc = true, CancellationToken token = default) { if (take > 1024) @@ -48,7 +46,7 @@ namespace AsbCloudWebApi.Controllers var result = await messageService.GetMessagesAsync(idWell, categoryids, begin, end, searchString, - skip, take, isUtc, token).ConfigureAwait(false); + skip, take, token).ConfigureAwait(false); if (result is null || result.Count == 0) return NoContent(); @@ -61,13 +59,11 @@ namespace AsbCloudWebApi.Controllers /// /// id скважины /// Токен для отмены задачи - /// Смена дат с UTC формата на часовой пояс скважины /// список сообщений по скважине [HttpGet] [Route("datesRange")] [ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)] - public async Task GetMessagesDateRangeAsync(int idWell, bool isUtc = true, - CancellationToken token = default) + public async Task GetMessagesDateRangeAsync(int idWell, CancellationToken token = default) { int? idCompany = User.GetCompanyId(); @@ -79,9 +75,8 @@ namespace AsbCloudWebApi.Controllers if (!isCompanyOwnsWell) return Forbid(); - - var wellMessagesDatesRange = await messageService.GetMessagesDatesRangeAsync(idWell, - isUtc, token); + + var wellMessagesDatesRange = wellService.GetDatesRange(idWell); return Ok(wellMessagesDatesRange); } diff --git a/AsbCloudWebApi/Controllers/OperationStatController.cs b/AsbCloudWebApi/Controllers/OperationStatController.cs index cece035b..556ea4d5 100644 --- a/AsbCloudWebApi/Controllers/OperationStatController.cs +++ b/AsbCloudWebApi/Controllers/OperationStatController.cs @@ -29,7 +29,7 @@ namespace AsbCloudWebApi.Controllers /// /// Формирует данные по среднему и максимальному МСП на кусту по id скважины /// - /// id скважины с данного куста (через нее будут полуены данные) + /// id скважины с данного куста (через нее будут получены данные) /// /// Возвращает данные по среднему и максимальному МСП на кусту [HttpGet("well/{idWell}/ropStat")] @@ -65,13 +65,13 @@ namespace AsbCloudWebApi.Controllers } /// - /// Получает статстику по скважинам куста + /// Получает статистику по скважинам куста /// /// id куста /// /// [HttpGet] - [Route("cluster/{idCluster}/stat")] // TODO: Это статистика клатера, перенести в ClusterOperationStatController + [Route("cluster/{idCluster}/stat")] // TODO: Это статистика кластера, перенести в ClusterOperationStatController [ProducesResponseType(typeof(StatClusterDto), (int)System.Net.HttpStatusCode.OK)] public async Task GetStatClusterAsync(int idCluster, CancellationToken token = default) @@ -91,7 +91,7 @@ namespace AsbCloudWebApi.Controllers } /// - /// Получает статстику по списку скважин + /// Получает статистику по списку скважин /// /// список скважин /// @@ -128,7 +128,7 @@ namespace AsbCloudWebApi.Controllers } /// - /// Получает данные для графика глубина-днь + /// Получает данные для графика глубина-день /// /// /// diff --git a/AsbCloudWebApi/Controllers/ReportController.cs b/AsbCloudWebApi/Controllers/ReportController.cs index fcd0c9e7..1d550a27 100644 --- a/AsbCloudWebApi/Controllers/ReportController.cs +++ b/AsbCloudWebApi/Controllers/ReportController.cs @@ -134,13 +134,11 @@ namespace AsbCloudWebApi.Controllers /// /// id скважины /// Токен для отмены задачи - /// Смена дат с UTC формата на часовой пояс скважины /// Даты самого старого и самого свежего отчетов в БД [HttpGet] [Route("datesRange")] [ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)] - public async Task GetReportsDateRangeAsync(int idWell, bool isUtc = true, - CancellationToken token = default) + public async Task GetReportsDateRangeAsync(int idWell, CancellationToken token = default) { int? idCompany = User.GetCompanyId(); @@ -150,9 +148,8 @@ namespace AsbCloudWebApi.Controllers if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token).ConfigureAwait(false)) return Forbid(); - - var wellReportsDatesRange = await reportService.GetReportsDatesRangeAsync(idWell, isUtc, - token).ConfigureAwait(false); + + var wellReportsDatesRange = reportService.GetDatesRangeOrDefault(idWell); return Ok(wellReportsDatesRange); } diff --git a/AsbCloudWebApi/Controllers/SetpointsController.cs b/AsbCloudWebApi/Controllers/SetpointsController.cs index b11734cb..22a129a6 100644 --- a/AsbCloudWebApi/Controllers/SetpointsController.cs +++ b/AsbCloudWebApi/Controllers/SetpointsController.cs @@ -71,7 +71,7 @@ namespace AsbCloudWebApi.Controllers return BadRequest("Wrong ObsolescenceSec"); if (!setpoints.Setpoints.Any()) - return BadRequest("Wrong Setpoints count"); + return BadRequest("Wrong setpoints count"); var result = await setpointsService.InsertAsync(setpoints, token) .ConfigureAwait(false); @@ -107,7 +107,7 @@ namespace AsbCloudWebApi.Controllers /// /// /// - /// можно передать только новый state eg.: {state:3} - принято + /// можно передать только новый state ex.: {state:3} - принято /// /// [HttpPut("api/telemetry/{uid}/setpoints/{id}")] diff --git a/AsbCloudWebApi/Controllers/TelemetryAnalyticsController.cs b/AsbCloudWebApi/Controllers/TelemetryAnalyticsController.cs index 1cd5a764..0ccd804d 100644 --- a/AsbCloudWebApi/Controllers/TelemetryAnalyticsController.cs +++ b/AsbCloudWebApi/Controllers/TelemetryAnalyticsController.cs @@ -176,13 +176,11 @@ namespace AsbCloudWebApi.Controllers /// /// id скважины /// Токен для отмены задачи - /// Смена дат с UTC формата на часовой пояс скважины /// Даты самой первой и самой последней операций на скважине [HttpGet] [Route("datesRange")] [ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)] - public async Task GetOperationsDateRangeAsync(int idWell, bool isUtc = true, - CancellationToken token = default) + public async Task GetOperationsDateRangeAsync(int idWell, CancellationToken token = default) { int? idCompany = User.GetCompanyId(); @@ -193,8 +191,7 @@ namespace AsbCloudWebApi.Controllers idWell, token).ConfigureAwait(false)) return Forbid(); - var wellOperationsDatesRange = await analyticsService.GetOperationsDateRangeAsync(idWell, - isUtc, token).ConfigureAwait(false); + var wellOperationsDatesRange = await analyticsService.GetOperationsDateRangeAsync(idWell, token).ConfigureAwait(false); return Ok(wellOperationsDatesRange); } diff --git a/AsbCloudWebApi/Controllers/TelemetryController.cs b/AsbCloudWebApi/Controllers/TelemetryController.cs index 70fb90eb..e66734a9 100644 --- a/AsbCloudWebApi/Controllers/TelemetryController.cs +++ b/AsbCloudWebApi/Controllers/TelemetryController.cs @@ -58,15 +58,15 @@ namespace AsbCloudWebApi.Controllers /// Обновляет часовой пояс скважины /// /// Уникальный идентификатор отправителя - /// Информация о часовом поясе + /// Информация о часовом поясе /// Токен отмены задачи /// [HttpPost] - [Route("{uid}/timeZone")] - public async Task UpdateTimeZoneAsync(string uid, TelemetryTimeZoneDto timeZoneInfo, + [Route("{uid}/timezone")] + public async Task UpdateTimeZoneAsync(string uid, SimpleTimezoneDto timezone, CancellationToken token = default) { - await telemetryService.UpdateTimeZoneAsync(uid, timeZoneInfo, token) + await telemetryService.UpdateTimezoneAsync(uid, timezone, token) .ConfigureAwait(false); return Ok(); } diff --git a/AsbCloudWebApi/Controllers/TelemetryDataBaseController.cs b/AsbCloudWebApi/Controllers/TelemetryDataBaseController.cs index 51cb7079..869f4815 100644 --- a/AsbCloudWebApi/Controllers/TelemetryDataBaseController.cs +++ b/AsbCloudWebApi/Controllers/TelemetryDataBaseController.cs @@ -68,12 +68,11 @@ namespace AsbCloudWebApi.Controllers /// дата начала выборки. По умолчанию: текущее время - intervalSec /// интервал времени даты начала выборки, секунды /// желаемое количество точек. Если в выборке точек будет больше, то выборка будет прорежена. - /// Даты в формате UTC или часового пояса скважины /// Токен завершения задачи /// [HttpGet("{idWell}")] public virtual async Task> GetDataAsync(int idWell, DateTime begin = default, - int intervalSec = 600, int approxPointsCount = 1024, bool isUtc = false, CancellationToken token = default) + int intervalSec = 600, int approxPointsCount = 1024, CancellationToken token = default) { int? idCompany = User.GetCompanyId(); @@ -87,7 +86,7 @@ namespace AsbCloudWebApi.Controllers return Forbid(); var content = await telemetryDataService.GetAsync(idWell, begin, - intervalSec, approxPointsCount, isUtc, token).ConfigureAwait(false); + intervalSec, approxPointsCount, token).ConfigureAwait(false); return Ok(content); } @@ -96,13 +95,12 @@ namespace AsbCloudWebApi.Controllers /// Возвращает диапазон дат сохраненных данных. /// /// id скважины - /// Смена дат с UTC формата на часовой пояс скважины /// Токен завершения задачи /// [HttpGet] [Route("{idWell}/datesRange")] [ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)] - public virtual async Task GetDataDatesRangeAsync(int idWell, bool isUtc = false, + public virtual async Task GetDataDatesRangeAsync(int idWell, CancellationToken token = default) { int? idCompany = User.GetCompanyId(); @@ -116,8 +114,7 @@ namespace AsbCloudWebApi.Controllers if (!isCompanyOwnsWell) return Forbid(); - var dataDatesRange = await telemetryDataService.GetDataDatesRangeAsync(idWell, isUtc, - token).ConfigureAwait(false); + var dataDatesRange = wellService.GetDatesRange(idWell); return Ok(dataDatesRange); } diff --git a/AsbCloudWebApi/Controllers/WellController.cs b/AsbCloudWebApi/Controllers/WellController.cs index 8f2bd24b..336340e0 100644 --- a/AsbCloudWebApi/Controllers/WellController.cs +++ b/AsbCloudWebApi/Controllers/WellController.cs @@ -52,7 +52,7 @@ namespace AsbCloudWebApi.Controllers /// Id требуемой скважины /// Токен отмены задачи /// Информация о требуемой скважине - [HttpGet("getWell")] + [HttpGet("{idWell}")] [ProducesResponseType(typeof(WellDto), (int)System.Net.HttpStatusCode.OK)] public async Task GetAsync(int idWell, CancellationToken token = default) { @@ -76,7 +76,7 @@ namespace AsbCloudWebApi.Controllers /// State: 0 - Неизвестно, 1 - В работе, 2 - Завершена. /// Токен отмены задачи /// - [HttpPut] + [HttpPut("{idWell}")] [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] public async Task UpdateWellAsync(int idWell, WellDto dto, CancellationToken token = default) diff --git a/AsbCloudWebApi/Docs/Timezone info api credentials.md b/AsbCloudWebApi/Docs/Timezone info api credentials.md index 43d38ee0..847e13c3 100644 --- a/AsbCloudWebApi/Docs/Timezone info api credentials.md +++ b/AsbCloudWebApi/Docs/Timezone info api credentials.md @@ -2,7 +2,7 @@ https://www.geonames.org/commercial-webservices.html # учетная запись для аутентификации на сайте -Имя пользователя: asbautodrilling +Имя пользователя: asbautodrilling Пароль: asbautodrilling1! # имя пользователя для запросов diff --git a/AsbCloudWebApi/Docs/about using DateTime[Offset].md b/AsbCloudWebApi/Docs/about using DateTime[Offset].md index eb533447..954748b5 100644 --- a/AsbCloudWebApi/Docs/about using DateTime[Offset].md +++ b/AsbCloudWebApi/Docs/about using DateTime[Offset].md @@ -2,33 +2,15 @@ Скважины и пользователи ЕЦП расположены на различных часовых поясах. В БД время хранится только в UTC. На страницах ЕЦП время везде должно отображаться в часовом поясе скважины. -Web Api должен понимать при обращении время как в UTC `2021-12-29T07:00:00Z`, так и с указанием часового пояса `2021-12-29T12:00:00Z5`. +Web Api должен понимать при обращении время как в UTC `2021-12-29T07:00:00Z`, так и с указанием часового пояса `2021-12-29T12:00:00+05`. ## Решение В БД уже хранится часовой пояс скважины в таблице телеметрии. -На стороне backEnd публичные методы контроллеров и методы сервисов, которые вызываются из контроллеров должны понимать параметры времени как тип DateTime, затем приводить его к UTC. -Если DateTime.Kind == unspecified, то считается что это время указанное в часовом поясе скважины. +На стороне backEnd публичные методы контроллеров и методы сервисов, +которые вызываются из контроллеров должны понимать параметры времени как тип DateTime, затем приводить его к UTC. +Если DateTime.Kind == unspecified, то считается что *это время указанное в часовом поясе скважины*. При переходе на DateTimeOffset флаги isUTC не нужны Даты в Model - используют DateTimeOffset. Даты в Dto - используют DateTime без указания часового пояса во времени скважины. При получении Dto от фронта с kind == unspecified дата приводится к UTC как будто она в часовом поясе скважины. Перед отправкой клиенту в Dto все даты приводятся к часовому поясу скважины и kind устанавливается как unspecified. - -## Affected -ReportController - .CreateReportAsync - .GetReportSizeAsync - .GetReportsDateRangeAsync - -TelemetryDataBaseController - .GetDataAsync - .GetDataDatesRangeAsync - -MessageController - .GetMessagesAsync - .GetMessagesDateRangeAsync - -WellOperationController - .GetOperationsAsync - .InsertRangeAsync - .UpdateAsync diff --git a/AsbCloudWebApi/Startup.cs b/AsbCloudWebApi/Startup.cs index c825a98a..4b0c6b0c 100644 --- a/AsbCloudWebApi/Startup.cs +++ b/AsbCloudWebApi/Startup.cs @@ -1,3 +1,4 @@ +using AsbCloudApp.Services; using AsbCloudInfrastructure; using AsbCloudWebApi.Middlewares; using AsbCloudWebApi.SignalR; @@ -11,13 +12,12 @@ namespace AsbCloudWebApi { public class Startup { + public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; } - public IConfiguration Configuration { get; } - public void ConfigureServices(IServiceCollection services) { services.AddControllers() @@ -61,6 +61,7 @@ namespace AsbCloudWebApi .AllowCredentials(); }); }); + } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) diff --git a/AsbCloudWebApi/TODO.md b/AsbCloudWebApi/TODO.md index 8c2f6745..701246c9 100644 --- a/AsbCloudWebApi/TODO.md +++ b/AsbCloudWebApi/TODO.md @@ -9,7 +9,7 @@ - мониторинг активно передающих скважин - доделать секционирование. - редуцирование архива телеметрии по принципу второй производной. Если вторая производная ~0, то промежуточные значения можно удалить. -- редуцирование выборки в контроллере. слишком большую выборку попробовать уменьшать оконными функиями, сохранять экстремумы и ближайшие к ним значения. +- редуцирование выборки в контроллере. слишком большую выборку попробовать уменьшать оконными функциями, сохранять экстремумы и ближайшие к ним значения. * Выполненные задачи * \ No newline at end of file diff --git a/AsbCloudWebApi/wwwroot/asset-manifest.json b/AsbCloudWebApi/wwwroot/asset-manifest.json index 1babaff4..be35f8d7 100644 --- a/AsbCloudWebApi/wwwroot/asset-manifest.json +++ b/AsbCloudWebApi/wwwroot/asset-manifest.json @@ -1,40 +1,40 @@ { "files": { - "main.css": "/static/css/main.dd1fcee2.chunk.css", - "main.js": "/static/js/main.b9f2543d.chunk.js", - "main.js.map": "/static/js/main.b9f2543d.chunk.js.map", - "runtime-main.js": "/static/js/runtime-main.e4d23dc4.js", - "runtime-main.js.map": "/static/js/runtime-main.e4d23dc4.js.map", - "static/js/2.c978f7e7.chunk.js": "/static/js/2.c978f7e7.chunk.js", - "static/js/2.c978f7e7.chunk.js.map": "/static/js/2.c978f7e7.chunk.js.map", - "static/js/3.6446ff6d.chunk.js": "/static/js/3.6446ff6d.chunk.js", - "static/js/3.6446ff6d.chunk.js.map": "/static/js/3.6446ff6d.chunk.js.map", - "static/js/4.eb6dbaeb.chunk.js": "/static/js/4.eb6dbaeb.chunk.js", - "static/js/4.eb6dbaeb.chunk.js.map": "/static/js/4.eb6dbaeb.chunk.js.map", - "static/js/5.7a9fb752.chunk.js": "/static/js/5.7a9fb752.chunk.js", - "static/js/5.7a9fb752.chunk.js.map": "/static/js/5.7a9fb752.chunk.js.map", - "static/js/6.61991758.chunk.js": "/static/js/6.61991758.chunk.js", - "static/js/6.61991758.chunk.js.map": "/static/js/6.61991758.chunk.js.map", - "static/js/7.a1c2547f.chunk.js": "/static/js/7.a1c2547f.chunk.js", - "static/js/7.a1c2547f.chunk.js.map": "/static/js/7.a1c2547f.chunk.js.map", - "static/js/8.2a766587.chunk.js": "/static/js/8.2a766587.chunk.js", - "static/js/8.2a766587.chunk.js.map": "/static/js/8.2a766587.chunk.js.map", - "static/js/9.6ba456d9.chunk.js": "/static/js/9.6ba456d9.chunk.js", - "static/js/9.6ba456d9.chunk.js.map": "/static/js/9.6ba456d9.chunk.js.map", - "static/js/10.f5187699.chunk.js": "/static/js/10.f5187699.chunk.js", - "static/js/10.f5187699.chunk.js.map": "/static/js/10.f5187699.chunk.js.map", - "static/js/11.37e8bbc7.chunk.js": "/static/js/11.37e8bbc7.chunk.js", - "static/js/11.37e8bbc7.chunk.js.map": "/static/js/11.37e8bbc7.chunk.js.map", + "main.css": "/static/css/main.9cfe6b31.chunk.css", + "main.js": "/static/js/main.6c26ed34.chunk.js", + "main.js.map": "/static/js/main.6c26ed34.chunk.js.map", + "runtime-main.js": "/static/js/runtime-main.33aef657.js", + "runtime-main.js.map": "/static/js/runtime-main.33aef657.js.map", + "static/js/2.968888d9.chunk.js": "/static/js/2.968888d9.chunk.js", + "static/js/2.968888d9.chunk.js.map": "/static/js/2.968888d9.chunk.js.map", + "static/js/3.d96a3708.chunk.js": "/static/js/3.d96a3708.chunk.js", + "static/js/3.d96a3708.chunk.js.map": "/static/js/3.d96a3708.chunk.js.map", + "static/js/4.a0d32a2c.chunk.js": "/static/js/4.a0d32a2c.chunk.js", + "static/js/4.a0d32a2c.chunk.js.map": "/static/js/4.a0d32a2c.chunk.js.map", + "static/js/5.8306e86d.chunk.js": "/static/js/5.8306e86d.chunk.js", + "static/js/5.8306e86d.chunk.js.map": "/static/js/5.8306e86d.chunk.js.map", + "static/js/6.642e7ca1.chunk.js": "/static/js/6.642e7ca1.chunk.js", + "static/js/6.642e7ca1.chunk.js.map": "/static/js/6.642e7ca1.chunk.js.map", + "static/js/7.d412fe5e.chunk.js": "/static/js/7.d412fe5e.chunk.js", + "static/js/7.d412fe5e.chunk.js.map": "/static/js/7.d412fe5e.chunk.js.map", + "static/js/8.0292b3ca.chunk.js": "/static/js/8.0292b3ca.chunk.js", + "static/js/8.0292b3ca.chunk.js.map": "/static/js/8.0292b3ca.chunk.js.map", + "static/js/9.35059bd2.chunk.js": "/static/js/9.35059bd2.chunk.js", + "static/js/9.35059bd2.chunk.js.map": "/static/js/9.35059bd2.chunk.js.map", + "static/js/10.de99360f.chunk.js": "/static/js/10.de99360f.chunk.js", + "static/js/10.de99360f.chunk.js.map": "/static/js/10.de99360f.chunk.js.map", + "static/js/11.8f392911.chunk.js": "/static/js/11.8f392911.chunk.js", + "static/js/11.8f392911.chunk.js.map": "/static/js/11.8f392911.chunk.js.map", "index.html": "/index.html", - "static/css/main.dd1fcee2.chunk.css.map": "/static/css/main.dd1fcee2.chunk.css.map", - "static/js/2.c978f7e7.chunk.js.LICENSE.txt": "/static/js/2.c978f7e7.chunk.js.LICENSE.txt", + "static/css/main.9cfe6b31.chunk.css.map": "/static/css/main.9cfe6b31.chunk.css.map", + "static/js/2.968888d9.chunk.js.LICENSE.txt": "/static/js/2.968888d9.chunk.js.LICENSE.txt", "static/media/ClusterIcon.a395f860.svg": "/static/media/ClusterIcon.a395f860.svg", "static/media/DepositIcon.6de7c7ae.svg": "/static/media/DepositIcon.6de7c7ae.svg" }, "entrypoints": [ - "static/js/runtime-main.e4d23dc4.js", - "static/js/2.c978f7e7.chunk.js", - "static/css/main.dd1fcee2.chunk.css", - "static/js/main.b9f2543d.chunk.js" + "static/js/runtime-main.33aef657.js", + "static/js/2.968888d9.chunk.js", + "static/css/main.9cfe6b31.chunk.css", + "static/js/main.6c26ed34.chunk.js" ] } \ No newline at end of file diff --git a/AsbCloudWebApi/wwwroot/index.html b/AsbCloudWebApi/wwwroot/index.html index eba35987..367a842d 100644 --- a/AsbCloudWebApi/wwwroot/index.html +++ b/AsbCloudWebApi/wwwroot/index.html @@ -1 +1 @@ -АСБ Vision
\ No newline at end of file +АСБ Vision
ц \ No newline at end of file diff --git a/AsbCloudWebApi/кейсы для админки.txt b/AsbCloudWebApi/кейсы для админки.txt index 52298220..a4dbed31 100644 --- a/AsbCloudWebApi/кейсы для админки.txt +++ b/AsbCloudWebApi/кейсы для админки.txt @@ -4,4 +4,4 @@ Есть t_telemetry для которой нет t_well | Кто-то начал новое бурение или исправил название старого 2 t_telemetry с не уникальными uid Провалы в непрерывной t_data. -Сопоставление сущетсвующих на диске файлов-рапортов с теми, что хранятся в БД \ No newline at end of file +Сопоставление существующих на диске файлов-рапортов с теми, что хранятся в БД \ No newline at end of file