using FrameworkBLL.SchedulerTaskGenerator; using FrameworkDAL.CustomCode.AutoScheduler; using FrameworkDAL.DTO.AutoScheduler; using GB5Shared.DTO.Framework.Login; using GB5Shared.Resource.Response; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Threading; using System.Threading.Tasks; namespace FrameworkBLL.AutoScheduler { public class AutoSchedulerBLL : IAutoSchedulerBLL { private readonly IAutoSchedulerDAL _AutoSchedulerDAL; private readonly IQuartzSyncService _QuartzSyncService; private readonly ILogger _Logger; public AutoSchedulerBLL( IAutoSchedulerDAL AutoSchedulerDAL, IQuartzSyncService QuartzSyncService, ILogger Logger) { _AutoSchedulerDAL = AutoSchedulerDAL; _QuartzSyncService = QuartzSyncService; _Logger = Logger; } public async Task GetAutoScheduler(AutoSchedulerDTO AutoSchedulerDTO, LoginDTO LoginDTO) { try { return await _AutoSchedulerDAL.GetAutoScheduler(AutoSchedulerDTO, LoginDTO); } catch (Exception) { throw; } } public async Task SaveAutoScheduler(AutoSchedulerDTO AutoSchedulerDTO, LoginDTO LoginDTO) { try { if (AutoSchedulerDTO.JobDefineId == 0) { var (message, jobId) = await _AutoSchedulerDAL.SaveAutoScheduler(AutoSchedulerDTO, LoginDTO); try { await _QuartzSyncService.SyncJobAsync(jobId, LoginDTO); } catch (Exception syncEx) { _Logger.LogWarning(syncEx, "AutoSchedulerBLL.SaveAutoScheduler: SyncJobAsync failed for JobId={JobId} — job saved, trigger not synced", jobId); } return message; } else { await _AutoSchedulerDAL.UpdateAutoSchedulerAsync(AutoSchedulerDTO, LoginDTO, CancellationToken.None); try { await _QuartzSyncService.SyncJobAsync(AutoSchedulerDTO.JobDefineId, LoginDTO); } catch (Exception syncEx) { _Logger.LogWarning(syncEx, "AutoSchedulerBLL.SaveAutoScheduler: SyncJobAsync failed for JobId={JobId} on update — trigger not re-synced", AutoSchedulerDTO.JobDefineId); } return SuccessResponse.UpdateSuccess; } } catch (Exception ex) { throw new Exception("Error while saving/updating AutoScheduler", ex); } } public async Task GetJobDefineAsync(int jobId, LoginDTO login, CancellationToken ct) { var rows = await _AutoSchedulerDAL.GetJobDefineAsync(jobId, login, ct).ConfigureAwait(false); return JsonConvert.SerializeObject(rows); } public async Task DeleteJobDefineAsync(int jobId, LoginDTO login, CancellationToken ct) { try { try { await _QuartzSyncService.RemoveJobAsync(jobId, login, ct).ConfigureAwait(false); } catch (Exception removeEx) { _Logger.LogWarning(removeEx, "AutoSchedulerBLL.DeleteJobDefineAsync: RemoveJobAsync failed for JobId={JobId} — proceeding with DB delete", jobId); } await _AutoSchedulerDAL.DeleteJobDefineAsync(jobId, login, ct).ConfigureAwait(false); return SuccessResponse.DeleteSuccessMessage; } catch (Exception ex) { throw new Exception($"Error while deleting JobDefine {jobId}", ex); } } } }