forked from ddrilling/AsbCloudServer
CS2-124 Создать контроллер рекомендый новыйх уставок бурильщику
This commit is contained in:
parent
b292fd2a8d
commit
18ad9fc91a
30
AsbCloudApp/Data/SetpointsRequestDto.cs
Normal file
30
AsbCloudApp/Data/SetpointsRequestDto.cs
Normal file
@ -0,0 +1,30 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AsbCloudApp.Data
|
||||
{
|
||||
public class SetpointsRequestDto : IId
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
public int IdWell { get; set; }
|
||||
|
||||
public int IdAuthor { get; set; }
|
||||
|
||||
public int IdState { get; set; }
|
||||
|
||||
public DateTime UploadDate { get; set; }
|
||||
|
||||
public int ObsolescenceSec { get; set; }
|
||||
|
||||
public Dictionary<string, double> Setpoints { get; set; }
|
||||
public string Comment { get; set; }
|
||||
|
||||
public WellDto Well { get; set; }
|
||||
|
||||
public UserDto Author { get; set; }
|
||||
}
|
||||
}
|
19
AsbCloudApp/Services/ISetpointsService.cs
Normal file
19
AsbCloudApp/Services/ISetpointsService.cs
Normal file
@ -0,0 +1,19 @@
|
||||
using AsbCloudApp.Data;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AsbCloudApp.Services
|
||||
{
|
||||
public interface ISetpointsService
|
||||
{
|
||||
Task<int> InsertAsync(SetpointsRequestDto setpoints, CancellationToken token);
|
||||
Task<IEnumerable<SetpointsRequestDto>> GetAsync(int idWell, CancellationToken token);
|
||||
Task<IEnumerable<SetpointsRequestDto>> GetForPanelAsync(string uid, CancellationToken token);
|
||||
Task<int> TryDelete(int idWell, int id, CancellationToken token);
|
||||
Task<int> UpdateStateAsync(string uid, int id, SetpointsRequestDto setpointsRequestDto, CancellationToken token);
|
||||
}
|
||||
}
|
2841
AsbCloudDb/Migrations/20211124111523_AddSetpoints.Designer.cs
generated
Normal file
2841
AsbCloudDb/Migrations/20211124111523_AddSetpoints.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load Diff
61
AsbCloudDb/Migrations/20211124111523_AddSetpoints.cs
Normal file
61
AsbCloudDb/Migrations/20211124111523_AddSetpoints.cs
Normal file
@ -0,0 +1,61 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
namespace AsbCloudDb.Migrations
|
||||
{
|
||||
public partial class AddSetpoints : Migration
|
||||
{
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "t_setpoints_rquest",
|
||||
columns: table => new
|
||||
{
|
||||
id = table.Column<int>(type: "integer", nullable: false)
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
id_well = table.Column<int>(type: "integer", nullable: false, comment: "id скважины"),
|
||||
id_author = table.Column<int>(type: "integer", nullable: false, comment: "Id пользователя, загрузившего файл"),
|
||||
id_state = table.Column<int>(type: "integer", nullable: false, comment: "0: неизвестно, 1:ожидает отправки, 2: отправлено, 3: принято оператором, 4: отклонено оператором, 5: устарело"),
|
||||
date = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||
obsolescence = table.Column<int>(type: "integer", nullable: false, comment: "сек. до устаревания"),
|
||||
setpoint_set = table.Column<Dictionary<string, double>>(type: "jsonb", nullable: true, comment: "Набор уставок"),
|
||||
comment = table.Column<string>(type: "text", nullable: true, comment: "комментарий для оператора")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_t_setpoints_rquest", x => x.id);
|
||||
table.ForeignKey(
|
||||
name: "FK_t_setpoints_rquest_t_user_id_author",
|
||||
column: x => x.id_author,
|
||||
principalTable: "t_user",
|
||||
principalColumn: "id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_t_setpoints_rquest_t_well_id_well",
|
||||
column: x => x.id_well,
|
||||
principalTable: "t_well",
|
||||
principalColumn: "id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
},
|
||||
comment: "Запросы на изменение уставок панели оператора");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_t_setpoints_rquest_id_author",
|
||||
table: "t_setpoints_rquest",
|
||||
column: "id_author");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_t_setpoints_rquest_id_well",
|
||||
table: "t_setpoints_rquest",
|
||||
column: "id_well");
|
||||
}
|
||||
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "t_setpoints_rquest");
|
||||
}
|
||||
}
|
||||
}
|
@ -750,6 +750,60 @@ namespace AsbCloudDb.Migrations
|
||||
.HasComment("Отчеты с данными по буровым");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("AsbCloudDb.Model.SetpointsRequest", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("id")
|
||||
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
|
||||
|
||||
b.Property<string>("Comment")
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("comment")
|
||||
.HasComment("комментарий для оператора");
|
||||
|
||||
b.Property<int>("IdAuthor")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("id_author")
|
||||
.HasComment("Id пользователя, загрузившего файл");
|
||||
|
||||
b.Property<int>("IdState")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("id_state")
|
||||
.HasComment("0: неизвестно, 1:ожидает отправки, 2: отправлено, 3: принято оператором, 4: отклонено оператором, 5: устарело");
|
||||
|
||||
b.Property<int>("IdWell")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("id_well")
|
||||
.HasComment("id скважины");
|
||||
|
||||
b.Property<int>("ObsolescenceSec")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("obsolescence")
|
||||
.HasComment("сек. до устаревания");
|
||||
|
||||
b.Property<Dictionary<string, double>>("Setpoints")
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("setpoint_set")
|
||||
.HasComment("Набор уставок");
|
||||
|
||||
b.Property<DateTime>("UploadDate")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("date");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("IdAuthor");
|
||||
|
||||
b.HasIndex("IdWell");
|
||||
|
||||
b.ToTable("t_setpoints_rquest");
|
||||
|
||||
b
|
||||
.HasComment("Запросы на изменение уставок панели оператора");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("AsbCloudDb.Model.Telemetry", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
@ -2491,6 +2545,25 @@ namespace AsbCloudDb.Migrations
|
||||
b.Navigation("Well");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("AsbCloudDb.Model.SetpointsRequest", b =>
|
||||
{
|
||||
b.HasOne("AsbCloudDb.Model.User", "Author")
|
||||
.WithMany()
|
||||
.HasForeignKey("IdAuthor")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("AsbCloudDb.Model.Well", "Well")
|
||||
.WithMany()
|
||||
.HasForeignKey("IdWell")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Author");
|
||||
|
||||
b.Navigation("Well");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("AsbCloudDb.Model.TelemetryAnalysis", b =>
|
||||
{
|
||||
b.HasOne("AsbCloudDb.Model.WellOperationCategory", "Operation")
|
||||
|
@ -21,6 +21,7 @@ namespace AsbCloudDb.Model
|
||||
public virtual DbSet<Measure> Measures { get; set; }
|
||||
public virtual DbSet<MeasureCategory> MeasureCategories { get; set; }
|
||||
public virtual DbSet<ReportProperty> ReportProperties { get; set; }
|
||||
public virtual DbSet<SetpointsRequest> SetpointsRequests { get; set; }
|
||||
public virtual DbSet<Telemetry> Telemetries { get; set; }
|
||||
public virtual DbSet<TelemetryDataSaub> TelemetryDataSaub { get; set; }
|
||||
public virtual DbSet<TelemetryDataSpin> TelemetryDataSpin { get; set; }
|
||||
|
43
AsbCloudDb/Model/SetpointsRequest.cs
Normal file
43
AsbCloudDb/Model/SetpointsRequest.cs
Normal file
@ -0,0 +1,43 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace AsbCloudDb.Model
|
||||
{
|
||||
[Table("t_setpoints_rquest"), Comment("Запросы на изменение уставок панели оператора")]
|
||||
public class SetpointsRequest : IId, IIdWell
|
||||
{
|
||||
[Key]
|
||||
[Column("id")]
|
||||
public int Id { get; set; }
|
||||
|
||||
[Column("id_well"), Comment("id скважины")]
|
||||
public int IdWell { get; set; }
|
||||
|
||||
[Column("id_author"), Comment("Id пользователя, загрузившего файл")]
|
||||
public int IdAuthor { get; set; }
|
||||
|
||||
[Column("id_state"), Comment("0: неизвестно, 1:ожидает отправки, 2: отправлено, 3: принято оператором, 4: отклонено оператором, 5: устарело")]
|
||||
public int IdState { get; set; }
|
||||
|
||||
[Column("date", TypeName = "timestamp with time zone")]
|
||||
public DateTime UploadDate { get; set; }
|
||||
|
||||
[Column("obsolescence"), Comment("сек. до устаревания")]
|
||||
public int ObsolescenceSec { get; set; }
|
||||
|
||||
[Column("setpoint_set", TypeName = "jsonb"), Comment("Набор уставок")]
|
||||
public Dictionary<string, double> Setpoints { get; set; }
|
||||
|
||||
[Column("comment"), Comment("комментарий для оператора")]
|
||||
public string Comment { get; set; }
|
||||
|
||||
[ForeignKey(nameof(IdWell))]
|
||||
public virtual Well Well { get; set; }
|
||||
|
||||
[ForeignKey(nameof(IdAuthor))]
|
||||
public virtual User Author { get; set; }
|
||||
}
|
||||
}
|
@ -48,6 +48,7 @@ namespace AsbCloudInfrastructure
|
||||
services.AddTransient<IDrillParamsService, DrillParamsService>();
|
||||
services.AddTransient<IDrillFlowChartService, DrillFlowChartService>();
|
||||
services.AddTransient<ITimeZoneService, TimeZoneService>();
|
||||
services.AddTransient<ISetpointsService, SetpointsService>();
|
||||
|
||||
// admin crud services:
|
||||
services.AddTransient<ICrudService<DepositDto>, CrudServiceBase<DepositDto, Deposit>>();
|
||||
|
@ -1,4 +1,5 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
|
||||
@ -10,7 +11,7 @@ namespace AsbCloudInfrastructure.Services.Cache
|
||||
private readonly ConcurrentDictionary<string, CacheTableDataStore> cache =
|
||||
new ConcurrentDictionary<string, CacheTableDataStore>();
|
||||
|
||||
public CacheTable<TEntity> GetCachedTable<TEntity>(DbContext context)
|
||||
public CacheTable<TEntity> GetCachedTable<TEntity>(DbContext context, IEnumerable<string> includes = null)
|
||||
where TEntity : class
|
||||
{
|
||||
var nameOfTEntity = typeof(TEntity).FullName;
|
||||
@ -18,7 +19,7 @@ namespace AsbCloudInfrastructure.Services.Cache
|
||||
NameOfTEntity = nameOfTEntity,
|
||||
Entities = new List<TEntity>(),
|
||||
});
|
||||
var tableCache = new CacheTable<TEntity>(context, cacheItem);
|
||||
var tableCache = new CacheTable<TEntity>(context, cacheItem, includes);
|
||||
return tableCache;
|
||||
}
|
||||
|
||||
|
@ -18,17 +18,42 @@ namespace AsbCloudInfrastructure.Services.Cache
|
||||
private static readonly string nameOfTEntity = typeof(TEntity).Name;
|
||||
|
||||
private readonly CacheTableDataStore data;
|
||||
private readonly Func<DbSet<TEntity>, IQueryable<TEntity>> configureDbSet;
|
||||
private readonly List<TEntity> cached;
|
||||
private readonly DbContext context;
|
||||
private readonly DbSet<TEntity> dbSet;
|
||||
|
||||
internal CacheTable(DbContext context, CacheTableDataStore data)
|
||||
internal CacheTable(DbContext context, CacheTableDataStore data, IEnumerable<string> includes = null)
|
||||
{
|
||||
this.context = context;
|
||||
this.data = data;
|
||||
dbSet = context.Set<TEntity>();
|
||||
|
||||
if (includes?.Any() == true)
|
||||
configureDbSet = (DbSet<TEntity> dbSet) =>
|
||||
{
|
||||
IQueryable<TEntity> result = dbSet;
|
||||
foreach (var include in includes)
|
||||
result = result.Include(include);
|
||||
return result;
|
||||
};
|
||||
|
||||
|
||||
cached = (List<TEntity>)data.Entities;
|
||||
if ((cached.Count == 0)||data.IsObsolete)
|
||||
if ((cached.Count == 0) || data.IsObsolete)
|
||||
Refresh(false);
|
||||
}
|
||||
|
||||
internal CacheTable(DbContext context, CacheTableDataStore data, Func<DbSet<TEntity>, IQueryable<TEntity>> configureDbSet = null)
|
||||
{
|
||||
this.context = context;
|
||||
this.data = data;
|
||||
this.configureDbSet = configureDbSet;
|
||||
|
||||
dbSet = context.Set<TEntity>();
|
||||
|
||||
cached = (List<TEntity>)data.Entities;
|
||||
if ((cached.Count == 0) || data.IsObsolete)
|
||||
Refresh(false);
|
||||
}
|
||||
|
||||
@ -97,7 +122,8 @@ namespace AsbCloudInfrastructure.Services.Cache
|
||||
if (force || data.LastResreshDate + minPeriodRefresh < DateTime.Now)
|
||||
{
|
||||
cached.Clear();
|
||||
var entities = dbSet.AsNoTracking().ToList();
|
||||
IQueryable<TEntity> query = configureDbSet is null ? dbSet : configureDbSet(dbSet);
|
||||
var entities = query.AsNoTracking().ToList();
|
||||
//Trace.WriteLine($"CacheTable<{nameOfTEntity}> refresh");
|
||||
cached.AddRange(entities);
|
||||
data.LastResreshDate = DateTime.Now;
|
||||
@ -109,7 +135,8 @@ namespace AsbCloudInfrastructure.Services.Cache
|
||||
if (force || data.LastResreshDate + minPeriodRefresh < DateTime.Now)
|
||||
{
|
||||
cached.Clear();
|
||||
var entities = await context.Set<TEntity>().AsNoTracking()
|
||||
IQueryable<TEntity> query = configureDbSet is null ? dbSet : configureDbSet(dbSet);
|
||||
var entities = await query.AsNoTracking()
|
||||
.ToListAsync(token).ConfigureAwait(false);
|
||||
//Trace.WriteLine($"CacheTable<{nameOfTEntity}> refreshAsync");
|
||||
cached.AddRange(entities);
|
||||
@ -246,8 +273,9 @@ namespace AsbCloudInfrastructure.Services.Cache
|
||||
dbSet.Update(entity);
|
||||
else
|
||||
dbSet.Add(entity);
|
||||
context.SaveChanges();
|
||||
InternalRefresh(true);
|
||||
var affected = context.SaveChanges();
|
||||
if (affected > 0)
|
||||
InternalRefresh(true);
|
||||
});
|
||||
}
|
||||
|
||||
@ -257,8 +285,9 @@ namespace AsbCloudInfrastructure.Services.Cache
|
||||
dbSet.Update(entity);
|
||||
else
|
||||
dbSet.Add(entity);
|
||||
await context.SaveChangesAsync(token).ConfigureAwait(false);
|
||||
await InternalRefreshAsync(true, token).ConfigureAwait(false);
|
||||
var affected = await context.SaveChangesAsync(token).ConfigureAwait(false);
|
||||
if(affected > 0)
|
||||
await InternalRefreshAsync(true, token).ConfigureAwait(false);
|
||||
}, token);
|
||||
|
||||
public void Upsert(IEnumerable<TEntity> entities)
|
||||
@ -275,8 +304,9 @@ namespace AsbCloudInfrastructure.Services.Cache
|
||||
else
|
||||
dbSet.Add(entity);
|
||||
}
|
||||
context.SaveChanges();
|
||||
InternalRefresh(true);
|
||||
var affected = context.SaveChanges();
|
||||
if (affected > 0)
|
||||
InternalRefresh(true);
|
||||
});
|
||||
}
|
||||
|
||||
@ -294,8 +324,9 @@ namespace AsbCloudInfrastructure.Services.Cache
|
||||
else
|
||||
dbSet.Add(entity);
|
||||
}
|
||||
await context.SaveChangesAsync(token).ConfigureAwait(false);
|
||||
await InternalRefreshAsync(true, token).ConfigureAwait(false);
|
||||
var affected = await context.SaveChangesAsync(token).ConfigureAwait(false);
|
||||
if (affected > 0)
|
||||
await InternalRefreshAsync(true, token).ConfigureAwait(false);
|
||||
}, token);
|
||||
}
|
||||
|
||||
@ -303,15 +334,17 @@ namespace AsbCloudInfrastructure.Services.Cache
|
||||
=> Sync(_ =>
|
||||
{
|
||||
dbSet.RemoveRange(dbSet.Where(predicate));
|
||||
context.SaveChanges();
|
||||
InternalRefresh(true);
|
||||
var affected = context.SaveChanges();
|
||||
if (affected > 0)
|
||||
InternalRefresh(true);
|
||||
});
|
||||
|
||||
public Task RemoveAsync(Func<TEntity, bool> predicate, CancellationToken token = default)
|
||||
=> SyncAsync(async (wasFree, token) => {
|
||||
dbSet.RemoveRange(dbSet.Where(predicate));
|
||||
await context.SaveChangesAsync(token).ConfigureAwait(false);
|
||||
await InternalRefreshAsync(true, token).ConfigureAwait(false);
|
||||
var affected = await context.SaveChangesAsync(token).ConfigureAwait(false);
|
||||
if (affected > 0)
|
||||
await InternalRefreshAsync(true, token).ConfigureAwait(false);
|
||||
}, token);
|
||||
|
||||
public TEntity Insert(TEntity entity)
|
||||
@ -320,8 +353,9 @@ namespace AsbCloudInfrastructure.Services.Cache
|
||||
Sync(_ =>
|
||||
{
|
||||
var entry = dbSet.Add(entity);
|
||||
context.SaveChanges();
|
||||
InternalRefresh(true);
|
||||
var affected = context.SaveChanges();
|
||||
if (affected > 0)
|
||||
InternalRefresh(true);
|
||||
result = entry.Entity;
|
||||
});
|
||||
return result;
|
||||
@ -333,8 +367,9 @@ namespace AsbCloudInfrastructure.Services.Cache
|
||||
await SyncAsync(async (wasFree, token) =>
|
||||
{
|
||||
var entry = dbSet.Add(entity);
|
||||
await context.SaveChangesAsync(token).ConfigureAwait(false);
|
||||
await InternalRefreshAsync(true, token).ConfigureAwait(false);
|
||||
var affected = await context.SaveChangesAsync(token).ConfigureAwait(false);
|
||||
if (affected > 0)
|
||||
await InternalRefreshAsync(true, token).ConfigureAwait(false);
|
||||
result = entry.Entity;
|
||||
}, token);
|
||||
return result;
|
||||
@ -346,7 +381,8 @@ namespace AsbCloudInfrastructure.Services.Cache
|
||||
Sync(_ => {
|
||||
dbSet.AddRange(newEntities);
|
||||
result = context.SaveChanges();
|
||||
InternalRefresh(true);
|
||||
if (result > 0)
|
||||
InternalRefresh(true);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
@ -357,7 +393,8 @@ namespace AsbCloudInfrastructure.Services.Cache
|
||||
await SyncAsync(async (wasFree, token) => {
|
||||
dbSet.AddRange(newEntities);
|
||||
result = await context.SaveChangesAsync(token).ConfigureAwait(false);
|
||||
await InternalRefreshAsync(true, token).ConfigureAwait(false);
|
||||
if (result > 0)
|
||||
await InternalRefreshAsync(true, token).ConfigureAwait(false);
|
||||
}, token);
|
||||
return result;
|
||||
}
|
||||
|
120
AsbCloudInfrastructure/Services/SetpointsService.cs
Normal file
120
AsbCloudInfrastructure/Services/SetpointsService.cs
Normal file
@ -0,0 +1,120 @@
|
||||
using AsbCloudApp.Data;
|
||||
using AsbCloudApp.Services;
|
||||
using AsbCloudDb.Model;
|
||||
using AsbCloudInfrastructure.Services.Cache;
|
||||
using Mapster;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AsbCloudInfrastructure.Services
|
||||
{
|
||||
public class SetpointsService : ISetpointsService, IConverter<SetpointsRequestDto, SetpointsRequest>
|
||||
{
|
||||
private readonly CacheTable<SetpointsRequest> cacheSetpoints;
|
||||
private readonly ITelemetryService telemetryService;
|
||||
|
||||
public SetpointsService(IAsbCloudDbContext db, CacheDb cacheDb, ITelemetryService telemetryService)
|
||||
{
|
||||
cacheSetpoints = cacheDb.GetCachedTable<SetpointsRequest>(
|
||||
(AsbCloudDbContext)db,
|
||||
new List<string> {
|
||||
nameof(SetpointsRequest.Author),
|
||||
nameof(SetpointsRequest.Well),
|
||||
});
|
||||
this.telemetryService = telemetryService;
|
||||
}
|
||||
|
||||
public async Task<int> InsertAsync(SetpointsRequestDto setpoints, CancellationToken token)
|
||||
{
|
||||
setpoints.IdState = 1;
|
||||
var inserted = await cacheSetpoints.InsertAsync(Convert(setpoints), token)
|
||||
.ConfigureAwait(false);
|
||||
return inserted?.Id ?? 0;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<SetpointsRequestDto>> GetAsync(int idWell, CancellationToken token)
|
||||
{
|
||||
var entities = await cacheSetpoints.WhereAsync(s => s.IdWell == idWell, token)
|
||||
.ConfigureAwait(false);
|
||||
var dtos = entities.Select(s => Convert(s));
|
||||
return dtos;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<SetpointsRequestDto>> GetForPanelAsync(string uid, CancellationToken token)
|
||||
{
|
||||
var idWell = telemetryService.GetidWellByTelemetryUid(uid) ?? -1;
|
||||
|
||||
if (idWell < 0)
|
||||
return null;
|
||||
|
||||
var entities = await cacheSetpoints.WhereAsync(s =>
|
||||
s.IdWell == idWell && s.IdState == 1 && s.UploadDate.AddSeconds(s.ObsolescenceSec) > DateTime.Now,
|
||||
token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (!entities.Any())
|
||||
return null;
|
||||
|
||||
foreach (var entity in entities)
|
||||
entity.IdState = 2;
|
||||
|
||||
await cacheSetpoints.UpsertAsync(entities, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var dtos = entities.Select(Convert);
|
||||
|
||||
return dtos;
|
||||
}
|
||||
|
||||
public async Task<int> UpdateStateAsync(string uid, int id, SetpointsRequestDto setpointsRequestDto, CancellationToken token)
|
||||
{
|
||||
if (setpointsRequestDto.IdState != 3 || setpointsRequestDto.IdState != 4)
|
||||
throw new ArgumentOutOfRangeException(nameof(setpointsRequestDto), $"{nameof(setpointsRequestDto.IdState)} = {setpointsRequestDto.IdState}. Mast be 3 or 4.");
|
||||
|
||||
var idWell = telemetryService.GetidWellByTelemetryUid(uid) ?? -1;
|
||||
|
||||
if (idWell < 0)
|
||||
return 0;
|
||||
|
||||
bool Predicate(SetpointsRequest s) => s.Id == id && s.IdWell == idWell && s.IdState == 2;
|
||||
|
||||
var entity = await cacheSetpoints.FirstOrDefaultAsync(Predicate, token)
|
||||
.ConfigureAwait(false);
|
||||
entity.IdState = setpointsRequestDto.IdState;
|
||||
await cacheSetpoints.UpsertAsync(entity, token)
|
||||
.ConfigureAwait(false);
|
||||
return 1;
|
||||
}
|
||||
|
||||
public async Task<int> TryDelete(int idWell, int id, CancellationToken token)
|
||||
{
|
||||
bool Predicate(SetpointsRequest s) => s.Id == id && s.IdWell == idWell && s.IdState == 1;
|
||||
var isExist = await cacheSetpoints.ContainsAsync(Predicate, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (!isExist)
|
||||
return 0;
|
||||
|
||||
await cacheSetpoints.RemoveAsync(Predicate, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
public SetpointsRequest Convert(SetpointsRequestDto src)
|
||||
{
|
||||
var entity = src.Adapt<SetpointsRequest>();
|
||||
return entity;
|
||||
}
|
||||
|
||||
public SetpointsRequestDto Convert(SetpointsRequest src)
|
||||
{
|
||||
var dto = src.Adapt<SetpointsRequestDto>();
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
}
|
162
AsbCloudWebApi/Controllers/SetpointsController.cs
Normal file
162
AsbCloudWebApi/Controllers/SetpointsController.cs
Normal file
@ -0,0 +1,162 @@
|
||||
using AsbCloudApp.Services;
|
||||
using AsbCloudApp.Data;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Threading;
|
||||
|
||||
namespace AsbCloudWebApi.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class SetpointsController : ControllerBase
|
||||
{
|
||||
private readonly ISetpointsService setpointsService;
|
||||
private readonly IWellService wellService;
|
||||
private const int ObsolescenceSecMin = 30;
|
||||
private const int ObsolescenceSecMax = 6 * 60 * 60;
|
||||
|
||||
public SetpointsController(ISetpointsService setpointsService, IWellService wellService)
|
||||
{
|
||||
this.setpointsService = setpointsService;
|
||||
this.wellService = wellService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Добавляет запрос на изменение заданий панели оператора.
|
||||
/// </summary>
|
||||
/// <param name="idWell"></param>
|
||||
/// <param name="setpoints"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("api/well/{idWell}/setpoints")]
|
||||
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
|
||||
public async Task<IActionResult> InsertAsync(int idWell, SetpointsRequestDto setpoints, CancellationToken token = default)
|
||||
{
|
||||
int? idCompany = User.GetCompanyId();
|
||||
int? idUser = User.GetUserId();
|
||||
|
||||
if (idCompany is null || idUser is null)
|
||||
return Forbid();
|
||||
|
||||
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
|
||||
idWell, token).ConfigureAwait(false))
|
||||
return Forbid();
|
||||
|
||||
setpoints.IdAuthor = idUser ?? -1;
|
||||
setpoints.IdWell = idWell;
|
||||
setpoints.IdState = 1;
|
||||
|
||||
if (setpoints is null
|
||||
|| setpoints.ObsolescenceSec > ObsolescenceSecMax
|
||||
|| setpoints.ObsolescenceSec < ObsolescenceSecMin)
|
||||
return BadRequest("Wrong ObsolescenceSec");
|
||||
|
||||
if (!setpoints.Setpoints.Any())
|
||||
return BadRequest("Wrong Setpoints count");
|
||||
|
||||
var result = await setpointsService.InsertAsync(setpoints, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получает список запросов на изменение уставок.
|
||||
/// </summary>
|
||||
/// <param name="idWell"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("api/well/{idWell}/setpoints")]
|
||||
[ProducesResponseType(typeof(IEnumerable<SetpointsRequestDto>), (int)System.Net.HttpStatusCode.OK)]
|
||||
public async Task<IActionResult> GetByIdWellAsync([FromRoute] int idWell, CancellationToken token = default)
|
||||
{
|
||||
int? idCompany = User.GetCompanyId();
|
||||
int? idUser = User.GetUserId();
|
||||
|
||||
if (idCompany is null || idUser is null)
|
||||
return Forbid();
|
||||
|
||||
var result = await setpointsService.GetAsync(idWell, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Отчет о принятии, или отклонении уставок оператором.
|
||||
/// После уставка будет не изменяемой.
|
||||
/// </summary>
|
||||
/// <param name="uid"></param>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="setpointsRequestDto">можно передать только новый state eg.: {state:3} - принято</param>
|
||||
/// <param name="token"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPut("api/telemetry/{uid}/setpoints/{id}")]
|
||||
[ProducesResponseType(typeof(SetpointsRequestDto), (int)System.Net.HttpStatusCode.OK)]
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> UpdateByTelemetryUidAsync([FromRoute] string uid, int id, SetpointsRequestDto setpointsRequestDto, CancellationToken token = default)
|
||||
{
|
||||
int? idCompany = User.GetCompanyId();
|
||||
int? idUser = User.GetUserId();
|
||||
|
||||
if (idCompany is null || idUser is null)
|
||||
return Forbid();
|
||||
|
||||
var result = await setpointsService.UpdateStateAsync(uid, id, setpointsRequestDto, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получает запросы на изменение уставок панели.
|
||||
/// !!SIDE EFFECT: изменяет состояние запросов уставок на отправлено, это не позволит удалить эти уставки после отправки на панель.
|
||||
/// </summary>
|
||||
/// <param name="uid"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("api/telemetry/{uid}/setpoints")]
|
||||
[AllowAnonymous]
|
||||
[ProducesResponseType(typeof(IEnumerable<SetpointsRequestDto>), (int)System.Net.HttpStatusCode.OK)]
|
||||
public async Task<IActionResult> GetByTelemetryUidAsync([FromRoute] string uid, CancellationToken token = default)
|
||||
{
|
||||
int? idCompany = User.GetCompanyId();
|
||||
int? idUser = User.GetUserId();
|
||||
|
||||
if (idCompany is null || idUser is null)
|
||||
return Forbid();
|
||||
|
||||
var result = await setpointsService.GetForPanelAsync(uid, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Пробуем удалить запрос на изменение уставок. Это будет выполнено, если запрос еще не был отправлен.
|
||||
/// </summary>
|
||||
/// <param name="idWell"></param>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <returns>1 - удалено, <= 0 - не удалено</returns>
|
||||
[HttpDelete("api/well/{idWell}/setpoints/{id}")]
|
||||
public async Task<IActionResult> TryDeleteByIdWellAsync(int idWell, int id, CancellationToken token = default)
|
||||
{
|
||||
int? idCompany = User.GetCompanyId();
|
||||
int? idUser = User.GetUserId();
|
||||
|
||||
if (idCompany is null || idUser is null)
|
||||
return Forbid();
|
||||
|
||||
var result = await setpointsService.TryDelete(idWell, id, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user