Отдельный work для создания диаграммы отчета

This commit is contained in:
Olga Nemt 2023-12-25 10:53:45 +05:00
parent 85d0aca9a8
commit 58edaf4204
5 changed files with 119 additions and 86 deletions

View File

@ -1,4 +1,5 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Requests;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading; using System.Threading;
@ -11,24 +12,16 @@ namespace AsbCloudApp.Services
/// </summary> /// </summary>
public interface IReportService public interface IReportService
{ {
/// <summary>
/// категория рапорта
/// </summary>
int ReportCategoryId { get; }
/// <summary> /// <summary>
/// Поставить рапорт в очередь на формирование /// Поставить рапорт в очередь на формирование
/// </summary> /// </summary>
/// <param name="idWell"></param> /// <param name="idWell"></param>
/// <param name="idUser"></param> /// <param name="idUser"></param>
/// <param name="stepSeconds"></param> /// <param name="request"></param>
/// <param name="format"></param>
/// <param name="begin"></param>
/// <param name="end"></param>
/// <param name="handleReportProgress"></param> /// <param name="handleReportProgress"></param>
/// <returns></returns> /// <returns></returns>
string EnqueueCreateReportWork(int idWell, int idUser, int stepSeconds, string EnqueueCreateReportWork(int idWell, int idUser, ReportParametersRequest request,
int format, DateTime begin, DateTime end,
Action<object, string> handleReportProgress); Action<object, string> handleReportProgress);
/// <summary> /// <summary>

View File

@ -0,0 +1,101 @@
using AsbCloudApp.Data;
using AsbCloudApp.Requests;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services;
using Mapster;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Background
{
/// <summary>
/// Класс для создания отчета
/// </summary>
internal class WorkToCreateReport : Work
{
private int idWell;
private DateTime begin;
private DateTime end;
private int stepSeconds;
private int format;
private int idUser;
private Action<object, string> progressHandler;
public WorkToCreateReport(int idWell, int idUser, ReportParametersRequest request, Action<object, string> progressHandler) : base("")
{
this.idWell = idWell;
this.idUser = idUser;
this.begin = request.Begin;
this.end = request.End;
this.stepSeconds = request.StepSeconds;
this.format = request.Format;
this.progressHandler = progressHandler;
Id = $"create report by wellid:{idWell} for userid:{idUser} requested at {DateTime.Now}";
}
protected override async Task Action(string id, IServiceProvider services, Action<string, double?> onProgress, CancellationToken token)
{
var wellService = services.GetRequiredService<IWellService>();
using var context = services.GetRequiredService<IAsbCloudDbContext>();
var fileService = services.GetRequiredService<FileService>();
var timezoneOffset = wellService.GetTimezone(idWell).Hours;
var beginRemote = begin.ToTimeZoneOffsetHours(timezoneOffset);
var endRemote = end.ToTimeZoneOffsetHours(timezoneOffset);
var beginUtc = begin.ToUtcDateTimeOffset(timezoneOffset);
var endUtc = end.ToUtcDateTimeOffset(timezoneOffset);
var tempDir = Path.Combine(Path.GetTempPath(), "report");
var generator = ReportService.GetReportGenerator(idWell, beginRemote, endRemote, stepSeconds, format, context);
var reportFileName = Path.Combine(tempDir, generator.GetReportDefaultFileName());
var totalPages = generator.GetPagesCount();
generator.OnProgress += (s, e) =>
{
var arg = e.Adapt<ReportProgressDto>();
onProgress(arg.Operation ?? string.Empty, arg.Progress);
progressHandler.Invoke(arg, id);
};
generator.Make(reportFileName);
var ReportCategoryId = context.FileCategories
.AsNoTracking()
.First(c => c.Name.Equals("Рапорт"))
.Id;
var fileInfo = (await fileService.MoveAsync(idWell, idUser, ReportCategoryId, reportFileName, reportFileName, token))!;
progressHandler.Invoke(new
{
Operation = "done",
Progress = 100f,
TotalPages = totalPages,
CurrentPage = totalPages,
file = fileInfo,
}, id);
var newReportProperties = new ReportProperty
{
IdWell = idWell,
IdFile = fileInfo.Id,
Begin = beginUtc,
End = endUtc,
Step = stepSeconds,
Format = format
};
context.ReportProperties.Add(newReportProperties);
context.SaveChanges();
}
}
}

View File

@ -1,14 +1,12 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Requests;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Background; using AsbCloudInfrastructure.Background;
using AsbSaubReport; using AsbSaubReport;
using Mapster;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -23,8 +21,6 @@ public class ReportService : IReportService
private readonly IWellService wellService; private readonly IWellService wellService;
private readonly BackgroundWorker backgroundWorkerService; private readonly BackgroundWorker backgroundWorkerService;
public int ReportCategoryId { get; private set; }
public ReportService(IAsbCloudDbContext db, public ReportService(IAsbCloudDbContext db,
ITelemetryService telemetryService, ITelemetryService telemetryService,
IWellService wellService, IWellService wellService,
@ -36,76 +32,21 @@ public class ReportService : IReportService
this.backgroundWorkerService = backgroundWorkerService; this.backgroundWorkerService = backgroundWorkerService;
this.telemetryService = telemetryService; this.telemetryService = telemetryService;
this.fileService = fileService; this.fileService = fileService;
ReportCategoryId = db.FileCategories
.AsNoTracking()
.First(c => c.Name.Equals("Рапорт"))
.Id;
} }
public string EnqueueCreateReportWork(int idWell, int idUser, int stepSeconds, int format, DateTime begin, public string EnqueueCreateReportWork(int idWell, int idUser, ReportParametersRequest request, Action<object, string> progressHandler)
DateTime end, Action<object, string> progressHandler)
{ {
var timezoneOffset = wellService.GetTimezone(idWell).Hours; var work = new WorkToCreateReport(idWell, idUser, request, progressHandler);
var beginUtc = begin.ToUtcDateTimeOffset(timezoneOffset);
var endUtc = end.ToUtcDateTimeOffset(timezoneOffset);
var beginRemote = begin.ToTimeZoneOffsetHours(timezoneOffset);
var endRemote = end.ToTimeZoneOffsetHours(timezoneOffset);
var workId = $"create report by wellid:{idWell} for userid:{idUser} requested at {DateTime.Now}";
var workAction = async (string id, IServiceProvider serviceProvider, Action<string, double?> onProgress, CancellationToken token) =>
{
using var context = serviceProvider.GetRequiredService<IAsbCloudDbContext>();
var fileService = serviceProvider.GetRequiredService<FileService>();
var tempDir = Path.Combine(Path.GetTempPath(), "report");
var generator = GetReportGenerator(idWell, beginRemote, endRemote, stepSeconds, format, context);
var reportFileName = Path.Combine(tempDir, generator.GetReportDefaultFileName());
var totalPages = generator.GetPagesCount();
generator.OnProgress += (s, e) =>
{
var arg = e.Adapt<ReportProgressDto>();
onProgress(arg.Operation?? string.Empty, arg.Progress);
progressHandler.Invoke(arg, id);
};
generator.Make(reportFileName);
var fileInfo = (await fileService.MoveAsync(idWell, idUser, ReportCategoryId, reportFileName, reportFileName, token))!;
progressHandler.Invoke(new
{
Operation = "done",
Progress = 100f,
TotalPages = totalPages,
CurrentPage = totalPages,
file = fileInfo,
}, id);
var newReportProperties = new ReportProperty
{
IdWell = idWell,
IdFile = fileInfo.Id,
Begin = beginUtc,
End = endUtc,
Step = stepSeconds,
Format = format
};
context.ReportProperties.Add(newReportProperties);
context.SaveChanges();
};
var work = Work.CreateByDelegate(workId, workAction);
work.OnErrorAsync = (message, exception, token) => Task.Run(() => progressHandler.Invoke(new work.OnErrorAsync = (message, exception, token) => Task.Run(() => progressHandler.Invoke(new
{ {
Operation = "error", Operation = "error",
Progress = 100f, Progress = 100f,
Message = string.IsNullOrEmpty(message) Message = string.IsNullOrEmpty(message)
? exception.Message ? exception.Message
: message, : message,
Exception = exception, Exception = exception,
}, workId) }, work.Id)
, token); , token);
backgroundWorkerService.Enqueue(work); backgroundWorkerService.Enqueue(work);
@ -114,8 +55,8 @@ public class ReportService : IReportService
{ {
Operation = "Ожидает начала в очереди.", Operation = "Ожидает начала в очереди.",
Progress = 0f, Progress = 0f,
}, workId); }, work.Id);
return workId; return work.Id;
} }
public int GetReportPagesCount(int idWell, DateTime begin, DateTime end, int stepSeconds, int format) public int GetReportPagesCount(int idWell, DateTime begin, DateTime end, int stepSeconds, int format)
@ -172,7 +113,7 @@ public class ReportService : IReportService
return dtos; return dtos;
} }
private static IReportGenerator GetReportGenerator(int idWell, DateTime begin, public static IReportGenerator GetReportGenerator(int idWell, DateTime begin,
DateTime end, int stepSeconds, int format, IAsbCloudDbContext context) DateTime end, int stepSeconds, int format, IAsbCloudDbContext context)
{ {
var dataSource = new ReportDataSourcePgCloud(context, idWell); var dataSource = new ReportDataSourcePgCloud(context, idWell);
@ -184,7 +125,7 @@ public class ReportService : IReportService
_ => new AsbSaubReportPdf.ReprotGeneratorPdf(dataSource), _ => new AsbSaubReportPdf.ReprotGeneratorPdf(dataSource),
}; };
if(begin == default || end == default) if (begin == default || end == default)
{ {
var analyzeResult = dataSource.Analyze(); var analyzeResult = dataSource.Analyze();
begin = begin == default ? analyzeResult.MinDate : begin; begin = begin == default ? analyzeResult.MinDate : begin;

View File

@ -65,8 +65,7 @@ namespace AsbCloudWebApi.Controllers
.GetReportProgress(progress, token); .GetReportProgress(progress, token);
}, token); }, token);
var id = reportService.EnqueueCreateReportWork(idWell, (int)idUser, var id = reportService.EnqueueCreateReportWork(idWell, (int)idUser, request, HandleReportProgressAsync);
request.StepSeconds, request.Format, request.Begin, request.End, HandleReportProgressAsync);
return Ok(id); return Ok(id);
} }

View File

@ -54,8 +54,7 @@ namespace AsbCloudWebApi.SignalR
.GetReportProgress(progress, CancellationToken.None); .GetReportProgress(progress, CancellationToken.None);
}, CancellationToken.None); }, CancellationToken.None);
var id = reportService.EnqueueCreateReportWork(idWell, (int)idUser, var id = reportService.EnqueueCreateReportWork(idWell, (int)idUser, request, HandleReportProgressAsync);
request.StepSeconds, request.Format, request.Begin, request.End, HandleReportProgressAsync);
} }
} }
} }