Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
14 kB
2
Indexable
Never
using AutoMapper;
using Dasync.Collections;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using ProvidersLeroyMerlin.Data;
using ProvidersLeroyMerlin.Dtos.DSV;
using ProvidersLeroyMerlin.Entities.Allerts;
using ProvidersLeroyMerlin.Entities.ApplicationErrors;
using ProvidersLeroyMerlin.Entities.Orders;
using ProvidersLeroyMerlin.Infrastructure;
using ProvidersLeroyMerlin.Services.Allerts;
using ProvidersLeroyMerlin.Services.ApiKeyLogs;
using ProvidersLeroyMerlin.Services.ApplicationErrors;
using ProvidersLeroyMerlin.Services.Common;
using ProvidersLeroyMerlin.Services.DSV;
using ProvidersLeroyMerlin.Services.Emails;
using ProvidersLeroyMerlin.Services.Localization;
using ProvidersLeroyMerlin.Services.Mail;
using ProvidersLeroyMerlin.Services.SupplierOrders;
using ProvidersLeroyMerlin.Services.User;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ProvidersLeroyMerlin.Services.ScheduledTasks
{
    public class VerifyDSVOrders : IScheduledTask
    {
        //https://crontab.guru  - The quick and simple editor for cron schedule expressions by Cronitor
        string scheduleGet = "*/20 * * * *";  // din minut in minut
        string taskNameGet = ScheduledTasksConstants.VerifyDSVOrders;
        public string Schedule { get { return scheduleGet; } set { this.scheduleGet = value; } }
        public string TaskName { get { return taskNameGet; } set { this.taskNameGet = value; } }

        private readonly IServiceProvider _provider;
        private readonly IDSVService _dSVService;
        private readonly IUserService _userService;
        private readonly UserDSVScanOrders _configUser;
        private readonly IMapper _mapService;
        private readonly IUserActivityLogService _userActivityLogService;

        public VerifyDSVOrders(IServiceProvider serviceProvider, IOptions<UserDSVScanOrders> configUser)
        {
            this._provider = serviceProvider;
            this._configUser = configUser.Value;

        }

        public async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            using (IServiceScope scope = _provider.CreateScope())
            {
                var allertTypeLogService = scope.ServiceProvider.GetRequiredService<IAllertTypeLogService>();
                var allertTypeService = scope.ServiceProvider.GetRequiredService<IAllertTypeService>();
                var localizationService = scope.ServiceProvider.GetRequiredService<ILocalizationService>();
                var allertTypeStoresService = scope.ServiceProvider.GetRequiredService<IAllertTypeStoreService>();
                var dictionaryService = scope.ServiceProvider.GetRequiredService<IDictionaryService>();
                var mailService = scope.ServiceProvider.GetRequiredService<IMailService>();
                var emailAccountXEmailTypesService = scope.ServiceProvider.GetRequiredService<IEmailAccountXEmailTypesService>();

                var userActivityLogService = scope.ServiceProvider.GetRequiredService<IUserActivityLogService>();
                var userService = scope.ServiceProvider.GetRequiredService<IUserService>();
                var dSVService = scope.ServiceProvider.GetRequiredService<IDSVService>();
                var mapService = scope.ServiceProvider.GetRequiredService<IMapper>();
                var apiKeyLogService = scope.ServiceProvider.GetRequiredService<IApiKeyLogService>();
                var readFromApiService = scope.ServiceProvider.GetRequiredService<IReadFromApiService>();

                if (allertTypeLogService != null && allertTypeService != null && allertTypeStoresService != null && localizationService != null)
                {
                    var allertType = await allertTypeService.GetAllertTypeByName(ScheduledTasksConstants.VerifyDSVOrders);

                    if (!allertType.LastRunEndDate.HasValue)
                        throw new Exception("VerifyDSVOrders - LastRunEndDate is null !");

                    DateTime currentTime = DateTime.Now;

                    allertType.LastRunStartDate = currentTime;
                    allertType.LastRunEndDate = null;
                    allertType.HadError = false;

                    await allertTypeService.UpdateAllertType(allertType);

                    AllertTypeLog allertTypeLog = new AllertTypeLog
                    {
                        StartRunDate = DateTime.Now,
                        HadError = false,
                        Comment = ""
                    };

                    try
                    {
                        allertTypeLog.AllertTypeId = allertType.Id;

                        if (allertType.Valid)
                        {
                            var currentUser = await userService.GetUserByADAsync(_configUser.Username, _configUser.Domain);
                            if (currentUser == null)
                                throw new ArgumentException("DSV.ScanOrders.InvalidUser");
                            if (!currentUser.IsEnabled)
                                throw new ArgumentException("DSV.ScanOrders.InactiveUser");



                            var dsvOrdersIList = await dSVService.GetAllOrdersWithStatusFalse();
                            List<DSVOrders> dsvOrders = new List<DSVOrders>(dsvOrdersIList);
                            if (dsvOrders != null)
                            {
                                List<DSVOrderToScan> orders = mapService.Map<List<DSVOrderToScan>>(dsvOrders);

                                if (orders != null && orders.Count > 0)
                                {
                                    var storeCodes = orders.Select(x => x.StoreCode).Distinct();

                                    var bag = new ConcurrentBag<DSVReturnedOrderToScan>();
                                    await storeCodes.ParallelForEachAsync(async storeCode =>
                                    {
                                        var dSVOrderToScan = new DSVOrdersToScan();
                                        List<DSVOrderToScan> orderListToScan = orders.Where(x => x.StoreCode == storeCode).Select(x => new DSVOrderToScan()
                                        {
                                            OrderNumber = x.OrderNumber,
                                            StoreCode = x.StoreCode
                                        }).ToList();
                                        dSVOrderToScan.OrdersToScan = orderListToScan;
                                        DSVReturnedOrdersToScan resultOrders = new DSVReturnedOrdersToScan();

                                        using (IServiceScope current = _provider.CreateScope())
                                        {
                                            IDSVService localDsvService = current.ServiceProvider.GetRequiredService<IDSVService>();
                                            resultOrders = await localDsvService.ScanOrders(dSVOrderToScan, currentUser);
                                        }

                                        if (resultOrders != null && resultOrders.ReturnedOrdersToScan != null && resultOrders.ReturnedOrdersToScan.Any())
                                        {
                                            foreach (var item in dsvOrders.Where(x => resultOrders.ReturnedOrdersToScan.Where(t => t.OrderNumber == x.OrderNumber).Any()))
                                            {
                                                item.Status = true;
                                                item.StatusChangeDate = DateTime.Now;
                                            }
                                            foreach (var i in resultOrders.ReturnedOrdersToScan)
                                            {
                                                bag.Add(i);
                                            }
                                        }
                                    }, maxDegreeOfParallelism: 10);

                                    await dSVService.UpdateDsvOrders(dsvOrders);
                                    var message = "Succes! " + JsonConvert.SerializeObject(bag);
                                    await apiKeyLogService.CreateFakeApiKeyLog(message, JsonConvert.SerializeObject(bag));
                                    // apeleaza endpointul lor cu agregatul de rezultate
                                }
                            }

                            allertTypeLog.HadError = false;
                            allertTypeLog.RunEndDate = DateTime.Now;
                            allertTypeLog.Comment = "Taskul a rulat cu success";



                            await allertTypeLogService.CreateAllertTypeLog(allertTypeLog);



                            allertType.LastRunStartDate = currentTime;
                            allertType.LastRunEndDate = DateTime.Now;
                            allertType.HadError = false;



                            await allertTypeService.UpdateAllertType(allertType);
                        }
                        else
                        {
                            allertTypeLog.HadError = false;
                            allertTypeLog.RunEndDate = DateTime.Now;
                            allertTypeLog.Comment = "Taskul a fost invalidat!";
                            await allertTypeLogService.CreateAllertTypeLog(allertTypeLog);

                            allertType.LastRunStartDate = currentTime;
                            allertType.LastRunEndDate = DateTime.Now;
                            allertType.HadError = false;

                            await allertTypeService.UpdateAllertType(allertType);

                            var emailType = await dictionaryService.GetDetailByNames(DictionaryConstants.EmailTypes, DictionaryConstants.EmailTypeImportError);
                            if (emailType == null)
                                throw new Exception("VerifyDSVOrders - invalid email type");
                            var emailAccountXEmailTypes = await emailAccountXEmailTypesService.GetEmailAccountXEmailTypesByEmailTypeId(emailType.Id);
                            if (emailAccountXEmailTypes == null)
                                throw new Exception("VerifyDSVOrders - invalid email type");
                            foreach (var emailAccountXEmailType in emailAccountXEmailTypes)
                            {
                                await mailService.SendErrorAlert(emailAccountXEmailType.EmailAccount, String.Format("Eroare: \"{0}\" la data: {1}", allertTypeLog.Comment, allertTypeLog.RunEndDate), String.Format("{0} - {1}", emailType.Name, ScheduledTasksConstants.VerifyDSVOrders), allertType.Id);
                            }
                        }
                    }

                    catch (Exception e)
                    {

                        await userActivityLogService.WriteUserActivityLog(e.InnerException.ToString() + " " + e.Message.ToString(), "Exceptie2", 1, String.Format("test", "ex2", DateTime.Now, e.InnerException.ToString() + " " + e.Message.ToString()));
                        if (allertType != null)
                            allertTypeLog.AllertTypeId = allertType.Id;

                        allertTypeLog.RunEndDate = DateTime.Now;
                        allertTypeLog.HadError = true;
                        allertTypeLog.Comment = ScheduledTasksConstants.VerifyDSVOrders + " " + e.StackTrace;

                        await allertTypeLogService.CreateAllertTypeLog(allertTypeLog);

                        allertType.LastRunStartDate = currentTime;
                        allertType.LastRunEndDate = DateTime.Now;
                        allertType.HadError = true;

                        await allertTypeService.UpdateAllertType(allertType);

                        var emailType = await dictionaryService.GetDetailByNames(DictionaryConstants.EmailTypes, DictionaryConstants.EmailTypeImportError);
                        if (emailType == null)
                            throw new Exception("VerifyDSVOrders - invalid email type");
                        var emailAccountXEmailTypes = await emailAccountXEmailTypesService.GetEmailAccountXEmailTypesByEmailTypeId(emailType.Id);
                        if (emailAccountXEmailTypes == null)
                            throw new Exception("VerifyDSVOrders - invalid email type");
                        foreach (var emailAccountXEmailType in emailAccountXEmailTypes)
                        {
                            await mailService.SendErrorAlert(emailAccountXEmailType.EmailAccount, String.Format("Eroare: \"{0}\" la data: {1}", allertTypeLog.Comment, allertTypeLog.RunEndDate), String.Format("{0} - {1}", emailType.Name, ScheduledTasksConstants.VerifyDSVOrders), allertType.Id);
                        }
                    }
                }
            }
        }
    }
}