Merge branch 'DailyReport' into dev

This commit is contained in:
ngfrolov 2022-05-05 10:09:47 +05:00
commit 7112ebc4f2
17 changed files with 6977 additions and 27 deletions

View File

@ -0,0 +1,216 @@
using System;
using System.Collections.Generic;
namespace AsbCloudApp.Data
{
/// <summary>
/// Параметры для формирования суточного рапорта
/// </summary>
public class DailyReportDto
{
/// <summary>
/// название скважины
/// </summary>
public string WellName { get; set; }
/// <summary>
/// название куста
/// </summary>
public string ClusterName { get; set; }
/// <summary>
/// заказчик
/// </summary>
public string Customer { get; set; }
/// <summary>
/// подрядчик
/// </summary>
public string Contractor { get; set; }
/// <summary>
/// дата рапорта
/// </summary>
public DateTime ReportDate { get; set; }
/// <summary>
/// глубина забоя на дату начала интервала
/// </summary>
public double? WellDepthIntervalStartDate { get; set; }
/// <summary>
/// глубина забоя на дату окончания интервала
/// </summary>
public double? WellDepthIntervalFinishDate { get; set; }
/// <summary>
/// Глубина забоя по стволу на окончание отчетного периода
/// </summary>
public double? BottomholeDepth { get; set; }
/// <summary>
/// Глубина забоя по вертикали на дату окончания отчетного периода
/// </summary>
public double? VerticalDepth { get; set; }
/// <summary>
/// Зенитный угол на дату окончания отчетного периода
/// </summary>
public double? ZenithAngle { get; set; }
/// <summary>
/// Азимутальный угол на дату окончания отчетного периода
/// </summary>
public double? AzimuthAngle { get; set; }
/// <summary>
/// ФИО бурильщиков
/// </summary>
public string FirstDriller { get; set; }
/// <summary>
/// ФИО бурильщиков
/// </summary>
public string SecondDriller { get; set; }
/// <summary>
/// Время работы АПД
/// </summary>
public double? WorkTimeSAUB { get; set; }
/// <summary>
/// Время работы спин мастер
/// </summary>
public double? WorkTimeSpinMaster { get; set; }
/// <summary>
/// Время работы torqueMaster
/// </summary>
public double? WorkTimeTorkMaster { get; set; }
/// <summary>
/// количество метров пробуренных с включенным АПД
/// </summary>
public double? PenetrationSAUB { get; set; }
/// <summary>
/// количество метров пробуренных с включенным Спин мастер
/// </summary>
public double? PenetrationSpinMaster { get; set; }
/// <summary>
/// количество метров пробуренных с включенным torqueMaster
/// </summary>
public double? PenetrationTorkMaster { get; set; }
/// <summary>
/// Количество запусков МСЕ
/// </summary>
public int CountLaunchesMSE { get; set; }
/// <summary>
/// КНБК описание
/// </summary>
public string BHADescription { get; set; }
/// <summary>
/// Нормативное время на одну операцию по подготовке ствола скважины к наращиванию
/// </summary>
public double? StandardTimeBarrelPreparation { get; set; }
/// <summary>
/// Нормативное время на одну операцию по наращиванию
/// </summary>
public double? StandardTimeExtension { get; set; }
/// <summary>
/// Фактическое время проработок при подготовке ствола скважины к наращиванию.
/// </summary>
public double? ActualTimeBarrelPreparation { get; set; }
/// <summary>
/// Фактическое время наращиваний
/// </summary>
public double? ActualTimeExtension { get; set; }
/// <summary>
/// Режимы бурения в роторе
/// </summary>
public IEnumerable<string> RotorDrillingModes { get; set; }
/// <summary>
/// режимы бурения в слайде
/// </summary>
public IEnumerable<string> SlideDrillingModes { get; set; }
/// <summary>
/// Количество метров пробуренных в роторе за отчетный период
/// </summary>
public double? PenetrationInRotor { get; set; }
/// <summary>
/// Количество часов бурения в роторе за отчетный период
/// </summary>
public double? NumberDrillingHours { get; set; }
/// <summary>
/// средний диф перепад в роторе за отчетный период
/// </summary>
public double? AVGDiffDropRotor { get; set; }
/// <summary>
/// количество метров пробуренных в слайде за отчетный период
/// </summary>
public double? PenetrationInSlide { get; set; }
/// <summary>
/// время бурения в роторе за отчетный период
/// </summary>
public double? DrillingTimeInRotor { get; set; }
/// <summary>
/// средний диф. перепад в слайде за отчетный период
/// </summary>
public double? AVGDiffPressureSlide { get; set; }
/// <summary>
/// Плановая МСП за секцию
/// </summary>
public double? SectionROPPlan { get; set; }
/// <summary>
/// Общее время бурения за секцию
/// </summary>
public double? SectionDrillingTimeTotal { get; set; }
/// <summary>
/// Общая проходка за секцию
/// </summary>
public double? SectionPenetrationTotal { get; set; }
/// <summary>
/// Количество наращиваний за отчетный период
/// </summary>
public int ExtensionsCount { get; set; }
/// <summary>
/// Отклонение относительно ГГД
/// </summary>
public double? DeviationFromTVD { get; set; }
/// <summary>
/// указываются все причины, которые влияют на снижение МСП.
/// </summary>
public string DeclinesReasonsROP { get; set; }
/// <summary>
/// ФИО Мастера буровой
/// </summary>
public string DrillingMaster { get; set; }
/// <summary>
/// ФИО супервайзера
/// </summary>
public string Supervisor { get; set; }
}
}

