CS2-3: Добавлено получение отчетов с сервера и оповещение о прогрессе получения

This commit is contained in:
KharchenkoVV 2021-06-07 16:31:14 +05:00
parent 528e649813
commit 1bc374523a
11 changed files with 83 additions and 30 deletions

View File

@ -0,0 +1,17 @@
using System;
namespace AsbCloudApp.Data
{
public class ReportPropertiesDto
{
public int Id { get; set; }
public string Name { get; set; }
public string FullName { get; set; }
public int WellId { get; set; }
public DateTime Date { get; set; }
public DateTimeOffset Begin { get; set; }
public DateTimeOffset End { get; set; }
public int Step { get; set; }
public string Format { get; set; }
}
}

View File

@ -8,9 +8,9 @@ namespace AsbCloudApp.Services
{ {
string RootPath { get; } string RootPath { get; }
int CreateReport(int wellId, int stepSeconds, int format, DateTime begin, DateTime end, int CreateReport(int wellId, int stepSeconds, int format, DateTime begin, DateTime end,
Action<float, string, int > handleReportProgress); Action<float, string, int> handleReportProgress, Action<string, int> handleReportName);
int GetReportPagesCount(int wellId, DateTime begin, DateTime end, int stepSeconds, int format); int GetReportPagesCount(int wellId, DateTime begin, DateTime end, int stepSeconds, int format);
IEnumerable<string> GetExistingReportNames(int wellId, DateTime begin, DateTime end, int stepSeconds, int format); IEnumerable<ReportPropertiesDto> GetSuitableReports(int wellId, DateTime begin, DateTime end, int stepSeconds, int format);
DatesRangeDto GetReportsDatesRange(int wellId); DatesRangeDto GetReportsDatesRange(int wellId);
} }
} }

View File

@ -18,9 +18,9 @@ namespace AsbCloudDb.Model
[Column("date", TypeName = "timestamp with time zone")] [Column("date", TypeName = "timestamp with time zone")]
public DateTime Date { get; set; } public DateTime Date { get; set; }
[Column("begin", TypeName = "timestamp with time zone")] [Column("begin", TypeName = "timestamp with time zone")]
public DateTime Begin { get; set; } public DateTimeOffset Begin { get; set; }
[Column("end"), Comment("timestamp with time zone")] [Column("end"), Comment("timestamp with time zone")]
public DateTime End { get; set; } public DateTimeOffset End { get; set; }
[Column("step"), Comment("размер шага в секундах")] [Column("step"), Comment("размер шага в секундах")]
public int Step { get; set; } public int Step { get; set; }
[Column("format"), Comment("Формат отчета")] [Column("format"), Comment("Формат отчета")]

View File

@ -16,7 +16,9 @@ namespace AsbCloudInfrastructure.Services
if (action == null) if (action == null)
throw new ArgumentNullException(nameof(action)); throw new ArgumentNullException(nameof(action));
tasks.Enqueue(new(action, id++)); id++;
tasks.Enqueue(new(action, id));
return id; return id;
} }

View File

