Merge branch 'dev' into fix/status_well

This commit is contained in:
Никита Фролов 2023-10-22 09:44:59 +05:00
commit be585d8c85
20 changed files with 9241 additions and 60 deletions

View File

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace AsbCloudApp.Data.SAUB
{
/// <summary>
/// DTO для описания записи drill_test
/// </summary>
public class DrillTestDto
{
/// <summary>
/// Идентификатор drill test
/// </summary>
public int Id { get; set; }
/// <summary>
/// Время начала drill test
/// </summary>
public DateTimeOffset TimeStampStart { get; set; }
/// <summary>
/// Глубина начала drill test
/// </summary>
public float DepthStart { get; set; }
/// <summary>
/// Параметры теста
/// </summary>
public IEnumerable<DrillTestParamsDto> Params { get; set; } = Enumerable.Empty<DrillTestParamsDto>();
}
}

View File

@ -0,0 +1,38 @@
namespace AsbCloudApp.Data.SAUB
{
/// <summary>
/// Параметры Drill Test
/// </summary>
public class DrillTestParamsDto
{
/// <summary>
/// Шаг
/// </summary>
public int Step { get; set; }
/// <summary>
/// Нагрузка
/// </summary>
public float? Workload { get; set; }
/// <summary>
/// Заданная скорость
/// </summary>
public float? Speed { get; set; }
/// <summary>
/// Скорость проходки
/// </summary>
public float? DepthSpeed { get; set; }
/// <summary>
/// Время бурения шага
/// </summary>
public float? TimeDrillStep { get; set; }
/// <summary>
/// Глубина бурения шага
/// </summary>
public float? DepthDrillStep { get; set; }
}
}

View File

@ -0,0 +1,21 @@
using AsbCloudApp.Data.SAUB;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Repositories
{
/// <summary>
/// репозиторий по работе с данными drill_test
/// </summary>
public interface IDrillTestRepository
{
/// <summary>
/// Сохранить данные drill_test
/// </summary>
/// <param name="idTelemetry">ключ телеметрии</param>
/// <param name="dto">запись drill test</param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> SaveDataAsync(int idTelemetry, DrillTestDto dto, CancellationToken token);
}
}

View File

@ -26,17 +26,25 @@ namespace AsbCloudApp.Services
Task<IEnumerable<TDto>> GetAsync(int idWell,
DateTime dateBegin = default, double intervalSec = 600d,
int approxPointsCount = 1024, CancellationToken token = default);
/// <summary>
/// Получить данные тех. процесса
/// </summary>
/// <param name="idWell"></param>
/// <param name="request"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<TDto>> GetAsync(int idWell, TelemetryDataRequest request, CancellationToken token);
/// <summary>
/// Получение статистики за период
/// Получение периода за период
/// </summary>
/// <param name="idWell"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<DatesRangeDto?> GetRangeAsync(int idWell, DateTimeOffset start, DateTimeOffset end, CancellationToken token);
DatesRangeDto? GetRange(int idWell, DateTimeOffset start, DateTimeOffset end);
/// <summary>
/// добавить/изменить данные тех. процесса (используется панелью)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,46 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AsbCloudDb.Migrations
{
public partial class Add_Drill_Test : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "t_drill_test",
columns: table => new
{
id = table.Column<int>(type: "integer", nullable: false, comment: "Идентификатор"),
id_telemetry = table.Column<int>(type: "integer", nullable: false, comment: "Идентификатор телеметрии"),
timestamp_start = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Время начала"),
depthStart = table.Column<float>(type: "real", nullable: false, comment: "Глубина начала"),
t_drill_test_params = table.Column<string>(type: "jsonb", nullable: false, comment: "Параметры записи drill test")
},
constraints: table =>
{
table.PrimaryKey("PK_t_drill_test", x => new { x.id, x.id_telemetry });
table.ForeignKey(
name: "FK_t_drill_test_t_telemetry_id_telemetry",
column: x => x.id_telemetry,
principalTable: "t_telemetry",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
},
comment: "Drill_test");
migrationBuilder.CreateIndex(
name: "IX_t_drill_test_id_telemetry",
table: "t_drill_test",
column: "id_telemetry");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "t_drill_test");
}
}
}

