This commit is contained in:
KharchenkoVV 2021-09-10 11:30:38 +05:00
commit 3017d6d990
62 changed files with 465 additions and 150 deletions

View File

@ -2,7 +2,7 @@
namespace AsbCloudApp.Data
{
public class ClusterDto : IMapPoint
public class ClusterDto : IMapPoint, IId
{
public int Id { get; set; }
public string Caption { get; set; }

View File

@ -1,6 +1,6 @@
namespace AsbCloudApp.Data
{
public class CompanyDto
public class CompanyDto : IId
{
public int Id { get; set; }
public string Caption { get; set; }

View File

@ -2,7 +2,7 @@
namespace AsbCloudApp.Data
{
public class DepositDto : IMapPoint
public class DepositDto : IMapPoint, IId
{
public int Id { get; set; }
public string Caption { get; set; }

View File

@ -1,6 +1,6 @@
namespace AsbCloudApp.Data
{
public class EventDto
public class EventDto : IId
{
public int Id { get; set; }
public string Message { get; set; }

View File

@ -2,7 +2,7 @@
namespace AsbCloudApp.Data
{
public class FileInfoDto
public class FileInfoDto : IId
{
public int Id { get; set; }
public int IdWell { get; set; }

View File

@ -3,7 +3,7 @@ using System.Collections.Generic;
namespace AsbCloudApp.Data
{
public class MeasureDto
public class MeasureDto : IId
{
public int Id { get; set; }

View File

@ -5,7 +5,7 @@ namespace AsbCloudApp.Data
/// <summary>
/// Сообщение для frontend
/// </summary>
public class MessageDto
public class MessageDto : IId
{
public int Id { get; set; }

View File

@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AsbCloudApp.Data
namespace AsbCloudApp.Data
{
public class PlanFactBase<T>
{

View File

@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AsbCloudApp.Data
namespace AsbCloudApp.Data
{
/// <summary>
/// Lines container for Time Vs Depth chart

View File

@ -2,7 +2,7 @@
namespace AsbCloudApp.Data
{
public class ReportPropertiesDto
public class ReportPropertiesDto : IId
{
public int Id { get; set; }
public string Name { get; set; }

View File

@ -2,7 +2,7 @@
namespace AsbCloudApp.Data
{
public class StatClusterDto //: ClusterDto
public class StatClusterDto : IId
{
public int Id { get; set; }
public string Caption { get; set; }

View File

@ -1,6 +1,6 @@
namespace AsbCloudApp.Data
{
public class StatSectionDto : PlanFactBase<StatOperationsDto>
public class StatSectionDto : PlanFactBase<StatOperationsDto>, IId
{
public int Id { get; set; }
public string Caption { get; set; }

View File

@ -2,7 +2,7 @@
namespace AsbCloudApp.Data
{
public class StatWellDto //: WellDto
public class StatWellDto : IId
{
public int Id { get; set; }
public string Caption { get; set; }

View File

@ -1,6 +1,6 @@
namespace AsbCloudApp.Data
{
public class TelemetryAnalysisDto
public class TelemetryAnalysisDto : IId
{
public int Id { get; set; }
public int IdTelemetry { get; set; }

View File

@ -0,0 +1,9 @@
namespace AsbCloudApp.Data
{
public class TelemetryDto : IId
{
public int Id { get; set; }
public string RemoteUid { get; set; }
public TelemetryInfoDto Info { get; set; }
}
}

View File

@ -5,7 +5,7 @@ namespace AsbCloudApp.Data
/// <summary>
/// Сообщение получаемое от телеметрии
/// </summary>
public class TelemetryMessageDto
public class TelemetryMessageDto : IId
{
public int Id { get; set; }
public DateTime Date { get; set; }

View File

@ -2,7 +2,7 @@
namespace AsbCloudApp.Data
{
public class TelemetryOperationDto
public class TelemetryOperationDto : IId
{
public int Id { get; set; }
public string Name { get; set; }

View File

@ -1,6 +1,6 @@
namespace AsbCloudApp.Data
{
public class TelemetryUserDto
public class TelemetryUserDto : IId
{
public int Id { get; set; }

View File

@ -1,6 +1,6 @@
namespace AsbCloudApp.Data
{
public class UserDto : UserBaseDto
public class UserDto : UserBaseDto, IId
{
public int Id { get; set; }

View File

@ -0,0 +1,11 @@
using System.Collections.Generic;
namespace AsbCloudApp.Data
{
public class UserRoleDto : IId
{
public int Id { get; set; }
public string Caption { get; set; }
public virtual ICollection<UserDto> Users { get; set; }
}
}

View File

@ -7,5 +7,6 @@
public double? Latitude { get; set; }
public double? Longitude { get; set; }
public string WellType { get; set; }
public TelemetryDto Telemetry { get; set; }
}
}

View File

@ -7,11 +7,15 @@ namespace AsbCloudApp.Services
public interface ICrudService<Tdto>
where Tdto : Data.IId
{
Task<Tdto> GetAsync(int id, CancellationToken token = default);
Task<Tdto> InsertAsync(Tdto newItem, CancellationToken token = default);
Task<IEnumerable<Tdto>> InsertRangeAsync(IEnumerable<Tdto> newItems, CancellationToken token = default);
Task<Tdto> UpdateAsync(Tdto item, CancellationToken token = default);
List<string> Incledes { get; }
Task<int> DeleteAsync(int id, CancellationToken token = default);
Task<int> DeleteAsync(IEnumerable<int> ids, CancellationToken token = default);
Task<IEnumerable<Tdto>> GetAllAsync(CancellationToken token = default);
Task<Tdto> GetAsync(int id, CancellationToken token = default);
Task<Data.PaginationContainer<Tdto>> GetPageAsync(int skip = 0, int take = 32, CancellationToken token = default);
Task<int> InsertAsync(Tdto newItem, CancellationToken token = default);
Task<int> InsertRangeAsync(IEnumerable<Tdto> newItems, CancellationToken token = default);
Task<int> UpdateAsync(int id, Tdto item, CancellationToken token = default);
}
}

View File

@ -1,7 +1,7 @@
using AsbCloudApp.Data;
using System;
using System.IO;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

View File

@ -1,8 +1,8 @@
using System;
using AsbCloudApp.Data;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
namespace AsbCloudApp.Services
{

View File

@ -1,8 +1,8 @@
using System;
using System.Collections.Generic;
using AsbCloudDb.Model;
using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using System;
using System.Collections.Generic;
namespace AsbCloudDb.Migrations
{

View File

@ -1,10 +1,10 @@
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Data.Common;
#nullable disable
@ -41,11 +41,15 @@ namespace AsbCloudDb.Model
//var context = new AsbCloudDbContext(options);
public AsbCloudDbContext() : base()
{ }
{
Database.Migrate();
}
public AsbCloudDbContext(DbContextOptions<AsbCloudDbContext> options)
: base(options)
{ }
{
Database.Migrate();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
@ -290,7 +294,8 @@ namespace AsbCloudDb.Model
});
});
modelBuilder.Entity<WellSectionType>(entity => {
modelBuilder.Entity<WellSectionType>(entity =>
{
entity.HasData(new List<WellSectionType>{
new WellSectionType{ Id = 1, Caption = "Пилотный ствол"},
new WellSectionType{ Id = 2, Caption = "Направление"},
@ -301,14 +306,16 @@ namespace AsbCloudDb.Model
});
});
modelBuilder.Entity<WellType>(entity => {
modelBuilder.Entity<WellType>(entity =>
{
entity.HasData(new List<WellType> {
new WellType{ Id = 1, Caption = "Наклонно-направленная"},
new WellType{ Id = 2, Caption = "Горизонтальная"},
});
});
modelBuilder.Entity<MeasureCategory>(entity => {
modelBuilder.Entity<MeasureCategory>(entity =>
{
entity.HasData(new List<MeasureCategory> {
new MeasureCategory{ Id = 1, Name = "Показатели бурового раствора", ShortName = "Раствор"},
new MeasureCategory{ Id = 2, Name = "Шламограмма", ShortName = "Шламограмма"},

View File

@ -7,7 +7,7 @@ using System.ComponentModel.DataAnnotations.Schema;
namespace AsbCloudDb.Model
{
[Table("t_company_type")]
public partial class CompanyType
public partial class CompanyType : IId
{
[Key]
[Column("id")]

View File

@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AsbCloudDb.Model
namespace AsbCloudDb.Model
{
/// <summary>
/// For well related entities

View File

@ -7,7 +7,7 @@ namespace AsbCloudDb.Model
{
[Table("t_telemetry_analysis"), Comment("События на скважине")]
public class TelemetryAnalysis
public class TelemetryAnalysis : IId
{
[Key]
[Column("id")]

View File

@ -1,5 +1,4 @@
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

View File

@ -1,5 +1,5 @@
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json.Serialization;
@ -7,11 +7,8 @@ using System.Text.Json.Serialization;
namespace AsbCloudDb.Model
{
[Table("t_well_operation"), Comment("Данные по операциям на скважине")]
public class WellOperation
public class WellOperation : IId
{
public WellOperation ShallowCopy() =>
(WellOperation) MemberwiseClone();
[Key]
[Column("id")]
public int Id { get; set; }

View File

@ -6,7 +6,7 @@ using System.ComponentModel.DataAnnotations.Schema;
namespace AsbCloudDb.Model
{
[Table("t_well_operation_category"), Comment("Справочник операций на скважине")]
public class WellOperationCategory
public class WellOperationCategory : IId
{
[Key]
[Column("id")]

View File

@ -8,7 +8,7 @@ using System.Text.Json.Serialization;
namespace AsbCloudDb.Model
{
[Table("t_well_section_type"), Comment("конструкция секции скважины")]
public class WellSectionType
public class WellSectionType : IId
{
[Key]
[Column("id")]

View File

@ -8,7 +8,7 @@ using System.Text.Json.Serialization;
namespace AsbCloudDb.Model
{
[Table("t_well_type"), Comment("конструкция скважины")]
public class WellType
public class WellType : IId
{
[Key]
[Column("id")]

4
AsbCloudDb/Readme.md Normal file
View File

@ -0,0 +1,4 @@
Применить миграции
```
dotnet ef database update --project .\AsbCloudDb
```

View File

@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore;
using AsbCloudDb.Model;
using System;
using System.Collections.Generic;
namespace AsbCloudDbDemoData
{

View File

@ -41,6 +41,15 @@ namespace AsbCloudInfrastructure
services.AddTransient<IMeasureService, MeasureService>();
services.AddTransient<IDrillingProgramService, DrillingProgramService>();
// admin crud services:
services.AddTransient<ICrudService<DepositDto>, CrudServiceBase<DepositDto, Deposit>>();
services.AddTransient<ICrudService<ClusterDto>, CrudServiceBase<ClusterDto, Cluster>>();
services.AddTransient<ICrudService<WellDto>, CrudServiceBase<WellDto, Well>>();
services.AddTransient<ICrudService<CompanyDto>, CrudServiceBase<CompanyDto, Company>>();
services.AddTransient<ICrudService<UserDto>, CrudServiceBase<UserDto, User>>();
services.AddTransient<ICrudService<UserRoleDto>, CrudServiceBase<UserRoleDto, UserRole>>();
services.AddTransient<ICrudService<TelemetryDto>, CrudServiceBase<TelemetryDto, Telemetry>>();
return services;
}
}

View File

@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace AsbCloudInfrastructure
{

View File

@ -36,7 +36,7 @@ namespace AsbCloudInfrastructure.Services.Cache
catch
{
// ignore
// TODO: figure out what the well
// TODO: figure out what the hell
}
}

View File

@ -1,7 +1,9 @@
using AsbCloudApp.Services;
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@ -16,46 +18,79 @@ namespace AsbCloudInfrastructure.Services
protected readonly IAsbCloudDbContext context;
protected readonly DbSet<TModel> dbSet;
public List<string> Incledes { get; } = new List<string>();
public CrudServiceBase(IAsbCloudDbContext context)
{
this.context = context;
dbSet = context.Set<TModel>();
}
public virtual async Task<Tdto> GetAsync(int id, CancellationToken token = default)
public virtual async Task<PaginationContainer<Tdto>> GetPageAsync(int skip = 0, int take = 32, CancellationToken token = default)
{
var entity = await dbSet.AsNoTracking()
.FirstOrDefaultAsync(e => e.Id == id, token).ConfigureAwait(false);
var dto = entity.Adapt<Tdto>();
var query = GetQueryWithIncludes();
var count = await query
.CountAsync(token)
.ConfigureAwait(false);
var container = new PaginationContainer<Tdto>
{
Skip = skip,
Take = take,
Count = count,
};
if (skip >= count)
return container;
var entities = await query
.ToListAsync(token)
.ConfigureAwait(false);
container.Items = entities
.Select(entity => Convert(entity))
.ToList();
return container;
}
public virtual async Task<IEnumerable<Tdto>> GetAllAsync(CancellationToken token = default)
{
var query = GetQueryWithIncludes();
var entities = await query
.ToListAsync(token).ConfigureAwait(false);
var dto = entities.Select(entity => Convert(entity));
return dto;
}
public virtual async Task<Tdto> InsertAsync(Tdto newItem, CancellationToken token = default)
public virtual async Task<Tdto> GetAsync(int id, CancellationToken token = default)
{
var newEntity = newItem.Adapt<TModel>();
var dbEntity = dbSet.Add(newEntity);
await context.SaveChangesAsync(token).ConfigureAwait(false);
return dbEntity.Entity.Adapt<Tdto>();
var query = GetQueryWithIncludes();
var entity = await query
.FirstOrDefaultAsync(e => e.Id == id, token).ConfigureAwait(false);
var dto = Convert(entity);
return dto;
}
public virtual async Task<IEnumerable<Tdto>> InsertRangeAsync(IEnumerable<Tdto> newItems, CancellationToken token = default)
public virtual Task<int> InsertAsync(Tdto item, CancellationToken token = default)
{
var newEntities = newItems.Adapt<IEnumerable<TModel>>();
var dbEntities = new Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<TModel>[newItems.Count()];
for (int i = 0; i < dbEntities.Length; i++)
dbEntities[i] = dbSet.Add(newEntities.ElementAt(i));
await context.SaveChangesAsync(token).ConfigureAwait(false);
return dbEntities.Select(e => e.Entity.Adapt<Tdto>());
var entity = Convert(item);
dbSet.Add(entity);
return context.SaveChangesAsync(token);
}
public virtual async Task<Tdto> UpdateAsync(Tdto item, CancellationToken token = default)
public virtual Task<int> InsertRangeAsync(IEnumerable<Tdto> items, CancellationToken token = default)
{
var newEntity = item.Adapt<TModel>();
var dbEntity = dbSet.Update(newEntity);
await context.SaveChangesAsync(token).ConfigureAwait(false);
return dbEntity.Entity.Adapt<Tdto>();
var entities = items.Select(i => Convert(i));
dbSet.AddRange(entities);
return context.SaveChangesAsync(token);
}
public virtual Task<int> UpdateAsync(int id, Tdto item, CancellationToken token = default)
{
var entity = Convert(item);
dbSet.Update(entity);
return context.SaveChangesAsync(token);
}
public virtual Task<int> DeleteAsync(int id, CancellationToken token = default)
@ -76,5 +111,17 @@ namespace AsbCloudInfrastructure.Services
dbSet.RemoveRange(entities);
return context.SaveChangesAsync(token);
}
public virtual Tdto Convert(TModel src) => src.Adapt<Tdto>();
public virtual TModel Convert(Tdto src) => src.Adapt<TModel>();
private IQueryable<TModel> GetQueryWithIncludes()
{
IQueryable<TModel> query = dbSet;
foreach (var include in Incledes)
query = query.Include(include);
return query;
}
}
}

View File

@ -1,15 +1,12 @@
using System;
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
namespace AsbCloudInfrastructure.Services
{
@ -39,7 +36,8 @@ namespace AsbCloudInfrastructure.Services
var matchFiles = await fileService.GetInfosByCategoryAsync(idWell, idFileCategoryDrillingProgram, token)
.ConfigureAwait(false);
if (matchFiles is not null && matchFiles.Any()) {
if (matchFiles is not null && matchFiles.Any())
{
matchFiles = matchFiles.OrderByDescending(f => f.UploadDate);
var matchFilesIterator = matchFiles.GetEnumerator();
matchFilesIterator.MoveNext();

View File

@ -0,0 +1,8 @@
using AsbCloudApp.Data;
namespace AsbCloudInfrastructure.Services
{
public interface ICachedCrudService<Tdto> where Tdto : IId
{
}
}

View File

@ -2,13 +2,13 @@
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Mapster;
namespace AsbCloudInfrastructure.Services
{
@ -139,6 +139,7 @@ namespace AsbCloudInfrastructure.Services
if (!wellOperations.Any())
return new StatWellDto()
{
Id = idWell,
Caption = well.Caption,
WellType = wellType.Caption
};

View File

@ -0,0 +1,47 @@
using AsbCloudApp.Data;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services
{
public class _CachedCrudService<Tdto, TModel> : ICachedCrudService<Tdto>
where TModel : class, AsbCloudDb.Model.IId
where Tdto : AsbCloudApp.Data.IId
{
private readonly CacheTable<TModel> cache;
public _CachedCrudService(IAsbCloudDbContext db, Cache.CacheDb cacheDb)
{
cache = cacheDb.GetCachedTable<TModel>((DbContext)db);
}
public virtual async Task<PaginationContainer<Tdto>> GetAsync(int skip = 0, int take = 32, CancellationToken token = default)
{
var count = cache.Count();
var result = new PaginationContainer<Tdto> { Skip = skip, Take = take, Count = count };
if (count <= skip)
return result;
var items = await cache.WhereAsync(token).ConfigureAwait(false);
result.Items.AddRange(items.OrderBy(i => i.Id).Skip(skip).Take(take).Select(i => Convert(i)));
return result;
}
public virtual Task<Tdto> GetAsync(int id, CancellationToken token = default)
{
throw new NotImplementedException();
}
public virtual Tdto Convert(TModel src) => src.Adapt<Tdto>();
public virtual TModel Convert(Tdto src) => src.Adapt<TModel>();
}
}

View File

@ -0,0 +1,19 @@
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace AsbCloudWebApi.Controllers
{
[Route("api/admin/cluster")]
[ApiController]
[Authorize]
public class AdminClusterController : CrudController<ClusterDto, ICrudService<ClusterDto>>
{
public AdminClusterController(ICrudService<ClusterDto> service)
:base(service)
{
service.Incledes.Add("Wells");
}
}
}

View File

@ -0,0 +1,19 @@
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace AsbCloudWebApi.Controllers
{
[Route("api/admin/company")]
[ApiController]
[Authorize]
public class AdminCompanyController : CrudController<CompanyDto, ICrudService<CompanyDto>>
{
public AdminCompanyController(ICrudService<CompanyDto> service)
: base(service)
{
}
}
}

View File

@ -0,0 +1,19 @@
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace AsbCloudWebApi.Controllers
{
[Route("api/admin/deposit")]
[ApiController]
[Authorize]
public class AdminDepositController : CrudController<DepositDto, ICrudService<DepositDto>>
{
public AdminDepositController(ICrudService<DepositDto> service)
:base(service)
{
service.Incledes.Add("Clusters");
}
}
}

View File

@ -0,0 +1,19 @@
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace AsbCloudWebApi.Controllers
{
[Route("api/admin/telemetry")]
[ApiController]
[Authorize]
public class AdminTelemetryController : CrudController<TelemetryDto, ICrudService<TelemetryDto>>
{
public AdminTelemetryController(ICrudService<TelemetryDto> service)
: base(service)
{
service.Incledes.Add("Well");
}
}
}

View File

@ -0,0 +1,19 @@
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace AsbCloudWebApi.Controllers
{
[Route("api/admin/user")]
[ApiController]
[Authorize]
public class AdminUserController : CrudController<UserDto, ICrudService<UserDto>>
{
public AdminUserController(ICrudService<UserDto> service)
: base(service)
{
}
}
}

View File

@ -0,0 +1,19 @@
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace AsbCloudWebApi.Controllers
{
[Route("api/admin/user/role")]
[ApiController]
[Authorize]
public class AdminUserRoleController : CrudController<UserRoleDto, ICrudService<UserRoleDto>>
{
public AdminUserRoleController(ICrudService<UserRoleDto> service)
: base(service)
{
}
}
}

View File

@ -0,0 +1,19 @@
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace AsbCloudWebApi.Controllers
{
[Route("api/admin/well")]
[ApiController]
[Authorize]
public class AdminWellController : CrudController<WellDto, ICrudService<WellDto>>
{
public AdminWellController(ICrudService<WellDto> service)
:base(service)
{
service.Incledes.Add("Telemetry");
}
}
}

View File

@ -1,54 +1,114 @@
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
// 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]
[Authorize]
public abstract class CrudController<T, TService> : ControllerBase
where T : IId
where TService : ICrudService<T>
{
protected readonly TService service;
public List<string> Roles { get; } = new List<string> { "Администратор" };
public CrudController(TService service)
{
this.service = service;
}
// GET api/<CrudController>/5
/// <summary>
/// Получить страницу с записями в PaginationContainer
/// </summary>
/// <param name="skip">пропустить skip записей</param>
/// <param name="take">получить take записей</param>
/// <param name="token">CancellationToken</param>
/// <returns>страница с записями в PaginationContainer</returns>
[HttpGet()]
public virtual async Task<IActionResult> GetPage(int skip = 0, int take = 32, CancellationToken token = default)
{
if (!Roles.Any(role => User.IsInRole(role)))
return Forbid();
var result = await service.GetPageAsync(skip, take, token).ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Получить одну запись по Id
/// </summary>
/// <param name="id">id записи</param>
/// <param name="token"></param>
/// <returns>запись</returns>
[HttpGet("{id}")]
public virtual IActionResult Get(int id, CancellationToken token = default)
public virtual async Task<IActionResult> Get(int id, CancellationToken token = default)
{
var result = service.GetAsync(id, token).ConfigureAwait(false);
if (!Roles.Any(role => User.IsInRole(role)))
return Forbid();
var result = await service.GetAsync(id, token).ConfigureAwait(false);
return Ok(result);
}
// POST api/<CrudController>
/// <summary>
/// Добавить запись
/// </summary>
/// <param name="value">запись</param>
/// <param name="token"></param>
/// <returns>1 - добавлено, 0 - нет</returns>
[HttpPost]
public virtual IActionResult Insert([FromBody] T value, CancellationToken token = default)
public virtual async Task<IActionResult> Insert([FromBody] T value, CancellationToken token = default)
{
var result = service.InsertAsync(value, token).ConfigureAwait(false);
if (!Roles.Any(role => User.IsInRole(role)))
return Forbid();
var result = await service.InsertAsync(value, token).ConfigureAwait(false);
return Ok(result);
}
// PUT api/<CrudController>/5
/// <summary>
/// Редактировать запись по id
/// </summary>
/// <param name="id">id записи</param>
/// <param name="value">запись</param>
/// <param name="token"></param>
/// <returns>1 - успешно отредактировано, 0 - нет</returns>
[HttpPut("{id}")]
public virtual IActionResult Put(int id, [FromBody] T value, CancellationToken token = default)
public virtual async Task<IActionResult> Put(int id, [FromBody] T value, CancellationToken token = default)
{
var result = service.UpdateAsync(value, token).ConfigureAwait(false);
if (!Roles.Any(role => User.IsInRole(role)))
return Forbid();
var result = await service.UpdateAsync(id, value, token).ConfigureAwait(false);
return Ok(result);
}
// DELETE api/<CrudController>/5
/// <summary>
/// Удалить запись по id
/// </summary>
/// <param name="id">id записи</param>
/// <param name="token"></param>
/// <returns>1 - успешно удалено, 0 - нет</returns>
[HttpDelete("{id}")]
public virtual IActionResult Delete(int id, CancellationToken token = default)
public virtual async Task<IActionResult> Delete(int id, CancellationToken token = default)
{
var result = service.DeleteAsync(id, token).ConfigureAwait(false);
if (!Roles.Any(role => User.IsInRole(role)))
return Forbid();
var result = await service.DeleteAsync(id, token).ConfigureAwait(false);
return Ok(result);
}
}