Merge branch 'dev' into feature/WellFinalDocumentsRepository

This commit is contained in:
ngfrolov 2023-01-30 17:26:58 +05:00
commit a367dea6a8
Signed by: ng.frolov
GPG Key ID: E99907A0357B29A7
19 changed files with 7384 additions and 81 deletions

View File

@ -63,6 +63,11 @@ namespace AsbCloudApp.Data.SAUB
/// </summary> /// </summary>
public float PressureDeltaLimitMax { get; set; } public float PressureDeltaLimitMax { get; set; }
/// <summary>
/// Перепад давления
/// </summary>
public float PressureDelta { get; set; }
/// <summary> /// <summary>
/// осевая нагрузка /// осевая нагрузка
/// </summary> /// </summary>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,57 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AsbCloudDb.Migrations
{
public partial class Fix_PlannedTrajectory_permissions : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "t_permission",
keyColumn: "id",
keyValue: 510,
column: "name",
value: "PlannedTrajectory.get");
migrationBuilder.UpdateData(
table: "t_permission",
keyColumn: "id",
keyValue: 511,
column: "name",
value: "PlannedTrajectory.edit");
migrationBuilder.UpdateData(
table: "t_permission",
keyColumn: "id",
keyValue: 512,
column: "name",
value: "PlannedTrajectory.delete");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "t_permission",
keyColumn: "id",
keyValue: 510,
column: "name",
value: "TelemetryWirelineRunOut.get");
migrationBuilder.UpdateData(
table: "t_permission",
keyColumn: "id",
keyValue: 511,
column: "name",
value: "TelemetryWirelineRunOut.edit");
migrationBuilder.UpdateData(
table: "t_permission",
keyColumn: "id",
keyValue: 512,
column: "name",
value: "TelemetryWirelineRunOut.delete");
}
}
}

View File

@ -1770,19 +1770,19 @@ namespace AsbCloudDb.Migrations
{ {
Id = 510, Id = 510,
Description = "Разрешение просматривать плановая траектория", Description = "Разрешение просматривать плановая траектория",
Name = "TelemetryWirelineRunOut.get" Name = "PlannedTrajectory.get"
}, },
new new
{ {
Id = 511, Id = 511,
Description = "Разрешение редактировать плановая траектория", Description = "Разрешение редактировать плановая траектория",
Name = "TelemetryWirelineRunOut.edit" Name = "PlannedTrajectory.edit"
}, },
new new
{ {
Id = 512, Id = 512,
Description = "Разрешение удалять плановая траектория", Description = "Разрешение удалять плановая траектория",
Name = "TelemetryWirelineRunOut.delete" Name = "PlannedTrajectory.delete"
}); });
}); });

View File

@ -138,9 +138,9 @@
new (){ Id = 507, Name="TelemetryWirelineRunOut.get", Description="Разрешение просматривать наработка талевого каната"}, new (){ Id = 507, Name="TelemetryWirelineRunOut.get", Description="Разрешение просматривать наработка талевого каната"},
new (){ Id = 510, Name="TelemetryWirelineRunOut.get", Description="Разрешение просматривать плановая траектория"}, new (){ Id = 510, Name="PlannedTrajectory.get", Description="Разрешение просматривать плановая траектория"},
new (){ Id = 511, Name="TelemetryWirelineRunOut.edit", Description="Разрешение редактировать плановая траектория"}, new (){ Id = 511, Name="PlannedTrajectory.edit", Description="Разрешение редактировать плановая траектория"},
new (){ Id = 512, Name="TelemetryWirelineRunOut.delete", Description="Разрешение удалять плановая траектория"}, new (){ Id = 512, Name="PlannedTrajectory.delete", Description="Разрешение удалять плановая траектория"},
}; };
} }
} }

View File