View File

@ -413,6 +413,43 @@ namespace AsbCloudDb.Migrations
b.HasComment("части программ бурения");
});
modelBuilder.Entity("AsbCloudDb.Model.DrillTest", b =>
{
b.Property<int>("Id")
.HasColumnType("integer")
.HasColumnName("id")
.HasComment("Идентификатор");
b.Property<int>("IdTelemetry")
.HasColumnType("integer")
.HasColumnName("id_telemetry")
.HasComment("Идентификатор телеметрии");
b.Property<float>("DepthStart")
.HasColumnType("real")
.HasColumnName("depthStart")
.HasComment("Глубина начала");
b.Property<string>("Params")
.IsRequired()
.HasColumnType("jsonb")
.HasColumnName("t_drill_test_params")
.HasComment("Параметры записи drill test");
b.Property<DateTimeOffset>("TimeStampStart")
.HasColumnType("timestamp with time zone")
.HasColumnName("timestamp_start")
.HasComment("Время начала");
b.HasKey("Id", "IdTelemetry");
b.HasIndex("IdTelemetry");
b.ToTable("t_drill_test");
b.HasComment("Drill_test");
});
modelBuilder.Entity("AsbCloudDb.Model.Faq", b =>
{
b.Property<int>("Id")
@ -7846,6 +7883,17 @@ namespace AsbCloudDb.Migrations
b.Navigation("Well");
});
modelBuilder.Entity("AsbCloudDb.Model.DrillTest", b =>
{
b.HasOne("AsbCloudDb.Model.Telemetry", "Telemetry")
.WithMany()
.HasForeignKey("IdTelemetry")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Telemetry");
});
modelBuilder.Entity("AsbCloudDb.Model.Faq", b =>
{
b.HasOne("AsbCloudDb.Model.User", "AuthorAnswer")

View File

@ -84,6 +84,7 @@ namespace AsbCloudDb.Model
public DbSet<ManualDirectory> ManualDirectories => Set<ManualDirectory>();
public DbSet<Contact> Contacts => Set<Contact>();
public DbSet<DrillTest> DrillTests => Set<DrillTest>();
public AsbCloudDbContext() : base()
{
Interlocked.Increment(ref referenceCount);
@ -411,6 +412,15 @@ namespace AsbCloudDb.Model
.HasForeignKey(m => m.IdDirectory)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<DrillTest>()
.HasKey(m => new { m.Id, m.IdTelemetry });
modelBuilder.Entity<DrillTest>(entity =>
{
entity.Property(e => e.Params)
.HasJsonConversion();
});
DefaultData.DefaultContextData.Fill(modelBuilder);
}

View File

@ -0,0 +1,42 @@
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace AsbCloudDb.Model
{
[Table("t_drill_test"), Comment("Drill_test")]
public class DrillTest
{
/// <summary>
/// Идентификатор drill test
/// </summary>
[Key, Column("id"), Comment("Идентификатор")]
public int Id { get; set; }
/// <summary>
/// Идентификатор телеметрии drill test
/// </summary>
[Key, Column("id_telemetry"), Comment("Идентификатор телеметрии")]
public int IdTelemetry { get; set; }
/// <summary>
/// Время начала drill test
/// </summary>
[Column("timestamp_start", TypeName = "timestamp with time zone"), Comment("Время начала")]
public DateTimeOffset TimeStampStart { get; set; }
/// <summary>
/// Глубина начала drill test
/// </summary>
[Column("depthStart"), Comment("Глубина начала")]
public float DepthStart { get; set; }
[ForeignKey(nameof(IdTelemetry))]
public virtual Telemetry Telemetry { get; set; } = null!;
[Column("t_drill_test_params", TypeName = "jsonb"), Comment("Параметры записи drill test")]
public virtual ICollection<DrillTestParameter> Params { get; set; } = null!;
}
}

View File

@ -0,0 +1,42 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace AsbCloudDb.Model
{
/// <summary>
/// Параметры записи drill test
/// </summary>
public class DrillTestParameter
{
/// <summary>
/// Шаг
/// </summary>
public int Step { get; set; }
/// <summary>
/// Нагрузка
/// </summary>
public float? Workload { get; set; }
/// <summary>
/// Заданная скорость
/// </summary>
public float? Speed { get; set; }
/// <summary>
/// Скорость проходки
/// </summary>
public float? DepthSpeed { get; set; }
/// <summary>
/// Время бурения шага
/// </summary>
public float? TimeDrillStep { get; set; }
/// <summary>
/// Глубина бурения шага
/// </summary>
public float? DepthDrillStep { get; set; }
}
}

View File

@ -76,6 +76,7 @@ namespace AsbCloudDb.Model
DbSet<Manual> Manuals { get; }
DbSet<ManualDirectory> ManualDirectories { get; }
DbSet<Contact> Contacts { get; }
DbSet<DrillTest> DrillTests { get; }
DatabaseFacade Database { get; }
Task<int> RefreshMaterializedViewAsync(string mwName, CancellationToken token);

View File

@ -205,10 +205,11 @@ namespace AsbCloudInfrastructure
services.AddTransient<IGtrRepository, GtrWitsRepository>();
services.AddTransient<NotificationService>();
services.AddTransient<INotificationRepository, NotificationRepository>();
services.AddTransient<ICrudRepository<NotificationCategoryDto>, CrudCacheRepositoryBase<NotificationCategoryDto,
NotificationCategory>>();
services.AddTransient<NotificationService>();
services.AddTransient<INotificationRepository, NotificationRepository>();
services.AddTransient<ICrudRepository<NotificationCategoryDto>, CrudCacheRepositoryBase<NotificationCategoryDto,
NotificationCategory>>();
services.AddTransient<IDrillTestRepository, DrillTestRepository>();
// admin crud services:
services.AddTransient<ICrudRepository<TelemetryDto>, CrudCacheRepositoryBase<TelemetryDto, Telemetry>>(s =>

View File

@ -0,0 +1,28 @@
using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Repositories;
using AsbCloudDb.Model;
using Mapster;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Repository
{
public class DrillTestRepository : IDrillTestRepository
{
private readonly IAsbCloudDbContext db;
public DrillTestRepository(IAsbCloudDbContext db)
{
this.db = db;
}
public async Task<int> SaveDataAsync(int idTelemetry, DrillTestDto dto, CancellationToken token)
{
var entity = dto.Adapt<DrillTest>();
entity.IdTelemetry = idTelemetry;
db.DrillTests.Add(entity);
var result = await db.SaveChangesAsync(token);
return result;
}
}
}

View File

@ -203,40 +203,27 @@ namespace AsbCloudInfrastructure.Services.SAUB
}
/// <inheritdoc/>
public virtual async Task<DatesRangeDto?> GetRangeAsync(
int idWell,
DateTimeOffset start,
DateTimeOffset end,
CancellationToken token)
public DatesRangeDto? GetRange(int idWell, DateTimeOffset start, DateTimeOffset end)
{
var telemetry = telemetryService.GetOrDefaultTelemetryByIdWell(idWell);
if (telemetry is null)
return default;
var timezone = telemetryService.GetTimezone(telemetry.Id);
var startUtc = start.ToOffset(TimeSpan.Zero);
var endUtc = end.ToOffset(TimeSpan.Zero);
var datesRange = telemetryDataCache.GetOrDefaultDataDateRange(telemetry.Id);
var dbSet = db.Set<TEntity>();
var query = dbSet
.Where(i => i.IdTelemetry == telemetry.Id)
.Where(i => i.DateTime >= startUtc)
.Where(i => i.DateTime <= endUtc)
.GroupBy(i => i.IdTelemetry)
.Select(g => new
{
DateStart = g.Min(i => i.DateTime),
DateEnd = g.Max(i => i.DateTime),
});
if (datesRange is null)
return null;
var data = await query.FirstOrDefaultAsync(token);
if (data is null)
return default;
var from = datesRange.From > start.DateTime
? datesRange.From : start.DateTime;
var to = datesRange.To < end.DateTime
? datesRange.To : end.DateTime;
return new DatesRangeDto
{
From = data.DateStart.ToRemoteDateTime(timezone.Hours),
To = data.DateEnd.ToRemoteDateTime(timezone.Hours),
From = from,
To = to,
};
}

View File

@ -27,6 +27,25 @@ public abstract class ProcessMapBaseController<T> : ControllerBase
{
private readonly IHubContext<TelemetryHub> telemetryHubContext;
private readonly ITelemetryService telemetryService;
private readonly IWellService wellService;
private readonly IUserRepository userRepository;
private readonly ICrudRepository<WellSectionTypeDto> wellSectionRepository;
private readonly IProcessMapPlanRepository<T> repository;
protected ProcessMapBaseController(IWellService wellService,
IProcessMapPlanRepository<T> repository,
IUserRepository userRepository,
ICrudRepository<WellSectionTypeDto> wellSectionRepository,
IHubContext<TelemetryHub> telemetryHubContext,
ITelemetryService telemetryService)
{
this.wellService = wellService;
this.repository = repository;
this.userRepository = userRepository;
this.wellSectionRepository = wellSectionRepository;
this.telemetryHubContext = telemetryHubContext;
this.telemetryService = telemetryService;
}
public abstract string SignalRMethod { get; }
@ -42,28 +61,7 @@ public abstract class ProcessMapBaseController<T> : ControllerBase
return idUser.Value;
}
}
private readonly IWellService wellService;
private readonly IUserRepository userRepository;
private readonly ICrudRepository<WellSectionTypeDto> wellSectionRepository;
protected readonly IProcessMapPlanRepository<T> repository;
protected ProcessMapBaseController(IWellService wellService,
IProcessMapPlanRepository<T> repository,
IUserRepository userRepository,
ICrudRepository<WellSectionTypeDto> wellSectionRepository,
IHubContext<TelemetryHub> telemetryHubContext,
ITelemetryService telemetryService)
{
this.wellService = wellService;
this.repository = repository;
this.userRepository = userRepository;
this.wellSectionRepository = wellSectionRepository;
this.telemetryHubContext = telemetryHubContext;
this.telemetryService = telemetryService;
}
/// <summary>
/// Создание плановой РТК
/// </summary>
@ -163,6 +161,7 @@ public abstract class ProcessMapBaseController<T> : ControllerBase
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("/api/telemetry/{uid}/[controller]")]
[AllowAnonymous]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)]
public async Task<ActionResult<IEnumerable<T>>> GetProcessMapPlanByTelemetry(string uid, DateTime updateFrom, CancellationToken cancellationToken)

