Правки и рефакторинг

This commit is contained in:
Оля Бизюкова 2024-12-03 17:05:46 +05:00
parent c3c04f9c66
commit e98cd7d6e9
6 changed files with 221 additions and 211 deletions

View File

@ -29,24 +29,25 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
var userId = User.GetUserId<Guid>();
var result = await repository.InsertRange(userId, idDiscriminator, [dto], token);
return Ok(result);
return CreatedAtAction(nameof(Add), result);
}
[HttpPost("range")]
[ProducesResponseType(typeof(int), (int)HttpStatusCode.OK)]
public async Task<IActionResult> AddRange(
Guid idDiscriminator,
[FromBody] IEnumerable<DataWithWellDepthAndSectionDto> dtos, CancellationToken token)
[FromBody] IEnumerable<DataWithWellDepthAndSectionDto> dtos,
CancellationToken token = default)
{
var userId = User.GetUserId<Guid>();
var result = await repository.InsertRange(userId, idDiscriminator, dtos, token);
return Ok(result);
return CreatedAtAction(nameof(AddRange), result);
}
[HttpDelete]
[ProducesResponseType(typeof(int), (int)HttpStatusCode.OK)]
public async Task<IActionResult> Delete(Guid id, CancellationToken token)
public async Task<IActionResult> Delete(Guid id, CancellationToken token = default)
{
var userId = User.GetUserId<Guid>();
var result = await repository.MarkAsDeleted(userId, [id], token);
@ -56,7 +57,7 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
[HttpDelete("range")]
[ProducesResponseType(typeof(int), (int)HttpStatusCode.OK)]
public async Task<IActionResult> DeleteRange(IEnumerable<Guid> ids, CancellationToken token)
public async Task<IActionResult> DeleteRange(IEnumerable<Guid> ids, CancellationToken token = default)
{
var userId = User.GetUserId<Guid>();
var result = await repository.MarkAsDeleted(userId, ids, token);
@ -69,7 +70,7 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
public async Task<IActionResult> ClearAndInsertRange(
Guid idDiscriminator,
IEnumerable<DataWithWellDepthAndSectionDto> dtos,
CancellationToken token)
CancellationToken token = default)
{
var userId = User.GetUserId<Guid>();
var result = await repository.ClearAndInsertRange(userId, idDiscriminator, dtos, token);
@ -81,7 +82,7 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
public async Task<IActionResult> Update(
Guid idDiscriminator,
DataWithWellDepthAndSectionDto dto,
CancellationToken token)
CancellationToken token = default)
{
var userId = User.GetUserId<Guid>();
var result = await repository.UpdateRange(userId, idDiscriminator, [dto], token);
@ -94,7 +95,7 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
public async Task<IActionResult> UpdateRange(
Guid idDiscriminator,
IEnumerable<DataWithWellDepthAndSectionDto> dtos,
CancellationToken token)
CancellationToken token = default)
{
var userId = User.GetUserId<Guid>();
var result = await repository.UpdateRange(userId, idDiscriminator, dtos, token);
@ -107,7 +108,7 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
public async Task<IActionResult> GetCurrent(
Guid idDiscriminator,
[FromQuery]SectionPartRequest request,
CancellationToken token)
CancellationToken token = default)
{
var moment = new DateTimeOffset(3000, 1, 1, 0, 0, 0, TimeSpan.Zero);
var result = await repository.GetByDate(idDiscriminator, moment, request, token);
@ -121,7 +122,7 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
Guid idDiscriminator,
DateTimeOffset moment,
[FromQuery] SectionPartRequest request,
CancellationToken token)
CancellationToken token = default)
{
var result = await repository.GetByDate(idDiscriminator, moment, request, token);
@ -130,7 +131,11 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
[HttpGet("history")]
[ProducesResponseType(typeof(IEnumerable<ChangeLogDto>), (int)HttpStatusCode.OK)]
public async Task<IActionResult> GetChangeLogForDate(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token)
public async Task<IActionResult> GetChangeLogForDate(
Guid idDiscriminator,
DateTimeOffset dateBegin,
DateTimeOffset dateEnd,
CancellationToken token = default)
{
var result = await repository.GetChangeLogForDate(idDiscriminator, dateBegin, dateEnd, token);
@ -139,7 +144,7 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
[HttpGet("datesChange")]
[ProducesResponseType(typeof(IEnumerable<DateOnly>), (int)HttpStatusCode.OK)]
public async Task<IActionResult> GetDatesChange(Guid idDiscriminator, CancellationToken token)
public async Task<IActionResult> GetDatesChange(Guid idDiscriminator, CancellationToken token = default)
{
var result = await repository.GetDatesChange(idDiscriminator, token);
@ -157,10 +162,13 @@ public class ChangeLogController : ControllerBase, IChangeLogApi
[HttpGet("datesRange")]
[ProducesResponseType(typeof(DatesRangeDto), (int)HttpStatusCode.OK)]
public async Task<IActionResult> GetDatesRangeAsync(Guid idDiscriminator, CancellationToken token)
public async Task<IActionResult> GetDatesRangeAsync(Guid idDiscriminator, CancellationToken token = default)
{
var result = await repository.GetDatesRange(idDiscriminator, token);
if(result is null)
return NoContent();
return Ok(result);
}
}

View File

@ -1,12 +1,10 @@
using System.Security.Claims;
using System.Text.Json.Nodes;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Persistence.Models.Configurations;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Text.Json.Nodes;
namespace Persistence.API;
@ -43,8 +41,8 @@ public static class DependencyInjection
//var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
//var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
//var includeControllerXmlComment = true;
//options.IncludeXmlComments(xmlPath, includeControllerXmlComment);
//options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "AsbCloudApp.xml"), includeControllerXmlComment);
//c.IncludeXmlComments(xmlPath, includeControllerXmlComment);
//c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "AsbCloudApp.xml"), includeControllerXmlComment);
});
}
@ -105,12 +103,6 @@ public static class DependencyInjection
},
OnTokenValidated = context =>
{
if(context.Principal != null && context.Principal.HasClaim(x => x.Type != ClaimTypes.NameIdentifier))
{
var claim = new Claim(ClaimTypes.NameIdentifier.ToString(), Guid.NewGuid().ToString());
(context.Principal.Identity as ClaimsIdentity)!.AddClaim(claim);
}
var username = context.Principal?.Claims
.FirstOrDefault(e => e.Type == "username")?.Value;

View File

@ -12,11 +12,7 @@ public static class DependencyInjection
string connectionStringName = "DefaultConnection";
services.AddDbContext<PersistenceDbContext>(options =>
{
var dataSourceBuilder = new NpgsqlDataSourceBuilder(configuration.GetConnectionString(connectionStringName));
dataSourceBuilder.EnableDynamicJson();
options.UseNpgsql(dataSourceBuilder.Build());
});
options.UseNpgsql(configuration.GetConnectionString(connectionStringName)));
services.AddScoped<DbContext>(provider => provider.GetRequiredService<PersistenceDbContext>());

