CS2-50: All controllers and services are made async

This commit is contained in:
KharchenkoVV 2021-08-11 16:54:42 +05:00
parent 4c4048865c
commit f13b757a84
35 changed files with 417 additions and 244 deletions

View File

@ -1,6 +1,7 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudApp.Services namespace AsbCloudApp.Services
@ -9,14 +10,19 @@ namespace AsbCloudApp.Services
{ {
Task<PaginationContainer<TelemetryOperationDto>> GetOperationsByWellAsync(int idWell, Task<PaginationContainer<TelemetryOperationDto>> GetOperationsByWellAsync(int idWell,
IEnumerable<int> categoryids = default, DateTime begin = default, IEnumerable<int> categoryids = default, DateTime begin = default,
DateTime end = default, int skip = 0, int take = 32); DateTime end = default, int skip = 0, int take = 32,
Task<IEnumerable<WellDepthToDayDto>> GetWellDepthToDayAsync(int idWell); CancellationToken token = default);
Task<IEnumerable<WellDepthToDayDto>> GetWellDepthToDayAsync(int idWell,
CancellationToken token = default);
Task<IEnumerable<WellDepthToIntervalDto>> GetWellDepthToIntervalAsync(int idWell, Task<IEnumerable<WellDepthToIntervalDto>> GetWellDepthToIntervalAsync(int idWell,
int intervalHoursTimestamp, int workBeginTimestamp); int intervalHoursTimestamp, int workBeginTimestamp,
CancellationToken token = default);
Task<IEnumerable<TelemetryOperationDurationDto>> GetOperationsSummaryAsync(int idWell, Task<IEnumerable<TelemetryOperationDurationDto>> GetOperationsSummaryAsync(int idWell,
DateTime begin = default, DateTime end = default); DateTime begin = default, DateTime end = default,
CancellationToken token = default);
Task<IEnumerable<TelemetryOperationInfoDto>> GetOperationsToIntervalAsync(int idWell, Task<IEnumerable<TelemetryOperationInfoDto>> GetOperationsToIntervalAsync(int idWell,
int intervalHoursTimestamp, int workBeginTimestamp); int intervalHoursTimestamp, int workBeginTimestamp,
CancellationToken token = default);
void SaveAnalytics(DataSaubBaseDto dataSaub); void SaveAnalytics(DataSaubBaseDto dataSaub);
} }
} }

View File

@ -1,5 +1,7 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using System.Security.Claims; using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Services namespace AsbCloudApp.Services
{ {
@ -7,7 +9,8 @@ namespace AsbCloudApp.Services
{ {
int ChangePassword(int idUser, string newPassword); int ChangePassword(int idUser, string newPassword);
int ChangePassword(string userLogin, string newPassword); int ChangePassword(string userLogin, string newPassword);
UserTokenDto Login(string login, string password); Task<UserTokenDto> LoginAsync(string login,
string password, CancellationToken token = default);
string Refresh(ClaimsPrincipal user); string Refresh(ClaimsPrincipal user);
int Register(UserDto userDto); int Register(UserDto userDto);

View File

@ -1,15 +1,21 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudApp.Services namespace AsbCloudApp.Services
{ {
public interface IClusterService public interface IClusterService
{ {
Task<IEnumerable<DepositDto>> GetDepositsAsync(int idCompany); Task<IEnumerable<DepositDto>> GetDepositsAsync(int idCompany,
Task<IEnumerable<ClusterDto>> GetClustersAsync(int idCompany, int depositId); CancellationToken token );
Task<IEnumerable<ClusterDto>> GetClustersAsync(int idCompany); Task<IEnumerable<ClusterDto>> GetClustersAsync(int idCompany,
Task<IEnumerable<WellDto>> GetWellsAsync(int idCompany, int clusterId); int depositId, CancellationToken token );
Task<ClusterStatDto> GetStatAsync(int idCompany, int clusterId); Task<IEnumerable<ClusterDto>> GetClustersAsync(int idCompany,
CancellationToken token);
Task<IEnumerable<WellDto>> GetWellsAsync(int idCompany,
int clusterId, CancellationToken token);
Task<ClusterStatDto> GetStatAsync(int idCompany,
int clusterId, CancellationToken token);
} }
} }

View File

@ -1,14 +1,20 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Services namespace AsbCloudApp.Services
{ {
public interface IDataService public interface IDataService
{ {
IEnumerable<DataSaubBaseDto> Get(int idWell, DateTime dateBegin = default, double intervalSec = 600d, int approxPointsCount = 1024); Task<IEnumerable<DataSaubBaseDto>> GetAsync(int idWell, DateTime dateBegin = default,
double intervalSec = 600d, int approxPointsCount = 1024,
CancellationToken token = default);
void UpdateData(string uid, IEnumerable<DataSaubBaseDto> dtos); Task UpdateDataAsync(string uid, IEnumerable<DataSaubBaseDto> dtos,
DatesRangeDto GetDataDatesRange(int idWell); CancellationToken token);
Task<DatesRangeDto> GetDataDatesRangeAsync(int idWell,
CancellationToken token);
} }
} }

View File

@ -1,10 +1,13 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Services namespace AsbCloudApp.Services
{ {
public interface IEventService public interface IEventService
{ {
void Upsert(string uid, IEnumerable<EventDto> dtos); Task UpsertAsync(string uid, IEnumerable<EventDto> dtos,
CancellationToken token = default);
} }
} }

View File

@ -1,6 +1,8 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Services namespace AsbCloudApp.Services
{ {
@ -11,9 +13,9 @@ namespace AsbCloudApp.Services
int idCategory, IEnumerable<(string fileName, int idWell, int idCategory, int idCategory, IEnumerable<(string fileName, int idWell, int idCategory,
DateTime date, int idUser)> filesInfo); DateTime date, int idUser)> filesInfo);
PaginationContainer<FilePropertiesDto> GetFilesInfo(int idWell, Task<PaginationContainer<FilePropertiesDto>> GetFilesInfoAsync(int idWell,
int idCategory, DateTime begin, DateTime end, int idCategory, DateTime begin, DateTime end,
int skip, int take); int skip, int take, CancellationToken token = default);
(int Id, string Name, int IdCategory)? GetFileInfo(int fileId); (int Id, string Name, int IdCategory)? GetFileInfo(int fileId);
} }

View File

@ -1,8 +1,13 @@
namespace AsbCloudApp.Services using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Services
{ {
public interface ILastDataService<Tdto> public interface ILastDataService<Tdto>
{ {
Tdto Get(int idWell, int idCategory); Task<Tdto> GetAsync(int idWell, int idCategory,
void Upsert(int idWell, int idCategory, Tdto value); CancellationToken token);
Task UpsertAsync(int idWell, int idCategory, Tdto value,
CancellationToken token);
} }
} }

View File

@ -1,13 +1,20 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Services namespace AsbCloudApp.Services
{ {
public interface IMessageService public interface IMessageService
{ {
PaginationContainer<MessageDto> GetMessages(int idWell, IEnumerable<int> categoryids = null, DateTime begin = default, DateTime end = default, string searchString = default, int skip = 0, int take = 32); Task<PaginationContainer<MessageDto>> GetMessagesAsync(int idWell,
DatesRangeDto GetMessagesDatesRange(int idWell); IEnumerable<int> categoryids = null, DateTime begin = default,
void Insert(string uid, IEnumerable<TelemetryMessageDto> dtos); DateTime end = default, string searchString = default,
int skip = 0, int take = 32, CancellationToken token = default);
Task<DatesRangeDto> GetMessagesDatesRangeAsync(int idWell,
CancellationToken token = default);
Task InsertAsync(string uid, IEnumerable<TelemetryMessageDto> dtos,
CancellationToken token);
} }
} }

View File

@ -1,6 +1,8 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudApp.Services namespace AsbCloudApp.Services
{ {
@ -13,8 +15,10 @@ namespace AsbCloudApp.Services
Action<string, int> handleReportName); Action<string, int> handleReportName);
int GetReportPagesCount(int idWell, DateTime begin, DateTime end, int GetReportPagesCount(int idWell, DateTime begin, DateTime end,
int stepSeconds, int format); int stepSeconds, int format);
IEnumerable<ReportPropertiesDto> GetSuitableReports(int idWell, Task<IEnumerable<ReportPropertiesDto>> GetSuitableReportsAsync(int idWell,
DateTime begin, DateTime end, int stepSeconds, int format); DateTime begin, DateTime end, int stepSeconds, int format,
DatesRangeDto GetReportsDatesRange(int idWell); CancellationToken token);
Task<DatesRangeDto> GetReportsDatesRangeAsync(int idWell,
CancellationToken token);
} }
} }

View File

@ -1,14 +1,15 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudApp.Services namespace AsbCloudApp.Services
{ {
public interface IWellService public interface IWellService
{ {
Task<IEnumerable<WellDto>> GetWellsByCompanyAsync(int idCompany); Task<IEnumerable<WellDto>> GetWellsByCompanyAsync(int idCompany, CancellationToken token);
Task<IEnumerable<WellDto>> GetTransmittingWellsAsync(int idCompany); Task<IEnumerable<WellDto>> GetTransmittingWellsAsync(int idCompany, CancellationToken token);
Task<bool> IsCompanyInvolvedInWellAsync(int idCompany, int idWell); Task<bool> IsCompanyInvolvedInWellAsync(int idCompany, int idWell, CancellationToken token);
Task<IEnumerable<WellOperationDto>> GetOperationsAsync(int idWell); Task<IEnumerable<WellOperationDto>> GetOperationsAsync(int idWell, CancellationToken token);
} }
} }

View File

