правки по результатам ревью

This commit is contained in:
Olga Nemt 2023-04-21 11:22:39 +05:00
parent 9806df01ae
commit 81ab77cdfc
8 changed files with 82 additions and 148 deletions

View File

@ -2,7 +2,6 @@
namespace AsbCloudApp.Data
{
#nullable enable
/// <summary>
/// DTO для faq-вопроса
/// </summary>
@ -13,11 +12,6 @@ namespace AsbCloudApp.Data
/// </summary>
public int Id { get; set; }
/// <summary>
/// ключ скважины
/// </summary>
public int? IdWell { get; set; }
/// <summary>
/// ключ автора вопроса
/// </summary>
@ -47,17 +41,16 @@ namespace AsbCloudApp.Data
/// <summary>
/// статус вопроса
/// </summary>
public int? State { get; set; } = 0!;
public int State { get; set; } = 0;
/// <summary>
/// Счетчик повторений вопроса
/// </summary>
public int? CounterQuestion { get; set; } = 0!;
public int CounterQuestion { get; set; } = 1;
/// <summary>
/// Частый вопрос
/// </summary>
public bool? IsFrequently { get; set; } = false!;
public bool IsFrequently { get; set; } = false;
}
#nullable disable
}

View File

@ -7,7 +7,6 @@ using AsbCloudApp.Services;
namespace AsbCloudApp.Repositories
{
#nullable enable
/// <summary>
/// репозиторий по работе с faq-вопросами
/// </summary>
@ -19,7 +18,7 @@ namespace AsbCloudApp.Repositories
/// <param name="request"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<FaqDto>> GetAllAsync(FaqRequest request, CancellationToken token);
Task<IEnumerable<FaqDto>> GetFilteredAsync(FaqRequest request, CancellationToken token);
/// <summary>
/// Добавить вопрос
@ -40,20 +39,27 @@ namespace AsbCloudApp.Repositories
/// <summary>
/// Объединить 2 вопроса в 1
/// </summary>
/// <param name="sourceIds">Ключи вопросов, подлежащих объединению</param>
/// <param name="mergeTexts">Флаг, объединять текст вопросов или нет</param>
/// <param name="sourceId1">ключ первого вопроса, подлежащего объединению</param>
/// <param name="sourceId2">ключ второго вопроса, подлежащего объединению</param>
/// <param name="mergeQuestions">Флаг, объединять текст вопросов или нет</param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> MergeAsync(IEnumerable<int> sourceIds, bool mergeTexts, CancellationToken token);
Task<int> MergeAsync(int sourceId1, int sourceId2, bool mergeQuestions, CancellationToken token);
/// <summary>
/// Пометить вопрос по id как удаленный
/// </summary>
/// <param name="idWell"></param>
/// <param name="id"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> MarkAsDeletedAsync(int idWell, int id, CancellationToken token);
Task<int> MarkAsDeletedAsync(int id, CancellationToken token);
/// <summary>
/// Удалить вопрос по ключу
/// </summary>
/// <param name="id"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> DeleteAsync(int id, CancellationToken token);
}
#nullable disable
}

View File

@ -7,11 +7,10 @@ using System.Threading.Tasks;
namespace AsbCloudApp.Requests
{
#nullable enable
/// <summary>
/// Параметры запроса для фильтрации faq-вопросов
/// </summary>
public class FaqRequestBase : RequestBase
public class FaqRequest
{
/// <summary>
/// Есть ли ответ на вопрос
@ -28,30 +27,4 @@ namespace AsbCloudApp.Requests
/// </summary>
public bool IncludeDeleted { get; set; } = false;
}
/// <summary>
/// Параметры запроса для фильтрации faq-вопросов (с id скважины)
/// </summary>
public class FaqRequest : FaqRequestBase
{
/// <summary>
/// копирующий конструктор
/// </summary>
/// <param name="request"></param>
/// <param name="idWell"></param>
public FaqRequest(FaqRequestBase request, int idWell)
{
IdWell = idWell;
this.IncludeDeleted = request.IncludeDeleted;
this.HasAnswer = request.HasAnswer;
this.IsFrequently = request.IsFrequently;
}
/// <summary>
/// id скважины
/// </summary>
public int IdWell { get; set; }
}
#nullable disable
}

View File