View File

@ -0,0 +1,18 @@
using AsbCloudApp.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Services
{
public interface IDailyReportService
{
Task<IEnumerable<DailyReportDto>> GetListAsync(int idWell, DateTime? v1, DateTime? v2, CancellationToken cancellationToken);
Task<DailyReportDto> GetOrGenerateAsync(int idWell, DateTime date, CancellationToken token);
Task<int> AddAsync(int idWell, DailyReportDto dto, CancellationToken token = default);
Task<int> UpdateAsync(int idWell, DateTime date, DailyReportDto dto, CancellationToken token = default);
Task<Stream> MakeReportAsync(int idWell, DateTime date, CancellationToken token = default);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,40 @@
using System;
using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AsbCloudDb.Migrations
{
public partial class Add_DailyReport_Table : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "t_daily_report",
columns: table => new
{
id_well = table.Column<int>(type: "integer", nullable: false, comment: "ID скважины"),
start_date = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Дата отчёта"),
info = table.Column<DailyReportInfo>(type: "jsonb", nullable: true, comment: "Список параметров для отчёта")
},
constraints: table =>
{
table.PrimaryKey("t_id_well_date_start_pk", x => new { x.id_well, x.start_date });
table.ForeignKey(
name: "FK_t_daily_report_t_well_id_well",
column: x => x.id_well,
principalTable: "t_well",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
},
comment: "Ежедневные отчёты");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "t_daily_report");
}
}
}

View File

@ -137,6 +137,31 @@ namespace AsbCloudDb.Migrations
});
});
modelBuilder.Entity("AsbCloudDb.Model.DailyReport", b =>
{
b.Property<int>("IdWell")
.HasColumnType("integer")
.HasColumnName("id_well")
.HasComment("ID скважины");
b.Property<DateTimeOffset>("StartDate")
.HasColumnType("timestamp with time zone")
.HasColumnName("start_date")
.HasComment("Дата отчёта");
b.Property<DailyReportInfo>("Info")
.HasColumnType("jsonb")
.HasColumnName("info")
.HasComment("Список параметров для отчёта");
b.HasKey("IdWell", "StartDate")
.HasName("t_id_well_date_start_pk");
b.ToTable("t_daily_report");
b.HasComment("Ежедневные отчёты");
});
modelBuilder.Entity("AsbCloudDb.Model.Deposit", b =>
{
b.Property<int>("Id")
@ -5142,6 +5167,17 @@ namespace AsbCloudDb.Migrations
b.Navigation("CompanyType");
});
modelBuilder.Entity("AsbCloudDb.Model.DailyReport", b =>
{
b.HasOne("AsbCloudDb.Model.Well", "Well")
.WithMany()
.HasForeignKey("IdWell")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Well");
});
modelBuilder.Entity("AsbCloudDb.Model.DrillFlowChart", b =>
{
b.HasOne("AsbCloudDb.Model.Well", "Well")

View File

@ -43,6 +43,7 @@ namespace AsbCloudDb.Model
public virtual DbSet<RelationUserRolePermission> RelationUserRolePermissions { get; set; }
public virtual DbSet<RelationUserRoleUserRole> RelationUserRoleUserRoles { get; set; }
public virtual DbSet<RelationUserDrillingProgramPart> RelationDrillingProgramPartUsers { get; set; }
public virtual DbSet<DailyReport> DailyReports { get; set; }
// WITS
public DbSet<WITS.Record1> Record1 { get; set; }
@ -299,6 +300,12 @@ namespace AsbCloudDb.Model
.IsRequired();
});
modelBuilder.Entity<DailyReport>(entity =>
{
entity.HasKey(e => new { e.IdWell, e.StartDate })
.HasName("t_id_well_date_start_pk");
});
FillData(modelBuilder);
}

View File

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json.Serialization;
namespace AsbCloudDb.Model
{
[Table("t_daily_report"), Comment("Ежедневные отчёты")]
public class DailyReport
{
[Column("id_well"), Comment("ID скважины")]
public int IdWell { get; set; }
[Column("start_date", TypeName = "timestamp with time zone"), Comment("Дата отчёта")]
public DateTimeOffset StartDate { get; set; }
[Column("info", TypeName = "jsonb"), Comment("Список параметров для отчёта")]
public DailyReportInfo Info { get; set; }
[ForeignKey(nameof(IdWell))]
public virtual Well Well { get; set; }
}
}

View File

