WellOperationImportService Add GetTemplate(),

Improve error handling.
This commit is contained in:
Фролов 2021-10-11 13:45:06 +05:00
parent e604d8a031
commit 9117471f82
3 changed files with 38 additions and 15 deletions

View File

@ -5,6 +5,7 @@ namespace AsbCloudApp.Services
public interface IWellOperationImportService public interface IWellOperationImportService
{ {
Stream Export(int idWell); Stream Export(int idWell);
Stream GetExcelTemplateStream();
void Import(int idWell, Stream stream, bool deleteWellOperationsBeforeImport = false); void Import(int idWell, Stream stream, bool deleteWellOperationsBeforeImport = false);
} }
} }

View File

@ -90,10 +90,15 @@ namespace AsbCloudInfrastructure.Services.WellOperationService
return MakeExelFileStream(operations); return MakeExelFileStream(operations);
} }
public Stream GetExcelTemplateStream() {
var stream = System.Reflection.Assembly.GetExecutingAssembly()
.GetManifestResourceStream("AsbCloudInfrastructure.Services.WellOperationService.WellOperationImportTemplate.xltx");
return stream;
}
private Stream MakeExelFileStream(IEnumerable<WellOperation> operations) private Stream MakeExelFileStream(IEnumerable<WellOperation> operations)
{ {
using Stream ecxelTemplateStream = System.Reflection.Assembly.GetExecutingAssembly() using Stream ecxelTemplateStream = GetExcelTemplateStream();
.GetManifestResourceStream("AsbCloudInfrastructure.Services.WellOperationService.WellOperationImportTemplate.xltx");
using var workbook = new XLWorkbook(ecxelTemplateStream, XLEventTracking.Disabled); using var workbook = new XLWorkbook(ecxelTemplateStream, XLEventTracking.Disabled);
AddOperationsToWorkbook(workbook, operations); AddOperationsToWorkbook(workbook, operations);
@ -225,12 +230,14 @@ namespace AsbCloudInfrastructure.Services.WellOperationService
} }
}; };
// проверка диапазона дат
if (operations.Min(o => o.DateStart) - operations.Max(o => o.DateStart) > drillingDurationLimitMax)
parseErrors.Add($"Лист {sheet.Name} содержит диапазон дат больше {drillingDurationLimitMax}");
if (parseErrors.Any()) if (parseErrors.Any())
throw new FileFormatException(string.Join("\r\n", parseErrors)); throw new FileFormatException(string.Join("\r\n", parseErrors));
else
{
if (operations.Any())
if (operations.Min(o => o.DateStart) - operations.Max(o => o.DateStart) > drillingDurationLimitMax)
parseErrors.Add($"Лист {sheet.Name} содержит диапазон дат больше {drillingDurationLimitMax}");
}
return operations; return operations;
} }

View File

@ -179,16 +179,15 @@ namespace AsbCloudWebApi.Controllers
/// Импортирует операции из excel (xlsx) файла /// Импортирует операции из excel (xlsx) файла
/// </summary> /// </summary>
/// <param name="idWell">id скважины</param> /// <param name="idWell">id скважины</param>
/// <param name="files">Коллекция файлов - 1 файл xlsx</param> /// <param name="files">Коллекция из одного файла xlsx</param>
/// <param name="deleteWellOperationsBeforeImport">Удалить операции перед импортом, если фал валидный</param> /// <param name="options">Удалить операции перед импортом = 1, если фал валидный</param>
/// <param name="token"> Токен отмены задачи </param> /// <param name="token"> Токен отмены задачи </param>
/// <returns></returns> /// <returns></returns>
[HttpPost] [HttpPost]
[Route("import")] [Route("import/{options}")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> ImportAsync(int idWell, public async Task<IActionResult> ImportAsync(int idWell,
[FromForm] IFormFileCollection files, [FromForm] IFormFileCollection files,
bool deleteWellOperationsBeforeImport = false, int options = 0,
CancellationToken token = default) CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
@ -205,13 +204,13 @@ namespace AsbCloudWebApi.Controllers
return BadRequest("нет файла"); return BadRequest("нет файла");
var file = files[0]; var file = files[0];
if(Path.GetExtension( file.FileName).ToLower() != "*.xlsx") if(Path.GetExtension( file.FileName).ToLower() != ".xlsx")
return BadRequest("Требуется xlsx файл."); return BadRequest("Требуется xlsx файл.");
using Stream stream = file.OpenReadStream(); using Stream stream = file.OpenReadStream();
try try
{ {
wellOperationImportService.Import(idWell, stream, deleteWellOperationsBeforeImport); wellOperationImportService.Import(idWell, stream, (options & 1) > 0);
} }
catch(FileFormatException ex) catch(FileFormatException ex)
{ {
@ -222,7 +221,7 @@ namespace AsbCloudWebApi.Controllers
} }
/// <summary> /// <summary>
/// Возвращает файл с диска на сервере /// Создает excel файл с операциями по скважине
/// </summary> /// </summary>
/// <param name="idWell">id скважины</param> /// <param name="idWell">id скважины</param>
/// <param name="token"> Токен отмены задачи </param> /// <param name="token"> Токен отмены задачи </param>
@ -246,6 +245,22 @@ namespace AsbCloudWebApi.Controllers
return File(stream, "application/octet-stream", fileName); return File(stream, "application/octet-stream", fileName);
} }
/// <summary>
/// Возвращает шаблон файла импорта
/// </summary>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>Запрашиваемый файл</returns>
[HttpGet]
[Route("tamplate")]
[AllowAnonymous]
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
public IActionResult GetTamplate()
{
var stream = wellOperationImportService.GetExcelTemplateStream();
var fileName = "ЕЦП_шаблон_файла_операций.xlsx";
return File(stream, "application/octet-stream", fileName);
}
private async Task<bool> CanUserAccessToWellAsync(int idWell, CancellationToken token = default) private async Task<bool> CanUserAccessToWellAsync(int idWell, CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();