90 lines
3.0 KiB
C#
Raw Normal View History

namespace Ordering.API.Infrastructure.HostedServices
2017-05-08 10:48:06 +02:00
{
using Dapper;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using Microsoft.eShopOnContainers.Services.Ordering.API;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Ordering.API.Application.IntegrationEvents.Events;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;
2017-05-08 10:48:06 +02:00
public class GracePeriodManagerService
: HostedService
2017-05-08 10:48:06 +02:00
{
private readonly OrderingSettings _settings;
private readonly ILogger<GracePeriodManagerService> _logger;
private readonly IEventBus _eventBus;
2017-05-08 10:48:06 +02:00
public GracePeriodManagerService(IOptions<OrderingSettings> settings,
IEventBus eventBus,
ILogger<GracePeriodManagerService> logger)
2017-05-08 10:48:06 +02:00
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus));
_settings = settings?.Value ?? throw new ArgumentNullException(nameof(settings));
2017-05-08 10:48:06 +02:00
}
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
2017-05-08 10:48:06 +02:00
{
while (true)
{
if (cancellationToken.IsCancellationRequested)
{
break;
}
CheckConfirmedGracePeriodOrders();
await Task.Delay(_settings.CheckUpdateTime, cancellationToken);
continue;
}
await Task.CompletedTask;
}
private void CheckConfirmedGracePeriodOrders()
{
_logger.LogDebug($"Checking confirmed grace period orders");
2017-05-17 11:57:02 +02:00
var orderIds = GetConfirmedGracePeriodOrders();
2017-05-08 10:48:06 +02:00
foreach (var orderId in orderIds)
{
var confirmGracePeriodEvent = new GracePeriodConfirmedIntegrationEvent(orderId);
_eventBus.Publish(confirmGracePeriodEvent);
2017-05-08 10:48:06 +02:00
}
}
2017-05-17 11:57:02 +02:00
private IEnumerable<int> GetConfirmedGracePeriodOrders()
2017-05-08 10:48:06 +02:00
{
IEnumerable<int> orderIds = new List<int>();
2017-05-08 10:48:06 +02:00
using (var conn = new SqlConnection(_settings.ConnectionString))
{
try
{
conn.Open();
orderIds = conn.Query<int>(
@"SELECT Id FROM [ordering].[orders]
WHERE DATEDIFF(minute, [OrderDate], GETDATE()) >= @GracePeriodTime
AND [OrderStatusId] = 1",
new { GracePeriodTime = _settings.GracePeriodTime });
}
catch (SqlException exception)
{
_logger.LogCritical($"FATAL ERROR: Database connections could not be opened: {exception.Message}");
}
2017-05-08 10:48:06 +02:00
}
return orderIds;
}
}
}