@ -37,9 +37,11 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="CliWrap" Version="3.6.0" />
<PackageReference Include="ClosedXML" Version="0.96.0" /> <PackageReference Include="ClosedXML" Version="0.96.0" />
<PackageReference Include="FluentValidation.AspNetCore" Version="11.2.2" /> <PackageReference Include="FluentValidation.AspNetCore" Version="11.2.2" />
<PackageReference Include="itext7" Version="7.2.3" /> <PackageReference Include="itext7" Version="7.2.3" />
<PackageReference Include="iTextSharp" Version="5.5.13.3" />
<PackageReference Include="Mapster" Version="7.3.0" /> <PackageReference Include="Mapster" Version="7.3.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" /> <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.23.1" /> <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.23.1" />

View File

@ -0,0 +1,93 @@
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CliWrap;
using System.Threading.Tasks;
using System.Threading;
using System;
namespace AsbCloudInfrastructure.Services.DrillingProgram.Convert
{
#nullable enable
sealed internal class ConvertToPdf
{
internal static readonly string[] filesExtensions = { ".xlsx", ".xls", ".ods", ".odt", ".doc", ".docx", ".pdf" };
private static void MergeFiles(IEnumerable<string> inputFiles, string outFile)
{
using var stream = new FileStream(outFile, FileMode.Create);
using var doc = new Document();
using var pdf = new PdfCopy(doc, stream);
doc.Open();
var inputFilesList = inputFiles.ToList();
foreach (var file in inputFilesList)
{
var reader = new PdfReader(file);
for (int i = 0; i < reader.NumberOfPages; i++)
{
pdf.AddPage(pdf.GetImportedPage(reader, i + 1));
}
pdf.FreeReader(reader);
reader.Close();
};
}
private static (string programFile, string programArg) GetOptionsStartupProcess (string inputFileName, string resultFileDir)
{
(string programFile, string programArg) startupOptions;
if (OperatingSystem.IsWindows())
{
startupOptions.programFile = "C:\\Program Files\\LibreOffice\\program\\soffice.exe";
startupOptions.programArg = $"-headless -convert-to pdf {inputFileName} --outdir {resultFileDir}";
return startupOptions;
}
if(OperatingSystem.IsLinux())
{
startupOptions.programFile = "/usr/bin/soffice";
startupOptions.programArg = $"--headless --convert-to pdf {inputFileName} --outdir {resultFileDir}";
return (startupOptions);
}
throw new NotSupportedException ("Вызов процесса в текущей операционной системе не возможен");
}
private static async Task StartConvertProcessAsync(string inputFileName, string resultFileDir, CancellationToken token)
{
var (programFile, programArg) = GetOptionsStartupProcess(inputFileName, resultFileDir);
var command = Cli.Wrap(programFile)
.WithArguments(programArg);
await command.ExecuteAsync(token);
}
public static async Task GetConverteAndMergedFileAsync(IEnumerable<string> files, string resultPath, string convertedFilesDir, CancellationToken token)
{
var badFiles = files.Where(f => !filesExtensions.Contains(Path.GetExtension(f)));
if (badFiles.Any())
{
throw new FileFormatException($"Файлы: {string.Join(", ", badFiles)} - неподдерживаемого формата. " +
$"Они не могут быть добавлены в список файлов для конвертации и слияния в общий файл программы бурения.");
}
var listFiles = files
.Distinct()
.Select(f => new
{
inputFile = f,
convertedFile = Path.Combine(convertedFilesDir, "pdf", Path.ChangeExtension(Path.GetFileName(f), ".pdf"))
})
.ToList();
foreach (var file in listFiles)
{
var fileExt = Path.GetExtension(file.inputFile).ToLower();
if (fileExt != ".pdf")
{
await StartConvertProcessAsync(file.inputFile, Path.GetDirectoryName(file.convertedFile)!, token);
}
}
MergeFiles(listFiles.Select(c => c.convertedFile), resultPath);
Directory.Delete(Path.Combine(convertedFilesDir, "pdf"), true);
}
}
#nullable disable
}

View File

