using AsbCloudApp.Data;
using AsbCloudApp.Data.DailyReport;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services;
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;
namespace AsbCloudWebApi.Controllers
{
///
/// Суточный рапорт
///
[Route("api/well/{idWell}/[controller]")]
[ApiController]
[Authorize]
public class DailyReportController : ControllerBase
{
private readonly IDailyReportService dailyReportService;
private readonly IWellService wellService;
private readonly IWellOperationRepository operationRepository;
public DailyReportController(
IDailyReportService dailyReportService,
IWellService wellService,
IWellOperationRepository operationRepository)
{
this.dailyReportService = dailyReportService;
this.wellService = wellService;
this.operationRepository = operationRepository;
}
///
/// Список наборов данных для формирования рапорта
///
///
///
///
///
///
[HttpGet]
[ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)]
public async Task GetListAsync(int idWell, DateOnly? begin, DateOnly? end, CancellationToken token)
{
var result = await dailyReportService.GetListAsync(idWell, begin, end, token);
return Ok(result);
}
///
/// Создание суточного рапорта
///
///
///
///
///
[HttpPost]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task AddAsync(int idWell, [Required] DateOnly startDate, CancellationToken token)
{
if (!await UserHasAccesToWellAsync(idWell, token))
return Forbid();
var idUser = User.GetUserId()!.Value;
var result = await dailyReportService.AddAsync(idWell, startDate, idUser, token);
return Ok(result);
}
///
/// Сохранение изменений набора данных для формирования рапорта (заголовок)
///
///
/// Дата без учета времени
///
///
///
[HttpPut("{date}/head")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public Task UpdateHeadAsync(int idWell, [Required] DateOnly date, [Required] HeadDto dto, CancellationToken token)
=> UpdateReportBlockAsync(idWell, date, dto, token);
///
/// Сохранение изменений набора данных для формирования рапорта (блок КНБК)
///
///
/// Дата без учета времени
///
///
///
[HttpPut("{date}/bha")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public Task UpdateBhaAsync(int idWell, [Required] DateOnly date, [Required] BhaDto dto, CancellationToken token)
=> UpdateReportBlockAsync(idWell, date, dto, token);
///
/// Сохранение изменений набора данных для формирования рапорта (безметражные работы)
///
///
/// Дата без учета времени
///
///
///
[HttpPut("{date}/noDrilling")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public Task UpdateNoDrillingAsync(int idWell, [Required] DateOnly date, [Required] NoDrillingDto dto, CancellationToken token)
=> UpdateReportBlockAsync(idWell, date, dto, token);
///
/// Сохранение изменений набора данных для формирования рапорта (САУБ)
///
///
/// Дата без учета времени
///
///
///
[HttpPut("{date}/saub")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public Task UpdateSaubAsync(int idWell, [Required] DateOnly date, [Required] SaubDto dto, CancellationToken token)
=> UpdateReportBlockAsync(idWell, date, dto, token);
///
/// Сохранение изменений набора данных для формирования рапорта (подпись)
///
///
/// Дата без учета времени
///
///
///
[HttpPut("{date}/sign")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public Task UpdateSignAsync(int idWell, [Required] DateOnly date, [Required] SignDto dto, CancellationToken token)
=> UpdateReportBlockAsync(idWell, date, dto, token);
///
/// Обновление блока суточного рапорта
///
/// ключ скважины
/// дата суточного рапорта
///
///
///
private async Task UpdateReportBlockAsync(int idWell, DateOnly date, ItemInfoDto dto, CancellationToken token)
{
if (!await UserHasAccesToWellAsync(idWell, token))
return Forbid();
dto.IdUser = User.GetUserId();
dto.LastUpdateDate = DateTimeOffset.Now;
var result = await dailyReportService.UpdateBlockAsync(idWell, date, dto, token);
return Ok(result);
}
///
/// Сформировать и скачать рапорт в формате excel
///
///
///
///
///
[HttpGet("{date}/excel")]
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
public async Task DownloadAsync(int idWell, DateOnly date, CancellationToken token)
{
if (!await UserHasAccesToWellAsync(idWell, token))
return Forbid();
var well = await wellService.GetOrDefaultAsync(idWell, token)
?? throw new ArgumentInvalidException($"Скважина c id:{idWell} не найдена", nameof(idWell));
var stream = await dailyReportService.MakeReportAsync(idWell, date, token);
if (stream is not null)
{
var fileName = $"Суточный рапорт по скважине {well.Caption} куст {well.Cluster}.xlsx";
return File(stream, "application/octet-stream", fileName);
}
else
return NoContent();
}
protected async Task UserHasAccesToWellAsync(int idWell, CancellationToken token)
{
var idCompany = User.GetCompanyId();
if (idCompany is not null &&
await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token)
.ConfigureAwait(false))
return true;
return false;
}
}
}