diff --git a/AsbCloudApp/Data/ClusterDto.cs b/AsbCloudApp/Data/ClusterDto.cs index 8a9a95e6..17a182ce 100644 --- a/AsbCloudApp/Data/ClusterDto.cs +++ b/AsbCloudApp/Data/ClusterDto.cs @@ -23,7 +23,7 @@ namespace AsbCloudApp.Data public double? Longitude { get; set; } /// - public SimpleTimezoneDto Timezone { get; set; } = null!; + public SimpleTimezoneDto? Timezone { get; set; } /// /// ИД месторождения, необязательный @@ -38,7 +38,7 @@ namespace AsbCloudApp.Data /// /// Список скважин куста /// - public IEnumerable Wells { get; set; } = null!; + public IEnumerable? Wells { get; set; } = null!; } #nullable disable } diff --git a/AsbCloudApp/Data/SimpleTimezoneDto.cs b/AsbCloudApp/Data/SimpleTimezoneDto.cs index 3d9dcc55..c2db8338 100644 --- a/AsbCloudApp/Data/SimpleTimezoneDto.cs +++ b/AsbCloudApp/Data/SimpleTimezoneDto.cs @@ -36,5 +36,9 @@ namespace AsbCloudApp.Data => Hours.GetHashCode() | TimezoneId.GetHashCode() | IsOverride.GetHashCode(); + + /// + public override string ToString() + => $"{TimezoneId} (UTC+{Hours:00.##})"; } } \ No newline at end of file diff --git a/AsbCloudApp/Data/TimeDto.cs b/AsbCloudApp/Data/TimeDto.cs index 969cf21f..28cb8916 100644 --- a/AsbCloudApp/Data/TimeDto.cs +++ b/AsbCloudApp/Data/TimeDto.cs @@ -55,6 +55,14 @@ namespace AsbCloudApp.Data public TimeDto() { } + /// + public TimeDto(int hour = 0, int minute = 0, int second = 0) + { + this.hour = hour; + this.minute = minute; + this.second = second; + } + /// public TimeDto(TimeOnly time) { 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..37dff698 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,18 +59,17 @@ namespace AsbCloudApp.Services /// /// Отредактировать запись /// - /// /// /// /// если больше 0 - Id записи, если меньше 0 - код ошибки - Task UpdateAsync(int id, Tdto item, CancellationToken token); + Task UpdateAsync(Tdto item, CancellationToken token); /// /// Удалить запись /// /// /// - /// если больше 0 - Id записи, если меньше 0 - код ошибки + /// количество добавленных, если меньше 0 - код ошибки Task DeleteAsync(int id, CancellationToken token); } #nullable disable 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/EfCache/EfCacheDictionaryExtensions.cs b/AsbCloudInfrastructure/EfCache/EfCacheDictionaryExtensions.cs index 9846f872..21a672f7 100644 --- a/AsbCloudInfrastructure/EfCache/EfCacheDictionaryExtensions.cs +++ b/AsbCloudInfrastructure/EfCache/EfCacheDictionaryExtensions.cs @@ -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 diff --git a/AsbCloudInfrastructure/EfCache/EfCacheExtensions.cs b/AsbCloudInfrastructure/EfCache/EfCacheExtensions.cs index e8c8a6e2..b1a9e382 100644 --- a/AsbCloudInfrastructure/EfCache/EfCacheExtensions.cs +++ b/AsbCloudInfrastructure/EfCache/EfCacheExtensions.cs @@ -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 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..c3e9fdb2 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 сервис для работы с БД /// @@ -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; } /// - public virtual Task InsertRangeAsync(IEnumerable items, CancellationToken token = default) + public virtual async Task InsertRangeAsync(IEnumerable 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(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; } /// - 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); + 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.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(); 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.Tests/ServicesTests/CrudServiceTestAbstract.cs b/AsbCloudWebApi.Tests/ServicesTests/CrudServiceTestAbstract.cs new file mode 100644 index 00000000..043af57f --- /dev/null +++ b/AsbCloudWebApi.Tests/ServicesTests/CrudServiceTestAbstract.cs @@ -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 + where TDto: AsbCloudApp.Data.IId + { + private readonly ICrudService service; + + public CrudServiceTestAbstract() + { + AsbCloudInfrastructure.DependencyInjection.MapsterSetup(); + service = MakeService(); + } + + protected abstract ICrudService MakeService(); + protected abstract TDto MakeNewItem(); + + [Fact] + public async Task 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); + } + } +} diff --git a/AsbCloudWebApi.Tests/ServicesTests/DepositCrudCacheServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/DepositCrudCacheServiceTest.cs new file mode 100644 index 00000000..d7769352 --- /dev/null +++ b/AsbCloudWebApi.Tests/ServicesTests/DepositCrudCacheServiceTest.cs @@ -0,0 +1,28 @@ +using AsbCloudApp.Data; +using AsbCloudApp.Services; +using AsbCloudDb.Model; +using AsbCloudInfrastructure.Services; + +namespace AsbCloudWebApi.Tests.ServicesTests +{ + public class DepositCrudCacheServiceTest : CrudServiceTestAbstract + { + 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 MakeService() + { + var dbContext = TestHelpter.MakeTestContext(); + return new CrudCacheServiceBase(dbContext); + } + } +} diff --git a/AsbCloudWebApi.Tests/ServicesTests/DrillerServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/DrillerServiceTest.cs index b54291b8..61cb6d49 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/DrillerServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/DrillerServiceTest.cs @@ -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); } diff --git a/AsbCloudWebApi.Tests/ServicesTests/EventServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/EventServiceTest.cs index f82aaff7..d8931261 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/EventServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/EventServiceTest.cs @@ -15,25 +15,22 @@ namespace AsbCloudWebApi.Tests.ServicesTests; public class EventServiceTest { private readonly AsbCloudDbContext context; - private readonly CacheDb cacheDb; - private readonly Mock telemetryService; + private readonly CacheDb cacheDb; + private readonly EventService service; public EventServiceTest() { context = TestHelpter.MakeTestContext(); cacheDb = new CacheDb(); - telemetryService = new Mock(); - telemetryService.Setup(s => s.GetOrCreateTelemetryIdByUid(It.IsAny())) - .Returns(1); - context.TelemetryEvents.RemoveRange(context.TelemetryEvents); - context.SaveChanges(); + var telemetryTracker = new Mock(); + var imezoneServiceMock = new Mock(); + 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 { new EventDto {Id = 1, IdCategory = 1, Message = "Test message 1"}, diff --git a/AsbCloudWebApi.Tests/ServicesTests/ScheduleServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/ScheduleServiceTest.cs index c4fc0ebc..a263ee35 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/ScheduleServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/ScheduleServiceTest.cs @@ -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, diff --git a/AsbCloudWebApi.Tests/ServicesTests/UserRoleServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/UserRoleServiceTest.cs index ea3095fb..00bf86c9 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/UserRoleServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/UserRoleServiceTest.cs @@ -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()); } diff --git a/AsbCloudWebApi.Tests/TestHelpter.cs b/AsbCloudWebApi.Tests/TestHelpter.cs index 0cf683ae..c9b61baa 100644 --- a/AsbCloudWebApi.Tests/TestHelpter.cs +++ b/AsbCloudWebApi.Tests/TestHelpter.cs @@ -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 { 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);