Скорректированная версия

-добавлена миграция
-изменены методы
- добавлен CRUD
This commit is contained in:
eugeniy_ivanov 2022-12-22 18:08:58 +05:00
parent 7e9ec57e53
commit 169968da44
15 changed files with 7898 additions and 0 deletions

View File

@ -0,0 +1,99 @@
using System;
namespace AsbCloudApp.Data
{
#nullable enable
/// <summary>
/// Формирование данных по плановой траектории
/// </summary>
public class PlannedTrajectoryDto
{
/// <summary>
/// ИД скважины
/// </summary>
public int IdWell { get; set; }
/// <summary>
/// Дата загрузки
/// </summary>
public DateTimeOffset Date { get; set; }
/// <summary>
/// ИД пользователя
/// </summary>
public double IdUser { get; set; }
/// <summary>
/// Глубина по стволу
/// </summary>
public double? WellboreDepth { get; set; }
/// <summary>
/// Угол зенитный
/// </summary>
public double? ZenithAngle { get; set; }
/// <summary>
/// Азимут Географ.
/// </summary>
public double? AzimuthGeo { get; set; }
/// <summary>
/// Азимут Магнитный
/// </summary>
public double? AzimuthMagnetic { get; set; }
/// <summary>
/// Глубина вертикальная
/// </summary>
public double? VerticalDepth { get; set; }
/// <summary>
/// Абсолютная отметка
/// </summary>
public double? AbsoluteMark { get; set; }
/// <summary>
/// Север отн- но устья
/// </summary>
public double? NorthOrifice { get; set; }
/// <summary>
/// Восток отн- но устья
/// </summary>
public double? EastOrifice { get; set; }
/// <summary>
/// Восток картографический
/// </summary>
public double? EastCartographic { get; set; }
/// <summary>
/// Север картографический
/// </summary>
public double? NorthCartographic { get; set; }
/// <summary>
/// Пространственная интенсивность
/// </summary>
public double? SpatialIntensity { get; set; }
/// <summary>
/// Интенсивность по углу
/// </summary>
public double? AngleIntensity { get; set; }
/// <summary>
/// Интенсивность по азимуту
/// </summary>
public double? AzimuthIntensity { get; set; }
/// <summary>
/// Смещение от устья
/// </summary>
public double? OrificeOffset { get; set; }
/// <summary>
/// Комментарии
/// </summary>
public string? Comment { get; set; }
}
#nullable disable
}

View File

@ -0,0 +1,30 @@
using System.IO;
namespace AsbCloudApp.Services
{
/// <summary>
/// Сервис загрузки и обработки плановой траектории из файла
/// </summary>
public interface IPlannedTrajectoryImportService
{
/// <summary>
/// шаблон для заполнения плановой траектории
/// </summary>
/// <returns></returns>
Stream GetTemplateFile();
/// <summary>
/// загрузить строки плановой траектории в .xlsx
/// </summary>
/// <param name="idWell"></param>
/// <returns></returns>
Stream ExportRows(int idWell);
/// <summary>
/// закгрузить из excel координаты плановой траектории
/// </summary>
/// <param name="idWell"></param>
/// <param name="idUser"></param>
/// <param name="stream"></param>
/// <param name="deleteWellOperationsBeforeImport">Очистить старые перед импортом (если файл проходит валидацию)</param>
void Import(int idWell, int idUser, Stream stream, bool deleteWellOperationsBeforeImport = false);
}
}

View File