View File

@ -16,6 +16,9 @@ using Microsoft.AspNetCore.SignalR;
namespace AsbCloudWebApi.Controllers.ProcessMaps;
/// <summary>
/// РТК бурение
/// </summary>
public class ProcessMapWellDrillingController : ProcessMapBaseController<ProcessMapPlanWellDrillingDto>
{
private readonly IProcessMapReportWellDrillingService processMapReportWellDrillingService;
@ -41,7 +44,7 @@ public class ProcessMapWellDrillingController : ProcessMapBaseController<Process
}
/// <summary>
/// Получение отчета РТК бурение
/// Получение данных для отчета РТК бурение
/// </summary>
/// <param name="idWell">Id</param>
/// <param name="cancellationToken"></param>
@ -75,7 +78,7 @@ public class ProcessMapWellDrillingController : ProcessMapBaseController<Process
}
/// <summary>
/// Импорт РТК бурение
/// Импорт РТК бурение план
/// </summary>
/// <param name="idWell">Id скважины</param>
/// <param name="options"></param>
@ -104,8 +107,8 @@ public class ProcessMapWellDrillingController : ProcessMapBaseController<Process
stream,
cancellationToken);
await NotifyUsersBySignalR(idWell, cancellationToken);
}
await NotifyUsersBySignalR(idWell, cancellationToken);
}
catch (FileFormatException ex)
{
return this.ValidationBadRequest(nameof(file), ex.Message);
@ -115,7 +118,7 @@ public class ProcessMapWellDrillingController : ProcessMapBaseController<Process
}
/// <summary>
/// Экспорт РТК бурение
/// Экспорт РТК бурение план
/// </summary>
/// <param name="idWell">Id скважины</param>
/// <param name="cancellationToken"></param>