@ -72,7 +72,7 @@ namespace AsbCloudDb.Model
private static int referenceCount;
public static int ReferenceCount => referenceCount;
public DbSet<Faq> FAQs => Set<Faq>();
public DbSet<Faq> Faqs => Set<Faq>();
public AsbCloudDbContext() : base()
{

View File

@ -6,7 +6,6 @@ using System.Text.Json.Serialization;
namespace AsbCloudDb.Model
{
#nullable enable
[Table("t_faq"), Comment("вопросы пользователей")]
public class Faq : IId
{
@ -17,16 +16,6 @@ namespace AsbCloudDb.Model
[Column("id"), Comment("Идентификатор")]
public int Id { get; set; }
/// <summary>
/// ключ скважины, к которой пивязан вопрос
/// </summary>
[Column("id_well"), Comment("id скважины")]
public int IdWell { get; set; }
[JsonIgnore]
[ForeignKey(nameof(IdWell))]
public virtual Well Well { get; set; } = null!;
/// <summary>
/// автор вопроса
/// </summary>
@ -45,7 +34,7 @@ namespace AsbCloudDb.Model
[JsonIgnore]
[ForeignKey(nameof(IdAuthorAnswer))]
public virtual User AuthorAnswer { get; set; } = null!;
public virtual User? AuthorAnswer { get; set; }
/// <summary>
/// дата создания вопроса
@ -87,7 +76,7 @@ namespace AsbCloudDb.Model
/// Счетчик повторений вопроса
/// </summary>
[Column("counter_question"), Comment("Счетчик повторений вопроса")]
public int CounterQuestion { get; set; }
public int CounterQuestion { get; set; } = 1;
/// <summary>
/// Ключ заменяющего вопроса
@ -102,5 +91,4 @@ namespace AsbCloudDb.Model
public bool IsFrequently { get; set; } = false;
}
#nullable disable
}

View File

@ -57,7 +57,7 @@ namespace AsbCloudDb.Model
DbSet<WellFinalDocument> WellFinalDocuments { get; }
DbSet<LimitingParameter> LimitingParameter { get; }
DbSet<TelemetryWirelineRunOut> TelemetryWirelineRunOut { get; }
DbSet<Faq> FAQs { get; }
DbSet<Faq> Faqs { get; }
DbSet<Record1> Record1 { get; }
DbSet<Record7> Record7 { get; }

View File

@ -15,7 +15,6 @@ using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Repository
{
#nullable enable
/// <summary>
/// сервис по работе с faq-вопросами
/// </summary>
@ -30,10 +29,9 @@ namespace AsbCloudInfrastructure.Repository
this.wellService = wellService;
}
public async Task<IEnumerable<FaqDto>> GetAllAsync(FaqRequest request, CancellationToken token)
public async Task<IEnumerable<FaqDto>> GetFilteredAsync(FaqRequest request, CancellationToken token)
{
var query = db.FAQs
.Where(o => o.IdWell == request.IdWell);
var query = db.Faqs.AsNoTracking();
if (request.IsFrequently)
{
@ -48,26 +46,19 @@ namespace AsbCloudInfrastructure.Repository
query = query.Where(o => o.State != Faq.StateDeleted);
}
var entities = query.Select(o => new FaqDto()
{
Id = o.Id,
Question = o.Question,
Answer = o.Answer,
CounterQuestion = o.CounterQuestion,
IsFrequently = o.IsFrequently,
State = o.State,
DateCreatedQuestion = o.DateCreatedQuestion,
});
var entities = query
.OrderByDescending(e => e.DateCreatedQuestion)
.Select(o => new FaqDto()
{
Id = o.Id,
Question = o.Question,
Answer = o.Answer,
CounterQuestion = o.CounterQuestion,
IsFrequently = o.IsFrequently,
State = o.State,
DateCreatedQuestion = o.DateCreatedQuestion,
});
if (request.SortFields?.Any() == true)
{
entities = entities.SortBy(request.SortFields);
}
else
{
entities = entities.OrderByDescending(e => e.DateCreatedQuestion);
};
var result = await entities.AsNoTracking()
.ToArrayAsync(token)
@ -81,22 +72,20 @@ namespace AsbCloudInfrastructure.Repository
{
var entity = faqDto.Adapt<Faq>();
entity.DateCreatedQuestion = entity.DateLastEditedQuestion = DateTimeOffset.UtcNow;
entity.CounterQuestion = 0;
entity.CounterQuestion = 1;
entity.State = Faq.StateOpened;
db.FAQs.Add(entity);
db.Faqs.Add(entity);
await db.SaveChangesAsync(token).ConfigureAwait(false);
return entity.Id;
}
public async Task<int> MergeAsync(IEnumerable<int> sourceIds, bool mergeTexts, CancellationToken token)
public async Task<int> MergeAsync(int sourceId1, int sourceId2, bool mergeQuestions, CancellationToken token)
{
var sourceFaqs = db.FAQs.Where(e => sourceIds.Contains(e.Id)).ToArray();
var sourceFaqs = db.Faqs.Where(e => e.Id == sourceId1 || e.Id == sourceId2).ToArray();
if (sourceFaqs.Count() < 2)
throw new ArgumentInvalidException("Questions with target ids don't exist", nameof(sourceIds));
if (sourceFaqs.Select(e => e.IdWell).Distinct().Count() > 1)
throw new ArgumentInvalidException("Questions with different idWell are not merged", nameof(sourceIds));
throw new ArgumentInvalidException("Questions with target ids don't exist", nameof(sourceFaqs));
var newFaq = new Faq()
{
@ -106,16 +95,15 @@ namespace AsbCloudInfrastructure.Repository
IdAuthorQuestion = sourceFaqs.Last().IdAuthorQuestion,
DateCreatedQuestion = DateTimeOffset.UtcNow,
DateLastEditedQuestion = DateTimeOffset.UtcNow,
IdWell = sourceFaqs.Last().IdWell,
Answer = mergeTexts == true
Answer = mergeQuestions == true
? string.Join(Environment.NewLine, sourceFaqs.Select(e => e.Answer))
: sourceFaqs.Last().Answer,
Question = mergeTexts == true
Question = mergeQuestions == true
? string.Join(Environment.NewLine, sourceFaqs.Select(e => e.Question))
: sourceFaqs.Last().Question,
};
db.FAQs.Add(newFaq);
db.Faqs.Add(newFaq);
await db.SaveChangesAsync(token).ConfigureAwait(false);
if (newFaq.Id == 0)
@ -135,18 +123,16 @@ namespace AsbCloudInfrastructure.Repository
{
var entity = dto.Adapt<Faq>();
entity.DateLastEditedQuestion = DateTimeOffset.UtcNow;
db.FAQs.Update(entity);
db.Faqs.Update(entity);
return await db.SaveChangesAsync(token)
.ConfigureAwait(false);
}
public async Task<int> MarkAsDeletedAsync(int idWell, int id, CancellationToken token)
public async Task<int> MarkAsDeletedAsync(int id, CancellationToken token)
{
var entity = db.FAQs.FirstOrDefault(e => e.Id == id);
var entity = db.Faqs.FirstOrDefault(e => e.Id == id);
if (entity is null)
throw new ArgumentInvalidException("Question doesn't exist", nameof(id));
if (entity.IdWell != idWell)
throw new ArgumentInvalidException("Question's well and idWell don't match", nameof(idWell));
entity.State = Faq.StateDeleted;
entity.DateLastEditedQuestion = DateTimeOffset.UtcNow;
@ -154,6 +140,15 @@ namespace AsbCloudInfrastructure.Repository
return await db.SaveChangesAsync(token)
.ConfigureAwait(false);
}
public async Task<int> DeleteAsync(int id, CancellationToken token)
{
var faq = db.Faqs.FirstOrDefault(f => f.Id == id);
if (faq is null)
throw new ArgumentInvalidException("Question doesn't exist", nameof(id));
db.Faqs.Remove(faq);
return await db.SaveChangesAsync(token);
}
}
#nullable disable
}

View File

@ -14,7 +14,6 @@ using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers
{
#nullable enable
/// <summary>
/// контроллер по работе с faq-вопросами
/// </summary>
@ -35,34 +34,23 @@ namespace AsbCloudWebApi.Controllers
/// <summary>
/// получение списка faq-вопросов
/// </summary>
/// <param name="idWell"></param>
/// <param name="request"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet]
[Permission]
[ProducesResponseType(typeof(IEnumerable<FaqDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetAllAsync(
[FromRoute] int idWell,
[FromQuery] FaqRequestBase request,
public async Task<IActionResult> GetFilteredAsync(
[FromQuery] FaqRequest request,
CancellationToken token)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
var requestToRepository = new FaqRequest(request, idWell);
var result = await faqRepository.GetAllAsync(
requestToRepository,
token)
.ConfigureAwait(false);
var result = await faqRepository.GetFilteredAsync(request, token).ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// добавление нового вопроса
/// </summary>
/// <param name="idWell">ключ скважины</param>
/// <param name="faqDto">вопрос</param>
/// <param name="token"></param>
/// <returns></returns>
@ -70,14 +58,9 @@ namespace AsbCloudWebApi.Controllers
[Permission]
[ProducesResponseType(typeof(FaqDto), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> InsertAsync(
[Range(1, int.MaxValue, ErrorMessage = "Id скважины не может быть меньше 1")] int idWell,
[FromBody] FaqDto faqDto,
CancellationToken token)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
faqDto.IdWell = idWell;
faqDto.IdAuthorQuestion = User.GetUserId()!.Value;
var result = await faqRepository.InsertAsync(faqDto, token)
@ -88,11 +71,8 @@ namespace AsbCloudWebApi.Controllers
[HttpPut]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> UpdateAsync(int idWell, [FromBody] FaqDto faqDto, CancellationToken token)
public async Task<IActionResult> UpdateAsync([FromBody] FaqDto faqDto, CancellationToken token)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
faqDto.IdAuthorAnswer = User.GetUserId()!.Value;
var result = await faqRepository.UpdateAsync(faqDto, token)
@ -103,8 +83,8 @@ namespace AsbCloudWebApi.Controllers
/// <summary>
/// Объединение 2 вопросов в один
/// </summary>
/// <param name="idWell">ключ скважины</param>
/// <param name="sourceIds">ключи вопросов, подлежащих объединению</param>
/// <param name="sourceId1"></param>
/// <param name="sourceId2"></param>
/// <param name="mergeTexts">настройка, объединять ли текст 2-х вопросов в один или нет</param>
/// <param name="token"></param>
/// <returns></returns>
@ -112,17 +92,12 @@ namespace AsbCloudWebApi.Controllers
[HttpGet("merge")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> MergeAsync(
int idWell,
[FromQuery] IEnumerable<int> sourceIds,
[FromQuery] int sourceId1,
[FromQuery] int sourceId2,
[FromQuery] bool mergeTexts,
CancellationToken token)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
if (sourceIds.Count() < 2)
throw new ArgumentInvalidException("Count of questions must be more than 1", nameof(sourceIds));
var result = await faqRepository.MergeAsync(sourceIds, mergeTexts, token)
var result = await faqRepository.MergeAsync(sourceId1, sourceId2, mergeTexts, token)
.ConfigureAwait(false);
return Ok(result);
}
@ -130,31 +105,35 @@ namespace AsbCloudWebApi.Controllers
/// <summary>
/// Помечает вопрос как удаленный
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="id">id вопроса</param>
/// <param name="token">Токен отмены задачи</param>
/// <returns>Количество удаленных из БД строк</returns>
[HttpPut("{id}")]
[Permission]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> MarkAsDeletedAsync(int idWell, int id, CancellationToken token)
public async Task<IActionResult> MarkAsDeletedAsync(int id, CancellationToken token)
{
if (!await CanUserAccessToWellAsync(idWell,
token).ConfigureAwait(false))
return Forbid();
var result = await faqRepository.MarkAsDeletedAsync(idWell, id, token)
var result = await faqRepository.MarkAsDeletedAsync(id, token)
.ConfigureAwait(false);
return Ok(result);
}
private async Task<bool> CanUserAccessToWellAsync(int idWell, CancellationToken token)
/// <summary>
/// Удаление вопроса
/// </summary>
/// <param name="id">id вопроса</param>
/// <param name="token">Токен отмены задачи</param>
/// <returns>Количество удаленных из БД строк</returns>
[HttpDelete("{id}")]
[Permission]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> DeleteAsync(int id, CancellationToken token)
{
int? idCompany = User.GetCompanyId();
return idCompany is not null && await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false);
var result = await faqRepository.DeleteAsync(id, token)
.ConfigureAwait(false);
return Ok(result);
}
}
#nullable disable
}