diff --git a/AsbCloudApp/Data/PlannedTrajectoryDto.cs b/AsbCloudApp/Data/PlannedTrajectoryDto.cs index d6aa97cc..52da8983 100644 --- a/AsbCloudApp/Data/PlannedTrajectoryDto.cs +++ b/AsbCloudApp/Data/PlannedTrajectoryDto.cs @@ -27,72 +27,72 @@ namespace AsbCloudApp.Data /// /// Глубина по стволу /// - public double? WellboreDepth { get; set; } + public double WellboreDepth { get; set; } /// /// Угол зенитный /// - public double? ZenithAngle { get; set; } + public double ZenithAngle { get; set; } /// /// Азимут Географ. /// - public double? AzimuthGeo { get; set; } + public double AzimuthGeo { get; set; } /// /// Азимут Магнитный /// - public double? AzimuthMagnetic { get; set; } + public double AzimuthMagnetic { get; set; } /// /// Глубина вертикальная /// - public double? VerticalDepth { get; set; } + public double VerticalDepth { get; set; } /// /// Абсолютная отметка /// - public double? AbsoluteMark { get; set; } + public double AbsoluteMark { get; set; } /// /// Север отн- но устья /// - public double? NorthOrifice { get; set; } + public double NorthOrifice { get; set; } /// /// Восток отн- но устья /// - public double? EastOrifice { get; set; } + public double EastOrifice { get; set; } /// /// Восток картографический /// - public double? EastCartographic { get; set; } + public double EastCartographic { get; set; } /// /// Север картографический /// - public double? NorthCartographic { get; set; } + public double NorthCartographic { get; set; } /// /// Пространственная интенсивность /// - public double? SpatialIntensity { get; set; } + public double SpatialIntensity { get; set; } /// /// Интенсивность по углу /// - public double? AngleIntensity { get; set; } + public double AngleIntensity { get; set; } /// /// Интенсивность по азимуту /// - public double? AzimuthIntensity { get; set; } + public double AzimuthIntensity { get; set; } /// /// Смещение от устья /// - public double? OrificeOffset { get; set; } + public double OrificeOffset { get; set; } /// /// Комментарии diff --git a/AsbCloudApp/Services/IPlannedTrajectoryImportService.cs b/AsbCloudApp/Services/IPlannedTrajectoryImportService.cs index 4b8f214b..e3013704 100644 --- a/AsbCloudApp/Services/IPlannedTrajectoryImportService.cs +++ b/AsbCloudApp/Services/IPlannedTrajectoryImportService.cs @@ -1,4 +1,7 @@ using System.IO; +using System.Threading; +using System.Threading.Tasks; + namespace AsbCloudApp.Services { #nullable enable @@ -12,20 +15,28 @@ namespace AsbCloudApp.Services /// /// Stream GetTemplateFile(); + /// + /// Получить имя файла (исходя из названия скважины) + /// + /// + string GetFileName(int idWell, CancellationToken token); + /// /// загрузить текущую плановую траекторию в .xlsx /// /// + /// /// - Stream Export(int idWell); + Task ExportAsync(int idWell, CancellationToken token); /// /// импортировать из excel плановую траекторию /// /// /// /// + /// /// Очистить старые координаты перед импортом (если файл проходит валидацию) - void Import(int idWell, int idUser, Stream stream, bool deleteWellOperationsBeforeImport = false); + Task ImportAsync(int idWell, int idUser, Stream stream, CancellationToken token, bool deleteWellOperationsBeforeImport = false); } #nullable disable } diff --git a/AsbCloudApp/Services/IPlannedTrajectoryService.cs b/AsbCloudApp/Services/IPlannedTrajectoryService.cs index fec54105..3c4c1c6f 100644 --- a/AsbCloudApp/Services/IPlannedTrajectoryService.cs +++ b/AsbCloudApp/Services/IPlannedTrajectoryService.cs @@ -18,7 +18,7 @@ namespace AsbCloudApp.Services /// /// /// - Task?> GetCoordinatesAsync(int idWell, CancellationToken token); + Task?> GetAsync(int idWell, CancellationToken token); /// /// Добавить строки с координатами @@ -50,6 +50,14 @@ namespace AsbCloudApp.Services /// /// Task DeleteRangeAsync(IEnumerable ids, CancellationToken token); + + /// + /// Удалить всю плановую траекторию по ИД скважины + /// + /// + /// + /// + Task DeleteAllByIdWellAsync(int idWell, CancellationToken token); } #nullable disable } diff --git a/AsbCloudInfrastructure/Services/PlannedTrajectoryService/PlannedTrajectoryImportService.cs b/AsbCloudInfrastructure/Services/PlannedTrajectoryService/PlannedTrajectoryImportService.cs index 87510201..fe1b9682 100644 --- a/AsbCloudInfrastructure/Services/PlannedTrajectoryService/PlannedTrajectoryImportService.cs +++ b/AsbCloudInfrastructure/Services/PlannedTrajectoryService/PlannedTrajectoryImportService.cs @@ -1,13 +1,11 @@ using AsbCloudApp.Data; using AsbCloudApp.Services; -using AsbCloudDb.Model; using ClosedXML.Excel; -using Mapster; -using Microsoft.EntityFrameworkCore; -using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Threading; +using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services.PlannedTrajectory { @@ -17,9 +15,9 @@ namespace AsbCloudInfrastructure.Services.PlannedTrajectory /* * password for PlannedTrajectoryTemplate.xlsx is Drill2022 */ - - private readonly IAsbCloudDbContext db; + private readonly IWellService wellService; + private readonly IPlannedTrajectoryService plannedTrajectoryService; private const string sheetNamePlannedTrajectory = "Плановая траектория"; private const int headerRowsCount = 2; @@ -39,35 +37,37 @@ namespace AsbCloudInfrastructure.Services.PlannedTrajectory private const int ColumnOrificeOffset = 14; private const int ColumnComment = 15; - public PlannedTrajectoryImportService(IAsbCloudDbContext db, IWellService wellService) + public PlannedTrajectoryImportService(IWellService wellService, IPlannedTrajectoryService plannedTrajectoryService) { - this.db = db; + this.wellService = wellService; + this.plannedTrajectoryService = plannedTrajectoryService; } public Stream GetTemplateFile() { var stream = System.Reflection.Assembly.GetExecutingAssembly() - .GetManifestResourceStream("AsbCloudInfrastructure.Services.PlannedTrajectoryService.PlannedTrajectoryTemplate.xlsx"); + .GetManifestResourceStream("AsbCloudInfrastructure.Services.PlannedTrajectoryService.PlannedTrajectoryTemplate.xlsx"); return stream; } - public Stream Export(int idWell) + public string GetFileName (int idWell, CancellationToken token) { - var plannedTrajectorys = db.PlannedTrajectorys - .Where(o => o.IdWell == idWell) - .AsNoTracking() - .ToList(); + var fileName = wellService.GetWellCaptionByIdAsync(idWell, token) + "_plannedTrajectory.xlsx"; + return fileName; + } + + public async Task ExportAsync(int idWell, CancellationToken token) + { + var plannedTrajectorys = await plannedTrajectoryService.GetAsync(idWell, token); if (!plannedTrajectorys.Any()) return null; - var timezone = wellService.GetTimezone(idWell); - return MakeExelFileStream(plannedTrajectorys); } - private Stream MakeExelFileStream(IEnumerable plannedTrajectories) + private Stream MakeExelFileStream(IEnumerable plannedTrajectories) { - using Stream ecxelTemplateStream = GetTemplateFile(); + using Stream ecxelTemplateStream = GetTemplateFile(); using var workbook = new XLWorkbook(ecxelTemplateStream, XLEventTracking.Disabled); AddOperationsToWorkbook(workbook, plannedTrajectories); MemoryStream memoryStream = new MemoryStream(); @@ -76,7 +76,7 @@ namespace AsbCloudInfrastructure.Services.PlannedTrajectory return memoryStream; } - private static void AddOperationsToWorkbook(XLWorkbook workbook, IEnumerable plannedTrajectories) + private static void AddOperationsToWorkbook(XLWorkbook workbook, IEnumerable plannedTrajectories) { if (plannedTrajectories.Any()) { @@ -85,16 +85,16 @@ namespace AsbCloudInfrastructure.Services.PlannedTrajectory } } - private static void AddOperationsToSheet(IXLWorksheet sheet, IEnumerable plannedTrajectories) + private static void AddOperationsToSheet(IXLWorksheet sheet, IEnumerable plannedTrajectories) { - var operationsList = plannedTrajectories.ToList(); - for (int i = 0; i < operationsList.Count; i++) + var rowList = plannedTrajectories.ToList(); + for (int i = 0; i < rowList.Count; i++) { var row = sheet.Row(1 + i + headerRowsCount); - AddOperationToRow(row, operationsList[i]); + AddOperationToRow(row, rowList[i]); } } - private static void AddOperationToRow(IXLRow row, AsbCloudDb.Model.PlannedTrajectory trajectory) + private static void AddOperationToRow(IXLRow row, PlannedTrajectoryDto trajectory) { row.Cell(ColumnWellboreDepth).Value = trajectory.WellboreDepth; row.Cell(ColumnZenithAngle).Value = trajectory.ZenithAngle; @@ -113,41 +113,25 @@ namespace AsbCloudInfrastructure.Services.PlannedTrajectory row.Cell(ColumnComment).Value = trajectory.Comment; } - public void Import(int idWell, int idUser, Stream stream, bool deletePrevRows = false) + public async Task ImportAsync(int idWell, int idUser, Stream stream, CancellationToken token, bool deletePrevRows = false) { using var workbook = new XLWorkbook(stream, XLEventTracking.Disabled); var trajectoryRows = ParseFileStream(stream); foreach (var row in trajectoryRows) row.IdWell = idWell; - SaveOperations(idWell, idUser, trajectoryRows, deletePrevRows); + var rowsCount = await SavePlannedTrajectoryAsync(idWell, idUser, trajectoryRows, token, deletePrevRows); + return rowsCount; } - private void SaveOperations(int idWell, int idUser, IEnumerable newRows, bool deletePrevRow = false) + private async Task SavePlannedTrajectoryAsync(int idWell, int idUser, IEnumerable newRows, CancellationToken token, bool deletePrevRow = false) { - var timezone = wellService.GetTimezone(idWell); - var transaction = db.Database.BeginTransaction(); - try + if (deletePrevRow) { - if (deletePrevRow) - db.WellOperations.RemoveRange(db.WellOperations.Where(o => o.IdWell == idWell)); - var entities = newRows.Select(o => - { - var entity = o.Adapt(); - entity.IdWell = idWell; - entity.UpdateDate = DateTime.Today.ToUtcDateTimeOffset(timezone.Hours); - entity.IdUser = idUser; - return entity; - }); - db.PlannedTrajectorys.AddRange(entities); - db.SaveChanges(); - transaction.Commit(); - } - catch - { - transaction.Rollback(); - throw; + await plannedTrajectoryService.DeleteAllByIdWellAsync(idWell, token); } + var rowsCount = await plannedTrajectoryService.AddAsync(idWell, idUser, newRows, token); + return rowsCount; } private IEnumerable ParseFileStream(Stream stream) @@ -215,23 +199,12 @@ namespace AsbCloudInfrastructure.Services.PlannedTrajectory var _comment = row.Cell(ColumnComment).Value; var trajectoryRow = new PlannedTrajectoryDto(); - - static bool isCorrectValue(object value) - { - if (value is null) - return true; - if (value is double) - return true; - return false; - } - - static double? getDoubleValue(object value, string nameParam, IXLRow row) - { - if (!isCorrectValue(value)) - throw new FileFormatException($"Лист {row.Worksheet.Name}. Строка {row.RowNumber()} - некорректные данные - {nameParam}"); + + static double getDoubleValue(object value, string nameParam, IXLRow row) + { if (value is double _value) - return _value; - return null; + return _value; + throw new FileFormatException($"Лист {row.Worksheet.Name}. Строка {row.RowNumber()} - некорректные данные - {nameParam}"); } trajectoryRow.WellboreDepth = getDoubleValue(_wellboreDepth, "Глубина по стволу", row); diff --git a/AsbCloudInfrastructure/Services/PlannedTrajectoryService/PlannedTrajectoryService.cs b/AsbCloudInfrastructure/Services/PlannedTrajectoryService/PlannedTrajectoryService.cs index edddc4eb..4c1be72e 100644 --- a/AsbCloudInfrastructure/Services/PlannedTrajectoryService/PlannedTrajectoryService.cs +++ b/AsbCloudInfrastructure/Services/PlannedTrajectoryService/PlannedTrajectoryService.cs @@ -38,6 +38,22 @@ namespace AsbCloudInfrastructure.Services.PlannedTrajectory .ConfigureAwait(false); } + public async Task AddListAsync(int idWell, int idUser, IEnumerable plannedTrajectoryRows, CancellationToken token) + { + var timezone = wellService.GetTimezone(idWell); + foreach (var dto in plannedTrajectoryRows) + { + var entity = dto.Adapt(); + entity.IdWell = idWell; + entity.Id = default; + entity.UpdateDate = DateTime.Today.ToUtcDateTimeOffset(timezone.Hours); + entity.IdUser = idUser; + db.PlannedTrajectorys.Add(entity); + } + return await db.SaveChangesAsync(token) + .ConfigureAwait(false); + } + public async Task DeleteRangeAsync(IEnumerable ids, CancellationToken token) { var query = db.PlannedTrajectorys.Where(e => ids.Contains(e.Id)); @@ -46,7 +62,16 @@ namespace AsbCloudInfrastructure.Services.PlannedTrajectory .ConfigureAwait(false); } - public async Task?> GetCoordinatesAsync(int idWell, CancellationToken token) + public async Task DeleteAllByIdWellAsync(int idWell, CancellationToken token) + { + var query = db.PlannedTrajectorys + .Where(e => e.IdWell == idWell); + var ids = await query.Select(r => r.IdWell).ToListAsync(token); + var result = await DeleteRangeAsync(ids, token); + } + + + public async Task?> GetAsync(int idWell, CancellationToken token) { var well = wellService.GetOrDefault(idWell); if (well is null || well.Timezone is null) diff --git a/AsbCloudWebApi/Controllers/PlannedTrajectoryController.cs b/AsbCloudWebApi/Controllers/PlannedTrajectoryController.cs index 5fdc0482..288b4750 100644 --- a/AsbCloudWebApi/Controllers/PlannedTrajectoryController.cs +++ b/AsbCloudWebApi/Controllers/PlannedTrajectoryController.cs @@ -59,17 +59,11 @@ namespace AsbCloudWebApi.Controllers [ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)] public async Task ExportAsync([FromRoute] int idWell, CancellationToken token = default) { - int? idCompany = User.GetCompanyId(); - - if (idCompany is null) + if (!await CanUserAccessToWellAsync(idWell, + token).ConfigureAwait(false)) return Forbid(); - - if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, - idWell, token).ConfigureAwait(false)) - return Forbid(); - - var stream = plannedTrajectoryImportService.Export(idWell); - var fileName = await wellService.GetWellCaptionByIdAsync(idWell, token) + "_plannedTrajectory.xlsx"; + var stream = await plannedTrajectoryImportService.ExportAsync(idWell, token); + var fileName = plannedTrajectoryImportService.GetFileName(idWell, token); return File(stream, "application/octet-stream", fileName); } @@ -110,14 +104,13 @@ namespace AsbCloudWebApi.Controllers try { - plannedTrajectoryImportService.Import(idWell, idUser.Value, stream, (options & 1) > 0); + var result = plannedTrajectoryImportService.ImportAsync(idWell, idUser.Value, stream, token,(options & 1) > 0); + return Ok(result); } catch (FileFormatException ex) { return BadRequest(ex.Message); - } - - return Ok(); + } } @@ -145,7 +138,7 @@ namespace AsbCloudWebApi.Controllers idWell, token).ConfigureAwait(false)) return Forbid(); - var result = plannedTrajectoryService.GetCoordinatesAsync(idWell,token); + var result = plannedTrajectoryService.GetAsync(idWell,token); return Ok(result); }