@ -0,0 +1,53 @@
using AsbCloudApp.Data;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Services
{
/// <summary>
/// CRUD для работы с плановой траекторией из клиента
/// </summary>
/// <returns></returns>
public interface IPlannedTrajectoryService
{
/// <summary>
/// Получить все добавленные по скважине координаты плановой траектории
/// </summary>
/// <param name="idWell"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<PlannedTrajectoryDto>> GetCoordinates(int idWell, CancellationToken token);
/// <summary>
/// Добавить строки с координатами
/// </summary>
/// <param name="idWell"></param>
/// <param name="idUser"></param>
/// <param name="plannedTrajectoryRows"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> AddAsync(int idWell, int idUser,
IEnumerable<PlannedTrajectoryDto> plannedTrajectoryRows, CancellationToken token);
/// <summary>
/// Обновить строку с координатами
/// </summary>
/// <param name="idWell"></param>
/// <param name="idUser"></param>
/// <param name="idRow"></param>
/// <param name="row"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> UpdateAsync(int idWell, int idUser, int idRow, PlannedTrajectoryDto row,
CancellationToken token);
/// <summary>
/// Удалить строку с координатами
/// </summary>
/// <param name="ids"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> DeleteAsync(IEnumerable<int> ids, CancellationToken token);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,73 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace AsbCloudDb.Migrations
{
public partial class AddTable_PlannedTrajectory : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "t_planned_trajectory",
columns: table => new
{
id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
id_user = table.Column<int>(type: "integer", nullable: false, comment: "ID пользователя который внес/изменил запись"),
id_well = table.Column<int>(type: "integer", nullable: false, comment: "ID скважины"),
load_date = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Дата загрузки траектории"),
wellbore_depth = table.Column<double>(type: "double precision", nullable: false, comment: "Глубина по стволу"),
zenith_angle = table.Column<double>(type: "double precision", nullable: false, comment: "Угол зенитный"),
azimuth_geo = table.Column<double>(type: "double precision", nullable: false, comment: "Азимут Географ."),
azimuth_magnetic = table.Column<double>(type: "double precision", nullable: false, comment: "Азимут Магнитный"),
vertical_depth = table.Column<double>(type: "double precision", nullable: false, comment: "Глубина вертикальная"),
absolute_mark = table.Column<double>(type: "double precision", nullable: false, comment: "Абсолютная отметка"),
north_orifice = table.Column<double>(type: "double precision", nullable: false, comment: "Север отн-но устья"),
east_orifice = table.Column<double>(type: "double precision", nullable: false, comment: "Восток отн-но устья"),
east_cartographic = table.Column<double>(type: "double precision", nullable: false, comment: "Восток картографический"),
north_cartographic = table.Column<double>(type: "double precision", nullable: false, comment: "Север картографический"),
spatial_intensity = table.Column<double>(type: "double precision", nullable: false, comment: "Пространственная интенсивность"),
angle_intensity = table.Column<double>(type: "double precision", nullable: false, comment: "Интенсивность по углу"),
azimuth_intensity = table.Column<double>(type: "double precision", nullable: false, comment: "Интенсивность по азимуту"),
orifice_offset = table.Column<double>(type: "double precision", nullable: false, comment: "Смещение от устья"),
comment = table.Column<string>(type: "text", nullable: true, comment: "Комментарии")
},
constraints: table =>
{
table.PrimaryKey("PK_t_planned_trajectory", x => x.id);
table.ForeignKey(
name: "FK_t_planned_trajectory_t_user_id_user",
column: x => x.id_user,
principalTable: "t_user",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_t_planned_trajectory_t_well_id_well",
column: x => x.id_well,
principalTable: "t_well",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
},
comment: "Загрузка плановой траектории");
migrationBuilder.CreateIndex(
name: "IX_t_planned_trajectory_id_user",
table: "t_planned_trajectory",
column: "id_user");
migrationBuilder.CreateIndex(
name: "IX_t_planned_trajectory_id_well",
table: "t_planned_trajectory",
column: "id_well");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "t_planned_trajectory");
}
}
}

View File