@ -0,0 +1,17 @@
КЛАСС ПРЕОБРАЗУЮЩИЙ ЧАСТИ ПРОГРАММЫ БУРЕНИЯ В ЕДИНЫЙ ФАЙЛ ПЕЧАТНОГО ФОРМАТА (pdf)
1. На Linux сервер необходимо установить пакеты LibreOffice:
sudo apt-get install libreoffice-writer libreoffice-calc
2. путь до бинарника LibreOffice:
Linux - /usr/bin/soffice
Windows - C:\Program Files\LibreOffice\program\soffice.exe
3. В массиве fileExtensions содержатся в виде стринг переменных необходимые расширения файлов
изначально обозначенные в задаче.
При необходимости список можно расширить.

View File

@ -4,6 +4,7 @@ using AsbCloudApp.Repositories;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Background; using AsbCloudInfrastructure.Background;
using AsbCloudInfrastructure.Services.DrillingProgram.Convert;
using Mapster; using Mapster;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@ -28,7 +29,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
private readonly IWellService wellService; private readonly IWellService wellService;
private readonly IConfiguration configuration; private readonly IConfiguration configuration;
private readonly BackgroundWorker backgroundWorker; private readonly BackgroundWorker backgroundWorker;
private readonly IEmailService emailService; private readonly IEmailService emailService;
private const int idFileCategoryDrillingProgram = 1000; private const int idFileCategoryDrillingProgram = 1000;
private const int idFileCategoryDrillingProgramPartsStart = 1001; private const int idFileCategoryDrillingProgramPartsStart = 1001;
@ -50,6 +51,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
private const int idStateReady = 3; private const int idStateReady = 3;
private const int idStateError = 4; private const int idStateError = 4;
private static readonly string[] validFileExtensions = ConvertToPdf.filesExtensions;
public DrillingProgramService( public DrillingProgramService(
IAsbCloudDbContext context, IAsbCloudDbContext context,
FileService fileService, FileService fileService,
@ -161,12 +164,21 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
return state; return state;
} }
public async Task<int> AddFile(int idWell, int idFileCategory, int idUser, string fileFullName, System.IO.Stream fileStream, CancellationToken token = default) private static bool IsFileExtensionValid(string file)
{ {
var fileExt = Path.GetExtension(file).ToLower();
return validFileExtensions.Contains(fileExt);
}
public async Task<int> AddFile(int idWell, int idFileCategory, int idUser, string fileFullName, Stream fileStream, CancellationToken token = default)
{
if (!IsFileExtensionValid(fileFullName))
throw new FileFormatException($"Файл {fileFullName} - неподдерживаемого формата. Файл не может быть загружен.");
var part = await context.DrillingProgramParts var part = await context.DrillingProgramParts
.Include(p => p.RelatedUsers) .Include(p => p.RelatedUsers)
.ThenInclude(r => r.User) .ThenInclude(r => r.User)
.FirstOrDefaultAsync(p => p.IdWell == idWell && p.IdFileCategory == idFileCategory, token); .FirstOrDefaultAsync(p => p.IdWell == idWell && p.IdFileCategory == idFileCategory, token);
if (part == null) if (part == null)
throw new ArgumentInvalidException($"DrillingProgramPart id == {idFileCategory} does not exist", nameof(idFileCategory)); throw new ArgumentInvalidException($"DrillingProgramPart id == {idFileCategory} does not exist", nameof(idFileCategory));
@ -333,9 +345,6 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
await NotifyPublisherOnFullAccepAsync(fileMarkDto, token); await NotifyPublisherOnFullAccepAsync(fileMarkDto, token);
} }
} }
return result; return result;
} }
@ -472,15 +481,15 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
if (!backgroundWorker.Contains(workId)) if (!backgroundWorker.Contains(workId))
{ {
var well = (await wellService.GetOrDefaultAsync(idWell, token))!; var well = (await wellService.GetOrDefaultAsync(idWell, token))!;
var resultFileName = $"Программа бурения {well.Cluster} {well.Caption}.xlsx"; var resultFileName = $"Программа бурения {well.Cluster} {well.Caption}.pdf";
var tempResultFilePath = Path.Combine(Path.GetTempPath(), "drillingProgram", resultFileName); var convertedFilesDir = Path.Combine(Path.GetTempPath(), "drillingProgram", $"{well.Cluster}_{well.Caption}");
var tempResultFilePath = Path.Combine(convertedFilesDir, resultFileName);
var workAction = async (string workId, IServiceProvider serviceProvider, CancellationToken token) => var workAction = async (string workId, IServiceProvider serviceProvider, CancellationToken token) =>
{ {
var context = serviceProvider.GetRequiredService<IAsbCloudDbContext>(); var context = serviceProvider.GetRequiredService<IAsbCloudDbContext>();
var fileService = serviceProvider.GetRequiredService<FileService>(); var fileService = serviceProvider.GetRequiredService<FileService>();
var files = state.Parts.Select(p => fileService.GetUrl(p.File)); var files = state.Parts.Select(p => fileService.GetUrl(p.File));
DrillingProgramMaker.UniteExcelFiles(files, tempResultFilePath, state.Parts, well); await ConvertToPdf.GetConverteAndMergedFileAsync(files, tempResultFilePath, convertedFilesDir, token);
await fileService.MoveAsync(idWell, null, idFileCategoryDrillingProgram, resultFileName, tempResultFilePath, token); await fileService.MoveAsync(idWell, null, idFileCategoryDrillingProgram, resultFileName, tempResultFilePath, token);
}; };

View File

@ -181,6 +181,7 @@ namespace AsbCloudInfrastructure.Services.ProcessMap
result.PressureSp += item.PressureSp * itemWeight; result.PressureSp += item.PressureSp * itemWeight;
result.PressureSpRotor += item.PressureSpSlide * itemWeight; result.PressureSpRotor += item.PressureSpSlide * itemWeight;
result.PressureIdle += item.PressureIdle * itemWeight; result.PressureIdle += item.PressureIdle * itemWeight;
result.PressureDelta += item.PressureDelta * itemWeight;
result.AxialLoad += item.AxialLoad * itemWeight; result.AxialLoad += item.AxialLoad * itemWeight;
result.AxialLoadSp += item.AxialLoadSp * itemWeight; result.AxialLoadSp += item.AxialLoadSp * itemWeight;
@ -227,7 +228,7 @@ namespace AsbCloudInfrastructure.Services.ProcessMap
if (telemetryDataStat is not null) if (telemetryDataStat is not null)
{ {
dto.PressureDiff.SetpointFact = telemetryDataStat.PressureSp; dto.PressureDiff.SetpointFact = telemetryDataStat.PressureSp;
dto.PressureDiff.Fact = telemetryDataStat.Pressure; dto.PressureDiff.Fact = telemetryDataStat.PressureDelta;
dto.PressureDiff.Limit = telemetryDataStat.PressureDeltaLimitMax; dto.PressureDiff.Limit = telemetryDataStat.PressureDeltaLimitMax;
dto.AxialLoad.SetpointFact = telemetryDataStat.AxialLoadSp; dto.AxialLoad.SetpointFact = telemetryDataStat.AxialLoadSp;

View File

@ -53,6 +53,7 @@ namespace AsbCloudInfrastructure.Services.SAUB
PressureSpSlide = g.Average(t => t.PressureSpSlide!.Value), PressureSpSlide = g.Average(t => t.PressureSpSlide!.Value),
PressureIdle = g.Average(t => t.PressureIdle!.Value), PressureIdle = g.Average(t => t.PressureIdle!.Value),
PressureDeltaLimitMax = g.Average(t => t.PressureDeltaLimitMax!.Value), PressureDeltaLimitMax = g.Average(t => t.PressureDeltaLimitMax!.Value),
PressureDelta = g.Average(t => t.Pressure!.Value - t.PressureIdle!.Value),
AxialLoad = g.Average(t => t.AxialLoad!.Value), AxialLoad = g.Average(t => t.AxialLoad!.Value),
AxialLoadSp = g.Average(t => t.AxialLoadSp!.Value), AxialLoadSp = g.Average(t => t.AxialLoadSp!.Value),

View File

@ -94,8 +94,8 @@ namespace AsbCloudInfrastructure.Services.Subsystems
var detectedOperationsRequest = new DetectedOperationRequest() var detectedOperationsRequest = new DetectedOperationRequest()
{ {
IdWell = request.IdWell, IdWell = request.IdWell,
IdsCategories = new List<int>() { IdsCategories = new int[] {
1,3 WellOperationCategory.IdRotor, WellOperationCategory.IdSlide,
}, },
LtDate = request.LtDate, LtDate = request.LtDate,
GtDate = request.GtDate, GtDate = request.GtDate,
@ -158,9 +158,9 @@ namespace AsbCloudInfrastructure.Services.Subsystems
} }
private static (double depthIntervalRotor, double depthIntervalSlide) GetDepthInterval (IEnumerable<DetectedOperationDto> detectedOperations) private static (double depthIntervalRotor, double depthIntervalSlide) GetDepthInterval (IEnumerable<DetectedOperationDto> detectedOperations)
{ {
var depthIntervalRotor = detectedOperations.Where(o => o.IdCategory == 1) var depthIntervalRotor = detectedOperations.Where(o => o.IdCategory == WellOperationCategory.IdRotor)
.Sum(o => o.DepthEnd - o.DepthStart); .Sum(o => o.DepthEnd - o.DepthStart);
var depthIntervalSlide = detectedOperations.Where(o => o.IdCategory == 3) var depthIntervalSlide = detectedOperations.Where(o => o.IdCategory == WellOperationCategory.IdSlide)
.Sum(o => o.DepthEnd - o.DepthStart); .Sum(o => o.DepthEnd - o.DepthStart);
var depthInterval = (depthIntervalRotor, depthIntervalSlide); var depthInterval = (depthIntervalRotor, depthIntervalSlide);

View File

@ -125,10 +125,7 @@ namespace AsbCloudWebApi.Controllers
return BadRequest(ArgumentInvalidException.MakeValidationError(nameof(files), "at list 1 file should be uploaded")); return BadRequest(ArgumentInvalidException.MakeValidationError(nameof(files), "at list 1 file should be uploaded"));
var fileName = files[0].FileName; var fileName = files[0].FileName;
if (!fileName.EndsWith(".xlsx"))
return BadRequest(ArgumentInvalidException.MakeValidationError("file", "Файл должен быть xlsx"));
var fileStream = files[0].OpenReadStream(); var fileStream = files[0].OpenReadStream();
var result = await drillingProgramService.AddFile(idWell, idFileCategory, (int)idUser, fileName, fileStream, token); var result = await drillingProgramService.AddFile(idWell, idFileCategory, (int)idUser, fileName, fileStream, token);

View File

@ -72,7 +72,7 @@ namespace AsbCloudWebApi.Controllers.SAUB
/// <returns></returns> /// <returns></returns>
[HttpGet("{idWell}")] [HttpGet("{idWell}")]
[Permission] [Permission]
public virtual async Task<ActionResult<TDto>> GetDataAsync(int idWell, DateTime begin = default, public virtual async Task<ActionResult<IEnumerable<TDto>>> GetDataAsync(int idWell, DateTime begin = default,
int intervalSec = 600, int approxPointsCount = 1024, CancellationToken token = default) int intervalSec = 600, int approxPointsCount = 1024, CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
@ -102,7 +102,7 @@ namespace AsbCloudWebApi.Controllers.SAUB
[Route("{idWell}/datesRange")] [Route("{idWell}/datesRange")]
[Permission] [Permission]
[ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)]
public virtual async Task<IActionResult> GetDataDatesRangeAsync(int idWell, public virtual async Task<ActionResult<DatesRangeDto>> GetDataDatesRangeAsync(int idWell,
CancellationToken token = default) CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();

View File

@ -10,10 +10,11 @@ namespace AsbCloudWebApi
EnshureRegisteredDataSpin(); EnshureRegisteredDataSpin();
EnshureRegisteredDataSaub(); EnshureRegisteredDataSaub();
EnshureRegisteredWITS(); EnshureRegisteredWITS();
EnshureRegisteredWirelineRunOutBaseDto();
EnshureRegisteredWirelineRunOutDto(); EnshureRegisteredWirelineRunOutDto();
} }
private static void EnshureRegisteredWirelineRunOutDto() private static void EnshureRegisteredWirelineRunOutBaseDto()
{ {
var type = typeof(TelemetryWirelineRunOutBaseDto); var type = typeof(TelemetryWirelineRunOutBaseDto);
if (RuntimeTypeModel.Default.IsDefined(type)) if (RuntimeTypeModel.Default.IsDefined(type))
@ -26,6 +27,19 @@ namespace AsbCloudWebApi
.Add(5, nameof(TelemetryWirelineRunOutBaseDto.ReplaceWarnSp)); .Add(5, nameof(TelemetryWirelineRunOutBaseDto.ReplaceWarnSp));
} }
private static void EnshureRegisteredWirelineRunOutDto()
{
var type = typeof(TelemetryWirelineRunOutDto);
if (RuntimeTypeModel.Default.IsDefined(type))
return;
RuntimeTypeModel.Default.Add(type, false)
.Add(1, nameof(TelemetryWirelineRunOutDto.DateTime))
.Add(2, nameof(TelemetryWirelineRunOutDto.Hauling))
.Add(3, nameof(TelemetryWirelineRunOutDto.HaulingWarnSp))
.Add(4, nameof(TelemetryWirelineRunOutDto.Replace))
.Add(5, nameof(TelemetryWirelineRunOutDto.ReplaceWarnSp));
}
private static void EnshureRegisteredWITS() private static void EnshureRegisteredWITS()
{ {
EnshureRegisteredRecord1(); EnshureRegisteredRecord1();

View File

@ -18,8 +18,8 @@
//}, //},
"email": { "email": {
"smtpServer": "smtp.timeweb.ru", "smtpServer": "smtp.timeweb.ru",
"sender": "bot@autodrilling.ru", "sender": "bot@digitaldrilling.ru",
"password": "xHhgwZ4D", "password": "8wZrXSfP",
"platformName": "Цифровое бурение", "platformName": "Цифровое бурение",
"platformUrl": "https://cloud.digitaldrilling.ru", "platformUrl": "https://cloud.digitaldrilling.ru",

View File

@ -1,70 +1,172 @@
using AsbCloudApp.Requests; using iTextSharp.text.pdf;
using AsbCloudDb.Model;
using AsbCloudInfrastructure;
using AsbCloudInfrastructure.Repository;
using Microsoft.Extensions.Caching.Memory;
using System; using System;
using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading.Tasks;
using Document = iTextSharp.text.Document;
using CliWrap;
namespace ConsoleApp1 namespace ConsoleApp1
{ {
class Program class Program
{ {
private static AsbCloudDbContext db = ServiceFactory.Context;
// use ServiceFactory to make services
static void Main(/*string[] args*/) static void Main(/*string[] args*/)
{ {
DependencyInjection.MapsterSetup(); // string[] fileExtension = { ".xlsx", ".xls", ".ods", ".odt", ".doc", ".docx", ".pdf" };
var sw = System.Diagnostics.Stopwatch.StartNew(); // Console.WriteLine($"start convert");
// var inputFiles = new List<string>();
// var resultFile = "C:\\Test\\result.pdf";
// inputFiles.Add("11112222.docx");
// inputFiles.Add("11117777.pdf");
// inputFiles.Add("22223333.xls");
// inputFiles.Add("33334444.xlsx");
// //inputFiles.Add("33334444.tts");
var idTelemetry = 5; // var listOutNames = new List<string>();
// var filteredFilesNames = inputFiles
// .Distinct()
// .Where(f => fileExtension.Any(fe => f.ToLower().EndsWith(fe)))
// .ToList();
// FileInfo fileInfo = new FileInfo(resultFile);
var query = db.Set<TelemetryDataSaub>() // //matchesExtensions(inputFiles);
.Where(t => t.IdTelemetry == idTelemetry) // foreach (var FileName in inputFiles)
.Where(t => t.BlockPosition > 0.0001) // {
.Where(t => t.WellDepth > 0.0001) // var outputFile = Path.ChangeExtension(FileName, ".pdf");
.Where(t => t.WellDepth - t.BitDepth < 0.01) // var outFile = StartConvertProcessAsync(FileName, outputFile);
.GroupBy(t => new { H = t.DateTime.Hour, W = Math.Truncate(t.WellDepth!.Value) }) // Console.WriteLine($"convert file - {FileName}");
.Select(g => new // Console.ReadLine();
// listOutNames.Add(outFile.Result.ToString());
// }
// Console.WriteLine("merged files");
// Console.ReadLine();
// DoMerged(listOutNames, resultFile);
//static void matchesExtensions(List<string> inputFiles)
// {
// string[] fileExtension = { ".xlsx", ".xls", ".ods", ".odt", ".doc", ".docx", ".pdf" };
// foreach (var file in inputFiles)
// {
// var fileExt = Path.GetExtension(file);
// if (fileExtension.All(fe => fileExt != fe))
// {
// throw new FileFormatException($"Файл с именем: {file} не может быть добавлен в список файлов для конвертации и слияния в общий файл программы бурения. Не поддерживаемый формат файла");
// }
// }
// }
if (OperatingSystem.IsWindows())
{
Console.WriteLine("win");
Console.ReadLine();
}
if (OperatingSystem.IsLinux())
{
Console.WriteLine("linux");
Console.ReadLine();
}
}
public static void DoMerged(IEnumerable<string> inputFiles, string outFile)
{
using var stream = new FileStream(outFile, FileMode.Create);
using var doc = new Document();
using var pdf = new PdfCopy(doc, stream);
doc.Open();
var inputFilesList = inputFiles.ToList();
foreach (var file in inputFilesList)
{
var reader = new PdfReader(file);
for (int i = 0; i < reader.NumberOfPages; i++)
{ {
Count = g.Count(), PdfImportedPage page = pdf.GetImportedPage(reader, i + 1);
pdf.AddPage(page);
}
pdf.FreeReader(reader);
reader.Close();
};
}
DateMin = g.Min(t => t.DateTime), private static (string programFile, string programArg) getOptionsStartupProcess(string inputFileName, string resultFileDir)
DateMax = g.Max(t => t.DateTime), {
(string programFile, string programArg) startupOptions;
if (OperatingSystem.IsWindows())
{
startupOptions.programFile = "C:\\Program Files\\LibreOffice\\program\\soffice.exe";
startupOptions.programArg = $"-headless -convert-to pdf {inputFileName} --outdir {resultFileDir}";
return startupOptions;
}
if (OperatingSystem.IsLinux())
{
startupOptions.programFile = "/usr/bin/soffice";
startupOptions.programArg = $"--headless --convert-to pdf {inputFileName} --outdir {resultFileDir}";
return (startupOptions);
}
WellDepthMin = g.Min(t => t.WellDepth), throw new NotSupportedException("Вызов процесса в текущей операционной системе не возможен");
WellDepthMax = g.Max(t => t.WellDepth), }
Pressure = g.Average(t => t.Pressure), //public static void StartConvertProcess(string inputFileName, string outFileName)
PressureSp = g.Average(t => t.PressureSp), //{
PressureSpRotor = g.Average(t => t.PressureSpRotor), // using (Process pdfprocess = new Process())
PressureSpSlide = g.Average(t => t.PressureSpSlide), // {
PressureIdle = g.Average(t => t.PressureIdle), // pdfprocess.StartInfo.UseShellExecute = true;
PressureDeltaLimitMax = g.Average(t => t.PressureDeltaLimitMax), // //pdfprocess.StartInfo.LoadUserProfile = true;
// pdfprocess.StartInfo.FileName = "soffice";
// pdfprocess.StartInfo.Arguments = $"--headless --convert-to pdf {inputFileName} --outdir {outFileName}";
// pdfprocess.StartInfo.WorkingDirectory = "/usr/bin";
// pdfprocess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// pdfprocess.Start();
// if (!pdfprocess.WaitForExit(1000 * 60 * 1))
// {
// pdfprocess.Kill();
// }
// pdfprocess.Close();
// }
//}
private static async Task<string> StartConvertProcessAsync(string inputFileName, string outFileName)
{
AxialLoad = g.Average(t => t.AxialLoad), var progrAndArg = getOptionsStartupProcess(inputFileName, outFileName);
AxialLoadSp = g.Average(t => t.AxialLoadSp),
AxialLoadLimitMax = g.Average(t => t.AxialLoadLimitMax),
RotorTorque = g.Average(t => t.RotorTorque), //string outPath = "/home/eddie/Test/OutFiles";
RotorTorqueSp = g.Average(t => t.RotorTorqueSp), string outPath = "C:\\Test\\OutFiles";
RotorTorqueIdle = g.Average(t => t.RotorTorqueIdle), var result = Cli.Wrap("C:\\Program Files\\LibreOffice\\program\\soffice.exe")
.WithArguments($"-headless -convert-to pdf C:\\Test\\InFiles\\{inputFileName} -outdir {outPath}");
await result.ExecuteAsync();
var outFile = $"{outPath}\\{outFileName}";
return outFile;
}
BlockSpeed = g.Average(t => t.BlockSpeed), public static async Task GetConverteAndMergedFileAsync(IEnumerable<string> filesNames, string resultPath)
BlockSpeedSp = g.Average(t => t.BlockSpeedSp), {
BlockSpeedSpRotor = g.Average(t => t.BlockSpeedSpRotor), string[] fileExtension = { ".xlsx", ".xls", ".ods", ".odt", ".doc", ".docx", ".pdf" };
BlockSpeedSpSlide = g.Average(t => t.BlockSpeedSpSlide), //var filteredFilesNames = filesNames.Distinct();
}) var filteredFilesNames = filesNames
.Where(s => s.WellDepthMin != s.WellDepthMax) .Distinct()
.Where(s => s.Count > 3) .Where(f => fileExtension.Any(fe => f.ToLower().EndsWith(fe)))
.OrderBy(t => t.DateMin); .ToList();
var data = query.ToArray(); var listFileNames = filteredFilesNames
sw.Stop(); .ToList()
Console.WriteLine($"total time: {sw.ElapsedMilliseconds} ms"); .Select(o => new {
var count = data.Length; inputFile = o,
convertedFile = Path.ChangeExtension(o, ".pdf")
});
foreach (var excelFileName in listFileNames)
{
await StartConvertProcessAsync(excelFileName.inputFile, excelFileName.convertedFile);
Console.WriteLine($"convert file - {excelFileName.inputFile}");
Console.ReadLine();
}
Console.WriteLine("merged files");
Console.ReadLine(); Console.ReadLine();
DoMerged(listFileNames.Select(c => c.convertedFile), resultPath);
} }
} }
} }

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<PublishDir>C:\home\linux_test_test</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<SelfContained>true</SelfContained>
<PublishSingleFile>false</PublishSingleFile>
<PublishTrimmed>false</PublishTrimmed>
</PropertyGroup>
</Project>

25
ConsoleApp1/ReadMe.md Normal file
View File

@ -0,0 +1,25 @@
ТЕСТ РАБОТЫ КЛАССА КОНВЕРТИРУЮЩЕГО ЧАСТИ ПРОГРАММЫ БУРЕНИЯ В ЕДИНЫЙ ФАЙЛ ПЕЧАТНОГО ФОРМАТА (pdf)
Тест настроен под проверку на винде
для проверки необходимо создать иерархию папок (в корне С:\)
C:\Test\InFiles и C:\Test\OutFiles
Для простоты тестирования имена файлов подлежащих конвертации
"зашиты" в код
Для теста/работы на линукс машинах
на Linux сервер необходимо установить пакеты LibreOffice
sudo apt-get install libreoffice-writer libreoffice-calc
перед компиляцией необходимо изменить пути к файлам и папкам
например :
C:\Test\InFiles => /home/{папка юзера}/Test/InFiles
путь до бинарника LibreOffice:
Linux - /usr/bin/soffice
Windows - C:\Program Files\LibreOffice\program\soffice.exe