refactor ArgumentInvalidException

This commit is contained in:
ngfrolov 2023-09-29 12:06:46 +05:00
parent 33c49e8a48
commit 7ae00fe2f7
Signed by untrusted user who does not match committer: ng.frolov
GPG Key ID: E99907A0357B29A7
33 changed files with 168 additions and 221 deletions

View File

@ -1,4 +1,5 @@
using System; using System;
using System.ComponentModel.DataAnnotations;
namespace AsbCloudApp.Data; namespace AsbCloudApp.Data;
@ -25,12 +26,14 @@ public class NotificationDto : IId
/// <summary> /// <summary>
/// Заголовок уведомления /// Заголовок уведомления
/// </summary> /// </summary>
[Required, StringLength(300, MinimumLength = 1, ErrorMessage = "Заголовок должен мыть не меньше 1-го знака и не больше 300")]
public string Title { get; set; } = null!; public string Title { get; set; } = null!;
/// <summary> /// <summary>
/// Сообщение уведомления /// Сообщение уведомления
/// </summary> /// </summary>
public string Message { get; set; } = null!; [Required, StringLength(2048, MinimumLength = 1, ErrorMessage = "Заголовок должен мыть не меньше 1-го знака и не больше 2048")]
public string Message { get; set; } = null!;
/// <summary> /// <summary>
/// Дата регистрации уведомления /// Дата регистрации уведомления
@ -90,6 +93,7 @@ public class NotificationDto : IId
/// 0 - SignalR /// 0 - SignalR
/// 1 - Email /// 1 - Email
/// </summary> /// </summary>
[Range(0,1)]
public int IdTransportType { get; set; } public int IdTransportType { get; set; }
/// <summary> /// <summary>

View File

@ -1,4 +1,5 @@
using System; using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace AsbCloudApp.Data.ProcessMap; namespace AsbCloudApp.Data.ProcessMap;
@ -6,7 +7,7 @@ namespace AsbCloudApp.Data.ProcessMap;
/// <summary> /// <summary>
/// РТК план проработка скважины /// РТК план проработка скважины
/// </summary> /// </summary>
public class ProcessMapWellboreDevelopmentDto : IId, IWellRelated public class ProcessMapWellboreDevelopmentDto : IId, IWellRelated, IValidatableObject
{ {
/// <inheritdoc/> /// <inheritdoc/>
public int Id { get; set; } public int Id { get; set; }
@ -94,4 +95,13 @@ public class ProcessMapWellboreDevelopmentDto : IId, IWellRelated
/// Комментарий /// Комментарий
/// </summary> /// </summary>
public string? Comment { get; set; } public string? Comment { get; set; }
/// <inheritdoc/>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (DepthEnd < DepthStart)
yield return new ValidationResult($"{nameof(DepthEnd)}:{DepthEnd:#0.0} меньше {nameof(DepthStart)}:{DepthStart:#0.0}", new[] { nameof(DepthEnd), nameof(DepthStart) });
yield break;
}
} }

View File

@ -47,6 +47,7 @@ namespace AsbCloudApp.Data
/// <summary> /// <summary>
/// ID типа скважины /// ID типа скважины
/// </summary> /// </summary>
[Range(1, 2, ErrorMessage = "Тип скважины указан неправильно.")]
public int IdWellType { get; set; } public int IdWellType { get; set; }
/// <summary> /// <summary>
@ -59,6 +60,7 @@ namespace AsbCloudApp.Data
/// 1 - в работе, /// 1 - в работе,
/// 2 - завершена /// 2 - завершена
/// </summary> /// </summary>
[Range(0, 2, ErrorMessage = "Текущее состояние работы скважины указано неправильно.")]
public int IdState { get; set; } public int IdState { get; set; }
/// <summary> /// <summary>

View File

@ -1,3 +1,5 @@
using System.ComponentModel.DataAnnotations;
namespace AsbCloudApp.Data.WellOperationImport; namespace AsbCloudApp.Data.WellOperationImport;
/// <summary> /// <summary>
@ -8,7 +10,8 @@ public class WellOperationParserOptionsDto
/// <summary> /// <summary>
/// Название листа /// Название листа
/// </summary> /// </summary>
public string? SheetName { get; set; } [StringLength(250, MinimumLength =1, ErrorMessage = "Название листа должно быть задано")]
public string SheetName { get; set; } = null!;
/// <summary> /// <summary>
/// Id шаблона /// Id шаблона

View File

