autoclean.

This commit is contained in:
ngfrolov 2022-06-15 14:57:37 +05:00
parent 341375bf1f
commit 7080b3e855
76 changed files with 347 additions and 464 deletions

View File

@ -1,6 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
namespace AsbCloudApp.Data namespace AsbCloudApp.Data
{ {
@ -31,7 +29,7 @@ namespace AsbCloudApp.Data
public double? AverageTargetValue { get; set; } public double? AverageTargetValue { get; set; }
/// <summary> /// <summary>
/// Коэффициент эффективности /// Коэффициент эффективности, %
/// </summary> /// </summary>
public double? Efficiency { get; set; } public double? Efficiency { get; set; }

View File

@ -16,7 +16,7 @@ namespace AsbCloudApp.Data
/// <summary> /// <summary>
/// Интерфейс записи данных телеметрии /// Интерфейс записи данных телеметрии
/// </summary> /// </summary>
public interface ITelemetryData: ITelemetryRelated public interface ITelemetryData : ITelemetryRelated
{ {
/// <summary> /// <summary>
/// Отметка времени для этой записи /// Отметка времени для этой записи

View File

@ -1,6 +1,4 @@
using System; namespace AsbCloudApp.Data
namespace AsbCloudApp.Data
{ {
/// <summary> /// <summary>
/// Описание целевых/нормативных показателей операций /// Описание целевых/нормативных показателей операций

View File

@ -5,7 +5,7 @@ namespace AsbCloudApp.Data
/// <summary> /// <summary>
/// DTO времени /// DTO времени
/// </summary> /// </summary>
public class TimeDto: IComparable<TimeDto> public class TimeDto : IComparable<TimeDto>
{ {
private int hour = 0; private int hour = 0;
private int minute = 0; private int minute = 0;
@ -14,13 +14,15 @@ namespace AsbCloudApp.Data
/// <summary> /// <summary>
/// час /// час
/// </summary> /// </summary>
public int Hour { public int Hour
get => hour; {
set { get => hour;
set
{
if (value > 23 || value < 0) if (value > 23 || value < 0)
throw new ArgumentOutOfRangeException(nameof(Hour), "hour should be in [0; 23]"); throw new ArgumentOutOfRangeException(nameof(Hour), "hour should be in [0; 23]");
hour = value; hour = value;
} }
} }
/// <summary> /// <summary>

View File

@ -3,7 +3,7 @@
/// <summary> /// <summary>
/// DTO категория операции /// DTO категория операции
/// </summary> /// </summary>
public class WellOperationCategoryDto: IId public class WellOperationCategoryDto : IId
{ {
/// <inheritdoc/> /// <inheritdoc/>
public int Id { get; set; } public int Id { get; set; }

View File

@ -1,12 +1,12 @@
using System.Collections.Generic; using System;
using System; using System.Collections.Generic;
namespace AsbCloudApp.Requests namespace AsbCloudApp.Requests
{ {
/// <summary> /// <summary>
/// Параметры запроса на получение операций определенных по телеметрии /// Параметры запроса на получение операций определенных по телеметрии
/// </summary> /// </summary>
public class DetectedOperationRequest: RequestBase public class DetectedOperationRequest : RequestBase
{ {
/// <summary> /// <summary>
/// категории операций /// категории операций

View File

@ -9,9 +9,9 @@ namespace AsbCloudApp.Services
/// <summary> /// <summary>
/// Сервис получения, добавления, изменения, удаления данных /// Сервис получения, добавления, изменения, удаления данных
/// </summary> /// </summary>
/// <typeparam name="Tdto"></typeparam> /// <typeparam name="TDto"></typeparam>
public interface ICrudService<Tdto> public interface ICrudService<TDto>
where Tdto : Data.IId where TDto : Data.IId
{ {
/// <summary> /// <summary>
/// Код возврата ошибки: Id не найден в БД. /// Код возврата ошибки: Id не найден в БД.
@ -23,7 +23,7 @@ namespace AsbCloudApp.Services
/// </summary> /// </summary>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns>emptyList if nothing found</returns> /// <returns>emptyList if nothing found</returns>
Task<IEnumerable<Tdto>> GetAllAsync(CancellationToken token); Task<IEnumerable<TDto>> GetAllAsync(CancellationToken token);
/// <summary> /// <summary>
/// Получить запись по id /// Получить запись по id
@ -31,14 +31,14 @@ namespace AsbCloudApp.Services
/// <param name="id"></param> /// <param name="id"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns>null if not found</returns> /// <returns>null if not found</returns>
Task<Tdto?> GetAsync(int id, CancellationToken token); Task<TDto?> GetAsync(int id, CancellationToken token);
/// <summary> /// <summary>
/// Получить запись по id /// Получить запись по id
/// </summary> /// </summary>
/// <param name="id"></param> /// <param name="id"></param>
/// <returns>null if not found</returns> /// <returns>null if not found</returns>
Tdto? Get(int id); TDto? Get(int id);
/// <summary> /// <summary>
/// Добавление новой записи /// Добавление новой записи
@ -46,7 +46,7 @@ namespace AsbCloudApp.Services
/// <param name="newItem"></param> /// <param name="newItem"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns>Id новой записи</returns> /// <returns>Id новой записи</returns>
Task<int> InsertAsync(Tdto newItem, CancellationToken token); Task<int> InsertAsync(TDto newItem, CancellationToken token);
/// <summary> /// <summary>
/// Добавление нескольких записей /// Добавление нескольких записей
@ -54,7 +54,7 @@ namespace AsbCloudApp.Services
/// <param name="newItems"></param> /// <param name="newItems"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns>количество добавленных</returns> /// <returns>количество добавленных</returns>
Task<int> InsertRangeAsync(IEnumerable<Tdto> newItems, CancellationToken token); Task<int> InsertRangeAsync(IEnumerable<TDto> newItems, CancellationToken token);
/// <summary> /// <summary>
/// Отредактировать запись /// Отредактировать запись
@ -62,7 +62,7 @@ namespace AsbCloudApp.Services
/// <param name="item"></param> /// <param name="item"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns>если больше 0 - Id записи, если меньше 0 - код ошибки</returns> /// <returns>если больше 0 - Id записи, если меньше 0 - код ошибки</returns>
Task<int> UpdateAsync(Tdto item, CancellationToken token); Task<int> UpdateAsync(TDto item, CancellationToken token);
/// <summary> /// <summary>
/// Удалить запись /// Удалить запись

View File

@ -11,7 +11,7 @@ namespace AsbCloudApp.Services
/// </summary> /// </summary>
/// <typeparam name="Tdto"></typeparam> /// <typeparam name="Tdto"></typeparam>
public interface ICrudWellRelatedService<Tdto> : ICrudService<Tdto> public interface ICrudWellRelatedService<Tdto> : ICrudService<Tdto>
where Tdto: IId, IWellRelated where Tdto : IId, IWellRelated
{ {
/// <summary> /// <summary>
/// Получение всех записей по скважине /// Получение всех записей по скважине

View File

@ -1,6 +1,5 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using System; using System;
using System.Collections.Generic;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;

View File

@ -10,8 +10,8 @@ namespace AsbCloudApp.Services
Task<int> InsertAsync(SetpointsRequestDto setpoints, CancellationToken token); Task<int> InsertAsync(SetpointsRequestDto setpoints, CancellationToken token);
Task<IEnumerable<SetpointsRequestDto>> GetAsync(int idWell, CancellationToken token); Task<IEnumerable<SetpointsRequestDto>> GetAsync(int idWell, CancellationToken token);
Task<IEnumerable<SetpointsRequestDto>> GetForPanelAsync(string uid, CancellationToken token); Task<IEnumerable<SetpointsRequestDto>> GetForPanelAsync(string uid, CancellationToken token);
Task<int> TryDelete(int idWell, int id, CancellationToken token); Task<int> TryDelete(int id, CancellationToken token);
Task<int> UpdateStateAsync(string uid, int id, SetpointsRequestDto setpointsRequestDto, CancellationToken token); Task<int> UpdateStateAsync(int id, SetpointsRequestDto setpointsRequestDto, CancellationToken token);
IEnumerable<SetpointInfoDto> GetSetpointsNames(int idWell); IEnumerable<SetpointInfoDto> GetSetpointsNames();
} }
} }

View File

@ -55,13 +55,13 @@ namespace AsbCloudDb
{ {
return dbSet.Contains(value) return dbSet.Contains(value)
? dbSet.Update(value) ? dbSet.Update(value)
: dbSet.Add(value); : dbSet.Add(value);
} }
public static (int updated, int inserted) UpsertRange<T>(this DbSet<T> dbSet, IEnumerable<T> values) public static (int updated, int inserted) UpsertRange<T>(this DbSet<T> dbSet, IEnumerable<T> values)
where T : class where T : class
{ {
(int updated, int inserted) stat = (0,0); (int updated, int inserted) stat = (0, 0);
foreach (var value in values) foreach (var value in values)
if (dbSet.Contains(value)) if (dbSet.Contains(value))
{ {

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;

View File

@ -7,10 +7,10 @@ using System.Text.Json.Serialization;
namespace AsbCloudDb.Model namespace AsbCloudDb.Model
{ {
[Table("t_driller"), Comment("Бурильщик")] [Table("t_driller"), Comment("Бурильщик")]
public class Driller: IId public class Driller : IId
{ {
[Key] [Key]
[Column("id"),Comment("Идентификатор")] [Column("id"), Comment("Идентификатор")]
public int Id { get; set; } public int Id { get; set; }
[Column("name"), Comment("Имя")] [Column("name"), Comment("Имя")]

View File

@ -5,7 +5,7 @@ using System.ComponentModel.DataAnnotations.Schema;
namespace AsbCloudDb.Model namespace AsbCloudDb.Model
{ {
[Table("t_operationvalue"), Comment("Целевые/нормативные показатели операции")] [Table("t_operationvalue"), Comment("Целевые/нормативные показатели операции")]
public class OperationValue: IId, IWellRelated public class OperationValue : IId, IWellRelated
{ {
[Key] [Key]
[Column("id"), Comment("Идентификатор")] [Column("id"), Comment("Идентификатор")]
@ -24,7 +24,7 @@ namespace AsbCloudDb.Model
public double StandardValue { get; set; } public double StandardValue { get; set; }
[Column("depth_start"), Comment("Старотовая глубина")] [Column("depth_start"), Comment("Старотовая глубина")]
public double DepthStart { get; set; } public double DepthStart { get; set; }
[Column("depth_end"), Comment("Конечная глубина")] [Column("depth_end"), Comment("Конечная глубина")]
public double DepthEnd { get; set; } public double DepthEnd { get; set; }

View File

@ -6,10 +6,10 @@ using System.ComponentModel.DataAnnotations.Schema;
namespace AsbCloudDb.Model namespace AsbCloudDb.Model
{ {
[Table("t_schedule"), Comment("График работы бурильщика")] [Table("t_schedule"), Comment("График работы бурильщика")]
public class Schedule: IId, IWellRelated public class Schedule : IId, IWellRelated
{ {
[Key] [Key]
[Column("id"),Comment("Идентификатор")] [Column("id"), Comment("Идентификатор")]
public int Id { get; set; } public int Id { get; set; }
[Column("id_driller"), Comment("Идентификатор бурильщика")] [Column("id_driller"), Comment("Идентификатор бурильщика")]

View File

@ -65,7 +65,7 @@ namespace AsbCloudInfrastructure
TypeAdapterConfig.GlobalSettings.Default.Config TypeAdapterConfig.GlobalSettings.Default.Config
.ForType<ClusterDto, Cluster>() .ForType<ClusterDto, Cluster>()
.Ignore(dst => dst.Deposit, .Ignore(dst => dst.Deposit,
dst=>dst.Wells); dst => dst.Wells);
} }
@ -120,7 +120,7 @@ namespace AsbCloudInfrastructure
services.AddTransient<IOperationValueService, OperationValueService>(); services.AddTransient<IOperationValueService, OperationValueService>();
// admin crud services: // admin crud services:
services.AddTransient<ICrudService<TelemetryDto>, CrudServiceBase<TelemetryDto, Telemetry>>(s => services.AddTransient<ICrudService<TelemetryDto>, CrudServiceBase<TelemetryDto, Telemetry>>(s =>
new CrudCacheServiceBase<TelemetryDto, Telemetry>( new CrudCacheServiceBase<TelemetryDto, Telemetry>(
s.GetService<IAsbCloudDbContext>(), s.GetService<IAsbCloudDbContext>(),
dbSet => dbSet.Include(t => t.Well))); // может быть включен в сервис TelemetryService dbSet => dbSet.Include(t => t.Well))); // может быть включен в сервис TelemetryService
@ -132,9 +132,9 @@ namespace AsbCloudInfrastructure
services.AddTransient<ICrudService<CompanyDto>, CrudCacheServiceBase<CompanyDto, Company>>(s => services.AddTransient<ICrudService<CompanyDto>, CrudCacheServiceBase<CompanyDto, Company>>(s =>
new CrudCacheServiceBase<CompanyDto, Company>( new CrudCacheServiceBase<CompanyDto, Company>(
s.GetService<IAsbCloudDbContext>(), s.GetService<IAsbCloudDbContext>(),
dbSet => dbSet.Include(c=>c.CompanyType))); dbSet => dbSet.Include(c => c.CompanyType)));
services.AddTransient<ICrudService<CompanyTypeDto>, CrudCacheServiceBase<CompanyTypeDto, CompanyType>>(); services.AddTransient<ICrudService<CompanyTypeDto>, CrudCacheServiceBase<CompanyTypeDto, CompanyType>>();
services.AddTransient<ICrudService<ClusterDto>, CrudCacheServiceBase<ClusterDto, Cluster>>(s => services.AddTransient<ICrudService<ClusterDto>, CrudCacheServiceBase<ClusterDto, Cluster>>(s =>
new CrudCacheServiceBase<ClusterDto, Cluster>( new CrudCacheServiceBase<ClusterDto, Cluster>(
s.GetService<IAsbCloudDbContext>(), s.GetService<IAsbCloudDbContext>(),
dbSet => dbSet dbSet => dbSet

View File

@ -42,7 +42,7 @@ namespace AsbCloudInfrastructure.EfCache
{ {
if (Data is Dictionary<TKey, TModel> typedData) if (Data is Dictionary<TKey, TModel> typedData)
return typedData; return typedData;
if (Data is Dictionary<TKey, TEntity > typedEntityData) if (Data is Dictionary<TKey, TEntity> typedEntityData)
{ {
if (semaphore.Wait(0)) if (semaphore.Wait(0))
{ {
@ -375,16 +375,16 @@ namespace AsbCloudInfrastructure.EfCache
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
public static async Task<Dictionary<TKey, TEntity>> FromCacheDictionaryAsync<TKey, TEntity>( public static async Task<Dictionary<TKey, TEntity>> FromCacheDictionaryAsync<TKey, TEntity>(
this IQueryable<TEntity> query, this IQueryable<TEntity> query,
string tag, string tag,
TimeSpan obsolescence, TimeSpan obsolescence,
Func<TEntity, TKey> keySelector, Func<TEntity, TKey> keySelector,
CancellationToken token = default) CancellationToken token = default)
where TEntity : class where TEntity : class
where TKey : notnull where TKey : notnull
{ {
async Task<IDictionary> factory(CancellationToken token) async Task<IDictionary> factory(CancellationToken token)
=> await query.AsNoTracking().ToDictionaryAsync(keySelector, token); => await query.AsNoTracking().ToDictionaryAsync(keySelector, token);
var cache = await GetOrAddCacheAsync(tag, factory, obsolescence, token); var cache = await GetOrAddCacheAsync(tag, factory, obsolescence, token);
return cache.GetData<TKey, TEntity>(); return cache.GetData<TKey, TEntity>();
} }

View File

@ -15,7 +15,7 @@ namespace AsbCloudInfrastructure.EfCache
/// </summary> /// </summary>
public static class EfCacheExtensions public static class EfCacheExtensions
{ {
private static readonly Dictionary<string, CacheItem> caches = new(16); private static readonly Dictionary<string, CacheItem> caches = new(16);
private static readonly TimeSpan semaphoreTimeout = TimeSpan.FromSeconds(25); private static readonly TimeSpan semaphoreTimeout = TimeSpan.FromSeconds(25);
private static readonly SemaphoreSlim semaphore = new(1); private static readonly SemaphoreSlim semaphore = new(1);
private static readonly TimeSpan minCacheTime = TimeSpan.FromSeconds(2); private static readonly TimeSpan minCacheTime = TimeSpan.FromSeconds(2);
@ -71,7 +71,7 @@ namespace AsbCloudInfrastructure.EfCache
} }
} }
} }
if(attempt > 0) if (attempt > 0)
return GetData(convert, --attempt); return GetData(convert, --attempt);
throw new TypeAccessException("Cache data has wrong type. Possible 'tag' is not unique."); throw new TypeAccessException("Cache data has wrong type. Possible 'tag' is not unique.");
} }
@ -84,18 +84,19 @@ namespace AsbCloudInfrastructure.EfCache
{ {
if (semaphore.Wait(0)) if (semaphore.Wait(0))
{ {
try { try
{
cache = new CacheItem(); cache = new CacheItem();
caches.Add(tag, cache); caches.Add(tag, cache);
} }
catch catch
{ {
throw; throw;
} }
finally finally
{ {
semaphore.Release(); semaphore.Release();
} }
break; break;
} }
else else
@ -109,7 +110,7 @@ namespace AsbCloudInfrastructure.EfCache
semaphore.Release(); semaphore.Release();
throw new TimeoutException("EfCacheL2.GetOrAddCache. Can't wait too long while getting cache"); throw new TimeoutException("EfCacheL2.GetOrAddCache. Can't wait too long while getting cache");
} }
} }
} }
cache = caches[tag]; cache = caches[tag];
@ -141,7 +142,7 @@ namespace AsbCloudInfrastructure.EfCache
cache.semaphore.Release(); cache.semaphore.Release();
} }
} }
else if(cache.DateObsoleteTotal < DateTime.Now) else if (cache.DateObsoleteTotal < DateTime.Now)
{ {
if (cache.semaphore.Wait(semaphoreTimeout)) if (cache.semaphore.Wait(semaphoreTimeout))
{ {
@ -152,7 +153,7 @@ namespace AsbCloudInfrastructure.EfCache
cache.semaphore.Release(); cache.semaphore.Release();
throw new TimeoutException("EfCacheL2.GetOrAddCache. Can't wait too long while getting cache"); throw new TimeoutException("EfCacheL2.GetOrAddCache. Can't wait too long while getting cache");
} }
} }
} }
return cache; return cache;
} }
@ -281,7 +282,7 @@ namespace AsbCloudInfrastructure.EfCache
public static IEnumerable<TModel> FromCache<TEntity, TModel>(this IQueryable<TEntity> query, string tag, TimeSpan obsolescence, Func<TEntity, TModel> convert) public static IEnumerable<TModel> FromCache<TEntity, TModel>(this IQueryable<TEntity> query, string tag, TimeSpan obsolescence, Func<TEntity, TModel> convert)
where TEntity : class where TEntity : class
{ {
IEnumerable factory () => query.AsNoTracking().ToList(); IEnumerable factory() => query.AsNoTracking().ToList();
var cache = GetOrAddCache(tag, factory, obsolescence); var cache = GetOrAddCache(tag, factory, obsolescence);
return cache.GetData(convert); return cache.GetData(convert);
} }
@ -327,7 +328,7 @@ namespace AsbCloudInfrastructure.EfCache
where TEntity : class where TEntity : class
{ {
async Task<IEnumerable> factory(CancellationToken token) async Task<IEnumerable> factory(CancellationToken token)
=> await query.AsNoTracking().ToListAsync(token); => await query.AsNoTracking().ToListAsync(token);
var cache = await GetOrAddCacheAsync(tag, factory, obsolescence, token); var cache = await GetOrAddCacheAsync(tag, factory, obsolescence, token);
return cache.GetData(convert); return cache.GetData(convert);
} }

View File

@ -4,5 +4,5 @@
/// Тип для поиска этой сборки /// Тип для поиска этой сборки
/// </summary> /// </summary>
public interface IInfrastructureMarker public interface IInfrastructureMarker
{} { }
} }

View File

@ -1,8 +1,4 @@
using System; namespace Mapster
using System.Collections.Generic;
using System.Linq;
namespace Mapster
{ {
public static class MapsterExtension public static class MapsterExtension
{ {

View File

@ -15,7 +15,7 @@ namespace AsbCloudInfrastructure.Services
/// </summary> /// </summary>
/// <typeparam name="TDto"></typeparam> /// <typeparam name="TDto"></typeparam>
/// <typeparam name="TEntity"></typeparam> /// <typeparam name="TEntity"></typeparam>
public class CrudCacheServiceBase<TDto, TEntity>: CrudServiceBase<TDto, TEntity> public class CrudCacheServiceBase<TDto, TEntity> : CrudServiceBase<TDto, TEntity>
where TDto : AsbCloudApp.Data.IId where TDto : AsbCloudApp.Data.IId
where TEntity : class, AsbCloudDb.Model.IId where TEntity : class, AsbCloudDb.Model.IId
{ {
@ -87,6 +87,15 @@ namespace AsbCloudInfrastructure.Services
return result; return result;
} }
/// <inheritdoc/>
public override async Task<int> UpdateRangeAsync(IEnumerable<TDto> dtos, CancellationToken token)
{
var result = await base.UpdateRangeAsync(dtos, token);
if (result > 0)
DropCache();
return result;
}
/// <inheritdoc/> /// <inheritdoc/>
public override async Task<int> DeleteAsync(int id, CancellationToken token) public override async Task<int> DeleteAsync(int id, CancellationToken token)
{ {

View File

@ -3,7 +3,6 @@ using AsbCloudDb.Model;
using Mapster; using Mapster;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
@ -37,7 +36,8 @@ namespace AsbCloudInfrastructure.Services
this.dbContext = dbContext; this.dbContext = dbContext;
dbSet = dbContext.Set<TEntity>(); dbSet = dbContext.Set<TEntity>();
GetQuery = () => { GetQuery = () =>
{
IQueryable<TEntity> query = dbSet; IQueryable<TEntity> query = dbSet;
foreach (var include in includes) foreach (var include in includes)
query = query.Include(include); query = query.Include(include);
@ -94,7 +94,7 @@ namespace AsbCloudInfrastructure.Services
{ {
var entity = Convert(item); var entity = Convert(item);
entity.Id = 0; entity.Id = 0;
var entry = dbSet.Add(entity); var entry = dbSet.Add(entity);
await dbContext.SaveChangesAsync(token); await dbContext.SaveChangesAsync(token);
entry.State = EntityState.Detached; entry.State = EntityState.Detached;
return entity.Id; return entity.Id;
@ -129,10 +129,10 @@ namespace AsbCloudInfrastructure.Services
.AsNoTracking() .AsNoTracking()
.FirstOrDefaultAsync(e => e.Id == item.Id, token) .FirstOrDefaultAsync(e => e.Id == item.Id, token)
.ConfigureAwait(false); .ConfigureAwait(false);
if (existingEntity is null) if (existingEntity is null)
return ICrudService<TDto>.ErrorIdNotFound; return ICrudService<TDto>.ErrorIdNotFound;
var entity = Convert(item); var entity = Convert(item);
var entry = dbSet.Update(entity); var entry = dbSet.Update(entity);
await dbContext.SaveChangesAsync(token); await dbContext.SaveChangesAsync(token);
@ -140,6 +140,29 @@ namespace AsbCloudInfrastructure.Services
return entry.Entity.Id; return entry.Entity.Id;
} }
public virtual async Task<int> UpdateRangeAsync(IEnumerable<TDto> dtos, CancellationToken token)
{
var ids = dtos.Select(d => d.Id);
var existingEntities = await dbSet
.AsNoTracking()
.Where(d => ids.Contains(d.Id))
.Select(d => d.Id)
.ToListAsync(token)
.ConfigureAwait(false);
if (ids.Count() > existingEntities.Count)
return ICrudService<TDto>.ErrorIdNotFound;
foreach (var dto in dtos)
{
var entity = Convert(dto);
var entry = dbSet.Update(entity);
}
var affected = await dbContext.SaveChangesAsync(token);
return affected;
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual Task<int> DeleteAsync(int id, CancellationToken token = default) public virtual Task<int> DeleteAsync(int id, CancellationToken token = default)
{ {

View File

@ -14,13 +14,13 @@ namespace AsbCloudInfrastructure.Services
where TDto : AsbCloudApp.Data.IId, AsbCloudApp.Data.IWellRelated where TDto : AsbCloudApp.Data.IId, AsbCloudApp.Data.IWellRelated
where TEntity : class, AsbCloudDb.Model.IId, AsbCloudDb.Model.IWellRelated where TEntity : class, AsbCloudDb.Model.IId, AsbCloudDb.Model.IWellRelated
{ {
public CrudWellRelatedServiceBase(IAsbCloudDbContext context) public CrudWellRelatedServiceBase(IAsbCloudDbContext context)
: base(context) { } : base(context) { }
public CrudWellRelatedServiceBase(IAsbCloudDbContext dbContext, ISet<string> includes) public CrudWellRelatedServiceBase(IAsbCloudDbContext dbContext, ISet<string> includes)
: base(dbContext, includes) { } : base(dbContext, includes) { }
public CrudWellRelatedServiceBase(IAsbCloudDbContext context, Func<DbSet<TEntity>, IQueryable<TEntity>> makeQuery) public CrudWellRelatedServiceBase(IAsbCloudDbContext context, Func<DbSet<TEntity>, IQueryable<TEntity>> makeQuery)
: base(context, makeQuery) { } : base(context, makeQuery) { }
public async Task<IEnumerable<TDto>> GetByIdWellAsync(int idWell, CancellationToken token) public async Task<IEnumerable<TDto>> GetByIdWellAsync(int idWell, CancellationToken token)
@ -36,9 +36,9 @@ namespace AsbCloudInfrastructure.Services
{ {
if (!idsWells.Any()) if (!idsWells.Any())
return Enumerable.Empty<TDto>(); return Enumerable.Empty<TDto>();
var entities = await GetQuery() var entities = await GetQuery()
.Where(e => idsWells.Contains( e.IdWell)) .Where(e => idsWells.Contains(e.IdWell))
.ToListAsync(token); .ToListAsync(token);
var dtos = entities.Select(Convert).ToList(); var dtos = entities.Select(Convert).ToList();
return dtos; return dtos;

View File

@ -1,14 +1,14 @@
using System; using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Mapster;
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using System.Collections.Generic;
namespace AsbCloudInfrastructure.Services.DailyReport namespace AsbCloudInfrastructure.Services.DailyReport
{ {
@ -26,7 +26,7 @@ namespace AsbCloudInfrastructure.Services.DailyReport
} }
public async Task<IEnumerable<DailyReportDto>> GetListAsync(int idWell, DateTime? begin, DateTime? end, CancellationToken token) public async Task<IEnumerable<DailyReportDto>> GetListAsync(int idWell, DateTime? begin, DateTime? end, CancellationToken token)
{ {
var query = db.DailyReports.Where(r => r.IdWell == idWell); var query = db.DailyReports.Where(r => r.IdWell == idWell);
var offsetHours = wellService.GetTimezone(idWell).Hours; var offsetHours = wellService.GetTimezone(idWell).Hours;
@ -41,7 +41,7 @@ namespace AsbCloudInfrastructure.Services.DailyReport
var endOffset = ((DateTime)end).ToUtcDateTimeOffset(offsetHours); var endOffset = ((DateTime)end).ToUtcDateTimeOffset(offsetHours);
query = query.Where(d => d.StartDate <= endOffset); query = query.Where(d => d.StartDate <= endOffset);
} }
var entities = await query var entities = await query
.ToListAsync(token); .ToListAsync(token);
@ -127,7 +127,7 @@ namespace AsbCloudInfrastructure.Services.DailyReport
{ {
ReportDate = date, ReportDate = date,
WellName = well.Caption, WellName = well.Caption,
ClusterName = well.Cluster, ClusterName = well.Cluster,
}; };
DailyReportDto result = dto; DailyReportDto result = dto;
return result; return result;
@ -143,7 +143,7 @@ namespace AsbCloudInfrastructure.Services.DailyReport
private static DailyReportInfo Convert(DailyReportDto dto, double offsetHours) private static DailyReportInfo Convert(DailyReportDto dto, double offsetHours)
{ {
var entity = dto.Adapt<DailyReportInfo>(); var entity = dto.Adapt<DailyReportInfo>();
entity.ReportDate = dto.ReportDate entity.ReportDate = dto.ReportDate
.ToUtcDateTimeOffset(offsetHours) .ToUtcDateTimeOffset(offsetHours)
.Date; .Date;

View File

@ -13,7 +13,7 @@ using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services.DetectOperations namespace AsbCloudInfrastructure.Services.DetectOperations
{ {
public class DetectedOperationService: IDetectedOperationService public class DetectedOperationService : IDetectedOperationService
{ {
public const int IdOperationRotor = 1; public const int IdOperationRotor = 1;
public const int IdOperationSlide = 3; public const int IdOperationSlide = 3;
@ -24,7 +24,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations
private readonly IOperationValueService operationValueService; private readonly IOperationValueService operationValueService;
private readonly IScheduleService scheduleService; private readonly IScheduleService scheduleService;
public DetectedOperationService(IAsbCloudDbContext db, IWellService wellService, public DetectedOperationService(IAsbCloudDbContext db, IWellService wellService,
IOperationValueService operationValueService, IScheduleService scheduleService) IOperationValueService operationValueService, IScheduleService scheduleService)
{ {
this.db = db; this.db = db;
@ -43,7 +43,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations
.AsNoTracking(); .AsNoTracking();
var data = await query.ToListAsync(token); var data = await query.ToListAsync(token);
var operationValues = await operationValueService.GetByIdWellAsync(idWell, token); var operationValues = await operationValueService.GetByIdWellAsync(idWell, token);
var schedules = await scheduleService.GetByIdWellAsync(idWell, token); var schedules = await scheduleService.GetByIdWellAsync(idWell, token);
var dtos = data.Select(o => Convert(o, well, operationValues, schedules)); var dtos = data.Select(o => Convert(o, well, operationValues, schedules));
@ -84,7 +84,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations
if (well?.IdTelemetry is null || well.Timezone is null) if (well?.IdTelemetry is null || well.Timezone is null)
return 0; return 0;
var query = BuildQuery(well, request); var query = BuildQuery(well, request);
db.DetectedOperations.RemoveRange(query); db.DetectedOperations.RemoveRange(query);
return await db.SaveChangesAsync(token); return await db.SaveChangesAsync(token);
} }
@ -170,10 +170,10 @@ namespace AsbCloudInfrastructure.Services.DetectOperations
&& e.DepthStart <= dto.DepthStart); && e.DepthStart <= dto.DepthStart);
var timeStart = new TimeDto(dateStart); var timeStart = new TimeDto(dateStart);
var driller = schedules.FirstOrDefault(s => var driller = schedules.FirstOrDefault(s =>
s.DrillStart <= dateStart && s.DrillStart <= dateStart &&
s.DrillEnd > dateStart && ( s.DrillEnd > dateStart && (
s.ShiftStart > s.ShiftEnd s.ShiftStart > s.ShiftEnd
) ^ (s.ShiftStart <= timeStart && ) ^ (s.ShiftStart <= timeStart &&
s.ShiftEnd > timeStart s.ShiftEnd > timeStart
)) ))
@ -191,6 +191,6 @@ namespace AsbCloudInfrastructure.Services.DetectOperations
return result; return result;
} }
} }
} }

View File

@ -16,11 +16,11 @@ namespace AsbCloudInfrastructure.Services.DetectOperations.Detectors
{ {
var firstItem = telemetry[position]; var firstItem = telemetry[position];
var delta = firstItem.WellDepth - firstItem.BitDepth; var delta = firstItem.WellDepth - firstItem.BitDepth;
if (delta is not null && if (delta is not null &&
System.Math.Abs((float)delta) > 1d) System.Math.Abs((float)delta) > 1d)
return false; return false;
var fragment = telemetry[position .. (position + FragmentLength)]; var fragment = telemetry[position..(position + FragmentLength)];
const double minRop = 5; //м/час const double minRop = 5; //м/час
const double minRotorSpeed = 5; //об/мин const double minRotorSpeed = 5; //об/мин
@ -31,7 +31,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations.Detectors
return false; return false;
var lineWellDepth = new InterpolationLine(fragment.Select(d => (d.WellDepth ?? 0d, d.DateTime.Ticks / ticksPerHour))); var lineWellDepth = new InterpolationLine(fragment.Select(d => (d.WellDepth ?? 0d, d.DateTime.Ticks / ticksPerHour)));
if(!lineWellDepth.IsYIncreases(minRop)) if (!lineWellDepth.IsYIncreases(minRop))
return false; return false;
var lineRotorSpeed = new InterpolationLine(fragment.Select(d => (d.RotorSpeed ?? 0d, d.DateTime.Ticks / ticksPerHour))); var lineRotorSpeed = new InterpolationLine(fragment.Select(d => (d.RotorSpeed ?? 0d, d.DateTime.Ticks / ticksPerHour)));

View File

@ -19,7 +19,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations.Detectors
System.Math.Abs((float)delta) > 1d) System.Math.Abs((float)delta) > 1d)
return false; return false;
var fragment = telemetry[position .. (position + FragmentLength)]; var fragment = telemetry[position..(position + FragmentLength)];
const double minRop = 5; //м/час const double minRop = 5; //м/час
const double minRotorSpeed = 5; //об/мин const double minRotorSpeed = 5; //об/мин
@ -30,7 +30,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations.Detectors
return false; return false;
var lineWellDepth = new InterpolationLine(fragment.Select(d => (d.WellDepth ?? 0d, d.DateTime.Ticks / ticksPerHour))); var lineWellDepth = new InterpolationLine(fragment.Select(d => (d.WellDepth ?? 0d, d.DateTime.Ticks / ticksPerHour)));
if(!lineWellDepth.IsYIncreases(minRop)) if (!lineWellDepth.IsYIncreases(minRop))
return false; return false;
var lineRotorSpeed = new InterpolationLine(fragment.Select(d => (d.RotorSpeed ?? 0d, d.DateTime.Ticks / ticksPerHour))); var lineRotorSpeed = new InterpolationLine(fragment.Select(d => (d.RotorSpeed ?? 0d, d.DateTime.Ticks / ticksPerHour)));

View File

@ -5,7 +5,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations.Detectors
#nullable enable #nullable enable
class DetectorSlipsTime : DetectorAbstract class DetectorSlipsTime : DetectorAbstract
{ {
public DetectorSlipsTime() :base(14) {} public DetectorSlipsTime() : base(14) { }
public double HookWeightSP { get; set; } = 20; public double HookWeightSP { get; set; } = 20;
public double PressureSP { get; set; } = 15; public double PressureSP { get; set; } = 15;
public double PosisionSP { get; set; } = 8; public double PosisionSP { get; set; } = 8;
@ -15,7 +15,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations.Detectors
{ {
var item = telemetry[position]; var item = telemetry[position];
var result = var result =
item.HookWeight < HookWeightSP && item.HookWeight < HookWeightSP &&
item.Pressure < PressureSP && item.Pressure < PressureSP &&
item.BlockPosition < PosisionSP && item.BlockPosition < PosisionSP &&

View File

@ -4,10 +4,10 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Diagnostics;
namespace AsbCloudInfrastructure.Services.DetectOperations namespace AsbCloudInfrastructure.Services.DetectOperations
{ {
@ -92,20 +92,20 @@ namespace AsbCloudInfrastructure.Services.DetectOperations
.GroupJoin(lastDetectedDates, .GroupJoin(lastDetectedDates,
t => t, t => t,
o => o.IdTelemetry, o => o.IdTelemetry,
(outer, inner) => new (outer, inner) => new
{ {
IdTelemetry = outer, IdTelemetry = outer,
LastDate = inner.SingleOrDefault()?.LastDate , LastDate = inner.SingleOrDefault()?.LastDate,
}); });
var affected = 0; var affected = 0;
foreach (var item in JounedlastDetectedDates) foreach (var item in JounedlastDetectedDates)
{ {
var newOperations = await DetectOperationsAsync(item.IdTelemetry, item.LastDate??DateTimeOffset.MinValue, db, token); var newOperations = await DetectOperationsAsync(item.IdTelemetry, item.LastDate ?? DateTimeOffset.MinValue, db, token);
if (newOperations.Any()) if (newOperations.Any())
{ {
db.DetectedOperations.AddRange(newOperations); db.DetectedOperations.AddRange(newOperations);
affected += await db.SaveChangesAsync(token); affected += await db.SaveChangesAsync(token);
} }
} }
return affected; return affected;
} }
@ -115,7 +115,8 @@ namespace AsbCloudInfrastructure.Services.DetectOperations
var query = db.TelemetryDataSaub var query = db.TelemetryDataSaub
.AsNoTracking() .AsNoTracking()
.Where(d => d.IdTelemetry == idTelemetry) .Where(d => d.IdTelemetry == idTelemetry)
.Select(d => new DetectableTelemetry{ .Select(d => new DetectableTelemetry
{
DateTime = d.DateTime, DateTime = d.DateTime,
IdUser = d.IdUser, IdUser = d.IdUser,
WellDepth = d.WellDepth, WellDepth = d.WellDepth,
@ -135,7 +136,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations
var dbTime_ = 0d; var dbTime_ = 0d;
var sw_ = new Stopwatch(); var sw_ = new Stopwatch();
var otherTime_ = 0d; var otherTime_ = 0d;
while (true) while (true)
{ {
sw_.Restart(); sw_.Restart();
@ -148,7 +149,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations
dbTime_ += sw_.ElapsedMilliseconds; dbTime_ += sw_.ElapsedMilliseconds;
dbRequests_++; dbRequests_++;
sw_.Restart(); sw_.Restart();
if (data.Length < minFragmentLength) if (data.Length < minFragmentLength)
break; break;
@ -162,7 +163,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations
foreach (var detector in detectors) foreach (var detector in detectors)
{ {
if(data.Length < skip + detector.StepLength + detector.FragmentLength) if (data.Length < skip + detector.StepLength + detector.FragmentLength)
continue; continue;
var detectedOperation = detector.DetectOrDefault(data, ref skip); var detectedOperation = detector.DetectOrDefault(data, ref skip);
@ -183,15 +184,15 @@ namespace AsbCloudInfrastructure.Services.DetectOperations
sw_.Stop(); sw_.Stop();
otherTime_ += sw_.ElapsedMilliseconds; otherTime_ += sw_.ElapsedMilliseconds;
if (!isDetected) if (!isDetected)
{ {
if (data.Length < take) if (data.Length < take)
break; break;
var lastPartDate = data.Last().DateTime; var lastPartDate = data.Last().DateTime;
startDate = startDate + (0.75 * (lastPartDate - startDate)); startDate = startDate + (0.75 * (lastPartDate - startDate));
} }
} }
return detectedOperations; return detectedOperations;

View File

@ -1,11 +1,6 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services namespace AsbCloudInfrastructure.Services
{ {

View File

@ -55,7 +55,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
IConfiguration configuration, IConfiguration configuration,
IBackgroundWorkerService backgroundWorker, IBackgroundWorkerService backgroundWorker,
IEmailService emailService) IEmailService emailService)
{ {
this.context = context; this.context = context;
this.fileService = fileService; this.fileService = fileService;
this.userService = userService; this.userService = userService;
@ -181,7 +181,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
await RemoveDrillingProgramAsync(part.IdWell, token); await RemoveDrillingProgramAsync(part.IdWell, token);
await NotifyApproversAsync(part, result.Id, fileFullName, token); await NotifyApproversAsync(part, result.Id, fileFullName, token);
return result.Id; return result.Id;
} }
@ -229,7 +229,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
throw new ArgumentInvalidException($"User id == {idUser} does not exist", nameof(idUser)); throw new ArgumentInvalidException($"User id == {idUser} does not exist", nameof(idUser));
var part = await context.DrillingProgramParts var part = await context.DrillingProgramParts
.Include(p=>p.FileCategory) .Include(p => p.FileCategory)
.FirstOrDefaultAsync(p => p.IdWell == idWell && p.IdFileCategory == idFileCategory, token); .FirstOrDefaultAsync(p => p.IdWell == idWell && p.IdFileCategory == idFileCategory, token);
if (part is null) if (part is null)
@ -367,7 +367,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
private async Task NotifyPublisherOnRejectAsync(FileMarkDto fileMark, CancellationToken token) private async Task NotifyPublisherOnRejectAsync(FileMarkDto fileMark, CancellationToken token)
{ {
var file = await fileService.GetInfoAsync(fileMark.IdFile, token); var file = await fileService.GetInfoAsync(fileMark.IdFile, token);
var well = await wellService.GetAsync(file.IdWell, token); var well = await wellService.GetAsync(file.IdWell, token);
var user = file.Author; var user = file.Author;
var factory = new MailBodyFactory(configuration); var factory = new MailBodyFactory(configuration);

View File

@ -1,8 +1,7 @@
using AsbCloudApp.Data.SAUB; using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache; using Microsoft.EntityFrameworkCore;
using Mapster;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -11,7 +10,7 @@ using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services.SAUB namespace AsbCloudInfrastructure.Services.SAUB
{ {
public class SetpointsService : ISetpointsService, IConverter<SetpointsRequestDto, SetpointsRequest> public class SetpointsService : ISetpointsService
{ {
// ## Инфо от АПГ от 26.11.2021, дополнения ШОВ от 26.11.2021 // ## Инфо от АПГ от 26.11.2021, дополнения ШОВ от 26.11.2021
private static readonly Dictionary<string, SetpointInfoDto> SetpointInfos = new() private static readonly Dictionary<string, SetpointInfoDto> SetpointInfos = new()
@ -23,38 +22,33 @@ namespace AsbCloudInfrastructure.Services.SAUB
{ "speedRotorSp", new SetpointInfoDto { Name = "speedRotorSp", DisplayName = "Скорость бурения в роторе, м/ч" } }, { "speedRotorSp", new SetpointInfoDto { Name = "speedRotorSp", DisplayName = "Скорость бурения в роторе, м/ч" } },
{ "speedSlideSp", new SetpointInfoDto { Name = "speedSlideSp", DisplayName = "Скорость бурения в слайде, м/ч" } }, { "speedSlideSp", new SetpointInfoDto { Name = "speedSlideSp", DisplayName = "Скорость бурения в слайде, м/ч" } },
{ "speedDevelopSp", new SetpointInfoDto { Name = "speedDevelopSp", DisplayName = "Скорость проработки, м/ч" } }, { "speedDevelopSp", new SetpointInfoDto { Name = "speedDevelopSp", DisplayName = "Скорость проработки, м/ч" } },
{ "torque_pid_out_limit", new SetpointInfoDto { Name = "torque_pid_out_limit", DisplayName = "Торк мастер. Допустимый процент отклонения от заданой скорости вращения" } }, // Такая же что и прямой { "torque_pid_out_limit", new SetpointInfoDto { Name = "torque_pid_out_limit", DisplayName = "Торк мастер. Допустимый процент отклонения от заданной скорости вращения" } }, // Такая же что и прямой
//{ "", new SetpointInfoDto { Name = "", DisplayName = "Обороты ВСП, об/мин" } }, // Оно в ПЛК спинмастера, пока сделать нельзя, позднее можно. //{ "", new SetpointInfoDto { Name = "", DisplayName = "Обороты ВСП, об/мин" } }, // Оно в ПЛК спинмастера, пока сделать нельзя, позднее можно.
//{ "", new SetpointInfoDto { Name = "", DisplayName = "Расход промывочной жидкости, л/с" } }, // Нет в контроллере //{ "", new SetpointInfoDto { Name = "", DisplayName = "Расход промывочной жидкости, л/с" } }, // Нет в контроллере
}; };
private readonly IAsbCloudDbContext db;
private readonly CacheTable<SetpointsRequest> cacheSetpoints;
private readonly ITelemetryService telemetryService; private readonly ITelemetryService telemetryService;
private readonly CrudCacheServiceBase<SetpointsRequestDto, SetpointsRequest> setpointsRepository;
public SetpointsService(IAsbCloudDbContext db, CacheDb cacheDb, ITelemetryService telemetryService) public SetpointsService(IAsbCloudDbContext db, ITelemetryService telemetryService)
{ {
cacheSetpoints = cacheDb.GetCachedTable<SetpointsRequest>( setpointsRepository = new CrudCacheServiceBase<SetpointsRequestDto, SetpointsRequest>(db, q => q.Include(s => s.Author).Include(s => s.Well));
(AsbCloudDbContext)db, this.db = db;
nameof(SetpointsRequest.Author),
nameof(SetpointsRequest.Well));
this.telemetryService = telemetryService; this.telemetryService = telemetryService;
} }
public async Task<int> InsertAsync(SetpointsRequestDto setpoints, CancellationToken token) public async Task<int> InsertAsync(SetpointsRequestDto setpointsRequest, CancellationToken token)
{ {
setpoints.IdState = 1; setpointsRequest.IdState = 1;
setpoints.UploadDate = DateTime.UtcNow; setpointsRequest.UploadDate = DateTime.UtcNow;
var dto = Convert(setpoints); var result = await setpointsRepository.InsertAsync(setpointsRequest, token);
var inserted = await cacheSetpoints.InsertAsync(dto, token) return result;
.ConfigureAwait(false);
return inserted?.Id ?? 0;
} }
public async Task<IEnumerable<SetpointsRequestDto>> GetAsync(int idWell, CancellationToken token) public async Task<IEnumerable<SetpointsRequestDto>> GetAsync(int idWell, CancellationToken token)
{ {
var entities = await cacheSetpoints.WhereAsync(s => s.IdWell == idWell, token) var all = await setpointsRepository.GetAllAsync(token);
.ConfigureAwait(false); var dtos = all.Where(s => s.IdWell == idWell);
var dtos = entities.Select(s => Convert(s));
return dtos; return dtos;
} }
@ -64,79 +58,45 @@ namespace AsbCloudInfrastructure.Services.SAUB
if (idWell < 0) if (idWell < 0)
return null; return null;
var all = await setpointsRepository.GetAllAsync(token);
var filtered = all.Where(s =>
s.IdWell == idWell &&
s.IdState == 1 &&
s.UploadDate.AddSeconds(s.ObsolescenceSec) > DateTime.Now);
var entities = (await cacheSetpoints.WhereAsync(s => if (!filtered.Any())
s.IdWell == idWell && s.IdState == 1 && s.UploadDate.AddSeconds(s.ObsolescenceSec) > DateTime.Now,
token)
.ConfigureAwait(false))
.ToList();// без .ToList() работает не правильно.
if (!entities.Any())
return null; return null;
foreach (var entity in entities) foreach (var entity in filtered)
entity.IdState = 2; entity.IdState = 2;
await cacheSetpoints.UpsertAsync(entities, token) await setpointsRepository.UpdateRangeAsync(filtered, token);
.ConfigureAwait(false);
var dtos = entities.Select(Convert); return filtered;
return dtos;
} }
public async Task<int> UpdateStateAsync(string uid, int id, SetpointsRequestDto setpointsRequestDto, CancellationToken token) public async Task<int> UpdateStateAsync(int id, SetpointsRequestDto setpointsRequestDto, CancellationToken token)
{ {
if (setpointsRequestDto.IdState != 3 && setpointsRequestDto.IdState != 4) if (setpointsRequestDto.IdState != 3 && setpointsRequestDto.IdState != 4)
throw new ArgumentOutOfRangeException(nameof(setpointsRequestDto), $"{nameof(setpointsRequestDto.IdState)} = {setpointsRequestDto.IdState}. Mast be 3 or 4."); throw new ArgumentOutOfRangeException(nameof(setpointsRequestDto), $"{nameof(setpointsRequestDto.IdState)} = {setpointsRequestDto.IdState}. Mast be 3 or 4.");
var idWell = telemetryService.GetIdWellByTelemetryUid(uid) ?? -1; var entity = await setpointsRepository.GetAsync(id, token);
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);
if (entity is null) if (entity is null)
return 0; return 0;
entity.IdState = setpointsRequestDto.IdState; entity.IdState = setpointsRequestDto.IdState;
await cacheSetpoints.UpsertAsync(entity, token) var affected = await setpointsRepository.UpdateAsync(entity, token);
.ConfigureAwait(false); return affected;
return 1;
} }
public async Task<int> TryDelete(int idWell, int id, CancellationToken token) public async Task<int> TryDelete(int id, CancellationToken token)
{ {
bool Predicate(SetpointsRequest s) => s.Id == id && s.IdWell == idWell && s.IdState == 1; var affected = await setpointsRepository.DeleteAsync(id, token);
var isExist = await cacheSetpoints.ContainsAsync(Predicate, token) return affected;
.ConfigureAwait(false);
if (!isExist)
return 0;
await cacheSetpoints.RemoveAsync(Predicate, token)
.ConfigureAwait(false);
return 1;
} }
public SetpointsRequest Convert(SetpointsRequestDto src) public IEnumerable<SetpointInfoDto> GetSetpointsNames()
{ => SetpointInfos.Values;
var entity = src.Adapt<SetpointsRequest>();
return entity;
}
public SetpointsRequestDto Convert(SetpointsRequest src)
{
var dto = src.Adapt<SetpointsRequestDto>();
return dto;
}
public IEnumerable<SetpointInfoDto> GetSetpointsNames(int idWell)
=> SetpointInfos.Values;
} }
} }

View File

@ -4,7 +4,6 @@ using AsbCloudApp.Services;
using AsbCloudDb; using AsbCloudDb;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.EfCache; using AsbCloudInfrastructure.EfCache;
using AsbCloudInfrastructure.Services.Cache;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;

View File

@ -4,7 +4,6 @@ using AsbCloudDb.Model;
using Mapster; using Mapster;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -16,7 +15,7 @@ namespace AsbCloudInfrastructure.Services
{ {
private readonly IWellService wellService; private readonly IWellService wellService;
public ScheduleService(IAsbCloudDbContext context, IWellService wellService) public ScheduleService(IAsbCloudDbContext context, IWellService wellService)
: base(context, dbSet => dbSet.Include(s => s.Driller)) : base(context, dbSet => dbSet.Include(s => s.Driller))
{ {
this.wellService = wellService; this.wellService = wellService;
@ -28,7 +27,7 @@ namespace AsbCloudInfrastructure.Services
var date = workTime.ToUtcDateTimeOffset(hoursOffset); var date = workTime.ToUtcDateTimeOffset(hoursOffset);
var entities = await GetQuery() var entities = await GetQuery()
.Where(s => s.IdWell==idWell .Where(s => s.IdWell == idWell
&& s.DrillStart <= date && s.DrillStart <= date
&& s.DrillEnd >= date) && s.DrillEnd >= date)
.ToListAsync(token); .ToListAsync(token);
@ -39,7 +38,7 @@ namespace AsbCloudInfrastructure.Services
var remoteDate = date.ToRemoteDateTime(hoursOffset); var remoteDate = date.ToRemoteDateTime(hoursOffset);
var time = new TimeOnly(remoteDate.Hour, remoteDate.Minute, remoteDate.Second); var time = new TimeOnly(remoteDate.Hour, remoteDate.Minute, remoteDate.Second);
var entity = entities.FirstOrDefault(s => var entity = entities.FirstOrDefault(s =>
(s.ShiftStart > s.ShiftEnd) ^ (s.ShiftStart > s.ShiftEnd) ^
(time >= s.ShiftStart && time < s.ShiftEnd) (time >= s.ShiftStart && time < s.ShiftEnd)
); );

View File

@ -52,7 +52,7 @@ namespace AsbCloudInfrastructure.Services.WellOperationService
public DateTimeOffset? FirstOperationDate(int idWell) public DateTimeOffset? FirstOperationDate(int idWell)
{ {
if(firstOperationsCache is null) if (firstOperationsCache is null)
{ {
var query = db.WellOperations var query = db.WellOperations
.GroupBy(o => o.IdWell) .GroupBy(o => o.IdWell)

View File

@ -2,8 +2,8 @@
using AsbCloudApp.Exceptions; using AsbCloudApp.Exceptions;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache;
using AsbCloudInfrastructure.EfCache; using AsbCloudInfrastructure.EfCache;
using AsbCloudInfrastructure.Services.Cache;
using Mapster; using Mapster;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System; using System;
@ -26,7 +26,7 @@ namespace AsbCloudInfrastructure.Services
public ITelemetryService TelemetryService => telemetryService; public ITelemetryService TelemetryService => telemetryService;
private static IQueryable<Well> MakeQueryWell(DbSet<Well> dbSet) private static IQueryable<Well> MakeQueryWell(DbSet<Well> dbSet)
=> dbSet => dbSet
.Include(w => w.Cluster) .Include(w => w.Cluster)
.ThenInclude(c => c.Deposit) .ThenInclude(c => c.Deposit)
@ -63,7 +63,7 @@ namespace AsbCloudInfrastructure.Services
public DateTimeOffset GetLastTelemetryDate(int idWell) public DateTimeOffset GetLastTelemetryDate(int idWell)
{ {
var well = Get(idWell); var well = Get(idWell);
if (well?.IdTelemetry is null) if (well?.IdTelemetry is null)
return DateTimeOffset.MinValue; return DateTimeOffset.MinValue;
@ -73,7 +73,7 @@ namespace AsbCloudInfrastructure.Services
public async Task<IEnumerable<WellDto>> GetWellsByCompanyAsync(int idCompany, CancellationToken token) public async Task<IEnumerable<WellDto>> GetWellsByCompanyAsync(int idCompany, CancellationToken token)
{ {
var relationsCache = await GetCacheRelationCompanyWellAsync(token); var relationsCache = await GetCacheRelationCompanyWellAsync(token);
var wellsIds = relationsCache var wellsIds = relationsCache
.Where(r => r.IdCompany == idCompany) .Where(r => r.IdCompany == idCompany)
@ -81,8 +81,8 @@ namespace AsbCloudInfrastructure.Services
var wellsDtos = (await GetCacheAsync(token)) var wellsDtos = (await GetCacheAsync(token))
.Where(kv => wellsIds.Contains(kv.Key)) .Where(kv => wellsIds.Contains(kv.Key))
.Select(kv =>kv.Value); .Select(kv => kv.Value);
return wellsDtos.ToList(); return wellsDtos.ToList();
} }
@ -227,7 +227,7 @@ namespace AsbCloudInfrastructure.Services
dto.WellType = entity.WellType?.Caption; dto.WellType = entity.WellType?.Caption;
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.GetLastTelemetryDate((int)entity.IdTelemetry); dto.LastTelemetryDate = telemetryService.GetLastTelemetryDate((int)entity.IdTelemetry);
dto.Companies = entity.RelationCompaniesWells dto.Companies = entity.RelationCompaniesWells
.Select(r => Convert(r.Company)) .Select(r => Convert(r.Company))
@ -315,7 +315,7 @@ namespace AsbCloudInfrastructure.Services
if (well.IdCluster is null) if (well.IdCluster is null)
throw new Exception($"Can't find coordinates of well {well.Caption} id: {well.Id}"); throw new Exception($"Can't find coordinates of well {well.Caption} id: {well.Id}");
var cluster = well.Cluster; var cluster = well.Cluster;
if (cluster.Latitude is not null & cluster.Longitude is not null) if (cluster.Latitude is not null & cluster.Longitude is not null)

View File

@ -7,8 +7,8 @@ namespace AsbCloudInfrastructure.Validators
{ {
public TimeDtoValidator() public TimeDtoValidator()
{ {
RuleFor(x=>x.Hour) RuleFor(x => x.Hour)
.InclusiveBetween(0,23) .InclusiveBetween(0, 23)
.WithMessage("hour should be in [0; 23]"); .WithMessage("hour should be in [0; 23]");
RuleFor(x => x.Minute) RuleFor(x => x.Minute)

View File

@ -1,17 +1,4 @@
using AsbCloudApp.Data; namespace AsbCloudWebApi.Tests.ControllersTests
using AsbCloudApp.Services;
using AsbCloudWebApi.Controllers.SAUB;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Moq;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace AsbCloudWebApi.Tests.ControllersTests
{ {
//public class AnalyticsControllerTests //public class AnalyticsControllerTests
//{ //{

View File

@ -1,11 +1,6 @@
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Tests.ControllersTests namespace AsbCloudWebApi.Tests.ControllersTests
{ {

View File

@ -1,17 +1,8 @@
using AsbCloudApp.Data.SAUB; using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudWebApi.Controllers;
using AsbCloudWebApi.SignalR; using AsbCloudWebApi.SignalR;
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Moq; using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace AsbCloudWebApi.Tests.ControllersTests namespace AsbCloudWebApi.Tests.ControllersTests
{ {

View File

@ -1,11 +1,11 @@
using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services; using AsbCloudInfrastructure.Services;
using Moq;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Moq;
using Xunit; using Xunit;
using AsbCloudApp.Services;
namespace AsbCloudWebApi.Tests.ServicesTests; namespace AsbCloudWebApi.Tests.ServicesTests;
@ -21,7 +21,7 @@ public class ClusterServiceTest
new Deposit { Id = 3, Caption = "Test deposit 3" }, new Deposit { Id = 3, Caption = "Test deposit 3" },
new Deposit { Id = 4, Caption = "Test deposit 4" } new Deposit { Id = 4, Caption = "Test deposit 4" }
}; };
private readonly List<Cluster> clusters = new() private readonly List<Cluster> clusters = new()
{ {
new Cluster { Id = 1, Caption = "Test cluster 1", IdDeposit = 1, Timezone = new SimpleTimezone()}, new Cluster { Id = 1, Caption = "Test cluster 1", IdDeposit = 1, Timezone = new SimpleTimezone()},
@ -29,7 +29,7 @@ public class ClusterServiceTest
new Cluster { Id = 3, Caption = "Test cluster 3", IdDeposit = 2, Timezone = new SimpleTimezone() }, new Cluster { Id = 3, Caption = "Test cluster 3", IdDeposit = 2, Timezone = new SimpleTimezone() },
new Cluster { Id = 4, Caption = "Test cluster 4", IdDeposit = 2, Timezone = new SimpleTimezone() } new Cluster { Id = 4, Caption = "Test cluster 4", IdDeposit = 2, Timezone = new SimpleTimezone() }
}; };
private readonly List<Well> wells = new() private readonly List<Well> wells = new()
{ {
new Well { Id = 1, Caption = "Test well 1", IdCluster = 1 }, new Well { Id = 1, Caption = "Test well 1", IdCluster = 1 },
@ -37,25 +37,25 @@ public class ClusterServiceTest
new Well { Id = 3, Caption = "Test well 3", IdCluster = 1 }, new Well { Id = 3, Caption = "Test well 3", IdCluster = 1 },
new Well { Id = 4, Caption = "Test well 4", IdCluster = 2 } new Well { Id = 4, Caption = "Test well 4", IdCluster = 2 }
}; };
private readonly List<CompanyType> companiesTypes = new() private readonly List<CompanyType> companiesTypes = new()
{ {
new CompanyType { Id = 1, Caption = "test company type"} new CompanyType { Id = 1, Caption = "test company type"}
}; };
private readonly List<Company> companies = new() private readonly List<Company> companies = new()
{ {
new Company { Id = 1, Caption = "Test company 1", IdCompanyType = 1}, new Company { Id = 1, Caption = "Test company 1", IdCompanyType = 1},
new Company { Id = 2, Caption = "Test company 2", IdCompanyType = 1} new Company { Id = 2, Caption = "Test company 2", IdCompanyType = 1}
}; };
private readonly List<RelationCompanyWell> relations = new() private readonly List<RelationCompanyWell> relations = new()
{ {
new RelationCompanyWell { IdCompany = 1, IdWell = 1 }, new RelationCompanyWell { IdCompany = 1, IdWell = 1 },
new RelationCompanyWell { IdCompany = 1, IdWell = 2 }, new RelationCompanyWell { IdCompany = 1, IdWell = 2 },
new RelationCompanyWell { IdCompany = 2, IdWell = 2 } new RelationCompanyWell { IdCompany = 2, IdWell = 2 }
}; };
private readonly List<WellSectionType> wellSectionTypes = new() private readonly List<WellSectionType> wellSectionTypes = new()
{ {
new WellSectionType { Id = 1, Caption = "Test well section type 1" } new WellSectionType { Id = 1, Caption = "Test well section type 1" }
@ -66,7 +66,7 @@ public class ClusterServiceTest
new DrillParams {Id = 1, IdWell = 1, IdWellSectionType = 1}, new DrillParams {Id = 1, IdWell = 1, IdWellSectionType = 1},
new DrillParams {Id = 2, IdWell = 2, IdWellSectionType = 1} new DrillParams {Id = 2, IdWell = 2, IdWellSectionType = 1}
}; };
public ClusterServiceTest() public ClusterServiceTest()
{ {
context = TestHelpter.MakeTestContext(); context = TestHelpter.MakeTestContext();
@ -79,7 +79,7 @@ public class ClusterServiceTest
context.RelationCompaniesWells.RemoveRange(context.RelationCompaniesWells); context.RelationCompaniesWells.RemoveRange(context.RelationCompaniesWells);
context.WellSectionTypes.RemoveRange(context.WellSectionTypes); context.WellSectionTypes.RemoveRange(context.WellSectionTypes);
context.DrillParams.RemoveRange(context.DrillParams); context.DrillParams.RemoveRange(context.DrillParams);
if(context.ChangeTracker.HasChanges()) if (context.ChangeTracker.HasChanges())
context.SaveChanges(); context.SaveChanges();
context.Deposits.AddRange(deposits); context.Deposits.AddRange(deposits);
context.Clusters.AddRange(clusters); context.Clusters.AddRange(clusters);
@ -91,7 +91,7 @@ public class ClusterServiceTest
context.DrillParams.AddRange(drillParams); context.DrillParams.AddRange(drillParams);
context.SaveChanges(); context.SaveChanges();
} }
~ClusterServiceTest() ~ClusterServiceTest()
{ {
context.Deposits.RemoveRange(context.Deposits); context.Deposits.RemoveRange(context.Deposits);
@ -105,16 +105,16 @@ public class ClusterServiceTest
[Fact] [Fact]
public async Task GetDepositsAsync_returns_one_deposit() public async Task GetDepositsAsync_returns_one_deposit()
{ {
var service = new ClusterService(context, wellService.Object); var service = new ClusterService(context, wellService.Object);
var dtos = await service.GetDepositsAsync(1); var dtos = await service.GetDepositsAsync(1);
Assert.Single(dtos); Assert.Single(dtos);
} }
[Fact] [Fact]
public async Task GetDepositsAsync_returns_one_deposit_with_two_clusters() public async Task GetDepositsAsync_returns_one_deposit_with_two_clusters()
{ {
var service = new ClusterService(context, wellService.Object); var service = new ClusterService(context, wellService.Object);
var dtos = await service.GetDepositsAsync(1); var dtos = await service.GetDepositsAsync(1);
@ -122,57 +122,57 @@ public class ClusterServiceTest
} }
[Fact] [Fact]
public async Task GetDrillParamsAsync_returns_depositDtos() public async Task GetDrillParamsAsync_returns_depositDtos()
{ {
var service = new ClusterService(context, wellService.Object); var service = new ClusterService(context, wellService.Object);
var dtos = await service.GetDepositsDrillParamsAsync(1); var dtos = await service.GetDepositsDrillParamsAsync(1);
Assert.True(dtos.Any()); Assert.True(dtos.Any());
} }
[Fact] [Fact]
public async Task GetDrillParamsAsync_returns_one_deposit() public async Task GetDrillParamsAsync_returns_one_deposit()
{ {
var service = new ClusterService(context, wellService.Object); var service = new ClusterService(context, wellService.Object);
var dtos = await service.GetDepositsDrillParamsAsync(1); var dtos = await service.GetDepositsDrillParamsAsync(1);
Assert.Single(dtos); Assert.Single(dtos);
} }
[Fact] [Fact]
public async Task GetDrillParamsAsync_returns_one_deposit_with_two_clusters() public async Task GetDrillParamsAsync_returns_one_deposit_with_two_clusters()
{ {
var service = new ClusterService(context, wellService.Object); var service = new ClusterService(context, wellService.Object);
var dtos = await service.GetDepositsDrillParamsAsync(1); var dtos = await service.GetDepositsDrillParamsAsync(1);
Assert.Equal(2, dtos.FirstOrDefault()?.Clusters.Count()); Assert.Equal(2, dtos.FirstOrDefault()?.Clusters.Count());
} }
[Fact] [Fact]
public async Task GetClustersAsync_returns_two_dtos() public async Task GetClustersAsync_returns_two_dtos()
{ {
var service = new ClusterService(context, wellService.Object); var service = new ClusterService(context, wellService.Object);
var dtos = await service.GetClustersAsync(1); var dtos = await service.GetClustersAsync(1);
Assert.Equal(2, dtos.Count()); Assert.Equal(2, dtos.Count());
} }
[Fact] [Fact]
public async Task GetClustersAsync_with_deposit_returns_two_clusters() public async Task GetClustersAsync_with_deposit_returns_two_clusters()
{ {
var service = new ClusterService(context, wellService.Object); var service = new ClusterService(context, wellService.Object);
var dtos = await service.GetClustersAsync(1,1); var dtos = await service.GetClustersAsync(1, 1);
Assert.Equal(2, dtos.Count()); Assert.Equal(2, dtos.Count());
} }
[Fact] [Fact]
public async Task GetWellsAsync_returns_one_well_by_cluster_and_company() public async Task GetWellsAsync_returns_one_well_by_cluster_and_company()
{ {
var service = new ClusterService(context, wellService.Object); var service = new ClusterService(context, wellService.Object);
var dtos = await service.GetWellsAsync(1,1); var dtos = await service.GetWellsAsync(1, 1);
Assert.Single(dtos); Assert.Single(dtos);
} }
} }

View File

@ -1,5 +1,4 @@
using AsbCloudApp.Services; using AsbCloudApp.Services;
using System;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -8,7 +7,7 @@ using Xunit;
namespace AsbCloudWebApi.Tests.ServicesTests namespace AsbCloudWebApi.Tests.ServicesTests
{ {
public abstract class CrudServiceTestAbstract<TDto> public abstract class CrudServiceTestAbstract<TDto>
where TDto: AsbCloudApp.Data.IId where TDto : AsbCloudApp.Data.IId
{ {
private readonly ICrudService<TDto> service; private readonly ICrudService<TDto> service;

View File

@ -14,7 +14,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
Caption = "test deposit", Caption = "test deposit",
Latitude = 1, Latitude = 1,
Longitude = 2, Longitude = 2,
Timezone = new SimpleTimezoneDto { Hours = 5, TimezoneId = "test Never-land"} Timezone = new SimpleTimezoneDto { Hours = 5, TimezoneId = "test Never-land" }
}; };
return item; return item;
} }

View File

@ -1,5 +1,4 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services; using AsbCloudInfrastructure.Services;
@ -7,9 +6,6 @@ using AsbCloudInfrastructure.Services.Cache;
using AsbCloudInfrastructure.Services.DetectOperations; using AsbCloudInfrastructure.Services.DetectOperations;
using Moq; using Moq;
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using Xunit;
@ -28,7 +24,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
{ {
Id = 1, Id = 1,
Caption = "Test well 1", Caption = "Test well 1",
IdTelemetry=1, IdTelemetry = 1,
IdCluster = 1, IdCluster = 1,
Timezone = new SimpleTimezone { Hours = 5 } Timezone = new SimpleTimezone { Hours = 5 }
}; };
@ -51,12 +47,12 @@ namespace AsbCloudWebApi.Tests.ServicesTests
}; };
private Telemetry telemetry = new Telemetry private Telemetry telemetry = new Telemetry
{ {
Id=1, Id = 1,
RemoteUid = Guid.NewGuid().ToString() RemoteUid = Guid.NewGuid().ToString()
}; };
#endregion #endregion
public DetectedOperationServiceTest() public DetectedOperationServiceTest()
{ {
context = TestHelpter.MakeTestContext(); context = TestHelpter.MakeTestContext();
context.SaveChanges(); context.SaveChanges();

View File

@ -1,11 +1,7 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services; using AsbCloudInfrastructure.Services;
using AsbCloudInfrastructure.Services.Cache; using AsbCloudInfrastructure.Services.Cache;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -61,7 +57,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
[Fact] [Fact]
public async Task InsertAsync_returns_id() public async Task InsertAsync_returns_id()
{ {
var id = await service.InsertAsync(drillerObj, CancellationToken.None); var id = await service.InsertAsync(drillerObj, CancellationToken.None);
Assert.NotEqual(0, id); Assert.NotEqual(0, id);
} }

View File

@ -1,24 +1,23 @@
using AsbCloudDb.Model; using AsbCloudApp.Data;
using AsbCloudInfrastructure.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.DrillingProgram;
using Mapster;
using Microsoft.Extensions.Configuration;
using Moq;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
using Moq;
using Xunit;
using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services.DrillingProgram;
using Microsoft.Extensions.Configuration;
using System.Threading; using System.Threading;
using AsbCloudApp.Data; using System.Threading.Tasks;
using Mapster; using Xunit;
using System;
namespace AsbCloudWebApi.Tests.ServicesTests namespace AsbCloudWebApi.Tests.ServicesTests
{ {
public class DrillingProgramServiceTest public class DrillingProgramServiceTest
{ {
private const int idWell = 3001; private const int idWell = 3001;
private static readonly SimpleTimezone baseTimezone = new () { Hours = 5d }; private static readonly SimpleTimezone baseTimezone = new() { Hours = 5d };
private readonly AsbCloudDbContext db; private readonly AsbCloudDbContext db;
private static readonly List<Well> wells = new() private static readonly List<Well> wells = new()
@ -27,15 +26,15 @@ namespace AsbCloudWebApi.Tests.ServicesTests
new Well { Id = 3002, Caption = "well 2", Timezone = baseTimezone }, new Well { Id = 3002, Caption = "well 2", Timezone = baseTimezone },
}; };
private static readonly List<Company> companies = new() { private static readonly List<Company> companies = new() {
new Company { Id = 3001, Caption = "company name", IdCompanyType = 2, }, new Company { Id = 3001, Caption = "company name", IdCompanyType = 2, },
new Company { Id = 3002, Caption = "company name", IdCompanyType = 2, }, new Company { Id = 3002, Caption = "company name", IdCompanyType = 2, },
new Company { Id = 3003, Caption = "company name", IdCompanyType = 2, }, new Company { Id = 3003, Caption = "company name", IdCompanyType = 2, },
}; };
private static readonly User publisher1 = new () { Id = 3001, IdCompany = 3001, Login = "user 1", Email = "aa@aa.aa", IdState = 2 }; private static readonly User publisher1 = new() { Id = 3001, IdCompany = 3001, Login = "user 1", Email = "aa@aa.aa", IdState = 2 };
private static readonly User approver1 = new () { Id = 3002, IdCompany = 3001, Login = "user 2", Email = "aa@aa.aa", IdState = 2 }; private static readonly User approver1 = new() { Id = 3002, IdCompany = 3001, Login = "user 2", Email = "aa@aa.aa", IdState = 2 };
private static readonly User approver2 = new () { Id = 3003, IdCompany = 3002, Login = "user 3", Email = "aa@aa.aa", IdState = 2 }; private static readonly User approver2 = new() { Id = 3003, IdCompany = 3002, Login = "user 3", Email = "aa@aa.aa", IdState = 2 };
private static readonly List<User> users = new() private static readonly List<User> users = new()
{ {
@ -46,7 +45,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
new User { Id = 3005, IdCompany = 3003, Login = "wrong 2", Email = "aa@aa.aa", IdState = 2 }, new User { Id = 3005, IdCompany = 3003, Login = "wrong 2", Email = "aa@aa.aa", IdState = 2 },
}; };
private static readonly FileInfo file1001 = new () private static readonly FileInfo file1001 = new()
{ {
Id = 3001, Id = 3001,
IdWell = idWell, IdWell = idWell,
@ -58,7 +57,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
UploadDate = System.DateTimeOffset.UtcNow, UploadDate = System.DateTimeOffset.UtcNow,
}; };
private static readonly FileInfo file1002 = new () private static readonly FileInfo file1002 = new()
{ {
Id = 3002, Id = 3002,
IdWell = idWell, IdWell = idWell,
@ -117,7 +116,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
emailService.Object); emailService.Object);
var users = await service.GetAvailableUsers(idWell, CancellationToken.None); var users = await service.GetAvailableUsers(idWell, CancellationToken.None);
Assert.Equal(3, users.Count()); Assert.Equal(3, users.Count());
} }
@ -141,7 +140,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
[Fact] [Fact]
public async Task RemovePartsAsync_returns_1() public async Task RemovePartsAsync_returns_1()
{ {
db.DrillingProgramParts.Add(new DrillingProgramPart { IdFileCategory = 1005, IdWell = idWell}); db.DrillingProgramParts.Add(new DrillingProgramPart { IdFileCategory = 1005, IdWell = idWell });
db.SaveChanges(); db.SaveChanges();
var service = new DrillingProgramService( var service = new DrillingProgramService(
db, db,
@ -185,12 +184,13 @@ namespace AsbCloudWebApi.Tests.ServicesTests
{ {
const int idUserRole = 1; const int idUserRole = 1;
const int idFileCategory = 1001; const int idFileCategory = 1001;
var entry = db.DrillingProgramParts.Add(new DrillingProgramPart { var entry = db.DrillingProgramParts.Add(new DrillingProgramPart
{
IdFileCategory = idFileCategory, IdFileCategory = idFileCategory,
IdWell = idWell IdWell = idWell
}); });
db.SaveChanges(); db.SaveChanges();
db.RelationDrillingProgramPartUsers.Add(new RelationUserDrillingProgramPart db.RelationDrillingProgramPartUsers.Add(new RelationUserDrillingProgramPart
{ {
IdUser = publisher1.Id, IdUser = publisher1.Id,
IdDrillingProgramPart = entry.Entity.Id, IdDrillingProgramPart = entry.Entity.Id,
@ -210,7 +210,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
emailService.Object); emailService.Object);
var result = await service.RemoveUserAsync(idWell, idFileCategory, publisher1.Id, idUserRole, CancellationToken.None); var result = await service.RemoveUserAsync(idWell, idFileCategory, publisher1.Id, idUserRole, CancellationToken.None);
Assert.Equal(1, result); Assert.Equal(1, result);
} }
@ -310,7 +310,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
IdMarkType = 0, IdMarkType = 0,
DateCreated = DateTime.Now, DateCreated = DateTime.Now,
}; };
int idMark = 0; int idMark = 0;
var affected = await service.MarkAsDeletedFileMarkAsync(idMark, CancellationToken.None); var affected = await service.MarkAsDeletedFileMarkAsync(idMark, CancellationToken.None);
@ -372,7 +372,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
new FileMark { IdFile = file1002.Id, IdUser = approver1.Id, IdMarkType = 1, DateCreated = DateTimeOffset.UtcNow }, new FileMark { IdFile = file1002.Id, IdUser = approver1.Id, IdMarkType = 1, DateCreated = DateTimeOffset.UtcNow },
new FileMark { IdFile = file1002.Id, IdUser = approver2.Id, IdMarkType = 1, DateCreated = DateTimeOffset.UtcNow } new FileMark { IdFile = file1002.Id, IdUser = approver2.Id, IdMarkType = 1, DateCreated = DateTimeOffset.UtcNow }
); );
db.Files.AddRange(new FileInfo { IdCategory = 1000, IdWell = idWell, Name = "DrillingProgram.xalsx", Size = 1024*1024, UploadDate = DateTimeOffset.UtcNow }); db.Files.AddRange(new FileInfo { IdCategory = 1000, IdWell = idWell, Name = "DrillingProgram.xalsx", Size = 1024 * 1024, UploadDate = DateTimeOffset.UtcNow });
await db.SaveChangesAsync(); await db.SaveChangesAsync();

View File

@ -1,21 +1,20 @@
using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache; using AsbCloudInfrastructure.Services.Cache;
using AsbCloudInfrastructure.Services; using AsbCloudInfrastructure.Services.SAUB;
using Moq;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsbCloudApp.Services;
using Moq;
using Xunit; using Xunit;
using AsbCloudApp.Data.SAUB;
using AsbCloudInfrastructure.Services.SAUB;
namespace AsbCloudWebApi.Tests.ServicesTests; namespace AsbCloudWebApi.Tests.ServicesTests;
public class EventServiceTest public class EventServiceTest
{ {
private readonly AsbCloudDbContext context; private readonly AsbCloudDbContext context;
private readonly CacheDb cacheDb; private readonly CacheDb cacheDb;
private readonly EventService service; private readonly EventService service;
public EventServiceTest() public EventServiceTest()
@ -38,7 +37,7 @@ public class EventServiceTest
}; };
await service.UpsertAsync("uid", dtos); await service.UpsertAsync("uid", dtos);
Assert.Equal(2, context.TelemetryEvents.Count()); Assert.Equal(2, context.TelemetryEvents.Count());
} }
} }

View File

@ -40,10 +40,11 @@ namespace AsbCloudWebApi.Tests.ServicesTests
DrillEnd = dto?.DrillEnd ?? DateTime.Parse("2022-05-16T18:00:00.286Z") DrillEnd = dto?.DrillEnd ?? DateTime.Parse("2022-05-16T18:00:00.286Z")
}; };
} }
private Well well = new Well { private Well well = new Well
Id=1, {
Caption = "Test well 1", Id = 1,
Caption = "Test well 1",
IdCluster = 1, IdCluster = 1,
Timezone = new SimpleTimezone { Hours = 5 } Timezone = new SimpleTimezone { Hours = 5 }
}; };
@ -55,7 +56,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
Surname = "Тестович" Surname = "Тестович"
}; };
public ScheduleServiceTest() public ScheduleServiceTest()
{ {
context = TestHelpter.MakeTestContext(); context = TestHelpter.MakeTestContext();
context.SaveChanges(); context.SaveChanges();
@ -117,7 +118,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
dto.ShiftStart = new TimeOnly(8, 00); dto.ShiftStart = new TimeOnly(8, 00);
dto.ShiftEnd = new TimeOnly(20, 00); dto.ShiftEnd = new TimeOnly(20, 00);
var id = await scheduleService.InsertAsync(dto, CancellationToken.None); var id = await scheduleService.InsertAsync(dto, CancellationToken.None);
var drillerWorkTime = new DateTime( var drillerWorkTime = new DateTime(
dto.DrillStart.Year, dto.DrillStart.Year,
dto.DrillStart.Month, dto.DrillStart.Month,
dto.DrillStart.Day, dto.DrillStart.Day,

View File

@ -24,7 +24,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
private readonly TelemetryService telemetryService; private readonly TelemetryService telemetryService;
private readonly DateTime drillingStartDate; private readonly DateTime drillingStartDate;
private readonly string uuid; private readonly string uuid;
public TelemetryDataSaubServiceTest() public TelemetryDataSaubServiceTest()
{ {
timezone = new() { Hours = 7 }; timezone = new() { Hours = 7 };
@ -65,22 +65,22 @@ namespace AsbCloudWebApi.Tests.ServicesTests
{ {
// Arrange // Arrange
var telemetryDataSaubService = new TelemetryDataSaubService(context, telemetryService, cacheDb); var telemetryDataSaubService = new TelemetryDataSaubService(context, telemetryService, cacheDb);
var now = DateTimeOffset.UtcNow.ToOffset(TimeSpan.FromHours(timezone.Hours)).DateTime; var now = DateTimeOffset.UtcNow.ToOffset(TimeSpan.FromHours(timezone.Hours)).DateTime;
var tuser = "Завулон"; var tuser = "Завулон";
var newData = new List<TelemetryDataSaubDto> var newData = new List<TelemetryDataSaubDto>
{ {
new TelemetryDataSaubDto{ new TelemetryDataSaubDto{
DateTime = now, DateTime = now,
AxialLoad = 1, AxialLoad = 1,
MseState = 1, MseState = 1,
User = tuser, User = tuser,
} }
}; };
// act // act
var affected = await telemetryDataSaubService.UpdateDataAsync(uuid, newData, CancellationToken.None); var affected = await telemetryDataSaubService.UpdateDataAsync(uuid, newData, CancellationToken.None);
// assert // assert
Assert.Equal(1, affected); Assert.Equal(1, affected);
} }

View File

@ -2,7 +2,6 @@
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services; using AsbCloudInfrastructure.Services;
using AsbCloudInfrastructure.Services.Cache; using AsbCloudInfrastructure.Services.Cache;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
@ -62,7 +61,8 @@ namespace AsbCloudWebApi.Tests.ServicesTests
context.SaveChanges(); context.SaveChanges();
} }
~UserRoleServiceTest(){ ~UserRoleServiceTest()
{
context.UserRoles.RemoveRange(roles); context.UserRoles.RemoveRange(roles);
context.Permissions.RemoveRange(permissions); context.Permissions.RemoveRange(permissions);
context.RelationUserRoleUserRoles.RemoveRange(relationRoleRole); context.RelationUserRoleUserRoles.RemoveRange(relationRoleRole);
@ -104,7 +104,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
Caption = "new role", Caption = "new role",
IdType = 0, IdType = 0,
}; };
var id = await service.InsertAsync(newRole, CancellationToken.None ); var id = await service.InsertAsync(newRole, CancellationToken.None);
Assert.NotEqual(0, id); Assert.NotEqual(0, id);
} }
@ -116,9 +116,9 @@ namespace AsbCloudWebApi.Tests.ServicesTests
{ {
Caption = "new role", Caption = "new role",
IdType = 0, IdType = 0,
Permissions = new[] { new PermissionDto{ Id = 2_000_001 } }, Permissions = new[] { new PermissionDto { Id = 2_000_001 } },
}; };
var id = await service.InsertAsync(newRole, CancellationToken.None); var id = await service.InsertAsync(newRole, CancellationToken.None);
var entity = await service.GetAsync(id); var entity = await service.GetAsync(id);
Assert.Equal(newRole.Permissions.Count(), entity.Permissions.Count()); Assert.Equal(newRole.Permissions.Count(), entity.Permissions.Count());
} }
@ -131,7 +131,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
{ {
Caption = "new role", Caption = "new role",
IdType = 0, IdType = 0,
Roles = new [] { new UserRoleDto { Id = 1_000_001 } } Roles = new[] { new UserRoleDto { Id = 1_000_001 } }
}; };
var id = await service.InsertAsync(newRole, CancellationToken.None); var id = await service.InsertAsync(newRole, CancellationToken.None);
var entity = await service.GetAsync(id); var entity = await service.GetAsync(id);
@ -143,10 +143,10 @@ namespace AsbCloudWebApi.Tests.ServicesTests
{ {
var service = new UserRoleService(context, cacheDb); var service = new UserRoleService(context, cacheDb);
const int updateId = 1_000_002; const int updateId = 1_000_002;
var modRole = new UserRoleDto var modRole = new UserRoleDto
{ {
Id = updateId, Id = updateId,
Caption = "role 2 level 1" Caption = "role 2 level 1"
}; };
var id = await service.UpdateAsync(modRole, CancellationToken.None); var id = await service.UpdateAsync(modRole, CancellationToken.None);
Assert.Equal(updateId, id); Assert.Equal(updateId, id);

View File

@ -36,7 +36,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
[Fact] [Fact]
public async Task InsertAsync_returns_id() public async Task InsertAsync_returns_id()
{ {
var service = new UserService(context, cacheDb, roleService.Object); var service = new UserService(context, cacheDb, roleService.Object);
var dto = new UserExtendedDto var dto = new UserExtendedDto
{ {

View File

@ -12,6 +12,6 @@ namespace AsbCloudWebApi.Controllers
{ {
public AdminClusterController(ICrudService<ClusterDto> service) public AdminClusterController(ICrudService<ClusterDto> service)
: base(service) : base(service)
{} { }
} }
} }

View File

@ -19,7 +19,7 @@ namespace AsbCloudWebApi.Controllers
return Task.FromResult(role?.IdType == 1); return Task.FromResult(role?.IdType == 1);
}; };
UpdateForbidAsync = async ( dto, token) => UpdateForbidAsync = async (dto, token) =>
{ {
var role = await service.GetAsync(dto.Id, token); var role = await service.GetAsync(dto.Id, token);
return role?.IdType == 1; return role?.IdType == 1;

View File

@ -14,7 +14,7 @@ namespace AsbCloudWebApi.Controllers
{ {
public AdminWellController(IWellService service) public AdminWellController(IWellService service)
: base(service) : base(service)
{} { }
[HttpPost("EnshureTimezonesIsSet")] [HttpPost("EnshureTimezonesIsSet")]
[Permission] [Permission]

View File

@ -92,9 +92,9 @@ namespace AsbCloudWebApi.Controllers
if (!values.Any()) if (!values.Any())
return BadRequest("there is no values to add"); return BadRequest("there is no values to add");
if (InsertForbidAsync is not null) if (InsertForbidAsync is not null)
foreach (var value in values) foreach (var value in values)
if(await InsertForbidAsync(value, token)) if (await InsertForbidAsync(value, token))
return Forbid(); return Forbid();
var result = await service.InsertRangeAsync(values, token).ConfigureAwait(false); var result = await service.InsertRangeAsync(values, token).ConfigureAwait(false);

View File

@ -22,7 +22,7 @@ namespace AsbCloudWebApi.Controllers
where T : IId, IWellRelated where T : IId, IWellRelated
where TService : ICrudWellRelatedService<T> where TService : ICrudWellRelatedService<T>
{ {
private readonly IWellService wellService; protected readonly IWellService wellService;
protected CrudWellRelatedController(IWellService wellService, TService service) protected CrudWellRelatedController(IWellService wellService, TService service)
: base(service) : base(service)
@ -74,7 +74,7 @@ namespace AsbCloudWebApi.Controllers
{ {
var actionResult = await base.GetAsync(id, token); var actionResult = await base.GetAsync(id, token);
var result = actionResult.Value; var result = actionResult.Value;
if(!await UserHasAccesToWellAsync(result.IdWell, token)) if (!await UserHasAccesToWellAsync(result.IdWell, token))
return Forbid(); return Forbid();
return Ok(result); return Ok(result);
} }
@ -113,7 +113,7 @@ namespace AsbCloudWebApi.Controllers
public override async Task<ActionResult<int>> DeleteAsync(int id, CancellationToken token) public override async Task<ActionResult<int>> DeleteAsync(int id, CancellationToken token)
{ {
var item = await service.GetAsync(id, token); var item = await service.GetAsync(id, token);
if(item is null) if (item is null)
return NoContent(); return NoContent();
if (!await UserHasAccesToWellAsync(item.IdWell, token)) if (!await UserHasAccesToWellAsync(item.IdWell, token))
return Forbid(); return Forbid();
@ -130,6 +130,4 @@ namespace AsbCloudWebApi.Controllers
return false; return false;
} }
} }
} }

View File

@ -1,4 +1,5 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System; using System;
@ -6,7 +7,6 @@ using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsbCloudApp.Services;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
{ {
@ -105,7 +105,7 @@ namespace AsbCloudWebApi.Controllers
var stream = await dailyReportService.MakeReportAsync(idWell, date, token); var stream = await dailyReportService.MakeReportAsync(idWell, date, token);
if (stream != null) if (stream != null)
{ {
var fileName = $"Суточный рапорт по скважине {well.Caption} куст {well.Cluster}.xlsx"; var fileName = $"Суточный рапорт по скважине {well.Caption} куст {well.Cluster}.xlsx";
return File(stream, "application/octet-stream", fileName); return File(stream, "application/octet-stream", fileName);
} }

View File

@ -22,7 +22,7 @@ namespace AsbCloudWebApi.Controllers
public DrillFlowChartController(IWellService wellService, IDrillFlowChartService service, public DrillFlowChartController(IWellService wellService, IDrillFlowChartService service,
ITelemetryService telemetryService) ITelemetryService telemetryService)
:base(wellService, service) : base(wellService, service)
{ {
this.telemetryService = telemetryService; this.telemetryService = telemetryService;
this.wellService = wellService; this.wellService = wellService;

View File

@ -11,7 +11,7 @@ namespace AsbCloudWebApi.Controllers
public class DrillerController : CrudController<DrillerDto, IDrillerService> public class DrillerController : CrudController<DrillerDto, IDrillerService>
{ {
public DrillerController(IDrillerService drillerService) public DrillerController(IDrillerService drillerService)
:base(drillerService) : base(drillerService)
{} { }
} }
} }

View File

@ -125,7 +125,7 @@ namespace AsbCloudWebApi.Controllers
if (!fileName.EndsWith(".xlsx")) if (!fileName.EndsWith(".xlsx"))
return BadRequest(ArgumentInvalidException.MakeValidationError("file", "Файл должен быть xlsx")); return BadRequest(ArgumentInvalidException.MakeValidationError("file", "Файл должен быть xlsx"));
var fileStream = files[0].OpenReadStream(); var fileStream = files[0].OpenReadStream();
var result = await drillingProgramService.AddFile(idWell, idFileCategory, (int)idUser, fileName, fileStream, token); var result = await drillingProgramService.AddFile(idWell, idFileCategory, (int)idUser, fileName, fileStream, token);

View File

@ -1,12 +1,7 @@
using AsbCloudApp.Data; using Microsoft.AspNetCore.Mvc;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ProtoBuf.Meta; using ProtoBuf.Meta;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
{ {

View File

@ -1,10 +1,10 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Requests;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading; using System.Threading;
using AsbCloudApp.Requests; using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers.SAUB namespace AsbCloudWebApi.Controllers.SAUB
{ {

View File

@ -34,7 +34,7 @@ namespace AsbCloudWebApi.Controllers.SAUB
[AllowAnonymous] [AllowAnonymous]
public IActionResult GetSetpointsNamesByIdWellAsync([FromRoute] int idWell) public IActionResult GetSetpointsNamesByIdWellAsync([FromRoute] int idWell)
{ {
var result = setpointsService.GetSetpointsNames(idWell); var result = setpointsService.GetSetpointsNames();
return Ok(result); return Ok(result);
} }
@ -115,7 +115,7 @@ namespace AsbCloudWebApi.Controllers.SAUB
[AllowAnonymous] [AllowAnonymous]
public async Task<IActionResult> UpdateByTelemetryUidAsync([FromRoute] string uid, int id, SetpointsRequestDto setpointsRequestDto, CancellationToken token = default) public async Task<IActionResult> UpdateByTelemetryUidAsync([FromRoute] string uid, int id, SetpointsRequestDto setpointsRequestDto, CancellationToken token = default)
{ {
var result = await setpointsService.UpdateStateAsync(uid, id, setpointsRequestDto, token) var result = await setpointsService.UpdateStateAsync(id, setpointsRequestDto, token)
.ConfigureAwait(false); .ConfigureAwait(false);
return Ok(result); return Ok(result);
@ -156,7 +156,7 @@ namespace AsbCloudWebApi.Controllers.SAUB
if (idCompany is null || idUser is null) if (idCompany is null || idUser is null)
return Forbid(); return Forbid();
var result = await setpointsService.TryDelete(idWell, id, token) var result = await setpointsService.TryDelete(id, token)
.ConfigureAwait(false); .ConfigureAwait(false);
return Ok(result); return Ok(result);

View File

@ -3,7 +3,6 @@ using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System; using System;
using System.Collections.Generic;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -12,37 +11,16 @@ namespace AsbCloudWebApi.Controllers
[Route("api/schedule")] [Route("api/schedule")]
[ApiController] [ApiController]
[Authorize] [Authorize]
public class ScheduleController : CrudController<ScheduleDto, IScheduleService> public class ScheduleController : CrudWellRelatedController<ScheduleDto, IScheduleService>
{ {
private readonly IScheduleService scheduleService; private readonly IScheduleService scheduleService;
private readonly IWellService wellService;
public ScheduleController(IScheduleService scheduleService, IWellService wellService) public ScheduleController(IScheduleService scheduleService, IWellService wellService)
:base(scheduleService) : base(wellService, scheduleService)
{ {
this.scheduleService = service; this.scheduleService = service;
this.wellService = wellService;
} }
/// <summary>
/// список расписаний бурильщиков по скважине
/// </summary>
/// <param name="idWell"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet("byWellId/{idWell}")]
[ProducesResponseType(typeof(IEnumerable<ScheduleDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetByIdWellAsync(int idWell, CancellationToken token)
{
var idCompany = User.GetCompanyId();
if(idCompany is null || !wellService.IsCompanyInvolvedInWell((int)idCompany, idWell))
return Forbid();
var result = await scheduleService.GetByIdWellAsync(idWell, token);
return Ok(result);
}
/// <summary> /// <summary>
/// Получить бурильщика работавшего на скважине в определенное время. /// Получить бурильщика работавшего на скважине в определенное время.
/// </summary> /// </summary>
@ -53,11 +31,10 @@ namespace AsbCloudWebApi.Controllers
[HttpGet("driller")] [HttpGet("driller")]
public async Task<ActionResult<DrillerDto>> GetDrillerAsync(int idWell, DateTime workTime, CancellationToken token) public async Task<ActionResult<DrillerDto>> GetDrillerAsync(int idWell, DateTime workTime, CancellationToken token)
{ {
var idCompany = User.GetCompanyId(); if (!await UserHasAccesToWellAsync(idWell, token))
if (idCompany is null || !wellService.IsCompanyInvolvedInWell((int)idCompany, idWell))
return Forbid(); return Forbid();
var result = await scheduleService.GetDrillerAsync(idWell,workTime, token); var result = await scheduleService.GetDrillerAsync(idWell, workTime, token);
return Ok(result); return Ok(result);
} }

View File

@ -1,5 +1,4 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Data.WITS;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudWebApi.SignalR; using AsbCloudWebApi.SignalR;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;

View File

@ -1,5 +1,4 @@
using AsbCloudInfrastructure.Services; using AsbCloudInfrastructure.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic; using System.Collections.Generic;

View File

@ -3,7 +3,6 @@ using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;

View File

@ -22,15 +22,16 @@ namespace AsbCloudWebApi
services.AddControllers() services.AddControllers()
.AddJsonOptions(new System.Action<Microsoft.AspNetCore.Mvc.JsonOptions>(options => .AddJsonOptions(new System.Action<Microsoft.AspNetCore.Mvc.JsonOptions>(options =>
{ {
options.JsonSerializerOptions.NumberHandling = options.JsonSerializerOptions.NumberHandling =
System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals | System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals |
System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString;})) System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString;
}))
.AddProtoBufNet(); .AddProtoBufNet();
ProtobufModel.EnshureRegistered(); ProtobufModel.EnshureRegistered();
services.AddSwagger(); services.AddSwagger();
services.AddInfrastructure(Configuration); services.AddInfrastructure(Configuration);
services.AddJWTAuthentication(); services.AddJWTAuthentication();

View File

@ -1,10 +1,7 @@
using AsbCloudDb.Model; using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1 namespace ConsoleApp1
{ {
@ -20,7 +17,7 @@ namespace ConsoleApp1
public static void Main() public static void Main()
{ {
using var db = new AsbCloudDbContext(options); using var db = new AsbCloudDbContext(options);
var wellsIds = db.WellOperations var wellsIds = db.WellOperations
.Select(o => o.IdWell) .Select(o => o.IdWell)
.Distinct() .Distinct()
@ -38,10 +35,10 @@ namespace ConsoleApp1
var operationsPlan = operations.Where(o => o.IdType == 0); var operationsPlan = operations.Where(o => o.IdType == 0);
RefactorWellOperations(operationsPlan); RefactorWellOperations(operationsPlan);
var operationsFact = operations.Where(o => o.IdType == 1); var operationsFact = operations.Where(o => o.IdType == 1);
RefactorWellOperations(operationsFact); RefactorWellOperations(operationsFact);
db.SaveChanges(); db.SaveChanges();
} }
transaction.Commit(); transaction.Commit();
@ -49,7 +46,7 @@ namespace ConsoleApp1
catch catch
{ {
transaction.Rollback(); transaction.Rollback();
} }
} }
private static void RefactorWellOperations(IEnumerable<WellOperation> operations) private static void RefactorWellOperations(IEnumerable<WellOperation> operations)

View File

@ -1,12 +1,11 @@
using AsbCloudApp.Data.SAUB;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;
using AsbCloudApp.Data; using System.Threading;
using AsbCloudApp.Data.SAUB; using System.Threading.Tasks;
namespace ConsoleApp1 namespace ConsoleApp1
{ {
@ -113,17 +112,17 @@ namespace ConsoleApp1
Flow = MakeFloatRandom(100), Flow = MakeFloatRandom(100),
FlowIdle = MakeFloatRandom(100), FlowIdle = MakeFloatRandom(100),
FlowDeltaLimitMax = MakeFloatRandom(100), FlowDeltaLimitMax = MakeFloatRandom(100),
}; };
return dto; return dto;
} }
private static float MakeFloatRandom( float max, float min = 0) private static float MakeFloatRandom(float max, float min = 0)
{ {
var val = (float)( min + random.NextDouble() * (max - min)); var val = (float)(min + random.NextDouble() * (max - min));
return val; return val;
} }
private static float MakeFloatSin( float max, float min, float angle) private static float MakeFloatSin(float max, float min, float angle)
{ {
var val = (float)(min + Math.Sin(angle) * (max - min) / 2); var val = (float)(min + Math.Sin(angle) * (max - min) / 2);
return val; return val;

View File

@ -1,13 +1,6 @@
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services;
using AsbCloudInfrastructure.Services.Cache;
using AsbCloudInfrastructure.Services.WellOperationService;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1 namespace ConsoleApp1
{ {

View File

@ -1,14 +1,6 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services;
using AsbCloudInfrastructure.Services.Cache;
using AsbCloudInfrastructure.Services.WellOperationService;
using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1 namespace ConsoleApp1
{ {

View File

@ -2,11 +2,10 @@ using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows; using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Responses; using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Drive.v3; using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services; using Google.Apis.Services;
using Google.Apis.Util.Store; using Google.Apis.Util.Store;
using Google.Apis.Drive.v3.Data;
using System.IO; using System.IO;
using System.Collections.Generic;
using System.Linq; using System.Linq;
// usage example at the very bottom // usage example at the very bottom
@ -15,7 +14,7 @@ namespace ConsoleApp1
public class GoogleDriveService public class GoogleDriveService
{ {
private readonly DriveService service; private readonly DriveService service;
public GoogleDriveService() public GoogleDriveService()
{ // ключи для почты asbautodrilling@gmail.com. { // ключи для почты asbautodrilling@gmail.com.
var tokenResponse = new TokenResponse var tokenResponse = new TokenResponse
@ -34,7 +33,7 @@ namespace ConsoleApp1
ClientId = "1020584579240-f7amqg35qg7j94ta1ntgitajq27cgh49.apps.googleusercontent.com", ClientId = "1020584579240-f7amqg35qg7j94ta1ntgitajq27cgh49.apps.googleusercontent.com",
ClientSecret = "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" ClientSecret = "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"
}, },
Scopes = new[] {DriveService.Scope.Drive}, Scopes = new[] { DriveService.Scope.Drive },
DataStore = new FileDataStore(applicationName) DataStore = new FileDataStore(applicationName)
}); });
@ -47,7 +46,7 @@ namespace ConsoleApp1
}); });
this.service = newService; this.service = newService;
} }
// public IEnumerable<Google.Apis.Drive.v3.Data.File> GetAllFiles() // get file names // public IEnumerable<Google.Apis.Drive.v3.Data.File> GetAllFiles() // get file names
// { // {
// var fileList = service.Files.List(); // var fileList = service.Files.List();
@ -77,10 +76,10 @@ namespace ConsoleApp1
var file = filesResult.Files.FirstOrDefault(f => f.Id == idFile); var file = filesResult.Files.FirstOrDefault(f => f.Id == idFile);
return file?.WebViewLink ?? string.Empty; return file?.WebViewLink ?? string.Empty;
} }
// У Гугла почему-то folder это и папка, и файл. // У Гугла почему-то folder это и папка, и файл.
public string CreateFolder(string folderName) public string CreateFolder(string folderName)
{ {
var driveFolder = new Google.Apis.Drive.v3.Data.File(); var driveFolder = new Google.Apis.Drive.v3.Data.File();
driveFolder.Name = folderName; driveFolder.Name = folderName;
driveFolder.MimeType = "application/vnd.google-apps.folder"; driveFolder.MimeType = "application/vnd.google-apps.folder";
@ -92,11 +91,11 @@ namespace ConsoleApp1
public void CreatePublicPermissionForFile(string idFile) public void CreatePublicPermissionForFile(string idFile)
{ {
var permission = new Permission() { Type = "anyone", Role = "reader"}; var permission = new Permission() { Type = "anyone", Role = "reader" };
var addPermissionRequest = service.Permissions.Create(permission, idFile); var addPermissionRequest = service.Permissions.Create(permission, idFile);
addPermissionRequest.Execute(); addPermissionRequest.Execute();
} }
public string UploadFile(Stream file, string fileName, string fileMime, string fileDescription) public string UploadFile(Stream file, string fileName, string fileMime, string fileDescription)
{ {
var driveFile = new Google.Apis.Drive.v3.Data.File(); var driveFile = new Google.Apis.Drive.v3.Data.File();
@ -104,14 +103,14 @@ namespace ConsoleApp1
driveFile.Description = fileDescription; driveFile.Description = fileDescription;
driveFile.MimeType = fileMime; driveFile.MimeType = fileMime;
//driveFile.Parents = new [] {folder}; //driveFile.Parents = new [] {folder};
var request = service.Files.Create(driveFile, file, fileMime); var request = service.Files.Create(driveFile, file, fileMime);
request.Fields = "id"; request.Fields = "id";
var response = request.Upload(); var response = request.Upload();
if (response.Status != Google.Apis.Upload.UploadStatus.Completed) if (response.Status != Google.Apis.Upload.UploadStatus.Completed)
throw response.Exception; throw response.Exception;
return request.ResponseBody.Id; return request.ResponseBody.Id;
} }

View File

@ -1,16 +1,12 @@
using AsbCloudApp.Data; using AsbCloudInfrastructure.EfCache;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.EfCache;
using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ConsoleApp1 namespace ConsoleApp1
{ {
class Program class Program
{ {
// use ServiceFactory to make services // use ServiceFactory to make services
@ -21,7 +17,8 @@ namespace ConsoleApp1
for (int i = 0; i < 24; i++) for (int i = 0; i < 24; i++)
{ {
var t = new Thread(_ => { var t = new Thread(_ =>
{
for (int j = 0; j < 32; j++) for (int j = 0; j < 32; j++)
//Task.Run(GetDataAsync).Wait(); //Task.Run(GetDataAsync).Wait();
GetData(); GetData();
@ -60,7 +57,7 @@ namespace ConsoleApp1
.Where(t => t.IdTelemetry == 135) .Where(t => t.IdTelemetry == 135)
.OrderBy(t => t.DateTime) .OrderBy(t => t.DateTime)
.Take(100_000) .Take(100_000)
.FromCacheDictionaryAsync("tds", obso, r => (r.IdTelemetry, r.DateTime), r => new {r.Pressure, r.HookWeight })) .FromCacheDictionaryAsync("tds", obso, r => (r.IdTelemetry, r.DateTime), r => new { r.Pressure, r.HookWeight }))
.ToList(); .ToList();
sw.Stop(); sw.Stop();
Console.WriteLine($"{DateTime.Now}\tth: {Thread.CurrentThread.ManagedThreadId}\ttime {sw.ElapsedMilliseconds}\tcount {cs.Count}"); Console.WriteLine($"{DateTime.Now}\tth: {Thread.CurrentThread.ManagedThreadId}\ttime {sw.ElapsedMilliseconds}\tcount {cs.Count}");

View File

@ -1,9 +1,4 @@
using System; using System.Net.Mail;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1 namespace ConsoleApp1
{ {
@ -14,7 +9,7 @@ namespace ConsoleApp1
MailAddress to = new MailAddress("ng.frolov@autodrilling.ru"); MailAddress to = new MailAddress("ng.frolov@autodrilling.ru");
MailAddress from = new MailAddress("bot@autodrilling.ru"); MailAddress from = new MailAddress("bot@autodrilling.ru");
MailMessage message = new MailMessage(from, to); MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client."; message.Subject = "Using the new SMTP client.";
message.Body = "<html><boby><H1>this is a test text</H1></boby></html>"; message.Body = "<html><boby><H1>this is a test text</H1></boby></html>";
message.IsBodyHtml = true; message.IsBodyHtml = true;

View File

@ -64,10 +64,10 @@ namespace ConsoleApp1
public static TelemetryTracker MakeTelemetryTracker() public static TelemetryTracker MakeTelemetryTracker()
=> new TelemetryTracker(CacheDb, ConfigurationService); => new TelemetryTracker(CacheDb, ConfigurationService);
public static TelemetryService MakeTelemetryService() public static TelemetryService MakeTelemetryService()
=> new TelemetryService(Context, MakeTelemetryTracker(), TimezoneService, CacheDb); => new TelemetryService(Context, MakeTelemetryTracker(), TimezoneService, CacheDb);
public static WellService MakeWellService() public static WellService MakeWellService()
=> new WellService(Context, CacheDb, MakeTelemetryService(), TimezoneService); => new WellService(Context, CacheDb, MakeTelemetryService(), TimezoneService);
public static WellOperationService MakeWellOperationsService() public static WellOperationService MakeWellOperationsService()
@ -76,7 +76,7 @@ namespace ConsoleApp1
public static OperationsStatService MakeOperationsStatService() public static OperationsStatService MakeOperationsStatService()
=> new OperationsStatService(Context, CacheDb, MakeWellService()); => new OperationsStatService(Context, CacheDb, MakeWellService());
public static ScheduleReportService MakeScheduleReportService() public static ScheduleReportService MakeScheduleReportService()
=> new ScheduleReportService(MakeOperationsStatService(), MakeWellService()); => new ScheduleReportService(MakeOperationsStatService(), MakeWellService());
} }
} }