@ -30,7 +30,7 @@ namespace AsbCloudInfrastructure.Services
public string RootPath { get ; private set; } public string RootPath { get ; private set; }
public int CreateReport(int wellId, int stepSeconds, int format, DateTime begin, public int CreateReport(int wellId, int stepSeconds, int format, DateTime begin,
DateTime end, Action<float , string , int> progressHandler) DateTime end, Action<float , string , int> progressHandler, Action<string, int> reportNameHandler)
{ {
var newReportId = queue.EnqueueTask((id) => var newReportId = queue.EnqueueTask((id) =>
{ {
@ -44,6 +44,9 @@ namespace AsbCloudInfrastructure.Services
var newReportName = generator.Make(); var newReportName = generator.Make();
if(newReportName is not null) if(newReportName is not null)
{ {
var shorReportName = newReportName.Split(Path.DirectorySeparatorChar).Last();
reportNameHandler.Invoke(shorReportName, id);
var newReportProperties = new Report var newReportProperties = new Report
{ {
Name = newReportName, Name = newReportName,
@ -55,7 +58,7 @@ namespace AsbCloudInfrastructure.Services
Format = format Format = format
}; };
context.Reports.Add(newReportProperties); context.Reports.Add(newReportProperties);
db.SaveChanges(); context.SaveChanges();
} }
} }
}); });
@ -69,17 +72,24 @@ namespace AsbCloudInfrastructure.Services
return generator.GetPagesCount(); return generator.GetPagesCount();
} }
public IEnumerable<string> GetExistingReportNames(int wellId, DateTime begin, DateTime end, int stepSeconds, int format) public IEnumerable<ReportPropertiesDto> GetSuitableReports(int wellId, DateTime begin, DateTime end, int stepSeconds, int format)
{ {
var suitableReportsFromDb = GetSuitableReportNamesFromDb(wellId, begin, end, stepSeconds, format); var suitableReportsFromDb = GetSuitableReportsFromDb(wellId, begin, end, stepSeconds, format);
var reportsFolder = Path.Combine(RootPath, $"{wellId}"); var suitableReportsProperties = suitableReportsFromDb.Select(r => new ReportPropertiesDto
{
Id = r.Id,
Name = Path.GetFileName(r.Name),
FullName = r.Name,
WellId = r.WellId,
Date = r.Date,
Begin = r.Begin,
End = r.End,
Step = r.Step,
Format = r.Format == 0 ? ".pdf" : ".las"
});
var suitableReportNames = Directory.GetFiles(reportsFolder) return suitableReportsProperties;
.Select(Path.GetFileName)
.Where(name => suitableReportsFromDb.Contains(name));
return suitableReportNames;
} }
public DatesRangeDto GetReportsDatesRange(int wellId) public DatesRangeDto GetReportsDatesRange(int wellId)
@ -110,13 +120,16 @@ namespace AsbCloudInfrastructure.Services
} }
} }
private IEnumerable<string> GetSuitableReportNamesFromDb(int wellId, DateTime begin, DateTime end, int stepSeconds, int format) private IEnumerable<Report> GetSuitableReportsFromDb(int wellId, DateTime begin, DateTime end, int stepSeconds, int format)
{ {
var suitableReportsNames = (from r in db.Reports var suitableReportsNames = (from r in db.Reports
where r.WellId == wellId && r.Begin == begin where r.WellId == wellId
&& r.End == end && r.Step == stepSeconds && r.Begin >= begin
&& r.End <= end
&& r.Step <= stepSeconds
&& r.Format == format && r.Format == format
select r.Name).ToList(); select r).OrderBy(o => o.Date).Take(512).ToList();
return suitableReportsNames; return suitableReportsNames;
} }

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Services; using AsbCloudApp.Services;
@ -12,7 +13,7 @@ namespace AsbCloudWebApi.Controllers
/// <summary> /// <summary>
/// Контроллер отчетов по буровым скважинам /// Контроллер отчетов по буровым скважинам
/// </summary> /// </summary>
[Route("api/well")] [Route("api/report")]
[ApiController] [ApiController]
public class ReportController : ControllerBase public class ReportController : ControllerBase
{ {
@ -27,9 +28,22 @@ namespace AsbCloudWebApi.Controllers
this.reportsHubContext = reportsHubContext; this.reportsHubContext = reportsHubContext;
} }
private void HandleReportProgress (float progress, string operation, int id) => private void HandleReportProgressAsync (float progress, string operation, int id) =>
reportsHubContext.Clients.Group($"Report{id}").SendAsync(nameof(IReportHubClient.GetReportProgress), progress); Task.Run(()=> {
reportsHubContext.Clients.Group($"Report_{id}").SendAsync(
nameof(IReportHubClient.GetReportProgress),
new { Progress = progress, Operation = operation, ReportName = "" }
);
});
private void HandleReportNameAsync (string reportName, int groupId) =>
Task.Run(() => {
reportsHubContext.Clients.All.SendAsync(
nameof(IReportHubClient.GetReportProgress),
new { Progress = 100, Operation = "Отчет успешно создан", ReportName = reportName }
);
});
/// <summary> /// <summary>
/// Создает отчет по скважине с указанными параметрами /// Создает отчет по скважине с указанными параметрами
@ -54,7 +68,7 @@ namespace AsbCloudWebApi.Controllers
if (!wellService.CheckWellOwnership((int)idCustomer, wellId)) if (!wellService.CheckWellOwnership((int)idCustomer, wellId))
return Forbid(); return Forbid();
var id = reportService.CreateReport(wellId, stepSeconds, format, begin, end, HandleReportProgress); var id = reportService.CreateReport(wellId, stepSeconds, format, begin, end, HandleReportProgressAsync, HandleReportNameAsync);
return Ok(id); return Ok(id);
} }
@ -66,9 +80,9 @@ namespace AsbCloudWebApi.Controllers
/// <param name="reportName">имя запрашиваемого файла (отчета)</param> /// <param name="reportName">имя запрашиваемого файла (отчета)</param>
/// <returns>файловый поток с отчетом</returns> /// <returns>файловый поток с отчетом</returns>
[HttpGet] [HttpGet]
[Route("{wellId}/report")] [Route("{wellId}/{reportName}")]
[ProducesResponseType(typeof(FileStreamResult), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(FileStreamResult), (int)System.Net.HttpStatusCode.OK)]
public IActionResult GetReport([FromRoute] int wellId, [FromQuery] string reportName) public IActionResult GetReport([FromRoute] int wellId, string reportName)
{ {
try try
{ {
@ -80,6 +94,7 @@ namespace AsbCloudWebApi.Controllers
if (!wellService.CheckWellOwnership((int)idCustomer, wellId)) if (!wellService.CheckWellOwnership((int)idCustomer, wellId))
return Forbid(); return Forbid();
// TODO: словарь content typoв // TODO: словарь content typoв
var a = Path.Combine(reportService.RootPath, $"{wellId}", reportName);
return PhysicalFile(Path.Combine(reportService.RootPath, $"{wellId}", reportName), "application/pdf", reportName); return PhysicalFile(Path.Combine(reportService.RootPath, $"{wellId}", reportName), "application/pdf", reportName);
} }
catch (FileNotFoundException ex) catch (FileNotFoundException ex)
@ -104,7 +119,7 @@ namespace AsbCloudWebApi.Controllers
public IActionResult GetSuitableReportsNames(int wellId, int stepSeconds, int format, public IActionResult GetSuitableReportsNames(int wellId, int stepSeconds, int format,
DateTime begin = default, DateTime end = default) DateTime begin = default, DateTime end = default)
{ {
var suitableReportsNames = reportService.GetExistingReportNames(wellId, begin, end, stepSeconds, format); var suitableReportsNames = reportService.GetSuitableReports(wellId, begin, end, stepSeconds, format);
return Ok(suitableReportsNames); return Ok(suitableReportsNames);
} }

View File

@ -2,6 +2,6 @@
{ {
public interface IReportHubClient public interface IReportHubClient
{ {
float GetReportProgress(); float GetReportProgress(float progress);
} }
} }

View File

@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Authorization; using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
namespace AsbCloudWebApi.SignalR namespace AsbCloudWebApi.SignalR
@ -9,6 +10,10 @@ namespace AsbCloudWebApi.SignalR
[Authorize] [Authorize]
public class ReportsHub : Hub<IReportHubClient> public class ReportsHub : Hub<IReportHubClient>
{ {
public Task AddToGroup(string groupName)
=> Groups.AddToGroupAsync(Context.ConnectionId, groupName);
public Task RemoveFromGroup(string groupName)
=> Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
} }
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 965 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

View File

@ -3,4 +3,5 @@
Есть t_message для которой нет t_event | Ошибка синхронизации Есть t_message для которой нет t_event | Ошибка синхронизации
Есть t_telemetry для которой нет t_well | Кто-то начал новое бурение или исправил название старого Есть t_telemetry для которой нет t_well | Кто-то начал новое бурение или исправил название старого
2 t_telemetry с не уникальными uid 2 t_telemetry с не уникальными uid
Провалы в непрерывной t_data. Провалы в непрерывной t_data.
Сопоставление сущетсвующих на диске файлов-рапортов с теми, что хранятся в БД.