@ -0,0 +1,213 @@
using System;
using System.Collections.Generic;
namespace AsbCloudDb.Model
{
public class DailyReportInfo
{
/// <summary>
/// название скважины
/// </summary>
public string WellName { get; set; }
/// <summary>
/// название куста
/// </summary>
public string ClusterName { get; set; }
/// <summary>
/// заказчик
/// </summary>
public string Customer { get; set; }
/// <summary>
/// подрядчик
/// </summary>
public string Contractor { get; set; }
/// <summary>
/// дата рапорта
/// </summary>
public DateTimeOffset ReportDate { get; set; }
/// <summary>
/// глубина забоя на дату начала интервала
/// </summary>
public double? WellDepthIntervalStartDate { get; set; }
/// <summary>
/// глубина забоя на дату окончания интервала
/// </summary>
public double? WellDepthIntervalFinishDate { get; set; }
/// <summary>
/// Глубина забоя по стволу на окончание отчетного периода
/// </summary>
public double? BottomholeDepth { get; set; }
/// <summary>
/// Глубина забоя по вертикали на дату окончания отчетного периода
/// </summary>
public double? VerticalDepth { get; set; }
/// <summary>
/// Зенитный угол на дату окончания отчетного периода
/// </summary>
public double? ZenithAngle { get; set; }
/// <summary>
/// Азимутальный угол на дату окончания отчетного периода
/// </summary>
public double? AzimuthAngle { get; set; }
/// <summary>
/// ФИО бурильщиков
/// </summary>
public string FirstDriller { get; set; }
/// <summary>
/// ФИО бурильщиков
/// </summary>
public string SecondDriller { get; set; }
/// <summary>
/// Время работы АПД
/// </summary>
public double? WorkTimeSAUB { get; set; }
/// <summary>
/// Время работы спин мастер
/// </summary>
public double? WorkTimeSpinMaster { get; set; }
/// <summary>
/// Время работы torqueMaster
/// </summary>
public double? WorkTimeTorkMaster { get; set; }
/// <summary>
/// количество метров пробуренных с включенным АПД
/// </summary>
public double? PenetrationSAUB { get; set; }
/// <summary>
/// количество метров пробуренных с включенным Спин мастер
/// </summary>
public double? PenetrationSpinMaster { get; set; }
/// <summary>
/// количество метров пробуренных с включенным torqueMaster
/// </summary>
public double? PenetrationTorkMaster { get; set; }
/// <summary>
/// Количество запусков МСЕ
/// </summary>
public int CountLaunchesMSE { get; set; }
/// <summary>
/// КНБК описание
/// </summary>
public string BHADescription { get; set; }
/// <summary>
/// Нормативное время на одну операцию по подготовке ствола скважины к наращиванию
/// </summary>
public double? StandardTimeBarrelPreparation { get; set; }
/// <summary>
/// Нормативное время на одну операцию по наращиванию
/// </summary>
public double? StandardTimeExtension { get; set; }
/// <summary>
/// Фактическое время проработок при подготовке ствола скважины к наращиванию.
/// </summary>
public double? ActualTimeBarrelPreparation { get; set; }
/// <summary>
/// Фактическое время наращиваний
/// </summary>
public double? ActualTimeExtension { get; set; }
/// <summary>
/// Режимы бурения в роторе
/// </summary>
public IEnumerable<string> RotorDrillingModes { get; set; }
/// <summary>
/// режимы бурения в слайде
/// </summary>
public IEnumerable<string> SlideDrillingModes { get; set; }
/// <summary>
/// Количество метров пробуренных в роторе за отчетный период
/// </summary>
public double? PenetrationInRotor { get; set; }
/// <summary>
/// Количество часов бурения в роторе за отчетный период
/// </summary>
public double? NumberDrillingHours { get; set; }
/// <summary>
/// средний диф перепад в роторе за отчетный период
/// </summary>
public double? AVGDiffDropRotor { get; set; }
/// <summary>
/// количество метров пробуренных в слайде за отчетный период
/// </summary>
public double? PenetrationInSlide { get; set; }
/// <summary>
/// время бурения в роторе за отчетный период
/// </summary>
public double? DrillingTimeInRotor { get; set; }
/// <summary>
/// средний диф перепад в слайде за отчетный период
/// </summary>
public double? AVGDiffPressureSlide { get; set; }
/// <summary>
/// Плановая МСП за секцию
/// </summary>
public double? SectionROPPlan { get; set; }
/// <summary>
/// Общее время бурения за секцию
/// </summary>
public double? SectionDrillingTimeTotal { get; set; }
/// <summary>
/// Общая проходка за секцию
/// </summary>
public double? SectionPenetrationTotal { get; set; }
/// <summary>
/// Количество наращиваний за отчетный период
/// </summary>
public int ExtensionsCount { get; set; }
/// <summary>
/// Отклонение относительно ГГД
/// </summary>
public double? DeviationFromTVD { get; set; }
/// <summary>
/// указываются все причины, которые влияют на снижение МСП.
/// </summary>
public string DeclinesReasonsROP { get; set; }
/// <summary>
/// ФИО Мастера буровой
/// </summary>
public string DrillingMaster { get; set; }
/// <summary>
/// ФИО супервайзера
/// </summary>
public string Supervisor { get; set; }
}
}

View File

