This commit is contained in:
Харченко Владимир 2022-01-17 10:40:27 +05:00
commit 52122358b8
152 changed files with 14830 additions and 1132 deletions

View File

@ -1,7 +1,7 @@
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16 # Visual Studio Version 17
VisualStudioVersion = 16.0.30907.101 VisualStudioVersion = 17.0.32014.148
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsbCloudWebApi", "AsbCloudWebApi\AsbCloudWebApi.csproj", "{A2768702-47CB-4127-941C-E339D5EFCFFE}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsbCloudWebApi", "AsbCloudWebApi\AsbCloudWebApi.csproj", "{A2768702-47CB-4127-941C-E339D5EFCFFE}"
EndProject EndProject
@ -15,6 +15,16 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsbCloudDb", "AsbCloudDb\As
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsbCloudWebApi.Tests", "AsbCloudWebApi.Tests\AsbCloudWebApi.Tests.csproj", "{9CF6FBB1-9AF5-45AB-A521-24F11A79B540}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsbCloudWebApi.Tests", "AsbCloudWebApi.Tests\AsbCloudWebApi.Tests.csproj", "{9CF6FBB1-9AF5-45AB-A521-24F11A79B540}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Reports", "Reports", "{E1EFA324-A3D3-46B9-A9B2-3EB9A50BB8EF}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsbSaubReport", "..\..\SAUB\AsbSaubReport\AsbSaubReport\AsbSaubReport.csproj", "{CB5A6A64-FFB3-4043-AF8D-68EAC60888BD}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsbSaubReportPdf", "..\..\SAUB\AsbSaubReport\AsbSaubReportPdf\AsbSaubReportPdf.csproj", "{E7073282-F24B-4C90-A251-4837E88A058B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsbSaubReportLas", "..\..\SAUB\AsbSaubReport\AsbSaubReportLas\AsbSaubReportLas.csproj", "{7DF7DF88-FF51-47C1-94F3-0A8326C971D1}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsbSaubReportGui", "..\..\SAUB\AsbSaubReport\AsbSaubReportGui\AsbSaubReportGui.csproj", "{F0B6B69F-E2B6-498E-AA7A-4E912C0F3602}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@ -45,10 +55,32 @@ Global
{9CF6FBB1-9AF5-45AB-A521-24F11A79B540}.Debug|Any CPU.Build.0 = Debug|Any CPU {9CF6FBB1-9AF5-45AB-A521-24F11A79B540}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9CF6FBB1-9AF5-45AB-A521-24F11A79B540}.Release|Any CPU.ActiveCfg = Release|Any CPU {9CF6FBB1-9AF5-45AB-A521-24F11A79B540}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9CF6FBB1-9AF5-45AB-A521-24F11A79B540}.Release|Any CPU.Build.0 = Release|Any CPU {9CF6FBB1-9AF5-45AB-A521-24F11A79B540}.Release|Any CPU.Build.0 = Release|Any CPU
{CB5A6A64-FFB3-4043-AF8D-68EAC60888BD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CB5A6A64-FFB3-4043-AF8D-68EAC60888BD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CB5A6A64-FFB3-4043-AF8D-68EAC60888BD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CB5A6A64-FFB3-4043-AF8D-68EAC60888BD}.Release|Any CPU.Build.0 = Release|Any CPU
{E7073282-F24B-4C90-A251-4837E88A058B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E7073282-F24B-4C90-A251-4837E88A058B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E7073282-F24B-4C90-A251-4837E88A058B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E7073282-F24B-4C90-A251-4837E88A058B}.Release|Any CPU.Build.0 = Release|Any CPU
{7DF7DF88-FF51-47C1-94F3-0A8326C971D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7DF7DF88-FF51-47C1-94F3-0A8326C971D1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7DF7DF88-FF51-47C1-94F3-0A8326C971D1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7DF7DF88-FF51-47C1-94F3-0A8326C971D1}.Release|Any CPU.Build.0 = Release|Any CPU
{F0B6B69F-E2B6-498E-AA7A-4E912C0F3602}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F0B6B69F-E2B6-498E-AA7A-4E912C0F3602}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F0B6B69F-E2B6-498E-AA7A-4E912C0F3602}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F0B6B69F-E2B6-498E-AA7A-4E912C0F3602}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{CB5A6A64-FFB3-4043-AF8D-68EAC60888BD} = {E1EFA324-A3D3-46B9-A9B2-3EB9A50BB8EF}
{E7073282-F24B-4C90-A251-4837E88A058B} = {E1EFA324-A3D3-46B9-A9B2-3EB9A50BB8EF}
{7DF7DF88-FF51-47C1-94F3-0A8326C971D1} = {E1EFA324-A3D3-46B9-A9B2-3EB9A50BB8EF}
{F0B6B69F-E2B6-498E-AA7A-4E912C0F3602} = {E1EFA324-A3D3-46B9-A9B2-3EB9A50BB8EF}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E446878D-6B1B-4279-A3F0-1974362B9921} SolutionGuid = {E446878D-6B1B-4279-A3F0-1974362B9921}
EndGlobalSection EndGlobalSection

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net5.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
</Project> </Project>

View File

@ -0,0 +1,24 @@
using AsbCloudApp.Data;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace AsbCloudApp.Comparators
{
public class ComparerIId : IComparer<IId>, IEqualityComparer<IId>
{
private static readonly ComparerIId instance = new ComparerIId();
private ComparerIId(){}
public static ComparerIId GetInstance() => instance;
public int Compare(IId x, IId y) =>
x.Id.CompareTo(y.Id);
public bool Equals(IId x, IId y) =>
x.Id == y.Id;
public int GetHashCode([DisallowNull] IId obj) =>
obj.GetHashCode();
}
}

View File

@ -8,6 +8,7 @@ namespace AsbCloudApp.Data
public string Caption { get; set; } public string Caption { get; set; }
public double? Latitude { get; set; } public double? Latitude { get; set; }
public double? Longitude { get; set; } public double? Longitude { get; set; }
public SimpleTimezoneDto Timezone { get; set; }
public int? IdDeposit { get; set; } public int? IdDeposit { get; set; }
public DepositBaseDto Deposit { get; set; } public DepositBaseDto Deposit { get; set; }
public IEnumerable<WellDto> Wells { get; set; } public IEnumerable<WellDto> Wells { get; set; }

View File

@ -1,9 +1,11 @@
namespace AsbCloudApp.Data namespace AsbCloudApp.Data
{ {
public class CompanyDto : IId public class CompanyDto : IId
{ {
public int Id { get; set; } public int Id { get; set; }
public string Caption { get; set; } public string Caption { get; set; }
public int IdCompanyType { get; set; }
public string CompanyTypeCaption { get; set; } public string CompanyTypeCaption { get; set; }
} }
} }

View File

@ -0,0 +1,9 @@
namespace AsbCloudApp.Data
{
public class CompanyTypeDto : IId
{
public int Id { get; set; }
public string Caption { get; set; }
}
}

View File

@ -8,6 +8,7 @@ namespace AsbCloudApp.Data
public string Caption { get; set; } public string Caption { get; set; }
public double? Latitude { get; set; } public double? Latitude { get; set; }
public double? Longitude { get; set; } public double? Longitude { get; set; }
public SimpleTimezoneDto Timezone { get; set; }
} }
public class DepositDto : DepositBaseDto public class DepositDto : DepositBaseDto

View File

@ -3,7 +3,7 @@ using System;
namespace AsbCloudApp.Data namespace AsbCloudApp.Data
{ {
/// <summary> /// <summary>
/// Параметры корридоров бурения (диапазоны параметров бурения) /// Параметры коридоров бурения (диапазоны параметров бурения)
/// </summary> /// </summary>
public class DrillFlowChartDto : IId public class DrillFlowChartDto : IId
{ {

View File

@ -4,5 +4,6 @@
{ {
double? Latitude { get; set; } double? Latitude { get; set; }
double? Longitude { get; set; } double? Longitude { get; set; }
SimpleTimezoneDto Timezone { get; set; }
} }
} }

View File

@ -19,7 +19,7 @@ namespace AsbCloudApp.Data
} }
/// <summary> /// <summary>
/// Кол-во записей пропущеных с начала таблицы в запросе от api /// Кол-во записей пропущенных с начала таблицы в запросе от api
/// </summary> /// </summary>
public int Skip { get; set; } public int Skip { get; set; }

View File

@ -9,8 +9,8 @@ namespace AsbCloudApp.Data
public FileInfoDto File { get; set; } public FileInfoDto File { get; set; }
public int IdWell { get; set; } public int IdWell { get; set; }
public DateTime Date { get; set; } public DateTime Date { get; set; }
public DateTimeOffset Begin { get; set; } public DateTime Begin { get; set; }
public DateTimeOffset End { get; set; } public DateTime End { get; set; }
public int Step { get; set; } public int Step { get; set; }
public string Format { get; set; } public string Format { get; set; }
} }

View File

@ -1,16 +1,16 @@
namespace AsbCloudApp.Data namespace AsbCloudApp.Data
{ {
public class TelemetryTimeZoneDto public class SimpleTimezoneDto
{ {
public double Hours { get; set; } public double Hours { get; set; }
public string TimeZoneId { get; set; } public string TimezoneId { get; set; }
public bool IsOverride { get; set; } public bool IsOverride { get; set; }
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
if(obj is TelemetryTimeZoneDto tTimeZone if(obj is SimpleTimezoneDto tTimeZone
&& tTimeZone.Hours == Hours && tTimeZone.Hours == Hours
&& tTimeZone.TimeZoneId == TimeZoneId && tTimeZone.TimezoneId == TimezoneId
&& tTimeZone.IsOverride == IsOverride) && tTimeZone.IsOverride == IsOverride)
return true; return true;
return false; return false;
@ -18,7 +18,7 @@ namespace AsbCloudApp.Data
public override int GetHashCode() public override int GetHashCode()
=> Hours.GetHashCode() => Hours.GetHashCode()
| TimeZoneId.GetHashCode() | TimezoneId.GetHashCode()
| IsOverride.GetHashCode(); | IsOverride.GetHashCode();
} }
} }

View File

@ -38,7 +38,7 @@ namespace AsbCloudApp.Data
public float? WellDepth { get; set; } public float? WellDepth { get; set; }
/// <summary> /// <summary>
/// Глубина долта /// Глубина долота
/// </summary> /// </summary>
public float? BitDepth { get; set; } public float? BitDepth { get; set; }
@ -83,12 +83,12 @@ namespace AsbCloudApp.Data
public float? BlockSpeedSpDevelop { get; set; } public float? BlockSpeedSpDevelop { get; set; }
/// <summary> /// <summary>
/// Давтение /// Давление
/// </summary> /// </summary>
public float? Pressure { get; set; } public float? Pressure { get; set; }
/// <summary> /// <summary>
/// Давтение при холостом ходе. /// Давление при холостом ходе.
/// </summary> /// </summary>
public float? PressureIdle { get; set; } public float? PressureIdle { get; set; }

View File

@ -5,7 +5,7 @@ namespace AsbCloudApp.Data
{ {
public class TelemetryOperationInfoDto public class TelemetryOperationInfoDto
{ {
public DateTimeOffset IntervalBegin { get; set; } public DateTime IntervalBegin { get; set; }
public IList<TelemetryOperationDetailsDto> Operations { get; set; } public IList<TelemetryOperationDetailsDto> Operations { get; set; }
} }
} }

View File

@ -7,10 +7,12 @@ namespace AsbCloudApp.Data
{ {
public int Id { get; set; } public int Id { get; set; }
public string Caption { get; set; } public string Caption { get; set; }
public int? IdParent { get; set; }
public int IdType { get; set; } public int IdType { get; set; }
public IEnumerable<PermissionDto> Permissions { get; set; } public IEnumerable<PermissionDto> Permissions { get; set; }
public virtual ICollection<UserRoleDto> Roles { get; set; }
[JsonIgnore] [JsonIgnore]
public virtual ICollection<UserDto> Users { get; set; } public virtual ICollection<UserDto> Users { get; set; }
} }
} }

View File

@ -8,12 +8,13 @@ namespace AsbCloudApp.Data
public int Id { get; set; } public int Id { get; set; }
public double? Latitude { get; set; } public double? Latitude { get; set; }
public double? Longitude { get; set; } public double? Longitude { get; set; }
public SimpleTimezoneDto Timezone { get; set; }
public string WellType { get; set; } public string WellType { get; set; }
public int IdWellType { get; set; } public int? IdWellType { get; set; }
public int? IdCluster { get; set; } public int? IdCluster { get; set; }
/// <summary> /// <summary>
/// 0 - незвестно, /// 0 - неизвестно,
/// 1 - в работе, /// 1 - в работе,
/// 2 - завершена /// 2 - завершена
/// </summary> /// </summary>

View File

@ -33,6 +33,11 @@ namespace AsbCloudApp.Data
/// </summary> /// </summary>
public double DepthEnd { get; set; } public double DepthEnd { get; set; }
/// <summary>
/// Кол-во дней от даты начала первой плановой (а если её нет, то фактической) операции
/// </summary>
public double Day { get; set; }
/// <summary> /// <summary>
/// Дата начала операции /// Дата начала операции
/// </summary> /// </summary>

View File

@ -11,10 +11,9 @@ namespace AsbCloudApp.Services
Task<PaginationContainer<MessageDto>> GetMessagesAsync(int idWell, Task<PaginationContainer<MessageDto>> GetMessagesAsync(int idWell,
IEnumerable<int> categoryids = default, DateTime begin = default, IEnumerable<int> categoryids = default, DateTime begin = default,
DateTime end = default, string searchString = default, DateTime end = default, string searchString = default,
int skip = 0, int take = 32, bool isUtc = true, int skip = 0, int take = 32,
CancellationToken token = default);
Task<DatesRangeDto> GetMessagesDatesRangeAsync(int idWell, bool isUtc,
CancellationToken token = default); CancellationToken token = default);
Task InsertAsync(string uid, IEnumerable<TelemetryMessageDto> dtos, Task InsertAsync(string uid, IEnumerable<TelemetryMessageDto> dtos,
CancellationToken token); CancellationToken token);
} }

