forked from ddrilling/AsbCloudServer
Merge branch 'dev' into feature/27526736-cache-table
This commit is contained in:
commit
d7cd45210a
12
AsbCloudApp/Data/ParserResultDto.cs
Normal file
12
AsbCloudApp/Data/ParserResultDto.cs
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace AsbCloudApp.Data;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Результат парсинга файла
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="TDto"></typeparam>
|
||||||
|
public class ParserResultDto<TDto> : ValidationResultDto<IEnumerable<ValidationResultDto<TDto>>>
|
||||||
|
where TDto : class, IId
|
||||||
|
{
|
||||||
|
}
|
@ -5,7 +5,7 @@ namespace AsbCloudApp.Data.Trajectory
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Базовая географическая траектория
|
/// Базовая географическая траектория
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public abstract class TrajectoryGeoDto
|
public abstract class TrajectoryGeoDto : IId
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// ИД строки с координатами
|
/// ИД строки с координатами
|
||||||
|
19
AsbCloudApp/Requests/ParserOptions/IParserOptionsRequest.cs
Normal file
19
AsbCloudApp/Requests/ParserOptions/IParserOptionsRequest.cs
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
namespace AsbCloudApp.Requests.ParserOptions;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Параметры парсинга
|
||||||
|
/// </summary>
|
||||||
|
public interface IParserOptionsRequest
|
||||||
|
{
|
||||||
|
private static DummyOptions empty => new();
|
||||||
|
|
||||||
|
private class DummyOptions : IParserOptionsRequest
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Получение пустого объекта опций
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static IParserOptionsRequest Empty() => empty;
|
||||||
|
}
|
38
AsbCloudApp/Services/IParserService.cs
Normal file
38
AsbCloudApp/Services/IParserService.cs
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
using System.IO;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using AsbCloudApp.Data;
|
||||||
|
using AsbCloudApp.Requests.ParserOptions;
|
||||||
|
|
||||||
|
namespace AsbCloudApp.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Сервис парсинга
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="TDto"></typeparam>
|
||||||
|
/// <typeparam name="TOptions"></typeparam>
|
||||||
|
public interface IParserService<TDto, in TOptions> : IParserService
|
||||||
|
where TDto : class, IId
|
||||||
|
where TOptions : IParserOptionsRequest
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Распарсить файл
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="file"></param>
|
||||||
|
/// <param name="options"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
ParserResultDto<TDto> Parse(Stream file, TOptions options);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Получение шаблона для заполнения
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
Stream GetTemplateFile();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Сервис парсинга(интерфейс маркер)
|
||||||
|
/// </summary>
|
||||||
|
public interface IParserService
|
||||||
|
{
|
||||||
|
}
|
@ -1,30 +1,50 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using System.Text;
|
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace AsbCloudInfrastructure
|
namespace AsbCloudInfrastructure
|
||||||
{
|
{
|
||||||
public static class AssemblyExtensions
|
public static class AssemblyExtensions
|
||||||
{
|
{
|
||||||
public static async Task<Stream> GetTemplateCopyStreamAsync(this Assembly assembly, string templateName, CancellationToken cancellationToken)
|
public static Stream GetTemplateCopyStream(this Assembly assembly, string templateName)
|
||||||
{
|
{
|
||||||
var resourceName = assembly
|
var resourceName = assembly
|
||||||
.GetManifestResourceNames()
|
.GetManifestResourceNames()
|
||||||
.FirstOrDefault(n => n.EndsWith(templateName))!;
|
.FirstOrDefault(n => n.EndsWith(templateName));
|
||||||
|
|
||||||
using var stream = Assembly.GetExecutingAssembly()
|
if (string.IsNullOrWhiteSpace(resourceName))
|
||||||
.GetManifestResourceStream(resourceName)!;
|
throw new ArgumentNullException(nameof(resourceName));
|
||||||
|
|
||||||
var memoryStream = new MemoryStream();
|
using var stream = Assembly.GetExecutingAssembly()
|
||||||
await stream.CopyToAsync(memoryStream, cancellationToken);
|
.GetManifestResourceStream(resourceName);
|
||||||
memoryStream.Position = 0;
|
|
||||||
|
|
||||||
return memoryStream;
|
var memoryStream = new MemoryStream();
|
||||||
}
|
stream?.CopyTo(memoryStream);
|
||||||
}
|
memoryStream.Position = 0;
|
||||||
}
|
|
||||||
|
return memoryStream;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Obsolete]
|
||||||
|
public static async Task<Stream> GetTemplateCopyStreamAsync(this Assembly assembly,
|
||||||
|
string templateName,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var resourceName = assembly
|
||||||
|
.GetManifestResourceNames()
|
||||||
|
.FirstOrDefault(n => n.EndsWith(templateName))!;
|
||||||
|
|
||||||
|
using var stream = Assembly.GetExecutingAssembly()
|
||||||
|
.GetManifestResourceStream(resourceName)!;
|
||||||
|
|
||||||
|
var memoryStream = new MemoryStream();
|
||||||
|
await stream.CopyToAsync(memoryStream, cancellationToken);
|
||||||
|
memoryStream.Position = 0;
|
||||||
|
|
||||||
|
return memoryStream;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -30,7 +30,6 @@ using AsbCloudInfrastructure.Services.SAUB;
|
|||||||
using AsbCloudInfrastructure.Services.Subsystems;
|
using AsbCloudInfrastructure.Services.Subsystems;
|
||||||
using AsbCloudInfrastructure.Services.Trajectory;
|
using AsbCloudInfrastructure.Services.Trajectory;
|
||||||
using AsbCloudInfrastructure.Services.Trajectory.Export;
|
using AsbCloudInfrastructure.Services.Trajectory.Export;
|
||||||
using AsbCloudInfrastructure.Services.Trajectory.Import;
|
|
||||||
using AsbCloudInfrastructure.Services.WellOperationImport;
|
using AsbCloudInfrastructure.Services.WellOperationImport;
|
||||||
using AsbCloudInfrastructure.Services.WellOperationImport.FileParser;
|
using AsbCloudInfrastructure.Services.WellOperationImport.FileParser;
|
||||||
using AsbCloudInfrastructure.Services.WellOperationService;
|
using AsbCloudInfrastructure.Services.WellOperationService;
|
||||||
@ -46,6 +45,7 @@ using AsbCloudDb.Model.WellSections;
|
|||||||
using AsbCloudInfrastructure.Services.ProcessMaps;
|
using AsbCloudInfrastructure.Services.ProcessMaps;
|
||||||
using AsbCloudApp.Data.ProcessMapPlan;
|
using AsbCloudApp.Data.ProcessMapPlan;
|
||||||
using AsbCloudApp.Requests;
|
using AsbCloudApp.Requests;
|
||||||
|
using AsbCloudInfrastructure.Services.Trajectory.Parser;
|
||||||
|
|
||||||
namespace AsbCloudInfrastructure
|
namespace AsbCloudInfrastructure
|
||||||
{
|
{
|
||||||
@ -328,6 +328,8 @@ namespace AsbCloudInfrastructure
|
|||||||
services.AddTransient<IProcessMapPlanService<ProcessMapPlanWellReamDto>, ProcessMapPlanService<ProcessMapPlanWellReamDto>>();
|
services.AddTransient<IProcessMapPlanService<ProcessMapPlanWellReamDto>, ProcessMapPlanService<ProcessMapPlanWellReamDto>>();
|
||||||
|
|
||||||
services.AddTransient<IWellSectionPlanRepository, WellSectionPlanRepository>();
|
services.AddTransient<IWellSectionPlanRepository, WellSectionPlanRepository>();
|
||||||
|
|
||||||
|
services.AddSingleton<ParserServiceFactory>();
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
|
72
AsbCloudInfrastructure/ParserServiceBase.cs
Normal file
72
AsbCloudInfrastructure/ParserServiceBase.cs
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using AsbCloudApp.Data;
|
||||||
|
using AsbCloudApp.Requests.ParserOptions;
|
||||||
|
using AsbCloudApp.Services;
|
||||||
|
using ClosedXML.Excel;
|
||||||
|
|
||||||
|
namespace AsbCloudInfrastructure;
|
||||||
|
|
||||||
|
public abstract class ParserServiceBase<TDto, TOptions> : IParserService<TDto, TOptions>
|
||||||
|
where TDto : class, IId
|
||||||
|
where TOptions : IParserOptionsRequest
|
||||||
|
{
|
||||||
|
protected readonly IServiceProvider serviceProvider;
|
||||||
|
|
||||||
|
protected ParserServiceBase(IServiceProvider serviceProvider)
|
||||||
|
{
|
||||||
|
this.serviceProvider = serviceProvider;
|
||||||
|
}
|
||||||
|
|
||||||
|
public abstract ParserResultDto<TDto> Parse(Stream file, TOptions options);
|
||||||
|
public abstract Stream GetTemplateFile();
|
||||||
|
|
||||||
|
protected virtual ParserResultDto<TDto> ParseExcelSheet(IXLWorksheet sheet,
|
||||||
|
Func<IXLRow, ValidationResultDto<TDto>> parseRow,
|
||||||
|
int columnCount,
|
||||||
|
int headerRowsCount = 0)
|
||||||
|
{
|
||||||
|
if (sheet.RangeUsed().RangeAddress.LastAddress.ColumnNumber < columnCount)
|
||||||
|
throw new FileFormatException($"Лист {sheet.Name} содержит меньшее количество столбцов.");
|
||||||
|
|
||||||
|
var count = sheet.RowsUsed().Count() - headerRowsCount;
|
||||||
|
|
||||||
|
if (count > 1024)
|
||||||
|
throw new FileFormatException($"Лист {sheet.Name} содержит слишком большое количество строк.");
|
||||||
|
|
||||||
|
if (count <= 0)
|
||||||
|
return new ParserResultDto<TDto>();
|
||||||
|
|
||||||
|
var dtos = new List<ValidationResultDto<TDto>>(count);
|
||||||
|
var warnings = new List<ValidationResult>();
|
||||||
|
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
var row = sheet.Row(1 + i + headerRowsCount);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var dto = parseRow.Invoke(row);
|
||||||
|
dtos.Add(dto);
|
||||||
|
}
|
||||||
|
catch (FileFormatException ex)
|
||||||
|
{
|
||||||
|
var warning = new ValidationResult(ex.Message);
|
||||||
|
warnings.Add(warning);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var parserResult = new ParserResultDto<TDto>
|
||||||
|
{
|
||||||
|
Item = dtos
|
||||||
|
};
|
||||||
|
|
||||||
|
if (warnings.Any())
|
||||||
|
parserResult.Warnings = warnings;
|
||||||
|
|
||||||
|
return parserResult;
|
||||||
|
}
|
||||||
|
}
|
36
AsbCloudInfrastructure/Services/ParserServiceFactory.cs
Normal file
36
AsbCloudInfrastructure/Services/ParserServiceFactory.cs
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using AsbCloudApp.Data;
|
||||||
|
using AsbCloudApp.Requests.ParserOptions;
|
||||||
|
using AsbCloudApp.Services;
|
||||||
|
using AsbCloudInfrastructure.Services.Trajectory.Parser;
|
||||||
|
|
||||||
|
namespace AsbCloudInfrastructure.Services;
|
||||||
|
|
||||||
|
public class ParserServiceFactory
|
||||||
|
{
|
||||||
|
public const int IdTrajectoryFactManualParserService = 1;
|
||||||
|
public const int IdTrajectoryPlanParserService = 2;
|
||||||
|
|
||||||
|
private readonly IDictionary<int, Func<IParserService>> parsers;
|
||||||
|
|
||||||
|
public ParserServiceFactory(IServiceProvider serviceProvider)
|
||||||
|
{
|
||||||
|
parsers = new Dictionary<int, Func<IParserService>>
|
||||||
|
{
|
||||||
|
{ IdTrajectoryPlanParserService, () => new TrajectoryPlanParserService(serviceProvider) },
|
||||||
|
{ IdTrajectoryFactManualParserService, () => new TrajectoryFactManualParserService(serviceProvider) }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public IParserService<TDto, TOptions> Create<TDto, TOptions>(int idParserService)
|
||||||
|
where TDto : class, IId
|
||||||
|
where TOptions : IParserOptionsRequest
|
||||||
|
{
|
||||||
|
if (!parsers.TryGetValue(idParserService, out var parserService))
|
||||||
|
throw new ArgumentNullException(nameof(idParserService), "Не правильный идентификатор парсера");
|
||||||
|
|
||||||
|
return parserService.Invoke() as IParserService<TDto, TOptions>
|
||||||
|
?? throw new ArgumentNullException(nameof(idParserService), "Ошибка приведения типа");
|
||||||
|
}
|
||||||
|
}
|
@ -299,7 +299,7 @@ namespace AsbCloudInfrastructure.Services.SAUB
|
|||||||
if (request.LeDate.HasValue)
|
if (request.LeDate.HasValue)
|
||||||
{
|
{
|
||||||
var leDate = request.LeDate.Value.ToRemoteDateTime(cacheItem.TimezoneHours);
|
var leDate = request.LeDate.Value.ToRemoteDateTime(cacheItem.TimezoneHours);
|
||||||
data = data.Where(d => d.DateTime >= request.LeDate);
|
data = data.Where(d => d.DateTime <= request.LeDate);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (request.Divider > 1)
|
if (request.Divider > 1)
|
||||||
|
@ -1,30 +0,0 @@
|
|||||||
using AsbCloudApp.Data.Trajectory;
|
|
||||||
using ClosedXML.Excel;
|
|
||||||
|
|
||||||
namespace AsbCloudInfrastructure.Services.Trajectory.Import
|
|
||||||
{
|
|
||||||
|
|
||||||
public class TrajectoryFactManualParserService : TrajectoryParserService<TrajectoryGeoFactDto>
|
|
||||||
{
|
|
||||||
public override string templateFileName { get; } = "TrajectoryFactManualTemplate.xlsx";
|
|
||||||
public override string usingTemplateFile { get; } = "AsbCloudInfrastructure.Services.Trajectory.Templates";
|
|
||||||
public override string sheetName { get; } = "Фактическая траектория";
|
|
||||||
public override int headerRowsCount { get; } = 2;
|
|
||||||
|
|
||||||
protected override TrajectoryGeoFactDto ParseRow(IXLRow row)
|
|
||||||
{
|
|
||||||
var trajectoryRow = new TrajectoryGeoFactDto
|
|
||||||
{
|
|
||||||
WellboreDepth = row.Cell(1).GetCellValue<double>(),
|
|
||||||
ZenithAngle = row.Cell(2).GetCellValue<double>(),
|
|
||||||
AzimuthGeo = row.Cell(3).GetCellValue<double>(),
|
|
||||||
AzimuthMagnetic = row.Cell(4).GetCellValue<double>(),
|
|
||||||
VerticalDepth = row.Cell(5).GetCellValue<double>(),
|
|
||||||
Comment = row.Cell(6).GetCellValue<string?>()
|
|
||||||
};
|
|
||||||
//TODO: Добавить валидацию модели IValidatableObject
|
|
||||||
return trajectoryRow;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,78 +0,0 @@
|
|||||||
using AsbCloudApp.Data.Trajectory;
|
|
||||||
using ClosedXML.Excel;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.IO;
|
|
||||||
using System.Linq;
|
|
||||||
|
|
||||||
namespace AsbCloudInfrastructure.Services.Trajectory.Import
|
|
||||||
{
|
|
||||||
public abstract class TrajectoryParserService<T>
|
|
||||||
where T : TrajectoryGeoDto
|
|
||||||
{
|
|
||||||
public abstract string templateFileName { get; }
|
|
||||||
public abstract string usingTemplateFile { get; }
|
|
||||||
public abstract string sheetName { get; }
|
|
||||||
public abstract int headerRowsCount { get; }
|
|
||||||
|
|
||||||
protected abstract T ParseRow(IXLRow row);
|
|
||||||
|
|
||||||
public IEnumerable<T> Import(Stream stream)
|
|
||||||
{
|
|
||||||
using var workbook = new XLWorkbook(stream, XLEventTracking.Disabled);
|
|
||||||
var trajectoryRows = ParseFileStream(stream);
|
|
||||||
|
|
||||||
return trajectoryRows;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private IEnumerable<T> ParseFileStream(Stream stream)
|
|
||||||
{
|
|
||||||
using var workbook = new XLWorkbook(stream, XLEventTracking.Disabled);
|
|
||||||
return ParseWorkbook(workbook);
|
|
||||||
}
|
|
||||||
|
|
||||||
private IEnumerable<T> ParseWorkbook(IXLWorkbook workbook)
|
|
||||||
{
|
|
||||||
var sheetTrajectory = workbook.Worksheets.FirstOrDefault(ws => ws.Name == sheetName);
|
|
||||||
if (sheetTrajectory is null)
|
|
||||||
throw new FileFormatException($"Книга excel не содержит листа {sheetName}.");
|
|
||||||
var trajectoryRows = ParseSheet(sheetTrajectory);
|
|
||||||
return trajectoryRows;
|
|
||||||
}
|
|
||||||
|
|
||||||
private IEnumerable<T> ParseSheet(IXLWorksheet sheet)
|
|
||||||
{
|
|
||||||
if (sheet.RangeUsed().RangeAddress.LastAddress.ColumnNumber < 6)
|
|
||||||
throw new FileFormatException($"Лист {sheet.Name} содержит меньшее количество столбцов.");
|
|
||||||
|
|
||||||
var count = sheet.RowsUsed().Count() - headerRowsCount;
|
|
||||||
|
|
||||||
if (count > 1024)
|
|
||||||
throw new FileFormatException($"Лист {sheet.Name} содержит слишком большое количество строк.");
|
|
||||||
|
|
||||||
if (count <= 0)
|
|
||||||
throw new FileFormatException($"Лист {sheet.Name} некорректного формата либо пустой");
|
|
||||||
|
|
||||||
var trajectoryRows = new List<T>(count);
|
|
||||||
var parseErrors = new List<string>();
|
|
||||||
for (int i = 0; i < count; i++)
|
|
||||||
{
|
|
||||||
var row = sheet.Row(1 + i + headerRowsCount);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var trajectoryRow = ParseRow(row);
|
|
||||||
trajectoryRows.Add(trajectoryRow);
|
|
||||||
}
|
|
||||||
catch (FileFormatException ex)
|
|
||||||
{
|
|
||||||
parseErrors.Add(ex.Message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (parseErrors.Any())
|
|
||||||
throw new FileFormatException(string.Join("\r\n", parseErrors));
|
|
||||||
|
|
||||||
return trajectoryRows;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,33 +0,0 @@
|
|||||||
using AsbCloudApp.Data.Trajectory;
|
|
||||||
using ClosedXML.Excel;
|
|
||||||
|
|
||||||
namespace AsbCloudInfrastructure.Services.Trajectory.Import
|
|
||||||
{
|
|
||||||
|
|
||||||
public class TrajectoryPlanParserService : TrajectoryParserService<TrajectoryGeoPlanDto>
|
|
||||||
{
|
|
||||||
public override string templateFileName { get; } = "TrajectoryPlanTemplate.xlsx";
|
|
||||||
public override string usingTemplateFile { get; } = "AsbCloudInfrastructure.Services.Trajectory.Templates";
|
|
||||||
public override string sheetName { get; } = "Плановая траектория";
|
|
||||||
public override int headerRowsCount { get; } = 2;
|
|
||||||
|
|
||||||
protected override TrajectoryGeoPlanDto ParseRow(IXLRow row)
|
|
||||||
{
|
|
||||||
var trajectoryRow = new TrajectoryGeoPlanDto
|
|
||||||
{
|
|
||||||
WellboreDepth = row.Cell(1).GetCellValue<double>(),
|
|
||||||
ZenithAngle = row.Cell(2).GetCellValue<double>(),
|
|
||||||
AzimuthGeo = row.Cell(3).GetCellValue<double>(),
|
|
||||||
AzimuthMagnetic = row.Cell(4).GetCellValue<double>(),
|
|
||||||
VerticalDepth = row.Cell(5).GetCellValue<double>(),
|
|
||||||
Radius = row.Cell(6).GetCellValue<double>(),
|
|
||||||
Comment = row.Cell(7).GetCellValue<string?>()
|
|
||||||
};
|
|
||||||
|
|
||||||
//TODO: Добавить валидацию модели IValidatableObject
|
|
||||||
return trajectoryRow;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
@ -0,0 +1,39 @@
|
|||||||
|
using System;
|
||||||
|
using AsbCloudApp.Data;
|
||||||
|
using AsbCloudApp.Data.Trajectory;
|
||||||
|
using ClosedXML.Excel;
|
||||||
|
|
||||||
|
namespace AsbCloudInfrastructure.Services.Trajectory.Parser;
|
||||||
|
|
||||||
|
public class TrajectoryFactManualParserService : TrajectoryParserService<TrajectoryGeoFactDto>
|
||||||
|
{
|
||||||
|
protected override string SheetName => "Фактическая траектория";
|
||||||
|
protected override string TemplateFileName => "TrajectoryFactManualTemplate.xlsx";
|
||||||
|
|
||||||
|
public TrajectoryFactManualParserService(IServiceProvider serviceProvider)
|
||||||
|
: base(serviceProvider)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override ValidationResultDto<TrajectoryGeoFactDto> ParseRow(IXLRow row)
|
||||||
|
{
|
||||||
|
var trajectoryRow = new TrajectoryGeoFactDto
|
||||||
|
{
|
||||||
|
WellboreDepth = row.Cell(1).GetCellValue<double>(),
|
||||||
|
ZenithAngle = row.Cell(2).GetCellValue<double>(),
|
||||||
|
AzimuthGeo = row.Cell(3).GetCellValue<double>(),
|
||||||
|
AzimuthMagnetic = row.Cell(4).GetCellValue<double>(),
|
||||||
|
VerticalDepth = row.Cell(5).GetCellValue<double>(),
|
||||||
|
Comment = row.Cell(6).GetCellValue<string?>()
|
||||||
|
};
|
||||||
|
|
||||||
|
//TODO: Добавить валидацию модели
|
||||||
|
|
||||||
|
var validationResult = new ValidationResultDto<TrajectoryGeoFactDto>
|
||||||
|
{
|
||||||
|
Item = trajectoryRow
|
||||||
|
};
|
||||||
|
|
||||||
|
return validationResult;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,44 @@
|
|||||||
|
using System;
|
||||||
|
using AsbCloudApp.Data.Trajectory;
|
||||||
|
using ClosedXML.Excel;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
using AsbCloudApp.Data;
|
||||||
|
using AsbCloudApp.Requests.ParserOptions;
|
||||||
|
|
||||||
|
namespace AsbCloudInfrastructure.Services.Trajectory.Parser;
|
||||||
|
|
||||||
|
public abstract class TrajectoryParserService<T> : ParserServiceBase<T, IParserOptionsRequest>
|
||||||
|
where T : TrajectoryGeoDto
|
||||||
|
{
|
||||||
|
private const int HeaderRowsCount = 2;
|
||||||
|
private const int ColumnCount = 6;
|
||||||
|
|
||||||
|
protected TrajectoryParserService(IServiceProvider serviceProvider)
|
||||||
|
: base(serviceProvider)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
protected abstract string SheetName { get; }
|
||||||
|
|
||||||
|
protected abstract string TemplateFileName { get; }
|
||||||
|
|
||||||
|
protected abstract ValidationResultDto<T> ParseRow(IXLRow row);
|
||||||
|
|
||||||
|
public override Stream GetTemplateFile() =>
|
||||||
|
Assembly.GetExecutingAssembly().GetTemplateCopyStream(TemplateFileName)
|
||||||
|
?? throw new ArgumentNullException($"Файл '{TemplateFileName}' не найден");
|
||||||
|
|
||||||
|
public override ParserResultDto<T> Parse(Stream file, IParserOptionsRequest options)
|
||||||
|
{
|
||||||
|
using var workbook = new XLWorkbook(file, XLEventTracking.Disabled);
|
||||||
|
|
||||||
|
var sheet = workbook.Worksheets.FirstOrDefault(ws =>
|
||||||
|
ws.Name.ToLower().Trim() == SheetName.ToLower().Trim())
|
||||||
|
?? throw new FileFormatException($"Книга excel не содержит листа {SheetName}.");
|
||||||
|
|
||||||
|
var trajectoryRows = ParseExcelSheet(sheet, ParseRow, ColumnCount, HeaderRowsCount);
|
||||||
|
return trajectoryRows;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,40 @@
|
|||||||
|
using System;
|
||||||
|
using AsbCloudApp.Data;
|
||||||
|
using AsbCloudApp.Data.Trajectory;
|
||||||
|
using ClosedXML.Excel;
|
||||||
|
|
||||||
|
namespace AsbCloudInfrastructure.Services.Trajectory.Parser;
|
||||||
|
|
||||||
|
public class TrajectoryPlanParserService : TrajectoryParserService<TrajectoryGeoPlanDto>
|
||||||
|
{
|
||||||
|
protected override string SheetName => "Плановая траектория";
|
||||||
|
protected override string TemplateFileName => "TrajectoryPlanTemplate.xlsx";
|
||||||
|
|
||||||
|
public TrajectoryPlanParserService(IServiceProvider serviceProvider)
|
||||||
|
: base(serviceProvider)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override ValidationResultDto<TrajectoryGeoPlanDto> ParseRow(IXLRow row)
|
||||||
|
{
|
||||||
|
var trajectoryRow = new TrajectoryGeoPlanDto
|
||||||
|
{
|
||||||
|
WellboreDepth = row.Cell(1).GetCellValue<double>(),
|
||||||
|
ZenithAngle = row.Cell(2).GetCellValue<double>(),
|
||||||
|
AzimuthGeo = row.Cell(3).GetCellValue<double>(),
|
||||||
|
AzimuthMagnetic = row.Cell(4).GetCellValue<double>(),
|
||||||
|
VerticalDepth = row.Cell(5).GetCellValue<double>(),
|
||||||
|
Radius = row.Cell(6).GetCellValue<double>(),
|
||||||
|
Comment = row.Cell(7).GetCellValue<string?>()
|
||||||
|
};
|
||||||
|
|
||||||
|
//TODO: Добавить валидацию модели
|
||||||
|
|
||||||
|
var validationResult = new ValidationResultDto<TrajectoryGeoPlanDto>
|
||||||
|
{
|
||||||
|
Item = trajectoryRow
|
||||||
|
};
|
||||||
|
|
||||||
|
return validationResult;
|
||||||
|
}
|
||||||
|
}
|
@ -2,96 +2,11 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using AsbCloudInfrastructure.Services.DailyReport;
|
|
||||||
|
|
||||||
namespace AsbCloudInfrastructure;
|
namespace AsbCloudInfrastructure;
|
||||||
|
|
||||||
internal static class XLExtentions
|
internal static class XLExtentions
|
||||||
{
|
{
|
||||||
internal static IXLRange _SetValue(this IXLRange range, object value)
|
|
||||||
{
|
|
||||||
var mergedRange = range.Merge();
|
|
||||||
mergedRange.FirstCell()._SetValue(value);
|
|
||||||
var colWidth = mergedRange.FirstCell().WorksheetColumn().Width;
|
|
||||||
var maxCharsToWrap = colWidth / (0.1d * mergedRange.FirstCell().Style.Font.FontSize);
|
|
||||||
if (value is string valueString && valueString.Length > maxCharsToWrap)
|
|
||||||
{
|
|
||||||
var row = mergedRange.FirstCell().WorksheetRow();
|
|
||||||
var baseHeight = row.Height;
|
|
||||||
row.Height = 0.5d * baseHeight * Math.Ceiling(1d + valueString.Length / maxCharsToWrap);
|
|
||||||
}
|
|
||||||
|
|
||||||
mergedRange.Style.SetAllBorders()
|
|
||||||
.Alignment.SetWrapText(true);
|
|
||||||
return mergedRange;
|
|
||||||
}
|
|
||||||
|
|
||||||
internal static IXLCell _SetValue(this IXLCell cell, object value)
|
|
||||||
{
|
|
||||||
switch (value)
|
|
||||||
{
|
|
||||||
case DateTime dateTime:
|
|
||||||
cell._SetValue(dateTime);
|
|
||||||
break;
|
|
||||||
case IFormattable formattable:
|
|
||||||
cell._SetValue(formattable);
|
|
||||||
break;
|
|
||||||
case string valueString:
|
|
||||||
cell._SetValue(valueString);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
cell.Value = value;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
return cell;
|
|
||||||
}
|
|
||||||
|
|
||||||
internal static IXLCell _SetValue(this IXLCell cell, string value, bool adaptRowHeight = false)
|
|
||||||
{
|
|
||||||
cell.Value = value;
|
|
||||||
cell.Style
|
|
||||||
.SetAllBorders()
|
|
||||||
.Alignment.WrapText = true;
|
|
||||||
|
|
||||||
cell.Value = value;
|
|
||||||
if (adaptRowHeight)
|
|
||||||
{
|
|
||||||
var colWidth = cell.WorksheetColumn().Width;
|
|
||||||
var maxCharsToWrap = colWidth / (0.1d * cell.Style.Font.FontSize);
|
|
||||||
if (value.Length > maxCharsToWrap)
|
|
||||||
{
|
|
||||||
var row = cell.WorksheetRow();
|
|
||||||
var baseHeight = row.Height;
|
|
||||||
row.Height = 0.5d * baseHeight * Math.Ceiling(1d + value.Length / maxCharsToWrap);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return cell;
|
|
||||||
}
|
|
||||||
|
|
||||||
internal static IXLCell _ValueNoBorder(this IXLCell cell, string value, bool adaptRowHeight = false)
|
|
||||||
{
|
|
||||||
cell.Value = value;
|
|
||||||
cell.Style.Alignment.WrapText = true;
|
|
||||||
|
|
||||||
cell.Value = value;
|
|
||||||
if (adaptRowHeight)
|
|
||||||
{
|
|
||||||
var colWidth = cell.WorksheetColumn().Width;
|
|
||||||
var maxCharsToWrap = colWidth / (0.1d * cell.Style.Font.FontSize);
|
|
||||||
if (value.Length > maxCharsToWrap)
|
|
||||||
{
|
|
||||||
var row = cell.WorksheetRow();
|
|
||||||
var baseHeight = row.Height;
|
|
||||||
row.Height = 0.5d * baseHeight * Math.Ceiling(1d + value.Length / maxCharsToWrap);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return cell;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
internal static IXLCell _SetValue(this IXLCell cell, DateTime value, string dateFormat = "DD.MM.YYYY HH:MM:SS", bool setAllBorders = true)
|
internal static IXLCell _SetValue(this IXLCell cell, DateTime value, string dateFormat = "DD.MM.YYYY HH:MM:SS", bool setAllBorders = true)
|
||||||
{
|
{
|
||||||
cell.Value = value;
|
cell.Value = value;
|
||||||
@ -111,21 +26,6 @@ internal static class XLExtentions
|
|||||||
return cell;
|
return cell;
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static IXLCell _SetValue(this IXLCell cell, IFormattable value, string format = "0.00")
|
|
||||||
{
|
|
||||||
cell.Value = value;
|
|
||||||
cell.Style
|
|
||||||
.SetAllBorders()
|
|
||||||
.Alignment.WrapText = true;
|
|
||||||
|
|
||||||
cell.Value = value;
|
|
||||||
|
|
||||||
cell.DataType = XLDataType.Number;
|
|
||||||
cell.Style.NumberFormat.Format = "0.00";
|
|
||||||
|
|
||||||
return cell;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static IXLCell SetVal(this IXLCell cell, double? value, string format = "0.00")
|
public static IXLCell SetVal(this IXLCell cell, double? value, string format = "0.00")
|
||||||
{
|
{
|
||||||
cell.Value = (value is not null && double.IsFinite(value.Value)) ? value : null;
|
cell.Value = (value is not null && double.IsFinite(value.Value)) ? value : null;
|
||||||
@ -161,7 +61,7 @@ internal static class XLExtentions
|
|||||||
return cell;
|
return cell;
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static IXLStyle SetAllBorders(this IXLStyle style, XLBorderStyleValues borderStyle = XLBorderStyleValues.Thin)
|
private static IXLStyle SetAllBorders(this IXLStyle style, XLBorderStyleValues borderStyle = XLBorderStyleValues.Thin)
|
||||||
{
|
{
|
||||||
style.Border.RightBorder = borderStyle;
|
style.Border.RightBorder = borderStyle;
|
||||||
style.Border.LeftBorder = borderStyle;
|
style.Border.LeftBorder = borderStyle;
|
||||||
@ -172,20 +72,6 @@ internal static class XLExtentions
|
|||||||
return style;
|
return style;
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static IXLStyle SetBaseFont(this IXLStyle style)
|
|
||||||
{
|
|
||||||
style.Font.FontName = "Calibri";
|
|
||||||
style.Font.FontSize = 10;
|
|
||||||
return style;
|
|
||||||
}
|
|
||||||
|
|
||||||
internal static IXLStyle SetH1(this IXLStyle style)
|
|
||||||
{
|
|
||||||
style.Font.FontName = "Calibri";
|
|
||||||
style.Font.FontSize = 14;
|
|
||||||
return style;
|
|
||||||
}
|
|
||||||
|
|
||||||
internal static T? GetCellValue<T>(this IXLCell cell)
|
internal static T? GetCellValue<T>(this IXLCell cell)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
@ -204,7 +90,7 @@ internal static class XLExtentions
|
|||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
throw new FileFormatException(
|
throw new FileFormatException(
|
||||||
$"Лист '{cell.Worksheet.Name}'. Ячейка: ({cell.Address.RowNumber},{cell.Address.ColumnNumber}) содержит некорректное значение");
|
$"Лист '{cell.Worksheet.Name}'. {cell.Address.RowNumber} строка содержит некорректное значение в {cell.Address.ColumnNumber} столбце");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,48 +0,0 @@
|
|||||||
using AsbCloudInfrastructure.Services.Trajectory.Import;
|
|
||||||
using System.Linq;
|
|
||||||
using Xunit;
|
|
||||||
|
|
||||||
namespace AsbCloudWebApi.Tests.Services.Trajectory
|
|
||||||
{
|
|
||||||
public class TrajectoryImportTest
|
|
||||||
{
|
|
||||||
private readonly TrajectoryPlanParserService trajectoryPlanImportService;
|
|
||||||
private readonly TrajectoryFactManualParserService trajectoryFactManualImportService;
|
|
||||||
|
|
||||||
private string usingTemplateFile = "AsbCloudWebApi.Tests.Services.Trajectory.Templates";
|
|
||||||
|
|
||||||
public TrajectoryImportTest()
|
|
||||||
{
|
|
||||||
trajectoryPlanImportService = new TrajectoryPlanParserService();
|
|
||||||
trajectoryFactManualImportService = new TrajectoryFactManualParserService();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Import_trajectory_plan()
|
|
||||||
{
|
|
||||||
var stream = System.Reflection.Assembly.GetExecutingAssembly()
|
|
||||||
.GetManifestResourceStream($"{usingTemplateFile}.TrajectoryPlanTemplate.xlsx");
|
|
||||||
|
|
||||||
if (stream is null)
|
|
||||||
Assert.Fail("Файла для импорта не существует");
|
|
||||||
|
|
||||||
var trajectoryRows = trajectoryPlanImportService.Import(stream);
|
|
||||||
|
|
||||||
Assert.Equal(3, trajectoryRows.Count());
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Import_trajectory_fact_manual()
|
|
||||||
{
|
|
||||||
var stream = System.Reflection.Assembly.GetExecutingAssembly()
|
|
||||||
.GetManifestResourceStream($"{usingTemplateFile}.TrajectoryFactManualTemplate.xlsx");
|
|
||||||
|
|
||||||
if (stream is null)
|
|
||||||
Assert.Fail("Файла для импорта не существует");
|
|
||||||
|
|
||||||
var trajectoryRows = trajectoryFactManualImportService.Import(stream);
|
|
||||||
|
|
||||||
Assert.Equal(4, trajectoryRows.Count());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,63 @@
|
|||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using AsbCloudApp.Data.Trajectory;
|
||||||
|
using AsbCloudApp.Requests.ParserOptions;
|
||||||
|
using AsbCloudInfrastructure.Services;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using NSubstitute;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace AsbCloudWebApi.Tests.Services.Trajectory;
|
||||||
|
|
||||||
|
public class TrajectoryParserTest
|
||||||
|
{
|
||||||
|
private const string UsingTemplateFile = "AsbCloudWebApi.Tests.Services.Trajectory.Templates";
|
||||||
|
|
||||||
|
private readonly IServiceProvider serviceProviderMock = Substitute.For<IServiceProvider, ISupportRequiredService>();
|
||||||
|
private readonly IServiceScope serviceScopeMock = Substitute.For<IServiceScope>();
|
||||||
|
private readonly IServiceScopeFactory serviceScopeFactoryMock = Substitute.For<IServiceScopeFactory>();
|
||||||
|
|
||||||
|
private readonly ParserServiceFactory parserServiceFactory;
|
||||||
|
|
||||||
|
public TrajectoryParserTest()
|
||||||
|
{
|
||||||
|
serviceScopeFactoryMock.CreateScope().Returns(serviceScopeMock);
|
||||||
|
((ISupportRequiredService)serviceProviderMock).GetRequiredService(typeof(IServiceScopeFactory)).Returns(serviceScopeFactoryMock);
|
||||||
|
|
||||||
|
parserServiceFactory = new ParserServiceFactory(serviceProviderMock);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Parse_trajectory_plan()
|
||||||
|
{
|
||||||
|
var stream = System.Reflection.Assembly.GetExecutingAssembly()
|
||||||
|
.GetManifestResourceStream($"{UsingTemplateFile}.TrajectoryPlanTemplate.xlsx");
|
||||||
|
|
||||||
|
if (stream is null)
|
||||||
|
Assert.Fail("Файла для импорта не существует");
|
||||||
|
|
||||||
|
var parserService = parserServiceFactory.Create<TrajectoryGeoPlanDto, IParserOptionsRequest>(
|
||||||
|
ParserServiceFactory.IdTrajectoryPlanParserService);
|
||||||
|
|
||||||
|
var trajectoryRows = parserService.Parse(stream, IParserOptionsRequest.Empty());
|
||||||
|
|
||||||
|
Assert.Equal(3, trajectoryRows.Item.Count());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Parse_trajectory_fact_manual()
|
||||||
|
{
|
||||||
|
var stream = System.Reflection.Assembly.GetExecutingAssembly()
|
||||||
|
.GetManifestResourceStream($"{UsingTemplateFile}.TrajectoryFactManualTemplate.xlsx");
|
||||||
|
|
||||||
|
if (stream is null)
|
||||||
|
Assert.Fail("Файла для импорта не существует");
|
||||||
|
|
||||||
|
var parserService = parserServiceFactory.Create<TrajectoryGeoFactDto, IParserOptionsRequest>(
|
||||||
|
ParserServiceFactory.IdTrajectoryFactManualParserService);
|
||||||
|
|
||||||
|
var trajectoryRows = parserService.Parse(stream, IParserOptionsRequest.Empty());
|
||||||
|
|
||||||
|
Assert.Equal(4, trajectoryRows.Item.Count());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
using System.IO;
|
||||||
|
using AsbCloudApp.Data;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace AsbCloudWebApi.Controllers.Interfaces;
|
||||||
|
|
||||||
|
public interface IControllerWithParser<TDto, in TOptions>
|
||||||
|
where TDto : class, IId
|
||||||
|
{
|
||||||
|
ActionResult<ParserResultDto<TDto>> Parse(Stream file, TOptions options);
|
||||||
|
|
||||||
|
IActionResult GetTemplate();
|
||||||
|
}
|
@ -2,7 +2,6 @@
|
|||||||
using AsbCloudApp.Repositories;
|
using AsbCloudApp.Repositories;
|
||||||
using AsbCloudApp.Services;
|
using AsbCloudApp.Services;
|
||||||
using AsbCloudInfrastructure.Services.Trajectory.Export;
|
using AsbCloudInfrastructure.Services.Trajectory.Export;
|
||||||
using AsbCloudInfrastructure.Services.Trajectory.Import;
|
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
@ -10,6 +9,10 @@ using System.Collections.Generic;
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using AsbCloudApp.Data;
|
||||||
|
using AsbCloudApp.Requests.ParserOptions;
|
||||||
|
using AsbCloudInfrastructure.Services;
|
||||||
|
using AsbCloudWebApi.Controllers.Interfaces;
|
||||||
|
|
||||||
namespace AsbCloudWebApi.Controllers.Trajectory
|
namespace AsbCloudWebApi.Controllers.Trajectory
|
||||||
{
|
{
|
||||||
@ -19,28 +22,41 @@ namespace AsbCloudWebApi.Controllers.Trajectory
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
public abstract class TrajectoryEditableController<TDto> : TrajectoryController<TDto>
|
public abstract class TrajectoryEditableController<TDto> : TrajectoryController<TDto>,
|
||||||
|
IControllerWithParser<TDto, IParserOptionsRequest>
|
||||||
where TDto : TrajectoryGeoDto
|
where TDto : TrajectoryGeoDto
|
||||||
{
|
{
|
||||||
private readonly TrajectoryParserService<TDto> trajectoryImportService;
|
private readonly IParserService<TDto, IParserOptionsRequest> parserService;
|
||||||
private readonly TrajectoryExportService<TDto> trajectoryExportService;
|
private readonly ITrajectoryEditableRepository<TDto> trajectoryRepository;
|
||||||
private readonly ITrajectoryEditableRepository<TDto> trajectoryRepository;
|
|
||||||
|
|
||||||
public TrajectoryEditableController(IWellService wellService,
|
protected TrajectoryEditableController(IWellService wellService,
|
||||||
TrajectoryParserService<TDto> trajectoryImportService,
|
ParserServiceFactory parserServiceFactory,
|
||||||
TrajectoryExportService<TDto> trajectoryExportService,
|
TrajectoryExportService<TDto> trajectoryExportService,
|
||||||
ITrajectoryEditableRepository<TDto> trajectoryRepository)
|
ITrajectoryEditableRepository<TDto> trajectoryRepository,
|
||||||
|
int idParserService)
|
||||||
: base(
|
: base(
|
||||||
wellService,
|
wellService,
|
||||||
trajectoryExportService,
|
trajectoryExportService,
|
||||||
trajectoryRepository)
|
trajectoryRepository)
|
||||||
{
|
{
|
||||||
this.trajectoryImportService = trajectoryImportService;
|
parserService = parserServiceFactory.Create<TDto, IParserOptionsRequest>(idParserService);
|
||||||
this.trajectoryExportService = trajectoryExportService;
|
this.trajectoryRepository = trajectoryRepository;
|
||||||
this.trajectoryRepository = trajectoryRepository;
|
}
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
ActionResult<ParserResultDto<TDto>> IControllerWithParser<TDto, IParserOptionsRequest>.Parse(Stream file,
|
||||||
|
IParserOptionsRequest options)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var parserResult = parserService.Parse(file, options);
|
||||||
|
return Ok(parserResult);
|
||||||
|
}
|
||||||
|
catch (FileFormatException ex)
|
||||||
|
{
|
||||||
|
return this.ValidationBadRequest("files", ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Возвращает excel шаблон для заполнения строк траектории
|
/// Возвращает excel шаблон для заполнения строк траектории
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@ -51,110 +67,96 @@ namespace AsbCloudWebApi.Controllers.Trajectory
|
|||||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
public IActionResult GetTemplate()
|
public IActionResult GetTemplate()
|
||||||
{
|
{
|
||||||
var stream = trajectoryExportService.GetTemplateFile();
|
var stream = parserService.GetTemplateFile();
|
||||||
return File(stream, "application/octet-stream", fileName);
|
return File(stream, "application/octet-stream", fileName);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Импортирует координаты из excel (xlsx) файла
|
/// Импортирует координаты из excel (xlsx) файла
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="idWell">id скважины</param>
|
/// <param name="idWell">id скважины</param>
|
||||||
/// <param name="files">Коллекция из одного файла xlsx</param>
|
/// <param name="files">Коллекция из одного файла xlsx</param>
|
||||||
/// <param name="deleteBeforeImport">Удалить операции перед импортом, если фал валидный</param>
|
/// <param name="token"> Токен отмены задачи </param>
|
||||||
/// <param name="token"> Токен отмены задачи </param>
|
/// <returns>количество успешно записанных строк в БД</returns>
|
||||||
/// <returns>количество успешно записанных строк в БД</returns>
|
[HttpPost("parse")]
|
||||||
[HttpPost("import/{deleteBeforeImport}")]
|
[ProducesResponseType((int)System.Net.HttpStatusCode.OK)]
|
||||||
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
|
[ProducesResponseType(typeof(ValidationProblemDetails), (int)System.Net.HttpStatusCode.BadRequest)]
|
||||||
[ProducesResponseType(typeof(ValidationProblemDetails), (int)System.Net.HttpStatusCode.BadRequest)]
|
public async Task<ActionResult<ParserResultDto<TDto>>> Parse(int idWell,
|
||||||
public async Task<IActionResult> ImportAsync(int idWell,
|
[FromForm] IFormFileCollection files,
|
||||||
[FromForm] IFormFileCollection files,
|
CancellationToken token)
|
||||||
bool deleteBeforeImport,
|
{
|
||||||
CancellationToken token)
|
var idUser = User.GetUserId();
|
||||||
{
|
|
||||||
int? idUser = User.GetUserId();
|
|
||||||
if (!idUser.HasValue)
|
|
||||||
return Forbid();
|
|
||||||
if (!await CanUserAccessToWellAsync(idWell,
|
|
||||||
token).ConfigureAwait(false))
|
|
||||||
return Forbid();
|
|
||||||
if (files.Count < 1)
|
|
||||||
return this.ValidationBadRequest(nameof(files), "нет файла");
|
|
||||||
var file = files[0];
|
|
||||||
if (Path.GetExtension(file.FileName).ToLower() != ".xlsx")
|
|
||||||
return this.ValidationBadRequest(nameof(files), "Требуется xlsx файл.");
|
|
||||||
using Stream stream = file.OpenReadStream();
|
|
||||||
|
|
||||||
try
|
if (!idUser.HasValue)
|
||||||
{
|
return Forbid();
|
||||||
var trajectoryRows = trajectoryImportService.Import(stream);
|
|
||||||
foreach (var row in trajectoryRows)
|
|
||||||
{
|
|
||||||
row.IdWell = idWell;
|
|
||||||
row.IdUser = idUser.Value;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (deleteBeforeImport)
|
if (!await CanUserAccessToWellAsync(idWell, token))
|
||||||
await trajectoryRepository.DeleteByIdWellAsync(idWell, token);
|
return Forbid();
|
||||||
|
|
||||||
var rowsCount = await trajectoryRepository.AddRangeAsync(trajectoryRows, token);
|
return this.ParseExcelFile(files, IParserOptionsRequest.Empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Добавление
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="idWell"></param>
|
||||||
|
/// <param name="dtos"></param>
|
||||||
|
/// <param name="token"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPost]
|
||||||
|
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
|
||||||
|
public async Task<IActionResult> InsertRangeAsync(int idWell, [FromBody] IEnumerable<TDto> dtos, CancellationToken token)
|
||||||
|
{
|
||||||
|
if (!await CanUserAccessToWellAsync(idWell, token))
|
||||||
|
return Forbid();
|
||||||
|
|
||||||
|
var idUser = User.GetUserId();
|
||||||
|
|
||||||
|
if (!idUser.HasValue)
|
||||||
|
return Forbid();
|
||||||
|
|
||||||
|
foreach (var dto in dtos)
|
||||||
|
{
|
||||||
|
dto.IdUser = idUser.Value;
|
||||||
|
dto.IdWell = idWell;
|
||||||
|
}
|
||||||
|
|
||||||
return Ok(rowsCount);
|
var result = await trajectoryRepository.AddRangeAsync(dtos, token);
|
||||||
}
|
return Ok(result);
|
||||||
catch (FileFormatException ex)
|
}
|
||||||
{
|
|
||||||
return this.ValidationBadRequest(nameof(files), ex.Message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Удалить все по скважине и добавить новые
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="idWell"></param>
|
||||||
|
/// <param name="dtos"></param>
|
||||||
|
/// <param name="token"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPost("replace")]
|
||||||
|
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
|
||||||
|
public async Task<IActionResult> ClearAndInsertRangeAsync(int idWell, [FromBody] IEnumerable<TDto> dtos, CancellationToken token)
|
||||||
|
{
|
||||||
|
//TODO: это вся радость требует рефакторинга.
|
||||||
|
//Удаление с добавлением новых записей должно происходить в рамках одной транзакции, да и вообще должно быть реализовано на уровне репозиторий.
|
||||||
|
//Рефакторинг будет когда доберёмся до журнала изменений для траекторий.
|
||||||
|
if (!await CanUserAccessToWellAsync(idWell, token))
|
||||||
|
return Forbid();
|
||||||
|
|
||||||
|
var idUser = User.GetUserId();
|
||||||
|
|
||||||
|
if (!idUser.HasValue)
|
||||||
|
return Forbid();
|
||||||
|
|
||||||
|
foreach (var dto in dtos)
|
||||||
|
{
|
||||||
|
dto.IdUser = idUser.Value;
|
||||||
|
dto.IdWell = idWell;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
await trajectoryRepository.DeleteByIdWellAsync(idWell, token);
|
||||||
/// Добавить одну новую строчку координат для плановой траектории
|
var result = await trajectoryRepository.AddRangeAsync(dtos, token);
|
||||||
/// </summary>
|
return Ok(result);
|
||||||
/// <param name="idWell"></param>
|
}
|
||||||
/// <param name="row"></param>
|
|
||||||
/// <param name="token"></param>
|
|
||||||
/// <returns>количество успешно записанных строк в БД</returns>
|
|
||||||
[HttpPost]
|
|
||||||
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
|
|
||||||
public async Task<IActionResult> AddAsync(int idWell, [FromBody] TDto row,
|
|
||||||
CancellationToken token)
|
|
||||||
{
|
|
||||||
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
|
|
||||||
return Forbid();
|
|
||||||
var idUser = User.GetUserId();
|
|
||||||
if (!idUser.HasValue)
|
|
||||||
return Forbid();
|
|
||||||
row.IdUser = idUser.Value;
|
|
||||||
row.IdWell = idWell;
|
|
||||||
var result = await trajectoryRepository.AddAsync(row, token);
|
|
||||||
return Ok(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Добавить массив строчек координат для плановой траектории
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="idWell"></param>
|
|
||||||
/// <param name="rows"></param>
|
|
||||||
/// <param name="token"></param>
|
|
||||||
/// <returns>количество успешно записанных строк в БД</returns>
|
|
||||||
[HttpPost("range")]
|
|
||||||
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
|
|
||||||
public async Task<IActionResult> AddRangeAsync(int idWell, [FromBody] IEnumerable<TDto> rows,
|
|
||||||
CancellationToken token)
|
|
||||||
{
|
|
||||||
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
|
|
||||||
return Forbid();
|
|
||||||
int? idUser = User.GetUserId();
|
|
||||||
if (!idUser.HasValue)
|
|
||||||
return Forbid();
|
|
||||||
foreach (var item in rows)
|
|
||||||
{
|
|
||||||
item.IdUser = idUser.Value;
|
|
||||||
item.IdWell = idWell;
|
|
||||||
}
|
|
||||||
var result = await trajectoryRepository.AddRangeAsync(rows, token);
|
|
||||||
return Ok(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Изменить выбранную строку с координатами
|
/// Изменить выбранную строку с координатами
|
||||||
@ -201,4 +203,4 @@ namespace AsbCloudWebApi.Controllers.Trajectory
|
|||||||
return Ok(result);
|
return Ok(result);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,8 +1,8 @@
|
|||||||
using AsbCloudApp.Data.Trajectory;
|
using AsbCloudApp.Data.Trajectory;
|
||||||
using AsbCloudApp.Repositories;
|
using AsbCloudApp.Repositories;
|
||||||
using AsbCloudApp.Services;
|
using AsbCloudApp.Services;
|
||||||
|
using AsbCloudInfrastructure.Services;
|
||||||
using AsbCloudInfrastructure.Services.Trajectory.Export;
|
using AsbCloudInfrastructure.Services.Trajectory.Export;
|
||||||
using AsbCloudInfrastructure.Services.Trajectory.Import;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
namespace AsbCloudWebApi.Controllers.Trajectory;
|
namespace AsbCloudWebApi.Controllers.Trajectory;
|
||||||
@ -14,15 +14,17 @@ namespace AsbCloudWebApi.Controllers.Trajectory;
|
|||||||
[Route("api/well/{idWell}/[controller]")]
|
[Route("api/well/{idWell}/[controller]")]
|
||||||
public class TrajectoryFactManualController : TrajectoryEditableController<TrajectoryGeoFactDto>
|
public class TrajectoryFactManualController : TrajectoryEditableController<TrajectoryGeoFactDto>
|
||||||
{
|
{
|
||||||
protected override string fileName => "ЕЦП_шаблон_файла_фактическая_траектория.xlsx";
|
protected override string fileName => "ЕЦП_шаблон_файла_фактическая_траектория.xlsx";
|
||||||
public TrajectoryFactManualController(IWellService wellService,
|
|
||||||
TrajectoryFactManualParserService factTrajectoryImportService,
|
public TrajectoryFactManualController(IWellService wellService,
|
||||||
TrajectoryFactManualExportService factTrajectoryExportService,
|
TrajectoryFactManualExportService trajectoryExportService,
|
||||||
ITrajectoryEditableRepository<TrajectoryGeoFactDto> trajectoryFactRepository)
|
ParserServiceFactory parserServiceFactory,
|
||||||
: base(
|
ITrajectoryEditableRepository<TrajectoryGeoFactDto> trajectoryRepository)
|
||||||
wellService,
|
: base(wellService,
|
||||||
factTrajectoryImportService,
|
parserServiceFactory,
|
||||||
factTrajectoryExportService,
|
trajectoryExportService,
|
||||||
trajectoryFactRepository)
|
trajectoryRepository,
|
||||||
{ }
|
ParserServiceFactory.IdTrajectoryFactManualParserService)
|
||||||
|
{
|
||||||
|
}
|
||||||
}
|
}
|
@ -2,58 +2,58 @@
|
|||||||
using AsbCloudApp.Repositories;
|
using AsbCloudApp.Repositories;
|
||||||
using AsbCloudApp.Services;
|
using AsbCloudApp.Services;
|
||||||
using AsbCloudInfrastructure.Services.Trajectory;
|
using AsbCloudInfrastructure.Services.Trajectory;
|
||||||
using AsbCloudInfrastructure.Services.Trajectory.Import;
|
|
||||||
using AsbCloudInfrastructure.Services.Trajectory.Export;
|
using AsbCloudInfrastructure.Services.Trajectory.Export;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using AsbCloudInfrastructure.Services;
|
||||||
|
|
||||||
namespace AsbCloudWebApi.Controllers.Trajectory
|
namespace AsbCloudWebApi.Controllers.Trajectory
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Плановая траектория (загрузка и хранение)
|
||||||
|
/// </summary>
|
||||||
|
[Route("api/well/{idWell}/[controller]")]
|
||||||
|
[ApiController]
|
||||||
|
public class TrajectoryPlanController : TrajectoryEditableController<TrajectoryGeoPlanDto>
|
||||||
|
{
|
||||||
|
private readonly TrajectoryService trajectoryVisualizationService;
|
||||||
|
|
||||||
/// <summary>
|
protected override string fileName => "ЕЦП_шаблон_файла_плановая_траектория.xlsx";
|
||||||
/// Плановая траектория (загрузка и хранение)
|
|
||||||
/// </summary>
|
|
||||||
[Route("api/well/{idWell}/[controller]")]
|
|
||||||
[ApiController]
|
|
||||||
public class TrajectoryPlanController : TrajectoryEditableController<TrajectoryGeoPlanDto>
|
|
||||||
{
|
|
||||||
private readonly TrajectoryService trajectoryVisualizationService;
|
|
||||||
|
|
||||||
protected override string fileName => "ЕЦП_шаблон_файла_плановая_траектория.xlsx";
|
public TrajectoryPlanController(IWellService wellService,
|
||||||
|
TrajectoryPlanExportService trajectoryExportService,
|
||||||
|
ParserServiceFactory parserServiceFactory,
|
||||||
|
ITrajectoryEditableRepository<TrajectoryGeoPlanDto> trajectoryRepository,
|
||||||
|
TrajectoryService trajectoryVisualizationService)
|
||||||
|
: base(wellService,
|
||||||
|
parserServiceFactory,
|
||||||
|
trajectoryExportService,
|
||||||
|
trajectoryRepository,
|
||||||
|
ParserServiceFactory.IdTrajectoryPlanParserService)
|
||||||
|
{
|
||||||
|
this.trajectoryVisualizationService = trajectoryVisualizationService;
|
||||||
|
}
|
||||||
|
|
||||||
public TrajectoryPlanController(IWellService wellService,
|
/// <summary>
|
||||||
TrajectoryPlanParserService trajectoryPlanImportService,
|
/// Получение координат для визуализации траектории (плановой и фактической)
|
||||||
TrajectoryPlanExportService trajectoryPlanExportService,
|
/// </summary>
|
||||||
ITrajectoryEditableRepository<TrajectoryGeoPlanDto> trajectoryPlanRepository,
|
/// <param name="idWell"></param>
|
||||||
TrajectoryService trajectoryVisualizationService)
|
/// <param name="token"></param>
|
||||||
: base(
|
/// <returns></returns>
|
||||||
wellService,
|
[HttpGet("trajectoryCartesianPlanFact")]
|
||||||
trajectoryPlanImportService,
|
[ProducesResponseType(
|
||||||
trajectoryPlanExportService,
|
typeof(TrajectoryPlanFactDto<IEnumerable<TrajectoryCartesianPlanDto>, IEnumerable<TrajectoryCartesianFactDto>>),
|
||||||
trajectoryPlanRepository)
|
(int)System.Net.HttpStatusCode.OK)]
|
||||||
{
|
public async Task<IActionResult> GetTrajectoryCartesianPlanFactAsync(int idWell, CancellationToken token)
|
||||||
this.trajectoryVisualizationService = trajectoryVisualizationService;
|
{
|
||||||
}
|
if (!await CanUserAccessToWellAsync(idWell,
|
||||||
|
token).ConfigureAwait(false))
|
||||||
|
return Forbid();
|
||||||
|
|
||||||
/// <summary>
|
var result = await trajectoryVisualizationService.GetTrajectoryCartesianAsync(idWell, token);
|
||||||
/// Получение координат для визуализации траектории (плановой и фактической)
|
return Ok(result);
|
||||||
/// </summary>
|
}
|
||||||
/// <param name="idWell"></param>
|
}
|
||||||
/// <param name="token"></param>
|
}
|
||||||
/// <returns></returns>
|
|
||||||
[HttpGet("trajectoryCartesianPlanFact")]
|
|
||||||
[ProducesResponseType(typeof(TrajectoryPlanFactDto<IEnumerable<TrajectoryCartesianPlanDto>, IEnumerable<TrajectoryCartesianFactDto>>), (int)System.Net.HttpStatusCode.OK)]
|
|
||||||
public async Task<IActionResult> GetTrajectoryCartesianPlanFactAsync(int idWell, CancellationToken token)
|
|
||||||
{
|
|
||||||
if (!await CanUserAccessToWellAsync(idWell,
|
|
||||||
token).ConfigureAwait(false))
|
|
||||||
return Forbid();
|
|
||||||
|
|
||||||
var result = await trajectoryVisualizationService.GetTrajectoryCartesianAsync(idWell, token);
|
|
||||||
return Ok(result);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
125
AsbCloudWebApi/Extensions.cs
Normal file
125
AsbCloudWebApi/Extensions.cs
Normal file
@ -0,0 +1,125 @@
|
|||||||
|
using AsbCloudApp.Data.User;
|
||||||
|
using AsbCloudWebApi.Converters;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.ComponentModel;
|
||||||
|
using System.IO;
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Security.Claims;
|
||||||
|
using AsbCloudApp.Data;
|
||||||
|
using AsbCloudApp.Requests.ParserOptions;
|
||||||
|
using AsbCloudWebApi.Controllers.Interfaces;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
|
||||||
|
namespace Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
public static class Extensions
|
||||||
|
{
|
||||||
|
public static int? GetCompanyId(this ClaimsPrincipal user)
|
||||||
|
{
|
||||||
|
var claimIdCompany = user.FindFirst(nameof(UserDto.IdCompany));
|
||||||
|
if (claimIdCompany is null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
return int.TryParse(claimIdCompany.Value, out int uid)
|
||||||
|
? uid
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int? GetUserId(this ClaimsPrincipal user)
|
||||||
|
{
|
||||||
|
var userId = user.FindFirst(nameof(UserDto.Id));
|
||||||
|
if (userId is null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
return int.TryParse(userId.Value, out int uid)
|
||||||
|
? uid
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <para>
|
||||||
|
/// Returns BadRequest with ValidationProblemDetails as body
|
||||||
|
/// </para>
|
||||||
|
/// <para>
|
||||||
|
/// Используйте этот метод только если валидацию нельзя сделать через
|
||||||
|
/// атрибуты валидации или IValidatableObject модели.
|
||||||
|
/// </para>
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="controller"></param>
|
||||||
|
/// <param name="paramName"></param>
|
||||||
|
/// <param name="error"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static BadRequestObjectResult ValidationBadRequest(this ControllerBase controller, string paramName, string error)
|
||||||
|
{
|
||||||
|
return MakeBadRequestObjectResult(paramName, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static BadRequestObjectResult MakeBadRequestObjectResult(string paramName, string error)
|
||||||
|
{
|
||||||
|
var errors = new Dictionary<string, string[]> {
|
||||||
|
{ paramName, new[]{ error } }
|
||||||
|
};
|
||||||
|
var problem = new ValidationProblemDetails(errors);
|
||||||
|
var badRequestObject = new BadRequestObjectResult(problem);
|
||||||
|
return badRequestObject;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <para>
|
||||||
|
/// Returns BadRequest with ValidationProblemDetails as body
|
||||||
|
/// </para>
|
||||||
|
/// <para>
|
||||||
|
/// Используйте этот метод только если валидацию нельзя сделать через
|
||||||
|
/// атрибуты валидации или IValidatableObject модели.
|
||||||
|
/// </para>
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="controller"></param>
|
||||||
|
/// <param name="validationResults"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static BadRequestObjectResult ValidationBadRequest(this ControllerBase controller, IEnumerable<ValidationResult> validationResults)
|
||||||
|
{
|
||||||
|
var errors = validationResults
|
||||||
|
.SelectMany(e => e.MemberNames.Select(name => new { name, e.ErrorMessage }))
|
||||||
|
.GroupBy(e => e.name)
|
||||||
|
.ToDictionary(e => e.Key, e => e.Select(el => el.ErrorMessage ?? string.Empty).ToArray());
|
||||||
|
|
||||||
|
var problem = new ValidationProblemDetails(errors);
|
||||||
|
return controller.BadRequest(problem);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static MvcOptions UseDateOnlyTimeOnlyStringConverters(this MvcOptions options)
|
||||||
|
{
|
||||||
|
TypeDescriptor.AddAttributes(typeof(DateOnly), new TypeConverterAttribute(typeof(DateOnlyTypeConverter)));
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Вызов парсера со стандартной валидацией входного файла
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="TDto"></typeparam>
|
||||||
|
/// <typeparam name="TOptions"></typeparam>
|
||||||
|
/// <param name="controller"></param>
|
||||||
|
/// <param name="files"></param>
|
||||||
|
/// <param name="options"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static ActionResult<ParserResultDto<TDto>> ParseExcelFile<TDto, TOptions>(
|
||||||
|
this IControllerWithParser<TDto, TOptions> controller,
|
||||||
|
IFormFileCollection files,
|
||||||
|
TOptions options)
|
||||||
|
where TDto : class, IId
|
||||||
|
where TOptions : class, IParserOptionsRequest
|
||||||
|
{
|
||||||
|
if (files.Count < 1)
|
||||||
|
return MakeBadRequestObjectResult(nameof(files), "Нет файла");
|
||||||
|
|
||||||
|
var file = files[0];
|
||||||
|
if (Path.GetExtension(file.FileName).ToLower() != ".xlsx")
|
||||||
|
return MakeBadRequestObjectResult(nameof(files), "Требуется .xlsx файл.");
|
||||||
|
|
||||||
|
var stream = file.OpenReadStream();
|
||||||
|
|
||||||
|
return controller.Parse(stream, options);
|
||||||
|
}
|
||||||
|
}
|
@ -1,89 +0,0 @@
|
|||||||
using AsbCloudApp.Data.User;
|
|
||||||
using AsbCloudWebApi.Converters;
|
|
||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.ComponentModel;
|
|
||||||
using System.ComponentModel.DataAnnotations;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Security.Claims;
|
|
||||||
|
|
||||||
namespace Microsoft.AspNetCore.Mvc
|
|
||||||
{
|
|
||||||
public static class Extentions
|
|
||||||
{
|
|
||||||
public static int? GetCompanyId(this ClaimsPrincipal user)
|
|
||||||
{
|
|
||||||
var claimIdCompany = user.FindFirst(nameof(UserDto.IdCompany));
|
|
||||||
if (claimIdCompany is null)
|
|
||||||
return null;
|
|
||||||
|
|
||||||
return int.TryParse(claimIdCompany.Value, out int uid)
|
|
||||||
? uid
|
|
||||||
: null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static int? GetUserId(this ClaimsPrincipal user)
|
|
||||||
{
|
|
||||||
var userId = user.FindFirst(nameof(UserDto.Id));
|
|
||||||
if (userId is null)
|
|
||||||
return null;
|
|
||||||
|
|
||||||
return int.TryParse(userId.Value, out int uid)
|
|
||||||
? uid
|
|
||||||
: null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// <para>
|
|
||||||
/// Returns BadRequest with ValidationProblemDetails as body
|
|
||||||
/// </para>
|
|
||||||
/// <para>
|
|
||||||
/// Используйте этот метод только если валидацию нельзя сделать через
|
|
||||||
/// атрибуты валидации или IValidatableObject модели.
|
|
||||||
/// </para>
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="controller"></param>
|
|
||||||
/// <param name="paramName"></param>
|
|
||||||
/// <param name="error"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
public static BadRequestObjectResult ValidationBadRequest(this ControllerBase controller, string paramName, string error)
|
|
||||||
{
|
|
||||||
var errors = new Dictionary<string, string[]> {
|
|
||||||
{ paramName, new[]{ error } }
|
|
||||||
};
|
|
||||||
var problem = new ValidationProblemDetails(errors);
|
|
||||||
return controller.BadRequest(problem);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// <para>
|
|
||||||
/// Returns BadRequest with ValidationProblemDetails as body
|
|
||||||
/// </para>
|
|
||||||
/// <para>
|
|
||||||
/// Используйте этот метод только если валидацию нельзя сделать через
|
|
||||||
/// атрибуты валидации или IValidatableObject модели.
|
|
||||||
/// </para>
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="controller"></param>
|
|
||||||
/// <param name="validationResults"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
public static BadRequestObjectResult ValidationBadRequest(this ControllerBase controller, IEnumerable<ValidationResult> validationResults)
|
|
||||||
{
|
|
||||||
var errors = validationResults
|
|
||||||
.SelectMany(e => e.MemberNames.Select(name => new { name, e.ErrorMessage }))
|
|
||||||
.GroupBy(e => e.name)
|
|
||||||
.ToDictionary(e => e.Key, e => e.Select(el => el.ErrorMessage ?? string.Empty).ToArray());
|
|
||||||
|
|
||||||
var problem = new ValidationProblemDetails(errors);
|
|
||||||
return controller.BadRequest(problem);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static MvcOptions UseDateOnlyTimeOnlyStringConverters(this MvcOptions options)
|
|
||||||
{
|
|
||||||
TypeDescriptor.AddAttributes(typeof(DateOnly), new TypeConverterAttribute(typeof(DateOnlyTypeConverter)));
|
|
||||||
return options;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user