@ -10,45 +10,43 @@ namespace AsbCloudDb.Model
{
DbSet<Cluster> Clusters { get; set; }
DbSet<Company> Companies { get; set; }
DbSet<TelemetryDataSaub> TelemetryDataSaub { get; set; }
DbSet<DailyReport> DailyReports { get; set; }
DbSet<Deposit> Deposits { get; set; }
DbSet<TelemetryEvent> TelemetryEvents { get; set; }
DbSet<TelemetryMessage> TelemetryMessages { get; set; }
DbSet<User> Users { get; set; }
DbSet<UserRole> UserRoles { get; set; }
DbSet<ReportProperty> ReportProperties { get; set; }
DbSet<DrillFlowChart> DrillFlowChart { get; set; }
DbSet<DrillingProgramPart> DrillingProgramParts { get; set; }
DbSet<DrillParams> DrillParams { get; set; }
DbSet<FileCategory> FileCategories { get; set; }
DbSet<FileInfo> Files { get; set; }
DbSet<FileMark> FileMarks { get; set; }
DbSet<FileCategory> FileCategories { get; set; }
DbSet<Telemetry> Telemetries { get; set; }
DbSet<TelemetryUser> TelemetryUsers { get; set; }
DbSet<WellOperationCategory> WellOperationCategories { get; set; }
DbSet<TelemetryAnalysis> TelemetryAnalysis { get; set; }
DbSet<Well> Wells { get; set; }
DbSet<WellComposite> WellComposites { get; set; }
DbSet<WellSectionType> WellSectionTypes { get; set; }
DbSet<WellOperation> WellOperations { get; set; }
DbSet<WellType> WellTypes { get; set; }
DbSet<Measure> Measures { get; set; }
DbSet<MeasureCategory> MeasureCategories { get; set; }
DbSet<TelemetryDataSpin> TelemetryDataSpin { get; set; }
DbSet<DrillParams> DrillParams { get; set; }
DbSet<DrillFlowChart> DrillFlowChart { get; set; }
DbSet<RelationUserUserRole> RelationUserUserRoles { get; set; }
DbSet<Permission> Permissions { get; set; }
DbSet<RelationCompanyWell> RelationCompaniesWells { get; set; }
DbSet<RelationUserDrillingProgramPart> RelationDrillingProgramPartUsers { get; set; }
DbSet<RelationUserRolePermission> RelationUserRolePermissions { get; set; }
DbSet<RelationUserUserRole> RelationUserUserRoles { get; set; }
DbSet<ReportProperty> ReportProperties { get; set; }
DbSet<Telemetry> Telemetries { get; set; }
DbSet<TelemetryAnalysis> TelemetryAnalysis { get; set; }
DbSet<TelemetryDataSaub> TelemetryDataSaub { get; set; }
DbSet<TelemetryDataSpin> TelemetryDataSpin { get; set; }
DbSet<TelemetryEvent> TelemetryEvents { get; set; }
DbSet<TelemetryMessage> TelemetryMessages { get; set; }
DbSet<TelemetryUser> TelemetryUsers { get; set; }
DbSet<User> Users { get; set; }
DbSet<UserRole> UserRoles { get; set; }
DbSet<Well> Wells { get; set; }
DbSet<WellComposite> WellComposites { get; set; }
DbSet<WellOperation> WellOperations { get; set; }
DbSet<WellOperationCategory> WellOperationCategories { get; set; }
DbSet<WellSectionType> WellSectionTypes { get; set; }
DbSet<WellType> WellTypes { get; set; }
DatabaseFacade Database { get; }
DbSet<DrillingProgramPart> DrillingProgramParts { get; set; }
DbSet<RelationUserDrillingProgramPart> RelationDrillingProgramPartUsers { get; set; }
DbSet<RelationCompanyWell> RelationCompaniesWells { get; set; }
int SaveChanges();
int SaveChanges(bool acceptAllChangesOnSuccess);
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
DbSet<TEntity> Set<TEntity>(string name) where TEntity : class;
DbSet<TEntity> Set<TEntity>() where TEntity : class;
}

View File

@ -9,11 +9,13 @@
</PropertyGroup>
<ItemGroup>
<None Remove="Services\DailyReport\DailyReportTemplate.xlsx" />
<None Remove="Services\WellOperationService\ScheduleReportTemplate.xlsx" />
<None Remove="Services\WellOperationService\WellOperationImportTemplate.xlsx" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Services\DailyReport\DailyReportTemplate.xlsx" />
<EmbeddedResource Include="Services\WellOperationService\ScheduleReportTemplate.xlsx" />
<EmbeddedResource Include="Services\WellOperationService\WellOperationImportTemplate.xlsx" />
</ItemGroup>

View File