View File

@ -7,6 +7,9 @@ using Microsoft.AspNetCore.SignalR;
namespace AsbCloudWebApi.Controllers.ProcessMaps;
/// <summary>
/// РТК проработки скважины
/// </summary>
public class ProcessMapWellReamController : ProcessMapBaseController<ProcessMapPlanWellReamDto>
{
public ProcessMapWellReamController(IWellService wellService,
@ -19,5 +22,5 @@ public class ProcessMapWellReamController : ProcessMapBaseController<ProcessMapP
{
}
public override string SignalRMethod => "ProccessMapWellReam";
public override string SignalRMethod => "ProccessMapWellReam";
}

View File

@ -0,0 +1,69 @@
using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services;
using AsbCloudWebApi.SignalR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers.SAUB
{
[Route("api/telemetry")]
[ApiController]
public class DrillTestController : ControllerBase
{
protected readonly IWellService wellService;
private readonly ITelemetryService telemetryService;
private readonly IDrillTestRepository drillTestRepository;
private readonly IHubContext<TelemetryHub> telemetryHubContext;
public string SignalRMethodGetDataName { get; protected set; } = "ReceiveDrilltestData";
public DrillTestController(
ITelemetryService telemetryService,
IDrillTestRepository drillTestRepository,
IWellService wellService,
IHubContext<TelemetryHub> telemetryHubContext)
{
this.telemetryService = telemetryService;
this.drillTestRepository = drillTestRepository;
this.wellService = wellService;
this.telemetryHubContext = telemetryHubContext;
}
/// <summary>
/// Метод получения данных drill_test и drill_test_params от панели оператора.
/// Сохраняет в БД.
/// </summary>
/// <param name="uid">уникальный идентификатор записи drill_test</param>
/// <param name="dto">запись drill test</param>
/// <param name="token"></param>
/// <returns></returns>
[HttpPost("{uid}/[controller]")]
public async Task<IActionResult> PostDataAsync(
string uid,
[FromBody] DrillTestDto dto,
CancellationToken token)
{
var telemetry = telemetryService.GetOrCreateTelemetryByUid(uid);
if (telemetry is null)
throw new Exception($"Telemetry with RemoteUid: {uid} does not exist.");
await drillTestRepository.SaveDataAsync(telemetry.Id, dto, token);
var idWell = telemetryService.GetIdWellByTelemetryUid(uid);
if (idWell is not null)
_ = Task.Run(async () =>
{
var clients = telemetryHubContext.Clients.Group($"well_{idWell}");
await clients.SendAsync(SignalRMethodGetDataName, dto);
}, CancellationToken.None);
return Ok();
}
}
}

View File

@ -153,7 +153,7 @@ namespace AsbCloudWebApi.Controllers.SAUB
if (!isCompanyOwnsWell)
return Forbid();
var content = await telemetryDataService.GetRangeAsync(idWell, start, end, token);
var content = telemetryDataService.GetRange(idWell, start, end);
return Ok(content);
}

View File

@ -68,7 +68,7 @@ namespace AsbCloudWebApi.Controllers.Subsystems
if (!await UserHasAccesToWellAsync(idWell, token))
return Forbid();
var dateRange = await telemetryDataSaubService.GetRangeAsync(idWell, DateTimeOffset.MinValue, DateTimeOffset.MaxValue, token);
var dateRange = telemetryDataSaubService.GetRange(idWell, DateTimeOffset.MinValue, DateTimeOffset.MaxValue);
return Ok(dateRange);
}