@ -471,19 +471,20 @@ namespace AsbCloudDb.Model
.Include(e => e.Company) .Include(e => e.Company)
.Where(e => e.Login == login); .Where(e => e.Login == login);
public (DateTime From, DateTime To) GetDatesRange<TEntity>(int idTelemetry) public async Task<(DateTime From, DateTime To)> GetDatesRangeAsync<TEntity>(int idTelemetry,
CancellationToken token = default)
where TEntity : class, IIdTelemetryDate where TEntity : class, IIdTelemetryDate
{ {
var dbSet = Set<TEntity>(); var dbSet = Set<TEntity>();
var datesRange = (from m in dbSet var datesRange = await (from m in dbSet
where m.IdTelemetry == idTelemetry where m.IdTelemetry == idTelemetry
group m by m.IdTelemetry into g group m by m.IdTelemetry into g
select new select new
{ {
From = g.Min(d => d.Date), From = g.Min(d => d.Date),
To = g.Max(d => d.Date) To = g.Max(d => d.Date)
}).AsNoTracking().FirstOrDefault(); }).AsNoTracking().FirstOrDefaultAsync(token);
if (datesRange is null) if (datesRange is null)
return (DateTime.MinValue, DateTime.MaxValue); return (DateTime.MinValue, DateTime.MaxValue);
@ -492,7 +493,7 @@ namespace AsbCloudDb.Model
} }
public async Task<IEnumerable<(double? MinDepth, double? MaxDepth, DateTime BeginPeriodDate)>> GetDepthToIntervalAsync(int telemetryId, public async Task<IEnumerable<(double? MinDepth, double? MaxDepth, DateTime BeginPeriodDate)>> GetDepthToIntervalAsync(int telemetryId,
int intervalHoursTimestamp, int workStartTimestamp, double timezoneOffset) int intervalHoursTimestamp, int workStartTimestamp, double timezoneOffset, CancellationToken token)
{ {
//TODO: Сменить на LINQ группирование //TODO: Сменить на LINQ группирование
using var command = Database.GetDbConnection().CreateCommand(); using var command = Database.GetDbConnection().CreateCommand();
@ -503,7 +504,7 @@ namespace AsbCloudDb.Model
GROUP BY floor((extract(epoch from t.date) - {workStartTimestamp} + {timezoneOffset}) / {intervalHoursTimestamp});"; GROUP BY floor((extract(epoch from t.date) - {workStartTimestamp} + {timezoneOffset}) / {intervalHoursTimestamp});";
Database.OpenConnection(); Database.OpenConnection();
using var reader = await command.ExecuteReaderAsync(); using var reader = await command.ExecuteReaderAsync(token);
IEnumerable<(double? MinDepth, double? MaxDepth, DateTime BeginPeriodDate)> GetResult(DbDataReader rd) IEnumerable<(double? MinDepth, double? MaxDepth, DateTime BeginPeriodDate)> GetResult(DbDataReader rd)
{ {

View File

@ -40,9 +40,9 @@ namespace AsbCloudDb.Model
IQueryable<Well> GetWellsForCompany(int idCompany); IQueryable<Well> GetWellsForCompany(int idCompany);
IQueryable<User> GetUsersByLogin(string login); IQueryable<User> GetUsersByLogin(string login);
(DateTime From, DateTime To) GetDatesRange<T>(int idTelemetry) where T : class, IIdTelemetryDate; Task<(DateTime From, DateTime To)> GetDatesRangeAsync<T>(int idTelemetry, CancellationToken token) where T : class, IIdTelemetryDate;
Task<IEnumerable<(double? MinDepth, double? MaxDepth, DateTime BeginPeriodDate)>> GetDepthToIntervalAsync(int telemetryId, Task<IEnumerable<(double? MinDepth, double? MaxDepth, DateTime BeginPeriodDate)>> GetDepthToIntervalAsync(int telemetryId,
int intervalHoursTimestamp, int workStartTimestamp, double timezoneOffset); int intervalHoursTimestamp, int workStartTimestamp, double timezoneOffset, CancellationToken token);
Task<int> CreatePartitionAsync<TEntity>(string propertyName, int id, CancellationToken token = default) where TEntity : class; Task<int> CreatePartitionAsync<TEntity>(string propertyName, int id, CancellationToken token = default) where TEntity : class;
} }
} }

View File