@ -15,9 +15,9 @@ namespace AsbCloudApp.Exceptions
/// <summary> /// <summary>
/// конструктор /// конструктор
/// </summary> /// </summary>
/// <param name="message"></param>
/// <param name="paramName"></param> /// <param name="paramName"></param>
public ArgumentInvalidException(string message, string paramName) /// <param name="message"></param>
public ArgumentInvalidException(string paramName, string message)
: base(message) : base(message)
{ {
ParamName = paramName; ParamName = paramName;

View File

@ -18,7 +18,7 @@ namespace AsbCloudApp.Repositories
/// <param name="dtos"></param> /// <param name="dtos"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task<IEnumerable<WellFinalDocumentDBDto>> UpdateRangeAsync(int idWell, IEnumerable<WellFinalDocumentInputDto>? dtos, CancellationToken token); Task<IEnumerable<WellFinalDocumentDBDto>> UpdateRangeAsync(int idWell, IEnumerable<WellFinalDocumentInputDto> dtos, CancellationToken token);
/// <summary> /// <summary>
/// Получение всех записей /// Получение всех записей

View File

@ -43,7 +43,7 @@ public class NotificationService
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
var notificationCategory = await notificationCategoryRepository.GetOrDefaultAsync(request.IdNotificationCategory, cancellationToken) var notificationCategory = await notificationCategoryRepository.GetOrDefaultAsync(request.IdNotificationCategory, cancellationToken)
?? throw new ArgumentInvalidException("Категория уведомления не найдена", nameof(request.IdNotificationCategory)); ?? throw new ArgumentInvalidException(nameof(request.IdNotificationCategory), "Категория уведомления не найдена");
var notification = new NotificationDto var notification = new NotificationDto
{ {
@ -75,10 +75,10 @@ public class NotificationService
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
var notification = await notificationRepository.GetOrDefaultAsync(idNotification, cancellationToken) var notification = await notificationRepository.GetOrDefaultAsync(idNotification, cancellationToken)
?? throw new ArgumentInvalidException("Уведомление не найдено", nameof(idNotification)); ?? throw new ArgumentInvalidException(nameof(idNotification), "Уведомление не найдено");
if(isRead && !notification.SentDate.HasValue) if(isRead && !notification.SentDate.HasValue)
throw new ArgumentInvalidException("Уведомление не может быть прочитано", nameof(isRead)); throw new ArgumentInvalidException(nameof(isRead), "Уведомление не может быть прочитано");
notification.ReadDate = isRead ? DateTime.UtcNow : null; notification.ReadDate = isRead ? DateTime.UtcNow : null;
@ -111,7 +111,7 @@ public class NotificationService
{ {
var notificationTransportService = notificationTransportServices var notificationTransportService = notificationTransportServices
.FirstOrDefault(s => s.IdTransportType == idTransportType) .FirstOrDefault(s => s.IdTransportType == idTransportType)
?? throw new ArgumentInvalidException("Доставщик уведомлений не найден", nameof(idTransportType)); ?? throw new ArgumentInvalidException(nameof(idTransportType), "Доставщик уведомлений не найден");
return notificationTransportService; return notificationTransportService;
} }

View File

@ -37,10 +37,10 @@ namespace AsbCloudInfrastructure
.ThenInclude(r => r.Company) .ThenInclude(r => r.Company)
.Include(w => w.Telemetry) .Include(w => w.Telemetry)
.FirstOrDefault(w => w.Id == idWell) .FirstOrDefault(w => w.Id == idWell)
?? throw new ArgumentInvalidException("idWell doesn`t exist", nameof(idWell)); ?? throw new ArgumentInvalidException(nameof(idWell), "idWell doesn`t exist");
idTelemetry = well?.IdTelemetry idTelemetry = well?.IdTelemetry
?? throw new ArgumentInvalidException($"Well {idWell} doesn't contain telemetry", nameof(idWell)); ?? throw new ArgumentInvalidException(nameof(idWell), $"Well {idWell} doesn't contain telemetry");
events = context.TelemetryEvents events = context.TelemetryEvents
.Where(e => e.IdTelemetry == idTelemetry) .Where(e => e.IdTelemetry == idTelemetry)

View File

@ -93,7 +93,7 @@ namespace AsbCloudInfrastructure.Repository
{ {
var sourceFaqs = db.Faqs.Where(e => e.Id == sourceId1 || e.Id == sourceId2).ToArray(); var sourceFaqs = db.Faqs.Where(e => e.Id == sourceId1 || e.Id == sourceId2).ToArray();
if (sourceFaqs.Count() < 2) if (sourceFaqs.Count() < 2)
throw new ArgumentInvalidException("Questions with target ids don't exist", nameof(sourceFaqs)); throw new ArgumentInvalidException(nameof(sourceFaqs), "Questions with target ids don't exist");
var newFaq = new Faq() var newFaq = new Faq()
{ {
@ -115,7 +115,7 @@ namespace AsbCloudInfrastructure.Repository
await db.SaveChangesAsync(token).ConfigureAwait(false); await db.SaveChangesAsync(token).ConfigureAwait(false);
if (newFaq.Id == 0) if (newFaq.Id == 0)
throw new ArgumentInvalidException("Error creating new question", nameof(newFaq)); throw new ArgumentInvalidException(nameof(sourceId1), "Error creating new question");
foreach (var sourceFaq in sourceFaqs) foreach (var sourceFaq in sourceFaqs)
{ {
@ -138,9 +138,8 @@ namespace AsbCloudInfrastructure.Repository
public async Task<int> MarkAsDeletedAsync(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(nameof(id), "Question doesn't exist");
throw new ArgumentInvalidException("Question doesn't exist", nameof(id));
entity.State = Faq.StateDeleted; entity.State = Faq.StateDeleted;
entity.DateLastEditedQuestion = DateTimeOffset.UtcNow; entity.DateLastEditedQuestion = DateTimeOffset.UtcNow;
@ -151,9 +150,8 @@ namespace AsbCloudInfrastructure.Repository
public async Task<int> DeleteAsync(int id, CancellationToken token) public async Task<int> DeleteAsync(int id, CancellationToken token)
{ {
var faq = db.Faqs.FirstOrDefault(f => f.Id == id); var faq = db.Faqs.FirstOrDefault(f => f.Id == id)
if (faq is null) ?? throw new ArgumentInvalidException(nameof(id), "Question doesn't exist");
throw new ArgumentInvalidException("Question doesn't exist", nameof(id));
db.Faqs.Remove(faq); db.Faqs.Remove(faq);
return await db.SaveChangesAsync(token); return await db.SaveChangesAsync(token);

View File

@ -28,7 +28,8 @@ namespace AsbCloudInfrastructure.Repository
{ {
var idWell = plannedTrajectoryRows.First().IdWell; var idWell = plannedTrajectoryRows.First().IdWell;
if (!plannedTrajectoryRows.All(r => r.IdWell == idWell)) if (!plannedTrajectoryRows.All(r => r.IdWell == idWell))
throw new ArgumentInvalidException("Все строки должны относиться к одной скважине", nameof(plannedTrajectoryRows)); throw new ArgumentInvalidException(nameof(plannedTrajectoryRows), "Все строки должны относиться к одной скважине");
var offsetHours = wellService.GetTimezone(idWell).Hours; var offsetHours = wellService.GetTimezone(idWell).Hours;
var entities = plannedTrajectoryRows var entities = plannedTrajectoryRows
.Select(e => .Select(e =>
@ -77,9 +78,9 @@ namespace AsbCloudInfrastructure.Repository
/// <inheritdoc/> /// <inheritdoc/>
public async Task<IEnumerable<TrajectoryGeoPlanDto>> GetAsync(int idWell, CancellationToken token) public async Task<IEnumerable<TrajectoryGeoPlanDto>> GetAsync(int idWell, CancellationToken token)
{ {
var well = wellService.GetOrDefault(idWell); var well = wellService.GetOrDefault(idWell)
if (well is null || well.Timezone is null) ?? throw new ArgumentInvalidException(nameof(idWell), "idWell doesn`t exist");
throw new ArgumentInvalidException("idWell doesn`t exist", nameof(idWell));
var offsetHours = well.Timezone.Hours; var offsetHours = well.Timezone.Hours;
var query = db.PlannedTrajectories var query = db.PlannedTrajectories
.AsNoTracking() .AsNoTracking()

View File

@ -97,13 +97,10 @@ namespace AsbCloudInfrastructure.Repository
public async Task<int> UpdateAsync(UserExtendedDto dto, CancellationToken token) public async Task<int> UpdateAsync(UserExtendedDto dto, CancellationToken token)
{ {
if (dto.Id <= 1) if (dto.Id <= 1)
throw new ArgumentInvalidException throw new ArgumentInvalidException(nameof(dto), $"Invalid id {dto.Id}. You can't edit this user.");
($"Invalid id {dto.Id}. You can't edit this user.", nameof(dto));
var oldUser = (await GetCacheUserAsync(token)).FirstOrDefault(u => u.Id == dto.Id); var oldUser = (await GetCacheUserAsync(token)).FirstOrDefault(u => u.Id == dto.Id)
if (oldUser is null) ?? throw new ArgumentInvalidException(nameof(dto), $"Invalid id {dto.Id}. You can't edit this user.");
throw new ArgumentInvalidException
($"Invalid id {dto.Id}. You can't edit this user.", nameof(dto));
if (oldUser.Login != dto.Login) if (oldUser.Login != dto.Login)
await AssertLoginIsBusyAsync(dto.Login, token); await AssertLoginIsBusyAsync(dto.Login, token);
@ -111,10 +108,9 @@ namespace AsbCloudInfrastructure.Repository
var userRoles = await userRoleRepository.GetByNamesAsync(dto.RoleNames, token).ConfigureAwait(false); var userRoles = await userRoleRepository.GetByNamesAsync(dto.RoleNames, token).ConfigureAwait(false);
await UpdateRolesCacheForUserAsync(dto.Id, userRoles, token); await UpdateRolesCacheForUserAsync(dto.Id, userRoles, token);
var entity = dbContext.Users.FirstOrDefault(u => u.Id == dto.Id); var entity = dbContext.Users.FirstOrDefault(u => u.Id == dto.Id)
if (entity is null) ?? throw new ArgumentInvalidException(nameof(dto), $"Invalid id {dto.Id}. You can't edit this user.");
throw new ArgumentInvalidException
($"Invalid id {dto.Id}. You can't edit this user.", nameof(dto));
entity.Id = dto.Id; entity.Id = dto.Id;
entity.Login = dto.Login; entity.Login = dto.Login;
entity.Name = dto.Name; entity.Name = dto.Name;
@ -132,10 +128,9 @@ namespace AsbCloudInfrastructure.Repository
public async Task<int> DeleteAsync(int id, CancellationToken token) public async Task<int> DeleteAsync(int id, CancellationToken token)
{ {
var user = (await GetCacheUserAsync(token)).FirstOrDefault(u => u.Id == id); var user = (await GetCacheUserAsync(token)).FirstOrDefault(u => u.Id == id)
if (user is null) ?? throw new ArgumentInvalidException(nameof(id), $"Invalid id {id}. You can't edit this user.");
throw new ArgumentInvalidException
($"Invalid id {id}. You can't edit this user.", nameof(id));
var query = dbContext var query = dbContext
.Users .Users
.Where(u => u.Id == id); .Where(u => u.Id == id);
@ -147,7 +142,7 @@ namespace AsbCloudInfrastructure.Repository
return result.Entity.Id; return result.Entity.Id;
} }
throw new ArgumentInvalidException throw new ArgumentInvalidException
($"Invalid id {id}. You can't edit this user.", nameof(id)); (nameof(id), $"Invalid id {id}. You can't edit this user.");
} }
public IEnumerable<UserRoleDto> GetRolesByIdUser(int idUser, int nestedLevel = 0) public IEnumerable<UserRoleDto> GetRolesByIdUser(int idUser, int nestedLevel = 0)
@ -161,6 +156,7 @@ namespace AsbCloudInfrastructure.Repository
var roles = GetRolesByIdUser(idUser, 7); var roles = GetRolesByIdUser(idUser, 7);
if (roles is null) if (roles is null)
return Enumerable.Empty<PermissionDto>(); return Enumerable.Empty<PermissionDto>();
var permissions = roles var permissions = roles
.Where(r => r.Permissions is not null) .Where(r => r.Permissions is not null)
.SelectMany(r => r.Permissions); .SelectMany(r => r.Permissions);
@ -198,9 +194,8 @@ namespace AsbCloudInfrastructure.Repository
.FirstOrDefault(u => u.Login.ToLower() == login.ToLower()); .FirstOrDefault(u => u.Login.ToLower() == login.ToLower());
if (existingUserDto is not null) if (existingUserDto is not null)
throw new ArgumentInvalidException($"Login {login} is busy by {existingUserDto.MakeDisplayName()}, id{existingUserDto.Id}", nameof(login)); throw new ArgumentInvalidException(nameof(login), $"Login {login} is busy by {existingUserDto.MakeDisplayName()}, id{existingUserDto.Id}");
} }
private IEnumerable<RelationUserUserRole> GetCachRelationUserUserRoleCacheTag() private IEnumerable<RelationUserUserRole> GetCachRelationUserUserRoleCacheTag()
{ {
@ -215,7 +210,8 @@ namespace AsbCloudInfrastructure.Repository
return entities; return entities;
}); });
return cache!; return cache!;
} }
private void DropCacheRelationUserUserRoleCacheTag() private void DropCacheRelationUserUserRoleCacheTag()
{ {
memoryCache.Remove(relationUserUserRoleCacheTag); memoryCache.Remove(relationUserUserRoleCacheTag);

View File

@ -85,7 +85,7 @@ namespace AsbCloudInfrastructure.Repository
.Where(r => names.Contains(r.Caption)); .Where(r => names.Contains(r.Caption));
if (entities?.Count() != names.Count()) if (entities?.Count() != names.Count())
throw new ArgumentInvalidException("Invalid role names", nameof(names)); throw new ArgumentInvalidException(nameof(names), "Invalid role names");
return entities.Select(Convert); return entities.Select(Convert);
} }
@ -196,7 +196,7 @@ namespace AsbCloudInfrastructure.Repository
var idsIncludeRole = GetNestedByIds(dto.Roles.Select(x => x.Id)).Select(x => x.Id); var idsIncludeRole = GetNestedByIds(dto.Roles.Select(x => x.Id)).Select(x => x.Id);
if (idsIncludeRole.Any(x => x == dto.Id)) if (idsIncludeRole.Any(x => x == dto.Id))
throw new ArgumentInvalidException("Invalid include role (self reference)", nameof(dto)); throw new ArgumentInvalidException(nameof(dto), "Invalid include role (self reference)");
var removeRelationsQuery = dbContext.RelationUserRoleUserRoles var removeRelationsQuery = dbContext.RelationUserRoleUserRoles
.Where(r => r.Id == dto.Id); .Where(r => r.Id == dto.Id);

View File

@ -32,10 +32,10 @@ namespace AsbCloudInfrastructure.Repository
} }
///<inheritdoc/> ///<inheritdoc/>
public async Task<IEnumerable<WellFinalDocumentDBDto>> UpdateRangeAsync(int idWell, IEnumerable<WellFinalDocumentInputDto>? dtos, CancellationToken token) public async Task<IEnumerable<WellFinalDocumentDBDto>> UpdateRangeAsync(int idWell, IEnumerable<WellFinalDocumentInputDto> dtos, CancellationToken token)
{ {
if (dtos is null) if (!dtos.Any())
throw new ArgumentInvalidException("Данные по категориям отсутствуют.", nameof(dtos)); throw new ArgumentInvalidException(nameof(dtos), "Данные по категориям отсутствуют.");
var entities = dtos var entities = dtos
.Where(dto => dto.IdsPublishers?.Any() == true) .Where(dto => dto.IdsPublishers?.Any() == true)
@ -128,11 +128,8 @@ namespace AsbCloudInfrastructure.Repository
{ {
var entity = await context.WellFinalDocuments var entity = await context.WellFinalDocuments
.AsNoTracking() .AsNoTracking()
.FirstOrDefaultAsync(x => x.IdWell == idWell && x.IdCategory == idCategory && x.IdUser == idUser, token); .FirstOrDefaultAsync(x => x.IdWell == idWell && x.IdCategory == idCategory && x.IdUser == idUser, token)
?? throw new ArgumentInvalidException(nameof(idUser), "Пользователь не является ответственным за загрузку файла для данной категории.");
if (entity is null)
throw new ArgumentInvalidException("Пользователь не является ответственным за загрузку файла для данной категории.", nameof(entity));
var dto = Convert(entity); var dto = Convert(entity);
return dto; return dto;
} }

View File

@ -79,10 +79,8 @@ namespace AsbCloudInfrastructure.Services
/// <inheritdoc/> /// <inheritdoc/>
public void Register(UserRegistrationDto userDto) public void Register(UserRegistrationDto userDto)
{ {
var user = db.Users.FirstOrDefault(u => u.Login == userDto.Login); var user = db.Users.FirstOrDefault(u => u.Login == userDto.Login)
?? throw new ArgumentInvalidException(nameof(userDto.Login), "Логин уже занят");
if (user is not null)
throw new ArgumentInvalidException("Логин уже занят", nameof(userDto.Login));
var salt = GenerateSalt(); var salt = GenerateSalt();
@ -114,7 +112,7 @@ namespace AsbCloudInfrastructure.Services
public void ChangePassword(string userLogin, string newPassword) public void ChangePassword(string userLogin, string newPassword)
{ {
var user = db.Users.FirstOrDefault(u => u.Login == userLogin) var user = db.Users.FirstOrDefault(u => u.Login == userLogin)
?? throw new ArgumentInvalidException("Логин не зарегистрирован", nameof(userLogin)); ?? throw new ArgumentInvalidException(nameof(userLogin), "Логин не зарегистрирован");
var salt = GenerateSalt(); var salt = GenerateSalt();
user.PasswordHash = salt + ComputeHash(salt, newPassword); user.PasswordHash = salt + ComputeHash(salt, newPassword);
@ -125,7 +123,7 @@ namespace AsbCloudInfrastructure.Services
public void ChangePassword(int idUser, string newPassword) public void ChangePassword(int idUser, string newPassword)
{ {
var user = db.Users.FirstOrDefault(u => u.Id == idUser) var user = db.Users.FirstOrDefault(u => u.Id == idUser)
?? throw new ArgumentInvalidException($"Пользователь с idUser:{idUser} не зарегистрирован", nameof(idUser)); ?? throw new ArgumentInvalidException(nameof(idUser), $"Пользователь с idUser:{idUser} не зарегистрирован");
var salt = GenerateSalt(); var salt = GenerateSalt();
user.PasswordHash = salt + ComputeHash(salt, newPassword); user.PasswordHash = salt + ComputeHash(salt, newPassword);

View File

@ -57,10 +57,10 @@ public class AutoGeneratedDailyReportService : IAutoGeneratedDailyReportService
var reports = new List<AutoGeneratedDailyReportInfoDto>(); var reports = new List<AutoGeneratedDailyReportInfoDto>();
var well = await wellService.GetOrDefaultAsync(idWell, cancellationToken) var well = await wellService.GetOrDefaultAsync(idWell, cancellationToken)
?? throw new ArgumentInvalidException("Скважина не найдена", nameof(idWell)); ?? throw new ArgumentInvalidException(nameof(idWell), "Скважина не найдена");
if (!well.IdTelemetry.HasValue) if (!well.IdTelemetry.HasValue)
throw new ArgumentInvalidException("Телеметрия для скважины отсутствует", nameof(idWell)); throw new ArgumentInvalidException(nameof(idWell), "Телеметрия для скважины отсутствует");
var datesRange = await GetDatesRangeAsync(idWell, cancellationToken); var datesRange = await GetDatesRangeAsync(idWell, cancellationToken);
@ -112,10 +112,10 @@ public class AutoGeneratedDailyReportService : IAutoGeneratedDailyReportService
var finishDate = startDate.AddDays(1); var finishDate = startDate.AddDays(1);
var well = await wellService.GetOrDefaultAsync(idWell, cancellationToken) var well = await wellService.GetOrDefaultAsync(idWell, cancellationToken)
?? throw new ArgumentInvalidException("Скважина не найдена", nameof(idWell)); ?? throw new ArgumentInvalidException(nameof(idWell), "Скважина не найдена");
if (!well.IdTelemetry.HasValue) if (!well.IdTelemetry.HasValue)
throw new ArgumentInvalidException("Телеметрия для скважины отсутствует", nameof(idWell)); throw new ArgumentInvalidException(nameof(idWell), "Телеметрия для скважины отсутствует");
var factOperations = await GetFactOperationsAsync(well.Id, startDate, finishDate, var factOperations = await GetFactOperationsAsync(well.Id, startDate, finishDate,
cancellationToken); cancellationToken);

View File

@ -42,9 +42,8 @@ namespace AsbCloudInfrastructure.Services.DailyReport
public async Task<IEnumerable<DailyReportDto>> GetListAsync(int idWell, DateOnly? begin, DateOnly? end, CancellationToken token) public async Task<IEnumerable<DailyReportDto>> GetListAsync(int idWell, DateOnly? begin, DateOnly? end, CancellationToken token)
{ {
var well = wellService.GetOrDefault(idWell); var well = wellService.GetOrDefault(idWell)
if (well is null || well.Timezone is null) ?? throw new ArgumentInvalidException(nameof(idWell), "idWell doesn`t exist");
throw new ArgumentInvalidException("idWell doesn`t exist", nameof(idWell));
var query = db.DailyReports.Where(r => r.IdWell == idWell); var query = db.DailyReports.Where(r => r.IdWell == idWell);
@ -90,15 +89,13 @@ namespace AsbCloudInfrastructure.Services.DailyReport
public async Task<int> AddAsync(int idWell, DateOnly startDate, int idUser, CancellationToken token) public async Task<int> AddAsync(int idWell, DateOnly startDate, int idUser, CancellationToken token)
{ {
var well = wellService.GetOrDefault(idWell); var well = wellService.GetOrDefault(idWell)
if (well is null) ?? throw new ArgumentInvalidException(nameof(idWell), "idWell doesn`t exist");
throw new ArgumentInvalidException("idWell doesn`t exist", nameof(idWell));
var hasEntity = await db.DailyReports var hasEntity = await db.DailyReports
.AnyAsync(r => r.IdWell == idWell && r.StartDate == startDate, token); .AnyAsync(r => r.IdWell == idWell && r.StartDate == startDate, token);
if (hasEntity) if (hasEntity)
throw new ArgumentInvalidException($"daily report on {startDate} already exists", nameof(startDate)); throw new ArgumentInvalidException(nameof(startDate), $"daily report on {startDate} already exists");
var entity = new AsbCloudDb.Model.DailyReport.DailyReport var entity = new AsbCloudDb.Model.DailyReport.DailyReport
{ {
@ -116,14 +113,11 @@ namespace AsbCloudInfrastructure.Services.DailyReport
public async Task<int> UpdateBlockAsync(int idWell, DateOnly startDate, ItemInfoDto dto, CancellationToken token) public async Task<int> UpdateBlockAsync(int idWell, DateOnly startDate, ItemInfoDto dto, CancellationToken token)
{ {
var well = wellService.GetOrDefault(idWell); var well = wellService.GetOrDefault(idWell)
if (well is null) ?? throw new ArgumentInvalidException(nameof(idWell), "idWell doesn`t exist");
throw new ArgumentInvalidException("idWell doesn`t exist", nameof(idWell));
var entity = await db.DailyReports.FirstOrDefaultAsync(r => r.IdWell == idWell && r.StartDate == startDate, token); var entity = await db.DailyReports.FirstOrDefaultAsync(r => r.IdWell == idWell && r.StartDate == startDate, token)
?? throw new ArgumentInvalidException(nameof(startDate), "Daily report doesn`t exist");
if (entity is null)
throw new ArgumentInvalidException("Daily report doesn`t exist", nameof(startDate));
dto.LastUpdateDate = DateTimeOffset.Now; dto.LastUpdateDate = DateTimeOffset.Now;
if (dto is HeadDto headDto) if (dto is HeadDto headDto)
@ -161,10 +155,8 @@ namespace AsbCloudInfrastructure.Services.DailyReport
private async Task<DailyReportDto?> GetOrDefaultAsync(int idWell, DateOnly date, CancellationToken token) private async Task<DailyReportDto?> GetOrDefaultAsync(int idWell, DateOnly date, CancellationToken token)
{ {
var entity = await db.DailyReports var entity = await db.DailyReports
.FirstOrDefaultAsync(r => r.IdWell == idWell && r.StartDate == date, token); .FirstOrDefaultAsync(r => r.IdWell == idWell && r.StartDate == date, token)
?? throw new ArgumentInvalidException(nameof(date), "Daily report doesn`t exist");
if (entity is null)
throw new ArgumentInvalidException("Daily report doesn`t exist", nameof(date));
var factOperationsForDtos = await GetFactOperationsForDailyReportAsync(idWell, token); var factOperationsForDtos = await GetFactOperationsForDailyReportAsync(idWell, token);
var userDtos = await userRepository.GetAllAsync(token); var userDtos = await userRepository.GetAllAsync(token);

View File

@ -185,10 +185,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
var part = await context.DrillingProgramParts var part = await context.DrillingProgramParts
.Include(p => p.RelatedUsers) .Include(p => p.RelatedUsers)
.ThenInclude(r => r.User) .ThenInclude(r => r.User)
.FirstOrDefaultAsync(p => p.IdWell == idWell && p.IdFileCategory == idFileCategory, token); .FirstOrDefaultAsync(p => p.IdWell == idWell && p.IdFileCategory == idFileCategory, token)
?? throw new ArgumentInvalidException(nameof(idFileCategory), $"DrillingProgramPart id == {idFileCategory} does not exist");
if (part == null)
throw new ArgumentInvalidException($"DrillingProgramPart id == {idFileCategory} does not exist", nameof(idFileCategory));
if (!part.RelatedUsers.Any(r => r.IdUser == idUser && r.IdUserRole == idUserRolePublisher)) if (!part.RelatedUsers.Any(r => r.IdUser == idUser && r.IdUserRole == idUserRolePublisher))
throw new ForbidException($"User {idUser} is not in the publisher list."); throw new ForbidException($"User {idUser} is not in the publisher list.");
@ -246,19 +244,16 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
public async Task<int> AddUserAsync(int idWell, int idFileCategory, int idUser, int idUserRole, CancellationToken token = default) public async Task<int> AddUserAsync(int idWell, int idFileCategory, int idUser, int idUserRole, CancellationToken token = default)
{ {
var user = await userRepository.GetOrDefaultAsync(idUser, token); var user = await userRepository.GetOrDefaultAsync(idUser, token)
if (user is null) ?? throw new ArgumentInvalidException(nameof(idUser), $"User id: {idUser} does not exist");
throw new ArgumentInvalidException($"User id == {idUser} does not exist", nameof(idUser));
var part = await context.DrillingProgramParts var part = await context.DrillingProgramParts
.Include(p => p.FileCategory) .Include(p => p.FileCategory)
.FirstOrDefaultAsync(p => p.IdWell == idWell && p.IdFileCategory == idFileCategory, token); .FirstOrDefaultAsync(p => p.IdWell == idWell && p.IdFileCategory == idFileCategory, token)
?? throw new ArgumentInvalidException(nameof(idFileCategory), $"DrillingProgramPart idFileCategory: {idFileCategory} does not exist");
if (part is null)
throw new ArgumentInvalidException($"DrillingProgramPart idFileCategory == {idFileCategory} does not exist", nameof(idFileCategory));
if (idUserRole != idUserRoleApprover && idUserRole != idUserRolePublisher) if (idUserRole != idUserRoleApprover && idUserRole != idUserRolePublisher)
throw new ArgumentInvalidException($"idUserRole ({idUserRole}), should be approver ({idUserRoleApprover}) or publisher ({idUserRolePublisher})", nameof(idUserRole)); throw new ArgumentInvalidException(nameof(idUserRole), $"idUserRole ({idUserRole}), should be approver ({idUserRoleApprover}) or publisher ({idUserRolePublisher})");
var oldRelation = await context.RelationDrillingProgramPartUsers var oldRelation = await context.RelationDrillingProgramPartUsers
.FirstOrDefaultAsync(r => r.IdUser == idUser && r.IdDrillingProgramPart == part.Id, token); .FirstOrDefaultAsync(r => r.IdUser == idUser && r.IdDrillingProgramPart == part.Id, token);
@ -300,17 +295,14 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
{ {
if (fileMarkDto.IdMarkType != idMarkTypeApprove && if (fileMarkDto.IdMarkType != idMarkTypeApprove &&
fileMarkDto.IdMarkType != idMarkTypeReject) fileMarkDto.IdMarkType != idMarkTypeReject)
throw new ArgumentInvalidException($"В этом методе допустимы только отметки о принятии или отклонении.", nameof(fileMarkDto)); throw new ArgumentInvalidException(nameof(fileMarkDto), $"В этом методе допустимы только отметки о принятии или отклонении.");
var fileInfo = await fileService.GetOrDefaultAsync(fileMarkDto.IdFile, token) var fileInfo = await fileService.GetOrDefaultAsync(fileMarkDto.IdFile, token)
.ConfigureAwait(false); ?? throw new ArgumentInvalidException(nameof(fileMarkDto), $"Файла для такой отметки не существует.");
if (fileInfo is null)
throw new ArgumentInvalidException($"Файла для такой отметки не существует.", nameof(fileMarkDto));
if (fileInfo.IdCategory < idFileCategoryDrillingProgramPartsStart || if (fileInfo.IdCategory < idFileCategoryDrillingProgramPartsStart ||
fileInfo.IdCategory > idFileCategoryDrillingProgramPartsEnd) fileInfo.IdCategory > idFileCategoryDrillingProgramPartsEnd)
throw new ArgumentInvalidException($"Этот метод допустим только для файлов-частей программы бурения.", nameof(fileMarkDto)); throw new ArgumentInvalidException(nameof(fileMarkDto), $"Этот метод допустим только для файлов-частей программы бурения.");
var part = await context.DrillingProgramParts var part = await context.DrillingProgramParts
.Include(p => p.RelatedUsers) .Include(p => p.RelatedUsers)
@ -318,9 +310,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
.AsNoTracking() .AsNoTracking()
.FirstOrDefaultAsync(p => p.IdWell == fileInfo.IdWell && p.IdFileCategory == fileInfo.IdCategory, token); .FirstOrDefaultAsync(p => p.IdWell == fileInfo.IdWell && p.IdFileCategory == fileInfo.IdCategory, token);
var user = part?.RelatedUsers.FirstOrDefault(r => r.IdUser == idUser && r.IdUserRole == idUserRoleApprover)?.User; var user = part?.RelatedUsers.FirstOrDefault(r => r.IdUser == idUser && r.IdUserRole == idUserRoleApprover)?.User
if (user is null) ?? throw new ForbidException($"User {idUser} is not in the approvers list.");
throw new ForbidException($"User {idUser} is not in the approvers list.");
fileMarkDto.User = user.Adapt<UserDto>(); fileMarkDto.User = user.Adapt<UserDto>();
@ -363,7 +354,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
if (fileInfo.IdCategory < idFileCategoryDrillingProgramPartsStart || if (fileInfo.IdCategory < idFileCategoryDrillingProgramPartsStart ||
fileInfo.IdCategory > idFileCategoryDrillingProgramPartsEnd) fileInfo.IdCategory > idFileCategoryDrillingProgramPartsEnd)
throw new ArgumentInvalidException($"Этот метод допустим только для файлов-частей программы бурения.", nameof(idMark)); throw new ArgumentInvalidException(nameof(idMark), $"Этот метод допустим только для файлов-частей программы бурения.");
var result = await fileService.MarkFileMarkAsDeletedAsync(idMark, token) var result = await fileService.MarkFileMarkAsDeletedAsync(idMark, token)
.ConfigureAwait(false); .ConfigureAwait(false);
@ -375,9 +366,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
private async Task NotifyPublisherOnFullAccepAsync(FileMarkDto fileMark, CancellationToken token) private async Task NotifyPublisherOnFullAccepAsync(FileMarkDto fileMark, CancellationToken token)
{ {
var file = await fileService.GetOrDefaultAsync(fileMark.IdFile, token); var file = await fileService.GetOrDefaultAsync(fileMark.IdFile, token);
var well = await wellService.GetOrDefaultAsync(file!.IdWell, token); var well = await wellService.GetOrDefaultAsync(file!.IdWell, token)
if (well is null) ?? throw new ArgumentInvalidException(nameof(file.IdWell), "idWell doesn`t exist");
throw new ArgumentInvalidException("idWell doesn`t exist", nameof(file.IdWell));
var user = file.Author!; var user = file.Author!;
var factory = new DrillingMailBodyFactory(configuration); var factory = new DrillingMailBodyFactory(configuration);
@ -397,9 +387,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
private async Task NotifyPublisherOnRejectAsync(FileMarkDto fileMark, CancellationToken token) private async Task NotifyPublisherOnRejectAsync(FileMarkDto fileMark, CancellationToken token)
{ {
var file = await fileService.GetOrDefaultAsync(fileMark.IdFile, token); var file = await fileService.GetOrDefaultAsync(fileMark.IdFile, token);
var well = await wellService.GetOrDefaultAsync(file!.IdWell, token); var well = await wellService.GetOrDefaultAsync(file!.IdWell, token)
if (well is null) ?? throw new ArgumentInvalidException(nameof(file.IdWell), "idWell doesn`t exist");
throw new ArgumentInvalidException("idWell doesn`t exist", nameof(file.IdWell));
var user = file.Author!; var user = file.Author!;
var factory = new DrillingMailBodyFactory(configuration); var factory = new DrillingMailBodyFactory(configuration);
@ -418,9 +407,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
private async Task NotifyApproversAsync(DrillingProgramPart part, int idFile, string fileName, CancellationToken token) private async Task NotifyApproversAsync(DrillingProgramPart part, int idFile, string fileName, CancellationToken token)
{ {
var well = await wellService.GetOrDefaultAsync(part.IdWell, token); var well = await wellService.GetOrDefaultAsync(part.IdWell, token)
if (well is null) ?? throw new ArgumentInvalidException(nameof(part.IdWell), "idWell doesn`t exist");
throw new ArgumentInvalidException("idWell doesn`t exist", nameof(part.IdWell));
var factory = new DrillingMailBodyFactory(configuration); var factory = new DrillingMailBodyFactory(configuration);
var subject = factory.MakeSubject(well, "Загружен новый документ для согласования."); var subject = factory.MakeSubject(well, "Загружен новый документ для согласования.");
@ -444,9 +432,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
private async Task NotifyNewPublisherAsync(int idWell, UserDto user, string documentCategory, CancellationToken token) private async Task NotifyNewPublisherAsync(int idWell, UserDto user, string documentCategory, CancellationToken token)
{ {
var well = await wellService.GetOrDefaultAsync(idWell, token); var well = await wellService.GetOrDefaultAsync(idWell, token)
if (well is null) ?? throw new ArgumentInvalidException(nameof(idWell), "idWell doesn`t exist");
throw new ArgumentInvalidException("idWell doesn`t exist", nameof(idWell));
var factory = new DrillingMailBodyFactory(configuration); var factory = new DrillingMailBodyFactory(configuration);
var subject = factory.MakeSubject(well, $"От вас ожидается загрузка на портал документа «{documentCategory}»"); var subject = factory.MakeSubject(well, $"От вас ожидается загрузка на портал документа «{documentCategory}»");

View File

@ -25,7 +25,7 @@ namespace AsbCloudInfrastructure.Services.Email
public static string GetOrEmptyImageBase64(string resourceFileName) public static string GetOrEmptyImageBase64(string resourceFileName)
{ {
if (string.IsNullOrEmpty(resourceFileName)) if (string.IsNullOrEmpty(resourceFileName))
throw new ArgumentInvalidException("ResourceFileName doesn`t exist", nameof(resourceFileName)); throw new ArgumentInvalidException(nameof(resourceFileName), "ResourceFileName doesn`t exist");
var baseDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) var baseDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
?? string.Empty; ?? string.Empty;

View File

@ -70,26 +70,22 @@ namespace AsbCloudInfrastructure.Services.Email
return Task.WhenAll(tasks); return Task.WhenAll(tasks);
} }
private Func<string, IServiceProvider, CancellationToken, Task> MakeEmailSendWorkAction(NotificationDto notification) private Func<string, IServiceProvider, CancellationToken, Task> MakeEmailSendWorkAction(NotificationDto notification)
{ {
if (string.IsNullOrWhiteSpace(notification.Title))
throw new ArgumentInvalidException($"{nameof(notification.Title)} should be set", nameof(notification.Title));
return async (_, serviceProvider, token) => return async (_, serviceProvider, token) =>
{ {
var notificationRepository = serviceProvider.GetRequiredService<INotificationRepository>(); var notificationRepository = serviceProvider.GetRequiredService<INotificationRepository>();
var userRepository = serviceProvider.GetRequiredService<IUserRepository>(); var userRepository = serviceProvider.GetRequiredService<IUserRepository>();
var user = await userRepository.GetOrDefaultAsync(notification.IdUser, token) var user = await userRepository.GetOrDefaultAsync(notification.IdUser, token)
?? throw new ArgumentInvalidException("Пользователь не найден" , nameof(notification.IdUser)); ?? throw new ArgumentInvalidException(nameof(notification.IdUser), "Пользователь не найден");
if(!MailAddress.TryCreate(user.Email, out var mailAddress)) if(!MailAddress.TryCreate(user.Email, out var mailAddress))
{
Trace.TraceWarning($"Mail {user.Email} is not correct."); Trace.TraceWarning($"Mail {user.Email} is not correct.");
throw new ArgumentInvalidException(nameof(user.Email), $"Mail {user.Email} is not null.");
}
if (mailAddress is null)
throw new ArgumentInvalidException($"Mail {user.Email} is not null.", nameof(user.Email));
var from = new MailAddress(sender); var from = new MailAddress(sender);
var message = new MailMessage var message = new MailMessage
{ {

View File

@ -47,8 +47,8 @@ public class ManualCatalogService : IManualCatalogService
if (!validExtensions.Contains(extension)) if (!validExtensions.Contains(extension))
throw new ArgumentInvalidException( throw new ArgumentInvalidException(
$"Невозможно загрузить файл с расширением '{extension}'. Допустимые форматы файлов: {string.Join(", ", validExtensions)}", nameof(name),
extension); $"Невозможно загрузить файл с расширением '{extension}'. Допустимые форматы файлов: {string.Join(", ", validExtensions)}");
var path = await BuildFilePathAsync(idDirectory, name, cancellationToken); var path = await BuildFilePathAsync(idDirectory, name, cancellationToken);
@ -69,7 +69,7 @@ public class ManualCatalogService : IManualCatalogService
public async Task<int> AddDirectoryAsync(string name, int? idParent, CancellationToken cancellationToken) public async Task<int> AddDirectoryAsync(string name, int? idParent, CancellationToken cancellationToken)
{ {
if (idParent.HasValue && !await manualDirectoryRepository.IsExistsAsync(idParent.Value, cancellationToken)) if (idParent.HasValue && !await manualDirectoryRepository.IsExistsAsync(idParent.Value, cancellationToken))
throw new ArgumentInvalidException("Родительской директории не существует", nameof(idParent)); throw new ArgumentInvalidException(nameof(idParent), "Родительской директории не существует");
var directory = new ManualDirectoryDto var directory = new ManualDirectoryDto
{ {
@ -78,7 +78,7 @@ public class ManualCatalogService : IManualCatalogService
}; };
if (await IsExistDirectoryAsync(directory, cancellationToken)) if (await IsExistDirectoryAsync(directory, cancellationToken))
throw new ArgumentInvalidException("Директория с таким названием уже существует", name); throw new ArgumentInvalidException(name, "Директория с таким названием уже существует");
return await manualDirectoryRepository.InsertAsync(directory, cancellationToken); return await manualDirectoryRepository.InsertAsync(directory, cancellationToken);
} }
@ -86,12 +86,12 @@ public class ManualCatalogService : IManualCatalogService
public async Task UpdateDirectoryAsync(int id, string name, CancellationToken cancellationToken) public async Task UpdateDirectoryAsync(int id, string name, CancellationToken cancellationToken)
{ {
var directory = await manualDirectoryRepository.GetOrDefaultAsync(id, cancellationToken) var directory = await manualDirectoryRepository.GetOrDefaultAsync(id, cancellationToken)
?? throw new ArgumentInvalidException($"Директории с Id: {id} не существует", nameof(id)); ?? throw new ArgumentInvalidException(nameof(id), $"Директории с Id: {id} не существует");
directory.Name = name; directory.Name = name;
if (await IsExistDirectoryAsync(directory, cancellationToken)) if (await IsExistDirectoryAsync(directory, cancellationToken))
throw new ArgumentInvalidException("Директория с таким названием уже существует", name); throw new ArgumentInvalidException(name, "Директория с таким названием уже существует");
await manualDirectoryRepository.UpdateAsync(directory, cancellationToken); await manualDirectoryRepository.UpdateAsync(directory, cancellationToken);
} }
@ -112,7 +112,7 @@ public class ManualCatalogService : IManualCatalogService
} }
catch (InvalidOperationException ex) catch (InvalidOperationException ex)
{ {
throw new ArgumentInvalidException(ex.Message, nameof(id)); throw new ArgumentInvalidException(nameof(id), ex.Message);
} }
return await manualDirectoryRepository.DeleteAsync(directory.Id, cancellationToken); return await manualDirectoryRepository.DeleteAsync(directory.Id, cancellationToken);
@ -157,15 +157,14 @@ public class ManualCatalogService : IManualCatalogService
var directiories = await manualDirectoryRepository.GetAllAsync(cancellationToken); var directiories = await manualDirectoryRepository.GetAllAsync(cancellationToken);
var directory = directiories.FirstOrDefault(d => d.Id == idDirectory) var directory = directiories.FirstOrDefault(d => d.Id == idDirectory)
?? throw new ArgumentInvalidException($"Директории с Id: {idDirectory} не существует", nameof(idDirectory)); ?? throw new ArgumentInvalidException(nameof(idDirectory), $"Директории с Id: {idDirectory} не существует");
var pathSegments = new List<int> { directory.Id }; var pathSegments = new List<int> { directory.Id };
while (directory.IdParent.HasValue) while (directory.IdParent.HasValue)
{ {
directory = directiories.FirstOrDefault(d => d.Id == directory.IdParent.Value); directory = directiories.FirstOrDefault(d => d.Id == directory.IdParent.Value);
pathSegments.Insert(0, directory!.Id);
pathSegments.Insert(0, directory.Id);
} }
return string.Join("/", pathSegments); return string.Join("/", pathSegments);

View File

@ -84,9 +84,9 @@ namespace AsbCloudInfrastructure.Services
public Task<int> InsertAsync(int idWell, MeasureDto dto, CancellationToken token) public Task<int> InsertAsync(int idWell, MeasureDto dto, CancellationToken token)
{ {
if (dto.IdCategory < 1) if (dto.IdCategory < 1)
throw new ArgumentInvalidException("wrong idCategory", nameof(dto)); throw new ArgumentInvalidException(nameof(dto), "wrong idCategory");
if (dto.Data is null) if (!dto.Data.Any())
throw new ArgumentInvalidException("data.data is not optional", nameof(dto)); throw new ArgumentInvalidException(nameof(dto), "data.data is not optional");
var timezone = wellService.GetTimezone(idWell); var timezone = wellService.GetTimezone(idWell);
var entity = Convert(dto, timezone.Hours); var entity = Convert(dto, timezone.Hours);
entity.IdWell = idWell; entity.IdWell = idWell;
@ -97,19 +97,16 @@ namespace AsbCloudInfrastructure.Services
public async Task<int> UpdateAsync(int idWell, MeasureDto dto, CancellationToken token) public async Task<int> UpdateAsync(int idWell, MeasureDto dto, CancellationToken token)
{ {
if (dto.Id < 1) if (dto.Id < 1)
throw new ArgumentInvalidException("wrong id", nameof(dto)); throw new ArgumentInvalidException(nameof(dto), "wrong id");
if (dto.IdCategory < 1) if (dto.IdCategory < 1)
throw new ArgumentInvalidException("wrong idCategory", nameof(dto)); throw new ArgumentInvalidException(nameof(dto), "wrong idCategory");
if (dto.Data is null) if (!dto.Data.Any())
throw new ArgumentInvalidException("data.data is not optional", nameof(dto)); throw new ArgumentInvalidException(nameof(dto), "data.data is not optional");
var entity = await db.Measures var entity = await db.Measures
.Where(m => m.Id == dto.Id && !m.IsDeleted) .Where(m => m.Id == dto.Id && !m.IsDeleted)
.FirstOrDefaultAsync(token) .FirstOrDefaultAsync(token)
.ConfigureAwait(false); ?? throw new ArgumentInvalidException(nameof(dto), "id doesn't exist");
if (entity is null)
throw new ArgumentInvalidException("id doesn't exist", nameof(dto));
var timezone = wellService.GetTimezone(idWell); var timezone = wellService.GetTimezone(idWell);
entity.IdWell = idWell; entity.IdWell = idWell;
@ -122,14 +119,11 @@ namespace AsbCloudInfrastructure.Services
public async Task<int> MarkAsDeleteAsync(int idWell, int idData, CancellationToken token) public async Task<int> MarkAsDeleteAsync(int idWell, int idData, CancellationToken token)
{ {
if (idData < 1) if (idData < 1)
throw new ArgumentInvalidException("wrong id", nameof(idData)); throw new ArgumentInvalidException(nameof(idData), "wrong id");
var entity = await db.Measures.Where(m => m.IdWell == idWell && m.Id == idData) var entity = await db.Measures.Where(m => m.IdWell == idWell && m.Id == idData)
.FirstOrDefaultAsync(token) .FirstOrDefaultAsync(token)
.ConfigureAwait(false); ?? throw new ArgumentInvalidException(nameof(idWell), $"Measure doesn't exist");
if (entity is null)
throw new ArgumentInvalidException($"Measure doesn't exist", nameof(idWell));
entity.IsDeleted = true; entity.IsDeleted = true;
@ -139,7 +133,7 @@ namespace AsbCloudInfrastructure.Services
public Task<int> DeleteAsync(int idWell, int idData, CancellationToken token) public Task<int> DeleteAsync(int idWell, int idData, CancellationToken token)
{ {
if (idData < 1) if (idData < 1)
throw new ArgumentInvalidException("wrong id", nameof(idData)); throw new ArgumentInvalidException(nameof(idData), "wrong id");
db.Measures.RemoveRange(db.Measures.Where(m => m.IdWell == idWell && m.Id == idData)); db.Measures.RemoveRange(db.Measures.Where(m => m.IdWell == idWell && m.Id == idData));
return db.SaveChangesAsync(token); return db.SaveChangesAsync(token);
} }

View File

@ -35,10 +35,10 @@ namespace AsbCloudInfrastructure.Services.ProcessMap
public async Task<IEnumerable<ProcessMapReportDto>> GetProcessMapReportAsync(int idWell, CancellationToken token) public async Task<IEnumerable<ProcessMapReportDto>> GetProcessMapReportAsync(int idWell, CancellationToken token)
{ {
var well = wellService.GetOrDefault(idWell) var well = wellService.GetOrDefault(idWell)
?? throw new ArgumentInvalidException("idWell not found", nameof(idWell)); ?? throw new ArgumentInvalidException(nameof(idWell), "idWell not found");
var idTelemetry = well.IdTelemetry var idTelemetry = well.IdTelemetry
?? throw new ArgumentInvalidException("telemetry by well not found", nameof(idWell)); ?? throw new ArgumentInvalidException(nameof(idWell), "telemetry by well not found");
var processMapPlan = await processMapPlanRepository.GetByIdWellAsync(idWell, token); var processMapPlan = await processMapPlanRepository.GetByIdWellAsync(idWell, token);

View File

@ -26,15 +26,9 @@ public class ProcessMapWellboreDevelopmentService : IProcessMapWellboreDevelopme
public async Task<int> InsertAsync(ProcessMapWellboreDevelopmentDto processMapWellboreDevelopment, CancellationToken cancellationToken) public async Task<int> InsertAsync(ProcessMapWellboreDevelopmentDto processMapWellboreDevelopment, CancellationToken cancellationToken)
{ {
var well = await wellService.GetOrDefaultAsync(processMapWellboreDevelopment.IdWell, cancellationToken); var well = await wellService.GetOrDefaultAsync(processMapWellboreDevelopment.IdWell, cancellationToken)
?? throw new ArgumentInvalidException(nameof(processMapWellboreDevelopment.IdWell),
if (well is null) $"Скважины с Id: {processMapWellboreDevelopment.IdWell} не существует");
throw new ArgumentInvalidException($"Скважины с Id: {processMapWellboreDevelopment.IdWell} не существует",
nameof(processMapWellboreDevelopment.IdWell));
if (processMapWellboreDevelopment.DepthStart > processMapWellboreDevelopment.DepthEnd)
throw new ArgumentInvalidException("Значение стартовой глубины должно быть не больше значения конечной глубины",
nameof(processMapWellboreDevelopment.DepthStart));
processMapWellboreDevelopment.LastUpdate = DateTimeOffset.UtcNow; processMapWellboreDevelopment.LastUpdate = DateTimeOffset.UtcNow;
@ -46,20 +40,16 @@ public class ProcessMapWellboreDevelopmentService : IProcessMapWellboreDevelopme
var well = await wellService.GetOrDefaultAsync(processMapWellboreDevelopment.IdWell, cancellationToken); var well = await wellService.GetOrDefaultAsync(processMapWellboreDevelopment.IdWell, cancellationToken);
if (well is null) if (well is null)
throw new ArgumentInvalidException($"Скважины с Id: {processMapWellboreDevelopment.IdWell} не существует", throw new ArgumentInvalidException(nameof(processMapWellboreDevelopment.IdWell),
nameof(processMapWellboreDevelopment.IdWell)); $"Скважины с Id: {processMapWellboreDevelopment.IdWell} не существует");
if (processMapWellboreDevelopment.DepthStart > processMapWellboreDevelopment.DepthEnd)
throw new ArgumentInvalidException("Значение стартовой глубины должно быть не больше значения конечной глубины",
nameof(processMapWellboreDevelopment.DepthStart));
processMapWellboreDevelopment.LastUpdate = DateTimeOffset.UtcNow; processMapWellboreDevelopment.LastUpdate = DateTimeOffset.UtcNow;
var result = await processMapWellboreDevelopmentRepository.UpdateAsync(processMapWellboreDevelopment, cancellationToken); var result = await processMapWellboreDevelopmentRepository.UpdateAsync(processMapWellboreDevelopment, cancellationToken);
if (result == ICrudRepository<ProcessMapWellboreDevelopmentDto>.ErrorIdNotFound) if (result == ICrudRepository<ProcessMapWellboreDevelopmentDto>.ErrorIdNotFound)
throw new ArgumentInvalidException($"Проработки с Id: {processMapWellboreDevelopment.Id} не существует", throw new ArgumentInvalidException(nameof(processMapWellboreDevelopment.Id),
nameof(processMapWellboreDevelopment.Id)); $"Проработки с Id: {processMapWellboreDevelopment.Id} не существует");
return result; return result;
} }
@ -70,7 +60,7 @@ public class ProcessMapWellboreDevelopmentService : IProcessMapWellboreDevelopme
var idWell = telemetryService.GetIdWellByTelemetryUid(uid); var idWell = telemetryService.GetIdWellByTelemetryUid(uid);
if (!idWell.HasValue) if (!idWell.HasValue)
throw new ArgumentInvalidException($"Неправильный телеметрии. Uid: {uid}", nameof(uid)); throw new ArgumentInvalidException(nameof(uid), $"Неправильный телеметрии. Uid: {uid}");
return await processMapWellboreDevelopmentRepository.GetAllAsync(idWell.Value, updateFrom, cancellationToken); return await processMapWellboreDevelopmentRepository.GetAllAsync(idWell.Value, updateFrom, cancellationToken);
} }

View File

@ -114,10 +114,10 @@ namespace AsbCloudInfrastructure.Services.SAUB
{ {
double intervalSec = (endDate - beginDate).TotalSeconds; double intervalSec = (endDate - beginDate).TotalSeconds;
if (intervalSec > 60*60*24*3) if (intervalSec > 60*60*24*3)
throw new ArgumentInvalidException("Слишком большой диапазон", nameof(endDate)); throw new ArgumentInvalidException(nameof(endDate), "Слишком большой диапазон");
var telemetry = telemetryService.GetOrDefaultTelemetryByIdWell(idWell) var telemetry = telemetryService.GetOrDefaultTelemetryByIdWell(idWell)
?? throw new ArgumentInvalidException($"Скважина id:{idWell} не содержит телеметрии", nameof(idWell)); ?? throw new ArgumentInvalidException(nameof(idWell), $"Скважина id:{idWell} не содержит телеметрии");
var approxPointsCount = intervalSec switch var approxPointsCount = intervalSec switch
{ {

View File

@ -336,9 +336,8 @@ namespace AsbCloudInfrastructure.Services.Subsystems
private IQueryable<SubsystemOperationTime> BuildQuery(SubsystemOperationTimeRequest request) private IQueryable<SubsystemOperationTime> BuildQuery(SubsystemOperationTimeRequest request)
{ {
var well = wellService.GetOrDefault(request.IdWell); var well = wellService.GetOrDefault(request.IdWell)
if (well?.IdTelemetry is null || well.Timezone is null) ?? throw new ArgumentInvalidException(nameof(request.IdWell), $"Not valid IdWell = {request.IdWell}");
throw new ArgumentInvalidException($"Not valid IdWell = {request.IdWell}", nameof(request.IdWell));
var query = db.SubsystemOperationTimes var query = db.SubsystemOperationTimes
.Include(o => o.Subsystem) .Include(o => o.Subsystem)

View File

@ -110,7 +110,7 @@ namespace AsbCloudInfrastructure.Services
})); }));
if(!docs.Any()) if(!docs.Any())
throw new ArgumentInvalidException("Нет такой категории, или в нее уже загружен документ", nameof(idCategory)); throw new ArgumentInvalidException(nameof(idCategory), "Нет такой категории, или в нее уже загружен документ");
var message = requester.MakeDisplayName() + " ожидает от Вас загрузку на портал документа «{{0}}»"; var message = requester.MakeDisplayName() + " ожидает от Вас загрузку на портал документа «{{0}}»";
await NotifyUsersAsync(docs, message, token); await NotifyUsersAsync(docs, message, token);
@ -126,9 +126,8 @@ namespace AsbCloudInfrastructure.Services
if (user?.Email is not null) if (user?.Email is not null)
{ {
var category = await fileCategoryService.GetOrDefaultAsync(item.IdCategory, token); var category = await fileCategoryService.GetOrDefaultAsync(item.IdCategory, token);
var well = await wellService.GetOrDefaultAsync(item.IdWell, token); var well = await wellService.GetOrDefaultAsync(item.IdWell, token)
if(well is null) ?? throw new ArgumentInvalidException(nameof(item.IdWell), "idWell doesn`t exist");
throw new ArgumentInvalidException("idWell doesn`t exist", nameof(item.IdWell));
await SendMessageAsync(well, user, category?.Name ?? string.Empty, message, await SendMessageAsync(well, user, category?.Name ?? string.Empty, message,
token); token);

View File

@ -26,7 +26,7 @@ public class WellOperationDefaultExcelParser : IWellOperationExcelParser
private static IEnumerable<RowDto> ParseWorkbook(IXLWorkbook workbook, WellOperationParserOptionsDto options) private static IEnumerable<RowDto> ParseWorkbook(IXLWorkbook workbook, WellOperationParserOptionsDto options)
{ {
if (string.IsNullOrWhiteSpace(options.SheetName)) if (string.IsNullOrWhiteSpace(options.SheetName))
throw new ArgumentInvalidException("Не указано название листа", nameof(options.SheetName)); throw new ArgumentInvalidException(nameof(options.SheetName), "Не указано название листа");
var sheet = workbook.Worksheets.FirstOrDefault(ws => var sheet = workbook.Worksheets.FirstOrDefault(ws =>
string.Equals(ws.Name, options.SheetName, StringComparison.CurrentCultureIgnoreCase)) string.Equals(ws.Name, options.SheetName, StringComparison.CurrentCultureIgnoreCase))

View File

@ -57,16 +57,16 @@ public class WellOperationGazpromKhantosExcelParser : IWellOperationExcelParser
private IEnumerable<RowDto> ParseWorkBook(IXLWorkbook workbook, WellOperationParserOptionsDto options) private IEnumerable<RowDto> ParseWorkBook(IXLWorkbook workbook, WellOperationParserOptionsDto options)
{ {
if (string.IsNullOrWhiteSpace(options.SheetName)) if (string.IsNullOrWhiteSpace(options.SheetName))
throw new ArgumentInvalidException("Не указано название листа", nameof(options.SheetName)); throw new ArgumentInvalidException(nameof(options.SheetName), "Не указано название листа");
if (options.StartRow is null or < 1 or > 1048576) if (options.StartRow is null or < 1 or > 1048576)
throw new ArgumentInvalidException("Некорректное значение начальной строки", nameof(options.StartRow)); throw new ArgumentInvalidException(nameof(options.StartRow), "Некорректное значение начальной строки");
if (options.EndRow is null or < 1 or > 1048576) if (options.EndRow is null or < 1 or > 1048576)
throw new ArgumentInvalidException("Некорректное значение конечной строки", nameof(options.EndRow)); throw new ArgumentInvalidException(nameof(options.EndRow), "Некорректное значение конечной строки");
if (options.EndRow < options.StartRow) if (options.EndRow < options.StartRow)
throw new ArgumentInvalidException("Конечный номер строки не может быть больше начального", nameof(options.EndRow)); throw new ArgumentInvalidException(nameof(options.EndRow), "Конечный номер строки не может быть больше начального");
var sheet = workbook.Worksheets.FirstOrDefault(ws => var sheet = workbook.Worksheets.FirstOrDefault(ws =>
string.Equals(ws.Name, options.SheetName, StringComparison.CurrentCultureIgnoreCase)) string.Equals(ws.Name, options.SheetName, StringComparison.CurrentCultureIgnoreCase))

View File

@ -34,14 +34,11 @@ public class WellOperationImportService : IWellOperationImportService
public async Task ImportAsync(int idWell, int idUser, int idType, Stream stream, WellOperationParserOptionsDto options, public async Task ImportAsync(int idWell, int idUser, int idType, Stream stream, WellOperationParserOptionsDto options,
bool deleteWellOperationsBeforeImport, CancellationToken cancellationToken) bool deleteWellOperationsBeforeImport, CancellationToken cancellationToken)
{ {
var excelParser = excelParsers.FirstOrDefault(p => p.IdTemplate == options.IdTemplate && var excelParser = excelParsers.FirstOrDefault(p => p.IdTemplate == options.IdTemplate && p.IdTypes.Contains(idType))
p.IdTypes.Contains(idType)); ?? throw new ArgumentInvalidException(nameof(options.IdTemplate), "Невозможно импортировать файл");
if (excelParser is null) if (idType != WellOperation.IdOperationTypePlan && idType != WellOperation.IdOperationTypeFact)
throw new ArgumentInvalidException("Невозможно импортировать файл", nameof(options.IdTemplate)); throw new ArgumentInvalidException(nameof(idType), "Операции не существует");
if (idType != WellOperation.IdOperationTypePlan && idType != WellOperation.IdOperationTypeFact)
throw new ArgumentInvalidException("Операции не существует", nameof(idType));
RowDto[] rows; RowDto[] rows;
var validationErrors = new List<string>(); var validationErrors = new List<string>();

View File

@ -33,10 +33,8 @@ namespace AsbCloudInfrastructure.Services.WellOperationService
{ {
var tvd = await operationsStatService.GetTvdAsync(idWell, token); var tvd = await operationsStatService.GetTvdAsync(idWell, token);
var well = await wellService.GetOrDefaultAsync(idWell, token); var well = await wellService.GetOrDefaultAsync(idWell, token)
?? throw new ArgumentInvalidException(nameof(idWell), "idWell doesn`t exist");
if(well is null)
throw new ArgumentInvalidException("idWell doesn`t exist", nameof(idWell));
var ecxelTemplateStream = GetExcelTemplateStream(); var ecxelTemplateStream = GetExcelTemplateStream();
using var workbook = new XLWorkbook(ecxelTemplateStream, XLEventTracking.Disabled); using var workbook = new XLWorkbook(ecxelTemplateStream, XLEventTracking.Disabled);

View File

@ -146,16 +146,10 @@ namespace AsbCloudInfrastructure.Services
public override async Task<int> InsertAsync(WellDto dto, CancellationToken token) public override async Task<int> InsertAsync(WellDto dto, CancellationToken token)
{ {
if (IsTelemetryAssignedToDifferentWell(dto)) if (IsTelemetryAssignedToDifferentWell(dto))
throw new ArgumentInvalidException("Телеметрия уже была привязана к другой скважине.", nameof(dto)); throw new ArgumentInvalidException(nameof(dto), "Телеметрия уже была привязана к другой скважине.");
if (dto.IdWellType is < 1 or > 2)
throw new ArgumentInvalidException("Тип скважины указан неправильно.", nameof(dto));
if (dto.IdState is < 0 or > 2)
throw new ArgumentInvalidException("Текущее состояние работы скважины указано неправильно.", nameof(dto));
if (dto.Id != 0 && (await GetCacheAsync(token)).Any(w => w.Id == dto.Id)) if (dto.Id != 0 && (await GetCacheAsync(token)).Any(w => w.Id == dto.Id))
throw new ArgumentInvalidException($"Нельзя повторно добавить скважину с id: {dto.Id}", nameof(dto)); throw new ArgumentInvalidException(nameof(dto), $"Нельзя повторно добавить скважину с id: {dto.Id}");
var entity = Convert(dto); var entity = Convert(dto);
@ -181,14 +175,8 @@ namespace AsbCloudInfrastructure.Services
CancellationToken token) CancellationToken token)
{ {
if (IsTelemetryAssignedToDifferentWell(dto)) if (IsTelemetryAssignedToDifferentWell(dto))
throw new ArgumentInvalidException("Телеметрия уже была привязана к другой скважине.", nameof(dto)); throw new ArgumentInvalidException(nameof(dto), "Телеметрия уже была привязана к другой скважине.");
if (dto.IdWellType is < 1 or > 2)
throw new ArgumentInvalidException("Тип скважины указан неправильно.", nameof(dto));
if (dto.IdState is < 0 or > 2)
throw new ArgumentInvalidException("Текущее состояние работы скважины указано неправильно.", nameof(dto));
var oldRelations = (await GetCacheRelationCompanyWellAsync(token)) var oldRelations = (await GetCacheRelationCompanyWellAsync(token))
.Where(r => r.IdWell == dto.Id).ToArray(); .Where(r => r.IdWell == dto.Id).ToArray();
@ -302,9 +290,8 @@ namespace AsbCloudInfrastructure.Services
public SimpleTimezoneDto GetTimezone(int idWell) public SimpleTimezoneDto GetTimezone(int idWell)
{ {
var well = GetOrDefault(idWell); var well = GetOrDefault(idWell)
if (well == null) ?? throw new ArgumentInvalidException(nameof(idWell), $"idWell: {idWell} does not exist.");
throw new ArgumentInvalidException($"idWell: {idWell} does not exist.", nameof(idWell));
return GetTimezone(well); return GetTimezone(well);
} }

View File

@ -196,7 +196,7 @@ namespace AsbCloudWebApi.Controllers.Subsystems
var ltDate = request.LtDate.Value; var ltDate = request.LtDate.Value;
var utcDateRequest = ltDate.ToUtcDateTimeOffset(well.Timezone.Hours); var utcDateRequest = ltDate.ToUtcDateTimeOffset(well.Timezone.Hours);
if (utcDateRequest.AddHours(2) > DateTime.UtcNow) if (utcDateRequest.AddHours(2) > DateTime.UtcNow)
throw new ArgumentInvalidException("Запрашиваемый диапазон должен заканчиваться за 2 часа до текущего времени", nameof(request.LtDate)); throw new ArgumentInvalidException(nameof(request.LtDate), "Запрашиваемый диапазон должен заканчиваться за 2 часа до текущего времени");
} }
} }
} }

View File

@ -77,14 +77,14 @@ public class WellboreController : ControllerBase
{ {
var idPair = id.Split(','); var idPair = id.Split(',');
if (!int.TryParse(idPair[0], out var idWell)) if (!int.TryParse(idPair[0], out var idWell))
throw new ArgumentInvalidException($"Не удалось получить Id скважины \"{idPair[0]}\"", nameof(id)); throw new ArgumentInvalidException(nameof(id), $"Не удалось получить Id скважины \"{idPair[0]}\"");
if (idPair.Length > 1) if (idPair.Length > 1)
{ {
if (int.TryParse(idPair[1], out int idWellSectionType)) if (int.TryParse(idPair[1], out int idWellSectionType))
return (idWell, idWellSectionType); return (idWell, idWellSectionType);
else else
throw new ArgumentInvalidException($"Не удалось получить Id ствола \"{idPair[1]}\"", nameof(id)); throw new ArgumentInvalidException(nameof(id), $"Не удалось получить Id ствола \"{idPair[1]}\"");
} }
return (idWell, null); return (idWell, null);
} }