@ -5,6 +5,7 @@ using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services;
using AsbCloudInfrastructure.Services.Analysis;
using AsbCloudInfrastructure.Services.Cache;
using AsbCloudInfrastructure.Services.DailyReport;
using AsbCloudInfrastructure.Services.DrillingProgram;
using AsbCloudInfrastructure.Services.SAUB;
using AsbCloudInfrastructure.Services.WellOperationService;
@ -85,6 +86,7 @@ namespace AsbCloudInfrastructure
services.AddTransient<IWellOperationImportService, WellOperationImportService>();
services.AddTransient<IWellOperationService, WellOperationService>();
services.AddTransient<IScheduleReportService, ScheduleReportService>();
services.AddTransient<IDailyReportService, DailyReportService>();
// admin crud services:
services.AddTransient<ICrudService<TelemetryDto>, CrudServiceBase<TelemetryDto, Telemetry>>(); // может быть включен в сервис TelemetryService

View File

@ -0,0 +1,8 @@
namespace AsbCloudInfrastructure
{
/// <summary>
/// Тип для поиска этой сборки
/// </summary>
public interface IInfrastructureMarker
{}
}

View File

@ -0,0 +1,299 @@
using AsbCloudApp.Data;
using ClosedXML.Excel;
using System;
using System.IO;
using System.Linq;
namespace AsbCloudInfrastructure.Services.DailyReport
{
public class DailyReportMakerExcel
{
public Stream MakeReport(DailyReportDto dailyReportDto)
{
using var templateStream = System.Reflection.Assembly.GetExecutingAssembly()
.GetManifestResourceStream("AsbCloudInfrastructure.Services.DailyReport.DailyReportTemplate.xlsx");
using var workbook = new XLWorkbook(templateStream, XLEventTracking.Disabled);
FillSheet(workbook, dailyReportDto);
MemoryStream memoryStream = new MemoryStream();
workbook.SaveAs(memoryStream, new SaveOptions { });
memoryStream.Seek(0, SeekOrigin.Begin);
return memoryStream;
}
public void FillSheet(XLWorkbook workbook, DailyReportDto reportParams)
{
var sheet = workbook.Worksheets.First();//.Add(reportParams.ReportDate.ToString("dd.MM.yyyy"));
sheet.Name = reportParams.ReportDate.ToString("dd.MM.yyyy");
var activeRow = 3;
activeRow = AddBlockHead(sheet, activeRow, reportParams);
activeRow = AddBlockSlaughtersReport(sheet, activeRow, reportParams);
activeRow = AddBlockTrajectoryReport(sheet, activeRow, reportParams);
activeRow = AddBlockDrillers(sheet, activeRow, reportParams);
activeRow = AddBlockSAUB(sheet, activeRow, reportParams);
activeRow = AddBlockBHA(sheet, activeRow, reportParams);
activeRow = AddBlockBHADescription(sheet, activeRow, reportParams);
activeRow = AddBlockOperations(sheet, activeRow, reportParams);
activeRow = AddBlockTimeBalans(sheet, activeRow, reportParams);
activeRow = AddBlockMeterlessWorks(sheet, activeRow, reportParams);
activeRow = AddBlockDrillingModes(sheet, activeRow, reportParams);
activeRow = AddBlockRotorDrilling(sheet, activeRow, reportParams);
activeRow = AddBlockSlideDrilling(sheet, activeRow, reportParams);
activeRow = AddBlockROPPlan(sheet, activeRow, reportParams);
activeRow = AddBlockSummary(sheet, activeRow, reportParams);
activeRow = AddBlockSubscribes(sheet, activeRow, reportParams);
}
private int AddBlockHead(IXLWorksheet sheet, int startRow, DailyReportDto reportDto)
{
sheet.Cell(startRow, 3).Value =
$"Суточная сводка бурения скважины №{reportDto.WellName}, куст: {reportDto.ClusterName}";
sheet.Cell(startRow + 1, 3).Value =
$"Заказчик: {reportDto.Customer}";
sheet.Cell(startRow + 2, 3).Value =
$"Подрядчик: {reportDto.Contractor}";
return startRow + 2;
}
private int AddBlockSlaughtersReport(IXLWorksheet sheet, int startRow, DailyReportDto reportDto)
{
sheet.Cell(startRow + 4, 3).Value =
$"{reportDto.ReportDate}";
sheet.Cell(startRow + 4, 5).Value =
$"{reportDto.WellDepthIntervalStartDate}";
sheet.Cell(startRow + 4, 6).Value =
$"{reportDto.WellDepthIntervalFinishDate}";
return startRow + 4;
}
private int AddBlockTrajectoryReport(IXLWorksheet sheet, int startRow, DailyReportDto reportDto)
{
sheet.Cell(startRow + 4, 3).Value =
$"{reportDto.BottomholeDepth}";
sheet.Cell(startRow + 4, 4).Value =
$"{reportDto.VerticalDepth}";
sheet.Cell(startRow + 4, 5).Value =
$"{reportDto.ZenithAngle}";
sheet.Cell(startRow + 4, 6).Value =
$"{reportDto.AzimuthAngle}";
return startRow + 4;
}
private int AddBlockDrillers(IXLWorksheet sheet, int startRow, DailyReportDto reportDto)
{
sheet.Cell(startRow + 2, 4).Value =
$"{reportDto.FirstDriller}";
sheet.Cell(startRow + 3, 4).Value =
$"{reportDto.SecondDriller}";
return startRow + 3;
}
private int AddBlockSAUB(IXLWorksheet sheet, int startRow, DailyReportDto reportDto)
{
sheet.Cell(startRow + 3, 6).Value =
$"{reportDto.WorkTimeSAUB}";
sheet.Cell(startRow + 4, 6).Value =
$"{reportDto.WorkTimeSpinMaster}";
sheet.Cell(startRow + 5, 6).Value =
$"{reportDto.WorkTimeTorkMaster}";
sheet.Cell(startRow + 3, 7).Value =
$"{reportDto.PenetrationSAUB}";
sheet.Cell(startRow + 4, 7).Value =
$"{reportDto.PenetrationSpinMaster}";
sheet.Cell(startRow + 5, 7).Value =
$"{reportDto.PenetrationTorkMaster}";
sheet.Cell(startRow + 6, 6).Value =
$"{reportDto.CountLaunchesMSE}";
return startRow + 6;
}
private int AddBlockBHA(IXLWorksheet sheet, int startRow, DailyReportDto reportDto)
{
sheet.Cell(startRow + 3, 6).Value =
$"{reportDto.WorkTimeSAUB}";
sheet.Cell(startRow + 4, 6).Value =
$"{reportDto.WorkTimeSpinMaster}";
sheet.Cell(startRow + 5, 6).Value =
$"{reportDto.WorkTimeTorkMaster}";
sheet.Cell(startRow + 3, 7).Value =
$"{reportDto.PenetrationSAUB}";
sheet.Cell(startRow + 4, 7).Value =
$"{reportDto.PenetrationSpinMaster}";
sheet.Cell(startRow + 5, 7).Value =
$"{reportDto.PenetrationTorkMaster}";
sheet.Cell(startRow + 6, 6).Value =
$"{reportDto.CountLaunchesMSE}";
return startRow + 6;
}
private int AddBlockBHADescription(IXLWorksheet sheet, int startRow, DailyReportDto reportDto)
{
sheet.Cell(startRow + 2, 3).Value =
$"{reportDto.BHADescription}";
return startRow + 6;
}
private int AddBlockOperations(IXLWorksheet sheet, int startRow, DailyReportDto reportDto)
{
return startRow + 7;
}
private int AddBlockTimeBalans(IXLWorksheet sheet, int startRow, DailyReportDto reportDto)
{
return startRow + 8;
}
private int AddBlockMeterlessWorks(IXLWorksheet sheet, int startRow, DailyReportDto reportDto)
{
sheet.Cell(startRow + 4, 6).Value =
$"{reportDto.StandardTimeBarrelPreparation}";
sheet.Cell(startRow + 4, 9).Value =
$"{reportDto.StandardTimeExtension}";
sheet.Cell(startRow + 6, 6).Value =
$"{reportDto.ActualTimeBarrelPreparation}";
sheet.Cell(startRow + 6, 9).Value =
$"{reportDto.ActualTimeExtension}";
return startRow + 9;
}
private int AddBlockDrillingModes(IXLWorksheet sheet, int startRow, DailyReportDto reportDto)
{
sheet.Cell(startRow + 2, 6).Value =
$"{reportDto.RotorDrillingModes}";
sheet.Cell(startRow + 3, 9).Value =
$"{reportDto.SlideDrillingModes}";
return startRow + 3;
}
private int AddBlockRotorDrilling(IXLWorksheet sheet, int startRow, DailyReportDto reportDto)
{
sheet.Cell(startRow + 3, 3).Value =
$"{reportDto.PenetrationInRotor}";
sheet.Cell(startRow + 3, 5).Value =
$"{reportDto.NumberDrillingHours}";
sheet.Cell(startRow + 3, 9).Value =
$"{reportDto.AVGDiffDropRotor}";
return startRow + 3;
}
private int AddBlockSlideDrilling(IXLWorksheet sheet, int startRow, DailyReportDto reportDto)
{
sheet.Cell(startRow + 3, 3).Value =
$"{reportDto.PenetrationInSlide}";
sheet.Cell(startRow + 3, 5).Value =
$"{reportDto.DrillingTimeInRotor}";
sheet.Cell(startRow + 3, 9).Value =
$"{reportDto.AVGDiffPressureSlide}";
return startRow + 3;
}
private int AddBlockROPPlan(IXLWorksheet sheet, int startRow, DailyReportDto reportDto)
{
sheet.Cell(startRow + 3, 9).Value =
$"{reportDto.SectionROPPlan}";
return startRow + 3;
}
private int AddBlockSummary(IXLWorksheet sheet, int startRow, DailyReportDto reportDto)
{
sheet.Cell(startRow + 7, 7).Value =
$"{reportDto.SectionDrillingTimeTotal}";
sheet.Cell(startRow + 8, 7).Value =
$"{reportDto.SectionPenetrationTotal}";
sheet.Cell(startRow + 9, 7).Value =
$"{reportDto.ExtensionsCount}";
sheet.Cell(startRow + 10, 7).Value =
$"{reportDto.DeviationFromTVD}";
sheet.Cell(startRow + 11, 3).Value =
$"{reportDto.DeclinesReasonsROP}";
return startRow + 13;
}
private int AddBlockSubscribes(IXLWorksheet sheet, int startRow, DailyReportDto reportDto)
{
sheet.Cell(startRow + 3, 9).Value =
$"{reportDto.DrillingMaster}";
sheet.Cell(startRow + 5, 9).Value =
$"{reportDto.Supervisor}";
return startRow + 5;
}
private static string GetColunmLetter(int columnNumber)
{
string letter = "";
while (columnNumber > 0)
{
int modulo = (columnNumber - 1) % 26;
letter = Convert.ToChar('A' + modulo) + letter;
columnNumber = (columnNumber - modulo) / 26;
}
return letter;
}
private static IXLStyle SetBorder(IXLStyle style)
{
style.Border.RightBorder = XLBorderStyleValues.Thin;
style.Border.LeftBorder = XLBorderStyleValues.Thin;
style.Border.TopBorder = XLBorderStyleValues.Thin;
style.Border.BottomBorder = XLBorderStyleValues.Thin;
style.Border.InsideBorder = XLBorderStyleValues.Thin;
return style;
}
private static IXLCell SetDateTime(IXLCell cell)
{
cell.DataType = XLDataType.DateTime;
cell.Style.DateFormat.Format = "DD.MM.YYYY HH:MM:SS";
return cell;
}
private static IXLCell SetNumber(IXLCell cell)
{
cell.DataType = XLDataType.Number;
cell.Style.NumberFormat.Format = "0.00";
return cell;
}
private static IXLCell SetCell(IXLRow row, int colunm, object value, int maxChartsToWrap = 88)
{
var cell = row.Cell(colunm);
cell.Value = value;
SetBorder(cell.Style);
cell.Style.Alignment.WrapText = true;
if (value is string valueString && valueString.Length > maxChartsToWrap)
{
var baseHeight = row.Height;
row.Height = 0.82d * baseHeight * Math.Ceiling(1d + valueString.Length / maxChartsToWrap);
}
if (value is DateTime)
{
SetDateTime(cell);
}
else if (value is IFormattable)
{
SetNumber(cell);
}
return cell;
}
}
}