@ -1762,6 +1762,116 @@ namespace AsbCloudDb.Migrations
});
});
modelBuilder.Entity("AsbCloudDb.Model.PlannedTrajectory", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasColumnName("id");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<double>("AbsoluteMark")
.HasColumnType("double precision")
.HasColumnName("absolute_mark")
.HasComment("Абсолютная отметка");
b.Property<double>("AngleIntensity")
.HasColumnType("double precision")
.HasColumnName("angle_intensity")
.HasComment("Интенсивность по углу");
b.Property<double>("AzimuthGeo")
.HasColumnType("double precision")
.HasColumnName("azimuth_geo")
.HasComment("Азимут Географ.");
b.Property<double>("AzimuthIntensity")
.HasColumnType("double precision")
.HasColumnName("azimuth_intensity")
.HasComment("Интенсивность по азимуту");
b.Property<double>("AzimuthMagnetic")
.HasColumnType("double precision")
.HasColumnName("azimuth_magnetic")
.HasComment("Азимут Магнитный");
b.Property<string>("Comment")
.HasColumnType("text")
.HasColumnName("comment")
.HasComment("Комментарии");
b.Property<double>("EastCartographic")
.HasColumnType("double precision")
.HasColumnName("east_cartographic")
.HasComment("Восток картографический");
b.Property<double>("EastOrifice")
.HasColumnType("double precision")
.HasColumnName("east_orifice")
.HasComment("Восток отн-но устья");
b.Property<int>("IdUser")
.HasColumnType("integer")
.HasColumnName("id_user")
.HasComment("ID пользователя который внес/изменил запись");
b.Property<int>("IdWell")
.HasColumnType("integer")
.HasColumnName("id_well")
.HasComment("ID скважины");
b.Property<DateTimeOffset>("LoadDate")
.HasColumnType("timestamp with time zone")
.HasColumnName("load_date")
.HasComment("Дата загрузки траектории");
b.Property<double>("NorthCartographic")
.HasColumnType("double precision")
.HasColumnName("north_cartographic")
.HasComment("Север картографический");
b.Property<double>("NorthOrifice")
.HasColumnType("double precision")
.HasColumnName("north_orifice")
.HasComment("Север отн-но устья");
b.Property<double>("OrificeOffset")
.HasColumnType("double precision")
.HasColumnName("orifice_offset")
.HasComment("Смещение от устья");
b.Property<double>("SpatialIntensity")
.HasColumnType("double precision")
.HasColumnName("spatial_intensity")
.HasComment("Пространственная интенсивность");
b.Property<double>("VerticalDepth")
.HasColumnType("double precision")
.HasColumnName("vertical_depth")
.HasComment("Глубина вертикальная");
b.Property<double>("WellboreDepth")
.HasColumnType("double precision")
.HasColumnName("wellbore_depth")
.HasComment("Глубина по стволу");
b.Property<double>("ZenithAngle")
.HasColumnType("double precision")
.HasColumnName("zenith_angle")
.HasComment("Угол зенитный");
b.HasKey("Id");
b.HasIndex("IdUser");
b.HasIndex("IdWell");
b.ToTable("t_planned_trajectory");
b.HasComment("Загрузка плановой траектории");
});
modelBuilder.Entity("AsbCloudDb.Model.ProcessMap", b =>
{
b.Property<int>("Id")
@ -6144,6 +6254,25 @@ namespace AsbCloudDb.Migrations
b.Navigation("Well");
});
modelBuilder.Entity("AsbCloudDb.Model.PlannedTrajectory", b =>
{
b.HasOne("AsbCloudDb.Model.User", "User")
.WithMany()
.HasForeignKey("IdUser")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AsbCloudDb.Model.Well", "Well")
.WithMany()
.HasForeignKey("IdWell")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
b.Navigation("Well");
});
modelBuilder.Entity("AsbCloudDb.Model.ProcessMap", b =>
{
b.HasOne("AsbCloudDb.Model.Well", "Well")

View File

@ -13,6 +13,7 @@ namespace AsbCloudDb.Model
public virtual DbSet<DailyReport.DailyReport> DailyReports => Set <DailyReport.DailyReport >();
public virtual DbSet<Deposit> Deposits => Set<Deposit>();
public virtual DbSet<DetectedOperation> DetectedOperations => Set<DetectedOperation>();
public virtual DbSet<PlannedTrajectory> PlannedTrajectorys => Set<PlannedTrajectory>();
public virtual DbSet<ProcessMap> ProcessMap => Set<ProcessMap>();
public virtual DbSet<DrillingProgramPart> DrillingProgramParts => Set<DrillingProgramPart>();
public virtual DbSet<FileCategory> FileCategories => Set<FileCategory>();

View File

@ -15,6 +15,7 @@ namespace AsbCloudDb.Model
DbSet<DailyReport.DailyReport> DailyReports { get; }
DbSet<Deposit> Deposits { get; }
DbSet<DetectedOperation> DetectedOperations { get; }
DbSet<PlannedTrajectory> PlannedTrajectorys { get; }
DbSet<ProcessMap> ProcessMap { get; }
DbSet<DrillingProgramPart> DrillingProgramParts { get; }
DbSet<FileCategory> FileCategories { get; }

View File

@ -0,0 +1,75 @@
using Microsoft.EntityFrameworkCore;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace AsbCloudDb.Model
{
#nullable disable
[Table("t_planned_trajectory"), Comment("Загрузка плановой траектории")]
public class PlannedTrajectory : IId
{
[Column("id"), Key]
public int Id { get; set; }
[Column("id_user"), Comment("ID пользователя который внес/изменил запись")]
public int IdUser { get; set; }
[Column("id_well"), Comment("ID скважины")]
public int IdWell { get; set; }
[Column("load_date"), Comment("Дата загрузки траектории")]
public DateTimeOffset LoadDate { get; set; }
[Column("wellbore_depth"), Comment("Глубина по стволу")]
public double WellboreDepth { get; set; }
[Column("zenith_angle"), Comment("Угол зенитный")]
public double ZenithAngle { get; set; }
[Column("azimuth_geo"), Comment("Азимут Географ.")]
public double AzimuthGeo { get; set; }
[Column("azimuth_magnetic"), Comment("Азимут Магнитный")]
public double AzimuthMagnetic { get; set; }
[Column("vertical_depth"), Comment("Глубина вертикальная")]
public double VerticalDepth { get; set; }
[Column("absolute_mark"), Comment("Абсолютная отметка")]
public double AbsoluteMark { get; set; }
[Column("north_orifice"), Comment("Север отн-но устья")]
public double NorthOrifice { get; set; }
[Column("east_orifice"), Comment("Восток отн-но устья")]
public double EastOrifice { get; set; }
[Column("east_cartographic"), Comment("Восток картографический")]
public double EastCartographic { get; set; }
[Column("north_cartographic"), Comment("Север картографический")]
public double NorthCartographic { get; set; }
[Column("spatial_intensity"), Comment("Пространственная интенсивность")]
public double SpatialIntensity { get; set; }
[Column("angle_intensity"), Comment("Интенсивность по углу")]
public double AngleIntensity { get; set; }
[Column("azimuth_intensity"), Comment("Интенсивность по азимуту")]
public double AzimuthIntensity { get; set; }
[Column("orifice_offset"), Comment("Смещение от устья")]
public double OrificeOffset { get; set; }
[Column("comment"), Comment("Комментарии")]
public string Comment { get; set; }
[ForeignKey(nameof(IdWell))]
public virtual Well Well { get; set; }
[ForeignKey(nameof(IdUser))]
public virtual User User { get; set; }
}
}

View File

@ -12,6 +12,7 @@
<None Remove="CommonLibs\logo_720x404.png" />
<None Remove="CommonLibs\Readme.md" />
<None Remove="Services\DailyReport\DailyReportTemplate.xlsx" />
<None Remove="Services\PlannedTrajectoryService\PlannedTrajectoryTemplate.xlsx" />
<None Remove="Services\WellOperationService\ScheduleReportTemplate.xlsx" />
<None Remove="Services\WellOperationService\WellOperationImportTemplate.xlsx" />
<None Remove="Services\DailyReport\DailyReportBlocks\" />
@ -28,6 +29,7 @@
<ItemGroup>
<EmbeddedResource Include="Services\DailyReport\DailyReportTemplate.xlsx" />
<EmbeddedResource Include="Services\PlannedTrajectoryService\PlannedTrajectoryTemplate.xlsx" />
<EmbeddedResource Include="Services\WellOperationService\ScheduleReportTemplate.xlsx" />
<EmbeddedResource Include="Services\WellOperationService\WellOperationImportTemplate.xlsx" />
</ItemGroup>

View File

@ -12,6 +12,7 @@ using AsbCloudInfrastructure.Services;
using AsbCloudInfrastructure.Services.DailyReport;
using AsbCloudInfrastructure.Services.DetectOperations;
using AsbCloudInfrastructure.Services.DrillingProgram;
using AsbCloudInfrastructure.Services.PlannedTrajectory;
using AsbCloudInfrastructure.Services.SAUB;
using AsbCloudInfrastructure.Services.Subsystems;
using AsbCloudInfrastructure.Services.WellOperationService;
@ -124,6 +125,8 @@ namespace AsbCloudInfrastructure
services.AddTransient<IWellService, WellService>();
services.AddTransient<IWellOperationImportService, WellOperationImportService>();
services.AddTransient<IWellOperationService, WellOperationService>();
services.AddTransient<IPlannedTrajectoryImportService, PlannedTrajectoryImportService>();
services.AddTransient<IPlannedTrajectoryService, PlannedTrajectoryService>();
services.AddTransient<IScheduleReportService, ScheduleReportService>();
services.AddTransient<IDailyReportService, DailyReportService>();
services.AddTransient<IDetectedOperationService, DetectedOperationService>();

View File

@ -0,0 +1,256 @@
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;
namespace AsbCloudInfrastructure.Services.PlannedTrajectory
{
public class PlannedTrajectoryImportService : IPlannedTrajectoryImportService
{
/*
* password for PlannedTrajectoryTemplate.xlsx is Drill2022
*/
private readonly IAsbCloudDbContext db;
private readonly IWellService wellService;
private const string sheetNamePlannedTrajectory = "Плановая траектория";
private const int headerRowsCount = 2;
private const int ColumnWellboreDepth = 1;
private const int ColumnZenithAngle = 2;
private const int ColumnAzimuthGeo = 3;
private const int ColumnAzimuthMagnetic = 4;
private const int ColumnVerticalDepth = 5;
private const int ColumnAbsoluteMark = 6;
private const int ColumnNorthOrifice = 7;
private const int ColumnEastOrifice = 8;
private const int ColumnEastCartographic = 9;
private const int ColumnNorthCartographic = 10;
private const int ColumnSpatialIntensity = 11;
private const int ColumnAngleIntensity = 12;
private const int ColumnAzimuthIntensity = 13;
private const int ColumnOrificeOffset = 14;
private const int ColumnComment = 15;
public PlannedTrajectoryImportService(IAsbCloudDbContext db, IWellService wellService)
{
this.db = db;
this.wellService = wellService;
}
public Stream GetTemplateFile()
{
var stream = System.Reflection.Assembly.GetExecutingAssembly()
.GetManifestResourceStream("AsbCloudInfrastructure.Services.PlannedTrajectoryService.PlannedTrajectoryTemplate.xlsx");
return stream;
}
public Stream ExportRows(int idWell)
{
var plannedTrajectorys = db.PlannedTrajectorys
.Where(o => o.IdWell == idWell)
.AsNoTracking()
.ToList();
if (!plannedTrajectorys.Any())
return null;
var timezone = wellService.GetTimezone(idWell);
return MakeExelFileStream(plannedTrajectorys);
}
private Stream MakeExelFileStream(IEnumerable<AsbCloudDb.Model.PlannedTrajectory> plannedTrajectories)
{
using Stream ecxelTemplateStream = GetTemplateFile();
using var workbook = new XLWorkbook(ecxelTemplateStream, XLEventTracking.Disabled);
AddOperationsToWorkbook(workbook, plannedTrajectories);
MemoryStream memoryStream = new MemoryStream();
workbook.SaveAs(memoryStream, new SaveOptions { });
memoryStream.Seek(0, SeekOrigin.Begin);
return memoryStream;
}
private static void AddOperationsToWorkbook(XLWorkbook workbook, IEnumerable<AsbCloudDb.Model.PlannedTrajectory> plannedTrajectories)
{
if (plannedTrajectories.Any())
{
var sheet = workbook.Worksheets.FirstOrDefault(ws => ws.Name == sheetNamePlannedTrajectory);
AddOperationsToSheet(sheet, plannedTrajectories);
}
}
private static void AddOperationsToSheet(IXLWorksheet sheet, IEnumerable<AsbCloudDb.Model.PlannedTrajectory> plannedTrajectories)
{
var operationsList = plannedTrajectories.ToList();
for (int i = 0; i < operationsList.Count; i++)
{
var row = sheet.Row(1 + i + headerRowsCount);
AddOperationToRow(row, operationsList[i]);
}
}
private static void AddOperationToRow(IXLRow row, AsbCloudDb.Model.PlannedTrajectory trajectory)
{
row.Cell(ColumnWellboreDepth).Value = trajectory.WellboreDepth;
row.Cell(ColumnZenithAngle).Value = trajectory.ZenithAngle;
row.Cell(ColumnAzimuthGeo).Value = trajectory.AzimuthGeo;
row.Cell(ColumnAzimuthMagnetic).Value = trajectory.AzimuthMagnetic;
row.Cell(ColumnVerticalDepth).Value = trajectory.VerticalDepth;
row.Cell(ColumnAbsoluteMark).Value = trajectory.AbsoluteMark;
row.Cell(ColumnNorthOrifice).Value = trajectory.NorthOrifice;
row.Cell(ColumnEastOrifice).Value = trajectory.EastOrifice;
row.Cell(ColumnEastCartographic).Value = trajectory.EastCartographic;
row.Cell(ColumnNorthCartographic).Value = trajectory.NorthCartographic;
row.Cell(ColumnSpatialIntensity).Value = trajectory.SpatialIntensity;
row.Cell(ColumnAngleIntensity).Value = trajectory.AngleIntensity;
row.Cell(ColumnAzimuthIntensity).Value = trajectory.AzimuthIntensity;
row.Cell(ColumnOrificeOffset).Value = trajectory.OrificeOffset;
row.Cell(ColumnComment).Value = trajectory.Comment;
}
public void Import(int idWell, int idUser, Stream stream, 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);
}
private void SaveOperations(int idWell, int idUser, IEnumerable<PlannedTrajectoryDto> newRows, bool deletePrevRow = false)
{
var timezone = wellService.GetTimezone(idWell);
var transaction = db.Database.BeginTransaction();
try
{
if (deletePrevRow)
db.WellOperations.RemoveRange(db.WellOperations.Where(o => o.IdWell == idWell));
var entities = newRows.Select(o =>
{
var entity = o.Adapt<AsbCloudDb.Model.PlannedTrajectory>();
entity.IdWell = idWell;
entity.LoadDate = DateTime.Today.ToUtcDateTimeOffset(timezone.Hours);
entity.IdUser = idUser;
return entity;
});
db.PlannedTrajectorys.AddRange(entities);
db.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
private IEnumerable<PlannedTrajectoryDto> ParseFileStream(Stream stream)
{
using var workbook = new XLWorkbook(stream, XLEventTracking.Disabled);
return ParseWorkbook(workbook);
}
private IEnumerable<PlannedTrajectoryDto> ParseWorkbook(IXLWorkbook workbook)
{
var sheetPlannedTrajectory = workbook.Worksheets.FirstOrDefault(ws => ws.Name == sheetNamePlannedTrajectory);
if (sheetPlannedTrajectory is null)
throw new FileFormatException($"Книга excel не содержит листа {sheetNamePlannedTrajectory}.");
var plannedTrajectoryRows = ParseSheet(sheetPlannedTrajectory);
return plannedTrajectoryRows;
}
private IEnumerable<PlannedTrajectoryDto> ParseSheet(IXLWorksheet sheet)
{
if (sheet.RangeUsed().RangeAddress.LastAddress.ColumnNumber < 15)
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<PlannedTrajectoryDto>(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);
}
};
return trajectoryRows;
}
private PlannedTrajectoryDto ParseRow(IXLRow row)
{
var _wellboreDepth = row.Cell(ColumnWellboreDepth).Value;
var _zenithAngle = row.Cell(ColumnZenithAngle).Value;
var _azimuthGeo = row.Cell(ColumnAzimuthGeo).Value;
var _azimuthMagnetic = row.Cell(ColumnAzimuthMagnetic).Value;
var _verticalDepth = row.Cell(ColumnVerticalDepth).Value;
var _absoluteMark = row.Cell(ColumnAbsoluteMark).Value;
var _northOrifice = row.Cell(ColumnNorthOrifice).Value;
var _eastOrifice = row.Cell(ColumnEastOrifice).Value;
var _eastCartographic = row.Cell(ColumnEastCartographic).Value;
var _northCartographic = row.Cell(ColumnNorthCartographic).Value;
var _spatialIntensity = row.Cell(ColumnSpatialIntensity).Value;
var _angleIntensity = row.Cell(ColumnAngleIntensity).Value;
var _azimuthIntensity = row.Cell(ColumnAzimuthIntensity).Value;
var _orificeOffset = row.Cell(ColumnOrificeOffset).Value;
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}");
if (value is double _value)
return _value;
return null;
}
trajectoryRow.WellboreDepth = getDoubleValue(_wellboreDepth, "Глубина по стволу", row);
trajectoryRow.ZenithAngle = getDoubleValue(_zenithAngle, "Зенитный угол", row);
trajectoryRow.AzimuthGeo = getDoubleValue(_azimuthGeo, "Азимут географический", row);
trajectoryRow.AzimuthMagnetic = getDoubleValue(_azimuthMagnetic, "Азимут магнитный", row);
trajectoryRow.VerticalDepth = getDoubleValue(_verticalDepth, "Глубина вертикальная", row);
trajectoryRow.AbsoluteMark = getDoubleValue(_absoluteMark, "Абсолютная отметка", row);
trajectoryRow.NorthOrifice = getDoubleValue(_northOrifice, "Север относительно устья", row);
trajectoryRow.EastOrifice = getDoubleValue(_eastOrifice, "Восток относительно устья", row);
trajectoryRow.EastCartographic = getDoubleValue(_eastCartographic, "Восток картографический", row);
trajectoryRow.NorthCartographic = getDoubleValue(_northCartographic, "Север картографический", row);
trajectoryRow.SpatialIntensity = getDoubleValue(_spatialIntensity, "Простр. интенсивность", row);
trajectoryRow.AngleIntensity = getDoubleValue(_angleIntensity, "Интенсивность по углу", row);
trajectoryRow.AzimuthIntensity = getDoubleValue(_azimuthIntensity, "Интенсивность по азимуту", row);
trajectoryRow.OrificeOffset = getDoubleValue(_orificeOffset, "Смещение от устья", row);
if (_comment is not null)
trajectoryRow.Comment = _comment.ToString();
return trajectoryRow;
}
}
}