View File

@ -14,8 +14,7 @@ namespace AsbCloudApp.Services
Action<object, int> handleReportProgress); Action<object, int> handleReportProgress);
int GetReportPagesCount(int idWell, DateTime begin, DateTime end, int GetReportPagesCount(int idWell, DateTime begin, DateTime end,
int stepSeconds, int format); int stepSeconds, int format);
Task<DatesRangeDto> GetReportsDatesRangeAsync(int idWell, bool isUtc, DatesRangeDto GetDatesRangeOrDefault(int idWell);
CancellationToken token = default); Task<IEnumerable<ReportPropertiesDto>> GetAllReportsByWellAsync(int idWell, CancellationToken token);
Task<List<ReportPropertiesDto>> GetAllReportsByWellAsync(int idWell, CancellationToken token);
} }
} }

View File

@ -24,7 +24,7 @@ namespace AsbCloudApp.Services
int intervalHoursTimestamp, int workBeginTimestamp, int intervalHoursTimestamp, int workBeginTimestamp,
CancellationToken token = default); CancellationToken token = default);
Task AnalyzeAndSaveTelemetriesAsync(CancellationToken token = default); Task AnalyzeAndSaveTelemetriesAsync(CancellationToken token = default);
Task<DatesRangeDto> GetOperationsDateRangeAsync(int idWell, bool isUtc, Task<DatesRangeDto> GetOperationsDateRangeAsync(int idWell,
CancellationToken token = default); CancellationToken token = default);
} }
} }

View File

@ -10,9 +10,8 @@ namespace AsbCloudApp.Services
{ {
Task<IEnumerable<TDto>> GetAsync(int idWell, Task<IEnumerable<TDto>> GetAsync(int idWell,
DateTime dateBegin = default, double intervalSec = 600d, DateTime dateBegin = default, double intervalSec = 600d,
int approxPointsCount = 1024, bool isUtc = false, CancellationToken token = default); int approxPointsCount = 1024, CancellationToken token = default);
Task<DatesRangeDto> GetDataDatesRangeAsync(int idWell, bool isUtc = false,
CancellationToken token = default);
Task<int> UpdateDataAsync(string uid, IEnumerable<TDto> dtos, CancellationToken token = default); Task<int> UpdateDataAsync(string uid, IEnumerable<TDto> dtos, CancellationToken token = default);
} }
} }

View File

@ -8,23 +8,17 @@ namespace AsbCloudApp.Services
{ {
public interface ITelemetryService public interface ITelemetryService
{ {
ITimeZoneService TimeZoneService { get; } ITimezoneService TimeZoneService { get; }
ITelemetryTracker TelemetryTracker { get; } ITelemetryTracker TelemetryTracker { get; }
int? GetIdWellByTelemetryUid(string uid); int? GetIdWellByTelemetryUid(string uid);
int GetOrCreateTelemetryIdByUid(string uid); int GetOrCreateTelemetryIdByUid(string uid);
double GetTimezoneOffsetByTelemetryId(int idTelemetry); SimpleTimezoneDto GetTimezone(int idTelemetry);
Task<double?> GetTelemetryTimeZoneOffsetAsync(int idTelemetry, CancellationToken token);
IEnumerable<TelemetryDto> GetTransmittingTelemetries(); IEnumerable<TelemetryDto> GetTransmittingTelemetries();
DateTime GetLastTelemetryDate(string telemetryUid); DateTime GetLastTelemetryDate(int idTelemetry, bool useUtc = false);
DateTime GetLastTelemetryDate(int telemetryId);
int? GetIdTelemetryByIdWell(int idWell); int? GetIdTelemetryByIdWell(int idWell);
DatesRangeDto GetDatesRange(int idTelemetry);
Task UpdateInfoAsync(string uid, TelemetryInfoDto info, CancellationToken token); Task UpdateInfoAsync(string uid, TelemetryInfoDto info, CancellationToken token);
Task<DatesRangeDto> DatesRangeToTelemetryTimeZoneAsync(int telemetryId, DatesRangeDto result, Task UpdateTimezoneAsync(string uid, SimpleTimezoneDto telemetryTimeZoneInfo, CancellationToken token);
CancellationToken token);
Task UpdateTimeZoneAsync(string uid, TelemetryTimeZoneDto telemetryTimeZoneInfo, CancellationToken token);
/// <summary> /// <summary>
/// Слить данные телеметрии в одну /// Слить данные телеметрии в одну
@ -33,8 +27,6 @@ namespace AsbCloudApp.Services
/// <param name="to">новая</param> /// <param name="to">новая</param>
/// <returns></returns> /// <returns></returns>
Task<int> MergeAsync(int from, int to, CancellationToken token); Task<int> MergeAsync(int from, int to, CancellationToken token);
void SaveRequestDate(string uid, DateTimeOffset remoteDate);
void SaveRequestDate(string uid, DateTime remoteDate);
Task<DatesRangeDto> GetDatesRangeAsync(int idWell, bool isUtc, CancellationToken token = default);
} }
} }

View File

@ -6,9 +6,9 @@ namespace AsbCloudApp.Services
{ {
public interface ITelemetryTracker public interface ITelemetryTracker
{ {
DateTime GetLastTelemetryDateByUid(string uid); DateTimeOffset GetLastTelemetryDateByUid(string uid);
DatesRangeDto GetTelemetryDateRangeByUid(string uid); DatesRangeDto GetTelemetryDateRangeByUid(string uid);
IEnumerable<string> GetTransmittingTelemetriesUids(); IEnumerable<string> GetTransmittingTelemetriesUids();
void SaveRequestDate(string uid, DateTime remoteDate); void SaveRequestDate(string uid, DateTimeOffset remoteDate);
} }
} }

View File

@ -1,13 +1,13 @@
using System; using AsbCloudApp.Data;
using System;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudApp.Services namespace AsbCloudApp.Services
{ {
public interface ITimeZoneService public interface ITimezoneService
{ {
DateTime DateToUtc(DateTime date, double remoteTimezoneOffsetHours); SimpleTimezoneDto GetByCoordinates(double latitude, double longitude);
DateTime DateToTimeZone(DateTime date, double remoteTimezoneOffsetHours); Task<Data.SimpleTimezoneDto> GetByCoordinatesAsync(double latitude, double longitude, CancellationToken token);
Task<Data.TelemetryTimeZoneDto> GetByCoordinatesAsync(double latitude, double longitude, CancellationToken token);
} }
} }

View File

@ -9,7 +9,7 @@ namespace AsbCloudApp.Services
{ {
Task<UserRoleDto> GetByNameAsync(string name, CancellationToken token = default); Task<UserRoleDto> GetByNameAsync(string name, CancellationToken token = default);
Task<IEnumerable<UserRoleDto>> GetByNamesAsync(IEnumerable<string> names, CancellationToken token = default); Task<IEnumerable<UserRoleDto>> GetByNamesAsync(IEnumerable<string> names, CancellationToken token = default);
List<UserRoleDto> GetNestedById(int id, int counter = 10); IEnumerable<UserRoleDto> GetNestedById(int id, int counter = 10);
bool HasPermission(IEnumerable<int> rolesIds, string permissionName); bool HasPermission(IEnumerable<int> rolesIds, string permissionName);
} }
} }

View File

@ -8,6 +8,8 @@ namespace AsbCloudApp.Services
{ {
public interface IWellService: ICrudService<WellDto> public interface IWellService: ICrudService<WellDto>
{ {
ITelemetryService TelemetryService { get; }
Task<IEnumerable<WellDto>> GetWellsByCompanyAsync(int idCompany, CancellationToken token); Task<IEnumerable<WellDto>> GetWellsByCompanyAsync(int idCompany, CancellationToken token);
Task<bool> IsCompanyInvolvedInWellAsync(int idCompany, int idWell, CancellationToken token); Task<bool> IsCompanyInvolvedInWellAsync(int idCompany, int idWell, CancellationToken token);
Task<string> GetWellCaptionByIdAsync(int idWell, CancellationToken token); Task<string> GetWellCaptionByIdAsync(int idWell, CancellationToken token);
@ -15,7 +17,10 @@ namespace AsbCloudApp.Services
Task<IEnumerable<CompanyDto>> GetCompaniesAsync(int idWell, CancellationToken token); Task<IEnumerable<CompanyDto>> GetCompaniesAsync(int idWell, CancellationToken token);
bool IsCompanyInvolvedInWell(int idCompany, int idWell); bool IsCompanyInvolvedInWell(int idCompany, int idWell);
string GetStateText(int state); string GetStateText(int state);
DateTime GetLastTelemetryDate(int idWell); DateTimeOffset GetLastTelemetryDate(int idWell);
Task<IEnumerable<int>> GetClusterWellsIdsAsync(int idWell, CancellationToken token); Task<IEnumerable<int>> GetClusterWellsIdsAsync(int idWell, CancellationToken token);
SimpleTimezoneDto GetTimezone(int idWell);
DatesRangeDto GetDatesRange(int idWell);
void EnshureTimezonesIsSet();
} }
} }

View File

@ -1,15 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net5.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.10"> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.1">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="5.0.10" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="6.0.2" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -125,6 +125,7 @@ namespace AsbCloudDb
{ {
string vStr => $"'{vStr}'", string vStr => $"'{vStr}'",
DateTime vDate => $"'{FormatDateValue(vDate)}'", DateTime vDate => $"'{FormatDateValue(vDate)}'",
DateTimeOffset vDate => $"'{FormatDateValue(vDate.UtcDateTime)}'",
IFormattable vFormattable=> FormatFormattableValue(vFormattable), IFormattable vFormattable=> FormatFormattableValue(vFormattable),
_ => System.Text.Json.JsonSerializer.Serialize(v), _ => System.Text.Json.JsonSerializer.Serialize(v),
}; };

View File

@ -770,7 +770,7 @@ namespace AsbCloudDb.Migrations
.HasColumnName("remote_uid") .HasColumnName("remote_uid")
.HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв.");
b.Property<TelemetryTimeZone>("TelemetryTimeZone") b.Property<SimpleTimezone>("TelemetryTimeZone")
.HasColumnType("jsonb") .HasColumnType("jsonb")
.HasColumnName("timezone") .HasColumnName("timezone")
.HasComment("Смещение часового пояса от UTC"); .HasComment("Смещение часового пояса от UTC");

View File