@ -7,6 +7,7 @@ using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services namespace AsbCloudInfrastructure.Services
@ -31,7 +32,7 @@ namespace AsbCloudInfrastructure.Services
operationDetectorService = new TelemetryOperationDetectorService(operations); operationDetectorService = new TelemetryOperationDetectorService(operations);
} }
public async Task<IEnumerable<WellDepthToDayDto>> GetWellDepthToDayAsync(int idWell) public async Task<IEnumerable<WellDepthToDayDto>> GetWellDepthToDayAsync(int idWell, CancellationToken token = default)
{ {
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell); var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell);
@ -58,11 +59,11 @@ namespace AsbCloudInfrastructure.Services
WellDepth = d.WellDepth ?? 0.0, WellDepth = d.WellDepth ?? 0.0,
BitDepth = d.BitDepth ?? 0.0, BitDepth = d.BitDepth ?? 0.0,
Date = d.Date Date = d.Date
}).AsNoTracking().ToListAsync(); }).AsNoTracking().ToListAsync(token);
} }
public async Task<IEnumerable<WellDepthToIntervalDto>> GetWellDepthToIntervalAsync(int idWell, public async Task<IEnumerable<WellDepthToIntervalDto>> GetWellDepthToIntervalAsync(int idWell,
int intervalSeconds, int workBeginSeconds) int intervalSeconds, int workBeginSeconds, CancellationToken token = default)
{ {
intervalSeconds = intervalSeconds == 0 ? 86400 : intervalSeconds; intervalSeconds = intervalSeconds == 0 ? 86400 : intervalSeconds;
@ -74,7 +75,7 @@ namespace AsbCloudInfrastructure.Services
var timezoneOffset = telemetryService.GetTimezoneOffsetByTelemetryId((int)telemetryId); var timezoneOffset = telemetryService.GetTimezoneOffsetByTelemetryId((int)telemetryId);
var drillingPeriodsInfo = await db.GetDepthToIntervalAsync((int)telemetryId, intervalSeconds, var drillingPeriodsInfo = await db.GetDepthToIntervalAsync((int)telemetryId, intervalSeconds,
workBeginSeconds, timezoneOffset); workBeginSeconds, timezoneOffset, token);
var wellDepthToIntervalData = drillingPeriodsInfo.Select(d => new WellDepthToIntervalDto var wellDepthToIntervalData = drillingPeriodsInfo.Select(d => new WellDepthToIntervalDto
{ {
@ -87,7 +88,7 @@ namespace AsbCloudInfrastructure.Services
public async Task<PaginationContainer<TelemetryOperationDto>> GetOperationsByWellAsync(int idWell, public async Task<PaginationContainer<TelemetryOperationDto>> GetOperationsByWellAsync(int idWell,
IEnumerable<int> categoryIds = default, DateTime begin = default, IEnumerable<int> categoryIds = default, DateTime begin = default,
DateTime end = default, int skip = 0, int take = 32) DateTime end = default, int skip = 0, int take = 32, CancellationToken token = default)
{ {
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell); var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell);
@ -121,12 +122,14 @@ namespace AsbCloudInfrastructure.Services
operations = operations.Where(m => (m.UnixDate + m.DurationSec) <= unixEnd); operations = operations.Where(m => (m.UnixDate + m.DurationSec) <= unixEnd);
} }
result.Count = operations.Count(); result.Count = await operations.CountAsync(token);
if (skip > 0) if (skip > 0)
operations = operations.Skip(skip); operations = operations.Skip(skip);
var operationsList = await operations.Take(take).AsNoTracking().ToListAsync(); var operationsList = await operations.Take(take)
.AsNoTracking()
.ToListAsync(token);
if (operationsList.Count == 0) if (operationsList.Count == 0)
return result; return result;
@ -150,7 +153,7 @@ namespace AsbCloudInfrastructure.Services
} }
public async Task<IEnumerable<TelemetryOperationDurationDto>> GetOperationsSummaryAsync(int idWell, public async Task<IEnumerable<TelemetryOperationDurationDto>> GetOperationsSummaryAsync(int idWell,
DateTime begin = default, DateTime end = default) DateTime begin = default, DateTime end = default, CancellationToken token = default)
{ {
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell); var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell);
@ -160,23 +163,21 @@ namespace AsbCloudInfrastructure.Services
var unixBegin = (begin - new DateTime(1970, 1, 1)).TotalSeconds; var unixBegin = (begin - new DateTime(1970, 1, 1)).TotalSeconds;
var unixEnd = (end - new DateTime(1970, 1, 1)).TotalSeconds; var unixEnd = (end - new DateTime(1970, 1, 1)).TotalSeconds;
var operations = await (from a in db.TelemetryAnalysis return await (from a in db.TelemetryAnalysis
where a.IdTelemetry == telemetryId && where a.IdTelemetry == telemetryId &&
a.UnixDate > unixBegin && a.UnixDate < unixEnd a.UnixDate > unixBegin && a.UnixDate < unixEnd
join o in db.TelemetryOperations on a.IdOperation equals o.Id join o in db.TelemetryOperations on a.IdOperation equals o.Id
group a by new { a.IdOperation, o.Name } into g group a by new { a.IdOperation, o.Name } into g
select new TelemetryOperationDurationDto select new TelemetryOperationDurationDto
{ {
OperationName = g.Key.Name, OperationName = g.Key.Name,
Duration = g.Where(g => g.DurationSec > 0) Duration = g.Where(g => g.DurationSec > 0)
.Sum(a => a.DurationSec) .Sum(a => a.DurationSec)
}).AsNoTracking().ToListAsync(); }).AsNoTracking().ToListAsync(token);
return operations;
} }
public async Task<IEnumerable<TelemetryOperationInfoDto>> GetOperationsToIntervalAsync(int idWell, public async Task<IEnumerable<TelemetryOperationInfoDto>> GetOperationsToIntervalAsync(int idWell,
int intervalSeconds, int workBeginSeconds) int intervalSeconds, int workBeginSeconds, CancellationToken token = default)
{ {
intervalSeconds = intervalSeconds == 0 ? 86400 : intervalSeconds; intervalSeconds = intervalSeconds == 0 ? 86400 : intervalSeconds;
@ -201,7 +202,7 @@ namespace AsbCloudInfrastructure.Services
IntervalStart = g.Min(d => d.UnixDate), IntervalStart = g.Min(d => d.UnixDate),
OperationName = g.Key.Name, OperationName = g.Key.Name,
OperationsDuration = g.Sum(an => an.DurationSec) OperationsDuration = g.Sum(an => an.DurationSec)
}).AsNoTracking().ToListAsync(); }).AsNoTracking().ToListAsync(token);
var operationsGroupedByInterval = operations.GroupBy(op => op.IntervalStart) var operationsGroupedByInterval = operations.GroupBy(op => op.IntervalStart)
.Select(o => new TelemetryOperationInfoDto .Select(o => new TelemetryOperationInfoDto

View File

@ -10,6 +10,8 @@ using System.Security.Claims;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services namespace AsbCloudInfrastructure.Services
{ {
@ -36,9 +38,10 @@ namespace AsbCloudInfrastructure.Services
rnd = new Random((int)(DateTime.Now.Ticks % 2147480161)); rnd = new Random((int)(DateTime.Now.Ticks % 2147480161));
} }
public UserTokenDto Login(string login, string password) public async Task<UserTokenDto> LoginAsync(string login, string password,
CancellationToken token = default)
{ {
var identity = GetClaimsUser(login, password); var identity = await GetClaimsUserAsync(login, password, token);
if (identity == default) if (identity == default)
return null; return null;
@ -135,12 +138,13 @@ namespace AsbCloudInfrastructure.Services
return new JwtSecurityTokenHandler().WriteToken(jwt); return new JwtSecurityTokenHandler().WriteToken(jwt);
} }
private (ClaimsIdentity Identity, User User) GetClaimsUser(string login, string password) private async Task<(ClaimsIdentity Identity, User User)> GetClaimsUserAsync(string login,
string password, CancellationToken token = default)
{ {
var user = db var user = await db
.GetUsersByLogin(login) .GetUsersByLogin(login)
.AsNoTracking() .AsNoTracking()
.FirstOrDefault(); .FirstOrDefaultAsync(token);
if (user is null) if (user is null)
return default; return default;

View File

@ -4,6 +4,7 @@ using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services namespace AsbCloudInfrastructure.Services
@ -17,7 +18,8 @@ namespace AsbCloudInfrastructure.Services
this.db = db; this.db = db;
} }
public async Task<IEnumerable<DepositDto>> GetDepositsAsync(int idCompany) public async Task<IEnumerable<DepositDto>> GetDepositsAsync(int idCompany,
CancellationToken token = default)
{ {
var wellEntities = await (from well in db.Wells var wellEntities = await (from well in db.Wells
.Include(w => w.RelationCompaniesWells) .Include(w => w.RelationCompaniesWells)
@ -25,7 +27,7 @@ namespace AsbCloudInfrastructure.Services
.Include(w => w.Cluster) .Include(w => w.Cluster)
.ThenInclude(c => c.Deposit) .ThenInclude(c => c.Deposit)
where well.RelationCompaniesWells.Any(r => r.IdCompany == idCompany) where well.RelationCompaniesWells.Any(r => r.IdCompany == idCompany)
select well).AsNoTracking().ToListAsync(); select well).AsNoTracking().ToListAsync(token);
var gDepositEntities = wellEntities var gDepositEntities = wellEntities
.GroupBy(w => w.Cluster) .GroupBy(w => w.Cluster)
@ -61,13 +63,14 @@ namespace AsbCloudInfrastructure.Services
return dtos; return dtos;
} }
public async Task<IEnumerable<ClusterDto>> GetClustersAsync(int idCompany) public async Task<IEnumerable<ClusterDto>> GetClustersAsync(int idCompany,
CancellationToken token = default)
{ {
var entities = await db.GetWellsForCompany(idCompany) var entities = await db.GetWellsForCompany(idCompany)
.Select(e => e.Cluster) .Select(e => e.Cluster)
.Distinct() .Distinct()
.AsNoTracking() .AsNoTracking()
.ToListAsync(); .ToListAsync(token);
var dtos = entities.Select(e => new ClusterDto var dtos = entities.Select(e => new ClusterDto
{ {
@ -80,14 +83,15 @@ namespace AsbCloudInfrastructure.Services
return dtos; return dtos;
} }
public async Task<IEnumerable<ClusterDto>> GetClustersAsync(int idCompany, int depositId) public async Task<IEnumerable<ClusterDto>> GetClustersAsync(int idCompany,
int depositId, CancellationToken token = default)
{ {
var entities = await db.GetWellsForCompany(idCompany) var entities = await db.GetWellsForCompany(idCompany)
.Select(e => e.Cluster) .Select(e => e.Cluster)
.Where(e => e.IdDeposit == depositId) .Where(e => e.IdDeposit == depositId)
.Distinct() .Distinct()
.AsNoTracking() .AsNoTracking()
.ToListAsync(); .ToListAsync(token);
var dtos = entities.Select(e => new ClusterDto var dtos = entities.Select(e => new ClusterDto
{ {
@ -100,12 +104,13 @@ namespace AsbCloudInfrastructure.Services
return dtos; return dtos;
} }
public async Task<IEnumerable<WellDto>> GetWellsAsync(int idCompany, int idCluster) public async Task<IEnumerable<WellDto>> GetWellsAsync(int idCompany,
int idCluster, CancellationToken token = default)
{ {
var entities = await db.GetWellsForCompany(idCompany) var entities = await db.GetWellsForCompany(idCompany)
.Where(e => e.IdCluster == idCluster) .Where(e => e.IdCluster == idCluster)
.AsNoTracking() .AsNoTracking()
.ToListAsync(); .ToListAsync(token);
var dtos = entities.Select(e => new WellDto var dtos = entities.Select(e => new WellDto
{ {
@ -120,7 +125,8 @@ namespace AsbCloudInfrastructure.Services
return dtos; return dtos;
} }
public async Task<ClusterStatDto> GetStatAsync(int idCompany, int idCluster) public async Task<ClusterStatDto> GetStatAsync(int idCompany,
int idCluster, CancellationToken token = default)
{ {
var wellEntities = from w in db.Wells var wellEntities = from w in db.Wells
where w.IdCluster == idCluster && w.RelationCompaniesWells.Any(c => c.IdCompany == idCompany) where w.IdCluster == idCluster && w.RelationCompaniesWells.Any(c => c.IdCompany == idCompany)
@ -168,12 +174,12 @@ namespace AsbCloudInfrastructure.Services
CompanyType = c.Company.CompanyType.Caption, CompanyType = c.Company.CompanyType.Caption,
}), }),
WellType = e.WellType.Caption, WellType = e.WellType.Caption,
}).AsNoTracking().ToListAsync(); }).AsNoTracking().ToListAsync(token);
if (!wellStatDtos.Any()) if (!wellStatDtos.Any())
return null; return null;
var clusterById = db.Clusters.AsNoTracking().FirstOrDefault(c => c.Id == idCluster); var clusterById = await db.Clusters.AsNoTracking().FirstOrDefaultAsync(c => c.Id == idCluster, token);
return new ClusterStatDto return new ClusterStatDto
{ {

View File

@ -7,6 +7,8 @@ using Mapster;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services namespace AsbCloudInfrastructure.Services
{ {
@ -28,7 +30,9 @@ namespace AsbCloudInfrastructure.Services
cacheWells = cacheDb.GetCachedTable<Well>((AsbCloudDbContext)db); cacheWells = cacheDb.GetCachedTable<Well>((AsbCloudDbContext)db);
} }
public IEnumerable<DataSaubBaseDto> Get(int idWell, DateTime dateBegin = default, double intervalSec = 600d, int approxPointsCount = 1024) public async Task<IEnumerable<DataSaubBaseDto>> GetAsync(int idWell,
DateTime dateBegin = default, double intervalSec = 600d,
int approxPointsCount = 1024, CancellationToken token = default)
{ {
var well = cacheWells.FirstOrDefault(w => w.Id == idWell); var well = cacheWells.FirstOrDefault(w => w.Id == idWell);
if (well is null) if (well is null)
@ -48,7 +52,7 @@ namespace AsbCloudInfrastructure.Services
&& data.Date >= dateBegin && data.Date < datEnd && data.Date >= dateBegin && data.Date < datEnd
select data; select data;
var fullDataCount = query.Count(); var fullDataCount = await query.CountAsync(token);
if (fullDataCount == 0) if (fullDataCount == 0)
return default; return default;
@ -60,14 +64,15 @@ namespace AsbCloudInfrastructure.Services
query = query.Where(d => d.Id % m == 0); query = query.Where(d => d.Id % m == 0);
} }
var entities = query.AsNoTracking().ToList(); var entities = await query.AsNoTracking().ToListAsync(token);
var dtos = entities.Adapt<DataSaubBaseDto>(); var dtos = entities.Adapt<DataSaubBaseDto>();
return dtos; return dtos;
} }
public void UpdateData(string uid, IEnumerable<DataSaubBaseDto> dtos) public async Task UpdateDataAsync(string uid, IEnumerable<DataSaubBaseDto> dtos,
CancellationToken token = default)
{ {
if (dtos == default || !dtos.Any()) if (dtos == default || !dtos.Any())
return; return;
@ -76,11 +81,11 @@ namespace AsbCloudInfrastructure.Services
var dtoMinDate = dtos.Min(d => d.Date); var dtoMinDate = dtos.Min(d => d.Date);
var dtoMaxDate = dtos.Max(d => d.Date); var dtoMaxDate = dtos.Max(d => d.Date);
var oldDataSaubBase = (from d in db.DataSaubBases var oldDataSaubBase = await (from d in db.DataSaubBases
where d.IdTelemetry == telemetryId where d.IdTelemetry == telemetryId
&& d.Date > dtoMinDate && d.Date > dtoMinDate
&& d.Date < dtoMaxDate && d.Date < dtoMaxDate
select d).AsNoTracking().ToList(); select d).AsNoTracking().ToListAsync(token);
if (oldDataSaubBase.Any()) if (oldDataSaubBase.Any())
db.DataSaubBases.RemoveRange(oldDataSaubBase); db.DataSaubBases.RemoveRange(oldDataSaubBase);
@ -99,13 +104,14 @@ namespace AsbCloudInfrastructure.Services
db.SaveChanges(); db.SaveChanges();
} }
public DatesRangeDto GetDataDatesRange(int idWell) public async Task<DatesRangeDto> GetDataDatesRangeAsync(int idWell,
CancellationToken token = default)
{ {
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell); var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell);
if (telemetryId is null) if (telemetryId is null)
return null; return null;
var (From, To) = db.GetDatesRange<DataSaubBase>((int)telemetryId); var (From, To) = await db.GetDatesRangeAsync<DataSaubBase>((int)telemetryId, token);
return new DatesRangeDto { From = From, To = To }; return new DatesRangeDto { From = From, To = To };
} }

View File

@ -4,6 +4,8 @@ using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache; using AsbCloudInfrastructure.Services.Cache;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services namespace AsbCloudInfrastructure.Services
{ {
@ -18,7 +20,8 @@ namespace AsbCloudInfrastructure.Services
cacheEvents = cacheDb.GetCachedTable<TelemetryEvent>((AsbCloudDbContext)db); cacheEvents = cacheDb.GetCachedTable<TelemetryEvent>((AsbCloudDbContext)db);
} }
public void Upsert(string uid, IEnumerable<EventDto> dtos) public async Task UpsertAsync(string uid, IEnumerable<EventDto> dtos,
CancellationToken token = default)
{ {
if (!dtos.Any()) if (!dtos.Any())
return; return;
@ -32,7 +35,7 @@ namespace AsbCloudInfrastructure.Services
IdCategory = dto.IdCategory, IdCategory = dto.IdCategory,
MessageTemplate = dto.Message MessageTemplate = dto.Message
}); });
cacheEvents.Upsert(entities); await cacheEvents.UpsertAsync(entities, token);
} }
} }
} }

View File