View File

@ -0,0 +1,84 @@
using AsbCloudApp.Data;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services.PlannedTrajectory
{
#nullable enable
public class PlannedTrajectoryService : IPlannedTrajectoryService
{
private readonly IAsbCloudDbContext db;
private readonly IWellService wellService;
public PlannedTrajectoryService(IAsbCloudDbContext db, IWellService wellService)
{
this.db = db;
this.wellService = wellService;
}
public async Task<int> AddAsync(int idWell, int idUser,IEnumerable<PlannedTrajectoryDto> plannedTrajectoryRows, CancellationToken token)
{
var timezone = wellService.GetTimezone(idWell);
foreach (var dto in plannedTrajectoryRows)
{
var entity = dto.Adapt<AsbCloudDb.Model.PlannedTrajectory>();
entity.IdWell = idWell;
entity.Id = default;
entity.LoadDate = DateTime.Today.ToUtcDateTimeOffset(timezone.Hours);
entity.IdUser = idUser;
db.PlannedTrajectorys.Add(entity);
}
return await db.SaveChangesAsync(token)
.ConfigureAwait(false);
}
public async Task<int> DeleteAsync(IEnumerable<int> ids, CancellationToken token)
{
var query = db.PlannedTrajectorys.Where(e => ids.Contains(e.Id));
db.PlannedTrajectorys.RemoveRange(query);
return await db.SaveChangesAsync(token)
.ConfigureAwait(false);
}
public async Task<IEnumerable<PlannedTrajectoryDto>?> GetCoordinates(int idWell, CancellationToken token)
{
var well = wellService.GetOrDefault(idWell);
if (well is null || well.Timezone is null)
throw new ArgumentInvalidException("idWell doesn`t exist", nameof(idWell));
var query = db.PlannedTrajectorys
.Where(x => x.IdWell == idWell);
var entities = await query
.OrderBy(e => e.LoadDate)
.ToListAsync(token);
var result = entities
.Select(r => Convert(r));
return result;
}
public async Task<int> UpdateAsync(int idWell, int idUser, int idRow, PlannedTrajectoryDto row, CancellationToken token)
{
var timezone = wellService.GetTimezone(idWell);
var entity = row.Adapt<AsbCloudDb.Model.PlannedTrajectory>();
entity.IdWell = idWell;
entity.Id = idUser;
entity.LoadDate = DateTime.Today.ToUtcDateTimeOffset(timezone.Hours);
entity.IdUser = idUser;
db.PlannedTrajectorys.Update(entity);
return await db.SaveChangesAsync(token)
.ConfigureAwait(false);
}
private static PlannedTrajectoryDto Convert(AsbCloudDb.Model.PlannedTrajectory entity)
{
var dto = entity.Adapt<PlannedTrajectoryDto>();
return dto;
}
}
#nullable disable
}

