* Maintain FaKrosno api to handle Hangfire
* Added checking of missing EdiCo based on EdiCoTranslate and send email every 30 minutes * Added Admin Scheduler view
This commit is contained in:
133
FaKrosnoApi/Controllers/HangfireJobsController.cs
Normal file
133
FaKrosnoApi/Controllers/HangfireJobsController.cs
Normal file
@@ -0,0 +1,133 @@
|
||||
using System.Diagnostics;
|
||||
using FaKrosnoApi.Models;
|
||||
using Hangfire;
|
||||
using Hangfire.Storage;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using OrdersManagementDataModel.Dtos;
|
||||
using OrdersManagementDataModel.Services;
|
||||
|
||||
namespace FaKrosnoApi.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class HangfireJobsController(JobStorage jobStorage, IRecurringJobManager recurringJobManager, ITaskSchedulerService service) : Controller
|
||||
{
|
||||
[HttpGet("GetJobsToRun")]
|
||||
public async Task<ActionResult<IEnumerable<JobModel>>> GetJobsToRun()
|
||||
{
|
||||
IList<JobModel> jobsToRun = new List<JobModel>();
|
||||
|
||||
using (IStorageConnection? connection = jobStorage.GetConnection())
|
||||
{
|
||||
IList<RecurringJobDto>? recurringJobs = connection.GetRecurringJobs();
|
||||
IList<TaskSchedulerDto>? taskSchedulers = (await service.GetTaskSchedulers()).ToList();
|
||||
|
||||
foreach (var recurringJob in recurringJobs)
|
||||
{
|
||||
TaskSchedulerDto? taskScheduler = taskSchedulers?.FirstOrDefault(ts => ts.Name == recurringJob.Id);
|
||||
|
||||
if (taskScheduler != null)
|
||||
{
|
||||
jobsToRun.Add(new JobModel(recurringJob.Id, recurringJob.Cron, taskScheduler.Path,
|
||||
recurringJob.LastExecution, recurringJob.NextExecution, recurringJob.Job));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(jobsToRun);
|
||||
}
|
||||
|
||||
[HttpPost("RunJobs")]
|
||||
public async Task<IActionResult> RunJobs()
|
||||
{
|
||||
var jobsToRun = (await GetJobsToRun()).Value?.ToList();
|
||||
|
||||
if (jobsToRun == null || jobsToRun.Count == 0)
|
||||
{
|
||||
return BadRequest("Nie udało się pobrać zadań do uruchomienia.");
|
||||
}
|
||||
|
||||
foreach (var job in jobsToRun)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(job.Path))
|
||||
{
|
||||
recurringJobManager.AddOrUpdate(job.JobId, () => RunConsoleApplication(job.Path), job.Cron,
|
||||
new RecurringJobOptions { TimeZone = TimeZoneInfo.Local });
|
||||
}
|
||||
}
|
||||
|
||||
return Ok("Zadania zostały zaplanowane do uruchamiania zgodnie z ich CRON.");
|
||||
}
|
||||
|
||||
[HttpPost("AddTask")]
|
||||
public async Task<IActionResult> AddTask([FromBody] TaskSchedulerDto taskSchedulerDto)
|
||||
{
|
||||
var taskScheduler = new OrdersManagementDataModel.Entities.TaskScheduler
|
||||
{
|
||||
Name = taskSchedulerDto.Name,
|
||||
Path = taskSchedulerDto.Path,
|
||||
CronOptions = taskSchedulerDto.CronOptions,
|
||||
CreateDate = DateTime.UtcNow
|
||||
};
|
||||
|
||||
int result = await service.AddTaskScheduler(taskSchedulerDto);
|
||||
|
||||
if (result == 0)
|
||||
{
|
||||
return BadRequest("Nie udało się dodać zadania.");
|
||||
}
|
||||
|
||||
recurringJobManager.AddOrUpdate(taskScheduler.Name, () => RunConsoleApplication(taskScheduler.Path),
|
||||
taskScheduler.CronOptions, new RecurringJobOptions { TimeZone = TimeZoneInfo.Local });
|
||||
|
||||
return Ok("Zadanie zostało dodane.");
|
||||
}
|
||||
|
||||
[HttpGet("GetTasks")]
|
||||
public async Task<ActionResult<IEnumerable<TaskSchedulerDto>>> GetTasks()
|
||||
{
|
||||
var tasks = await service.GetTaskSchedulers();
|
||||
|
||||
// foreach (TaskSchedulerDto taskSchedulerDto in tasks)
|
||||
// {
|
||||
// taskSchedulerDto.JobDetails = GetJob(taskSchedulerDto.Name);
|
||||
// }
|
||||
|
||||
return Ok(tasks);
|
||||
}
|
||||
|
||||
private JobData? GetJob(string jobId)
|
||||
{
|
||||
using IStorageConnection? connection = jobStorage.GetConnection();
|
||||
return connection.GetJobData(jobId);
|
||||
}
|
||||
|
||||
private void RunConsoleApplication(string pathToApp)
|
||||
{
|
||||
try
|
||||
{
|
||||
var process = new Process
|
||||
{
|
||||
StartInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = pathToApp,
|
||||
UseShellExecute = false,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
CreateNoWindow = true
|
||||
}
|
||||
};
|
||||
process.Start();
|
||||
string output = process.StandardOutput.ReadToEnd();
|
||||
string error = process.StandardError.ReadToEnd();
|
||||
process.WaitForExit();
|
||||
|
||||
Console.WriteLine($"Output: {output}");
|
||||
Console.WriteLine($"Error: {error}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Error executing console application: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
17
FaKrosnoApi/Controllers/ScheduleJobController.cs
Normal file
17
FaKrosnoApi/Controllers/ScheduleJobController.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
using FaKrosnoApi.Services;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace FaKrosnoApi.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("[controller]")]
|
||||
public class ScheduleJobController(IScheduleJobService scheduledJob) : ControllerBase
|
||||
{
|
||||
[HttpPost("start")]
|
||||
public IActionResult StartJob()
|
||||
{
|
||||
scheduledJob.ExecuteAsync();
|
||||
return Ok("Job started");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,8 +7,10 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Hangfire" Version="1.8.17" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.11" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.11" />
|
||||
<PackageReference Include="Microsoft.Data.SqlClient" Version="6.0.1" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
@@ -20,6 +22,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\FaKrosnoEfDataModel\FaKrosnoEfDataModel.csproj" />
|
||||
<ProjectReference Include="..\OrdersManagementDataModel\OrdersManagementDataModel.csproj" />
|
||||
<ProjectReference Include="..\SytelineSaAppEfDataModel\SytelineSaAppEfDataModel.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
11
FaKrosnoApi/Models/EmailSettingsModel.cs
Normal file
11
FaKrosnoApi/Models/EmailSettingsModel.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace FaKrosnoApi.Models;
|
||||
|
||||
public class EmailSettingsModel
|
||||
{
|
||||
public string SmtpServer { get; set; }
|
||||
public int Port { get; set; }
|
||||
public string SenderEmail { get; set; }
|
||||
public string SenderPassword { get; set; }
|
||||
public string RecipientEmail { get; set; }
|
||||
public bool UseSsl { get; set; }
|
||||
}
|
||||
19
FaKrosnoApi/Models/JobModel.cs
Normal file
19
FaKrosnoApi/Models/JobModel.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using Hangfire.Common;
|
||||
|
||||
namespace FaKrosnoApi.Models;
|
||||
|
||||
public class JobModel(
|
||||
string jobId,
|
||||
string cron,
|
||||
string path,
|
||||
DateTime? lastExecution,
|
||||
DateTime? nextExecution,
|
||||
Job jobDetails)
|
||||
{
|
||||
public string JobId { get; set; } = jobId;
|
||||
public string Cron { get; set; } = cron;
|
||||
public string Path { get; set; } = path;
|
||||
public DateTime? LastExecution { get; set; } = lastExecution;
|
||||
public DateTime? NextExecution { get; set; } = nextExecution;
|
||||
public Job JobDetails { get; set; } = jobDetails;
|
||||
}
|
||||
6
FaKrosnoApi/Models/JobSettingsModel.cs
Normal file
6
FaKrosnoApi/Models/JobSettingsModel.cs
Normal file
@@ -0,0 +1,6 @@
|
||||
namespace FaKrosnoApi.Models;
|
||||
|
||||
public class JobSettingsModel
|
||||
{
|
||||
public int QueryIntervalMinutes { get; set; }
|
||||
}
|
||||
@@ -1,35 +1,60 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Text;
|
||||
using FaKrosnoApi.Models;
|
||||
using FaKrosnoApi.Services;
|
||||
using FaKrosnoEfDataModel;
|
||||
using FaKrosnoEfDataModel.Services;
|
||||
using Hangfire;
|
||||
using Hangfire.SqlServer;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using OrdersManagementDataModel;
|
||||
using OrdersManagementDataModel.Services;
|
||||
using SytelineSaAppEfDataModel;
|
||||
using SytelineSaAppEfDataModel.Services;
|
||||
using FaKrosnoMappingProfile = FaKrosnoEfDataModel.MappingProfile;
|
||||
using SytelineSaAppMappingProfile = SytelineSaAppEfDataModel.MappingProfile;
|
||||
using OrdersManagementMappingProfile = OrdersManagementDataModel.MappingProfile;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
var configuration = builder.Configuration;
|
||||
// Add services to the container.
|
||||
|
||||
builder.Services.AddDbContext<FaKrosnoDbContext>(options =>
|
||||
options.UseSqlServer(builder.Configuration.GetConnectionString("FaKrosnoConnection")));
|
||||
builder.Services.AddDbContext<SytelineSaAppDbContext>(options =>
|
||||
options.UseSqlServer(builder.Configuration.GetConnectionString("SytelineSaAppConnection")));
|
||||
builder.Services.AddDbContext<OrdersManagementDbContext>(options =>
|
||||
options.UseSqlServer(builder.Configuration.GetConnectionString("OrdersManagementConnection")));
|
||||
|
||||
builder.Services.Configure<EmailSettingsModel>(builder.Configuration.GetSection("EmailSettings"));
|
||||
builder.Services.Configure<JobSettingsModel>(builder.Configuration.GetSection("JobSettings"));
|
||||
|
||||
builder.WebHost.UseUrls("http://*:5555");
|
||||
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddOpenApiDocument(config =>
|
||||
{
|
||||
config.Title = "FaKrosnoApi";
|
||||
config.Version = "v1";
|
||||
});
|
||||
|
||||
builder.Services.AddHangfire(config => config
|
||||
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
|
||||
.UseSimpleAssemblyNameTypeSerializer()
|
||||
.UseRecommendedSerializerSettings()
|
||||
.UseSqlServerStorage(builder.Configuration.GetConnectionString("OrdersManagementConnection"), new SqlServerStorageOptions
|
||||
{
|
||||
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
|
||||
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
|
||||
QueuePollInterval = TimeSpan.Zero,
|
||||
UseRecommendedIsolationLevel = true,
|
||||
DisableGlobalLocks = true
|
||||
}));
|
||||
builder.Services.AddHangfireServer();
|
||||
|
||||
// Configure AutoMapper
|
||||
builder.Services.AddAutoMapper(typeof(FaKrosnoMappingProfile), typeof(SytelineSaAppMappingProfile));
|
||||
builder.Services.AddAutoMapper(typeof(FaKrosnoMappingProfile), typeof(SytelineSaAppMappingProfile),
|
||||
typeof(OrdersManagementMappingProfile));
|
||||
|
||||
// Configure JWT Authentication
|
||||
builder.Services.AddAuthentication(options =>
|
||||
@@ -55,15 +80,15 @@ builder.Services.AddScoped<IScheduleOrderDetailsService, ScheduleOrderDetailsSer
|
||||
builder.Services.AddScoped<IEdiCustomerOrderService, EdiCustomerOrderService>();
|
||||
builder.Services.AddScoped<IErrorLogService, ErrorLogService>();
|
||||
builder.Services.AddScoped<ICustomerOrderService, CustomerOrderService>();
|
||||
builder.Services.AddScoped<IEmailService, EmailService>();
|
||||
builder.Services.AddScoped<IScheduleJobService, ScheduleJobService>();
|
||||
builder.Services.AddScoped<ITaskSchedulerService, TaskSchedulerService>();
|
||||
builder.Services.AddHostedService<TimedHostedService>();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
//if (app.Environment.IsDevelopment())
|
||||
//{
|
||||
app.UseOpenApi(); // Serwuje dokument OpenAPI
|
||||
app.UseSwaggerUi(); // Dodaje interfejs u<>ytkownika Swagger
|
||||
//}
|
||||
app.UseOpenApi();
|
||||
app.UseSwaggerUi();
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
@@ -72,4 +97,13 @@ app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.UseHangfireDashboard();
|
||||
|
||||
// var scopeFactory = app.Services.GetRequiredService<IServiceScopeFactory>();
|
||||
// using (var scope = scopeFactory.CreateScope())
|
||||
// {
|
||||
// var scheduledJob = scope.ServiceProvider.GetRequiredService<IScheduleJobService>();
|
||||
// scheduledJob.Start();
|
||||
// }
|
||||
|
||||
app.Run();
|
||||
30
FaKrosnoApi/Services/EmailService.cs
Normal file
30
FaKrosnoApi/Services/EmailService.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
using System.Net;
|
||||
using System.Net.Mail;
|
||||
using FaKrosnoApi.Models;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace FaKrosnoApi.Services;
|
||||
|
||||
public class EmailService(IOptions<EmailSettingsModel> emailSettings) : IEmailService
|
||||
{
|
||||
private readonly EmailSettingsModel _emailSettings = emailSettings.Value;
|
||||
|
||||
public void SendEmail(string subject, string body)
|
||||
{
|
||||
using var smtpClient = new SmtpClient(_emailSettings.SmtpServer, _emailSettings.Port);
|
||||
smtpClient.EnableSsl = true;
|
||||
smtpClient.UseDefaultCredentials = false;
|
||||
smtpClient.Credentials = new NetworkCredential(_emailSettings.SenderEmail, _emailSettings.SenderPassword);
|
||||
|
||||
var mailMessage = new MailMessage
|
||||
{
|
||||
From = new MailAddress(_emailSettings.SenderEmail),
|
||||
Subject = subject,
|
||||
Body = body
|
||||
};
|
||||
|
||||
mailMessage.To.Add(_emailSettings.RecipientEmail);
|
||||
|
||||
smtpClient.Send(mailMessage);
|
||||
}
|
||||
}
|
||||
6
FaKrosnoApi/Services/IEmailService.cs
Normal file
6
FaKrosnoApi/Services/IEmailService.cs
Normal file
@@ -0,0 +1,6 @@
|
||||
namespace FaKrosnoApi.Services;
|
||||
|
||||
public interface IEmailService
|
||||
{
|
||||
void SendEmail(string subject, string body);
|
||||
}
|
||||
6
FaKrosnoApi/Services/IScheduleJobService.cs
Normal file
6
FaKrosnoApi/Services/IScheduleJobService.cs
Normal file
@@ -0,0 +1,6 @@
|
||||
namespace FaKrosnoApi.Services;
|
||||
|
||||
public interface IScheduleJobService
|
||||
{
|
||||
Task ExecuteAsync();
|
||||
}
|
||||
29
FaKrosnoApi/Services/ScheduleJobService.cs
Normal file
29
FaKrosnoApi/Services/ScheduleJobService.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using System.Text;
|
||||
using SytelineSaAppEfDataModel.Dtos;
|
||||
using SytelineSaAppEfDataModel.Services;
|
||||
|
||||
namespace FaKrosnoApi.Services;
|
||||
|
||||
public class ScheduleJobService(IEmailService emailService, IServiceScopeFactory scopeFactory) : IScheduleJobService
|
||||
{
|
||||
public async Task ExecuteAsync()
|
||||
{
|
||||
using var scope = scopeFactory.CreateScope();
|
||||
IEdiCustomerOrderService ediCustomerOrderService = scope.ServiceProvider.GetRequiredService<IEdiCustomerOrderService>();
|
||||
IEnumerable<EdiCustomerOrderTranslateDto> missingOrders =
|
||||
(await ediCustomerOrderService.FindMissingOrders(new DateTime(2025, 2, 5))).ToList();
|
||||
|
||||
if (missingOrders.Any())
|
||||
{
|
||||
StringBuilder result = new StringBuilder();
|
||||
result.AppendLine("Znaleziono brakujące zamówienia w bazie 'edi_co':");
|
||||
|
||||
foreach (EdiCustomerOrderTranslateDto missingOrder in missingOrders)
|
||||
{
|
||||
result.AppendLine($"- {missingOrder.EdiCoCoNum}");
|
||||
}
|
||||
|
||||
emailService.SendEmail("Znaleziono brakujące zamówienia!", result.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
32
FaKrosnoApi/Services/TimedHostedService.cs
Normal file
32
FaKrosnoApi/Services/TimedHostedService.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
using SytelineSaAppEfDataModel.Services;
|
||||
|
||||
namespace FaKrosnoApi.Services;
|
||||
|
||||
public class TimedHostedService(IServiceScopeFactory scopeFactory) : IHostedService, IDisposable
|
||||
{
|
||||
private Timer? _timer;
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromMinutes(30));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void DoWork(object? state)
|
||||
{
|
||||
using var scope = scopeFactory.CreateScope();
|
||||
var scheduledJob = scope.ServiceProvider.GetRequiredService<IScheduleJobService>();
|
||||
scheduledJob.ExecuteAsync();
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_timer?.Change(Timeout.Infinite, 0);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_timer?.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
{
|
||||
"ConnectionStrings": {
|
||||
"FaKrosnoConnection": "Server=192.168.0.7;Database=fakrosnotest;User Id=sa;Password=Tetum#2021!;TrustServerCertificate=true",
|
||||
"SytelineSaAppConnection": "Server=192.168.0.7;Database=SL_PRODTEST_SA_APP;User Id=sa;Password=Tetum#2021!;TrustServerCertificate=true"
|
||||
"SytelineSaAppConnection": "Server=192.168.0.7;Database=SL_PROD_SA_APP;User Id=sa;Password=Tetum#2021!;TrustServerCertificate=true",
|
||||
"OrdersManagementConnection": "Server=192.168.0.7;Database=OrdersManagement;User Id=sa;Password=Tetum#2021!;TrustServerCertificate=true"
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
@@ -16,5 +17,16 @@
|
||||
},
|
||||
"Host": {
|
||||
"Urls": "http://0.0.0.0:5555"
|
||||
},
|
||||
"EmailSettings": {
|
||||
"SmtpServer": "poczta.fakrosno.pl",
|
||||
"Port": 587,
|
||||
"SenderEmail": "edi@fakrosno.pl",
|
||||
"SenderPassword": "F@Krosno2014",
|
||||
"RecipientEmail": "piotr.kus@fakrosno.pl",
|
||||
"UseSsl": false
|
||||
},
|
||||
"JobSettings": {
|
||||
"QueryIntervalMinutes": 30
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user