@ -5,6 +5,8 @@ using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services namespace AsbCloudInfrastructure.Services
{ {
@ -43,9 +45,9 @@ namespace AsbCloudInfrastructure.Services
return fileIdsToNames; return fileIdsToNames;
} }
public PaginationContainer<FilePropertiesDto> GetFilesInfo(int idWell, public async Task<PaginationContainer<FilePropertiesDto>> GetFilesInfoAsync(int idWell,
int idCategory, DateTime begin = default, DateTime end = default, int idCategory, DateTime begin = default, DateTime end = default,
int skip = 0, int take = 32) int skip = 0, int take = 32, CancellationToken token = default)
{ {
var filesInfoQuery = db.Files.Include(f => f.User) var filesInfoQuery = db.Files.Include(f => f.User)
.Where(f => f.IdWell == idWell && .Where(f => f.IdWell == idWell &&
@ -62,12 +64,12 @@ namespace AsbCloudInfrastructure.Services
if (end != default) if (end != default)
filesInfoQuery = filesInfoQuery.Where(m => m.Date <= end).AsNoTracking(); filesInfoQuery = filesInfoQuery.Where(m => m.Date <= end).AsNoTracking();
result.Count = filesInfoQuery.Count(); result.Count = await filesInfoQuery.CountAsync(token);
if (skip > 0) if (skip > 0)
filesInfoQuery = filesInfoQuery.Skip(skip).AsNoTracking(); filesInfoQuery = filesInfoQuery.Skip(skip).AsNoTracking();
var filesInfoList = filesInfoQuery.OrderBy(f => f.Date).Take(take).ToList(); var filesInfoList = await filesInfoQuery.OrderBy(f => f.Date).Take(take).ToListAsync(token);
if (filesInfoList.Count == 0) if (filesInfoList.Count == 0)
return result; return result;

View File

@ -1,8 +1,9 @@
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using Mapster; using Mapster;
using System.Linq;
using System.Text.Json; using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
namespace AsbCloudInfrastructure.Services namespace AsbCloudInfrastructure.Services
@ -16,10 +17,11 @@ namespace AsbCloudInfrastructure.Services
this.db = db; this.db = db;
} }
public Tdto Get(int idWell, int idCategory) public async Task<Tdto> GetAsync(int idWell, int idCategory,
CancellationToken token = default)
{ {
var entity = db.LastData.AsNoTracking().FirstOrDefault(e => var entity = await db.LastData.AsNoTracking().FirstOrDefaultAsync(e =>
e.IdWell == idWell && e.IdCategory == idCategory); e.IdWell == idWell && e.IdCategory == idCategory, token);
if (entity is null) if (entity is null)
return new Tdto(); return new Tdto();
@ -28,13 +30,14 @@ namespace AsbCloudInfrastructure.Services
return dto; return dto;
} }
public void Upsert(int idWell, int idCategory, Tdto value) public async Task UpsertAsync(int idWell, int idCategory,
Tdto value, CancellationToken token = default)
{ {
var model = value.Adapt<TModel>(); var model = value.Adapt<TModel>();
var entity = db.LastData.AsNoTracking() var entity = await db.LastData.AsNoTracking()
.FirstOrDefault(ld => ld.IdWell == idWell && .FirstOrDefaultAsync(ld => ld.IdWell == idWell &&
ld.IdCategory == idCategory); ld.IdCategory == idCategory, token);
if (entity is not null) if (entity is not null)
{ {

View File

@ -7,6 +7,8 @@ using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services namespace AsbCloudInfrastructure.Services
{ {
@ -25,14 +27,15 @@ namespace AsbCloudInfrastructure.Services
cacheTUsers = cacheDb.GetCachedTable<TelemetryUser>((AsbCloudDbContext)db); cacheTUsers = cacheDb.GetCachedTable<TelemetryUser>((AsbCloudDbContext)db);
} }
public PaginationContainer<MessageDto> GetMessages( public async Task<PaginationContainer<MessageDto>> GetMessagesAsync(
int idWell, int idWell,
IEnumerable<int> categoryids = default, IEnumerable<int> categoryids = default,
DateTime begin = default, DateTime begin = default,
DateTime end = default, DateTime end = default,
string searchString = default, string searchString = default,
int skip = 0, int skip = 0,
int take = 32) int take = 32,
CancellationToken token = default)
{ {
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell); var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell);
if (telemetryId is null) if (telemetryId is null)
@ -43,7 +46,8 @@ namespace AsbCloudInfrastructure.Services
if (!events.Any()) if (!events.Any())
return null; return null;
var query = db.TelemetryMessages.Where(m => m.IdTelemetry == telemetryId); var query = db.TelemetryMessages.Where(m => m.IdTelemetry == telemetryId)
.AsNoTracking();
if ((categoryids?.Any() == true) || !string.IsNullOrEmpty(searchString)) if ((categoryids?.Any() == true) || !string.IsNullOrEmpty(searchString))
{ {
@ -79,7 +83,8 @@ namespace AsbCloudInfrastructure.Services
if (skip > 0) if (skip > 0)
query = query.Skip(skip); query = query.Skip(skip);
var messagesList = query.Take(take).AsNoTracking().ToList(); var messagesList = await query.Take(take).AsNoTracking()
.ToListAsync(token);
if (messagesList.Count == 0) if (messagesList.Count == 0)
return result; return result;
@ -108,21 +113,23 @@ namespace AsbCloudInfrastructure.Services
return result; return result;
} }
public DatesRangeDto GetMessagesDatesRange(int idWell) public async Task<DatesRangeDto> GetMessagesDatesRangeAsync(int idWell,
CancellationToken token = default)
{ {
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell); var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell);
if (telemetryId is null) if (telemetryId is null)
return null; return null;
var (From, To) = db.GetDatesRange<TelemetryMessage>((int)telemetryId); var (From, To) = await db.GetDatesRangeAsync<TelemetryMessage>((int)telemetryId, token);
return new DatesRangeDto { From = From, To = To }; return new DatesRangeDto { From = From, To = To };
} }
public void Insert(string uid, IEnumerable<TelemetryMessageDto> dtos) public Task InsertAsync(string uid, IEnumerable<TelemetryMessageDto> dtos,
CancellationToken token = default)
{ {
if (!dtos.Any()) if (!dtos.Any())
return; return null;
var telemetryId = telemetryService.GetOrCreateTemetryIdByUid(uid); var telemetryId = telemetryService.GetOrCreateTemetryIdByUid(uid);
@ -134,7 +141,7 @@ namespace AsbCloudInfrastructure.Services
db.TelemetryMessages.Add(entity); db.TelemetryMessages.Add(entity);
} }
db.SaveChanges(); return db.SaveChangesAsync(token);
} }
} }
} }

View File

