Унификация дат для DailyReport + всё, что пришлось исправить, чтобы проект собрался

This commit is contained in:
Olga Nemt 2024-03-19 17:21:05 +05:00
parent 9723ee3b9e
commit 616cb242d6
15 changed files with 110 additions and 106 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -282,7 +282,7 @@ namespace AsbCloudDb.Migrations
.HasColumnName("date") .HasColumnName("date")
.HasComment("Дата формирования отчёта"); .HasComment("Дата формирования отчёта");
b.Property<DateTime?>("DateLastUpdate") b.Property<DateTimeOffset?>("DateLastUpdate")
.HasColumnType("timestamp with time zone") .HasColumnType("timestamp with time zone")
.HasColumnName("date_last_update") .HasColumnName("date_last_update")
.HasComment("Дата последнего обновления"); .HasComment("Дата последнего обновления");

View File

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

View File

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

View File

@ -4,6 +4,7 @@ using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using Mapster; using Mapster;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
@ -111,7 +112,8 @@ namespace AsbCloudInfrastructure.Repository
{ {
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)
.ToOffset(TimeSpan.FromHours(well.Timezone.Hours));
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

@ -177,8 +177,8 @@ public class WellOperationRepository : IWellOperationRepository
return new DatesRangeDto return new DatesRangeDto
{ {
From = minDate.ToRemoteDateTime(timezone.Hours), From = minDate.ToOffset(timezone.Offset),
To = maxDate.ToRemoteDateTime(timezone.Hours) To = maxDate.ToOffset(timezone.Offset)
}; };
} }
@ -197,12 +197,12 @@ public class WellOperationRepository : IWellOperationRepository
WellOperationRequest request, WellOperationRequest request,
CancellationToken token) CancellationToken token)
{ {
var query = BuildQuery(request) var query = BuildQuery(request)
.AsNoTracking(); .AsNoTracking();
var dtos = await query.ToArrayAsync(token); var dtos = await query.ToArrayAsync(token);
return dtos.Select(Convert); return dtos.Select(Convert);
} }
public async Task<IEnumerable<WellOperationDataDto>> GetAsync( public async Task<IEnumerable<WellOperationDataDto>> GetAsync(
@ -413,14 +413,14 @@ public class WellOperationRepository : IWellOperationRepository
if (request.GeDate.HasValue) if (request.GeDate.HasValue)
{ {
//var geDateOffset = request.GeDate.Value.ToUtcDateTimeOffset(timeZoneOffset); var geDateOffset = request.GeDate.Value.ToUniversalTime();
query = query.Where(e => e.DateStart >= request.GeDate); query = query.Where(e => e.DateStart >= geDateOffset);
} }
if (request.LeDate.HasValue) if (request.LeDate.HasValue)
{ {
//var leDateOffset = request.LeDate.Value.ToUtcDateTimeOffset(timeZoneOffset); var leDateOffset = request.LeDate.Value.ToUniversalTime();
query = query.Where(e => e.DateStart <= request.LeDate); query = query.Where(e => e.DateStart <= leDateOffset);
} }
var currentWellOperations = db.WellOperations var currentWellOperations = db.WellOperations

View File

@ -83,7 +83,7 @@ public class DailyReportService : IDailyReportService
editableBlock.IdUser = idUser; editableBlock.IdUser = idUser;
editableBlock.LastUpdateDate = DateTime.UtcNow; editableBlock.LastUpdateDate = DateTime.UtcNow;
dailyReport.DateLastUpdate = DateTime.UtcNow; dailyReport.DateLastUpdate = DateTimeOffset.UtcNow;
if (dailyReport.Id == 0) if (dailyReport.Id == 0)
return await dailyReportRepository.InsertAsync(dailyReport, cancellationToken); return await dailyReportRepository.InsertAsync(dailyReport, cancellationToken);
@ -158,28 +158,27 @@ public class DailyReportService : IDailyReportService
return result; return result;
var dailyReports = new List<DailyReportDto>(); var dailyReports = new List<DailyReportDto>();
TimeSpan offset = wellService.GetTimezone(idWell).Offset;
if (request.GeDate.HasValue)
{
var startDate = new DateTime(request.GeDate.Value.Year, request.GeDate.Value.Month,
request.GeDate.Value.Day);
if (startDate.Date >= datesRange.From.Date) if (request.GeDate.HasValue)
{
var startDate = new DateTimeOffset(request.GeDate.Value, TimeOnly.MinValue, offset);
if (startDate >= datesRange.From)
datesRange.From = startDate; datesRange.From = startDate;
} }
if (request.LeDate.HasValue) if (request.LeDate.HasValue)
{ {
var finishDate = new DateTime(request.LeDate.Value.Year, request.LeDate.Value.Month, var finishDate = new DateTimeOffset(request.LeDate.Value, TimeOnly.MinValue, offset);
request.LeDate.Value.Day);
if (finishDate.Date <= datesRange.To.Date) if (finishDate <= datesRange.To)
datesRange.To = finishDate; datesRange.To = finishDate;
} }
if (datesRange.From.AddDays(result.Skip) <= datesRange.To) if (datesRange.From.AddDays(result.Skip) <= datesRange.To)
result.Count = (int)(Math.Ceiling((datesRange.To - DateTime.UnixEpoch).TotalDays) - result.Count = (int)(Math.Ceiling((datesRange.To - DateTimeOffset.UnixEpoch).TotalDays) -
Math.Floor((datesRange.From - DateTime.UnixEpoch).TotalDays)) + 1; Math.Floor((datesRange.From - DateTimeOffset.UnixEpoch).TotalDays)) + 1;
var existingDailyReports = await dailyReportRepository.GetAsync(idWell, request, cancellationToken); var existingDailyReports = await dailyReportRepository.GetAsync(idWell, request, cancellationToken);
@ -200,16 +199,16 @@ public class DailyReportService : IDailyReportService
{ {
for (var day = result.Skip; day - result.Skip < result.Take && datesRange.To.AddDays(-day) >= datesRange.From; day++) for (var day = result.Skip; day - result.Skip < result.Take && datesRange.To.AddDays(-day) >= datesRange.From; day++)
{ {
var dateDailyReport = DateOnly.FromDateTime(datesRange.To.AddDays(-day)); var dateDailyReport = DateOnly.FromDateTime(datesRange.To.AddDays(-day).DateTime);
AddDailyReport(dateDailyReport); AddDailyReport(dateDailyReport);
} }
} }
else else
{ {
for (var day = result.Skip; day - result.Skip < result.Take && datesRange.From.AddDays(day) <= datesRange.To; day++) for (var day = result.Skip; day - result.Skip < result.Take && datesRange.From.AddDays(day) <= datesRange.To; day++)
{ {
var dateDailyReport = DateOnly.FromDateTime(datesRange.From.AddDays(day)); var dateDailyReport = DateOnly.FromDateTime(datesRange.From.AddDays(day).DateTime);
AddDailyReport(dateDailyReport); AddDailyReport(dateDailyReport);
} }
@ -243,7 +242,7 @@ public class DailyReportService : IDailyReportService
public async Task<DatesRangeDto?> GetDatesRangeAsync(int idWell, CancellationToken cancellationToken) public async Task<DatesRangeDto?> GetDatesRangeAsync(int idWell, CancellationToken cancellationToken)
{ {
var timezone = wellService.GetTimezone(idWell); var timezone = wellService.GetTimezone(idWell);
var currentDate = DateTimeOffset.UtcNow.ToRemoteDateTime(timezone.Hours); var currentDate = DateTimeOffset.UtcNow.ToOffset(TimeSpan.FromHours(timezone.Hours));
var factOperationDatesRange = await wellOperationRepository.GetDatesRangeAsync(idWell, WellOperation.IdOperationTypeFact, var factOperationDatesRange = await wellOperationRepository.GetDatesRangeAsync(idWell, WellOperation.IdOperationTypeFact,
cancellationToken); cancellationToken);
@ -251,15 +250,13 @@ public class DailyReportService : IDailyReportService
if (factOperationDatesRange is null) if (factOperationDatesRange is null)
return null; return null;
var from = (factOperationDatesRange.From.AddDays(1) <= DateTime.UtcNow ? var from = (factOperationDatesRange.From.AddDays(1) <= DateTimeOffset.UtcNow.ToOffset(TimeSpan.FromHours(timezone.Hours)) ?
factOperationDatesRange.From : factOperationDatesRange.From :
currentDate.AddDays(-1)) currentDate.AddDays(-1));
.Date;
var to = (factOperationDatesRange.To.AddDays(1) <= DateTime.UtcNow ? var to = (factOperationDatesRange.To.AddDays(1) <= DateTimeOffset.UtcNow.ToOffset(TimeSpan.FromHours(timezone.Hours)) ?
factOperationDatesRange.To : factOperationDatesRange.To :
currentDate.AddDays(-1)) currentDate.AddDays(-1));
.Date;
return new DatesRangeDto return new DatesRangeDto
{ {
@ -417,9 +414,8 @@ public class DailyReportService : IDailyReportService
if (datesRange is null) if (datesRange is null)
return false; return false;
var from = DateOnly.FromDateTime(datesRange.From.ToUniversalTime().DateTime);
var from = DateOnly.FromDateTime(datesRange.From); var to = DateOnly.FromDateTime(datesRange.To.ToUniversalTime().DateTime);
var to = DateOnly.FromDateTime(datesRange.To);
return dateDailyReport >= from && dateDailyReport <= to; return dateDailyReport >= from && dateDailyReport <= to;
} }

View File

@ -102,7 +102,7 @@ namespace AsbCloudInfrastructure.Services.SAUB
if (dateBegin == default) if (dateBegin == default)
{ {
var dateRange = telemetryDataCache.GetOrDefaultDataDateRange(telemetry.Id); var dateRange = telemetryDataCache.GetOrDefaultDataDateRange(telemetry.Id);
dateBeginUtc = (dateRange?.To.ToUtcDateTimeOffset(timezone.Hours) ?? DateTime.UtcNow) dateBeginUtc = (dateRange?.To.ToOffset(timezone.Offset) ?? DateTimeOffset.UtcNow)
.AddSeconds(-intervalSec); .AddSeconds(-intervalSec);
} }
else else

View File

@ -145,6 +145,8 @@ public class OperationsStatService : IOperationsStatService
private async Task<StatWellDto> CalcWellStatAsync(Well well, CancellationToken token) private async Task<StatWellDto> CalcWellStatAsync(Well well, CancellationToken token)
{ {
var timezone = wellService.GetTimezone(well.Id);
var wellType = (await memoryCache var wellType = (await memoryCache
.GetOrCreateBasicAsync(db.Set<WellType>(), token)) .GetOrCreateBasicAsync(db.Set<WellType>(), token))
.FirstOrDefault(t => t.Id == well.IdWellType); .FirstOrDefault(t => t.Id == well.IdWellType);
@ -155,7 +157,7 @@ public class OperationsStatService : IOperationsStatService
WellType = wellType?.Caption ?? "", WellType = wellType?.Caption ?? "",
IdState = well.IdState, IdState = well.IdState,
State = wellService.GetStateText(well.IdState), State = wellService.GetStateText(well.IdState),
LastTelemetryDate = wellService.GetLastTelemetryDate(well.Id), LastTelemetryDate = wellService.GetLastTelemetryDate(well.Id).ToOffset(timezone.Offset),
Companies = await wellService.GetCompaniesAsync(well.Id, token) Companies = await wellService.GetCompaniesAsync(well.Id, token)
}; };
@ -169,9 +171,8 @@ public class OperationsStatService : IOperationsStatService
if (!wellOperations.Any()) if (!wellOperations.Any())
return statWellDto; return statWellDto;
var timezoneOffsetH = wellService.GetTimezone(well.Id).Hours; statWellDto.Sections = CalcSectionsStats(wellOperations, timezone.Hours);
statWellDto.Sections = CalcSectionsStats(wellOperations, timezoneOffsetH); statWellDto.Total = GetStatTotal(wellOperations, well.IdState, timezone.Hours);
statWellDto.Total = GetStatTotal(wellOperations, well.IdState, timezoneOffsetH);
statWellDto.TvdLagDays = CalcTvdLagDays(wellOperations); statWellDto.TvdLagDays = CalcTvdLagDays(wellOperations);
statWellDto.TvdDrillingDays = CalcDrillingDays(wellOperations); statWellDto.TvdDrillingDays = CalcDrillingDays(wellOperations);

View File

@ -63,12 +63,12 @@ namespace AsbCloudInfrastructure.Services
private void DropCacheRelationCompanyWell() private void DropCacheRelationCompanyWell()
=> memoryCache.DropBasic<RelationCompanyWell>(); => memoryCache.DropBasic<RelationCompanyWell>();
public DateTime GetLastTelemetryDate(int idWell) public DateTimeOffset GetLastTelemetryDate(int idWell)
{ {
var well = GetOrDefault(idWell); var well = GetOrDefault(idWell);
if (well?.IdTelemetry is null) if (well?.IdTelemetry is null)
return DateTime.MinValue; return DateTimeOffset.MinValue;
var datesRange = telemetryService.GetDatesRange(well.IdTelemetry.Value); var datesRange = telemetryService.GetDatesRange(well.IdTelemetry.Value);
return datesRange.To; return datesRange.To;
@ -278,7 +278,7 @@ namespace AsbCloudInfrastructure.Services
dto.Cluster = entity.Cluster.Caption; dto.Cluster = entity.Cluster.Caption;
dto.Deposit = entity.Cluster.Deposit.Caption; dto.Deposit = entity.Cluster.Deposit.Caption;
if (entity.IdTelemetry is not null) if (entity.IdTelemetry is not null)
dto.LastTelemetryDate = telemetryService.GetDatesRange(entity.IdTelemetry.Value).To; dto.LastTelemetryDate = telemetryService.GetDatesRange(entity.IdTelemetry.Value).To.ToOffset(dto.Timezone.Offset);
dto.Companies = entity.RelationCompaniesWells dto.Companies = entity.RelationCompaniesWells
.Select(r => Convert(r.Company)) .Select(r => Convert(r.Company))
.ToList(); .ToList();

View File

@ -21,7 +21,7 @@ public class WellboreServiceTest
Id = 1, Id = 1,
IdState = 1, IdState = 1,
IdTelemetry = 1, IdTelemetry = 1,
LastTelemetryDate = DateTime.Now, LastTelemetryDate = DateTimeOffset.Now,
Caption = "well 1" Caption = "well 1"
}; };
@ -30,7 +30,7 @@ public class WellboreServiceTest
Id = 2, Id = 2,
IdState = 1, IdState = 1,
IdTelemetry = 100, IdTelemetry = 100,
LastTelemetryDate = DateTime.Now, LastTelemetryDate = DateTimeOffset.Now,
Caption = "well 2" Caption = "well 2"
}; };