@ -7,7 +7,7 @@ namespace AsbCloudDb.Migrations
{ {
protected override void Up(MigrationBuilder migrationBuilder) protected override void Up(MigrationBuilder migrationBuilder)
{ {
migrationBuilder.AddColumn<TelemetryTimeZone>( migrationBuilder.AddColumn<SimpleTimezone>(
name: "timezone", name: "timezone",
table: "t_telemetry", table: "t_telemetry",
type: "jsonb", type: "jsonb",

View File

@ -853,7 +853,7 @@ namespace AsbCloudDb.Migrations
.HasColumnName("remote_uid") .HasColumnName("remote_uid")
.HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв.");
b.Property<TelemetryTimeZone>("TelemetryTimeZone") b.Property<SimpleTimezone>("TelemetryTimeZone")
.HasColumnType("jsonb") .HasColumnType("jsonb")
.HasColumnName("timezone") .HasColumnName("timezone")
.HasComment("Смещение часового пояса от UTC"); .HasComment("Смещение часового пояса от UTC");

View File

@ -824,7 +824,7 @@ namespace AsbCloudDb.Migrations
.HasColumnName("remote_uid") .HasColumnName("remote_uid")
.HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв.");
b.Property<TelemetryTimeZone>("TelemetryTimeZone") b.Property<SimpleTimezone>("TelemetryTimeZone")
.HasColumnType("jsonb") .HasColumnType("jsonb")
.HasColumnName("timezone") .HasColumnName("timezone")
.HasComment("Смещение часового пояса от UTC"); .HasComment("Смещение часового пояса от UTC");

View File

@ -854,7 +854,7 @@ namespace AsbCloudDb.Migrations
.HasColumnName("remote_uid") .HasColumnName("remote_uid")
.HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв.");
b.Property<TelemetryTimeZone>("TelemetryTimeZone") b.Property<SimpleTimezone>("TelemetryTimeZone")
.HasColumnType("jsonb") .HasColumnType("jsonb")
.HasColumnName("timezone") .HasColumnName("timezone")
.HasComment("Смещение часового пояса от UTC"); .HasComment("Смещение часового пояса от UTC");

View File

@ -854,7 +854,7 @@ namespace AsbCloudDb.Migrations
.HasColumnName("remote_uid") .HasColumnName("remote_uid")
.HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв.");
b.Property<TelemetryTimeZone>("TelemetryTimeZone") b.Property<SimpleTimezone>("TelemetryTimeZone")
.HasColumnType("jsonb") .HasColumnType("jsonb")
.HasColumnName("timezone") .HasColumnName("timezone")
.HasComment("Смещение часового пояса от UTC"); .HasComment("Смещение часового пояса от UTC");

View File

@ -854,7 +854,7 @@ namespace AsbCloudDb.Migrations
.HasColumnName("remote_uid") .HasColumnName("remote_uid")
.HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв.");
b.Property<TelemetryTimeZone>("TelemetryTimeZone") b.Property<SimpleTimezone>("TelemetryTimeZone")
.HasColumnType("jsonb") .HasColumnType("jsonb")
.HasColumnName("timezone") .HasColumnName("timezone")
.HasComment("Смещение часового пояса от UTC"); .HasComment("Смещение часового пояса от UTC");

View File

@ -854,7 +854,7 @@ namespace AsbCloudDb.Migrations
.HasColumnName("remote_uid") .HasColumnName("remote_uid")
.HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв.");
b.Property<TelemetryTimeZone>("TelemetryTimeZone") b.Property<SimpleTimezone>("TelemetryTimeZone")
.HasColumnType("jsonb") .HasColumnType("jsonb")
.HasColumnName("timezone") .HasColumnName("timezone")
.HasComment("Смещение часового пояса от UTC"); .HasComment("Смещение часового пояса от UTC");

View File

@ -824,7 +824,7 @@ namespace AsbCloudDb.Migrations
.HasColumnName("remote_uid") .HasColumnName("remote_uid")
.HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв.");
b.Property<TelemetryTimeZone>("TelemetryTimeZone") b.Property<SimpleTimezone>("TelemetryTimeZone")
.HasColumnType("jsonb") .HasColumnType("jsonb")
.HasColumnName("timezone") .HasColumnName("timezone")
.HasComment("Смещение часового пояса от UTC"); .HasComment("Смещение часового пояса от UTC");

View File

@ -908,7 +908,7 @@ namespace AsbCloudDb.Migrations
.HasColumnName("remote_uid") .HasColumnName("remote_uid")
.HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв.");
b.Property<TelemetryTimeZone>("TelemetryTimeZone") b.Property<SimpleTimezone>("TelemetryTimeZone")
.HasColumnType("jsonb") .HasColumnType("jsonb")
.HasColumnName("timezone") .HasColumnName("timezone")
.HasComment("Смещение часового пояса от UTC"); .HasComment("Смещение часового пояса от UTC");

View File

@ -908,7 +908,7 @@ namespace AsbCloudDb.Migrations
.HasColumnName("remote_uid") .HasColumnName("remote_uid")
.HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв.");
b.Property<TelemetryTimeZone>("TelemetryTimeZone") b.Property<SimpleTimezone>("TelemetryTimeZone")
.HasColumnType("jsonb") .HasColumnType("jsonb")
.HasColumnName("timezone") .HasColumnName("timezone")
.HasComment("Смещение часового пояса от UTC"); .HasComment("Смещение часового пояса от UTC");

View File

@ -908,7 +908,7 @@ namespace AsbCloudDb.Migrations
.HasColumnName("remote_uid") .HasColumnName("remote_uid")
.HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв.");
b.Property<TelemetryTimeZone>("TelemetryTimeZone") b.Property<SimpleTimezone>("TelemetryTimeZone")
.HasColumnType("jsonb") .HasColumnType("jsonb")
.HasColumnName("timezone") .HasColumnName("timezone")
.HasComment("Смещение часового пояса от UTC"); .HasComment("Смещение часового пояса от UTC");

View File

@ -899,7 +899,7 @@ namespace AsbCloudDb.Migrations
.HasColumnName("remote_uid") .HasColumnName("remote_uid")
.HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв.");
b.Property<TelemetryTimeZone>("TelemetryTimeZone") b.Property<SimpleTimezone>("TelemetryTimeZone")
.HasColumnType("jsonb") .HasColumnType("jsonb")
.HasColumnName("timezone") .HasColumnName("timezone")
.HasComment("Смещение часового пояса от UTC"); .HasComment("Смещение часового пояса от UTC");

View File

@ -902,7 +902,7 @@ namespace AsbCloudDb.Migrations
.HasColumnName("remote_uid") .HasColumnName("remote_uid")
.HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв.");
b.Property<TelemetryTimeZone>("TelemetryTimeZone") b.Property<SimpleTimezone>("TelemetryTimeZone")
.HasColumnType("jsonb") .HasColumnType("jsonb")
.HasColumnName("timezone") .HasColumnName("timezone")
.HasComment("Смещение часового пояса от UTC"); .HasComment("Смещение часового пояса от UTC");

View File

@ -893,7 +893,7 @@ namespace AsbCloudDb.Migrations
.HasColumnName("remote_uid") .HasColumnName("remote_uid")
.HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв.");
b.Property<TelemetryTimeZone>("TelemetryTimeZone") b.Property<SimpleTimezone>("TelemetryTimeZone")
.HasColumnType("jsonb") .HasColumnType("jsonb")
.HasColumnName("timezone") .HasColumnName("timezone")
.HasComment("Смещение часового пояса от UTC"); .HasComment("Смещение часового пояса от UTC");

View File

@ -893,7 +893,7 @@ namespace AsbCloudDb.Migrations
.HasColumnName("remote_uid") .HasColumnName("remote_uid")
.HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв.");
b.Property<TelemetryTimeZone>("TelemetryTimeZone") b.Property<SimpleTimezone>("TelemetryTimeZone")
.HasColumnType("jsonb") .HasColumnType("jsonb")
.HasColumnName("timezone") .HasColumnName("timezone")
.HasComment("Смещение часового пояса от UTC"); .HasComment("Смещение часового пояса от UTC");

View File

@ -893,7 +893,7 @@ namespace AsbCloudDb.Migrations
.HasColumnName("remote_uid") .HasColumnName("remote_uid")
.HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв."); .HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв.");
b.Property<TelemetryTimeZone>("TelemetryTimeZone") b.Property<SimpleTimezone>("TelemetryTimeZone")
.HasColumnType("jsonb") .HasColumnType("jsonb")
.HasColumnName("timezone") .HasColumnName("timezone")
.HasComment("Смещение часового пояса от UTC"); .HasComment("Смещение часового пояса от UTC");

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,113 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AsbCloudDb.Migrations
{
public partial class Fix_spelling_of_defaults : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "t_well_operation_category",
keyColumn: "id",
keyValue: 1014,
column: "name",
value: "Опрессовка Ц.К.");
migrationBuilder.UpdateData(
table: "t_well_section_type",
keyColumn: "id",
keyValue: 1,
column: "caption",
value: "Пилотный ствол");
migrationBuilder.UpdateData(
table: "t_well_section_type",
keyColumn: "id",
keyValue: 2,
column: "caption",
value: "Направление");
migrationBuilder.UpdateData(
table: "t_well_section_type",
keyColumn: "id",
keyValue: 3,
column: "caption",
value: "Кондуктор");
migrationBuilder.UpdateData(
table: "t_well_section_type",
keyColumn: "id",
keyValue: 4,
column: "caption",
value: "Эксплуатационная колонна");
migrationBuilder.UpdateData(
table: "t_well_section_type",
keyColumn: "id",
keyValue: 5,
column: "caption",
value: "Транспортный ствол");
migrationBuilder.UpdateData(
table: "t_well_section_type",
keyColumn: "id",
keyValue: 6,
column: "caption",
value: "Хвостовик");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "t_well_operation_category",
keyColumn: "id",
keyValue: 1014,
column: "name",
value: "Опресовка Ц.К.");
migrationBuilder.UpdateData(
table: "t_well_section_type",
keyColumn: "id",
keyValue: 1,
column: "caption",
value: "Пилотный ствол 1");
migrationBuilder.UpdateData(
table: "t_well_section_type",
keyColumn: "id",
keyValue: 2,
column: "caption",
value: "Направление 1");
migrationBuilder.UpdateData(
table: "t_well_section_type",
keyColumn: "id",
keyValue: 3,
column: "caption",
value: "Кондуктор 1");
migrationBuilder.UpdateData(
table: "t_well_section_type",
keyColumn: "id",
keyValue: 4,
column: "caption",
value: "Эксплуатационная колонна 1");
migrationBuilder.UpdateData(
table: "t_well_section_type",
keyColumn: "id",
keyValue: 5,
column: "caption",
value: "Транспортный ствол 1");
migrationBuilder.UpdateData(
table: "t_well_section_type",
keyColumn: "id",
keyValue: 6,
column: "caption",
value: "Хвостовик 1");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,49 @@
using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AsbCloudDb.Migrations
{
public partial class Add_timeZone_to_IMapPoint : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<SimpleTimezone>(
name: "timezone",
table: "t_well",
type: "jsonb",
nullable: true,
comment: "Смещение часового пояса от UTC");
migrationBuilder.AddColumn<SimpleTimezone>(
name: "timezone",
table: "t_deposit",
type: "jsonb",
nullable: true,
comment: "Смещение часового пояса от UTC");
migrationBuilder.AddColumn<SimpleTimezone>(
name: "timezone",
table: "t_cluster",
type: "jsonb",
nullable: true,
comment: "Смещение часового пояса от UTC");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "timezone",
table: "t_well");
migrationBuilder.DropColumn(
name: "timezone",
table: "t_deposit");
migrationBuilder.DropColumn(
name: "timezone",
table: "t_cluster");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -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<float>(
name: "torque_starting",
table: "t_telemetry_data_spin",
type: "real",
nullable: true,
comment: "Страгивающий момент",
oldClrType: typeof(float),
oldType: "real",
oldNullable: true,
oldComment: " Страгивающий момент");
migrationBuilder.AlterColumn<float>(
name: "rotor_torque_avg",
table: "t_telemetry_data_spin",
type: "real",
nullable: true,
comment: "Момент в роторе средний",
oldClrType: typeof(float),
oldType: "real",
oldNullable: true,
oldComment: " Момент в роторе средний");
migrationBuilder.AlterColumn<float>(
name: "ratio",
table: "t_telemetry_data_spin",
type: "real",
nullable: true,
comment: " Коэффициент редукции редуктора",
oldClrType: typeof(float),
oldType: "real",
oldNullable: true,
oldComment: " Коэффициент редукции редектора");
migrationBuilder.AlterColumn<float>(
name: "position_zero",
table: "t_telemetry_data_spin",
type: "real",
nullable: true,
comment: "Нулевая позиция осцилляции",
oldClrType: typeof(float),
oldType: "real",
oldNullable: true,
oldComment: "Нулевая позиция осциляции");
migrationBuilder.AlterColumn<float>(
name: "position_right",
table: "t_telemetry_data_spin",
type: "real",
nullable: true,
comment: "Крайний правый угол осцилляции",
oldClrType: typeof(float),
oldType: "real",
oldNullable: true,
oldComment: "Крайний правый угол осциляции");
migrationBuilder.AlterColumn<float>(
name: "encoder_resolution",
table: "t_telemetry_data_spin",
type: "real",
nullable: true,
comment: "Разрешение энкодера",
oldClrType: typeof(float),
oldType: "real",
oldNullable: true,
oldComment: " Разрешение энкодера");
migrationBuilder.AlterColumn<bool>(
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<float>(
name: "torque_starting",
table: "t_telemetry_data_spin",
type: "real",
nullable: true,
comment: " Страгивающий момент",
oldClrType: typeof(float),
oldType: "real",
oldNullable: true,
oldComment: "Страгивающий момент");
migrationBuilder.AlterColumn<float>(
name: "rotor_torque_avg",
table: "t_telemetry_data_spin",
type: "real",
nullable: true,
comment: " Момент в роторе средний",
oldClrType: typeof(float),
oldType: "real",
oldNullable: true,
oldComment: "Момент в роторе средний");
migrationBuilder.AlterColumn<float>(
name: "ratio",
table: "t_telemetry_data_spin",
type: "real",
nullable: true,
comment: " Коэффициент редукции редектора",
oldClrType: typeof(float),
oldType: "real",
oldNullable: true,
oldComment: " Коэффициент редукции редуктора");
migrationBuilder.AlterColumn<float>(
name: "position_zero",
table: "t_telemetry_data_spin",
type: "real",
nullable: true,
comment: "Нулевая позиция осциляции",
oldClrType: typeof(float),
oldType: "real",
oldNullable: true,
oldComment: "Нулевая позиция осцилляции");
migrationBuilder.AlterColumn<float>(
name: "position_right",
table: "t_telemetry_data_spin",
type: "real",
nullable: true,
comment: "Крайний правый угол осциляции",
oldClrType: typeof(float),
oldType: "real",
oldNullable: true,
oldComment: "Крайний правый угол осцилляции");
migrationBuilder.AlterColumn<float>(
name: "encoder_resolution",
table: "t_telemetry_data_spin",
type: "real",
nullable: true,
comment: " Разрешение энкодера",
oldClrType: typeof(float),
oldType: "real",
oldNullable: true,
oldComment: "Разрешение энкодера");
migrationBuilder.AlterColumn<bool>(
name: "is_pressure_gt_20",
table: "t_telemetry_analysis",
type: "boolean",
nullable: false,
comment: "Давоение более 20",
oldClrType: typeof(bool),
oldType: "boolean",
oldComment: "Давление более 20");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,59 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AsbCloudDb.Migrations
{
public partial class Refactor_UserRole : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "id_parent",
table: "t_user_role");
migrationBuilder.CreateTable(
name: "t_relation_user_role_user_role",
columns: table => new
{
id_user_role = table.Column<int>(type: "integer", nullable: false),
id_include_user_role = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("t_relation_user_role_user_role_pk", x => new { x.id_user_role, x.id_include_user_role });
table.ForeignKey(
name: "FK_t_relation_user_role_user_role_t_user_role_id_include_user_~",
column: x => x.id_include_user_role,
principalTable: "t_user_role",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_t_relation_user_role_user_role_t_user_role_id_user_role",
column: x => x.id_user_role,
principalTable: "t_user_role",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
},
comment: "Отношение ролей к ролям");
migrationBuilder.CreateIndex(
name: "IX_t_relation_user_role_user_role_id_include_user_role",
table: "t_relation_user_role_user_role",
column: "id_include_user_role");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "t_relation_user_role_user_role");
migrationBuilder.AddColumn<int>(
name: "id_parent",
table: "t_user_role",
type: "integer",
nullable: true,
comment: "От какой роли унаследована данная роль");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,5 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#nullable disable #nullable disable
@ -42,6 +38,7 @@ namespace AsbCloudDb.Model
public virtual DbSet<RelationUserUserRole> RelationUserUserRoles { get; set; } public virtual DbSet<RelationUserUserRole> RelationUserUserRoles { get; set; }
public virtual DbSet<Permission> Permissions { get; set; } public virtual DbSet<Permission> Permissions { get; set; }
public virtual DbSet<RelationUserRolePermission> RelationUserRolePermissions { get; set; } public virtual DbSet<RelationUserRolePermission> RelationUserRolePermissions { get; set; }
public virtual DbSet<RelationUserRoleUserRole> RelationUserRoleUserRoles { get; set; }
//var options = new DbContextOptionsBuilder<AsbCloudDbContext>() //var options = new DbContextOptionsBuilder<AsbCloudDbContext>()
// .UseNpgsql("Host=localhost;Database=postgres;Username=postgres;Password=q;Persist Security Info=True") // .UseNpgsql("Host=localhost;Database=postgres;Username=postgres;Password=q;Persist Security Info=True")
@ -209,6 +206,11 @@ namespace AsbCloudDb.Model
.HasConstraintName("t_relation_company_well_t_company_id_fk"); .HasConstraintName("t_relation_company_well_t_company_id_fk");
}); });
modelBuilder.Entity<RelationUserRoleUserRole>(entity => {
entity.HasKey(x => new { x.Id, x.IdInclude })
.HasName("t_relation_user_role_user_role_pk");
});
modelBuilder.Entity<WellOperation>(entity => modelBuilder.Entity<WellOperation>(entity =>
{ {
entity.HasIndex(d => d.DepthEnd); entity.HasIndex(d => d.DepthEnd);
@ -281,7 +283,7 @@ namespace AsbCloudDb.Model
Id = 1, Id = 1,
IdCompany = 1, IdCompany = 1,
Login = "dev", Login = "dev",
PasswordHash = "Vlcj|4fa529103dde7ff72cfe76185f344d4aa87931f8e1b2044e8a7739947c3d18923464eaad93843e4f809c5e126d013072", // dev PasswordHash = "Vlcj|4fa529103dde7ff72cfe76185f344d4aa87931f8e1b2044e8a7739947c3d18923464eaad93843e4f809c5e126d013072",
Name = "Разработчик", Name = "Разработчик",
}, },
}); });
@ -304,7 +306,7 @@ namespace AsbCloudDb.Model
modelBuilder.Entity<WellOperationCategory>(entity => modelBuilder.Entity<WellOperationCategory>(entity =>
{ {
entity.HasData(new List<WellOperationCategory> { entity.HasData(new List<WellOperationCategory> {
// Автоматически опеределяемые операции // Автоматически определяемые операции
new WellOperationCategory {Id = 1, Name = "Невозможно определить операцию", Code = 0}, new WellOperationCategory {Id = 1, Name = "Невозможно определить операцию", Code = 0},
new WellOperationCategory {Id = 2, Name = "Роторное бурение", Code = 0 }, new WellOperationCategory {Id = 2, Name = "Роторное бурение", Code = 0 },
new WellOperationCategory {Id = 3, Name = "Слайдирование", Code = 0 }, new WellOperationCategory {Id = 3, Name = "Слайдирование", Code = 0 },
@ -334,7 +336,7 @@ namespace AsbCloudDb.Model
new WellOperationCategory {Id = 1011, Name = "Начало цикла строительства скважины", Code = 0 }, new WellOperationCategory {Id = 1011, Name = "Начало цикла строительства скважины", Code = 0 },
new WellOperationCategory {Id = 1012, Name = "Окончание цикла строительства скважины", Code = 0 }, new WellOperationCategory {Id = 1012, Name = "Окончание цикла строительства скважины", Code = 0 },
new WellOperationCategory {Id = 1013, Name = "Опрессовка ПВО", Code = 0 }, new WellOperationCategory {Id = 1013, Name = "Опрессовка ПВО", Code = 0 },
new WellOperationCategory {Id = 1014, Name = "Опресовка Ц.К.", Code = 0 }, new WellOperationCategory {Id = 1014, Name = "Опрессовка Ц.К.", Code = 0 },
new WellOperationCategory {Id = 1015, Name = "Опрессовка ВЗД", Code = 0 }, new WellOperationCategory {Id = 1015, Name = "Опрессовка ВЗД", Code = 0 },
new WellOperationCategory {Id = 1016, Name = "Перевод скв на другой тип промывочной жидкости", Code = 0 }, new WellOperationCategory {Id = 1016, Name = "Перевод скв на другой тип промывочной жидкости", Code = 0 },
new WellOperationCategory {Id = 1017, Name = "Перезапись каротажа", Code = 0 }, new WellOperationCategory {Id = 1017, Name = "Перезапись каротажа", Code = 0 },
@ -402,12 +404,12 @@ namespace AsbCloudDb.Model
modelBuilder.Entity<WellSectionType>(entity => modelBuilder.Entity<WellSectionType>(entity =>
{ {
entity.HasData(new List<WellSectionType>{ entity.HasData(new List<WellSectionType>{
new WellSectionType{ Id = 1, Caption = "Пилотный ствол 1"}, new WellSectionType{ Id = 1, Caption = "Пилотный ствол"},
new WellSectionType{ Id = 2, Caption = "Направление 1"}, new WellSectionType{ Id = 2, Caption = "Направление"},
new WellSectionType{ Id = 3, Caption = "Кондуктор 1"}, new WellSectionType{ Id = 3, Caption = "Кондуктор"},
new WellSectionType{ Id = 4, Caption = "Эксплуатационная колонна 1"}, new WellSectionType{ Id = 4, Caption = "Эксплуатационная колонна"},
new WellSectionType{ Id = 5, Caption = "Транспортный ствол 1"}, new WellSectionType{ Id = 5, Caption = "Транспортный ствол"},
new WellSectionType{ Id = 6, Caption = "Хвостовик 1"}, new WellSectionType{ Id = 6, Caption = "Хвостовик"},
new WellSectionType{ Id = 7, Caption = "Пилотный ствол 2"}, new WellSectionType{ Id = 7, Caption = "Пилотный ствол 2"},
new WellSectionType{ Id = 8, Caption = "Направление 2"}, new WellSectionType{ Id = 8, Caption = "Направление 2"},

View File

@ -38,5 +38,8 @@ namespace AsbCloudDb.Model
[Column("longitude")] [Column("longitude")]
public double? Longitude { get; set; } public double? Longitude { get; set; }
[Column("timezone", TypeName = "jsonb"), Comment("Смещение часового пояса от UTC")]
public SimpleTimezone Timezone { get; set; }
} }
} }

View File

@ -31,5 +31,8 @@ namespace AsbCloudDb.Model
[Column("longitude")] [Column("longitude")]
public double? Longitude { get; set; } public double? Longitude { get; set; }
[Column("timezone", TypeName = "jsonb"), Comment("Смещение часового пояса от UTC")]
public SimpleTimezone Timezone { get; set; }
} }
} }

View File

@ -6,7 +6,7 @@ using System.Text.Json.Serialization;
namespace AsbCloudDb.Model namespace AsbCloudDb.Model
{ {
[Table("t_drill_flow_chart"), Comment("Параметры корридоров бурения (диапазоны параметров бурения)")] [Table("t_drill_flow_chart"), Comment("Параметры коридоров бурения (диапазоны параметров бурения)")]
public class DrillFlowChart : IId public class DrillFlowChart : IId
{ {
[Key] [Key]
@ -20,7 +20,7 @@ namespace AsbCloudDb.Model
public int IdWellOperationCategory { get; set; } public int IdWellOperationCategory { get; set; }
[Column("last_update", TypeName = "timestamp with time zone"), Comment("Дата последнего изменения")] [Column("last_update", TypeName = "timestamp with time zone"), Comment("Дата последнего изменения")]
public DateTime LastUpdate { get; set; } public DateTimeOffset LastUpdate { get; set; }
[Column("depth_start"), Comment("Стартовая глубина")] [Column("depth_start"), Comment("Стартовая глубина")]
public double DepthStart { get; set; } public double DepthStart { get; set; }

View File

@ -27,7 +27,7 @@ namespace AsbCloudDb.Model
public string Name { get; set; } public string Name { get; set; }
[Column("date", TypeName = "timestamp with time zone")] [Column("date", TypeName = "timestamp with time zone")]
public DateTime UploadDate { get; set; } public DateTimeOffset UploadDate { get; set; }
[Column("file_size"), Comment("Размер файла")] [Column("file_size"), Comment("Размер файла")]
public long Size { get; set; } public long Size { get; set; }

View File

@ -20,7 +20,7 @@ namespace AsbCloudDb.Model
public int IdMarkType { get; set; } public int IdMarkType { get; set; }
[Column("date_created", TypeName = "timestamp with time zone"), Comment("Дата совершенного действия")] [Column("date_created", TypeName = "timestamp with time zone"), Comment("Дата совершенного действия")]
public DateTime DateCreated { get; set; } public DateTimeOffset DateCreated { get; set; }
[Column("id_user"), Comment("id пользователя")] [Column("id_user"), Comment("id пользователя")]
public int IdUser { get; set; } public int IdUser { get; set; }

View File

@ -5,7 +5,7 @@ namespace AsbCloudDb.Model
public class FilePublishInfo public class FilePublishInfo
{ {
public int IdPublisher { get; set; } public int IdPublisher { get; set; }
public DateTime Date { get; set; } public DateTimeOffset Date { get; set; }
public string WebStorageFileUrl { get; set; } public string WebStorageFileUrl { get; set; }
} }
} }

View File

@ -5,5 +5,7 @@
double? Latitude { get; set; } double? Latitude { get; set; }
double? Longitude { get; set; } double? Longitude { get; set; }
SimpleTimezone Timezone { get; set; }
} }
} }

View File

@ -5,6 +5,6 @@ namespace AsbCloudDb.Model
public interface ITelemetryData public interface ITelemetryData
{ {
int IdTelemetry { get; set; } int IdTelemetry { get; set; }
DateTime Date { get; set; } DateTimeOffset Date { get; set; }
} }
} }

View File

@ -1,6 +1,5 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
@ -21,10 +20,10 @@ namespace AsbCloudDb.Model
public int IdCategory { get; set; } public int IdCategory { get; set; }
[Column("timestamp", TypeName = "timestamp with time zone"), Comment("время добавления")] [Column("timestamp", TypeName = "timestamp with time zone"), Comment("время добавления")]
public DateTime Timestamp { get; set; } public DateTimeOffset Timestamp { get; set; }
[Column("data", TypeName = "jsonb"), Comment("Данные таблицы последних данных")] [Column("data", TypeName = "jsonb"), Comment("Данные таблицы последних данных")]
public Dictionary<string, object> Data { get; set; } public RawData Data { get; set; }
[Column("is_deleted"), Comment("Пометка удаленным")] [Column("is_deleted"), Comment("Пометка удаленным")]
public bool IsDeleted { get; set; } public bool IsDeleted { get; set; }

View File

@ -0,0 +1,9 @@
using System.Collections.Generic;
namespace AsbCloudDb.Model
{
public class RawData: Dictionary<string, object>
{
}
}

View File

@ -1,5 +1,4 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
namespace AsbCloudDb.Model namespace AsbCloudDb.Model

View File

@ -0,0 +1,23 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;
namespace AsbCloudDb.Model
{
[Table("t_relation_user_role_user_role"), Comment("Отношение ролей к ролям")]
public class RelationUserRoleUserRole
{
[Column("id_user_role")]
public int Id { get; set; }
[Column("id_include_user_role")]
public int IdInclude { get; set; }
[ForeignKey(nameof(Id))]
[InverseProperty(nameof(UserRole.RelationUserRoleUserRoles))]
public virtual UserRole Role { get; set; }
[ForeignKey(nameof(IdInclude))]
public virtual UserRole IncludeRole { get; set; }
}
}

View File

@ -23,7 +23,7 @@ namespace AsbCloudDb.Model
public int IdState { get; set; } public int IdState { get; set; }
[Column("date", TypeName = "timestamp with time zone")] [Column("date", TypeName = "timestamp with time zone")]
public DateTime UploadDate { get; set; } public DateTimeOffset UploadDate { get; set; }
[Column("obsolescence"), Comment("сек. до устаревания")] [Column("obsolescence"), Comment("сек. до устаревания")]
public int ObsolescenceSec { get; set; } public int ObsolescenceSec { get; set; }

View File

@ -1,6 +1,6 @@
namespace AsbCloudDb.Model namespace AsbCloudDb.Model
{ {
public class TelemetryTimeZone public class SimpleTimezone
{ {
public double Hours { get; set; } public double Hours { get; set; }
public string TimeZoneId { get; set; } public string TimeZoneId { get; set; }

View File

@ -28,7 +28,7 @@ namespace AsbCloudDb.Model
public TelemetryInfo Info { get; set; } public TelemetryInfo Info { get; set; }
[Column("timezone", TypeName = "jsonb"), Comment("Смещение часового пояса от UTC")] [Column("timezone", TypeName = "jsonb"), Comment("Смещение часового пояса от UTC")]
public TelemetryTimeZone TelemetryTimeZone { get; set; } public SimpleTimezone TimeZone { get; set; }
[InverseProperty(nameof(Model.Well.Telemetry))] [InverseProperty(nameof(Model.Well.Telemetry))]
public virtual Well Well { get; set; } public virtual Well Well { get; set; }

View File

@ -71,7 +71,7 @@ namespace AsbCloudDb.Model
[Column("is_pressure_lt_20"), Comment("Давление менее 20")] [Column("is_pressure_lt_20"), Comment("Давление менее 20")]
public bool IsPressureLt20 { get; set; } public bool IsPressureLt20 { get; set; }
[Column("is_pressure_gt_20"), Comment("Давоение более 20")] [Column("is_pressure_gt_20"), Comment("Давление более 20")]
public bool IsPressureGt20 { get; set; } public bool IsPressureGt20 { get; set; }
[Column("is_hook_weight_not_changes"), Comment("Вес на крюке не меняется")] [Column("is_hook_weight_not_changes"), Comment("Вес на крюке не меняется")]

View File

@ -18,7 +18,7 @@ namespace AsbCloudDb.Model
public int? IdUser { get; set; } public int? IdUser { get; set; }
[Column("date", TypeName = "timestamp with time zone"), Comment("'2021-10-19 18:23:54+05'")] [Column("date", TypeName = "timestamp with time zone"), Comment("'2021-10-19 18:23:54+05'")]
public DateTime Date { get; set; } public DateTimeOffset Date { get; set; }
[Column("mode"), Comment("Режим САУБ")] [Column("mode"), Comment("Режим САУБ")]
public short? Mode { get; set; } public short? Mode { get; set; }

View File

@ -12,7 +12,7 @@ namespace AsbCloudDb.Model
[Column("id_telemetry")] [Column("id_telemetry")]
public int IdTelemetry { get; set; } public int IdTelemetry { get; set; }
[Column("date", TypeName = "timestamp with time zone"), Comment("'2021-10-19 18:23:54+05'")] [Column("date", TypeName = "timestamp with time zone"), Comment("'2021-10-19 18:23:54+05'")]
public DateTime Date { get; set; } public DateTimeOffset Date { get; set; }
[Column("top_drive_speed"), Comment("Скорость СВП")] [Column("top_drive_speed"), Comment("Скорость СВП")]
public float? TopDriveSpeed { get; set; } public float? TopDriveSpeed { get; set; }
@ -62,13 +62,13 @@ namespace AsbCloudDb.Model
public float? TopDriveTorqueSpToMax { get; set; } public float? TopDriveTorqueSpToMax { get; set; }
[Column("top_drive_torque_sp_to_offset")] [Column("top_drive_torque_sp_to_offset")]
public float? TopDriveTorqueSpToOffset { get; set; } public float? TopDriveTorqueSpToOffset { get; set; }
[Column("torque_starting"), Comment(" Страгивающий момент")] [Column("torque_starting"), Comment("Страгивающий момент")]
public float? TorqueStarting { get; set; } public float? TorqueStarting { get; set; }
[Column("rotor_torque_avg"), Comment(" Момент в роторе средний")] [Column("rotor_torque_avg"), Comment("Момент в роторе средний")]
public float? RotorTorqueAvg { get; set; } public float? RotorTorqueAvg { get; set; }
[Column("encoder_resolution"), Comment(" Разрешение энкодера")] [Column("encoder_resolution"), Comment("Разрешение энкодера")]
public float? EncoderResolution { get; set; } public float? EncoderResolution { get; set; }
[Column("ratio"), Comment(" Коэффициент редукции редектора")] [Column("ratio"), Comment(" Коэффициент редукции редуктора")]
public float? Ratio { get; set; } public float? Ratio { get; set; }
[Column("torque_right_limit"), Comment("Ограничение крутящего момента вправо")] [Column("torque_right_limit"), Comment("Ограничение крутящего момента вправо")]
public float? TorqueRightLimit { get; set; } public float? TorqueRightLimit { get; set; }
@ -102,9 +102,9 @@ namespace AsbCloudDb.Model
public float? BreakAngleK { get; set; } public float? BreakAngleK { get; set; }
[Column("reverse_k_torque"), Comment("Коэффициент на который умножается момент, для того чтобы система поняла что мы движемся в обратную сторону")] [Column("reverse_k_torque"), Comment("Коэффициент на который умножается момент, для того чтобы система поняла что мы движемся в обратную сторону")]
public float? ReverseKTorque { get; set; } public float? ReverseKTorque { get; set; }
[Column("position_zero"), Comment("Нулевая позиция осциляции")] [Column("position_zero"), Comment("Нулевая позиция осцилляции")]
public float? PositionZero { get; set; } public float? PositionZero { get; set; }
[Column("position_right"), Comment("Крайний правый угол осциляции")] [Column("position_right"), Comment("Крайний правый угол осцилляции")]
public float? PositionRight { get; set; } public float? PositionRight { get; set; }
[Column("torque_ramp_time"), Comment("Время нарастания момента")] [Column("torque_ramp_time"), Comment("Время нарастания момента")]
public float? TorqueRampTime { get; set; } public float? TorqueRampTime { get; set; }

View File

@ -4,7 +4,7 @@ namespace AsbCloudDb.Model
{ {
public class TelemetryInfo public class TelemetryInfo
{ {
public DateTime DrillingStartDate { get; set; } public DateTimeOffset DrillingStartDate { get; set; }
public string TimeZoneId { get; set; } public string TimeZoneId { get; set; }
public double TimeZoneOffsetTotalHours { get; set; } public double TimeZoneOffsetTotalHours { get; set; }
public string Well { get; set; } public string Well { get; set; }

View File

@ -24,7 +24,7 @@ namespace AsbCloudDb.Model
public int? IdTelemetryUser { get; set; } public int? IdTelemetryUser { get; set; }
[Column("date", TypeName = "timestamp with time zone")] [Column("date", TypeName = "timestamp with time zone")]
public DateTime Date { get; set; } public DateTimeOffset Date { get; set; }
[Column("well_depth")] [Column("well_depth")]
public double WellDepth { get; set; } public double WellDepth { get; set; }

View File

@ -20,9 +20,8 @@ namespace AsbCloudDb.Model
[Column("id_type"), Comment("0-роль из стандартной матрицы, \n1-специальная роль для какого-либо пользователя")] [Column("id_type"), Comment("0-роль из стандартной матрицы, \n1-специальная роль для какого-либо пользователя")]
public int IdType { get; set; } public int IdType { get; set; }
[Column("id_parent"), Comment("От какой роли унаследована данная роль")] [InverseProperty(nameof(RelationUserRoleUserRole.Role))]
public int? IdParent { get; set; } public virtual ICollection<RelationUserRoleUserRole> RelationUserRoleUserRoles { get; set; }
[InverseProperty(nameof(RelationUserUserRole.UserRole))] [InverseProperty(nameof(RelationUserUserRole.UserRole))]
public virtual ICollection<RelationUserUserRole> RelationUsersUserRoles { get; set; } public virtual ICollection<RelationUserUserRole> RelationUsersUserRoles { get; set; }

View File

@ -37,6 +37,9 @@ namespace AsbCloudDb.Model
[Column("longitude")] [Column("longitude")]
public double? Longitude { get; set; } public double? Longitude { get; set; }
[Column("timezone", TypeName = "jsonb"), Comment("Смещение часового пояса от UTC")]
public SimpleTimezone Timezone { get; set; }
[ForeignKey(nameof(IdWellType))] [ForeignKey(nameof(IdWellType))]
[InverseProperty(nameof(Model.WellType.Wells))] [InverseProperty(nameof(Model.WellType.Wells))]
public virtual WellType WellType { get; set; } public virtual WellType WellType { get; set; }

View File

@ -32,7 +32,7 @@ namespace AsbCloudDb.Model
public double DepthEnd { get; set; } public double DepthEnd { get; set; }
[Column("date_start", TypeName = "timestamp with time zone"), Comment("Дата начала операции")] [Column("date_start", TypeName = "timestamp with time zone"), Comment("Дата начала операции")]
public DateTime DateStart { get; set; } public DateTimeOffset DateStart { get; set; }
[Column("duration_hours"), Comment("Продолжительность, часы")] [Column("duration_hours"), Comment("Продолжительность, часы")]
public double DurationHours { get; set; } public double DurationHours { get; set; }

View File

@ -17,10 +17,10 @@ dotnet ef migrations add <MigrationName> --project AsbCloudDb
``` ```
## Откатить миграцию ## Откатить миграцию
``` ```
dotnet ef migrations remvoe <MigrationName> --project AsbCloudDb dotnet ef migrations remove <MigrationName> --project AsbCloudDb
``` ```
\<MigrationName> - Name of migration class. \<MigrationName> - Name of migration class.
После создания миграции обязательно прочитать сгенерированый код. После создания миграции обязательно прочитать генерированный код.
## Применить миграции ## Применить миграции
При старте проекта применяются автоматически При старте проекта применяются автоматически
@ -45,7 +45,7 @@ CREATE DATABASE postgres;
create schema public; 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; CREATE EXTENSION IF NOT EXISTS timescaledb;
SELECT timescaledb_pre_restore(); SELECT timescaledb_pre_restore();
@ -54,13 +54,17 @@ SELECT timescaledb_pre_restore();
### Step 3. Restore DB, then [Longest operation] ### Step 3. Restore DB, then [Longest operation]
Terminal: Terminal:
``` ```
sudo -u postgres psql -p 5499 -U postgres postgres -W < dump_2021-11-26.bak sudo -u postgres psql -p 5499 -U postgres postgres -W < dump_2021-11-26.bak
or
sudo -u postgres pg_restore -Fc -d postgres dump_2021-11-26.bak
``` ```
OR psql: OR psql:
``` ```
\! pg_restore -Fc -d postgres dump_2021-11-26.bak \! pg_restore -Fc -d postgres dump_2021-11-26.bak
``` ```
Then 'exit resore mode' psql: win:
pg_restore -Fc -d postgres -U postgres -W dump_2022-01-11.bak
Then 'exit restore mode' psql:
``` ```
SELECT timescaledb_post_restore(); SELECT timescaledb_post_restore();
``` ```

View File

@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net5.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<NoWarn>1701;1702;IDE0090;IDE0063;IDE0066</NoWarn> <NoWarn>1701;1702;IDE0090;IDE0063;IDE0066;IDE0054</NoWarn>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@ -23,10 +23,14 @@
<PackageReference Include="itext7" Version="7.2.0" /> <PackageReference Include="itext7" Version="7.2.0" />
<PackageReference Include="Mapster" Version="7.2.0" /> <PackageReference Include="Mapster" Version="7.2.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" /> <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.14.1" /> <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.15.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.15.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\..\SAUB\AsbSaubReport\AsbSaubReportLas\AsbSaubReportLas.csproj" />
<ProjectReference Include="..\..\..\SAUB\AsbSaubReport\AsbSaubReportPdf\AsbSaubReportPdf.csproj" />
<ProjectReference Include="..\..\..\SAUB\AsbSaubReport\AsbSaubReport\AsbSaubReport.csproj" />
<ProjectReference Include="..\AsbCloudApp\AsbCloudApp.csproj" /> <ProjectReference Include="..\AsbCloudApp\AsbCloudApp.csproj" />
<ProjectReference Include="..\AsbCloudDb\AsbCloudDb.csproj" /> <ProjectReference Include="..\AsbCloudDb\AsbCloudDb.csproj" />
</ItemGroup> </ItemGroup>
@ -35,16 +39,4 @@
<Folder Include="CommonLibs\" /> <Folder Include="CommonLibs\" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Reference Include="AsbSaubReport">
<HintPath>CommonLibs\AsbSaubReport.dll</HintPath>
</Reference>
<Reference Include="AsbSaubReportLas">
<HintPath>CommonLibs\AsbSaubReportLas.dll</HintPath>
</Reference>
<Reference Include="AsbSaubReportPdf">
<HintPath>CommonLibs\AsbSaubReportPdf.dll</HintPath>
</Reference>
</ItemGroup>
</Project> </Project>

View File

@ -1,11 +1,11 @@
{ {
"runtimeTarget": { "runtimeTarget": {
"name": ".NETCoreApp,Version=v5.0", "name": ".NETCoreApp,Version=v6.0",
"signature": "" "signature": ""
}, },
"compilationOptions": {}, "compilationOptions": {},
"targets": { "targets": {
".NETCoreApp,Version=v5.0": { ".NETCoreApp,Version=v6.0": {
"AsbSaubReport/1.0.0": { "AsbSaubReport/1.0.0": {
"runtime": { "runtime": {
"AsbSaubReport.dll": {} "AsbSaubReport.dll": {}

View File

@ -1,11 +1,11 @@
{ {
"runtimeTarget": { "runtimeTarget": {
"name": ".NETCoreApp,Version=v5.0", "name": ".NETCoreApp,Version=v6.0",
"signature": "" "signature": ""
}, },
"compilationOptions": {}, "compilationOptions": {},
"targets": { "targets": {
".NETCoreApp,Version=v5.0": { ".NETCoreApp,Version=v6.0": {
"AsbSaubReportLas/1.0.0": { "AsbSaubReportLas/1.0.0": {
"dependencies": { "dependencies": {
"AsbSaubReport": "1.0.0" "AsbSaubReport": "1.0.0"

View File

@ -1,53 +1,25 @@
{ {
"runtimeTarget": { "runtimeTarget": {
"name": ".NETCoreApp,Version=v5.0", "name": ".NETCoreApp,Version=v6.0",
"signature": "" "signature": ""
}, },
"compilationOptions": {}, "compilationOptions": {},
"targets": { "targets": {
".NETCoreApp,Version=v5.0": { ".NETCoreApp,Version=v6.0": {
"AsbSaubReportPdf/1.0.0": { "AsbSaubReportPdf/1.0.0": {
"dependencies": { "dependencies": {
"AsbSaubReport": "1.0.0", "AsbSaubReport": "1.0.0",
"itext7": "7.1.15" "itext7": "7.2.0"
}, },
"runtime": { "runtime": {
"AsbSaubReportPdf.dll": {} "AsbSaubReportPdf.dll": {}
} }
}, },
"Common.Logging/3.4.1": { "itext7/7.2.0": {
"dependencies": { "dependencies": {
"Common.Logging.Core": "3.4.1", "Microsoft.DotNet.PlatformAbstractions": "1.1.0",
"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.Extensions.DependencyModel": "1.1.0", "Microsoft.Extensions.DependencyModel": "1.1.0",
"Microsoft.Extensions.Logging": "5.0.0",
"Portable.BouncyCastle": "1.8.9", "Portable.BouncyCastle": "1.8.9",
"System.Collections.NonGeneric": "4.3.0", "System.Collections.NonGeneric": "4.3.0",
"System.Diagnostics.Process": "4.3.0", "System.Diagnostics.Process": "4.3.0",
@ -58,44 +30,56 @@
"System.Text.Encoding.CodePages": "4.3.0", "System.Text.Encoding.CodePages": "4.3.0",
"System.Threading.Thread": "4.3.0", "System.Threading.Thread": "4.3.0",
"System.Threading.ThreadPool": "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": { "runtime": {
"lib/netstandard2.0/itext.barcodes.dll": { "lib/netstandard2.0/itext.barcodes.dll": {
"assemblyVersion": "7.1.15.0", "assemblyVersion": "7.2.0.0",
"fileVersion": "7.1.15.0" "fileVersion": "7.2.0.0"
}, },
"lib/netstandard2.0/itext.forms.dll": { "lib/netstandard2.0/itext.forms.dll": {
"assemblyVersion": "7.1.15.0", "assemblyVersion": "7.2.0.0",
"fileVersion": "7.1.15.0" "fileVersion": "7.2.0.0"
}, },
"lib/netstandard2.0/itext.io.dll": { "lib/netstandard2.0/itext.io.dll": {
"assemblyVersion": "7.1.15.0", "assemblyVersion": "7.2.0.0",
"fileVersion": "7.1.15.0" "fileVersion": "7.2.0.0"
}, },
"lib/netstandard2.0/itext.kernel.dll": { "lib/netstandard2.0/itext.kernel.dll": {
"assemblyVersion": "7.1.15.0", "assemblyVersion": "7.2.0.0",
"fileVersion": "7.1.15.0" "fileVersion": "7.2.0.0"
}, },
"lib/netstandard2.0/itext.layout.dll": { "lib/netstandard2.0/itext.layout.dll": {
"assemblyVersion": "7.1.15.0", "assemblyVersion": "7.2.0.0",
"fileVersion": "7.1.15.0" "fileVersion": "7.2.0.0"
}, },
"lib/netstandard2.0/itext.pdfa.dll": { "lib/netstandard2.0/itext.pdfa.dll": {
"assemblyVersion": "7.1.15.0", "assemblyVersion": "7.2.0.0",
"fileVersion": "7.1.15.0" "fileVersion": "7.2.0.0"
}, },
"lib/netstandard2.0/itext.sign.dll": { "lib/netstandard2.0/itext.sign.dll": {
"assemblyVersion": "7.1.15.0", "assemblyVersion": "7.2.0.0",
"fileVersion": "7.1.15.0" "fileVersion": "7.2.0.0"
}, },
"lib/netstandard2.0/itext.styledxmlparser.dll": { "lib/netstandard2.0/itext.styledxmlparser.dll": {
"assemblyVersion": "7.1.15.0", "assemblyVersion": "7.2.0.0",
"fileVersion": "7.1.15.0" "fileVersion": "7.2.0.0"
}, },
"lib/netstandard2.0/itext.svg.dll": { "lib/netstandard2.0/itext.svg.dll": {
"assemblyVersion": "7.1.15.0", "assemblyVersion": "7.2.0.0",
"fileVersion": "7.1.15.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": { "Microsoft.Extensions.DependencyModel/1.1.0": {
"dependencies": { "dependencies": {
"Microsoft.DotNet.PlatformAbstractions": "1.1.0", "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.Platforms/1.1.0": {},
"Microsoft.NETCore.Targets/1.1.0": {}, "Microsoft.NETCore.Targets/1.1.0": {},
"Microsoft.Win32.Primitives/4.3.0": { "Microsoft.Win32.Primitives/4.3.0": {
@ -757,26 +802,19 @@
"serviceable": false, "serviceable": false,
"sha512": "" "sha512": ""
}, },
"Common.Logging/3.4.1": { "itext7/7.2.0": {
"type": "package", "type": "package",
"serviceable": true, "serviceable": true,
"sha512": "sha512-5eZ/vgEOqzLg4PypZqnJ+wMhhgHyckicbZY4iDxqQ4FtOz0CpdYZ0xQ78aszMzeAJZiLLb5VdR9tPfunVQLz6g==", "sha512": "sha512-1MkQiUY0pCevnKWrY/le7BiW/oV/9CLwB2jGD6xfs0tepE5eU5BTSlabgYq7oWZP8OB7KXoGySMqP+Ugj6MeOA==",
"path": "common.logging/3.4.1", "path": "itext7/7.2.0",
"hashPath": "common.logging.3.4.1.nupkg.sha512" "hashPath": "itext7.7.2.0.nupkg.sha512"
}, },
"Common.Logging.Core/3.4.1": { "itext7.commons/7.2.0": {
"type": "package", "type": "package",
"serviceable": true, "serviceable": true,
"sha512": "sha512-wLHldZHvxsSD6Ahonfj00/SkfHfKqO+YT6jsUwVm8Rch1REL9IArHAcSLXxYxYfu5/4ydGtmXvOtaH3AkVPu0A==", "sha512": "sha512-bfysIirFpBOTc/mSfElJMOy9D/I2LTLeL0uae7xNgV4Vv7P2HF2n2/CJRTe9iZFsL3r8JdH0hd+eusnt0BjA8w==",
"path": "common.logging.core/3.4.1", "path": "itext7.commons/7.2.0",
"hashPath": "common.logging.core.3.4.1.nupkg.sha512" "hashPath": "itext7.commons.7.2.0.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"
}, },
"Microsoft.CSharp/4.0.1": { "Microsoft.CSharp/4.0.1": {
"type": "package", "type": "package",
@ -792,6 +830,20 @@
"path": "microsoft.dotnet.platformabstractions/1.1.0", "path": "microsoft.dotnet.platformabstractions/1.1.0",
"hashPath": "microsoft.dotnet.platformabstractions.1.1.0.nupkg.sha512" "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": { "Microsoft.Extensions.DependencyModel/1.1.0": {
"type": "package", "type": "package",
"serviceable": true, "serviceable": true,
@ -799,6 +851,34 @@
"path": "microsoft.extensions.dependencymodel/1.1.0", "path": "microsoft.extensions.dependencymodel/1.1.0",
"hashPath": "microsoft.extensions.dependencymodel.1.1.0.nupkg.sha512" "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": { "Microsoft.NETCore.Platforms/1.1.0": {
"type": "package", "type": "package",
"serviceable": true, "serviceable": true,
@ -830,7 +910,7 @@
"Newtonsoft.Json/9.0.1": { "Newtonsoft.Json/9.0.1": {
"type": "package", "type": "package",
"serviceable": true, "serviceable": true,
"sha512": "sha512-U82mHQSKaIk+lpSVCbWYKNavmNH1i5xrExDEquU1i6I5pV6UMOqRnJRSlKO3cMPfcpp0RgDY+8jUXHdQ4IfXvw==", "sha512": "sha512-2okXpTRwUcgQb06put5LwwCjtgoFo74zkPksjcvOpnIjx7TagGW5IoBCAA4luZx1+tfiIhoNqoiI7Y7zwWGyKA==",
"path": "newtonsoft.json/9.0.1", "path": "newtonsoft.json/9.0.1",
"hashPath": "newtonsoft.json.9.0.1.nupkg.sha512" "hashPath": "newtonsoft.json.9.0.1.nupkg.sha512"
}, },
@ -1145,7 +1225,7 @@
"System.Runtime.InteropServices.RuntimeInformation/4.0.0": { "System.Runtime.InteropServices.RuntimeInformation/4.0.0": {
"type": "package", "type": "package",
"serviceable": true, "serviceable": true,
"sha512": "sha512-hWPhJxc453RCa8Z29O91EmfGeZIHX1ZH2A8L6lYQVSaKzku2DfArSfMEb1/MYYzPQRJZeu0c9dmYeJKxW5Fgng==", "sha512": "sha512-Ri015my90h3AB/BsbvEpq1foEPoPBBa9L8b7fu1VE4eA1NMeMe5iZ6guLjoWB+XGQr1u/rEwtXobqofjFBsAgA==",
"path": "system.runtime.interopservices.runtimeinformation/4.0.0", "path": "system.runtime.interopservices.runtimeinformation/4.0.0",
"hashPath": "system.runtime.interopservices.runtimeinformation.4.0.0.nupkg.sha512" "hashPath": "system.runtime.interopservices.runtimeinformation.4.0.0.nupkg.sha512"
}, },

View File

@ -0,0 +1,29 @@
using System;
namespace AsbCloudInfrastructure
{
public static class DateTimeExtentions
{
public static DateTimeOffset ToUtcDateTimeOffset(this DateTime date, double remoteTimezoneOffsetHours)
{
if (date == default)
return new DateTimeOffset();
var dateUtc = date.Kind switch
{
DateTimeKind.Local => date.ToUniversalTime(),
DateTimeKind.Unspecified => DateTime.SpecifyKind(date.AddHours(-remoteTimezoneOffsetHours), DateTimeKind.Utc),
_ => date,
};
return new DateTimeOffset( dateUtc);
}
public static DateTime ToRemoteDateTime(this DateTimeOffset date, double remoteTimezoneOffsetHours)
{
if (date == default)
return new DateTime(0, DateTimeKind.Unspecified);
var dateTz = date.ToOffset(TimeSpan.FromHours(remoteTimezoneOffsetHours));
return dateTz.DateTime;
}
}
}

View File

@ -6,6 +6,7 @@ using AsbCloudInfrastructure.Services.Analysis;
using AsbCloudInfrastructure.Services.Cache; using AsbCloudInfrastructure.Services.Cache;
using AsbCloudInfrastructure.Services.WellOperationService; using AsbCloudInfrastructure.Services.WellOperationService;
using AsbCloudInfrastructure.Validators; using AsbCloudInfrastructure.Validators;
using Mapster;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@ -26,8 +27,21 @@ namespace AsbCloudInfrastructure
return context; return context;
} }
public static void MapsterSetup()
{
TypeAdapterConfig.GlobalSettings.Default.Config
.ForType<DateTimeOffset, DateTime>()
.MapWith((source) => source.DateTime);
TypeAdapterConfig.GlobalSettings.Default.Config
.ForType<DateTime, DateTimeOffset>()
.MapWith((source) => source == default ? new DateTime(0, DateTimeKind.Utc) : source);
}
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration) public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
{ {
MapsterSetup();
services.AddDbContext<AsbCloudDbContext>(options => services.AddDbContext<AsbCloudDbContext>(options =>
options.UseNpgsql(configuration.GetConnectionString("DefaultConnection"))); options.UseNpgsql(configuration.GetConnectionString("DefaultConnection")));
@ -59,7 +73,7 @@ namespace AsbCloudInfrastructure
services.AddTransient<ITelemetryAnalyticsService, TelemetryAnalyticsService>(); services.AddTransient<ITelemetryAnalyticsService, TelemetryAnalyticsService>();
services.AddTransient<ITelemetryService, TelemetryService>(); services.AddTransient<ITelemetryService, TelemetryService>();
services.AddTransient<ITelemetryUserService, TelemetryUserService>(); services.AddTransient<ITelemetryUserService, TelemetryUserService>();
services.AddTransient<ITimeZoneService, TimeZoneService>(); services.AddTransient<ITimezoneService, TimezoneService>();
services.AddTransient<IUserService, UserService>(); services.AddTransient<IUserService, UserService>();
services.AddTransient<IUserRoleService, UserRoleService>(); services.AddTransient<IUserRoleService, UserRoleService>();
services.AddTransient<IWellService, WellService>(); services.AddTransient<IWellService, WellService>();
@ -68,11 +82,12 @@ namespace AsbCloudInfrastructure
services.AddTransient<IWellOperationService, WellOperationService>(); services.AddTransient<IWellOperationService, WellOperationService>();
// admin crud services: // admin crud services:
services.AddTransient<ICrudService<TelemetryDto>, CrudServiceBase<TelemetryDto, Telemetry>>(); services.AddTransient<ICrudService<TelemetryDto>, CrudServiceBase<TelemetryDto, Telemetry>>(); // может быть включен в сервис TelemetryService
services.AddTransient<ICrudService<DrillParamsDto>, DrillParamsService>(); services.AddTransient<ICrudService<DrillParamsDto>, DrillParamsService>();
services.AddTransient<ICrudService<DepositDto>, CrudServiceBase<DepositDto, Deposit>>(); services.AddTransient<ICrudService<DepositDto>, CrudCacheServiceBase<DepositDto, Deposit>>();
services.AddTransient<ICrudService<CompanyDto>, CrudServiceBase<CompanyDto, Company>>(); services.AddTransient<ICrudService<CompanyDto>, CrudCacheServiceBase<CompanyDto, Company>>();
services.AddTransient<ICrudService<ClusterDto>, CrudServiceBase<ClusterDto, Cluster>>(); services.AddTransient<ICrudService<CompanyTypeDto>, CrudCacheServiceBase<CompanyTypeDto, CompanyType>>();
services.AddTransient<ICrudService<ClusterDto>, CrudCacheServiceBase<ClusterDto, Cluster>>(); // может быть включен в сервис ClusterService
services.AddTransient<ICrudService<PermissionDto>, CrudCacheServiceBase<PermissionDto, Permission>>(); services.AddTransient<ICrudService<PermissionDto>, CrudCacheServiceBase<PermissionDto, Permission>>();
// TelemetryData services // TelemetryData services

View File

@ -16,6 +16,7 @@ namespace AsbCloudInfrastructure
private readonly Dictionary<int, TelemetryEvent> events; private readonly Dictionary<int, TelemetryEvent> events;
private readonly Dictionary<int, TelemetryUser> users; private readonly Dictionary<int, TelemetryUser> users;
private readonly double timezoneOffset;
private readonly Dictionary<int, string> categories = new Dictionary<int, string> private readonly Dictionary<int, string> categories = new Dictionary<int, string>
{ {
{1, "Авария"}, {1, "Авария"},
@ -26,6 +27,7 @@ namespace AsbCloudInfrastructure
public ReportDataSourcePgCloud(AsbCloudDbContext context, int idWell) public ReportDataSourcePgCloud(AsbCloudDbContext context, int idWell)
{ {
this.context = context; this.context = context;
var well = context.Wells var well = context.Wells
.Include(w => w.Cluster) .Include(w => w.Cluster)
.ThenInclude(c => c.Deposit) .ThenInclude(c => c.Deposit)
@ -46,15 +48,17 @@ namespace AsbCloudInfrastructure
.Where(u => u.IdTelemetry == idTelemetry) .Where(u => u.IdTelemetry == idTelemetry)
.ToDictionary(u => u.IdUser, u => u); .ToDictionary(u => u.IdUser, u => u);
timezoneOffset = well?.Telemetry?.Info?.TimeZoneOffsetTotalHours ?? well.Timezone?.Hours ?? 5.0;
info = new WellInfoReport info = new WellInfoReport
{ {
Deposit = well?.Cluster?.Deposit?.Caption, Deposit = well.Cluster?.Deposit?.Caption,
Cluster = well?.Cluster?.Caption, Cluster = well.Cluster?.Caption,
Well = well?.Caption, Well = well.Caption,
Customer = well?.RelationCompaniesWells.FirstOrDefault(c => c.Company.IdCompanyType == 1)?.Company.Caption, Customer = well.RelationCompaniesWells.FirstOrDefault(c => c.Company.IdCompanyType == 1)?.Company.Caption,
DrillingStartDate = well?.Telemetry?.Info?.DrillingStartDate ?? default, DrillingStartDate = well.Telemetry?.Info?.DrillingStartDate.ToRemoteDateTime(timezoneOffset) ?? default,
TimeZoneId = well?.Telemetry?.Info?.TimeZoneId ?? default, TimeZoneId = well.Telemetry?.Info?.TimeZoneId ?? well.Timezone?.TimeZoneId ?? default,
TimeZoneOffsetTotalHours = well?.Telemetry?.Info?.TimeZoneOffsetTotalHours ?? default, TimeZoneOffsetTotalHours = timezoneOffset,
}; };
} }
@ -74,8 +78,8 @@ namespace AsbCloudInfrastructure
var result = new AnalyzeResult var result = new AnalyzeResult
{ {
MinDate = dataStat?.min ?? messagesStat?.min ?? default, MinDate = dataStat?.min.UtcDateTime ?? messagesStat?.min.UtcDateTime ?? default,
MaxDate = dataStat?.max ?? messagesStat?.max ?? default, MaxDate = dataStat?.max.UtcDateTime ?? messagesStat?.max.UtcDateTime ?? default,
MessagesCount = messagesStat?.count ?? 0, MessagesCount = messagesStat?.count ?? 0,
}; };
@ -83,57 +87,67 @@ namespace AsbCloudInfrastructure
} }
public IQueryable<DataSaubReport> GetDataSaubItems(DateTime begin, DateTime end) public IQueryable<DataSaubReport> GetDataSaubItems(DateTime begin, DateTime end)
=> from item in context.TelemetryDataSaub {
where item.IdTelemetry == idTelemetry var beginUtc = begin.ToUtcDateTimeOffset(timezoneOffset);
&& item.Date >= begin var endUtc = end.ToUtcDateTimeOffset(timezoneOffset);
&& item.Date <= end
orderby item.Date var query = context.TelemetryDataSaub
select new DataSaubReport .Where(d => d.IdTelemetry == idTelemetry
{ && d.Date >= beginUtc
//Id = item.Id, && d.Date <= endUtc)
Date = item.Date, .OrderBy(d => d.Date)
Mode = item.Mode, .Select(d => new DataSaubReport {
WellDepth = item.WellDepth, Date = d.Date.DateTime.AddHours(timezoneOffset),
BitDepth = item.BitDepth, Mode = d.Mode,
BlockPosition = item.BlockPosition, WellDepth = d.WellDepth,
BlockSpeed = item.BlockSpeed, BitDepth = d.BitDepth,
BlockSpeedSp = item.BlockSpeedSp, BlockPosition = d.BlockPosition,
BlockSpeedSpDevelop = item.BlockSpeedSpDevelop, BlockSpeed = d.BlockSpeed,
Pressure = item.Pressure, BlockSpeedSp = d.BlockSpeedSp,
PressureSp = item.PressureSp, BlockSpeedSpDevelop = d.BlockSpeedSpDevelop,
AxialLoad = item.AxialLoad, Pressure = d.Pressure,
AxialLoadSp = item.AxialLoadSp, PressureSp = d.PressureSp,
AxialLoadLimitMax = item.AxialLoadLimitMax, AxialLoad = d.AxialLoad,
HookWeight = item.HookWeight, AxialLoadSp = d.AxialLoadSp,
RotorTorque = item.RotorTorque, AxialLoadLimitMax = d.AxialLoadLimitMax,
RotorTorqueSp = item.RotorTorqueSp, HookWeight = d.HookWeight,
RotorSpeed = item.RotorSpeed, RotorTorque = d.RotorTorque,
Flow = item.Flow, RotorTorqueSp = d.RotorTorqueSp,
PressureSpDevelop = item.PressureSpDevelop, RotorSpeed = d.RotorSpeed,
}; Flow = d.Flow,
PressureSpDevelop = d.PressureSpDevelop,
});
return query;
}
public IQueryable<MessageReport> GetMessages(DateTime begin, DateTime end) public IQueryable<MessageReport> GetMessages(DateTime begin, DateTime end)
=> from item in context.TelemetryMessages {
where item.IdTelemetry == idTelemetry var beginUtc = begin.ToUtcDateTimeOffset(timezoneOffset);
&& item.Date >= begin var endUtc = end.ToUtcDateTimeOffset(timezoneOffset);
&& item.Date <= end
orderby item.Date var query = from item in context.TelemetryMessages
select new MessageReport where item.IdTelemetry == idTelemetry
{ && item.Date >= beginUtc
Id = item.Id, && item.Date <= endUtc
Date = item.Date, orderby item.Date
Category = events.GetValueOrDefault(item.IdEvent) == null select new MessageReport
? $"" {
: categories[events[item.IdEvent].IdCategory], Id = item.Id,
User = item.IdTelemetryUser == null Date = item.Date.DateTime,
? "" Category = events.GetValueOrDefault(item.IdEvent) == null
: users.GetValueOrDefault((int)item.IdTelemetryUser) == null ? $""
? $"User id{item.IdTelemetryUser}" : categories[events[item.IdEvent].IdCategory],
: users[(int)item.IdTelemetryUser].MakeDisplayName(), User = item.IdTelemetryUser == null
Text = events.GetValueOrDefault(item.IdEvent) == null ? ""
? $"Стбытие {item.IdEvent} {item.Arg0} {item.Arg1} {item.Arg2} {item.Arg3}" : users.GetValueOrDefault((int)item.IdTelemetryUser) == null
: events[item.IdEvent].MakeMessageText(item) ? $"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() public WellInfoReport GetWellInfo()
=> info; => info;

View File

@ -5,7 +5,7 @@ namespace AsbCloudInfrastructure.Services.Analysis
class DataSaubAnalyse class DataSaubAnalyse
{ {
public int IdTelemetry { get; internal set; } public int IdTelemetry { get; internal set; }
public DateTime Date { get; internal set; } public DateTimeOffset Date { get; internal set; }
public double WellDepth { get; internal set; } public double WellDepth { get; internal set; }
public double BitDepth { get; internal set; } public double BitDepth { get; internal set; }
public double BlockPosition { get; internal set; } public double BlockPosition { get; internal set; }

View File

@ -40,8 +40,8 @@ namespace AsbCloudInfrastructure.Services.Analysis
try try
{ {
using var context = new AsbCloudDbContext(options); using var context = new AsbCloudDbContext(options);
var timeZoneService = new TimeZoneService(); var timezoneService = new TimezoneService();
var telemetryService = new TelemetryService(context, telemetryTracker, timeZoneService, cacheDb); var telemetryService = new TelemetryService(context, telemetryTracker, timezoneService, cacheDb);
var analyticsService = new TelemetryAnalyticsService(context, var analyticsService = new TelemetryAnalyticsService(context,
telemetryService, cacheDb); telemetryService, cacheDb);

View File

@ -33,13 +33,14 @@ namespace AsbCloudInfrastructure.Services.Analysis
public async Task<IEnumerable<WellDepthToDayDto>> GetWellDepthToDayAsync(int idWell, CancellationToken token = default) public async Task<IEnumerable<WellDepthToDayDto>> 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; return null;
var timezone = telemetryService.GetTimezone((int)idTelemetry);
var depthToTimeData = (from d in db.TelemetryDataSaub var depthToTimeData = (from d in db.TelemetryDataSaub
where d.IdTelemetry == telemetryId where d.IdTelemetry == idTelemetry
select new select new
{ {
d.WellDepth, d.WellDepth,
@ -56,7 +57,7 @@ namespace AsbCloudInfrastructure.Services.Analysis
{ {
WellDepth = d.WellDepth ?? 0.0, WellDepth = d.WellDepth ?? 0.0,
BitDepth = d.BitDepth ?? 0.0, BitDepth = d.BitDepth ?? 0.0,
Date = d.Date Date = d.Date.ToRemoteDateTime(timezone.Hours),
}).AsNoTracking().ToListAsync(token).ConfigureAwait(false); }).AsNoTracking().ToListAsync(token).ConfigureAwait(false);
} }
@ -70,11 +71,11 @@ namespace AsbCloudInfrastructure.Services.Analysis
if (telemetryId is null) if (telemetryId is null)
return null; return null;
var timezoneOffset = telemetryService.GetTimezoneOffsetByTelemetryId((int)telemetryId); var timezone = telemetryService.GetTimezone((int)telemetryId);
var drillingPeriodsInfo = await db.TelemetryDataSaub var drillingPeriodsInfo = await db.TelemetryDataSaub
.Where(t => t.IdTelemetry == telemetryId) .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 { .Select(g => new {
WellDepthMin = g.Min(t => t.WellDepth), WellDepthMin = g.Min(t => t.WellDepth),
WellDepthMax = g.Max(t => t.WellDepth), WellDepthMax = g.Max(t => t.WellDepth),
@ -86,7 +87,7 @@ namespace AsbCloudInfrastructure.Services.Analysis
var wellDepthToIntervalData = drillingPeriodsInfo.Select(d => new WellDepthToIntervalDto var wellDepthToIntervalData = drillingPeriodsInfo.Select(d => new WellDepthToIntervalDto
{ {
IntervalStartDate = d.DateMin, IntervalStartDate = d.DateMin.ToRemoteDateTime(timezone.Hours),
IntervalDepthProgress = (d.WellDepthMax - d.WellDepthMin) ?? 0.0 IntervalDepthProgress = (d.WellDepthMax - d.WellDepthMin) ?? 0.0
// / (d.DateMax - d.DateMin).TotalHours, // / (d.DateMax - d.DateMin).TotalHours,
}).OrderBy(d => d.IntervalStartDate).ToList(); }).OrderBy(d => d.IntervalStartDate).ToList();
@ -201,7 +202,7 @@ namespace AsbCloudInfrastructure.Services.Analysis
if (telemetryId is null) if (telemetryId is null)
return null; return null;
var timezoneOffset = telemetryService.GetTimezoneOffsetByTelemetryId((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). // 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 // 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 join o in db.WellOperationCategories on a.IdOperation equals o.Id
group a by new group a by new
{ {
Interval = Math.Floor((a.UnixDate - workBeginSeconds + timezoneOffset) / intervalSeconds), Interval = Math.Floor((a.UnixDate - workBeginSeconds + timezone.Hours) / intervalSeconds),
o.Name o.Name
} into g } into g
select new select new
@ -223,17 +224,15 @@ namespace AsbCloudInfrastructure.Services.Analysis
.ToListAsync(token) .ToListAsync(token)
.ConfigureAwait(false); .ConfigureAwait(false);
var groupedOperationsList = new List<TelemetryOperationInfoDto>(); var groupedOperationsList = new List<TelemetryOperationInfoDto>();
if (operations is not null && operations.Any()) if (operations is not null && operations.Any())
{ {
var operations = ops.Select(o => (o.IntervalStart, o.OperationName, o.OperationDuration)); var operations = ops.Select(o => (o.IntervalStart, o.OperationName, o.OperationDuration));
var splittedOperationsByInterval = DivideOperationsByIntervalLength(operations, intervalSeconds); // divides good 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; return groupedOperationsList;
@ -251,7 +250,7 @@ namespace AsbCloudInfrastructure.Services.Analysis
} }
} }
private async Task AnalyseAndSaveTelemetryAsync(int idTelemetry, DateTime analyzeStartDate, CancellationToken token = default) private async Task AnalyseAndSaveTelemetryAsync(int idTelemetry, DateTimeOffset analyzeStartDate, CancellationToken token = default)
{ {
const int step = 10; const int step = 10;
const int take = step * 2; const int take = step * 2;
@ -300,16 +299,17 @@ namespace AsbCloudInfrastructure.Services.Analysis
} }
} }
public async Task<DatesRangeDto> GetOperationsDateRangeAsync(int idWell, bool isUtc, public async Task<DatesRangeDto> GetOperationsDateRangeAsync(int idWell, CancellationToken token = default)
CancellationToken token = default)
{ {
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell); var idTelemetry = telemetryService.GetIdTelemetryByIdWell(idWell);
if (telemetryId is null) if (idTelemetry is null)
return null; return null;
var timezone = telemetryService.GetTimezone((int)idTelemetry);
var datesRange = await (from d in db.TelemetryAnalysis var datesRange = await (from d in db.TelemetryAnalysis
where d.IdTelemetry == telemetryId where d.IdTelemetry == idTelemetry
select d.UnixDate).DefaultIfEmpty() select d.UnixDate).DefaultIfEmpty()
.GroupBy(g => true) .GroupBy(g => true)
.AsNoTracking() .AsNoTracking()
@ -323,18 +323,12 @@ namespace AsbCloudInfrastructure.Services.Analysis
var result = new DatesRangeDto var result = new DatesRangeDto
{ {
From = DateTimeOffset.FromUnixTimeSeconds(datesRange.From).DateTime, From = DateTimeOffset.FromUnixTimeSeconds(datesRange.From).ToRemoteDateTime(timezone.Hours),
To = datesRange.To == default To = (datesRange.To == default
? DateTime.MaxValue ? 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; return result;
} }
@ -347,7 +341,7 @@ namespace AsbCloudInfrastructure.Services.Analysis
.LastOrDefaultAsync(token) .LastOrDefaultAsync(token)
.ConfigureAwait(false); .ConfigureAwait(false);
DateTime lastAnalysisDate = default; DateTime lastAnalysisDate = new DateTime(0, DateTimeKind.Utc);
if(lastAnalysisInDb is not null) if(lastAnalysisInDb is not null)
lastAnalysisDate = DateTime.UnixEpoch.AddSeconds(lastAnalysisInDb.DurationSec + lastAnalysisInDb.UnixDate); lastAnalysisDate = DateTime.UnixEpoch.AddSeconds(lastAnalysisInDb.DurationSec + lastAnalysisInDb.UnixDate);
@ -355,7 +349,7 @@ namespace AsbCloudInfrastructure.Services.Analysis
return lastAnalysisDate; return lastAnalysisDate;
} }
private Task<List<DataSaubAnalyse>> GetDataSaubPartOrDefaultAsync(int idTelemetry, DateTime analyzeStartDate, CancellationToken token) => private Task<List<DataSaubAnalyse>> GetDataSaubPartOrDefaultAsync(int idTelemetry, DateTimeOffset analyzeStartDate, CancellationToken token) =>
db.TelemetryDataSaub db.TelemetryDataSaub
.Where(d => .Where(d =>
d.IdTelemetry == idTelemetry && d.IdTelemetry == idTelemetry &&
@ -396,7 +390,7 @@ namespace AsbCloudInfrastructure.Services.Analysis
operationDurationTimeCounter += OperationDuration; operationDurationTimeCounter += OperationDuration;
} }
else 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; var remainingIntervalTime = intervalSeconds - operationDurationTimeCounter;
splittedOperationsByInterval.Add((IntervalStart, OperationName, remainingIntervalTime)); // first part of long operation splittedOperationsByInterval.Add((IntervalStart, OperationName, remainingIntervalTime)); // first part of long operation
@ -432,13 +426,14 @@ namespace AsbCloudInfrastructure.Services.Analysis
} }
private static IEnumerable<TelemetryOperationInfoDto> UniteOperationsInDto( private static IEnumerable<TelemetryOperationInfoDto> 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<TelemetryOperationInfoDto>(); var groupedOperationsList = new List<TelemetryOperationInfoDto>();
var groupedOperationsObj = new TelemetryOperationInfoDto var groupedOperationsObj = new TelemetryOperationInfoDto
{ {
IntervalBegin = DateTimeOffset.FromUnixTimeSeconds(operations.First().IntervalStart), IntervalBegin = DateTimeOffset.FromUnixTimeSeconds(operations.First().IntervalStart)
.ToRemoteDateTime(timezoneOffset),
Operations = new List<TelemetryOperationDetailsDto>() Operations = new List<TelemetryOperationDetailsDto>()
}; };
@ -461,7 +456,8 @@ namespace AsbCloudInfrastructure.Services.Analysis
intervalEndDate = IntervalStart + intervalSeconds; intervalEndDate = IntervalStart + intervalSeconds;
groupedOperationsObj = new TelemetryOperationInfoDto groupedOperationsObj = new TelemetryOperationInfoDto
{ {
IntervalBegin = DateTimeOffset.FromUnixTimeSeconds(IntervalStart), IntervalBegin = DateTimeOffset.FromUnixTimeSeconds(IntervalStart)
.ToRemoteDateTime(timezoneOffset),
Operations = new List<TelemetryOperationDetailsDto>() Operations = new List<TelemetryOperationDetailsDto>()
}; };

View File

@ -5,15 +5,14 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq; using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsbCloudInfrastructure.Services.Cache;
using Mapster; using Mapster;
using System.IdentityModel.Tokens.Jwt;
namespace AsbCloudInfrastructure.Services namespace AsbCloudInfrastructure.Services
{ {

View File

@ -309,7 +309,7 @@ namespace AsbCloudInfrastructure.Services.Cache
{ {
foreach (var entity in entities) foreach (var entity in entities)
{ {
if (dbSet.Contains(entity)) // TODO: это очень ммедленно if (dbSet.Contains(entity)) // TODO: это очень медленно
dbSet.Update(entity); dbSet.Update(entity);
else else
dbSet.Add(entity); dbSet.Add(entity);

View File

@ -148,7 +148,7 @@ namespace AsbCloudInfrastructure.Services
Wells = gCluster.Select(well => { Wells = gCluster.Select(well => {
var dto = well.Adapt<WellDto>(); var dto = well.Adapt<WellDto>();
dto.WellType = well.WellType?.Caption; dto.WellType = well.WellType?.Caption;
dto.LastTelemetryDate = wellService.GetLastTelemetryDate(well.Id); dto.LastTelemetryDate = wellService.GetLastTelemetryDate(well.Id).DateTime;
dto.Cluster = gCluster.Key.Caption; dto.Cluster = gCluster.Key.Caption;
dto.Deposit = gDeposit.Key.Caption; dto.Deposit = gDeposit.Key.Caption;
return dto; return dto;

View File

@ -15,36 +15,42 @@ namespace AsbCloudInfrastructure.Services
IDrillFlowChartService IDrillFlowChartService
{ {
private readonly IAsbCloudDbContext db; private readonly IAsbCloudDbContext db;
private readonly IWellService wellService;
public DrillFlowChartService(IAsbCloudDbContext context) public DrillFlowChartService(IAsbCloudDbContext context, IWellService wellService)
: base(context) : base(context)
{ {
this.db = context; this.db = context;
this.wellService = wellService;
} }
public async Task<IEnumerable<DrillFlowChartDto>> GetAllAsync(int idWell, public async Task<IEnumerable<DrillFlowChartDto>> GetAllAsync(int idWell,
DateTime updateFrom, CancellationToken token = default) DateTime updateFrom, CancellationToken token = default)
{ {
var timezone = wellService.GetTimezone(idWell);
var updateFromUtc = updateFrom.ToUtcDateTimeOffset(timezone.Hours);
var entities = await (from p in db.DrillFlowChart var entities = await (from p in db.DrillFlowChart
where p.IdWell == idWell && where p.IdWell == idWell &&
p.LastUpdate > updateFrom p.LastUpdate > updateFromUtc
orderby p.DepthStart, p.Id orderby p.DepthStart, p.Id
select p) select p)
.ToListAsync(token) .ToListAsync(token)
.ConfigureAwait(false); .ConfigureAwait(false);
var dto = entities.Adapt<DrillFlowChartDto>(); var dtos = entities.Select(entity => {
return dto; var dto = entity.Adapt<DrillFlowChartDto>();
dto.LastUpdate = entity.LastUpdate.ToRemoteDateTime(timezone.Hours);
return dto;
});
return dtos;
} }
public async Task<int> InsertAsync(int idWell, DrillFlowChartDto dto, public async Task<int> InsertAsync(int idWell, DrillFlowChartDto dto,
CancellationToken token = default) CancellationToken token = default)
{ {
dto.IdWell = idWell; dto.IdWell = idWell;
dto.LastUpdate = DateTime.Now; dto.LastUpdate = DateTime.UtcNow;
var result = await base.InsertAsync(dto, token).ConfigureAwait(false); var result = await base.InsertAsync(dto, token).ConfigureAwait(false);
return result; return result;
} }
@ -54,7 +60,7 @@ namespace AsbCloudInfrastructure.Services
foreach (var dto in dtos) foreach (var dto in dtos)
{ {
dto.IdWell = idWell; dto.IdWell = idWell;
dto.LastUpdate = DateTime.Now; dto.LastUpdate = DateTime.UtcNow;
} }
var result = await base.InsertRangeAsync(dtos, token).ConfigureAwait(false); var result = await base.InsertRangeAsync(dtos, token).ConfigureAwait(false);

View File

@ -164,7 +164,7 @@ namespace AsbCloudInfrastructure.Services
newSheetName = sheetSrc.Name; newSheetName = sheetSrc.Name;
suffix = $"_{index++}"; suffix = $"_{index++}";
if (newSheetName.Length + suffix.Length >= 31) if (newSheetName.Length + suffix.Length >= 31)
newSheetName = newSheetName.Substring(0, (31 - suffix.Length)); newSheetName = newSheetName[..(31 - suffix.Length)];
newSheetName += suffix; newSheetName += suffix;
} }

View File

@ -28,7 +28,8 @@ namespace AsbCloudInfrastructure.Services
.ThenInclude(u => u.Company) .ThenInclude(u => u.Company)
.ThenInclude(c => c.CompanyType) .ThenInclude(c => c.CompanyType)
.Include(f => f.FileMarks) .Include(f => f.FileMarks)
.ThenInclude(m => m.User); .ThenInclude(m => m.User)
.Include(f=>f.Well);
} }
public async Task<string> GetSharedUrlAsync(int idFileInfo, int idUser, IFileShareService fileShareService, public async Task<string> GetSharedUrlAsync(int idFileInfo, int idUser, IFileShareService fileShareService,
@ -75,7 +76,7 @@ namespace AsbCloudInfrastructure.Services
IdAuthor = idUser, IdAuthor = idUser,
IdCategory = idCategory, IdCategory = idCategory,
Name = destinationFileName, Name = destinationFileName,
UploadDate = DateTime.Now, UploadDate = DateTime.UtcNow,
IsDeleted = false, IsDeleted = false,
Size = sysFileInfo.Length, Size = sysFileInfo.Length,
}; };
@ -87,8 +88,7 @@ namespace AsbCloudInfrastructure.Services
Directory.CreateDirectory(Path.GetDirectoryName(filePath)); Directory.CreateDirectory(Path.GetDirectoryName(filePath));
File.Move(srcFilePath, filePath); File.Move(srcFilePath, filePath);
var dto = entry.Entity.Adapt<FileInfoDto>(); return await GetInfoAsync(entry.Entity.Id, token);
return dto;
} }
public async Task<FileInfoDto> SaveAsync(int idWell, int? idUser, int idCategory, public async Task<FileInfoDto> SaveAsync(int idWell, int? idUser, int idCategory,
@ -101,7 +101,7 @@ namespace AsbCloudInfrastructure.Services
IdAuthor = idUser, IdAuthor = idUser,
IdCategory = idCategory, IdCategory = idCategory,
Name = Path.GetFileName(fileFullName), Name = Path.GetFileName(fileFullName),
UploadDate = DateTime.Now, UploadDate = DateTime.UtcNow,
IsDeleted = false, IsDeleted = false,
Size = fileStream?.Length ?? 0 Size = fileStream?.Length ?? 0
}; };
@ -116,9 +116,8 @@ namespace AsbCloudInfrastructure.Services
using var newfileStream = new FileStream(filePath, FileMode.Create); using var newfileStream = new FileStream(filePath, FileMode.Create);
await fileStream.CopyToAsync(newfileStream, token).ConfigureAwait(false); await fileStream.CopyToAsync(newfileStream, token).ConfigureAwait(false);
var dto = entry.Entity.Adapt<FileInfoDto>(); return await GetInfoAsync(entry.Entity.Id, token);
return dto;
} }
private string MakeFilePath(int idWell, int idCategory, string fileFullName, int fileId) private string MakeFilePath(int idWell, int idCategory, string fileFullName, int fileId)
@ -136,7 +135,7 @@ namespace AsbCloudInfrastructure.Services
.ToListAsync(token) .ToListAsync(token)
.ConfigureAwait(false); .ConfigureAwait(false);
var dtos = entities.Adapt<FileInfoDto>(); var dtos = entities.Select(e => Convert(e));
return dtos; return dtos;
} }
@ -157,11 +156,28 @@ namespace AsbCloudInfrastructure.Services
if (!string.IsNullOrEmpty(fileName)) if (!string.IsNullOrEmpty(fileName))
query = query.Where(e => e.Name.ToLower().Contains(fileName.ToLower())); query = query.Where(e => e.Name.ToLower().Contains(fileName.ToLower()));
var firstFile = await query.FirstOrDefaultAsync(token);
if (firstFile is null)
return new PaginationContainer<FileInfoDto>()
{
Skip = skip,
Take = take,
Count = 0,
};
var timezoneOffset = firstFile.Well.Timezone?.Hours ?? 5;
if (begin != default) 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) 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); var count = await query.CountAsync(token).ConfigureAwait(false);
@ -185,8 +201,7 @@ namespace AsbCloudInfrastructure.Services
.Take(take).AsNoTracking().ToListAsync(token) .Take(take).AsNoTracking().ToListAsync(token)
.ConfigureAwait(false); .ConfigureAwait(false);
var dtos = entities.Adapt<FileInfoDto>(); var dtos = entities.Select(e => Convert(e, timezoneOffset));
result.Items.AddRange(dtos); result.Items.AddRange(dtos);
return result; return result;
} }
@ -202,7 +217,7 @@ namespace AsbCloudInfrastructure.Services
if (entity is null) if (entity is null)
return null; return null;
var dto = entity.Adapt<FileInfoDto>(); var dto = Convert(entity);
return dto; return dto;
} }
@ -259,10 +274,29 @@ namespace AsbCloudInfrastructure.Services
var entity = await dbSetConfigured var entity = await dbSetConfigured
.FirstOrDefaultAsync(f => f.FileMarks.Any(m => m.Id == idMark), token) .FirstOrDefaultAsync(f => f.FileMarks.Any(m => m.Id == idMark), token)
.ConfigureAwait(false); .ConfigureAwait(false);
var dto = entity.Adapt<FileInfoDto>();
FileInfoDto dto = Convert(entity);
return dto; 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<FileInfoDto>();
dto.UploadDate = entity.UploadDate.ToRemoteDateTime(timezoneOffset);
dto.FileMarks = entity.FileMarks.Select(m =>
{
var mark = m.Adapt<FileMarkDto>();
mark.DateCreated = m.DateCreated.ToRemoteDateTime(timezoneOffset);
return mark;
});
return dto;
}
public async Task<int> CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token) public async Task<int> CreateFileMarkAsync(FileMarkDto fileMarkDto, int idUser, CancellationToken token)
{ {
var fileMark = await db.FileMarks var fileMark = await db.FileMarks
@ -278,7 +312,7 @@ namespace AsbCloudInfrastructure.Services
var newFileMark = fileMarkDto.Adapt<FileMark>(); var newFileMark = fileMarkDto.Adapt<FileMark>();
newFileMark.Id = default; newFileMark.Id = default;
newFileMark.DateCreated = DateTime.Now; newFileMark.DateCreated = DateTime.UtcNow;
newFileMark.IdUser = idUser; newFileMark.IdUser = idUser;
db.FileMarks.Add(newFileMark); db.FileMarks.Add(newFileMark);
@ -303,7 +337,7 @@ namespace AsbCloudInfrastructure.Services
fileInfo.PublishInfo = new FilePublishInfo() fileInfo.PublishInfo = new FilePublishInfo()
{ {
IdPublisher = idUser, IdPublisher = idUser,
Date = DateTime.Now, Date = DateTime.UtcNow,
WebStorageFileUrl = weblink WebStorageFileUrl = weblink
}; };

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