View File

@ -0,0 +1,225 @@
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers
{
#nullable enable
/// <summary>
/// Плановая траектория (загрузка и хранение)
/// </summary>
[Route("api/well/{idWell}/plannedTrajectory")]
[ApiController]
[Authorize]
public class PlannedTrajectoryController : ControllerBase
{
private readonly IWellService wellService;
private readonly IPlannedTrajectoryImportService plannedTrajectoryImportService;
private readonly IPlannedTrajectoryService plannedTrajectoryService;
public PlannedTrajectoryController(IWellService wellService, IPlannedTrajectoryImportService plannedTrajectoryImportService, IPlannedTrajectoryService plannedTrajectoryService)
{
this.plannedTrajectoryImportService = plannedTrajectoryImportService;
this.wellService = wellService;
this.plannedTrajectoryService = plannedTrajectoryService;
}
// ---------FROM FILE-----------
/// <summary>
/// Возвращает шаблон для заполнения строк плановой траектории
/// </summary>
/// <returns>Запрашиваемый файл</returns>
[HttpGet]
[Route("template")]
[AllowAnonymous]
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
public IActionResult GetTamplate()
{
var stream = plannedTrajectoryImportService.GetTemplateFile();
var fileName = "ЕЦП_шаблон_файла_плановая_траектория.xlsx";
return File(stream, "application/octet-stream", fileName);
}
/// <summary>
/// Формируем excel файл с текущими строками плановой траектории
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>Запрашиваемый файл</returns>
[HttpGet]
[Route("export")]
[Permission]
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> ExportAsync([FromRoute] int idWell, CancellationToken token = default)
{
int? idCompany = User.GetCompanyId();
if (idCompany is null)
return Forbid();
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false))
return Forbid();
var stream = plannedTrajectoryImportService.ExportRows(idWell);
var fileName = await wellService.GetWellCaptionByIdAsync(idWell, token) + "_plannedTrajectory.xlsx";
return File(stream, "application/octet-stream", fileName);
}
/// <summary>
/// Импортирует координаты из excel (xlsx) файла
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="files">Коллекция из одного файла xlsx</param>
/// <param name="options">Удалить операции перед импортом = 1, если фал валидный</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns></returns>
[HttpPost]
//[Permission]
[Route("import/{options}")]
public async Task<IActionResult> ImportAsync(int idWell,
[FromForm] IFormFileCollection files,
int options = 0,
CancellationToken token = default)
{
int? idCompany = User.GetCompanyId();
int? idUser = User.GetUserId();
if (!idUser.HasValue)
return Forbid();
if (idCompany is null || idUser is null)
return Forbid();
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false))
return Forbid();
if (files.Count < 1)
return BadRequest("нет файла");
var file = files[0];
if (Path.GetExtension(file.FileName).ToLower() != ".xlsx")
return BadRequest("Требуется xlsx файл.");
using Stream stream = file.OpenReadStream();
try
{
plannedTrajectoryImportService.Import(idWell, idUser.Value, stream, (options & 1) > 0);
}
catch (FileFormatException ex)
{
return BadRequest(ex.Message);
}
return Ok();
}
//-------------MANUAL---------------
// !!! методы не реализованы в сервисе, в контроллере заглушка !!!
/// <summary>
/// Получаем список всех строк координат плановой траектории (для клиента)
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>Запрашиваемый файл</returns>
[HttpGet]
[Route("allRows")]
[Permission]
[ProducesResponseType(typeof(IEnumerable<PlannedTrajectoryDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetRows([FromRoute] int idWell, CancellationToken token = default)
{
int? idCompany = User.GetCompanyId();
if (idCompany is null)
return Forbid();
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false))
return Forbid();
var result = plannedTrajectoryService.GetCoordinates(idWell,token);
return Ok(result);
}
/// <summary>
/// Добавить новые координаты для плановой траектории
/// </summary>
/// <param name="idWell"></param>
/// <param name="row"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpPost]
[Permission]
[ProducesResponseType(typeof(PlannedTrajectoryDto), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> AddRowAsync(int idWell, [FromBody] PlannedTrajectoryDto row,
CancellationToken token = default)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
var result = row;
return Ok(result);
}
/// <summary>
/// Изменить выбранную строку с координатами
/// </summary>
/// <param name="idWell"></param>
/// <param name="idRow"></param>
/// <param name="row"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpPut("{idRow}")]
[Permission]
[ProducesResponseType(typeof(PlannedTrajectoryDto), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> UpdateRowAsync(int idWell, int idRow,
[FromBody] PlannedTrajectoryDto row, CancellationToken token = default)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
int? idUser = User.GetUserId();
if (!idUser.HasValue)
return Forbid();
var result = await plannedTrajectoryService.UpdateAsync(idWell, idUser.Value, idRow, row, token)
.ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Удалить выбранную строку с координатами
/// </summary>
/// <param name="idWell"></param>
/// <param name="idRow"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpDelete("{idOperation}")]
[Permission]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> DeleteRowAsync(int idWell, int idRow, CancellationToken token = default)
{
if (!await CanUserAccessToWellAsync(idWell,
token).ConfigureAwait(false))
return Forbid();
var result = await plannedTrajectoryService.DeleteAsync(new int[] { idRow }, token)
.ConfigureAwait(false);
return Ok(result);
}
private async Task<bool> CanUserAccessToWellAsync(int idWell, CancellationToken token = default)
{
int? idCompany = User.GetCompanyId();
return idCompany is not null && await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false);
}
}
}