Merge conflict fix

This commit is contained in:
Lyudmila Romanova 2022-06-10 12:01:46 +05:00
commit 4bc07bc727
36 changed files with 493 additions and 335 deletions

View File

@ -23,7 +23,7 @@ namespace AsbCloudApp.Data
public double? Longitude { get; set; }
/// <inheritdoc/>
public SimpleTimezoneDto Timezone { get; set; } = null!;
public SimpleTimezoneDto? Timezone { get; set; }
/// <summary>
/// ИД месторождения, необязательный
@ -38,7 +38,7 @@ namespace AsbCloudApp.Data
/// <summary>
/// Список скважин куста
/// </summary>
public IEnumerable<WellDto> Wells { get; set; } = null!;
public IEnumerable<WellDto>? Wells { get; set; } = null!;
}
#nullable disable
}

View File

@ -36,5 +36,9 @@ namespace AsbCloudApp.Data
=> Hours.GetHashCode()
| TimezoneId.GetHashCode()
| IsOverride.GetHashCode();
/// <inheritdoc/>
public override string ToString()
=> $"{TimezoneId} (UTC+{Hours:00.##})";
}
}

View File

@ -55,6 +55,14 @@ namespace AsbCloudApp.Data
public TimeDto()
{ }
/// <inheritdoc/>
public TimeDto(int hour = 0, int minute = 0, int second = 0)
{
this.hour = hour;
this.minute = minute;
this.second = second;
}
/// <inheritdoc/>
public TimeDto(TimeOnly time)
{

View File

@ -7,9 +7,15 @@ namespace AsbCloudApp.Exceptions
/// </summary>
public class ForbidException : Exception
{
/// <summary>
/// Access denied exception
/// </summary>
public ForbidException()
: base() { }
/// <summary>
/// Access denied exception
/// </summary>
public ForbidException(string message)
: base(message) { }

View File

@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@ -60,18 +59,17 @@ namespace AsbCloudApp.Services
/// <summary>
/// Отредактировать запись
/// </summary>
/// <param name="id"></param>
/// <param name="item"></param>
/// <param name="token"></param>
/// <returns>если больше 0 - Id записи, если меньше 0 - код ошибки</returns>
Task<int> UpdateAsync(int id, Tdto item, CancellationToken token);
Task<int> UpdateAsync(Tdto item, CancellationToken token);
/// <summary>
/// Удалить запись
/// </summary>
/// <param name="id"></param>
/// <param name="token"></param>
/// <returns>если больше 0 - Id записи, если меньше 0 - код ошибки</returns>
/// <returns>количество добавленных, если меньше 0 - код ошибки</returns>
Task<int> DeleteAsync(int id, CancellationToken token);
}
#nullable disable

View File

@ -0,0 +1,33 @@
using AsbCloudApp.Data;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Services
{
/// <summary>
/// Сервис получения, добавления, изменения, удаления данных<br/>
/// Для сущностей относящихся к скважине
/// </summary>
/// <typeparam name="Tdto"></typeparam>
public interface ICrudWellRelatedService<Tdto> : ICrudService<Tdto>
where Tdto: IId, IWellRelated
{
/// <summary>
/// Получение всех записей по скважине
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="token"></param>
/// <returns>emptyList if nothing found</returns>
Task<IEnumerable<Tdto>> GetAllAsync(int idWell, CancellationToken token);
/// <summary>
/// Получение всех записей по нескольким скважинам
/// </summary>
/// <param name="idsWells">id скважин</param>
/// <param name="token"></param>
/// <returns>emptyList if nothing found</returns>
Task<IEnumerable<Tdto>> GetAllAsync(IEnumerable<int> idsWells, CancellationToken token);
}
#nullable disable
}

View File

@ -6,18 +6,9 @@ using System.Threading.Tasks;
namespace AsbCloudApp.Services
{
public interface IDrillFlowChartService : ICrudService<DrillFlowChartDto>
public interface IDrillFlowChartService : ICrudWellRelatedService<DrillFlowChartDto>
{
Task<IEnumerable<DrillFlowChartDto>> GetAllAsync(int idWell,
DateTime updateFrom, CancellationToken token = default);
Task<int> InsertAsync(int idWell, DrillFlowChartDto dto,
CancellationToken token = default);
Task<int> InsertRangeAsync(int idWell, IEnumerable<DrillFlowChartDto> dtos,
CancellationToken token = default);
Task<int> UpdateAsync(int idWell, int idDto, DrillFlowChartDto dto,
CancellationToken token = default);
}
}

View File

@ -8,7 +8,7 @@ namespace AsbCloudDb.Model
{
#nullable disable
[Table("t_drill_flow_chart"), Comment("Параметры коридоров бурения (диапазоны параметров бурения)")]
public class DrillFlowChart : IId
public class DrillFlowChart : IId, IWellRelated
{
[Key]
[Column("id")]

View File

@ -9,7 +9,7 @@ namespace AsbCloudDb.Model
{
#nullable disable
[Table("t_file_info"), Comment("Файлы всех категорий")]
public class FileInfo : IId, IIdWell
public class FileInfo : IId, IWellRelated
{
[Key]
[Column("id")]

View File

@ -3,8 +3,11 @@
/// <summary>
/// For well related entities
/// </summary>
public interface IIdWell
public interface IWellRelated
{
/// <summary>
/// Id скважины
/// </summary>
int IdWell { get; set; }
}
}

View File

@ -6,7 +6,7 @@ using System.ComponentModel.DataAnnotations.Schema;
namespace AsbCloudDb.Model
{
[Table("t_relation_company_well"), Comment("отношение скважин и компаний")]
public partial class RelationCompanyWell : IIdWell
public partial class RelationCompanyWell : IWellRelated
{
[Column("id_well")]
public int IdWell { get; set; }

View File

@ -7,7 +7,7 @@ namespace AsbCloudDb.Model
{
#nullable disable
[Table("t_report_property"), Comment("Отчеты с данными по буровым")]
public class ReportProperty : IId, IIdWell
public class ReportProperty : IId, IWellRelated
{
[Key]
[Column("id")]

View File

@ -8,7 +8,7 @@ namespace AsbCloudDb.Model
{
#nullable disable
[Table("t_setpoints_rquest"), Comment("Запросы на изменение уставок панели оператора")]
public class SetpointsRequest : IId, IIdWell
public class SetpointsRequest : IId, IWellRelated
{
[Key]
[Column("id")]

View File

@ -4,7 +4,7 @@ using System.ComponentModel.DataAnnotations.Schema;
namespace AsbCloudDb.Model
{
[Table("t_well_composite"), Comment("Композитная скважина")]
public class WellComposite : IIdWell
public class WellComposite : IWellRelated
{
[Column("id_well"), Comment("Id скважины получателя")]
public int IdWell { get; set; }

View File

@ -89,18 +89,6 @@ namespace AsbCloudInfrastructure.EfCache
try
{
cache = new CacheItem();
var dateObsolete = DateTime.Now + obsolete;
var dateQueryStart = DateTime.Now;
var data = valueFactory();
var queryTime = DateTime.Now - dateQueryStart;
if (dateObsolete - DateTime.Now < minCacheTime)
dateObsolete = DateTime.Now + minCacheTime;
cache.Data = data;
cache.DateObsolete = dateObsolete;
cache.DateObsoleteTotal = dateObsolete + queryTime + minCacheTime;
caches.Add(tag, cache);
}
catch
@ -182,18 +170,6 @@ namespace AsbCloudInfrastructure.EfCache
try
{
cache = new CacheItem();
var dateObsolete = DateTime.Now + obsolete;
var dateQueryStart = DateTime.Now;
var data = await valueFactoryAsync(token);
var queryTime = DateTime.Now - dateQueryStart;
if (dateObsolete - DateTime.Now < minCacheTime)
dateObsolete = DateTime.Now + minCacheTime;
cache.Data = data;
cache.DateObsolete = dateObsolete;
cache.DateObsoleteTotal = dateObsolete + queryTime + minCacheTime;
caches.Add(tag, cache);
}
catch

View File

@ -85,18 +85,6 @@ namespace AsbCloudInfrastructure.EfCache
{
try {
cache = new CacheItem();
var dateObsolete = DateTime.Now + obsolete;
var dateQueryStart = DateTime.Now;
var data = valueFactory();
var queryTime = DateTime.Now - dateQueryStart;
if (dateObsolete - DateTime.Now < minCacheTime)
dateObsolete = DateTime.Now + minCacheTime;
cache.Data = data;
cache.DateObsolete = dateObsolete;
cache.DateObsoleteTotal = dateObsolete + queryTime + minCacheTime;
caches.Add(tag, cache);
}
catch
@ -178,18 +166,6 @@ namespace AsbCloudInfrastructure.EfCache
try
{
cache = new CacheItem();
var dateObsolete = DateTime.Now + obsolete;
var dateQueryStart = DateTime.Now;
var data = await valueFactoryAsync(token);
var queryTime = DateTime.Now - dateQueryStart;
if (dateObsolete - DateTime.Now < minCacheTime)
dateObsolete = DateTime.Now + minCacheTime;
cache.Data = data;
cache.DateObsolete = dateObsolete;
cache.DateObsoleteTotal = dateObsolete + queryTime + minCacheTime;
caches.Add(tag, cache);
}
catch

View File

@ -79,9 +79,9 @@ namespace AsbCloudInfrastructure.Services
}
/// <inheritdoc/>
public override async Task<int> UpdateAsync(int id, TDto dto, CancellationToken token)
public override async Task<int> UpdateAsync(TDto dto, CancellationToken token)
{
var result = await base.UpdateAsync(id, dto, token);
var result = await base.UpdateAsync(dto, token);
if (result > 0)
DropCache();
return result;

View File

@ -3,6 +3,7 @@ using AsbCloudDb.Model;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@ -10,7 +11,7 @@ using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services
{
#nullable enable
/// <summary>
/// CRUD сервис для работы с БД
/// </summary>
@ -93,40 +94,49 @@ namespace AsbCloudInfrastructure.Services
{
var entity = Convert(item);
entity.Id = 0;
dbSet.Add(entity);
var entry = dbSet.Add(entity);
await dbContext.SaveChangesAsync(token);
entry.State = EntityState.Detached;
return entity.Id;
}
/// <inheritdoc/>
public virtual Task<int> InsertRangeAsync(IEnumerable<TDto> items, CancellationToken token = default)
public virtual async Task<int> InsertRangeAsync(IEnumerable<TDto> items, CancellationToken token = default)
{
if (!items.Any())
return Task.FromResult(0);
return 0;
var entities = items.Select(i =>
{
var entity = Convert(i);
entity.Id = 0;
return entity;
});
dbSet.AddRange(entities);
return dbContext.SaveChangesAsync(token);
var entries = new List<Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry>(items.Count());
foreach (var entity in entities)
{
var entry = dbSet.Add(entity);
entries.Add(entry);
}
var affected = await dbContext.SaveChangesAsync(token);
entries.ForEach(e => e.State = EntityState.Detached);
return affected;
}
/// <inheritdoc/>
public virtual async Task<int> UpdateAsync(int id, TDto item, CancellationToken token = default)
public virtual async Task<int> UpdateAsync(TDto item, CancellationToken token = default)
{
var existingEntity = await dbSet
.AsNoTracking()
.FirstOrDefaultAsync(e => e.Id == id, token)
.FirstOrDefaultAsync(e => e.Id == item.Id, token)
.ConfigureAwait(false);
if (existingEntity is null)
return ICrudService<TDto>.ErrorIdNotFound;
var entity = Convert(item);
entity.Id = id;
var entry = dbSet.Update(entity);
await dbContext.SaveChangesAsync(token);
entry.State = EntityState.Detached;
return entry.Entity.Id;
}
@ -138,8 +148,10 @@ namespace AsbCloudInfrastructure.Services
.FirstOrDefault(e => e.Id == id);
if (entity == default)
return Task.FromResult(ICrudService<TDto>.ErrorIdNotFound);
dbSet.Remove(entity);
return dbContext.SaveChangesAsync(token);
var entry = dbSet.Remove(entity);
var affected = dbContext.SaveChangesAsync(token);
entry.State = EntityState.Detached;
return affected;
}
protected virtual TDto Convert(TEntity src) => src.Adapt<TDto>();

View File

@ -0,0 +1,48 @@
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services
{
#nullable enable
public class CrudWellRelatedServiceBase<TDto, TEntity> : CrudServiceBase<TDto, TEntity>, ICrudWellRelatedService<TDto>
where TDto : AsbCloudApp.Data.IId, AsbCloudApp.Data.IWellRelated
where TEntity : class, AsbCloudDb.Model.IId, AsbCloudDb.Model.IWellRelated
{
public CrudWellRelatedServiceBase(IAsbCloudDbContext context)
: base(context) { }
public CrudWellRelatedServiceBase(IAsbCloudDbContext dbContext, ISet<string> includes)
: base(dbContext, includes) { }
public CrudWellRelatedServiceBase(IAsbCloudDbContext context, Func<DbSet<TEntity>, IQueryable<TEntity>> makeQuery)
: base(context, makeQuery) { }
public async Task<IEnumerable<TDto>> GetAllAsync(int idWell, CancellationToken token)
{
var entities = await GetQuery()
.Where(e => e.IdWell == idWell)
.ToListAsync(token);
var dtos = entities.Select(Convert).ToList();
return dtos;
}
public async Task<IEnumerable<TDto>> GetAllAsync(IEnumerable<int> idsWells, CancellationToken token)
{
if (!idsWells.Any())
return Enumerable.Empty<TDto>();
var entities = await GetQuery()
.Where(e => idsWells.Contains( e.IdWell))
.ToListAsync(token);
var dtos = entities.Select(Convert).ToList();
return dtos;
}
}
#nullable disable
}

View File

@ -11,7 +11,7 @@ using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services
{
public class DrillFlowChartService : CrudServiceBase<DrillFlowChartDto, DrillFlowChart>,
public class DrillFlowChartService : CrudWellRelatedServiceBase<DrillFlowChartDto, DrillFlowChart>,
IDrillFlowChartService
{
private readonly IAsbCloudDbContext db;
@ -29,13 +29,13 @@ namespace AsbCloudInfrastructure.Services
{
var timezone = wellService.GetTimezone(idWell);
var updateFromUtc = updateFrom.ToUtcDateTimeOffset(timezone.Hours);
var entities = await (from p in db.DrillFlowChart
where p.IdWell == idWell &&
p.LastUpdate > updateFromUtc
orderby p.DepthStart, p.Id
select p)
.ToListAsync(token)
.ConfigureAwait(false);
var entities = await GetQuery()
.Where(e => e.IdWell == idWell)
.Where(e => e.LastUpdate == updateFromUtc)
.OrderBy(e => e.DepthStart)
.ThenBy(e => e.Id)
.ToListAsync(token)
.ConfigureAwait(false);
var dtos = entities.Select(entity =>
{
@ -46,36 +46,19 @@ namespace AsbCloudInfrastructure.Services
return dtos;
}
public async Task<int> InsertAsync(int idWell, DrillFlowChartDto dto,
public override async Task<int> InsertAsync(DrillFlowChartDto dto,
CancellationToken token = default)
{
dto.IdWell = idWell;
dto.LastUpdate = DateTime.UtcNow;
var result = await base.InsertAsync(dto, token).ConfigureAwait(false);
var result = await base.InsertAsync(dto, token);
return result;
}
public async Task<int> InsertRangeAsync(int idWell, IEnumerable<DrillFlowChartDto> dtos,
public override async Task<int> UpdateAsync(DrillFlowChartDto dto,
CancellationToken token = default)
{
foreach (var dto in dtos)
{
dto.IdWell = idWell;
dto.LastUpdate = DateTime.UtcNow;
}
var result = await base.InsertRangeAsync(dtos, token).ConfigureAwait(false);
return result;
}
public async Task<int> UpdateAsync(int idWell, int idDto, DrillFlowChartDto dto,
CancellationToken token = default)
{
dto.IdWell = idWell;
dto.LastUpdate = DateTime.UtcNow;
var result = await base.UpdateAsync(idDto, dto, token).ConfigureAwait(false);
var result = await base.UpdateAsync(dto, token);
return result;
}
}

View File

@ -139,7 +139,7 @@ namespace AsbCloudInfrastructure.Services
{
dto.IdWell = idWell;
var result = await base.UpdateAsync(dtoId, dto, token).ConfigureAwait(false);
var result = await base.UpdateAsync(dto, token).ConfigureAwait(false);
return result;
}
}

View File

@ -97,20 +97,8 @@ namespace AsbCloudInfrastructure.Services
return dtos;
}
public async Task<int> UpdateAsync(int id, UserRoleDto dto, CancellationToken token = default)
public async Task<int> UpdateAsync(UserRoleDto dto, CancellationToken token = default)
{
if (dto.Id != id)
{
var exist = await cacheUserRoles.ContainsAsync(i => i.Id == dto.Id, token)
.ConfigureAwait(false);
if (exist)
return ICrudService<UserRoleDto>.ErrorIdNotFound;
await cacheUserRoles.RemoveAsync(i => i.Id == id, token)
.ConfigureAwait(false);
}
var entity = Convert(dto);
await UpdatePermissionsAsync(dto, token);
await UpdateIncludedRolesAsync(dto, token);

View File

@ -97,23 +97,19 @@ namespace AsbCloudInfrastructure.Services
return dto;
}
public async Task<int> UpdateAsync(int id, UserExtendedDto dto, CancellationToken token = default)
public async Task<int> UpdateAsync(UserExtendedDto dto, CancellationToken token = default)
{
if (id <= 1)
throw new ArgumentInvalidException($"Invalid id {id}. You can't edit this user.", nameof(id));
if (dto.Id <= 1)
throw new ArgumentInvalidException($"Invalid id {dto.Id}. You can't edit this user.", nameof(dto));
var oldUser = await cacheUsers.FirstOrDefaultAsync(u => u.Id == id, token);
var oldUser = await cacheUsers.FirstOrDefaultAsync(u => u.Id == dto.Id, token);
if (oldUser.Login != dto.Login)
await AssertLoginIsBusyAsync(dto.Login, token);
var userRoles = await RoleService.GetByNamesAsync(dto.RoleNames, token).ConfigureAwait(false);
await UpdateRolesCacheForUserAsync(id, userRoles, token);
await UpdateRolesCacheForUserAsync(dto.Id, userRoles, token);
var entity = Convert(dto);
if (dto.Id == 0)
entity.Id = id;
else if (dto.Id != id)
throw new ArgumentInvalidException($"Invalid userDto.id it mast be 0 or {id}", nameof(dto));
var result = await cacheUsers.UpsertAsync(entity, token)
.ConfigureAwait(false);

View File

@ -117,7 +117,7 @@ namespace AsbCloudInfrastructure.Services
throw new NotImplementedException();
}
public override async Task<int> UpdateAsync(int idWell, WellDto dto,
public override async Task<int> UpdateAsync(WellDto dto,
CancellationToken token = default)
{
if (dto.IdWellType is < 1 or > 2)
@ -126,24 +126,21 @@ namespace AsbCloudInfrastructure.Services
if (dto.IdState is < 0 or > 2)
throw new ArgumentInvalidException("Текущее состояние работы скважины указано неправильно.", nameof(dto));
if (dto.Id != idWell)
throw new ArgumentInvalidException($"Нельзя поменять id для скважины: {idWell} => {dto.Id}.", nameof(dto));
var oldRelations = (await GetCacheRelationCompanyWellAsync(token))
.Where(r => r.IdWell == idWell);
.Where(r => r.IdWell == dto.Id);
if (dto.Companies.Count() != oldRelations.Count() ||
dto.Companies.Any(c => !oldRelations.Any(oldC => oldC.IdCompany == c.Id)))
{
dbContext.RelationCompaniesWells
.RemoveRange(dbContext.RelationCompaniesWells
.Where(r => r.IdWell == idWell));
.Where(r => r.IdWell == dto.Id));
var newRelations = dto.Companies.Select(c => new RelationCompanyWell { IdWell = idWell, IdCompany = c.Id });
var newRelations = dto.Companies.Select(c => new RelationCompanyWell { IdWell = dto.Id, IdCompany = c.Id });
dbContext.RelationCompaniesWells.AddRange(newRelations);
}
var result = await base.UpdateAsync(idWell, dto, token);
var result = await base.UpdateAsync(dto, token);
return result;
}

View File

@ -0,0 +1,95 @@
using AsbCloudApp.Services;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace AsbCloudWebApi.Tests.ServicesTests
{
public abstract class CrudServiceTestAbstract<TDto>
where TDto: AsbCloudApp.Data.IId
{
private readonly ICrudService<TDto> service;
public CrudServiceTestAbstract()
{
AsbCloudInfrastructure.DependencyInjection.MapsterSetup();
service = MakeService();
}
protected abstract ICrudService<TDto> MakeService();
protected abstract TDto MakeNewItem();
[Fact]
public async Task<int> Insert()
{
var newItem = MakeNewItem();
var id = await service.InsertAsync(newItem, CancellationToken.None);
Assert.True(id > 0);
return id;
}
[Fact]
public async Task InsertRange()
{
var items = new TDto[2];
items[0] = MakeNewItem();
items[1] = MakeNewItem();
var count = await service.InsertRangeAsync(items, CancellationToken.None);
Assert.Equal(2, count);
}
[Fact]
public async Task GetById()
{
var id = await Insert();
var gotItem = await service.GetAsync(id, CancellationToken.None);
Assert.True(id > 0);
Assert.Equal(id, gotItem.Id);
}
[Fact]
public async Task GetAll()
{
var items = await service.GetAllAsync(CancellationToken.None);
var count = items.Count();
await Insert();
var newItems = await service.GetAllAsync(CancellationToken.None);
var newCount = newItems.Count();
Assert.True(newCount > 0);
Assert.Equal(count + 1, newCount);
}
[Fact]
public async Task UpdateAsync_returns_notfound()
{
var item = MakeNewItem();
item.Id = int.MaxValue - 1;
var updatedId = await service.UpdateAsync(item, CancellationToken.None);
Assert.True(updatedId < 0);
}
[Fact]
public async Task UpdateAsync()
{
var newItem = MakeNewItem();
newItem.Id = await service.InsertAsync(newItem, CancellationToken.None);
var item = MakeNewItem();
item.Id = newItem.Id;
var updatedId = await service.UpdateAsync(item, CancellationToken.None);
Assert.True(newItem.Id > 0);
Assert.Equal(newItem.Id, updatedId);
}
[Fact]
public async Task DeleteAsync()
{
var newItem = MakeNewItem();
var id = await service.InsertAsync(newItem, CancellationToken.None);
var deletedId = await service.DeleteAsync(id, CancellationToken.None);
Assert.True(id > 0);
Assert.Equal(id, deletedId);
}
}
}

View File

@ -0,0 +1,28 @@
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services;
namespace AsbCloudWebApi.Tests.ServicesTests
{
public class DepositCrudCacheServiceTest : CrudServiceTestAbstract<DepositDto>
{
protected override DepositDto MakeNewItem()
{
var item = new DepositDto
{
Caption = "test deposit",
Latitude = 1,
Longitude = 2,
Timezone = new SimpleTimezoneDto { Hours = 5, TimezoneId = "test Never-land"}
};
return item;
}
protected override ICrudService<DepositDto> MakeService()
{
var dbContext = TestHelpter.MakeTestContext();
return new CrudCacheServiceBase<DepositDto, Deposit>(dbContext);
}
}
}

View File

@ -76,7 +76,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
//Обновляем
drillerObj.Id = driller.Id;
drillerObj.Name = "Исправлено";
await service.UpdateAsync(driller.Id, drillerObj, CancellationToken.None);
await service.UpdateAsync(drillerObj, CancellationToken.None);
var newCount = (await service.GetAllAsync(CancellationToken.None)).Count();
Assert.Equal(newCount, oldCount);
}

View File

@ -15,25 +15,22 @@ namespace AsbCloudWebApi.Tests.ServicesTests;
public class EventServiceTest
{
private readonly AsbCloudDbContext context;
private readonly CacheDb cacheDb;
private readonly Mock<ITelemetryService> telemetryService;
private readonly CacheDb cacheDb;
private readonly EventService service;
public EventServiceTest()
{
context = TestHelpter.MakeTestContext();
cacheDb = new CacheDb();
telemetryService = new Mock<ITelemetryService>();
telemetryService.Setup(s => s.GetOrCreateTelemetryIdByUid(It.IsAny<string>()))
.Returns(1);
context.TelemetryEvents.RemoveRange(context.TelemetryEvents);
context.SaveChanges();
var telemetryTracker = new Mock<ITelemetryTracker>();
var imezoneServiceMock = new Mock<ITimezoneService>();
var telemetryService = new TelemetryService(context, telemetryTracker.Object, imezoneServiceMock.Object, cacheDb);
service = new EventService(context, cacheDb, telemetryService);
}
[Fact]
public async Task It_should_save_two_telemetry_events()
public async Task Upsert_telemetry_events()
{
var service = new EventService(context, cacheDb, telemetryService.Object);
var dtos = new List<EventDto>
{
new EventDto {Id = 1, IdCategory = 1, Message = "Test message 1"},

View File

@ -105,7 +105,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
var dto = MakeScheduleDto();
dto.Id = 1;
dto.DrillEnd = dto.DrillEnd.AddHours(-3);
await scheduleService.UpdateAsync(dto.Id, dto, CancellationToken.None);
await scheduleService.UpdateAsync(dto, CancellationToken.None);
var newCount = (await scheduleService.GetAllAsync(CancellationToken.None)).Count();
Assert.Equal(newCount, oldCount);
}
@ -114,8 +114,8 @@ namespace AsbCloudWebApi.Tests.ServicesTests
public async Task GetDriller_by_workTime_shift1()
{
var dto = MakeScheduleDto();
//dto.ShiftStart = new TimeOnly(8, 00);
//dto.ShiftEnd = new TimeOnly(20, 00);
dto.ShiftStart = new TimeOnly(8, 00);
dto.ShiftEnd = new TimeOnly(20, 00);
var id = await scheduleService.InsertAsync(dto, CancellationToken.None);
var drillerWorkTime = new DateTime(
dto.DrillStart.Year,
@ -130,8 +130,8 @@ namespace AsbCloudWebApi.Tests.ServicesTests
public async Task GetDriller_by_workTime_shift2()
{
var dto = MakeScheduleDto();
//dto.ShiftStart = new TimeOnly(20, 00);
//dto.ShiftEnd = new TimeOnly(8, 00);
dto.ShiftStart = new TimeOnly(20, 00);
dto.ShiftEnd = new TimeOnly(8, 00);
var id = await scheduleService.InsertAsync(dto, CancellationToken.None);
var drillerWorkTime = new DateTime(
dto.DrillStart.Year,

View File

@ -148,7 +148,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
Id = updateId,
Caption = "role 2 level 1"
};
var id = await service.UpdateAsync(1_000_002, modRole, CancellationToken.None);
var id = await service.UpdateAsync(modRole, CancellationToken.None);
Assert.Equal(updateId, id);
}
@ -163,7 +163,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
Caption = "role 2 level 1",
Permissions = new[] { new PermissionDto { Id = 2_000_001 } },
};
var id = await service.UpdateAsync(1_000_002, modRole, CancellationToken.None);
var id = await service.UpdateAsync(modRole, CancellationToken.None);
var entity = await service.GetAsync(id);
Assert.Equal(modRole.Permissions.Count(), entity.Permissions.Count());
}
@ -179,7 +179,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
Caption = "role 2 level 1",
Roles = new[] { new UserRoleDto { Id = 1_000_001 } }
};
var id = await service.UpdateAsync(1_000_002, modRole, CancellationToken.None);
var id = await service.UpdateAsync(modRole, CancellationToken.None);
var entity = await service.GetAsync(id);
Assert.Equal(modRole.Roles.Count(), entity.Roles.Count());
}

View File

@ -1,10 +1,5 @@
using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Tests
{

View File

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

View File

@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@ -16,6 +17,7 @@ namespace AsbCloudWebApi.Controllers
/// <typeparam name="T"></typeparam>
/// <typeparam name="TService"></typeparam>
[ApiController]
[Route("api/[controller]")]
[Authorize]
public abstract class CrudController<T, TService> : ControllerBase
where T : IId
@ -24,7 +26,7 @@ namespace AsbCloudWebApi.Controllers
protected readonly TService service;
public Func<T, CancellationToken, Task<bool>> InsertForbidAsync { get; protected set; } = null;
public Func<int, T, CancellationToken, Task<bool>> UpdateForbidAsync { get; protected set; } = null;
public Func<T, CancellationToken, Task<bool>> UpdateForbidAsync { get; protected set; } = null;
public Func<int, CancellationToken, Task<bool>> DeleteForbidAsync { get; protected set; } = null;
public CrudController(TService service)
@ -37,9 +39,9 @@ namespace AsbCloudWebApi.Controllers
/// </summary>
/// <param name="token">CancellationToken</param>
/// <returns>все записи</returns>
[HttpGet("all")]
[HttpGet]
[Permission]
public virtual async Task<ActionResult<IEnumerable<T>>> GetAllAsync(CancellationToken token = default)
public virtual async Task<ActionResult<IEnumerable<T>>> GetAllAsync(CancellationToken token)
{
var result = await service.GetAllAsync(token).ConfigureAwait(false);
return Ok(result);
@ -53,7 +55,7 @@ namespace AsbCloudWebApi.Controllers
/// <returns>запись</returns>
[HttpGet("{id}")]
[Permission]
public virtual async Task<ActionResult<T>> GetAsync(int id, CancellationToken token = default)
public virtual async Task<ActionResult<T>> GetAsync(int id, CancellationToken token)
{
var result = await service.GetAsync(id, token).ConfigureAwait(false);
return Ok(result);
@ -67,32 +69,54 @@ namespace AsbCloudWebApi.Controllers
/// <returns>id</returns>
[HttpPost]
[Permission]
public virtual async Task<ActionResult<int>> InsertAsync([FromBody] T value, CancellationToken token = default)
public virtual async Task<ActionResult<int>> InsertAsync([FromBody] T value, CancellationToken token)
{
if (InsertForbidAsync is not null && await InsertForbidAsync(value, token))
Forbid();
return Forbid();
var result = await service.InsertAsync(value, token).ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Добавить несколько записей<br/>
/// При невозможности добавить любую из записей, все не будут добавлены.
/// </summary>
/// <param name="values">записи</param>
/// <param name="token"></param>
/// <returns>id</returns>
[HttpPost("range")]
[Permission]
public virtual async Task<ActionResult<int>> InsertRangeAsync([FromBody] IEnumerable<T> values, CancellationToken token)
{
if (!values.Any())
return BadRequest("there is no values to add");
if (InsertForbidAsync is not null)
foreach (var value in values)
if(await InsertForbidAsync(value, token))
return Forbid();
var result = await service.InsertRangeAsync(values, token).ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Редактировать запись по id
/// </summary>
/// <param name="id">id записи</param>
/// <param name="value">запись</param>
/// <param name="token"></param>
/// <returns>1 - успешно отредактировано, 0 - нет</returns>
[HttpPut("{id}")]
[HttpPut]
[Permission]
public virtual async Task<ActionResult<int>> UpdateAsync(int id, [FromBody] T value, CancellationToken token = default)
public virtual async Task<ActionResult<int>> UpdateAsync([FromBody] T value, CancellationToken token)
{
if (UpdateForbidAsync is not null && await UpdateForbidAsync(id, value, token))
Forbid();
if (UpdateForbidAsync is not null && await UpdateForbidAsync(value, token))
return Forbid();
var result = await service.UpdateAsync(id, value, token).ConfigureAwait(false);
var result = await service.UpdateAsync(value, token).ConfigureAwait(false);
if (result == ICrudService<T>.ErrorIdNotFound)
return BadRequest($"id:{id} does not exist in the db");
return BadRequest($"id:{value.Id} does not exist in the db");
return Ok(result);
}
@ -103,15 +127,15 @@ namespace AsbCloudWebApi.Controllers
/// <param name="token"></param>
/// <returns>1 - успешно удалено, 0 - нет</returns>
[HttpDelete("{id}")]
public virtual async Task<ActionResult<int>> DeleteAsync(int id, CancellationToken token = default)
public virtual async Task<ActionResult<int>> DeleteAsync(int id, CancellationToken token)
{
if (DeleteForbidAsync is not null && await DeleteForbidAsync(id, token))
Forbid();
return Forbid();
var result = await service.DeleteAsync(id, token).ConfigureAwait(false);
if (result == ICrudService<T>.ErrorIdNotFound)
return NoContent();
return Ok(result);
}
}
}

View File

@ -0,0 +1,134 @@
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace AsbCloudWebApi.Controllers
{
/// <summary>
/// CRUD контроллер для админки.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TService"></typeparam>
[ApiController]
[Route("api/[controller]")]
[Authorize]
public abstract class CrudWellRelatedController<T, TService> : CrudController<T, TService>
where T : IId, IWellRelated
where TService : ICrudWellRelatedService<T>
{
private readonly IWellService wellService;
protected CrudWellRelatedController(IWellService wellService, TService service)
: base(service)
{
this.wellService = wellService;
}
/// <summary>
/// Получение всех записей, доступных компании пользователя.
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet]
public override async Task<ActionResult<IEnumerable<T>>> GetAllAsync(CancellationToken token)
{
var idCompany = User.GetCompanyId();
if (idCompany is null)
return Forbid();
var wells = await wellService.GetWellsByCompanyAsync((int)idCompany, token);
if (!wells.Any())
return NoContent();
var idsWells = wells.Select(w => w.Id);
var result = await service.GetAllAsync(idsWells, token);
return Ok(result);
}
/// <summary>
/// Получение всех записей, для скважины.
/// </summary>
/// <param name="idWell"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet("well/{idWell}")]
public async Task<ActionResult<IEnumerable<T>>> GetAllAsync(int idWell, CancellationToken token)
{
if (!await UserHasAccesToWellAsync(idWell, token))
return Forbid();
var result = await service.GetAllAsync(idWell, token);
return Ok(result);
}
/// <inheritdoc/>
[HttpGet("{id}")]
public override async Task<ActionResult<T>> GetAsync(int id, CancellationToken token)
{
var actionResult = await base.GetAsync(id, token);
var result = actionResult.Value;
if(!await UserHasAccesToWellAsync(result.IdWell, token))
return Forbid();
return Ok(result);
}
/// <inheritdoc/>
[HttpPost]
public override async Task<ActionResult<int>> InsertAsync([FromBody] T value, CancellationToken token)
{
if (!await UserHasAccesToWellAsync(value.IdWell, token))
return Forbid();
return await base.InsertAsync(value, token);
}
/// <inheritdoc/>
[HttpPost("range")]
public override async Task<ActionResult<int>> InsertRangeAsync([FromBody] IEnumerable<T> values, CancellationToken token)
{
var idsWells = values.Select(v => v.IdWell).Distinct();
foreach (var idWell in idsWells)
if (!await UserHasAccesToWellAsync(idWell, token))
return Forbid();
return await base.InsertRangeAsync(values, token);
}
/// <inheritdoc/>
[HttpPut]
public override async Task<ActionResult<int>> UpdateAsync([FromBody] T value, CancellationToken token)
{
if (!await UserHasAccesToWellAsync(value.IdWell, token))
return Forbid();
return await base.UpdateAsync(value, token);
}
[HttpDelete("{id}")]
public override async Task<ActionResult<int>> DeleteAsync(int id, CancellationToken token)
{
var item = await service.GetAsync(id, token);
if(item is null)
return NoContent();
if (!await UserHasAccesToWellAsync(item.IdWell, token))
return Forbid();
return await base.DeleteAsync(id, token);
}
protected async Task<bool> UserHasAccesToWellAsync(int idWell, CancellationToken token)
{
var idCompany = User.GetCompanyId();
if (idCompany is not null &&
await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token)
.ConfigureAwait(false))
return true;
return false;
}
}
}

View File

@ -13,47 +13,21 @@ namespace AsbCloudWebApi.Controllers
/// Контроллер для коридоров бурения на панели
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class DrillFlowChartController : ControllerBase
public class DrillFlowChartController : CrudWellRelatedController<DrillFlowChartDto, IDrillFlowChartService>
{
private readonly IDrillFlowChartService drillFlowChartService;
private readonly ITelemetryService telemetryService;
private readonly IWellService wellService;
public DrillFlowChartController(IDrillFlowChartService drillFlowChartService,
ITelemetryService telemetryService, IWellService wellService)
public DrillFlowChartController(IWellService wellService, IDrillFlowChartService service,
ITelemetryService telemetryService)
:base(wellService, service)
{
this.drillFlowChartService = drillFlowChartService;
this.telemetryService = telemetryService;
this.wellService = wellService;
}
/// <summary>
/// Возвращает все значения для коридоров бурения по id скважины
/// </summary>
/// <param name="idWell"> id скважины </param>
/// <param name="updateFrom"> Дата, с которой следует искать новые параметры </param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns> Список параметров для коридоров бурения </returns>
[HttpGet]
[Route("api/well/{idWell}/drillFlowChart")]
[Permission]
[ProducesResponseType(typeof(IEnumerable<DrillFlowChartDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetAsync(int idWell, DateTime updateFrom = default,
CancellationToken token = default)
{
var idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false))
return Forbid();
var dto = await drillFlowChartService.GetAllAsync(idWell,
updateFrom, token);
return Ok(dto);
}
/// <summary>
/// Возвращает все значения для коридоров бурения по uid панели
/// </summary>
@ -62,7 +36,7 @@ namespace AsbCloudWebApi.Controllers
/// <param name="token"> Токен отмены задачи </param>
/// <returns> Список параметров для коридоров бурения </returns>
[HttpGet]
[Route("api/telemetry/{uid}/drillFlowChart")]
[Route("/api/telemetry/{uid}/drillFlowChart")]
[AllowAnonymous]
[ProducesResponseType(typeof(IEnumerable<DrillFlowChartDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetByTelemetryAsync(string uid, DateTime updateFrom = default, CancellationToken token = default)
@ -71,113 +45,11 @@ namespace AsbCloudWebApi.Controllers
if (idWell is null)
return BadRequest($"Wrong uid {uid}");
var dto = await drillFlowChartService.GetAllAsync((int)idWell,
var dto = await service.GetAllAsync((int)idWell,
updateFrom, token);
return Ok(dto);
}
/// <summary>
/// Сохраняет значения для коридоров бурения
/// </summary>
/// <param name="idWell"> id скважины </param>
/// <param name="drillFlowChartDto"> Параметры коридоров бурения</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns></returns>
[HttpPost]
[Route("api/well/{idWell}/drillFlowChart")]
[Permission]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> InsertAsync(int idWell,
DrillFlowChartDto drillFlowChartDto, CancellationToken token = default)
{
var idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false))
return Forbid();
var result = await drillFlowChartService.InsertAsync(idWell, drillFlowChartDto, token);
return Ok(result);
}
/// <summary>
/// Добавляет массив объектов коридоров бурения
/// </summary>
/// <param name="idWell"> id скважины </param>
/// <param name="drillFlowChartParams"> Массив объектов параметров коридоров бурения</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns></returns>
[HttpPost]
[Route("api/well/{idWell}/drillFlowChart/range")]
[Permission]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> InsertRangeAsync(int idWell,
IEnumerable<DrillFlowChartDto> drillFlowChartParams, CancellationToken token = default)
{
var idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false))
return Forbid();
var result = await drillFlowChartService.InsertRangeAsync(idWell, drillFlowChartParams,
token);
return Ok(result);
}
/// <summary>
/// Изменяет значения выбранного коридора бурения
/// </summary>
/// <param name="idWell"> id скважины </param>
/// <param name="drillFlowChart"> Параметры коридоров бурения</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns></returns>
[HttpPut]
[Route("api/well/{idWell}/drillFlowChart")]
[Permission]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> EditAsync(int idWell,
DrillFlowChartDto drillFlowChart, CancellationToken token = default)
{
var idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false))
return Forbid();
var result = await drillFlowChartService.UpdateAsync(idWell, drillFlowChart.Id,
drillFlowChart, token);
return Ok(result);
}
/// <summary>
/// Удаляет значения выбранного коридора бурения
/// </summary>
/// <param name="idWell"> id скважины </param>
/// <param name="drillFlowChartParamsId"> Id объекта коридоров бурения</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns></returns>
[HttpDelete]
[Route("api/well/{idWell}/drillFlowChart")]
[Permission]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> DeleteAsync(int idWell,
int drillFlowChartParamsId, CancellationToken token = default)
{
var idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false))
return Forbid();
var result = await drillFlowChartService.DeleteAsync(drillFlowChartParamsId,
token);
return Ok(result);
}
}
}

View File

@ -34,16 +34,11 @@ namespace AsbCloudWebApi.Controllers
var idCompany = User.GetCompanyId();
if (idCompany is null)
{
return NoContent();
}
var wells = await wellService.GetWellsByCompanyAsync((int)idCompany,
token).ConfigureAwait(false);
if (wells is null || !wells.Any())
return NoContent();
return Ok(wells);
}
@ -61,7 +56,7 @@ namespace AsbCloudWebApi.Controllers
var idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync(idCompany ?? default, idWell, token).ConfigureAwait(false))
return NoContent();
return Forbid();
var well = await wellService.GetAsync(idWell,
token).ConfigureAwait(false);
@ -72,25 +67,24 @@ namespace AsbCloudWebApi.Controllers
/// <summary>
/// Редактирует указанные поля скважины
/// </summary>
/// <param name="idWell"> Id скважины </param>
/// <param name="dto"> Объект параметров скважины.
/// IdWellType: 1 - Наклонно-направленная, 2 - Горизонтальная.
/// State: 0 - Неизвестно, 1 - В работе, 2 - Завершена.</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns></returns>
[HttpPut("{idWell}")]
[HttpPut]
[Permission]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> UpdateWellAsync(int idWell, WellDto dto,
public async Task<IActionResult> UpdateWellAsync(WellDto dto,
CancellationToken token = default)
{
var idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false))
dto.Id, token).ConfigureAwait(false))
return Forbid();
var result = await wellService.UpdateAsync(idWell, dto, token)
var result = await wellService.UpdateAsync(dto, token)
.ConfigureAwait(false);
return Ok(result);