View File

@ -0,0 +1,148 @@
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Mapster;
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using System.Collections.Generic;
namespace AsbCloudInfrastructure.Services.DailyReport
{
#nullable enable
public class DailyReportService : IDailyReportService
{
private readonly IAsbCloudDbContext db;
private readonly IWellService wellService;
private readonly DailyReportMakerExcel dailyReportMaker = new DailyReportMakerExcel();
public DailyReportService(IAsbCloudDbContext db, IWellService wellService)
{
this.db = db;
this.wellService = wellService;
}
public async Task<IEnumerable<DailyReportDto>> GetListAsync(int idWell, DateTime? begin, DateTime? end, CancellationToken token)
{
var query = db.DailyReports.Where(r => r.IdWell == idWell);
var offsetHours = wellService.GetTimezone(idWell).Hours;
if (begin is not null)
{
var beginOffset = ((DateTime)begin).ToUtcDateTimeOffset(offsetHours);
query = query.Where(d => d.StartDate >= beginOffset);
}
if (end is not null)
{
var endOffset = ((DateTime)end).ToUtcDateTimeOffset(offsetHours);
query = query.Where(d => d.StartDate <= endOffset);
}
var entities = await query
.ToListAsync(token);
return entities.Select(r => Convert(r, offsetHours));
}
public async Task<DailyReportDto> GetOrGenerateAsync(int idWell, DateTime date, CancellationToken token)
{
var dailyReportDto = await GetAsync(idWell, date, token);
if (dailyReportDto is null)
return await MakeDefaultDailyReportAsync(idWell, token);
else
return dailyReportDto;
}
public async Task<int> AddAsync(int idWell, DailyReportDto dto, CancellationToken token = default)
{
var offsetHours = wellService.GetTimezone(idWell).Hours;
var reportDateOffset = dto.ReportDate.ToUtcDateTimeOffset(offsetHours);
var info = Convert(dto, offsetHours);
var entity = new AsbCloudDb.Model.DailyReport
{
IdWell = idWell,
StartDate = reportDateOffset,
Info = info,
};
db.DailyReports.Add(entity);
var result = await db.SaveChangesAsync(token);
return result;
}
public async Task<int> UpdateAsync(int idWell, DateTime date, DailyReportDto dto, CancellationToken token)
{
var offsetHours = wellService.GetTimezone(idWell).Hours;
var reportDateOffset = date.ToUtcDateTimeOffset(offsetHours);
var entity = await db.DailyReports
.FirstOrDefaultAsync(r => r.IdWell == idWell && r.StartDate == reportDateOffset, token);
if (entity is null)
return 0;
entity.Info = Convert(dto, offsetHours);
db.DailyReports.Update(entity);
var result = await db.SaveChangesAsync(token);
return result;
}
public async Task<Stream?> MakeReportAsync(int idWell, DateTime date, CancellationToken token = default)
{
var dailyReportDto = await GetAsync(idWell, date, token);
if (dailyReportDto is null)
return null;
var memoryStream = dailyReportMaker.MakeReport(dailyReportDto);
return memoryStream;
}
private async Task<DailyReportDto?> GetAsync(int idWell, DateTime date, CancellationToken token)
{
var offsetHours = wellService.GetTimezone(idWell).Hours;
var dateOffset = date.ToUtcDateTimeOffset(offsetHours);
var query = db.DailyReports
.Where(r => r.IdWell == idWell)
.Where(d => d.StartDate == dateOffset);
var data = await query.FirstOrDefaultAsync(token);
if (data is null)
return null;
else
return Convert(data, offsetHours);
}
private async Task<DailyReportDto> MakeDefaultDailyReportAsync(int idWell, CancellationToken token)
{
var well = await wellService.GetAsync(idWell, token);
var offsetHours = wellService.GetTimezone(idWell).Hours;
var dto = new DailyReportDto()
{
ReportDate = DateTimeOffset.UtcNow.ToRemoteDateTime(offsetHours),
WellName = well.Caption,
ClusterName = well.Cluster,
};
DailyReportDto result = dto;
return result;
}
private static DailyReportDto Convert(AsbCloudDb.Model.DailyReport entity, double offsetHours)
{
var dto = entity.Info.Adapt<DailyReportDto>();
dto.ReportDate = entity.StartDate.ToRemoteDateTime(offsetHours);
return dto;
}
private static DailyReportInfo Convert(DailyReportDto dto, double offsetHours)
{
var entity = dto.Adapt<DailyReportInfo>();
entity.ReportDate = dto.ReportDate.ToUtcDateTimeOffset(offsetHours);
return entity;
}
}
#nullable disable
}