View File

@ -78,39 +78,46 @@ public class ChangeLogControllerTest : BaseIntegrationTest
var idDiscriminator = Guid.NewGuid();
var dtos = Generate(1, DateTimeOffset.UtcNow);
var dto = dtos.FirstOrDefault()!;
var entity = dto.Adapt<ChangeLog>();
dbContext.ChangeLog.Add(entity);
dbContext.SaveChanges();
var result = await client.Add(idDiscriminator, dto);
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
dto.Id = entity.Id;
dto.DepthStart = dto.DepthStart + 10;
var entity = dbContext.ChangeLog
.Where(x => x.IdDiscriminator == idDiscriminator)
.FirstOrDefault();
dto = entity.Adapt<DataWithWellDepthAndSectionDto>();
dto.DepthEnd = dto.DepthEnd + 10;
// act
var result = await client.Update(idDiscriminator, dto);
result = await client.Update(idDiscriminator, dto);
// assert
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
Assert.Equal(2, result.Content);
//var entities = dbContext.ChangeLog
// .Where(e => e.IdDiscriminator == idDiscriminator)
// .ToArray();
//var obsoleteEntity = entities
// .Where(e => e.Obsolete.HasValue)
// .FirstOrDefault();
var dateBegin = DateTimeOffset.UtcNow.AddDays(-1);
var dateEnd = DateTimeOffset.UtcNow.AddDays(1);
//var activeEntity = entities
// .Where(e => !e.Obsolete.HasValue)
// .FirstOrDefault();
var changeLogResult = await client.GetChangeLogForDate(idDiscriminator, dateBegin, dateEnd);
Assert.Equal(HttpStatusCode.OK, changeLogResult.StatusCode);
Assert.NotNull(changeLogResult.Content);
//if (obsoleteEntity == null || activeEntity == null)
//{
// Assert.Fail();
// return;
//}
var changeLogDtos = changeLogResult.Content;
//Assert.Equal(activeEntity.IdNext, obsoleteEntity.Id);
var obsoleteDto = changeLogDtos
.Where(e => e.Obsolete.HasValue)
.FirstOrDefault();
var activeDto = changeLogDtos
.Where(e => !e.Obsolete.HasValue)
.FirstOrDefault();
if (obsoleteDto == null || activeDto == null)
{
Assert.Fail();
return;
}
Assert.Equal(activeDto.Id, obsoleteDto.IdNext);
}
@ -185,11 +192,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest
// arrange
var changeLogItems = CreateChangeLogItems(3, (-15, 15));
var idDiscriminator = changeLogItems.Item1;
var entities = changeLogItems.Item2;
var orderedEntities = entities.OrderBy(e => e.Creation);
var minDate = orderedEntities.First().Creation;
var maxDate = orderedEntities.Last().Creation;
var entities = changeLogItems.Item2.OrderBy(e => e.Creation);
// act
var result = await client.GetDatesRange(idDiscriminator);
@ -198,12 +201,15 @@ public class ChangeLogControllerTest : BaseIntegrationTest
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
Assert.NotNull(result.Content);
var minDate = entities.First().Creation;
var maxDate = entities.Last().Creation;
var expectedMinDate = minDate.ToUniversalTime().ToString();
var actualMinDate = result.Content!.From.ToUniversalTime().ToString();
var actualMinDate = result.Content.From.ToUniversalTime().ToString();
Assert.Equal(expectedMinDate, actualMinDate);
var expectedMaxDate = maxDate.ToUniversalTime().ToString();
var actualMaxDate = result.Content!.To.ToUniversalTime().ToString();
var actualMaxDate = result.Content.To.ToUniversalTime().ToString();
Assert.Equal(expectedMaxDate, actualMaxDate);
}

