Добавление даты и ключа пользователя, внесшего изменения в блок суточного рапорта

This commit is contained in:
Olga Nemt 2023-03-21 15:55:03 +05:00
parent a97fd12b74
commit f1e0aaf3ae
18 changed files with 187 additions and 223 deletions

View File

@ -3,8 +3,8 @@
/// <summary>
/// блок КНБК
/// </summary>
public class BhaDto
{
public class BhaDto : ItemInfoDto
{
/// <summary>
/// КНБК описание
/// </summary>

View File

@ -4,8 +4,8 @@ namespace AsbCloudApp.Data.DailyReport
/// <summary>
/// блок заголовка
/// </summary>
public class HeadDto
{
public class HeadDto : ItemInfoDto
{
/// <summary>
/// название скважины
/// </summary>

View File

@ -0,0 +1,25 @@
using System;
namespace AsbCloudApp.Data.DailyReport
{
/// <summary>
/// хранение дополнительной информации о записи
/// </summary>
public class ItemInfoDto
{
/// <summary>
/// пользователь, внесший изменения
/// </summary>
public int? IdUser { get; set; }
/// <summary>
/// имя пользователя, внесшего изменения
/// </summary>
public string? UserName { get; set; }
/// <summary>
/// дата последнего обновления
/// </summary>
public DateTimeOffset? LastUpdateDate { get; set; }
}
}

View File

@ -3,7 +3,7 @@
/// <summary>
/// блок безметражные работы
/// </summary>
public class NoDrillingDto
public class NoDrillingDto : ItemInfoDto
{
/// <summary>
/// Нормативное время на одну операцию по подготовке ствола скважины к наращиванию

View File

@ -0,0 +1,13 @@
namespace AsbCloudApp.Data.DailyReport
{
/// <summary>
/// Статистика по операции
/// </summary>
public class OperationStatDto
{
/// <summary>
/// Глубина забоя
/// </summary>
public double Depth { get; set; }
}
}

View File

@ -5,7 +5,7 @@ namespace AsbCloudApp.Data.DailyReport
/// <summary>
/// блок САУБ
/// </summary>
public class SaubDto
public class SaubDto : ItemInfoDto
{
/// <summary>
/// Режимы бурения в роторе

View File

@ -3,8 +3,8 @@
/// <summary>
/// блок подписи
/// </summary>
public class SignDto
{
public class SignDto : ItemInfoDto
{
/// <summary>
/// ФИО Мастера буровой
/// </summary>

View File

@ -1,119 +1,17 @@
namespace AsbCloudApp.Data.DailyReport
using System.Collections.Generic;
namespace AsbCloudApp.Data.DailyReport
{
/// <summary>
/// блок баланса времени
/// </summary>
public class TimeBalanceDto
{
/// <summary>
/// Бурение
/// </summary>
public string Drilling { get; set; } = string.Empty;
/// <summary>
/// Промывка
/// </summary>
public string Flushing { get; set; } = string.Empty;
/// <summary>
/// Блок баланса времени
/// </summary>
public class TimeBalanceDto : ItemInfoDto
{
/// <summary>
/// Наращивание
/// Статистика по операциям
/// </summary>
public string Building { get; set; } = string.Empty;
/// <summary>
/// Проработка
/// </summary>
public string Elaboration { get; set; } = string.Empty;
/// <summary>
/// Расширка
/// </summary>
public string Extension { get; set; } = string.Empty;
/// <summary>
/// Ремонт
/// </summary>
public string Repair { get; set; } = string.Empty;
/// <summary>
/// КНБК
/// </summary>
public string Knbk { get; set; } = string.Empty;
/// <summary>
/// СПО
/// </summary>
public string Spo { get; set; } = string.Empty;
/// <summary>
/// ПЗР
/// </summary>
public string Pzr { get; set; } = string.Empty;
/// <summary>
/// ПВО
/// </summary>
public string Pvo { get; set; } = string.Empty;
/// <summary>
/// ПГР
/// </summary>
public string Pgr { get; set; } = string.Empty;
/// <summary>
/// ГИС
/// </summary>
public string Gis { get; set; } = string.Empty;
/// <summary>
/// ОЗЦ
/// </summary>
public string Ozc { get; set; } = string.Empty;
/// <summary>
/// Тех. работы
/// </summary>
public string EngineeringWorks { get; set; } = string.Empty;
/// <summary>
/// Снятие замера
/// </summary>
public string TakingMeasure { get; set; } = string.Empty;
/// <summary>
/// Цементирование
/// </summary>
public string Cementing { get; set; } = string.Empty;
/// <summary>
/// Простой
/// </summary>
public string Simple { get; set; } = string.Empty;
/// <summary>
/// НПВ
/// </summary>
public string Npv { get; set; } = string.Empty;
/// <summary>
/// Проработка перед наращиванием
/// </summary>
public string ElaborationBeforeBuilding { get; set; } = string.Empty;
/// <summary>
/// Шаблонировка перед наращиванием
/// </summary>
public string TemplatingBeforeBuilding { get; set; } = string.Empty;
/// <summary>
/// Промывка перед наращиванием
/// </summary>
public string FlushingBeforeBuilding { get; set; } = string.Empty;
/// <summary>
/// Статический замер телесистемы
/// </summary>
public string StaticSurveying { get; set; } = string.Empty;
public IEnumerable<OperationStatDto>? OperationsStat { get; set; }
}
}

View File

@ -22,23 +22,15 @@ namespace AsbCloudApp.Services
/// <returns></returns>
Task<IEnumerable<DailyReportDto>> GetListAsync(int idWell, DateTime? v1, DateTime? v2, CancellationToken cancellationToken);
/// <summary>
/// получить из БД или генерировать данные для суточного рапорта за указанную дату
/// </summary>
/// <param name="idWell"></param>
/// <param name="date"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<DailyReportDto> GetOrGenerateAsync(int idWell, DateTime date, CancellationToken token);
/// <summary>
/// Добавить новый рапорт
/// </summary>
/// <param name="idWell"></param>
/// <param name="startDate"></param>
/// <param name="idUser"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> AddAsync(int idWell, DateTime startDate, CancellationToken token = default);
Task<int> AddAsync(int idWell, DateTime startDate, int idUser, CancellationToken token = default);
/// <summary>
/// изменить данные для суточного рапорта
@ -62,12 +54,11 @@ namespace AsbCloudApp.Services
/// <summary>
/// изменить блок данных для суточного рапорта
/// </summary>
/// <typeparam name="Tdto"></typeparam>
/// <param name="idWell"></param>
/// <param name="date"></param>
/// <param name="startDate"></param>
/// <param name="dto"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> UpdateBlockAsync<Tdto>(int idWell, DateTime date, Tdto dto, CancellationToken token);
Task<int> UpdateBlockAsync(int idWell, DateTime startDate, ItemInfoDto dto, CancellationToken token);
}
}

View File

@ -1,6 +1,6 @@
namespace AsbCloudDb.Model.DailyReport
{
public class Bha
public class Bha : ItemInfo
{
/// <summary>
/// КНБК описание

View File

@ -1,7 +1,7 @@
using System;
namespace AsbCloudDb.Model.DailyReport
{
public class Head
public class Head : ItemInfo
{
/// <summary>
/// название скважины

View File

@ -0,0 +1,17 @@
using System;
namespace AsbCloudDb.Model
{
public class ItemInfo
{
/// <summary>
/// пользователь, внесший изменения
/// </summary>
public int? IdUser { get; set; }
/// <summary>
/// дата последнего обновления блока
/// </summary>
public DateTimeOffset? LastUpdateDate { get; set; }
}
}

View File

@ -1,6 +1,6 @@
namespace AsbCloudDb.Model.DailyReport
{
public class NoDrilling
public class NoDrilling : ItemInfo
{
/// <summary>
/// Нормативное время на одну операцию по подготовке ствола скважины к наращиванию

View File

@ -1,8 +1,6 @@
using System.Collections.Generic;
namespace AsbCloudDb.Model.DailyReport
namespace AsbCloudDb.Model.DailyReport
{
public class Saub
public class Saub : ItemInfo
{
/// <summary>
/// Режимы бурения в роторе
@ -98,7 +96,6 @@ namespace AsbCloudDb.Model.DailyReport
/// МСП
/// </summary>
public string MspSection { get; set; } = string.Empty;
}
}

View File

@ -1,6 +1,6 @@
namespace AsbCloudDb.Model.DailyReport
{
public class Sign
public class Sign : ItemInfo
{
/// <summary>
/// ФИО Мастера буровой

View File

@ -1,6 +1,6 @@
namespace AsbCloudDb.Model.DailyReport
{
public class TimeBalance
public class TimeBalance : ItemInfo
{
/// <summary>
/// Бурение

View File

@ -1,5 +1,8 @@
using AsbCloudApp.Data.DailyReport;
using AsbCloudApp.Data;
using AsbCloudApp.Data.DailyReport;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Repositories;
using AsbCloudApp.Requests;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudDb.Model.DailyReport;
@ -18,13 +21,22 @@ namespace AsbCloudInfrastructure.Services.DailyReport
public class DailyReportService : IDailyReportService
{
private readonly IAsbCloudDbContext db;
private readonly IUserRepository userRepository;
private readonly IWellOperationRepository wellOperationRepository;
private readonly IWellService wellService;
private readonly DailyReportMakerExcel dailyReportMaker = new DailyReportMakerExcel();
public DailyReportService(IAsbCloudDbContext db, IWellService wellService)
public DailyReportService(
IAsbCloudDbContext db,
IWellService wellService,
IUserRepository userRepository,
IWellOperationRepository wellOperationRepository)
{
this.db = db;
this.wellService = wellService;
this.userRepository = userRepository;
this.wellOperationRepository = wellOperationRepository;
}
public async Task<IEnumerable<DailyReportDto>> GetListAsync(int idWell, DateTime? begin, DateTime? end, CancellationToken token)
@ -54,21 +66,58 @@ namespace AsbCloudInfrastructure.Services.DailyReport
query = query.Where(d => d.StartDate <= endDateOnly);
}
var entities = await query
.OrderByDescending(e => e.StartDate)
.ToListAsync(token);
return entities.Select(r => Convert(r));
var entities = await query.OrderByDescending(e => e.StartDate).ToListAsync(token);
var request = new WellOperationRequest()
{
IdWell = idWell,
OperationType = WellOperation.IdOperationTypeFact,
};
var factOperations = await wellOperationRepository.GetAsync(request, token);
var dtos = entities.Select(Convert);
var result = await Task.WhenAll(dtos.Select(i => BindDataToDtoAsync(i, factOperations, token)));
return result;
}
public async Task<DailyReportDto> GetOrGenerateAsync(int idWell, DateTime date, CancellationToken token)
/// <summary>
/// Заполнение DTO-модели необходимыми данными
/// </summary>
/// <param name="dto"></param>
/// <param name="factOperations"></param>
/// <param name="token"></param>
/// <returns></returns>
private async Task<DailyReportDto> BindDataToDtoAsync(DailyReportDto dto, IEnumerable<WellOperationDto> factOperations, CancellationToken token)
{
var dateOnly = DateTime.SpecifyKind(date.Date, DateTimeKind.Utc);
var dailyReportDto = await GetOrDefaultAsync(idWell, dateOnly, token);
dailyReportDto ??= await MakeDefaultDailyReportAsync(idWell, dateOnly, token);
return dailyReportDto;
var blocks = new ItemInfoDto[] {
dto.Head,
dto.Bha,
dto.NoDrilling,
dto.Saub,
dto.Sign,
dto.TimeBalance
};
foreach (var block in blocks)
{
if (block.IdUser is not null)
{
var userDto = await userRepository.GetOrDefaultAsync(block.IdUser.Value, token);
if (userDto is not null)
block.UserName = string.Format("{0} {1} {2}", userDto.Surname, userDto.Name, userDto.Patronymic);
}
}
dto.TimeBalance.OperationsStat = (factOperations
.Where(o => DateOnly.FromDateTime(o.DateStart) == dto.StartDate)
.GroupBy(o => o.IdCategory)
.Select(g => new OperationStatDto() { Depth = g.Sum(o => o.DepthEnd - o.DepthStart) }));
return dto;
}
public async Task<int> AddAsync(int idWell, DateTime startDate, CancellationToken token = default)
public async Task<int> AddAsync(int idWell, DateTime startDate, int idUser, CancellationToken token = default)
{
var well = wellService.GetOrDefault(idWell);
if (well is null || well.Timezone is null)
@ -97,6 +146,8 @@ namespace AsbCloudInfrastructure.Services.DailyReport
ClusterName = well?.Cluster ?? String.Empty,
Customer = customer?.Caption ?? String.Empty,
Contractor = contractor?.Caption ?? String.Empty,
IdUser = idUser,
LastUpdateDate = DateTimeOffset.Now,
}
}
};
@ -123,14 +174,15 @@ namespace AsbCloudInfrastructure.Services.DailyReport
return result;
}
public async Task<int> UpdateBlockAsync<Tdto>(int idWell, DateTime date, Tdto dto, CancellationToken token)
public async Task<int> UpdateBlockAsync(int idWell, DateTime startDate, ItemInfoDto dto, CancellationToken token)
{
var startDateOnly = DateOnly.FromDateTime(date);
var startDateOnly = DateOnly.FromDateTime(startDate);
var entity = await db.DailyReports.FirstOrDefaultAsync(r => r.IdWell == idWell && r.StartDate == startDateOnly, token);
if (entity is null)
return 0;
dto.LastUpdateDate = DateTimeOffset.Now;
if (dto is HeadDto headDto)
entity.Info.Head = headDto.Adapt<Head>();
if (dto is BhaDto bhaDto)
@ -174,39 +226,6 @@ namespace AsbCloudInfrastructure.Services.DailyReport
return dto;
}
private async Task<DailyReportDto> MakeDefaultDailyReportAsync(int idWell, DateTime date, CancellationToken token)
{
var well = await wellService.GetOrDefaultAsync(idWell, token);
var dto = new DailyReportDto()
{
Head = new HeadDto()
{
ReportDate = date.Date,
WellName = well?.Caption ?? "",
ClusterName = well?.Cluster ?? "",
},
Bha = await GetPrevOrNewBhaAsync(idWell, date, token)
};
return dto;
}
private async Task<BhaDto> GetPrevOrNewBhaAsync(int idWell, DateTime date, CancellationToken token)
{
var dateOffset = date.Date;
var entity = await db.DailyReports
.Where(x => x.IdWell == idWell)
.OrderByDescending(x => x.StartDate)
.FirstOrDefaultAsync(r => r.StartDate.Year <= dateOffset.Year &&
r.StartDate.DayOfYear <= dateOffset.DayOfYear, token);
if (entity is null)
return new BhaDto();
var dto = Convert(entity);
return dto.Bha;
}
private static DailyReportDto Convert(AsbCloudDb.Model.DailyReport.DailyReport entity)
{
var dto = entity.Info.Adapt<DailyReportDto>();

View File

@ -1,4 +1,5 @@
using AsbCloudApp.Data.DailyReport;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@ -20,11 +21,16 @@ namespace AsbCloudWebApi.Controllers
{
private readonly IDailyReportService dailyReportService;
private readonly IWellService wellService;
private readonly IWellOperationRepository operationRepository;
public DailyReportController(IDailyReportService dailyReportService, IWellService wellService)
public DailyReportController(
IDailyReportService dailyReportService,
IWellService wellService,
IWellOperationRepository operationRepository)
{
this.dailyReportService = dailyReportService;
this.wellService = wellService;
this.operationRepository = operationRepository;
}
/// <summary>
@ -44,22 +50,6 @@ namespace AsbCloudWebApi.Controllers
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>
@ -72,9 +62,13 @@ namespace AsbCloudWebApi.Controllers
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> AddAsync(int idWell, [Required] DateTime startDate, CancellationToken token = default)
{
var idUser = User.GetUserId();
if (idUser is null)
return Forbid();
try
{
var result = await dailyReportService.AddAsync(idWell, startDate, token);
var result = await dailyReportService.AddAsync(idWell, startDate, (int)idUser, token);
return Ok(result);
}
catch (Exception ex)
@ -97,6 +91,11 @@ namespace AsbCloudWebApi.Controllers
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> UpdateHeadAsync(int idWell, [Required] DateTime date, [Required] HeadDto dto, CancellationToken token = default)
{
var idUser = User.GetUserId();
if (idUser is null)
return Forbid();
dto.IdUser = idUser;
var result = await dailyReportService.UpdateBlockAsync(idWell, date, dto, token);
return Ok(result);
}
@ -113,6 +112,11 @@ namespace AsbCloudWebApi.Controllers
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> UpdateBhaAsync(int idWell, [Required] DateTime date, [Required] BhaDto dto, CancellationToken token = default)
{
var idUser = User.GetUserId();
if (idUser is null)
return Forbid();
dto.IdUser = idUser;
var result = await dailyReportService.UpdateBlockAsync(idWell, date, dto, token);
return Ok(result);
}
@ -129,25 +133,15 @@ namespace AsbCloudWebApi.Controllers
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> UpdateNoDrillingAsync(int idWell, [Required] DateTime date, [Required] NoDrillingDto dto, CancellationToken token = default)
{
var idUser = User.GetUserId();
if (idUser is null)
return Forbid();
dto.IdUser = idUser;
var result = await dailyReportService.UpdateBlockAsync(idWell, date, 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}/timeBalance")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> UpdateTimeBalanceAsync(int idWell, [Required] DateTime date, [Required] TimeBalanceDto dto, CancellationToken token = default)
{
var result = await dailyReportService.UpdateBlockAsync(idWell, date, dto, token);
return Ok(result);
}
/// <summary>
/// Сохранение изменений набора данных для формирования рапорта (САУБ)
@ -161,6 +155,11 @@ namespace AsbCloudWebApi.Controllers
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> UpdateSaubAsync(int idWell, [Required] DateTime date, [Required] SaubDto dto, CancellationToken token = default)
{
var idUser = User.GetUserId();
if (idUser is null)
return Forbid();
dto.IdUser = idUser;
var result = await dailyReportService.UpdateBlockAsync(idWell, date, dto, token);
return Ok(result);
}
@ -177,6 +176,11 @@ namespace AsbCloudWebApi.Controllers
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> UpdateSignAsync(int idWell, [Required] DateTime date, [Required] SignDto dto, CancellationToken token = default)
{
var idUser = User.GetUserId();
if (idUser is null)
return Forbid();
dto.IdUser = idUser;
var result = await dailyReportService.UpdateBlockAsync(idWell, date, dto, token);
return Ok(result);
}