View File

@ -0,0 +1,114 @@
using AsbCloudApp.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Services;
namespace AsbCloudWebApi.Controllers
{
[Route("api/well/{idWell}/[controller]")]
[ApiController]
[Authorize]
public class DailyReportController : ControllerBase
{
private readonly IDailyReportService dailyReportService;
private readonly IWellService wellService;
public DailyReportController(IDailyReportService dailyReportService, IWellService wellService)
{
this.dailyReportService = dailyReportService;
this.wellService = wellService;
}
/// <summary>
/// Список наборов данных для формирования рапорта
/// </summary>
/// <param name="idWell"></param>
/// <param name="begin"></param>
/// <param name="end"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet]
//[Permission]
[ProducesResponseType(typeof(IEnumerable<DailyReportDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetListAsync(int idWell, DateTime? begin = null, DateTime? end = null, CancellationToken token = default)
{
var result = await dailyReportService.GetListAsync(idWell, begin, end, token);
return Ok(result);
}
/// <summary>
/// новый набор данных для формирования рапорта (на новую дату). Если в архиве на эту дату уже есть данные то вернуться они.
/// </summary>
/// <param name="idWell"></param>
/// <param name="date"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet("{date}")]
//[Permission]
[ProducesResponseType(typeof(DailyReportDto), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetOrGenerateAsync(int idWell, [Required] DateTime date, CancellationToken token = default)
{
var dto = await dailyReportService.GetOrGenerateAsync(idWell, date, token);
return Ok(dto);
}
/// <summary>
/// Сохранение нового набора данных для формирования рапорта
/// </summary>
/// <param name="idWell"></param>
/// <param name="dto"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpPost]
//[Permission]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> AddAsync(int idWell, [Required][FromBody] DailyReportDto dto, CancellationToken token = default)
{
var result = await dailyReportService.AddAsync(idWell, dto, token);
return Ok(result);
}
/// <summary>
/// Сохранение изменений набора данных для формирования рапорта
/// </summary>
/// <param name="idWell"></param>
/// <param name="date"></param>
/// <param name="dto"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpPut("{date}")]
//[Permission]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> UpdateAsync(int idWell, [Required] DateTime date, [Required] DailyReportDto dto, CancellationToken token = default)
{
var result = await dailyReportService.UpdateAsync(idWell, date, dto, token);
return Ok(result);
}
/// <summary>
/// Сформировать и скачать рапорт в формате excel
/// </summary>
/// <param name="idWell"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet("{date}/excel")]
//[Permission]
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> DownloadAsync(int idWell, DateTime date, CancellationToken token = default)
{
var stream = await dailyReportService.MakeReportAsync(idWell, date, token);
if (stream != null)
{
var fileName = "CP.xlsx";
return File(stream, "application/octet-stream", fileName);
}
else
return NoContent();
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using AsbCloudInfrastructure.Services.DailyReport;
using System;
namespace ConsoleApp1
{
@ -8,7 +9,20 @@ namespace ConsoleApp1
static void Main(/*string[] args*/)
{
// use ServiceFactory to make services
var makerExcel = new DailyReportMakerExcel();
AsbCloudApp.Data.DailyReportDto dto = new() {
WellName = "111",
ClusterName = "cluster name",
Contractor = "NaftaGas",
};
using var stream = makerExcel.MakeReport(dto);
using (var fileStream = System.IO.File.Create(@"c:/temp/1.xlsx"))
{
stream.CopyTo(fileStream);
fileStream.Flush();
}
Console.WriteLine("End of Test");
Console.ReadLine();