View File

@ -232,11 +232,6 @@ public class ChangeLogRepository : IChangeLogRepository
return datesOnly;
}
public Task<IEnumerable<IDictionary<string, object>>> GetGtDate(DateTimeOffset dateBegin, CancellationToken token)
{
throw new NotImplementedException();
}
private ChangeLog CreateEntityFromDto(Guid idUser, Guid idDiscriminator, DataWithWellDepthAndSectionDto dto)
{
var entity = new ChangeLog()
@ -273,17 +268,25 @@ public class ChangeLogRepository : IChangeLogRepository
public async Task<DatesRangeDto?> GetDatesRange(Guid idDiscriminator, CancellationToken token)
{
var query = db.Set<ChangeLog>()
.Where(e => e.IdDiscriminator == idDiscriminator);
var test = db.Set<ChangeLog>().ToArray();
var test2 = query.ToArray();
.Where(e => e.IdDiscriminator == idDiscriminator)
.GroupBy(e => 1)
.Select(group => new
{
Min = group.Min(e => e.Creation),
Max = group.Max(e => e.Creation),
});
var minDate = await query.MinAsync(o => o.Creation, token);
var maxDate = await query.MaxAsync(o => o.Creation, token);
var values = await query.FirstOrDefaultAsync(token);
if(values is null)
{
return null;
}
return new DatesRangeDto
{
From = minDate,
To = maxDate
From = values.Min,
To = values.Max,
};
}
}

View File

@ -10,6 +10,11 @@ public class ChangeLogDto
}
/// <summary>
/// Ключ записи
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// Создатель записи
/// </summary>
@ -38,5 +43,5 @@ public class ChangeLogDto
/// <summary>
/// Объект записи
/// </summary>
public DataWithWellDepthAndSectionDto Value { get; set; }
public DataWithWellDepthAndSectionDto Value { get; set; } = default!;
}