Crud services, controllers refactoring. Not tested version of new API.

This commit is contained in:
ngfrolov 2022-06-09 11:19:52 +05:00
parent 9ae268f4c5
commit dd2a777d3d
24 changed files with 319 additions and 252 deletions

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,11 +59,10 @@ 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>
/// Удалить запись

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

@ -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>
@ -115,16 +116,15 @@ namespace AsbCloudInfrastructure.Services
}
/// <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);
return entry.Entity.Id;

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

@ -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);