@ -9,6 +9,8 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services namespace AsbCloudInfrastructure.Services
{ {
@ -90,9 +92,10 @@ namespace AsbCloudInfrastructure.Services
return generator.GetPagesCount(); return generator.GetPagesCount();
} }
public IEnumerable<ReportPropertiesDto> GetSuitableReports(int idWell, DateTime begin, DateTime end, int stepSeconds, int format) public async Task<IEnumerable<ReportPropertiesDto>> GetSuitableReportsAsync(int idWell,
DateTime begin, DateTime end, int stepSeconds, int format, CancellationToken token = default)
{ {
var suitableReportsFromDb = GetSuitableReportsFromDb(idWell, begin, end, stepSeconds, format); var suitableReportsFromDb = await GetSuitableReportsFromDbAsync(idWell, begin, end, stepSeconds, format);
var suitableReportsProperties = suitableReportsFromDb.Select(r => new ReportPropertiesDto var suitableReportsProperties = suitableReportsFromDb.Select(r => new ReportPropertiesDto
{ {
@ -110,27 +113,28 @@ namespace AsbCloudInfrastructure.Services
return suitableReportsProperties; return suitableReportsProperties;
} }
public DatesRangeDto GetReportsDatesRange(int idWell) public async Task<DatesRangeDto> GetReportsDatesRangeAsync(int idWell,
CancellationToken token = default)
{ {
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell); var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell);
if (telemetryId is null) if (telemetryId is null)
return null; return null;
var datesRange = (from d in db.DataSaubBases var datesRange = await (from d in db.DataSaubBases
where d.IdTelemetry == telemetryId where d.IdTelemetry == telemetryId
select d.Date).Union( select d.Date).Union(
from m in db.TelemetryMessages from m in db.TelemetryMessages
where m.IdTelemetry == telemetryId where m.IdTelemetry == telemetryId
select m.Date).DefaultIfEmpty() select m.Date).DefaultIfEmpty()
.GroupBy(g => true) .GroupBy(g => true)
.AsNoTracking() .AsNoTracking()
.Select(g => new .Select(g => new
{ {
From = g.Min(), From = g.Min(),
To = g.Max() To = g.Max()
}).OrderBy(gr => gr.From) }).OrderBy(gr => gr.From)
.FirstOrDefault(); .FirstOrDefaultAsync(token);
return new DatesRangeDto return new DatesRangeDto
{ {
@ -139,22 +143,25 @@ namespace AsbCloudInfrastructure.Services
}; };
} }
private IEnumerable<ReportProperties> GetSuitableReportsFromDb(int idWell, DateTime begin, DateTime end, int stepSeconds, int format) private async Task<IEnumerable<ReportProperties>> GetSuitableReportsFromDbAsync(int idWell,
DateTime begin, DateTime end, int stepSeconds, int format,
CancellationToken token = default)
{ {
var suitableReportsNames = (from r in db.ReportProperties.Include(r => r.File) var suitableReportsNames = await(from r in db.ReportProperties.Include(r => r.File)
where r.IdWell == idWell where r.IdWell == idWell
&& r.Begin >= begin && r.Begin >= begin
&& r.End <= end && r.End <= end
&& r.Step <= stepSeconds && r.Step <= stepSeconds
&& r.Format == format && r.Format == format
select r).OrderBy(o => o.File.Date) select r).OrderBy(o => o.File.Date)
.AsNoTracking() .AsNoTracking()
.Take(512).ToList(); .Take(512).ToListAsync(token);
return suitableReportsNames; return suitableReportsNames;
} }
private IReportGenerator GetReportGenerator(int idWell, DateTime begin, DateTime end, int stepSeconds, int format, AsbCloudDbContext context) private IReportGenerator GetReportGenerator(int idWell, DateTime begin,
DateTime end, int stepSeconds, int format, AsbCloudDbContext context)
{ {
var dataSource = new ReportDataSourcePgCloud(context, idWell); var dataSource = new ReportDataSourcePgCloud(context, idWell);

View File

@ -3,6 +3,8 @@ using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache; using AsbCloudInfrastructure.Services.Cache;
using Mapster; using Mapster;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services namespace AsbCloudInfrastructure.Services
{ {

View File

@ -25,7 +25,7 @@ namespace AsbCloudInfrastructure.Services
cacheRelationCompaniesWells = cacheDb.GetCachedTable<RelationCompanyWell>((AsbCloudDbContext)db); cacheRelationCompaniesWells = cacheDb.GetCachedTable<RelationCompanyWell>((AsbCloudDbContext)db);
} }
public async Task<IEnumerable<WellDto>> GetTransmittingWellsAsync(int idCompany) public async Task<IEnumerable<WellDto>> GetTransmittingWellsAsync(int idCompany, CancellationToken token)
{ {
var wells = new List<Well>(); var wells = new List<Well>();
IEnumerable<string> activeTelemetriesUids = telemetryTracker.GetTransmittingTelemetryUids(); IEnumerable<string> activeTelemetriesUids = telemetryTracker.GetTransmittingTelemetryUids();
@ -34,26 +34,26 @@ namespace AsbCloudInfrastructure.Services
wells = await db.GetWellsForCompany(idCompany) wells = await db.GetWellsForCompany(idCompany)
.Where(w => activeTelemetriesUids.Contains(w.Telemetry.RemoteUid)) .Where(w => activeTelemetriesUids.Contains(w.Telemetry.RemoteUid))
.AsNoTracking() .AsNoTracking()
.ToListAsync(); .ToListAsync(token);
} }
return wells.Select(w => From(w)); return wells.Select(w => From(w));
} }
public async Task<IEnumerable<WellDto>> GetWellsByCompanyAsync(int idCompany) public async Task<IEnumerable<WellDto>> GetWellsByCompanyAsync(int idCompany, CancellationToken token)
{ {
var wells = await db.GetWellsForCompany(idCompany).ToListAsync(); var wells = await db.GetWellsForCompany(idCompany).ToListAsync(token);
return wells.Select(w => From(w)); return wells.Select(w => From(w));
} }
public async Task<bool> IsCompanyInvolvedInWellAsync(int idCompany, int idWell) public async Task<bool> IsCompanyInvolvedInWellAsync(int idCompany, int idWell, CancellationToken token)
=> await cacheRelationCompaniesWells.ContainsAsync(r => r.IdWell == idWell && => await cacheRelationCompaniesWells.ContainsAsync(r => r.IdWell == idWell &&
r.IdCompany == idCompany, new CancellationToken()); r.IdCompany == idCompany, token);
public async Task<IEnumerable<WellOperationDto>> GetOperationsAsync(int idWell) public async Task<IEnumerable<WellOperationDto>> GetOperationsAsync(int idWell, CancellationToken token)
{ {
var entities = await db.WellOperations.Where(o => o.IdWell == idWell) var entities = await db.WellOperations.Where(o => o.IdWell == idWell)
.AsNoTracking() .AsNoTracking()
.ToListAsync(); .ToListAsync(token);
var dtos = entities.Adapt<WellOperationDto>(); var dtos = entities.Adapt<WellOperationDto>();

View File

@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Mvc;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
@ -32,19 +33,21 @@ namespace AsbCloudWebApi.Controllers
/// <param name="end">окончание</param> /// <param name="end">окончание</param>
/// <param name="skip">для пагинации кол-во записей пропустить</param> /// <param name="skip">для пагинации кол-во записей пропустить</param>
/// <param name="take">для пагинации кол-во записей </param> /// <param name="take">для пагинации кол-во записей </param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>Список операций на скважине за все время</returns> /// <returns>Список операций на скважине за все время</returns>
[HttpGet] [HttpGet]
[Route("{idWell}/operationsByWell")] [Route("{idWell}/operationsByWell")]
[ProducesResponseType(typeof(PaginationContainer<TelemetryOperationDto>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(PaginationContainer<TelemetryOperationDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetOperationsByWellAsync(int idWell, int skip = 0, int take = 32, public async Task<IActionResult> GetOperationsByWellAsync(int idWell, int skip = 0, int take = 32,
[FromQuery] IEnumerable<int> categoryIds = default, DateTime begin = default, DateTime end = default) [FromQuery] IEnumerable<int> categoryIds = default, DateTime begin = default, DateTime end = default,
CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token))
return Forbid(); return Forbid();
var analytics = await analyticsService.GetOperationsByWellAsync(idWell, categoryIds, begin, end, skip, take); var analytics = await analyticsService.GetOperationsByWellAsync(idWell, categoryIds, begin, end, skip, take, token);
if (analytics is null || analytics.Count == 0) if (analytics is null || analytics.Count == 0)
return NoContent(); return NoContent();
@ -56,18 +59,20 @@ namespace AsbCloudWebApi.Controllers
/// Возвращает данные по скважине "глубина-день" /// Возвращает данные по скважине "глубина-день"
/// </summary> /// </summary>
/// <param name="idWell">id скважины</param> /// <param name="idWell">id скважины</param>
/// <param name="token">Токен отмены задачи</param>
/// <returns>Коллекцию данных по скважине "глубина-день"</returns> /// <returns>Коллекцию данных по скважине "глубина-день"</returns>
[HttpGet] [HttpGet]
[Route("{idWell}/wellDepthToDay")] [Route("{idWell}/wellDepthToDay")]
[ProducesResponseType(typeof(IEnumerable<WellDepthToDayDto>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(IEnumerable<WellDepthToDayDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetWellDepthToDayAsync(int idWell) public async Task<IActionResult> GetWellDepthToDayAsync(int idWell,
CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token))
return Forbid(); return Forbid();
var wellDepthToDayData = await analyticsService.GetWellDepthToDayAsync(idWell); var wellDepthToDayData = await analyticsService.GetWellDepthToDayAsync(idWell, token);
if (wellDepthToDayData is null || !wellDepthToDayData.Any()) if (wellDepthToDayData is null || !wellDepthToDayData.Any())
return NoContent(); return NoContent();
@ -81,20 +86,22 @@ namespace AsbCloudWebApi.Controllers
/// <param name="idWell">id скважины</param> /// <param name="idWell">id скважины</param>
/// <param name="intervalSeconds">количество секунд в необходимом интервале времени</param> /// <param name="intervalSeconds">количество секунд в необходимом интервале времени</param>
/// <param name="workBeginSeconds">количество секунд в времени начала смены</param> /// <param name="workBeginSeconds">количество секунд в времени начала смены</param>
/// <param name="token">Токен отмены задачи</param>
/// <returns>Коллекцию данных по глубине скважины за период</returns> /// <returns>Коллекцию данных по глубине скважины за период</returns>
[HttpGet] [HttpGet]
[Route("{idWell}/wellDepthToInterval")] [Route("{idWell}/wellDepthToInterval")]
[ProducesResponseType(typeof(IEnumerable<WellDepthToIntervalDto>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(IEnumerable<WellDepthToIntervalDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetWellDepthToIntervalAsync(int idWell, public async Task<IActionResult> GetWellDepthToIntervalAsync(int idWell,
int intervalSeconds, int workBeginSeconds) int intervalSeconds, int workBeginSeconds, CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync ((int)idCompany, idWell)) if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token))
return Forbid(); return Forbid();
var wellDepthToIntervalData = await analyticsService.GetWellDepthToIntervalAsync(idWell, var wellDepthToIntervalData = await analyticsService.GetWellDepthToIntervalAsync(idWell,
intervalSeconds, workBeginSeconds); intervalSeconds, workBeginSeconds, token);
if (wellDepthToIntervalData is null || !wellDepthToIntervalData.Any()) if (wellDepthToIntervalData is null || !wellDepthToIntervalData.Any())
return NoContent(); return NoContent();
@ -108,18 +115,20 @@ namespace AsbCloudWebApi.Controllers
/// <param name="idWell">id скважины</param> /// <param name="idWell">id скважины</param>
/// <param name="begin">дата начала интервала</param> /// <param name="begin">дата начала интервала</param>
/// <param name="end">дата окончания интервала</param> /// <param name="end">дата окончания интервала</param>
/// <param name="token">Токен отмены задачи</param>
/// <returns>Коллекцию операций на скважине</returns> /// <returns>Коллекцию операций на скважине</returns>
[HttpGet] [HttpGet]
[Route("{idWell}/operationsSummary")] [Route("{idWell}/operationsSummary")]
[ProducesResponseType(typeof(IEnumerable<TelemetryOperationDurationDto>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(IEnumerable<TelemetryOperationDurationDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetOperationsSummaryAsync(int idWell, DateTime begin = default, DateTime end = default) public async Task<IActionResult> GetOperationsSummaryAsync(int idWell, DateTime begin = default,
DateTime end = default, CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync ((int)idCompany, idWell)) if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token))
return Forbid(); return Forbid();
var analytics = await analyticsService .GetOperationsSummaryAsync(idWell, begin, end); var analytics = await analyticsService .GetOperationsSummaryAsync(idWell, begin, end, token);
if (analytics is null || !analytics.Any()) if (analytics is null || !analytics.Any())
return NoContent(); return NoContent();
@ -133,19 +142,21 @@ namespace AsbCloudWebApi.Controllers
/// <param name="idWell">id скважины</param> /// <param name="idWell">id скважины</param>
/// <param name="intervalSeconds">количество секунд в необходимом интервале времени</param> /// <param name="intervalSeconds">количество секунд в необходимом интервале времени</param>
/// <param name="workBeginSeconds">количество секунд в времени начала смены</param> /// <param name="workBeginSeconds">количество секунд в времени начала смены</param>
/// <param name="token">Токен отмены задачи</param>
/// <returns>Коллекцию операций на скважине</returns> /// <returns>Коллекцию операций на скважине</returns>
[HttpGet] [HttpGet]
[Route("{idWell}/operationsToInterval")] [Route("{idWell}/operationsToInterval")]
[ProducesResponseType(typeof(IEnumerable<TelemetryOperationDurationDto>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(IEnumerable<TelemetryOperationDurationDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetOperationsToIntervalAsync(int idWell, public async Task<IActionResult> GetOperationsToIntervalAsync(int idWell,
int intervalSeconds, int workBeginSeconds) int intervalSeconds, int workBeginSeconds, CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync ((int)idCompany, idWell)) if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync ((int)idCompany, idWell, token))
return Forbid(); return Forbid();
var analytics = await analyticsService.GetOperationsToIntervalAsync(idWell, intervalSeconds, workBeginSeconds); var analytics = await analyticsService.GetOperationsToIntervalAsync(idWell,
intervalSeconds, workBeginSeconds, token);
if (analytics is null || !analytics.Any()) if (analytics is null || !analytics.Any())
return NoContent(); return NoContent();

View File

@ -2,6 +2,8 @@
using AsbCloudApp.Services; using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.Threading;
using System.Threading.Tasks;
using Swashbuckle.AspNetCore.Annotations; using Swashbuckle.AspNetCore.Annotations;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
@ -21,15 +23,16 @@ namespace AsbCloudWebApi.Controllers
/// Аутентификация пользователя /// Аутентификация пользователя
/// </summary> /// </summary>
/// <param name="auth"></param> /// <param name="auth"></param>
/// <param name="token">Токен отмены задачи</param>
/// <response code="200">новый токен</response> /// <response code="200">новый токен</response>
/// <response code="400">логин и пароль не подходят</response> /// <response code="400">логин и пароль не подходят</response>
[AllowAnonymous] [AllowAnonymous]
[HttpPost("login")] [HttpPost("login")]
[SwaggerOperation(OperationId = "logiin")] [SwaggerOperation(OperationId = "login")]
[ProducesResponseType(typeof(UserTokenDto), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(UserTokenDto), (int)System.Net.HttpStatusCode.OK)]
public IActionResult Login([FromBody] AuthDto auth) public async Task<IActionResult> LoginAsync([FromBody] AuthDto auth, CancellationToken token = default)
{ {
var userToken = authService.Login(auth.Login, auth.Password); var userToken = await authService.LoginAsync(auth.Login, auth.Password, token);
if (userToken is null) if (userToken is null)
BadRequest();//"wrong login or password" BadRequest();//"wrong login or password"

View File

@ -3,6 +3,7 @@ using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
@ -25,17 +26,18 @@ namespace AsbCloudWebApi.Controllers
/// <summary> /// <summary>
/// Получает список доступных пользователю кустов /// Получает список доступных пользователю кустов
/// </summary> /// </summary>
/// <param name="token"> Токен отмены задачи </param>
/// <returns></returns> /// <returns></returns>
[HttpGet()] [HttpGet()]
[ProducesResponseType(typeof(IEnumerable<ClusterDto>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(IEnumerable<ClusterDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetClustersAsync() public async Task<IActionResult> GetClustersAsync(CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null) if (idCompany is null)
return Forbid(); return Forbid();
var result = await clusterService.GetClustersAsync((int)idCompany); var result = await clusterService.GetClustersAsync((int)idCompany, token);
return Ok(result); return Ok(result);
} }
@ -43,17 +45,18 @@ namespace AsbCloudWebApi.Controllers
/// Получение доступных пользователю скважин /// Получение доступных пользователю скважин
/// </summary> /// </summary>
/// <param name="idCluster"></param> /// <param name="idCluster"></param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns></returns> /// <returns></returns>
[HttpGet("{idCluster}")] [HttpGet("{idCluster}")]
[ProducesResponseType(typeof(IEnumerable<WellDto>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(IEnumerable<WellDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetWellsAsync(int idCluster) public async Task<IActionResult> GetWellsAsync(int idCluster, CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null) if (idCompany is null)
return Forbid(); return Forbid();
var result = await clusterService.GetWellsAsync((int)idCompany, idCluster); var result = await clusterService.GetWellsAsync((int)idCompany, idCluster, token);
return Ok(result); return Ok(result);
} }
@ -61,17 +64,18 @@ namespace AsbCloudWebApi.Controllers
/// Получение обопщенной статистики по кусту (лучшая/худшая скважина) /// Получение обопщенной статистики по кусту (лучшая/худшая скважина)
/// </summary> /// </summary>
/// <param name="idCluster"></param> /// <param name="idCluster"></param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns></returns> /// <returns></returns>
[HttpGet("{idCluster}/Stat")] [HttpGet("{idCluster}/Stat")]
[ProducesResponseType(typeof(ClusterStatDto), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(ClusterStatDto), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetStatAsync(int idCluster) public async Task<IActionResult> GetStatAsync(int idCluster, CancellationToken token)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null) if (idCompany is null)
return Forbid(); return Forbid();
var result = await clusterService.GetStatAsync((int)idCompany, idCluster); var result = await clusterService.GetStatAsync((int)idCompany, idCluster, token);
return Ok(result); return Ok(result);
} }
} }

View File

@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Mvc;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
@ -34,15 +35,18 @@ namespace AsbCloudWebApi.Controllers
/// <param name="begin">дата начала выборки. По умолчанию: текущее время - intervalSec</param> /// <param name="begin">дата начала выборки. По умолчанию: текущее время - intervalSec</param>
/// <param name="intervalSec">интервал времени даты начала выборки, секунды</param> /// <param name="intervalSec">интервал времени даты начала выборки, секунды</param>
/// <param name="approxPointsCount">желаемое количество точек. Если в выборке точек будет больше, то выборка будет прорежена.</param> /// <param name="approxPointsCount">желаемое количество точек. Если в выборке точек будет больше, то выборка будет прорежена.</param>
/// <param name="token">Токен завершения задачи</param>
/// <returns></returns> /// <returns></returns>
[HttpGet] [HttpGet]
[Route("{idWell}/data")] [Route("{idWell}/data")]
[ProducesResponseType(typeof(IEnumerable<DataSaubBaseDto>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(IEnumerable<DataSaubBaseDto>), (int)System.Net.HttpStatusCode.OK)]
public IActionResult GetData(int idWell, DateTime begin = default, int intervalSec = 600, int approxPointsCount = 1024) public async Task<IActionResult> GetDataAsync(int idWell, DateTime begin = default,
int intervalSec = 600, int approxPointsCount = 1024, CancellationToken token = default)
{ {
if (begin == default) if (begin == default)
begin = DateTime.Now.AddSeconds(-intervalSec); begin = DateTime.Now.AddSeconds(-intervalSec);
var content = telemetryDataService.Get(idWell, begin, intervalSec, approxPointsCount); var content = await telemetryDataService.GetAsync(idWell, begin,
intervalSec, approxPointsCount, token);
if (content is null || !content.Any()) if (content is null || !content.Any())
return NoContent(); return NoContent();
@ -50,22 +54,31 @@ namespace AsbCloudWebApi.Controllers
return Ok(content); return Ok(content);
} }
/// <summary>
/// Возвращает диапазон дат сохраненных данных.
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="token">Токен завершения задачи</param>
/// <returns></returns>
[HttpGet] [HttpGet]
[Route("{idWell}/dataDatesRange")] [Route("{idWell}/dataDatesRange")]
[ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetDataDatesRangeAsync(int idWell) public async Task<IActionResult> GetDataDatesRangeAsync(int idWell,
CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null) if (idCompany is null)
return Forbid(); return Forbid();
bool isCompanyOwnsWell = await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell); bool isCompanyOwnsWell = await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token);
if (!isCompanyOwnsWell) if (!isCompanyOwnsWell)
return Forbid(); return Forbid();
DatesRangeDto dataDatesRange = telemetryDataService.GetDataDatesRange(idWell); DatesRangeDto dataDatesRange = await telemetryDataService.GetDataDatesRangeAsync(idWell,
token);
return Ok(dataDatesRange); return Ok(dataDatesRange);
} }

View File

@ -3,6 +3,7 @@ using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
@ -25,17 +26,18 @@ namespace AsbCloudWebApi.Controllers
/// <summary> /// <summary>
/// Получает список доступных пользователю месторождений /// Получает список доступных пользователю месторождений
/// </summary> /// </summary>
/// <param name="token"> Токен отмены задачи </param>
/// <returns></returns> /// <returns></returns>
[HttpGet] [HttpGet]
[ProducesResponseType(typeof(IEnumerable<DepositDto>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(IEnumerable<DepositDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetDepositsAsync() public async Task<IActionResult> GetDepositsAsync(CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null) if (idCompany is null)
return Forbid(); return Forbid();
var result = await clusterService.GetDepositsAsync((int)idCompany); var result = await clusterService.GetDepositsAsync((int)idCompany, token);
return Ok(result); return Ok(result);
} }
@ -43,17 +45,19 @@ namespace AsbCloudWebApi.Controllers
/// Получает список доступных пользователю кустов месторождения /// Получает список доступных пользователю кустов месторождения
/// </summary> /// </summary>
/// <param name="depositId"></param> /// <param name="depositId"></param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns></returns> /// <returns></returns>
[HttpGet("{depositId}")] [HttpGet("{depositId}")]
[ProducesResponseType(typeof(IEnumerable<ClusterDto>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(IEnumerable<ClusterDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetClustersAsync(int depositId) public async Task<IActionResult> GetClustersAsync(int depositId,
CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null) if (idCompany is null)
return Forbid(); return Forbid();
var result = await clusterService.GetClustersAsync((int)idCompany, depositId); var result = await clusterService.GetClustersAsync((int)idCompany, depositId, token);
return Ok(result); return Ok(result);
} }

View File

@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Mvc;
using System; using System;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
@ -31,19 +32,20 @@ namespace AsbCloudWebApi.Controllers
/// <param name="idCategory">id категории файла</param> /// <param name="idCategory">id категории файла</param>
/// <param name="idUser">id отправившего файл пользователя</param> /// <param name="idUser">id отправившего файл пользователя</param>
/// <param name="files">Коллекция файлов</param> /// <param name="files">Коллекция файлов</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns></returns> /// <returns></returns>
[HttpPost] [HttpPost]
[Route("{idWell}/files")] [Route("{idWell}/files")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> SaveFilesAsync(int idWell, int idCategory, int idUser, public async Task<IActionResult> SaveFilesAsync(int idWell, int idCategory,
[FromForm] IFormFileCollection files) int idUser, [FromForm] IFormFileCollection files, CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null) if (idCompany is null)
return Forbid(); return Forbid();
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token))
return Forbid(); return Forbid();
var fileInfoCollection = files.Select(f => var fileInfoCollection = files.Select(f =>
@ -78,21 +80,23 @@ namespace AsbCloudWebApi.Controllers
/// <param name="end">дата окончания</param> /// <param name="end">дата окончания</param>
/// <param name="skip">для пагинации кол-во записей пропустить</param> /// <param name="skip">для пагинации кол-во записей пропустить</param>
/// <param name="take">для пагинации кол-во записей взять </param> /// <param name="take">для пагинации кол-во записей взять </param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>Список информации о файлах в этой категории</returns> /// <returns>Список информации о файлах в этой категории</returns>
[HttpGet] [HttpGet]
[Route("{idWell}")] [Route("{idWell}")]
[ProducesResponseType(typeof(PaginationContainer<FilePropertiesDto>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(PaginationContainer<FilePropertiesDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetFilesInfoAsync([FromRoute] int idWell, public async Task<IActionResult> GetFilesInfoAsync([FromRoute] int idWell,
int skip = 0, int take = 32, int idCategory = default, int skip = 0, int take = 32, int idCategory = default,
DateTime begin = default, DateTime end = default) DateTime begin = default, DateTime end = default, CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token))
return Forbid(); return Forbid();
var filesInfo = fileService.GetFilesInfo(idWell, idCategory, var filesInfo = await fileService.GetFilesInfoAsync(idWell, idCategory,
begin, end, skip, take); begin, end, skip, take, token);
if (filesInfo is null || !filesInfo.Items.Any()) if (filesInfo is null || !filesInfo.Items.Any())
return NoContent(); return NoContent();
@ -105,11 +109,13 @@ namespace AsbCloudWebApi.Controllers
/// </summary> /// </summary>
/// <param name="idWell">id скважины</param> /// <param name="idWell">id скважины</param>
/// <param name="fileId">id запрашиваемого файла</param> /// <param name="fileId">id запрашиваемого файла</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>Запрашиваемый файл</returns> /// <returns>Запрашиваемый файл</returns>
[HttpGet] [HttpGet]
[Route("{idWell}/{fileId}")] [Route("{idWell}/{fileId}")]
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetFileAsync([FromRoute] int idWell, int fileId) public async Task<IActionResult> GetFileAsync([FromRoute] int idWell,
int fileId, CancellationToken token = default)
{ {
try try
{ {
@ -118,7 +124,7 @@ namespace AsbCloudWebApi.Controllers
if (idCompany is null) if (idCompany is null)
return Forbid(); return Forbid();
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token))
return Forbid(); return Forbid();
var fileInfo = fileService.GetFileInfo(fileId); var fileInfo = fileService.GetFileInfo(fileId);

View File

@ -1,6 +1,7 @@
using AsbCloudApp.Services; using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
@ -19,26 +20,28 @@ namespace AsbCloudWebApi.Controllers
} }
[HttpGet] [HttpGet]
public async Task<IActionResult> GetAsync([FromRoute] int idWell, [FromQuery] int idCategory) public async Task<IActionResult> GetAsync([FromRoute] int idWell,
[FromQuery] int idCategory, CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token))
return Forbid(); return Forbid();
var result = lastDataService.Get(idWell, idCategory); var result = await lastDataService.GetAsync(idWell, idCategory, token);
return Ok(result); return Ok(result);
} }
[HttpPost] [HttpPost]
public async Task<IActionResult> PutAsync([FromRoute] int idWell, [FromQuery] int idCategory, T data) public async Task<IActionResult> PutAsync([FromRoute] int idWell,
[FromQuery] int idCategory, T data, CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token))
return Forbid(); return Forbid();
lastDataService.Upsert(idWell, idCategory, data); await lastDataService.UpsertAsync(idWell, idCategory, data, token);
return Ok(); return Ok();
} }
} }

View File

@ -3,6 +3,7 @@ using AsbCloudApp.Services;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
@ -29,11 +30,17 @@ namespace AsbCloudWebApi.Controllers
/// <param name="end">окончание</param> /// <param name="end">окончание</param>
/// <param name="skip">для пагинации кол-во записей пропустить</param> /// <param name="skip">для пагинации кол-во записей пропустить</param>
/// <param name="take">для пагинации кол-во записей </param> /// <param name="take">для пагинации кол-во записей </param>
/// <param name="searchString"> Строка поиска </param>
/// <param name="token">Токен для отмены задачи</param>
/// <returns>список сообщений по скважине</returns> /// <returns>список сообщений по скважине</returns>
[HttpGet] [HttpGet]
[Route("{idWell}/message")] [Route("{idWell}/message")]
[ProducesResponseType(typeof(PaginationContainer<MessageDto>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(PaginationContainer<MessageDto>), (int)System.Net.HttpStatusCode.OK)]
public IActionResult GetMessage(int idWell, int skip = 0, int take = 32, [FromQuery] IEnumerable<int> categoryids = default, DateTime begin = default, DateTime end = default, string searchString = default) public async Task<IActionResult> GetMessagesAsync(int idWell, int skip = 0, int take = 32,
[FromQuery] IEnumerable<int> categoryids = default,
DateTime begin = default, DateTime end = default,
string searchString = default,
CancellationToken token = default)
{ {
if (take > 1024) if (take > 1024)
return BadRequest("limit mast be less then 1024"); return BadRequest("limit mast be less then 1024");
@ -41,7 +48,9 @@ namespace AsbCloudWebApi.Controllers
if (begin > DateTime.Now) if (begin > DateTime.Now)
begin = default; begin = default;
var result = messageService.GetMessages(idWell, categoryids, begin, end, searchString, skip, take); var result = await messageService.GetMessagesAsync(idWell,
categoryids, begin, end, searchString,
skip, take, token);
if (result is null || result.Count == 0) if (result is null || result.Count == 0)
return NoContent(); return NoContent();
@ -49,22 +58,31 @@ namespace AsbCloudWebApi.Controllers
return Ok(result); return Ok(result);
} }
/// <summary>
/// Выдает список сообщений по скважине
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="token">Токен для отмены задачи</param>
/// <returns>список сообщений по скважине</returns>
[HttpGet] [HttpGet]
[Route("{idWell}/messagesDatesRange")] [Route("{idWell}/messagesDatesRange")]
[ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetMessagesDateRangeAsync(int idWell) public async Task<IActionResult> GetMessagesDateRangeAsync(int idWell,
CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null) if (idCompany is null)
return Forbid(); return Forbid();
bool isCompanyOwnsWell = await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell); bool isCompanyOwnsWell = await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token);
if (!isCompanyOwnsWell) if (!isCompanyOwnsWell)
return Forbid(); return Forbid();
DatesRangeDto wellMessagesDatesRange = messageService.GetMessagesDatesRange(idWell); DatesRangeDto wellMessagesDatesRange = await messageService.GetMessagesDatesRangeAsync(idWell,
token);
return Ok(wellMessagesDatesRange); return Ok(wellMessagesDatesRange);
} }

View File

@ -7,6 +7,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
@ -60,19 +61,21 @@ namespace AsbCloudWebApi.Controllers
/// <param name="format">формат отчета (0-PDF, 1-LAS)</param> /// <param name="format">формат отчета (0-PDF, 1-LAS)</param>
/// <param name="begin">дата начала интервала</param> /// <param name="begin">дата начала интервала</param>
/// <param name="end">дата окончания интервала</param> /// <param name="end">дата окончания интервала</param>
/// <param name="token">Токен для отмены задачи</param>
/// <returns>id фоновой задачи формирования отчета</returns> /// <returns>id фоновой задачи формирования отчета</returns>
[HttpPost] [HttpPost]
[Route("{idWell}/report")] [Route("{idWell}/report")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> CreateReportAsync(int idWell, int idUser, int stepSeconds, int format, public async Task<IActionResult> CreateReportAsync(int idWell, int idUser, int stepSeconds, int format,
DateTime begin = default, DateTime end = default) DateTime begin = default, DateTime end = default,
CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null) if (idCompany is null)
return Forbid(); return Forbid();
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token))
return Forbid(); return Forbid();
var id = reportService.CreateReport(idWell, idUser, var id = reportService.CreateReport(idWell, idUser,
@ -86,11 +89,13 @@ namespace AsbCloudWebApi.Controllers
/// </summary> /// </summary>
/// <param name="idWell">id скважины</param> /// <param name="idWell">id скважины</param>
/// <param name="reportName">имя запрашиваемого файла (отчета)</param> /// <param name="reportName">имя запрашиваемого файла (отчета)</param>
/// <param name="token">Токен для отмены задачи</param>
/// <returns>файл с отчетом</returns> /// <returns>файл с отчетом</returns>
[HttpGet] [HttpGet]
[Route("{idWell}/{reportName}")] [Route("{idWell}/{reportName}")]
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetReportAsync([FromRoute] int idWell, string reportName) public async Task<IActionResult> GetReportAsync([FromRoute] int idWell,
string reportName, CancellationToken token = default)
{ {
try try
{ {
@ -99,7 +104,7 @@ namespace AsbCloudWebApi.Controllers
if (idCompany is null) if (idCompany is null)
return Forbid(); return Forbid();
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token))
return Forbid(); return Forbid();
// TODO: словарь content typoв // TODO: словарь content typoв
var relativePath = Path.Combine(fileService.RootPath, $"{idWell}", var relativePath = Path.Combine(fileService.RootPath, $"{idWell}",
@ -121,14 +126,17 @@ namespace AsbCloudWebApi.Controllers
/// <param name="format">формат отчета (0-PDF, 1-LAS)</param> /// <param name="format">формат отчета (0-PDF, 1-LAS)</param>
/// <param name="begin">дата начала интервала</param> /// <param name="begin">дата начала интервала</param>
/// <param name="end">дата окончания интервала</param> /// <param name="end">дата окончания интервала</param>
/// <param name="token">Токен для отмены задачи</param>
/// <returns>Список имен существующих отчетов (отчетов)</returns> /// <returns>Список имен существующих отчетов (отчетов)</returns>
[HttpGet] [HttpGet]
[Route("{idWell}/suitableReports")] [Route("{idWell}/suitableReports")]
[ProducesResponseType(typeof(IEnumerable<string>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(IEnumerable<string>), (int)System.Net.HttpStatusCode.OK)]
public IActionResult GetSuitableReportsNames(int idWell, int stepSeconds, int format, public async Task<IActionResult> GetSuitableReportsNamesAsync(int idWell, int stepSeconds, int format,
DateTime begin = default, DateTime end = default) DateTime begin = default, DateTime end = default,
CancellationToken token = default)
{ {
var suitableReportsNames = reportService.GetSuitableReports(idWell, begin, end, stepSeconds, format); var suitableReportsNames = await reportService.GetSuitableReportsAsync(idWell,
begin, end, stepSeconds, format, token);
if (suitableReportsNames is null || !suitableReportsNames.Any()) if (suitableReportsNames is null || !suitableReportsNames.Any())
return NoContent(); return NoContent();
@ -144,21 +152,25 @@ namespace AsbCloudWebApi.Controllers
/// <param name="end">дата окончания интервала</param> /// <param name="end">дата окончания интервала</param>
/// <param name="stepSeconds">шаг интервала</param> /// <param name="stepSeconds">шаг интервала</param>
/// <param name="format">формат отчета (0-PDF, 1-LAS)</param> /// <param name="format">формат отчета (0-PDF, 1-LAS)</param>
/// <param name="token">Токен для отмены задачи</param>
/// <returns>прогнозируемое кол-во страниц отчета</returns> /// <returns>прогнозируемое кол-во страниц отчета</returns>
[HttpGet] [HttpGet]
[Route("{idWell}/reportSize")] [Route("{idWell}/reportSize")]
[ProducesResponseType(typeof(string), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(string), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetReportSizeAsync(int idWell, int stepSeconds, int format, DateTime begin = default, DateTime end = default) public async Task<IActionResult> GetReportSizeAsync(int idWell,
int stepSeconds, int format, DateTime begin = default,
DateTime end = default, CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null) if (idCompany is null)
return Forbid(); return Forbid();
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token))
return Forbid(); return Forbid();
int reportSize = reportService.GetReportPagesCount(idWell, begin, end, stepSeconds, format); int reportSize = reportService.GetReportPagesCount(idWell,
begin, end, stepSeconds, format);
return Ok(reportSize); return Ok(reportSize);
} }
@ -167,21 +179,24 @@ namespace AsbCloudWebApi.Controllers
/// Возвращает даты самого старого и самого свежего отчетов в БД /// Возвращает даты самого старого и самого свежего отчетов в БД
/// </summary> /// </summary>
/// <param name="idWell">id скважины</param> /// <param name="idWell">id скважины</param>
/// <param name="token">Токен для отмены задачи</param>
/// <returns>Даты самого старого и самого свежего отчетов в БД</returns> /// <returns>Даты самого старого и самого свежего отчетов в БД</returns>
[HttpGet] [HttpGet]
[Route("{idWell}/reportsDatesRange")] [Route("{idWell}/reportsDatesRange")]
[ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetReportsDateRangeAsync(int idWell) public async Task<IActionResult> GetReportsDateRangeAsync(int idWell,
CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
if (idCompany is null) if (idCompany is null)
return Forbid(); return Forbid();
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token))
return Forbid(); return Forbid();
DatesRangeDto wellReportsDatesRange = reportService.GetReportsDatesRange(idWell); DatesRangeDto wellReportsDatesRange = await reportService.GetReportsDatesRangeAsync(idWell,
token);
return Ok(wellReportsDatesRange); return Ok(wellReportsDatesRange);
} }

View File

@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
@ -62,16 +63,18 @@ namespace AsbCloudWebApi.Controllers
/// </summary> /// </summary>
/// <param name="uid">Уникальный идентификатор отправителя</param> /// <param name="uid">Уникальный идентификатор отправителя</param>
/// <param name="dtos">Данные</param> /// <param name="dtos">Данные</param>
/// <param name="token">Токен для отмены задачи</param>
/// <returns></returns> /// <returns></returns>
[HttpPost] [HttpPost]
[Route("{uid}/data")] [Route("{uid}/data")]
public IActionResult PostData(string uid, [FromBody] IEnumerable<DataSaubBaseDto> dtos) public async Task<IActionResult> PostDataAsync(string uid, [FromBody] IEnumerable<DataSaubBaseDto> dtos,
CancellationToken token = default)
{ {
var idWell = telemetryService.GetidWellByTelemetryUid(uid); var idWell = telemetryService.GetidWellByTelemetryUid(uid);
DataService.UpdateData(uid, dtos); await DataService.UpdateDataAsync(uid, dtos, token);
if (idWell != null && dtos.Any()) if (idWell != null && dtos.Any())
Task.Run(() => telemetryHubContext.Clients.Group($"well_{idWell}").SendAsync(nameof(ITelemetryHubClient.ReceiveDataSaub), dtos)); await Task.Run(() => telemetryHubContext.Clients.Group($"well_{idWell}").SendAsync(nameof(ITelemetryHubClient.ReceiveDataSaub), dtos), token);
telemetryTracker.SaveRequestDate(uid); telemetryTracker.SaveRequestDate(uid);
return Ok(); return Ok();
@ -82,16 +85,18 @@ namespace AsbCloudWebApi.Controllers
/// </summary> /// </summary>
/// <param name="uid">Уникальный идентификатор отправителя</param> /// <param name="uid">Уникальный идентификатор отправителя</param>
/// <param name="dtos">сообщения</param> /// <param name="dtos">сообщения</param>
/// <param name="token">Токен для отмены задачи</param>
/// <returns></returns> /// <returns></returns>
[HttpPost] [HttpPost]
[Route("{uid}/message")] [Route("{uid}/message")]
public IActionResult PostMessages(string uid, [FromBody] IEnumerable<TelemetryMessageDto> dtos) public async Task<IActionResult> PostMessagesAsync(string uid, [FromBody] IEnumerable<TelemetryMessageDto> dtos,
CancellationToken token = default)
{ {
var idWell = telemetryService.GetidWellByTelemetryUid(uid); var idWell = telemetryService.GetidWellByTelemetryUid(uid);
messageService.Insert(uid, dtos); await messageService.InsertAsync(uid, dtos, token);
if (dtos.Any()) if (dtos.Any())
Task.Run(() => telemetryHubContext.Clients.Group($"well_{idWell}").SendAsync(nameof(ITelemetryHubClient.ReceiveMessages), dtos)); await Task.Run(() => telemetryHubContext.Clients.Group($"well_{idWell}").SendAsync(nameof(ITelemetryHubClient.ReceiveMessages), dtos), token);
telemetryTracker.SaveRequestDate(uid); telemetryTracker.SaveRequestDate(uid);
return Ok(); return Ok();
@ -102,12 +107,14 @@ namespace AsbCloudWebApi.Controllers
/// </summary> /// </summary>
/// <param name="uid">Уникальный идентификатор отправителя</param> /// <param name="uid">Уникальный идентификатор отправителя</param>
/// <param name="events">справочник событий</param> /// <param name="events">справочник событий</param>
/// <param name="token">Токен для отмены задачи</param>
/// <returns></returns> /// <returns></returns>
[HttpPost] [HttpPost]
[Route("{uid}/event")] [Route("{uid}/event")]
public IActionResult PostEvents(string uid, [FromBody] List<EventDto> events) public async Task<IActionResult> PostEventsAsync(string uid, [FromBody] List<EventDto> events,
CancellationToken token = default)
{ {
eventService.Upsert(uid, events); await eventService.UpsertAsync(uid, events, token);
telemetryTracker.SaveRequestDate(uid); telemetryTracker.SaveRequestDate(uid);
return Ok(); return Ok();
} }

View File

@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
@ -22,7 +23,7 @@ namespace AsbCloudWebApi.Controllers
[HttpGet] [HttpGet]
[ProducesResponseType(typeof(IEnumerable<WellDto>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(IEnumerable<WellDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetWellsAsync() public async Task<IActionResult> GetWellsAsync(CancellationToken token = default)
{ {
var idCompany = User.GetCompanyId(); var idCompany = User.GetCompanyId();
@ -31,7 +32,7 @@ namespace AsbCloudWebApi.Controllers
return NoContent(); return NoContent();
} }
var wells = await wellService.GetWellsByCompanyAsync((int)idCompany); var wells = await wellService.GetWellsByCompanyAsync((int)idCompany, token);
if (wells is null || !wells.Any()) if (wells is null || !wells.Any())
return NoContent(); return NoContent();
@ -41,31 +42,31 @@ namespace AsbCloudWebApi.Controllers
[HttpGet("{idWell}/operations")] [HttpGet("{idWell}/operations")]
[ProducesResponseType(typeof(IEnumerable<WellOperationDto>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(IEnumerable<WellOperationDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetOperationsAsync(int idWell) public async Task<IActionResult> GetOperationsAsync(int idWell, CancellationToken token = default)
{ {
var idCompany = User.GetCompanyId(); var idCompany = User.GetCompanyId();
if (idCompany is null) if (idCompany is null)
return NoContent(); return NoContent();
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell)) if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token))
return Forbid(); return Forbid();
var dto = await wellService.GetOperationsAsync(idWell); var dto = await wellService.GetOperationsAsync(idWell, token);
return Ok(dto); return Ok(dto);
} }
[HttpGet("transmittingWells")] [HttpGet("transmittingWells")]
[ProducesResponseType(typeof(IEnumerable<WellDto>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(IEnumerable<WellDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetTransmittingWellsAsync() public async Task<IActionResult> GetTransmittingWellsAsync(CancellationToken token = default)
{ {
var idCompany = User.GetCompanyId(); var idCompany = User.GetCompanyId();
if (idCompany is null) if (idCompany is null)
return NoContent(); return NoContent();
var transmittingWells = await wellService.GetTransmittingWellsAsync((int)idCompany); var transmittingWells = await wellService.GetTransmittingWellsAsync((int)idCompany, token);
if (transmittingWells is null || !transmittingWells.Any()) if (transmittingWells is null || !transmittingWells.Any())
return NoContent(); return NoContent();

View File

@ -23,9 +23,10 @@ namespace AsbCloudWebApi.Controllers
} }
[HttpGet] [HttpGet]
public async Task<IActionResult> GetAllAsync(int idWell, int skip = 0, int take = 32, CancellationToken token = default) public async Task<IActionResult> GetAllAsync(int idWell, int skip = 0, int take = 32,
CancellationToken token = default)
{ {
if(!await CanUserAccessToWellAsync(idWell)) if(!await CanUserAccessToWellAsync(idWell, token))
return Forbid(); return Forbid();
var result = await sectionsService.GetAllByWellIdAsync(idWell, skip, take, token).ConfigureAwait(false); var result = await sectionsService.GetAllByWellIdAsync(idWell, skip, take, token).ConfigureAwait(false);
@ -34,9 +35,10 @@ namespace AsbCloudWebApi.Controllers
[HttpGet] [HttpGet]
[Route("{idSection}")] [Route("{idSection}")]
public async Task<IActionResult> GetAsync(int idSection, int idWell, CancellationToken token = default) public async Task<IActionResult> GetAsync(int idSection, int idWell,
CancellationToken token = default)
{ {
if (!await CanUserAccessToWellAsync(idWell)) if (!await CanUserAccessToWellAsync(idWell, token))
return Forbid(); return Forbid();
var result = await sectionsService.GetAsync(idSection, token).ConfigureAwait(false); var result = await sectionsService.GetAsync(idSection, token).ConfigureAwait(false);
@ -44,9 +46,10 @@ namespace AsbCloudWebApi.Controllers
} }
[HttpPost] [HttpPost]
public async Task<IActionResult> InsertAsync(int idWell, [FromBody] IEnumerable<WellSectionDto> values, CancellationToken token = default) public async Task<IActionResult> InsertAsync(int idWell, [FromBody] IEnumerable<WellSectionDto> values,
CancellationToken token = default)
{ {
if (!await CanUserAccessToWellAsync(idWell)) if (!await CanUserAccessToWellAsync(idWell, token))
return Forbid(); return Forbid();
var result = await sectionsService.InsertRangeAsync(values, idWell, token).ConfigureAwait(false); var result = await sectionsService.InsertRangeAsync(values, idWell, token).ConfigureAwait(false);
@ -56,7 +59,7 @@ namespace AsbCloudWebApi.Controllers
[HttpPut("{id}")] [HttpPut("{id}")]
public async Task<IActionResult> PutAsync(int id, int idWell, [FromBody] WellSectionDto value, CancellationToken token = default) public async Task<IActionResult> PutAsync(int id, int idWell, [FromBody] WellSectionDto value, CancellationToken token = default)
{ {
if (!await CanUserAccessToWellAsync(idWell)) if (!await CanUserAccessToWellAsync(idWell, token))
return Forbid(); return Forbid();
var result = await sectionsService.UpdateAsync(value, id, idWell, token).ConfigureAwait(false); var result = await sectionsService.UpdateAsync(value, id, idWell, token).ConfigureAwait(false);
@ -66,17 +69,17 @@ namespace AsbCloudWebApi.Controllers
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<IActionResult> DeleteAsync(int id, int idWell, CancellationToken token = default) public async Task<IActionResult> DeleteAsync(int id, int idWell, CancellationToken token = default)
{ {
if (!await CanUserAccessToWellAsync(idWell)) if (!await CanUserAccessToWellAsync(idWell, token))
return Forbid(); return Forbid();
var result = await sectionsService.DeleteAsync(new int[] { id }, token).ConfigureAwait(false); var result = await sectionsService.DeleteAsync(new int[] { id }, token).ConfigureAwait(false);
return Ok(result); return Ok(result);
} }
private async Task<bool> CanUserAccessToWellAsync(int idWell) private async Task<bool> CanUserAccessToWellAsync(int idWell, CancellationToken token = default)
{ {
int? idCompany = User.GetCompanyId(); int? idCompany = User.GetCompanyId();
return idCompany is not null && await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell); return idCompany is not null && await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token);
} }
} }
} }