diff --git a/AsbCloudApp/Exceptions/ForbidException.cs b/AsbCloudApp/Exceptions/ForbidException.cs
index a0858d43..fccf1ca4 100644
--- a/AsbCloudApp/Exceptions/ForbidException.cs
+++ b/AsbCloudApp/Exceptions/ForbidException.cs
@@ -7,9 +7,15 @@ namespace AsbCloudApp.Exceptions
///
public class ForbidException : Exception
{
+ ///
+ /// Access denied exception
+ ///
public ForbidException()
: base() { }
+ ///
+ /// Access denied exception
+ ///
public ForbidException(string message)
: base(message) { }
diff --git a/AsbCloudApp/Services/ICrudService.cs b/AsbCloudApp/Services/ICrudService.cs
index 8d5edb8d..859e8fd4 100644
--- a/AsbCloudApp/Services/ICrudService.cs
+++ b/AsbCloudApp/Services/ICrudService.cs
@@ -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
///
/// Отредактировать запись
///
- ///
///
///
/// если больше 0 - Id записи, если меньше 0 - код ошибки
- Task UpdateAsync(int id, Tdto item, CancellationToken token);
+ Task UpdateAsync(Tdto item, CancellationToken token);
///
/// Удалить запись
diff --git a/AsbCloudApp/Services/ICrudWellRelatedService.cs b/AsbCloudApp/Services/ICrudWellRelatedService.cs
new file mode 100644
index 00000000..8c350bf3
--- /dev/null
+++ b/AsbCloudApp/Services/ICrudWellRelatedService.cs
@@ -0,0 +1,33 @@
+using AsbCloudApp.Data;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace AsbCloudApp.Services
+{
+ ///
+ /// Сервис получения, добавления, изменения, удаления данных
+ /// Для сущностей относящихся к скважине
+ ///
+ ///
+ public interface ICrudWellRelatedService : ICrudService
+ where Tdto: IId, IWellRelated
+ {
+ ///
+ /// Получение всех записей по скважине
+ ///
+ /// id скважины
+ ///
+ /// emptyList if nothing found
+ Task> GetAllAsync(int idWell, CancellationToken token);
+
+ ///
+ /// Получение всех записей по нескольким скважинам
+ ///
+ /// id скважин
+ ///
+ /// emptyList if nothing found
+ Task> GetAllAsync(IEnumerable idsWells, CancellationToken token);
+ }
+#nullable disable
+}
\ No newline at end of file
diff --git a/AsbCloudApp/Services/IDrillFlowChartService.cs b/AsbCloudApp/Services/IDrillFlowChartService.cs
index 68102427..693cab85 100644
--- a/AsbCloudApp/Services/IDrillFlowChartService.cs
+++ b/AsbCloudApp/Services/IDrillFlowChartService.cs
@@ -6,18 +6,9 @@ using System.Threading.Tasks;
namespace AsbCloudApp.Services
{
- public interface IDrillFlowChartService : ICrudService
+ public interface IDrillFlowChartService : ICrudWellRelatedService
{
Task> GetAllAsync(int idWell,
DateTime updateFrom, CancellationToken token = default);
-
- Task InsertAsync(int idWell, DrillFlowChartDto dto,
- CancellationToken token = default);
-
- Task InsertRangeAsync(int idWell, IEnumerable dtos,
- CancellationToken token = default);
-
- Task UpdateAsync(int idWell, int idDto, DrillFlowChartDto dto,
- CancellationToken token = default);
}
}
\ No newline at end of file
diff --git a/AsbCloudDb/Model/DrillFlowChart.cs b/AsbCloudDb/Model/DrillFlowChart.cs
index 71bd3aa5..b7fa904a 100644
--- a/AsbCloudDb/Model/DrillFlowChart.cs
+++ b/AsbCloudDb/Model/DrillFlowChart.cs
@@ -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")]
diff --git a/AsbCloudDb/Model/FileInfo.cs b/AsbCloudDb/Model/FileInfo.cs
index 6e05e2d2..923bc3ec 100644
--- a/AsbCloudDb/Model/FileInfo.cs
+++ b/AsbCloudDb/Model/FileInfo.cs
@@ -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")]
diff --git a/AsbCloudDb/Model/IIdWell.cs b/AsbCloudDb/Model/IWellRelated.cs
similarity index 57%
rename from AsbCloudDb/Model/IIdWell.cs
rename to AsbCloudDb/Model/IWellRelated.cs
index d800f74b..f61aeae6 100644
--- a/AsbCloudDb/Model/IIdWell.cs
+++ b/AsbCloudDb/Model/IWellRelated.cs
@@ -3,8 +3,11 @@
///
/// For well related entities
///
- public interface IIdWell
+ public interface IWellRelated
{
+ ///
+ /// Id скважины
+ ///
int IdWell { get; set; }
}
}
diff --git a/AsbCloudDb/Model/RelationCompanyWell.cs b/AsbCloudDb/Model/RelationCompanyWell.cs
index e7f5c0b5..0e7bdccd 100644
--- a/AsbCloudDb/Model/RelationCompanyWell.cs
+++ b/AsbCloudDb/Model/RelationCompanyWell.cs
@@ -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; }
diff --git a/AsbCloudDb/Model/ReportProperty.cs b/AsbCloudDb/Model/ReportProperty.cs
index a08b9488..33fd70f1 100644
--- a/AsbCloudDb/Model/ReportProperty.cs
+++ b/AsbCloudDb/Model/ReportProperty.cs
@@ -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")]
diff --git a/AsbCloudDb/Model/SetpointsRequest.cs b/AsbCloudDb/Model/SetpointsRequest.cs
index a1f62808..59640b2a 100644
--- a/AsbCloudDb/Model/SetpointsRequest.cs
+++ b/AsbCloudDb/Model/SetpointsRequest.cs
@@ -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")]
diff --git a/AsbCloudDb/Model/WellComposite.cs b/AsbCloudDb/Model/WellComposite.cs
index a364d0e0..acf6aaf4 100644
--- a/AsbCloudDb/Model/WellComposite.cs
+++ b/AsbCloudDb/Model/WellComposite.cs
@@ -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; }
diff --git a/AsbCloudInfrastructure/Services/CrudCacheServiceBase.cs b/AsbCloudInfrastructure/Services/CrudCacheServiceBase.cs
index d49100c1..82c19335 100644
--- a/AsbCloudInfrastructure/Services/CrudCacheServiceBase.cs
+++ b/AsbCloudInfrastructure/Services/CrudCacheServiceBase.cs
@@ -79,9 +79,9 @@ namespace AsbCloudInfrastructure.Services
}
///
- public override async Task UpdateAsync(int id, TDto dto, CancellationToken token)
+ public override async Task 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;
diff --git a/AsbCloudInfrastructure/Services/CrudServiceBase.cs b/AsbCloudInfrastructure/Services/CrudServiceBase.cs
index f5f6ff3f..57cda971 100644
--- a/AsbCloudInfrastructure/Services/CrudServiceBase.cs
+++ b/AsbCloudInfrastructure/Services/CrudServiceBase.cs
@@ -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
+
///
/// CRUD сервис для работы с БД
///
@@ -115,16 +116,15 @@ namespace AsbCloudInfrastructure.Services
}
///
- public virtual async Task UpdateAsync(int id, TDto item, CancellationToken token = default)
+ public virtual async Task 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.ErrorIdNotFound;
var entity = Convert(item);
- entity.Id = id;
var entry = dbSet.Update(entity);
await dbContext.SaveChangesAsync(token);
return entry.Entity.Id;
diff --git a/AsbCloudInfrastructure/Services/CrudWellRelatedServiceBase.cs b/AsbCloudInfrastructure/Services/CrudWellRelatedServiceBase.cs
new file mode 100644
index 00000000..3f34a245
--- /dev/null
+++ b/AsbCloudInfrastructure/Services/CrudWellRelatedServiceBase.cs
@@ -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 : CrudServiceBase, ICrudWellRelatedService
+ 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 includes)
+ : base(dbContext, includes) { }
+
+ public CrudWellRelatedServiceBase(IAsbCloudDbContext context, Func, IQueryable> makeQuery)
+ : base(context, makeQuery) { }
+
+ public async Task> 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> GetAllAsync(IEnumerable idsWells, CancellationToken token)
+ {
+ if (!idsWells.Any())
+ return Enumerable.Empty();
+
+ var entities = await GetQuery()
+ .Where(e => idsWells.Contains( e.IdWell))
+ .ToListAsync(token);
+ var dtos = entities.Select(Convert).ToList();
+ return dtos;
+ }
+ }
+#nullable disable
+}
diff --git a/AsbCloudInfrastructure/Services/DrillFlowChartService.cs b/AsbCloudInfrastructure/Services/DrillFlowChartService.cs
index c9e927ea..8d5a2f1d 100644
--- a/AsbCloudInfrastructure/Services/DrillFlowChartService.cs
+++ b/AsbCloudInfrastructure/Services/DrillFlowChartService.cs
@@ -11,7 +11,7 @@ using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services
{
- public class DrillFlowChartService : CrudServiceBase,
+ public class DrillFlowChartService : CrudWellRelatedServiceBase,
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 InsertAsync(int idWell, DrillFlowChartDto dto,
+ public override async Task 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 InsertRangeAsync(int idWell, IEnumerable dtos,
+ public override async Task 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 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;
}
}
diff --git a/AsbCloudInfrastructure/Services/DrillParamsService.cs b/AsbCloudInfrastructure/Services/DrillParamsService.cs
index 00b45ca3..1b7c9f31 100644
--- a/AsbCloudInfrastructure/Services/DrillParamsService.cs
+++ b/AsbCloudInfrastructure/Services/DrillParamsService.cs
@@ -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;
}
}
diff --git a/AsbCloudInfrastructure/Services/UserRoleService.cs b/AsbCloudInfrastructure/Services/UserRoleService.cs
index 12e501ad..c3c0d48e 100644
--- a/AsbCloudInfrastructure/Services/UserRoleService.cs
+++ b/AsbCloudInfrastructure/Services/UserRoleService.cs
@@ -97,20 +97,8 @@ namespace AsbCloudInfrastructure.Services
return dtos;
}
- public async Task UpdateAsync(int id, UserRoleDto dto, CancellationToken token = default)
+ public async Task 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.ErrorIdNotFound;
-
- await cacheUserRoles.RemoveAsync(i => i.Id == id, token)
- .ConfigureAwait(false);
- }
-
var entity = Convert(dto);
await UpdatePermissionsAsync(dto, token);
await UpdateIncludedRolesAsync(dto, token);
diff --git a/AsbCloudInfrastructure/Services/UserService.cs b/AsbCloudInfrastructure/Services/UserService.cs
index 2984ebd0..a32448da 100644
--- a/AsbCloudInfrastructure/Services/UserService.cs
+++ b/AsbCloudInfrastructure/Services/UserService.cs
@@ -97,23 +97,19 @@ namespace AsbCloudInfrastructure.Services
return dto;
}
- public async Task UpdateAsync(int id, UserExtendedDto dto, CancellationToken token = default)
+ public async Task 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);
diff --git a/AsbCloudInfrastructure/Services/WellService.cs b/AsbCloudInfrastructure/Services/WellService.cs
index ffa5866f..6478a296 100644
--- a/AsbCloudInfrastructure/Services/WellService.cs
+++ b/AsbCloudInfrastructure/Services/WellService.cs
@@ -117,7 +117,7 @@ namespace AsbCloudInfrastructure.Services
throw new NotImplementedException();
}
- public override async Task UpdateAsync(int idWell, WellDto dto,
+ public override async Task 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;
}
diff --git a/AsbCloudWebApi/Controllers/AdminUserRoleController.cs b/AsbCloudWebApi/Controllers/AdminUserRoleController.cs
index 2651e66f..39ea60ef 100644
--- a/AsbCloudWebApi/Controllers/AdminUserRoleController.cs
+++ b/AsbCloudWebApi/Controllers/AdminUserRoleController.cs
@@ -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;
};
diff --git a/AsbCloudWebApi/Controllers/CrudController.cs b/AsbCloudWebApi/Controllers/CrudController.cs
index e2e9d2e6..fd6c06de 100644
--- a/AsbCloudWebApi/Controllers/CrudController.cs
+++ b/AsbCloudWebApi/Controllers/CrudController.cs
@@ -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
///
///
[ApiController]
+ [Route("api/[controller]")]
[Authorize]
public abstract class CrudController : ControllerBase
where T : IId
@@ -24,7 +26,7 @@ namespace AsbCloudWebApi.Controllers
protected readonly TService service;
public Func> InsertForbidAsync { get; protected set; } = null;
- public Func> UpdateForbidAsync { get; protected set; } = null;
+ public Func> UpdateForbidAsync { get; protected set; } = null;
public Func> DeleteForbidAsync { get; protected set; } = null;
public CrudController(TService service)
@@ -37,9 +39,9 @@ namespace AsbCloudWebApi.Controllers
///
/// CancellationToken
/// все записи
- [HttpGet("all")]
+ [HttpGet]
[Permission]
- public virtual async Task>> GetAllAsync(CancellationToken token = default)
+ public virtual async Task>> GetAllAsync(CancellationToken token)
{
var result = await service.GetAllAsync(token).ConfigureAwait(false);
return Ok(result);
@@ -53,7 +55,7 @@ namespace AsbCloudWebApi.Controllers
/// запись
[HttpGet("{id}")]
[Permission]
- public virtual async Task> GetAsync(int id, CancellationToken token = default)
+ public virtual async Task> GetAsync(int id, CancellationToken token)
{
var result = await service.GetAsync(id, token).ConfigureAwait(false);
return Ok(result);
@@ -67,32 +69,54 @@ namespace AsbCloudWebApi.Controllers
/// id
[HttpPost]
[Permission]
- public virtual async Task> InsertAsync([FromBody] T value, CancellationToken token = default)
+ public virtual async Task> 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);
}
+ ///
+ /// Добавить несколько записей
+ /// При невозможности добавить любую из записей, все не будут добавлены.
+ ///
+ /// записи
+ ///
+ /// id
+ [HttpPost("range")]
+ [Permission]
+ public virtual async Task> InsertRangeAsync([FromBody] IEnumerable 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);
+ }
+
///
/// Редактировать запись по id
///
- /// id записи
/// запись
///
/// 1 - успешно отредактировано, 0 - нет
- [HttpPut("{id}")]
+ [HttpPut]
[Permission]
- public virtual async Task> UpdateAsync(int id, [FromBody] T value, CancellationToken token = default)
+ public virtual async Task> 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.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
///
/// 1 - успешно удалено, 0 - нет
[HttpDelete("{id}")]
- public virtual async Task> DeleteAsync(int id, CancellationToken token = default)
+ public virtual async Task> 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.ErrorIdNotFound)
+ return NoContent();
return Ok(result);
}
}
-
-
}
diff --git a/AsbCloudWebApi/Controllers/CrudWellRelatedController.cs b/AsbCloudWebApi/Controllers/CrudWellRelatedController.cs
new file mode 100644
index 00000000..9677c411
--- /dev/null
+++ b/AsbCloudWebApi/Controllers/CrudWellRelatedController.cs
@@ -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
+{
+ ///
+ /// CRUD контроллер для админки.
+ ///
+ ///
+ ///
+ [ApiController]
+ [Route("api/[controller]")]
+ [Authorize]
+ public abstract class CrudWellRelatedController : CrudController
+ where T : IId, IWellRelated
+ where TService : ICrudWellRelatedService
+ {
+ private readonly IWellService wellService;
+
+ protected CrudWellRelatedController(IWellService wellService, TService service)
+ : base(service)
+ {
+ this.wellService = wellService;
+ }
+
+ ///
+ /// Получение всех записей, доступных компании пользователя.
+ ///
+ ///
+ ///
+ [HttpGet]
+ public override async Task>> 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);
+ }
+
+ ///
+ /// Получение всех записей, для скважины.
+ ///
+ ///
+ ///
+ ///
+ [HttpGet("well/{idWell}")]
+ public async Task>> GetAllAsync(int idWell, CancellationToken token)
+ {
+ if (!await UserHasAccesToWellAsync(idWell, token))
+ return Forbid();
+
+ var result = await service.GetAllAsync(idWell, token);
+ return Ok(result);
+ }
+
+ ///
+ [HttpGet("{id}")]
+ public override async Task> 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);
+ }
+
+ ///
+ [HttpPost]
+ public override async Task> InsertAsync([FromBody] T value, CancellationToken token)
+ {
+ if (!await UserHasAccesToWellAsync(value.IdWell, token))
+ return Forbid();
+ return await base.InsertAsync(value, token);
+ }
+
+ ///
+ [HttpPost("range")]
+ public override async Task> InsertRangeAsync([FromBody] IEnumerable 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);
+ }
+
+ ///
+ [HttpPut]
+ public override async Task> 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> 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 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;
+ }
+ }
+
+
+}
diff --git a/AsbCloudWebApi/Controllers/DrillFlowChartController.cs b/AsbCloudWebApi/Controllers/DrillFlowChartController.cs
index 2fcb6f07..ec0aaefd 100644
--- a/AsbCloudWebApi/Controllers/DrillFlowChartController.cs
+++ b/AsbCloudWebApi/Controllers/DrillFlowChartController.cs
@@ -13,47 +13,21 @@ namespace AsbCloudWebApi.Controllers
/// Контроллер для коридоров бурения на панели
///
[ApiController]
+ [Route("api/[controller]")]
[Authorize]
- public class DrillFlowChartController : ControllerBase
+ public class DrillFlowChartController : CrudWellRelatedController
{
- 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;
}
- ///
- /// Возвращает все значения для коридоров бурения по id скважины
- ///
- /// id скважины
- /// Дата, с которой следует искать новые параметры
- /// Токен отмены задачи
- /// Список параметров для коридоров бурения
- [HttpGet]
- [Route("api/well/{idWell}/drillFlowChart")]
- [Permission]
- [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)]
- public async Task 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);
- }
-
///
/// Возвращает все значения для коридоров бурения по uid панели
///
@@ -62,7 +36,7 @@ namespace AsbCloudWebApi.Controllers
/// Токен отмены задачи
/// Список параметров для коридоров бурения
[HttpGet]
- [Route("api/telemetry/{uid}/drillFlowChart")]
+ [Route("/api/telemetry/{uid}/drillFlowChart")]
[AllowAnonymous]
[ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)]
public async Task 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);
}
- ///
- /// Сохраняет значения для коридоров бурения
- ///
- /// id скважины
- /// Параметры коридоров бурения
- /// Токен отмены задачи
- ///
- [HttpPost]
- [Route("api/well/{idWell}/drillFlowChart")]
- [Permission]
- [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
- public async Task 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);
- }
-
- ///
- /// Добавляет массив объектов коридоров бурения
- ///
- /// id скважины
- /// Массив объектов параметров коридоров бурения
- /// Токен отмены задачи
- ///
- [HttpPost]
- [Route("api/well/{idWell}/drillFlowChart/range")]
- [Permission]
- [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
- public async Task InsertRangeAsync(int idWell,
- IEnumerable 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);
- }
-
- ///
- /// Изменяет значения выбранного коридора бурения
- ///
- /// id скважины
- /// Параметры коридоров бурения
- /// Токен отмены задачи
- ///
- [HttpPut]
- [Route("api/well/{idWell}/drillFlowChart")]
- [Permission]
- [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
- public async Task 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);
- }
-
- ///
- /// Удаляет значения выбранного коридора бурения
- ///
- /// id скважины
- /// Id объекта коридоров бурения
- /// Токен отмены задачи
- ///
- [HttpDelete]
- [Route("api/well/{idWell}/drillFlowChart")]
- [Permission]
- [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
- public async Task 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);
- }
}
}
\ No newline at end of file
diff --git a/AsbCloudWebApi/Controllers/WellController.cs b/AsbCloudWebApi/Controllers/WellController.cs
index 7e2cfb3b..46d072ea 100644
--- a/AsbCloudWebApi/Controllers/WellController.cs
+++ b/AsbCloudWebApi/Controllers/WellController.cs
@@ -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
///
/// Редактирует указанные поля скважины
///
- /// Id скважины
/// Объект параметров скважины.
/// IdWellType: 1 - Наклонно-направленная, 2 - Горизонтальная.
/// State: 0 - Неизвестно, 1 - В работе, 2 - Завершена.
/// Токен отмены задачи
///
- [HttpPut("{idWell}")]
+ [HttpPut]
[Permission]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
- public async Task UpdateWellAsync(int idWell, WellDto dto,
+ public async Task 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);