Esempio n. 1
0
        public EligibilityUploadListModel GetEligibilityUploadDetails(int pageNumber, int pageSize, EligibilityUploadListModelFilter filter, out int totalRecords)
        {
            var eligibilityUploads = (IReadOnlyCollection <EligibilityUpload>)_eligibilityUploadRepository.GetByFilter(pageNumber, pageSize, filter, out totalRecords);

            if (eligibilityUploads == null || !eligibilityUploads.Any())
            {
                return(null);
            }

            var successfileIds = eligibilityUploads.Select(s => s.FileId).ToArray();
            var failedfileIds  = eligibilityUploads.Where(x => x.LogFileId.HasValue).Select(s => s.LogFileId.Value).ToArray();
            var fileIds        = successfileIds.Concat(failedfileIds).ToArray();
            var accountIds     = eligibilityUploads.Select(x => x.AccountId).ToArray();
            var accounts       = _corporateAccountRepository.GetByIds(accountIds);

            IEnumerable <FileModel> fileModels = null;

            if (fileIds != null && fileIds.Any())
            {
                var files = _fileRepository.GetByIds(fileIds);

                if (files != null && files.Any())
                {
                    fileModels = GetFileModelFromFile(files, _mediaRepository.GetEligibilityUploadMediaFileLocation());
                }
            }
            var eligibilityUploadByIds = eligibilityUploads.Select(c => c.UploadedBy).ToArray();
            IEnumerable <OrderedPair <long, string> > uploadedbyAgentNameIdPair = null;

            uploadedbyAgentNameIdPair = _organizationRoleUserRepository.GetNameIdPairofUsers(eligibilityUploadByIds).ToArray();

            return(_eligibilityUploadListModelFactory.Create(fileModels, eligibilityUploads, uploadedbyAgentNameIdPair, accounts));
        }
Esempio n. 2
0
        public void PollForAppointmentBookExport()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }
                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

                foreach (var account in corporateAccounts)
                {
                    try
                    {
                        _logger.Info(string.Format("Generating AppointmentBooked for accountId {0} and account tag {1}. ", account.Id, account.Tag));

                        var fromDate = DateTime.Now.Year > _cutOfDate.Date.Year ? DateTime.Today.GetFirstDateOfYear() : _cutOfDate;

                        var destinationPath     = string.Format(_optumAppointmentBookedReportDownloadPath, account.FolderName, fromDate.Year);
                        var appointmentSettings = string.Format(_appointmentSettings, account.Tag);
                        var customSettings      = _customSettingManager.Deserialize(appointmentSettings);

                        try
                        {
                            DirectoryOperationsHelper.DeleteDirectory(destinationPath, true);
                        }
                        catch (Exception ex)
                        {
                            _logger.Error("Some error occurred while deleting directory at path: " + destinationPath);
                            _logger.Error("Message: " + ex.Message);
                            _logger.Error("Stack Trace: " + ex.StackTrace);
                        }

                        var toDate = DateTime.Today.GetLastDateOfYear();

                        AppointmentsBooked(new AppointmentsBookedListModelFilter {
                            EventFrom = fromDate, EventTo = toDate.Date, AccountId = account.Id, Tag = account.Tag
                        }, destinationPath);

                        var fileName = destinationPath + string.Format(@"\AppointmentBookedReport_{0}.csv", DateTime.Today.ToString("yyyyMMdd"));

                        if (DirectoryOperationsHelper.IsFileExist(fileName))
                        {
                            _pgpFileEncryptionHelper.EncryptFile(account, fileName);
                        }

                        customSettings.LastTransactionDate = toDate;
                        _customSettingManager.SerializeandSave(appointmentSettings, customSettings);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(string.Format("Exception For AccountId {0} and Account Tag {1} : \n Error {2} \n Trace: {3} \n\n\n", account.Id, account.Tag, ex.Message, ex.StackTrace));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Main App: \n Error {0} \n Trace: {1} \n\n\n", ex.Message, ex.StackTrace));
            }
        }
Esempio n. 3
0
        public ListModelBase <ConfirmationReportViewModel, ConfirmationReportFilter> GetConfirmationReport(int pageNumber, int pageSize, ModelFilterBase filter, out int totalRecords)
        {
            var confirmationReportFilter   = filter as ConfirmationReportFilter ?? new ConfirmationReportFilter();
            var confirmationQueueCustomers = _callQueueCustomerRepository.GetForConfirmationReport(confirmationReportFilter, pageNumber, pageSize, out totalRecords);

            var collection = new List <ConfirmationReportViewModel>();

            if (confirmationQueueCustomers.IsNullOrEmpty())
            {
                return(new ConfirmationReportListModel
                {
                    Collection = new List <ConfirmationReportViewModel>(),
                    Filter = confirmationReportFilter
                });
            }

            var customerIds = confirmationQueueCustomers.Select(x => x.CustomerId.Value).ToArray();
            var customers   = _customerRepository.GetCustomers(customerIds);

            var callQueueCustomerCalls = _callQueueCustomerCallRepository.GetByCallQueueCustomerIds(confirmationQueueCustomers.Select(x => x.Id));

            var calls = _callCenterCallRepository.GetCallByCustomerIdAndCallQueue(customerIds, HealthPlanCallQueueCategory.AppointmentConfirmation);

            var eventIds = confirmationQueueCustomers.Where(x => x.EventId.HasValue && x.EventId.Value > 0).Select(x => x.EventId.Value).ToArray();
            var events   = _eventService.GetEventBasicInfoEventIds(eventIds);

            var eventCustomerIds = confirmationQueueCustomers.Where(x => x.EventCustomerId.HasValue).Select(x => x.EventCustomerId.Value).ToArray();
            var eventCustomers   = _eventCustomerRepository.GetByIds(eventCustomerIds);

            var eventCustomersByEventIdsAndCustomerIds = _eventCustomerRepository.GetEventCustomersByEventIdsCustomerIds(eventIds, customerIds);

            if (!eventCustomersByEventIdsAndCustomerIds.IsNullOrEmpty())
            {
                eventCustomersByEventIdsAndCustomerIds = eventCustomersByEventIdsAndCustomerIds.Where(x => !eventCustomerIds.Contains(x.Id)).ToArray();
                eventCustomers = eventCustomers.Concat(eventCustomersByEventIdsAndCustomerIds);
            }

            var appointments = _appointmentRepository.GetByIds(eventCustomers.Where(ec => ec.AppointmentId.HasValue).Select(ec => ec.AppointmentId.Value).ToList());

            var healthPlanIds          = confirmationQueueCustomers.Where(x => x.HealthPlanId.HasValue).Select(x => x.HealthPlanId.Value).ToArray();
            var healthPlans            = _corporateAccountRepository.GetByIds(healthPlanIds);
            var restrictionIdNamePairs = _corporateAccountRepository.GetRestrictionIdNamePairs(healthPlanIds);

            var calledByAgentIds         = calls.Select(x => x.CreatedByOrgRoleUserId).Distinct().ToArray();
            var calledByAgentNameIdPairs = _organizationRoleUserRepository.GetNameIdPairofUsers(calledByAgentIds).ToArray();

            var confirmedByAgentIds         = eventCustomers.Where(x => x.ConfirmedBy.HasValue).Select(x => x.ConfirmedBy.Value).ToArray();
            var confirmedByAgentNameIdPairs = _organizationRoleUserRepository.GetNameIdPairofUsers(confirmedByAgentIds).ToArray();

            collection = _confirmationReportingFactory.Create(confirmationQueueCustomers, customers, events, calls, eventCustomers, appointments, healthPlans, restrictionIdNamePairs,
                                                              confirmedByAgentNameIdPairs, calledByAgentNameIdPairs, callQueueCustomerCalls).ToList();

            return(new ConfirmationReportListModel
            {
                Collection = collection,
                Filter = confirmationReportFilter
            });
        }
        public void PollForCallQueue()
        {
            try
            {
                _logger.Info("Entering Single Health Plan NoShows Polling Agent");
                var callQueue = _callQueueRepository.GetCallQueueByCategory(HealthPlanCallQueueCategory.NoShows);
                var criterias = _healthPlanCallQueueCriteriaService.GetHealthPlanCallQueueCriteriaNotGenerated(callQueue.Id);

                var healthPlanIds = criterias.Where(x => x.HealthPlanId != null).Select(x => x.HealthPlanId.Value).ToArray();
                var healthPlans   = _corporateAccountRepository.GetByIds(healthPlanIds);

                foreach (var criteria in criterias)
                {
                    try
                    {
                        _logger.Info(string.Format("Generating single No Show call queue."));
                        _healthPlanCallQueueAssignmentRepository.DeleteByCriteriaId(criteria.Id);

                        if (criteria.HealthPlanId.HasValue)
                        {
                            var healthPlan = healthPlans.First(x => x.Id == criteria.HealthPlanId.Value);
                            _healthPlanCallRoundService.SaveNoShowCallQueueCustomers(healthPlan, criteria, callQueue, _logger);
                        }

                        _logger.Info(string.Format("Completed single No Show call queue."));

                        criteria.IsQueueGenerated       = true;
                        criteria.LastQueueGeneratedDate = DateTime.Now;

                        _healthPlanCallQueueCriteriaService.Save(criteria);
                    }
                    catch (Exception exception)
                    {
                        _logger.Error(string.Format("Error while generating call queue No show  customer data for Criteria Id: {0} \n message: {1} stack trace {2}", criteria.Id, exception.Message, exception.StackTrace));
                    }
                }

                callQueue.IsQueueGenerated       = true;
                callQueue.LastQueueGeneratedDate = DateTime.Now;
                _callQueueRepository.Save(callQueue);
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Error while pulling single call round call queue. Message {0} \n Stack Trace {1}", ex.Message, ex.StackTrace));
            }
        }
Esempio n. 5
0
        public void ResultExport()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }
                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

                foreach (var account in corporateAccounts)
                {
                    try
                    {
                        var resultExportSettings = string.Format(_resultExportSettings, account.Tag);
                        var houseCallHafResultExportDownloadPath = string.Format(_settings.HousecallHafResultReportDownloadPath, account.FolderName);

                        var customSettings = _customSettingManager.Deserialize(resultExportSettings);

                        var fromDate = customSettings.LastTransactionDate == null ? _settings.HousecallOutreachReportCutOfDate : new DateTime(customSettings.LastTransactionDate.Value.Year, 1, 1);
                        var toDate   = DateTime.Now;

                        _logger.Info(string.Format("Generating Result Report for Account ID : {0} and Tag : {1}", account.Id, account.Tag));

                        GenerateResultReport(account.Id, fromDate, toDate, houseCallHafResultExportDownloadPath);

                        customSettings.LastTransactionDate = toDate;
                        _customSettingManager.SerializeandSave(resultExportSettings, customSettings);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(string.Format("Account Id {0} and account Tag {1}  Message: {2} \n Stack Trace: {3} ", account.Id, account.Tag, ex.Message, ex.StackTrace));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Message: {0} \n Stack Trace: {1} ", ex.Message, ex.StackTrace));
            }
        }
        public void PollForDailyPatientRecapReport()
        {
            try
            {
                /*if (!_daysOfWeek.Contains(DateTime.Today.DayOfWeek))
                 * {
                 *  _logger.Info(string.Format("todays day : {0}, export set to run on {1}", DateTime.Today.DayOfWeek, string.Join(", ", _daysOfWeek)));
                 *  return;
                 * }*/

                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }
                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

                foreach (var account in corporateAccounts)
                {
                    try
                    {
                        _logger.Info(string.Format("Generating Daily Patient Recap Report for accountId {0} and account tag {1}. ", account.Id, account.Tag));

                        var fromDate = new DateTime(DateTime.Now.Year, 1, 1);
                        var toDate   = DateTime.Now.Date;

                        var destinationPath = string.Format(_dailyPatientRecapReportDestinationPathSettings, account.FolderName);

                        try
                        {
                            var files = Directory.GetFiles(destinationPath);
                            if (files.Any())
                            {
                                foreach (var file in files)
                                {
                                    File.Delete(file);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.Error("Error deleting files from : " + destinationPath);
                            _logger.Error(string.Format("Error {0} \n Trace: {1} \n", ex.Message, ex.StackTrace));
                        }

                        _logger.Info(string.Format("Generating Daily Patient Recap Report Date From. {0} To Date {1}", fromDate.Date.ToShortDateString(), toDate.ToShortDateString()));

                        DailyPatientRecapReport(new DailyPatientRecapModelFilter {
                            EventDateFrom = fromDate, EventDateTo = toDate.Date, CorporateAccountId = account.Id, Tag = account.Tag
                        }, destinationPath);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(string.Format("Exception For AccountId {0} and Account Tag {1} : \n Error {2} \n Trace: {3} \n\n\n", account.Id, account.Tag, ex.Message, ex.StackTrace));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Main App: \n Error {0} \n Trace: {1} \n\n\n", ex.Message, ex.StackTrace));
            }
        }
Esempio n. 7
0
        public void ResultExport()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }

                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

                foreach (var account in corporateAccounts)
                {
                    try
                    {
                        _logger.Info(string.Format("Generating for accountId {0} and account tag {1}. ", account.Id, account.Tag));

                        var resultExportSettings          = string.Format(_resultExportSettings, account.Tag);
                        var optumResultExportDownloadPath = string.Format(_optumeResultExportDownloadPath, account.FolderName);

                        var customSettings = _customSettingManager.Deserialize(resultExportSettings);

                        var fromDate = customSettings.LastTransactionDate ?? DateTime.Today.GetFirstDateOfYear();

                        var toDate = DateTime.Now;

                        if (_optumAccountIds.Contains(account.Id))
                        {
                            try
                            {
                                DirectoryOperationsHelper.DeleteDirectory(optumResultExportDownloadPath, true);
                            }
                            catch (Exception ex)
                            {
                                _logger.Error("Some error occurred while deleting directory at path: " + optumResultExportDownloadPath);
                                _logger.Error("Message: " + ex.Message);
                                _logger.Error("Stack Trace: " + ex.StackTrace);
                            }
                        }

                        string[] showHiddenColumns = new string[1];

                        if (_optumNVSettingAccountIds.Contains(account.Id))
                        {
                            showHiddenColumns[0] = "Mrn";
                        }

                        _logger.Info(" Create Destination Path: " + optumResultExportDownloadPath);

                        DirectoryOperationsHelper.CreateDirectoryIfNotExist(optumResultExportDownloadPath);

                        var fileName = optumResultExportDownloadPath + string.Format(@"\ResultExport_{0}.csv", DateTime.Now.Date.ToString("yyyyMMdd"));

                        if (_optumAccountIds.Contains(account.Id))
                        {
                            GenerateCummulativeReport(fromDate, toDate, account, optumResultExportDownloadPath, showHiddenColumns, fileName);
                        }
                        else
                        {
                            DateTime?stopSendingPdftoHealthPlanDate = null;
                            if (account != null && account.IsHealthPlan)
                            {
                                stopSendingPdftoHealthPlanDate = _stopSendingPdftoHealthPlanDate;
                            }

                            _pcpResultExportServiceHelper.ResultExport(fromDate, toDate, account.Id, optumResultExportDownloadPath, account.Tag, resultExportFileName: fileName, showHiddenColumns: showHiddenColumns, stopSendingPdftoHealthPlanDate: stopSendingPdftoHealthPlanDate);
                        }

                        if (DirectoryOperationsHelper.IsFileExist(fileName))
                        {
                            _pgpFileEncryptionHelper.EncryptFile(account, fileName);
                        }
                        else if (_optumNVSettingAccountIds.Contains(account.Id))
                        {
                            _pcpResultExportServiceHelper.WriteCsvHeader(fileName, showHiddenColumns);
                        }

                        customSettings.LastTransactionDate = toDate;
                        _customSettingManager.SerializeandSave(resultExportSettings, customSettings);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(string.Format("Account Id {0} and account Tag {1}  Message: {2} \n Stack Trace: {3} ", account.Id, account.Tag, ex.Message, ex.StackTrace));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Message: {0} \n Stack Trace: {1} ", ex.Message, ex.StackTrace));
            }
        }
        public void PollForHealthPlanMailRoundCallQueue()
        {
            try
            {
                var callDate           = DateTime.Now;
                var campaigns          = new List <Campaign>();
                var campaignByCallDate = _campaignRepository.GeCotporateCampaignForCallQueue(callDate);

                if (!campaignByCallDate.IsNullOrEmpty())
                {
                    campaigns.AddRange(campaignByCallDate);
                }

                var campaignsNotGenerated = _campaignRepository.GetCotporateCampaignForNotGenerated();

                if (!campaignsNotGenerated.IsNullOrEmpty())
                {
                    var campaigIds = campaigns.Select(x => x.Id).ToArray();
                    if (!campaigIds.IsNullOrEmpty())
                    {
                        campaignsNotGenerated = campaignsNotGenerated.Where(x => !campaigIds.Contains(x.Id)).ToArray();
                        if (!campaignsNotGenerated.IsNullOrEmpty())
                        {
                            campaigns.AddRange(campaignsNotGenerated);
                        }
                    }
                    else
                    {
                        campaigns.AddRange(campaignsNotGenerated);
                    }
                }

                if (campaigns.IsNullOrEmpty())
                {
                    _logger.Info("No Campaigns found for call queue generation.");
                    return;
                }

                var healthPlanIds = campaigns.Select(x => x.AccountId).ToArray();
                var healthPlans   = _corporateAccountRepository.GetByIds(healthPlanIds);

                foreach (var campaign in campaigns)
                {
                    try
                    {
                        _logger.Info("Started creating Mail Round call queue for campaign: " + campaign.Name);

                        var campaignActivites = _campaignActivityRepository.GetByCampaignId(campaign.Id);

                        var outboundCallAcivity = campaignActivites.FirstOrDefault(ca => ca.TypeId == (long)CampaignActivityType.OutboundCall && ca.ActivityDate.Date == callDate.Date);

                        if (outboundCallAcivity == null)
                        {
                            outboundCallAcivity = campaignActivites.Where(ca => ca.TypeId == (long)CampaignActivityType.OutboundCall).OrderByDescending(x => x.ActivityDate).FirstOrDefault();
                        }

                        if (outboundCallAcivity == null)
                        {
                            continue;
                        }

                        var firstDirectMailActivity = campaignActivites.Where(ca => ca.TypeId == (long)CampaignActivityType.DirectMail && ca.ActivityDate <= outboundCallAcivity.ActivityDate).OrderBy(ca => ca.ActivityDate).FirstOrDefault();

                        if (firstDirectMailActivity == null)
                        {
                            _logger.Info("No Direct mail activity before outbound call.");
                            _logger.Info("Completed creating Mail Round call queue for campaign: " + campaign.Name);
                            continue;
                        }

                        var criterias = _healthPlanCallQueueCriteriaRepository.GetByCampaignId(campaign.Id);
                        if (criterias.IsNullOrEmpty())
                        {
                            _logger.Info("No Criteria has been created.");
                            _logger.Info("Completed creating Mail Round call queue for campaign: " + campaign.Name);
                            continue;
                        }

                        foreach (var campaingnCriteria in criterias)
                        {
                            try
                            {
                                if (campaingnCriteria.IsQueueGenerated && campaingnCriteria.LastQueueGeneratedDate.HasValue && campaingnCriteria.LastQueueGeneratedDate.Value.Date == callDate.Date)
                                {
                                    _logger.Info("Call queue has been already generated for the campaign.");
                                    _logger.Info("Completed creating Mail Round call queue for campaign: " + campaign.Name);
                                    continue;
                                }

                                _healthPlanCallQueueAssignmentRepository.DeleteByCriteriaId(campaingnCriteria.Id);

                                var healthPlan = healthPlans.Single(x => x.Id == campaign.AccountId);

                                var callQueue = _callQueueRepository.GetCallQueueByCategory(HealthPlanCallQueueCategory.MailRound);

                                _healthPlanCallRoundService.SaveMailRoundCallQueueCustomers(healthPlan, campaingnCriteria, callQueue, _logger, campaign);

                                campaingnCriteria.IsQueueGenerated       = true;
                                campaingnCriteria.LastQueueGeneratedDate = DateTime.Now;
                                _healthPlanCallQueueCriteriaRepository.Save(campaingnCriteria);
                            }
                            catch (Exception ex)
                            {
                                _logger.Error("Some Error Occurred While Generating Campaign Criteria Data: " + campaign.Name);
                                _logger.Error("Message: " + ex.Message);
                                _logger.Error("Stack Trace: " + ex.StackTrace);
                            }
                        }

                        _logger.Info("Completed creating Mail Round call queue for campaign: " + campaign.Name);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Error while Creating Mail Round call queue for campaign: " + campaign.Name);
                        _logger.Error("Message : " + ex.Message);
                        _logger.Error("Stack Trace : " + ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error while Polling Mail Round call queue");
                _logger.Error("Message : " + ex.Message);
                _logger.Error("Stack Trace : " + ex.StackTrace);
            }
        }
Esempio n. 9
0
        public void ResultExport()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }
                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

                foreach (var account in corporateAccounts)
                {
                    try
                    {
                        if (account.Id == _settings.ExcellusAccountId && _settings.ExcellusExportResultReportDayOfWeek != DateTime.Now.DayOfWeek)
                        {
                            _logger.Info(string.Format("The job runs for Account ID : {0} and Tag : {1} on every {2}.", account.Id, account.Tag, _settings.ExcellusExportResultReportDayOfWeek));
                            continue;
                        }
                        if (account.Id == _settings.MedMutualAccountId && _settings.MedMutualExportDay != DateTime.Now.Day)
                        {
                            _logger.Info(string.Format("The job runs for Account ID : {0} and Tag : {1} on {2} of every month.", account.Id, account.Tag, _settings.MedMutualExportDay));
                            continue;
                        }
                        if (account.Id == _settings.FloridaBlueFepAccountId && _settings.FloridaBlueFepExportDayOfWeek != DateTime.Now.DayOfWeek)
                        {
                            _logger.Info(string.Format("The job runs for Account ID : {0} and Tag : {1} on every {2}.", account.Id, account.Tag, _settings.FloridaBlueFepExportDayOfWeek));
                            continue;
                        }

                        string[] customTags = null;

                        if (account.Id == _settings.ExcellusAccountId)
                        {
                            customTags = _settings.ExcellusCustomTags;
                        }
                        else if (account.Id == _settings.HealthNowAccountId)
                        {
                            customTags = _settings.HealthNowCustomTags;
                        }

                        var resultExportSettings = string.Format(_resultExportSettings, account.Tag);
                        var physicianPartnerResultExportDownloadPath = string.Format(_physicianPartnerResultExportDownloadPath, account.FolderName);

                        if (account.Id == _settings.MedMutualAccountId || account.Id == _settings.HealthNowAccountId)
                        {
                            physicianPartnerResultExportDownloadPath = string.Format(_settings.HealthPlanDownloadPath, account.FolderName);
                        }
                        else if (account.Id == _settings.BcbsScAccountId || account.Id == _settings.BcbsScAssessmentAccountId || account.Id == _settings.NammAccountId)
                        {
                            physicianPartnerResultExportDownloadPath = string.Format(_settings.HealthPlanExportRootPath, account.FolderName);
                        }
                        else if (account.Id == _settings.FloridaBlueFepAccountId)
                        {
                            physicianPartnerResultExportDownloadPath = Path.Combine(string.Format(_settings.HealthPlanDownloadPath, account.FolderName), "Reports");
                        }

                        var customSettings = _customSettingManager.Deserialize(resultExportSettings);
                        var sftpSettings   = _sftpCridentialManager.Deserialize(_settings.SftpResouceFilePath + account.Tag + ".xml");

                        var fromDate = customSettings.LastTransactionDate ?? _cutOfDate;
                        var toDate   = DateTime.Now;

                        _logger.Info(string.Format("Generating Result Report for Account ID : {0} and Tag : {1}", account.Id, account.Tag));

                        DateTime?stopSendingPdftoHealthPlanDate = null;
                        if (account != null && account.IsHealthPlan)
                        {
                            stopSendingPdftoHealthPlanDate = _settings.StopSendingPdftoHealthPlanDate;
                        }

                        _pcpResultExportServiceHelper.ResultExport(fromDate, toDate, account.Id, physicianPartnerResultExportDownloadPath, account.Tag, customTags, stopSendingPdftoHealthPlanDate: stopSendingPdftoHealthPlanDate);

                        var resultExportFileName = string.Format(@"ResultExport_{0}.csv", DateTime.Now.Date.ToString("yyyyMMdd"));
                        var fileName             = physicianPartnerResultExportDownloadPath + "\\" + resultExportFileName;

                        if (DirectoryOperationsHelper.IsFileExist(fileName))
                        {
                            _pgpFileEncryptionHelper.EncryptFile(account, fileName);

                            if (account.Id == _settings.FloridaBlueFepAccountId && _settings.SendReportToFloridaBlueSftp)
                            {
                                var destinationSftpPath = _settings.FloridaBlueSftpPath + "\\" + account.FolderName + "\\Download\\Reports";
                                PostFile(fileName, destinationSftpPath, _settings.FloridaBlueSftpHost, _settings.FloridaBlueSftpUserName, _settings.FloridaBlueSftpPassword);
                            }
                            else
                            {
                                PostFileOnClientSftp(sftpSettings, account, fileName, fromDate);
                            }
                        }

                        customSettings.LastTransactionDate = toDate;
                        _customSettingManager.SerializeandSave(resultExportSettings, customSettings);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(string.Format("Account Id {0} and account Tag {1}  Message: {2} \n Stack Trace: {3} ", account.Id, account.Tag, ex.Message, ex.StackTrace));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Message: {0} \n Stack Trace: {1} ", ex.Message, ex.StackTrace));
            }
        }
Esempio n. 10
0
        public void PollForPcpLogSummaryReportExport()
        {
            try
            {
                if (_wellCarePcpSummaryLogReportDayOfWeek != DateTime.Today.DayOfWeek)
                {
                    _logger.Info("Report is schedule to run on " + _wellCarePcpSummaryLogReportDayOfWeek);
                    _logger.Info("Today is day of week " + DateTime.Today.DayOfWeek);
                    _logger.Info(string.Format("Set day of week to {0} to run today ", ((int)DateTime.Today.DayOfWeek)));
                    return;
                }

                if (_accountIds.IsNullOrEmpty())
                {
                    _logger.Info("No Account Ids found");
                    return;
                }

                var directoryPath = _destinationFolderPdfPath + "\\";

                CreateDestinationDirectory(directoryPath);

                var toDate = DateTime.Now;

                var fileName = string.Format("PCPSummaryLog-HealthFair-CA-{0}.csv", toDate.ToString("yyyyMMdd"));


                var accounts = _corporateAccountRepository.GetByIds(_accountIds);

                foreach (var account in accounts)
                {
                    _logger.Info("Running Report for Tag: " + account.Tag);

                    try
                    {
                        var serviceReportSettings = string.Format(_wellCarePcpSummaryLogReportSettingPath, account.Tag);
                        var customSettings        = _customSettingManager.Deserialize(serviceReportSettings);

                        var fromDate = (customSettings.LastTransactionDate != null) ? customSettings.LastTransactionDate.Value : _cutOfDate;

                        PcpSummaryLogReport(account, fromDate, toDate, directoryPath, fileName);

                        customSettings.LastTransactionDate = toDate;
                        _customSettingManager.SerializeandSave(serviceReportSettings, customSettings);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Some Error occurred  for Tag" + account.Tag);
                        _logger.Error("Message: " + ex.Message);
                        _logger.Error("Stack Trace: " + ex.StackTrace);
                    }
                }

                if (_settings.SendPdfToWellCareSftp)
                {
                    ExportResultOnWellCareSftp(fileName, directoryPath + fileName);
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Message: " + ex.Message);
                _logger.Error("Stack Trace: " + ex.StackTrace);
            }
        }
        public void PollForClinicalDocument()
        {
            if (_accountIds.IsNullOrEmpty())
            {
                return;
            }
            var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

            _logger.Info("Starting CCD Service...");

            foreach (var account in corporateAccounts)
            {
                try
                {
                    _logger.Info("running For Account Id..... " + account.Id);

                    var customSettingFilePath = string.Format(_settings.ClinicalDoumentSettingPath, account.Tag);
                    var customSettings        = _customSettingManager.Deserialize(customSettingFilePath);

                    var fromDate = customSettings.LastTransactionDate ?? _settings.PcpDownloadCutOfDate;
                    var toDate   = DateTime.Now;

                    var eventCustomers = _eventCustomerResultRepository.GetEventCustomerResultsToFax((int)TestResultStateNumber.ResultDelivered, (int)NewTestResultStateNumber.ResultDelivered, false, toDate, fromDate, account.Id, account.Tag);

                    if (eventCustomers.IsNullOrEmpty())
                    {
                        return;
                    }

                    var directoryPath = string.Format(_settings.ClinicalDoumentPath, account.FolderName);

                    foreach (var ecr in eventCustomers)
                    {
                        try
                        {
                            _logger.Info("Generating CCD Report for Customer Id " + ecr.CustomerId + " eventid: " + ecr.EventId);
                            var customer = _customerRepository.GetCustomer(ecr.CustomerId);
                            var pcp      = _primaryCarePhysicianRepository.Get(customer.CustomerId);
                            var theEvent = _eventRepository.GetById(ecr.EventId);
                            var model    = _clinicalDocumentFactory.Create(ecr, customer, pcp, theEvent);

                            var fileName = customer.Name.FirstName + customer.Name.LastName + ".xml";

                            var filePath = Path.Combine(directoryPath, fileName);

                            DirectoryOperationsHelper.DeleteFileIfExist(filePath);

                            _clinicalDocumentSerializer.SerializeandSave(filePath, model);
                        }
                        catch (Exception exception)
                        {
                            _logger.Error("some Exception occured while generating CCD Xml for customerId: " + ecr.CustomerId + " Eventid: " + ecr.EventId + " for Tag" + account.Tag);
                            _logger.Error("Message: " + exception.Message);
                            _logger.Error("Stack Trace: " + exception.StackTrace);
                        }
                    }

                    _logger.Info("compeletd  For Account Id..... " + account.Id);
                }
                catch (Exception exception)
                {
                    _logger.Error("some Exception occured while generating CCD Xml for account Tag " + account.Tag);
                    _logger.Error("Message: " + exception.Message);
                    _logger.Error("Stack Trace: " + exception.StackTrace);
                }
            }
        }
        public void PollForReport()
        {
            if (_healthPlanIds.IsNullOrEmpty())
            {
                _logger.Info("No Health Plan IDs found.");
                return;
            }

            var healthPlans = _corporateAccountRepository.GetByIds(_healthPlanIds);

            var callQueue = _callQueueRepository.GetCallQueueByCategory(HealthPlanCallQueueCategory.MailRound);

            var collection = new List <GmsExcludedCustomerViewModel>();

            foreach (var healthPlan in healthPlans)
            {
                _logger.Info("Getting excluded customers for Account ID : " + healthPlan.Id);

                var criterias = _healthPlanCallQueueCriteriaRepository.GetCriteriaForMailRoundGms(healthPlan.Id);

                if (!_settings.GmsCampaignIds.IsNullOrEmpty())
                {
                    criterias = _healthPlanCallQueueCriteriaRepository.GetByCampaignIds(_settings.GmsCampaignIds, healthPlan.Id);

                    _logger.Info(string.Format("Found {0} criterias for Campaign IDs : ", criterias.Count(), string.Join(",", _settings.GmsCampaignIds)));
                }

                foreach (var criteria in criterias)
                {
                    _logger.Info("Criteria ID : " + criteria.Id);

                    try
                    {
                        var filter = new OutboundCallQueueFilter
                        {
                            CallQueueId             = callQueue.Id,
                            CriteriaId              = criteria.Id,
                            CampaignId              = criteria.CampaignId,
                            Tag                     = healthPlan.Tag,
                            HealthPlanId            = healthPlan.Id,
                            UseCustomTagExclusively = false
                        };

                        if (filter.HealthPlanId == _settings.OptumUtAccountId)
                        {
                            filter.CustomCorporateTag = _settings.OptumUtCustomTagsForGms;
                        }
                        else if (filter.HealthPlanId == 1083)
                        {
                            filter.CustomCorporateTag = "UHC-TX_GMS_2018_List-1";
                        }
                        else if (filter.HealthPlanId == 1066)
                        {
                            filter.CustomCorporateTag = "Excellus_GMS_2018_List-1";
                        }
                        else if (filter.HealthPlanId == 1061)
                        {
                            filter.CustomCorporateTag = "Optum-NV_Assessments_2018_List-1_GMS,Optum-NV_Assessments_2018_List-2_GMS,Optum-NV_Assessments_2018_List-3_GMS,Optum-NV_Mammo_2018_List-2_GMS";
                        }
                        else if (filter.HealthPlanId == 1111)
                        {
                            filter.CustomCorporateTag = "Optum-NV_Assessments_2018_List-4_GMS";
                        }
                        else if (filter.HealthPlanId == 1087)
                        {
                            filter.CustomCorporateTag = "UHC-AZ_Assessments_2018_List-1_GMS";
                        }
                        else if (filter.HealthPlanId == 1093)
                        {
                            filter.CustomCorporateTag = "UHC-CT_Assessments_2018_List-1_GMS";
                        }

                        var excludedCustomerCollection = _gmsExcludedCustomerService.GetGmsExcludedCustomers(filter, callQueue);

                        var distinctCustomers = excludedCustomerCollection.Where(x => !collection.Select(c => c.CustomerId).Contains(x.CustomerId));

                        collection.AddRange(distinctCustomers);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Error getting excluded customers for Account ID : " + healthPlan.Id + " Criteria ID : " + criteria.Id);
                        _logger.Error(ex);
                    }
                }

                _logger.Info("Completed for Account ID : " + healthPlan.Id);
            }

            var excludedPath = _settings.GmsExcludeReportDownloadCustomerPath;

            if (DirectoryOperationsHelper.CreateDirectoryIfNotExist(excludedPath))
            {
                var fileName = Path.Combine(excludedPath, string.Format("ExcludedPatientList_{0}.csv", DateTime.Today.ToString("yyyyMMdd")));
                WriteCsv(collection, fileName);
            }
            else
            {
                _logger.Error("Folder can not be created");
            }
        }
        public void PollGiftCertificateOptumReport()
        {
            try
            {
                var corporateAccounts = _corporateAccountRepository.GetByIds(_settings.GiftCerificateOptumAccountIds);

                if (corporateAccounts.IsNullOrEmpty())
                {
                    _logger.Info("No Account Found to run Report");
                    return;
                }

                var      fromDate = DateTime.Today.GetFirstDateOfYear();
                DateTime toDate   = DateTime.Today;

                _logger.Info("starting for PollGiftCerificateOptumReport ");

                foreach (var account in corporateAccounts)
                {
                    if (account.Id == _applecareAccountId && _runReportForAppleCareDaysOfWeek != DateTime.Today.DayOfWeek)
                    {
                        _logger.Info(string.Format("Today is {0}. Job is set to run on {1} for Account Tag {2}.", DateTime.Today.DayOfWeek, _runReportForAppleCareDaysOfWeek, account.Tag));
                        continue;
                    }

                    if (account.Id != _applecareAccountId && (long)DateTime.Today.DayOfWeek != _settings.GiftCerificateOptumDayServiceRun)
                    {
                        _logger.Info("Today is Day of Week is " + DateTime.Today.DayOfWeek);
                        _logger.Info("Service will run on Day of Week " + (DayOfWeek)_settings.GiftCerificateOptumDayServiceRun);
                        return;
                    }

                    _logger.Info("starting for Account : " + account.Tag);

                    var destinationFoler = string.Format(_settings.GiftCerificateOptumDownloadPath, account.FolderName);

                    if (account.Id == _applecareAccountId)
                    {
                        destinationFoler = string.Format(_settings.GiftCertificateReportDownloadPath, account.FolderName);
                    }
                    if (account.Id != _applecareAccountId)
                    {
                        try
                        {
                            DirectoryOperationsHelper.DeleteDirectory(destinationFoler, true);
                        }
                        catch (Exception ex)
                        {
                            _logger.Error("Some error occurred while deleting directory at path: " + destinationFoler);
                            _logger.Error("Message: " + ex.Message);
                            _logger.Error("Stack Trace: " + ex.StackTrace);
                        }
                    }

                    DirectoryOperationsHelper.CreateDirectoryIfNotExist(destinationFoler);

                    var lastReportRunDate = toDate.AddDays(-7);

                    if (toDate.Year == lastReportRunDate.Year)
                    {
                        var fileName = "GiftCardReport_" + DateTime.Today.ToString("yyyyMMdd") + ".csv";
                        var filter   = new GiftCertificateReportFilter
                        {
                            HealthPlanId = account.Id,
                            EventFrom    = fromDate,
                            EventTo      = toDate,
                            Tag          = account.Tag
                        };

                        var isReportGenerated = GenerateReport(destinationFoler, fileName, filter);
                        if (account.Id != _applecareAccountId)
                        {
                            if (!isReportGenerated)
                            {
                                filter = new GiftCertificateReportFilter
                                {
                                    HealthPlanId = account.Id,
                                    EventFrom    = new DateTime((fromDate.Year - 1), 1, 1),
                                    EventTo      = new DateTime((fromDate.Year - 1), 12, 31),
                                    Tag          = account.Tag
                                };
                                isReportGenerated = GenerateReport(destinationFoler, fileName, filter);
                                if (!isReportGenerated)
                                {
                                    WriteHeader(Path.Combine(destinationFoler, fileName));
                                }
                            }
                        }
                    }
                    else if (lastReportRunDate.Year < toDate.Year)
                    {
                        fromDate = new DateTime(lastReportRunDate.Year, 1, 1);
                        var toforPreviousYearDate = fromDate.GetLastDateOfYear();

                        var filter = new GiftCertificateReportFilter
                        {
                            HealthPlanId = account.Id,
                            EventFrom    = fromDate,
                            EventTo      = toforPreviousYearDate,
                            Tag          = account.Tag
                        };

                        var fileName = "GiftCardReport_" + toforPreviousYearDate.ToString("yyyyMMdd") + ".csv";

                        GenerateReport(destinationFoler, fileName, filter);

                        filter = new GiftCertificateReportFilter
                        {
                            HealthPlanId = account.Id,
                            EventFrom    = toDate.GetFirstDateOfYear(),
                            EventTo      = toDate,
                            Tag          = account.Tag
                        };

                        fileName = "GiftCardReport_" + toDate.ToString("yyyyMMdd") + ".csv";
                        GenerateReport(destinationFoler, fileName, filter);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Message: " + ex.Message);
                _logger.Error("Stack Trace: " + ex.StackTrace);
            }
        }
        public void CreateZipFile()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }
                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);
                foreach (var account in corporateAccounts)
                {
                    try
                    {
                        _logger.Info(string.Format("Creating zip for accountId {0} and account tag {1}. ", account.Id, account.Tag));

                        var fileName = account.FolderName.Replace("_", "") + "_DATA_" + DateTime.Today.ToString("MMyydd");

                        var sourceFile      = string.Format(_optumZipFolderDownloadFromPath, account.FolderName);
                        var destinationPath = string.Format(_optumZipFolderPostToPath, account.FolderName);

                        if (_monarchAccountIds.Contains(account.Id))
                        {
                            destinationPath = string.Format(_monarchZipFolderPath, account.FolderName);
                            fileName        = account.FolderName + "_DATA_" + DateTime.Today.ToString("yyyyMMdd");
                        }

                        _logger.Info("Destination Path:" + destinationPath);

                        if (!DirectoryOperationsHelper.IsDirectoryExist(destinationPath))
                        {
                            Directory.CreateDirectory(destinationPath);
                        }

                        var destinationfile = destinationPath + "\\" + fileName + ".zip";

                        if (DirectoryOperationsHelper.IsFileExist(destinationfile))
                        {
                            DirectoryOperationsHelper.Delete(destinationfile);
                        }

                        var directoryToDeleteFrom = new DirectoryInfo(destinationPath);

                        if (_monarchAccountIds.Contains(account.Id))
                        {
                            var zipFiles = directoryToDeleteFrom.GetFiles(account.FolderName + "_DATA_*.zip");

                            foreach (var file in zipFiles)
                            {
                                _logger.Info("Deleting zip file : " + file.Name);
                                file.Delete();
                            }
                        }
                        else
                        {
                            var fileNotToBeDelete = GetFileNotDeleted();

                            var zipFiles = directoryToDeleteFrom.GetFiles(account.FolderName.Replace("_", "") + "_DATA_*.zip");

                            foreach (var file in zipFiles)
                            {
                                if (fileNotToBeDelete.Any(x => file.Name.EndsWith(x)))
                                {
                                    continue;
                                }

                                _logger.Info("Deleting zip file : " + file.Name);
                                file.Delete();
                            }
                        }

                        _zipHelper.CreateZipFiles(sourceFile, destinationfile, true);


                        if (_monarchAccountIds.Contains(account.Id))
                        {
                            var sftpCridential = _sftpCridentialManager.Deserialize(_sftpResouceFilePath + account.Tag + ".xml");

                            try
                            {
                                ExportResultInSftp(fileName + ".zip", destinationfile, sftpCridential);
                            }
                            catch (Exception exception)
                            {
                                _logger.Error("message: " + exception.Message);
                                _logger.Error("stack trace: " + exception.StackTrace);
                            }

                            var archiveDestinationPath = string.Format(_monarchResultPdfArchive, account.FolderName);

                            DirectoryOperationsHelper.CreateDirectoryIfNotExist(archiveDestinationPath + "\\pdfs\\");

                            var sourceDir      = new DirectoryInfo(sourceFile + "/pdfs/");
                            var destinationDir = new DirectoryInfo(archiveDestinationPath + "\\pdfs\\");

                            DeepCopy(sourceDir, destinationDir);
                            Directory.Delete(sourceFile + "/pdfs/", true);
                        }

                        _logger.Info("Zip File Created");
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Some Error occurred for Account Id " + account.Id + " Account Tag " + account.Tag);
                        _logger.Error("Message " + ex.Message);
                        _logger.Error("Stack Trace " + ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Some Error occurred ");
                _logger.Error("Message " + ex.Message);
                _logger.Error("Stack Trace " + ex.StackTrace);
            }
        }
Esempio n. 15
0
        public void PollGiftCertificateWellmedReport()
        {
            try
            {
                var wellmedFlAccountId = _settings.WellmedAccountId;
                var wellmedTxAccountId = _settings.WellmedTxAccountId;

                var giftCertificateWellmedAccountIds = new List <long> {
                    wellmedFlAccountId, wellmedTxAccountId
                };

                var corporateAccounts = _corporateAccountRepository.GetByIds(giftCertificateWellmedAccountIds);

                if (corporateAccounts.IsNullOrEmpty())
                {
                    _logger.Info("No Account Found to run Report");
                    return;
                }

                var      fromDate = DateTime.Today.GetFirstDateOfYear();
                DateTime toDate   = DateTime.Today;

                _logger.Info("starting for Poll Gift Cerificate Wellmed Report ");

                foreach (var account in corporateAccounts)
                {
                    if ((long)DateTime.Today.DayOfWeek != _settings.WellmedGiftCertificateDayOfWeek)
                    {
                        _logger.Info("Today is Day of Week is " + DateTime.Today.DayOfWeek);
                        _logger.Info("Service will run on Day of Week " +
                                     (DayOfWeek)_settings.WellmedGiftCertificateDayOfWeek);
                        return;
                    }

                    _logger.Info("starting for Account : " + account.Tag);

                    var folderName = account.Id == wellmedFlAccountId ? _settings.WellmedFlFolder : _settings.WellmedTxFolder;

                    var destinationFoler = Path.Combine(string.Format(_settings.OutTakeReportPath, folderName), "GiftCard");

                    DirectoryOperationsHelper.CreateDirectoryIfNotExist(destinationFoler);

                    var lastReportRunDate = toDate.AddDays(-7);

                    if (toDate.Year == lastReportRunDate.Year)
                    {
                        GenerateReport(destinationFoler, fromDate, toDate, account, folderName);
                    }
                    else if (lastReportRunDate.Year < toDate.Year)
                    {
                        fromDate = new DateTime(lastReportRunDate.Year, 1, 1);
                        var toforPreviousYearDate = fromDate.GetLastDateOfYear();

                        GenerateReport(destinationFoler, fromDate, toforPreviousYearDate, account, folderName);
                        GenerateReport(destinationFoler, toDate.GetFirstDateOfYear(), toDate, account, folderName);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Message: " + ex.Message);
                _logger.Error("Stack Trace: " + ex.StackTrace);
            }
        }
Esempio n. 16
0
        public void PollForParsingEligibilityUpload()
        {
            try
            {
                var timeOfDay = DateTime.Now;
                if (_isDevEnvironment || timeOfDay.TimeOfDay > new TimeSpan(3, 0, 0))
                {
                    _logger.Info("Entering EligibilityUpload parse polling agent @:" + timeOfDay);

                    var eligibilityFilesForParsing = (IReadOnlyCollection <EligibilityUpload>)_eligibilityUploadRepository.GetFilesToParse();

                    if (eligibilityFilesForParsing.IsNullOrEmpty())
                    {
                        _logger.Info("No file found for parsing , exiting");
                        return;
                    }

                    _logger.Info("No. of files to Parse:" + eligibilityFilesForParsing.Count());

                    var parseFileIds      = eligibilityFilesForParsing.Select(x => x.FileId);
                    var uploadedFiles     = (IReadOnlyCollection <File>)_fileRepository.GetByIds(parseFileIds);
                    var filesLocation     = _mediaRepository.GetEligibilityUploadMediaFileLocation();
                    var corporateAccounts = (IReadOnlyCollection <CorporateAccount>)_corporateAccountRepository.GetByIds(eligibilityFilesForParsing.Select(x => x.AccountId).Distinct());

                    foreach (var eligibilityUploadDomain in eligibilityFilesForParsing)
                    {
                        var failedRecords = new List <EligibilityUploadLogViewModel>();
                        try
                        {
                            eligibilityUploadDomain.ParseStartTime = DateTime.Now;
                            var fileDomain = uploadedFiles.FirstOrDefault(x => x.Id == eligibilityUploadDomain.FileId);
                            if (fileDomain == null)
                            {
                                UpdateParsingStatus(eligibilityUploadDomain, (long)EligibilityUploadStatus.FileNotFound);
                                _logger.Info("Parsing Failed: FileNotFound EligibilityUpload Id: " + eligibilityUploadDomain.Id);
                                continue;
                            }

                            var corporateAccount = corporateAccounts.FirstOrDefault(x => x.Id == eligibilityUploadDomain.AccountId);
                            if (corporateAccount == null)
                            {
                                UpdateParsingStatus(eligibilityUploadDomain, (long)EligibilityUploadStatus.ParseFailed);
                                _logger.Info("Parsing Failed: Corporate Account not found File name: " + fileDomain.Path + " AccountId: " + eligibilityUploadDomain.AccountId);
                                continue;
                            }

                            var filePhysicalLocation = filesLocation.PhysicalPath + fileDomain.Path;
                            _logger.Info("Parsing for File: " + filePhysicalLocation);

                            if (!System.IO.File.Exists(filePhysicalLocation))
                            {
                                UpdateParsingStatus(eligibilityUploadDomain, (long)EligibilityUploadStatus.FileNotFound);
                                _logger.Info("Parsing Failed: FileNotFound on Physical Storage File name: " + fileDomain.Path);
                                continue;
                            }

                            var fInfo = new FileInfo(filePhysicalLocation);
                            if (fInfo.Extension != ".csv")
                            {
                                UpdateParsingStatus(eligibilityUploadDomain, (long)EligibilityUploadStatus.InvalidFileFormat);
                                _logger.Info("Parsing Failed: InvalidFileFormat File name: " + fileDomain.Path);
                                continue;
                            }

                            _logger.Error("Beginning to Parse File : File name: " + fileDomain.Path);
                            UpdateParsingStatus(eligibilityUploadDomain, (long)EligibilityUploadStatus.Parsing, false);
                            var customerEligibleUploadTable = _csvReader.ReadWithTextQualifier(filePhysicalLocation);
                            var recordsInFile = customerEligibleUploadTable.Rows.Count;

                            var totalPages = recordsInFile / PageSize + (recordsInFile % PageSize != 0 ? 1 : 0);
                            _logger.Info("Total no. of Pages to process: " + totalPages + " ,total records to parse: " + recordsInFile);
                            var pageNumber = 1;

                            while (pageNumber <= totalPages)
                            {
                                try
                                {
                                    IEnumerable <CustomerEligibilityViewModel> tempParsedRecords = null;
                                    var query = customerEligibleUploadTable.AsEnumerable();
                                    _logger.Info("Parsing For Page Number: " + pageNumber);
                                    var rows = query.Skip(PageSize * (pageNumber - 1)).Take(PageSize);
                                    pageNumber++;

                                    //failedRecords is updated for invalid CustomerId and Year while parsed
                                    tempParsedRecords = ParseEligibilityDataTable(rows, failedRecords);

                                    if (tempParsedRecords.IsNullOrEmpty())
                                    {
                                        continue;
                                    }

                                    UpdateEligibilityStatus(tempParsedRecords, failedRecords, corporateAccount, fileDomain.UploadedBy.Id);
                                }
                                catch (Exception ex)
                                {
                                    _logger.Info(string.Format("Parsing failed for Page: {0} File name: {1}", pageNumber, fileDomain.Path));
                                    _logger.Error("ExceptionMessage: " + ex.Message + "\n\tStackTrace: " + ex.StackTrace);
                                    continue;
                                }
                            }
                            eligibilityUploadDomain.SuccessfullUploadCount = recordsInFile - failedRecords.Count();
                            eligibilityUploadDomain.ParseEndTime           = DateTime.Now;
                            eligibilityUploadDomain.StatusId = (long)EligibilityUploadStatus.Parsed;

                            UpdateEligibilityUploadDetail(eligibilityUploadDomain, failedRecords, filePhysicalLocation);
                            _logger.Error("Parse Succeeded : File name: " + fileDomain.Path);
                        }
                        catch (Exception ex)
                        {
                            var fileDomain = uploadedFiles.FirstOrDefault(x => x.Id == eligibilityUploadDomain.FileId);

                            if (fileDomain != null)
                            {
                                _logger.Error("Failed to parse File , File name: " + fileDomain.Path);
                                var filePhysicalLocation = filesLocation.PhysicalPath + fileDomain.Path;
                                eligibilityUploadDomain.StatusId = (long)EligibilityUploadStatus.ParseFailed;
                                UpdateEligibilityUploadDetail(eligibilityUploadDomain, failedRecords, filePhysicalLocation);
                            }
                            else
                            {
                                _logger.Error("Record does not exist in file table");
                            }

                            _logger.Error("ExceptionMessage: " + ex.Message + "\n\tStackTrace: " + ex.StackTrace);
                            continue;
                        }
                    }
                }
                else
                {
                    _logger.Info(string.Format("Eligibility Upload Parser can not be invoked as time of day is {0}", timeOfDay.TimeOfDay));
                }
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Exception occurred during execution of polling agent\nException Message: {0}\n\tStackTrace:{1}", ex.Message, ex.StackTrace));
                return;
            }
        }
        public void PollForPdfDownload()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }
                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

                foreach (var corporateAccount in corporateAccounts)
                {
                    try
                    {
                        _logger.Info(string.Format("Generating for accountId {0} and account tag {1}. ", corporateAccount.Id, corporateAccount.Tag));

                        var destinationFolderPdf  = string.Format(_destinationFolderPdfSetting, corporateAccount.FolderName);
                        var customSettingFilePath = string.Format(_customSettingFile, corporateAccount.Tag);
                        var customSettings        = _customSettingManager.Deserialize(customSettingFilePath);

                        var exportToTime   = DateTime.Now.AddHours(-1);
                        var exportFromTime = customSettings.LastTransactionDate ?? _cutOfDate;

                        DateTime?stopSendingPdftoHealthPlanDate = null;
                        if (corporateAccount.IsHealthPlan)
                        {
                            stopSendingPdftoHealthPlanDate = _stopSendingPdftoHealthPlanDate;
                        }
                        _logger.Info("exportToTime: " + exportToTime.ToString("MM/dd/yyyy"));
                        _logger.Info("exportFromTime: " + exportFromTime.ToString("MM/dd/yyyy"));

                        var eventCustomerResults = _eventCustomerResultRepository.GetEventCustomerResultsToFax((int)TestResultStateNumber.ResultDelivered, (int)NewTestResultStateNumber.ResultDelivered, false, exportToTime, exportFromTime, corporateAccount.Id, corporateAccount.Tag, true, stopSendingPdftoHealthPlanDate: stopSendingPdftoHealthPlanDate);

                        var customerResults = eventCustomerResults as EventCustomerResult[] ?? eventCustomerResults.ToArray();

                        if (eventCustomerResults == null || !customerResults.Any())
                        {
                            _logger.Info(string.Format("No event customer result list for {0} Result Pdf Download.", corporateAccount.Tag));
                            continue;
                        }

                        if (_optumAccountIds.Contains(corporateAccount.Id))
                        {
                            try
                            {
                                DirectoryOperationsHelper.DeleteDirectory(destinationFolderPdf, true);
                            }
                            catch (Exception ex)
                            {
                                _logger.Error("Some error occurred while deleting directory at path: " + destinationFolderPdf);
                                _logger.Error("Message: " + ex.Message);
                                _logger.Error("Stack Trace: " + ex.StackTrace);
                            }
                        }

                        _logger.Info(string.Format("Found {0} customers for {1} Result Pdf Download. ", eventCustomerResults.Count(), corporateAccount.Tag));

                        var pcpResultReport = _mediaRepository.GetPdfFileNameForPcpResultReport();

                        var healthPlanResultReport = _mediaRepository.GetPdfFileNameForHealthPlanResultReport();

                        var resultPostedToPlanFileName = Path.Combine(_resultPostedToPlanPath, string.Format("ResultPostedto_{0}.xml", corporateAccount.Tag));
                        var resultPosted = _resultPdfPostedSerializer.Deserialize(resultPostedToPlanFileName);
                        resultPosted = resultPosted == null || resultPosted.Customer.IsNullOrEmpty() ? new ResultPdfPostedXml {
                            Customer = new List <CustomerInfo>()
                        } : resultPosted;

                        _logger.Info(string.Format("Result Pdf file Transfer started for {0} ", corporateAccount.Tag));

                        var customersWithNoMrn    = new List <long>();
                        var newCustomersWithNoMrn = new List <long>();

                        foreach (var ecr in customerResults)
                        {
                            var sourceUrl = _mediaRepository.GetPremiumVersionResultPdfLocation(ecr.EventId, ecr.CustomerId).PhysicalPath + healthPlanResultReport;

                            if (!File.Exists(sourceUrl))
                            {
                                sourceUrl = _mediaRepository.GetPremiumVersionResultPdfLocation(ecr.EventId, ecr.CustomerId).PhysicalPath + pcpResultReport;
                            }

                            if (File.Exists(sourceUrl))
                            {
                                try
                                {
                                    SetReusltPdfNameing(ecr, corporateAccount, destinationFolderPdf, sourceUrl, resultPosted, newCustomersWithNoMrn);
                                }
                                catch (Exception exception)
                                {
                                    _logger.Error(string.Format("some error occured for the customerId {0}, {1},\n Messagen {2} \n Stack Trace {3}", ecr.CustomerId, ecr.EventId, exception.Message, exception.StackTrace));
                                }
                            }
                            else
                            {
                                _logger.Info(string.Format("File not generated or removed for the customerId {0}, {1}", ecr.CustomerId, ecr.EventId));
                            }
                        }

                        if (corporateAccount.Id == _settings.OptumNvAccountId || corporateAccount.Id == _settings.OptumNvMedicareAccountId)
                        {
                            _logger.Info("Sending Old Files to SFTP");

                            PostCustomerWithNoMrn(corporateAccount, destinationFolderPdf, resultPosted, customersWithNoMrn);

                            _logger.Info("Sending Old Files to SFTP Completed");

                            if (!customersWithNoMrn.IsNullOrEmpty())
                            {
                                newCustomersWithNoMrn.AddRange(customersWithNoMrn);
                            }

                            newCustomersWithNoMrn = newCustomersWithNoMrn.Distinct().ToList();

                            SaveCustomersWithNoMrn(corporateAccount, newCustomersWithNoMrn);
                        }

                        customSettings.LastTransactionDate = exportToTime;
                        _customSettingManager.SerializeandSave(customSettingFilePath, customSettings);

                        if (resultPosted != null && !resultPosted.Customer.IsNullOrEmpty())
                        {
                            _logger.Info("Result posted Log for " + corporateAccount.Tag);
                            resultPosted = _resultPdfFileHelper.CorrectMissingRecords(resultPosted);

                            var pdfLogfile = string.Format(_settings.PdfLogFilePath, corporateAccount.FolderName);
                            pdfLogfile = Path.Combine(pdfLogfile, "Download");

                            try
                            {
                                DirectoryOperationsHelper.CreateDirectoryIfNotExist(pdfLogfile);
                                if (DirectoryOperationsHelper.IsDirectoryExist(pdfLogfile))
                                {
                                    var filesTobedeleted = DirectoryOperationsHelper.GetFiles(pdfLogfile, "*" + corporateAccount.Tag + "_PdfLogFile*");
                                    foreach (var logFile in filesTobedeleted)
                                    {
                                        DirectoryOperationsHelper.DeleteFileIfExist(logFile);
                                    }
                                }

                                var resultPostedCustomers = resultPosted.Customer.Where(x => x.EventDate.HasValue && x.EventDate.Value.Year >= _cutOfDate.Year);
                                _resultPdfFileHelper.CreateCsvForFileShared(resultPostedCustomers, pdfLogfile, corporateAccount.Tag + "_PdfLogFile");
                            }
                            catch (Exception ex)
                            {
                                _logger.Error("some error occurred");
                                _logger.Error("exception: " + ex.Message);
                                _logger.Error("stack trace: " + ex.StackTrace);
                            }

                            _logger.Info("Result posted Log Completed for " + corporateAccount.Tag);
                        }

                        _resultPdfPostedSerializer.SerializeandSave(resultPostedToPlanFileName, resultPosted);

                        _logger.Info(string.Format("Result Pdf file Transfer completed for {0} ", corporateAccount.Tag));
                        _logger.Info("");
                        _logger.Info("");
                        _logger.Info("================================================================================");
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(string.Format("some error occured for AccountId: {0} and account tag: {1} Exception Message: \n{2}, \n stack Trace: \n\t {3} ", corporateAccount.Id, corporateAccount.Tag, ex.Message, ex.StackTrace));
                    }
                }
            }
            catch (Exception exception)
            {
                _logger.Error(string.Format("some error occured Exception Message: \n{0}, \n stack Trace: \n\t {1} ", exception.Message, exception.StackTrace));
            }
        }
        public void PollForReportGeneration()
        {
            var healthPlans = !_healthPlanIds.IsNullOrEmpty() ? _corporateAccountRepository.GetByIds(_healthPlanIds) : _corporateAccountRepository.GetAllHealthPlan();

            var callQueue = _callQueueRepository.GetCallQueueByCategory(HealthPlanCallQueueCategory.MailRound);

            var collection = new List <GmsCallQueueCustomerViewModel>();

            foreach (var healthPlan in healthPlans)
            {
                if (_settings.GmsMaxCustomerCount > 0 && collection.Count() >= _settings.GmsMaxCustomerCount)
                {
                    break;
                }

                _logger.Info(string.Format("Getting call queue customers for Account ID : {0} and Tag : {1}", healthPlan.Id, healthPlan.Tag));

                var criterias = _healthPlanCallQueueCriteriaRepository.GetCriteriaByHealthPlanCallQueue(healthPlan.Id, HealthPlanCallQueueCategory.MailRound);

                if (!_settings.GmsCampaignIds.IsNullOrEmpty())
                {
                    criterias = _healthPlanCallQueueCriteriaRepository.GetByCampaignIds(_settings.GmsCampaignIds, healthPlan.Id);

                    _logger.Info(string.Format("Found {0} criterias for Campaign IDs : ", criterias.Count(), string.Join(",", _settings.GmsCampaignIds)));
                }

                foreach (var criteria in criterias)
                {
                    if (_settings.GmsMaxCustomerCount > 0 && collection.Count() >= _settings.GmsMaxCustomerCount)
                    {
                        break;
                    }

                    _logger.Info(string.Format("Criteria ID : {0}", criteria.Id));

                    try
                    {
                        var filter = new OutboundCallQueueFilter
                        {
                            CallQueueId             = callQueue.Id,
                            CriteriaId              = criteria.Id,
                            CampaignId              = criteria.CampaignId,
                            Tag                     = healthPlan.Tag,
                            HealthPlanId            = healthPlan.Id,
                            UseCustomTagExclusively = false
                        };

                        if (filter.HealthPlanId == _settings.OptumUtAccountId)
                        {
                            filter.CustomCorporateTag = _settings.OptumUtCustomTagsForGms;
                        }
                        else if (filter.HealthPlanId == 1083)
                        {
                            filter.CustomCorporateTag = "UHC-TX_GMS_2018_List-1";
                        }
                        else if (filter.HealthPlanId == 1066)
                        {
                            filter.CustomCorporateTag = "Excellus_GMS_2018_List-1";
                        }
                        else if (filter.HealthPlanId == 1061)
                        {
                            filter.CustomCorporateTag = "Optum-NV_Assessments_2018_List-1_GMS,Optum-NV_Assessments_2018_List-2_GMS,Optum-NV_Assessments_2018_List-3_GMS,Optum-NV_Mammo_2018_List-2_GMS";
                        }
                        else if (filter.HealthPlanId == 1111)
                        {
                            filter.CustomCorporateTag = "Optum-NV_Assessments_2018_List-4_GMS";
                        }
                        else if (filter.HealthPlanId == 1087)
                        {
                            filter.CustomCorporateTag = "UHC-AZ_Assessments_2018_List-1_GMS";
                        }
                        else if (filter.HealthPlanId == 1093)
                        {
                            filter.CustomCorporateTag = "UHC-CT_Assessments_2018_List-1_GMS";
                        }

                        _healthPlanOutboundCallQueueService.GetAccountCallQueueSettingForCallQueue(filter);

                        var dataGen = new ExportableDataGenerator <GmsCallQueueCustomerViewModel, OutboundCallQueueFilter>(_callQueueCustomerReportService.GetGmsCallQueueCustomersReport, _logger);

                        var model = dataGen.GetData(filter);

                        var distinctCustomers = model.Collection.Where(x => !collection.Select(c => c.CustomerId).Contains(x.CustomerId));

                        collection.AddRange(distinctCustomers);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Error getting call queue customers for Account ID : " + healthPlan.Id + " Criteria ID : " + criteria.Id);
                        _logger.Error(ex);
                    }
                }
            }

            if (!collection.Any())
            {
                _logger.Info("No records found.");
                return;
            }

            if (_settings.GmsMaxCustomerCount > 0 && collection.Count() >= _settings.GmsMaxCustomerCount)
            {
                collection = collection.Take(_settings.GmsMaxCustomerCount).ToList();
            }

            if (!Directory.Exists(_settings.GmsCustomerReportPath))
            {
                Directory.CreateDirectory(_settings.GmsCustomerReportPath);
            }

            var fileName = _settings.GmsCustomerReportPath + @"\" + string.Format("PatientList_{0}.csv", DateTime.Today.ToString("yyyyMMdd"));

            WriteCsv(collection, fileName);

            if (_settings.SendReportToGmsSftp)
            {
                _logger.Info("Sending Customer List to GMS sftp.");
                var sftpFolderReportDirectory = _settings.GmsSftpPath;
                var processFtp = new ProcessFtp(_logger, _settings.GmsSftpHost, _settings.GmsSftpUserName, _settings.GmsSftpPassword);

                processFtp.UploadSingleFile(fileName, sftpFolderReportDirectory, "");
                _logger.Info("Sent Customer List to GMS sftp.");
            }
            else
            {
                _logger.Info("Setting to send Customer list to sftp is OFF.");
            }
        }
Esempio n. 19
0
        public void ParseLockedEventFilesForWellmed()
        {
            try
            {
                var    lockCorporateEventFolderLocation = string.Empty;
                var    wellmedFlAccountId = _settings.WellmedAccountId;
                var    wellmedTxAccountId = _settings.WellmedTxAccountId;
                long[] wellmedAccountIds  = { wellmedFlAccountId, wellmedTxAccountId };

                var corporateAccounts = _corporateAccountRepository.GetByIds(wellmedAccountIds);

                foreach (var corporateAccount in corporateAccounts)
                {
                    _logger.Info("Getting events for Account : " + corporateAccount.Tag);

                    if (corporateAccount != null && corporateAccount.Id == _settings.WellmedAccountId)
                    {
                        lockCorporateEventFolderLocation = _settings.WellmedFlLockCorporateEventFolderLocation;
                    }
                    else if (corporateAccount != null && corporateAccount.Id == _settings.WellmedTxAccountId)
                    {
                        lockCorporateEventFolderLocation = _settings.WellmedTxLockCorporateEventFolderLocation;
                    }

                    var eventIds = _eventRepository.GetEventIdsByAccountIdAndDate(corporateAccount.Id, DateTime.Today, DateTime.Today.AddDays(1));

                    if (eventIds.IsNullOrEmpty())
                    {
                        _logger.Info("No events found for Account : " + corporateAccount.Tag);
                        continue;
                    }

                    foreach (var eventId in eventIds)
                    {
                        _logger.Info("Importing for EventId " + eventId);
                        try
                        {
                            var location = _mediaRepository.GetUnlockEventsParseLocation(eventId, true);

                            var eventCustomers = _eventCustomerRepository.GetEventCustomersbyEventId(eventId);
                            if (!eventCustomers.IsNullOrEmpty())
                            {
                                var customers = _customerRepository.GetCustomers(eventCustomers.Select(ec => ec.CustomerId).ToArray());
                                if (!customers.IsNullOrEmpty())
                                {
                                    var memberIds = customers.Where(x => !x.InsuranceId.IsNullOrEmpty()).Select(x => x.InsuranceId).ToArray();
                                    if (!memberIds.IsNullOrEmpty())
                                    {
                                        CopyFileFromBPShare(memberIds, lockCorporateEventFolderLocation, location.PhysicalPath);
                                    }
                                }
                            }
                            _logger.Info("Import completed for EventId " + eventId);
                        }
                        catch (Exception exception)
                        {
                            _logger.Error("some error occurred while parsing event id " + eventId);
                            _logger.Error(string.Format("Message: " + exception.Message + "\n stack trace: " + exception.StackTrace));
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                _logger.Error(string.Format("Message: " + exception.Message + "\n stack trace: " + exception.StackTrace));
            }
        }
        public void PollForAppointmentBookExport()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }
                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

                foreach (var account in corporateAccounts)
                {
                    try
                    {
                        _logger.Info(string.Format("Generating AppointmentBooked for accountId {0} and account tag {1}. ", account.Id, account.Tag));

                        DateTime fromDate;
                        if (DateTime.Now.Year > _cutOfDate.Date.Year)
                        {
                            fromDate = DateTime.Today.GetFirstDateOfYear();
                        }
                        else
                        {
                            fromDate = _cutOfDate;
                        }

                        var destinationPath = string.Format(_pcpAppointmentBookedReportDownloadPath, account.FolderName);

                        if (account.Id != _settings.ExcellusAccountId && account.Id != _settings.HealthNowAccountId)
                        {
                            destinationPath = Path.Combine(destinationPath, DateTime.Today.Year.ToString());
                        }

                        var appointmentSettings = string.Format(_appointmentSettings, account.Tag);
                        var customSettings      = _customSettingManager.Deserialize(appointmentSettings);


                        var toDate = DateTime.Today.GetLastDateOfYear();

                        _logger.Info(string.Format("Generating AppointmentBooked Date From. {0} To Date {1}", fromDate.Date.ToShortDateString(), toDate.ToShortDateString()));
                        string[] customTags          = null;
                        var      appointmentFileName = string.Format(@"\AppointmentBookedReport_{0}.csv", DateTime.Today.ToString("yyyyMMdd"));

                        if (account.Id == _martinsPointExclusiveAccountId)
                        {
                            appointmentFileName = string.Format(@"\Exclusive_AppointmentBookedReport_{0}.csv", DateTime.Today.ToString("yyyyMMdd"));
                            DirectoryOperationsHelper.DeleteFiles(destinationPath, "Exclusive_AppointmentBookedReport*.csv");
                        }
                        else if (account.Id == _settings.ExcellusAccountId)
                        {
                            appointmentFileName = string.Format(@"\AppointmentBooked_{0}.csv", DateTime.Today.ToString("yyyyMMdd"));
                            customTags          = _settings.ExcellusCustomTags;
                            DirectoryOperationsHelper.DeleteFiles(destinationPath, "AppointmentBooked*.csv");
                        }
                        else if (account.Id == _settings.HealthNowAccountId)
                        {
                            destinationPath     = string.Format(_settings.HealthPlanDownloadPath, account.FolderName);
                            appointmentFileName = string.Format(@"\AppointmentBooked_{0}.csv", DateTime.Today.ToString("yyyyMMdd"));
                            customTags          = _settings.HealthNowCustomTags;
                            DirectoryOperationsHelper.DeleteFiles(destinationPath, "AppointmentBooked*.csv");
                        }
                        else if (account.Id == _settings.MedMutualAccountId)
                        {
                            destinationPath     = string.Format(_settings.HealthPlanDownloadPath, account.FolderName);
                            appointmentFileName = string.Format(@"\AppointmentsBooked_{0}.csv", DateTime.Today.ToString("yyyyMMdd"));
                            DirectoryOperationsHelper.DeleteFiles(destinationPath, "AppointmentsBooked*.csv");
                        }
                        else if (account.Id == _settings.AppleCareAccountId)
                        {
                            if (DateTime.Today.DayOfWeek != _settings.AppleCareAppointmentBookedReportDayOfWeek)
                            {
                                _logger.Info("today is " + DateTime.Today.DayOfWeek + " while service is configured to run on " + _settings.AppleCareAppointmentBookedReportDayOfWeek);
                                _logger.Info("Please set in " + (int)DateTime.Today.DayOfWeek + " to run Service today");
                                continue;
                            }

                            appointmentFileName = @"\AppointmentsBooked.csv";
                            DirectoryOperationsHelper.DeleteFiles(destinationPath, "AppointmentsBooked.csv");
                        }
                        else if (account.Id == _settings.ConnecticareAccountId)
                        {
                            destinationPath     = string.Format(_settings.HealthPlanDownloadPath, account.FolderName);
                            appointmentFileName = @"\Comm Appts Booked " + DateTime.Today.ToString("yyyy-MM-dd") + ".csv";
                        }
                        else if (account.Id == _settings.ConnecticareMaAccountId)
                        {
                            destinationPath     = string.Format(_settings.HealthPlanDownloadPath, account.FolderName);
                            appointmentFileName = @"\MCR Appts Booked " + DateTime.Today.ToString("yyyy-MM-dd") + ".csv";
                        }
                        else if (account.Id == _settings.BcbsScAssessmentAccountId)
                        {
                            destinationPath = string.Format(_settings.HealthPlanExportRootPath, account.FolderName);
                        }
                        else if (account.Id == _settings.FloridaBlueFepAccountId)
                        {
                            destinationPath     = Path.Combine(string.Format(_settings.HealthPlanDownloadPath, account.FolderName), "Reports");
                            appointmentFileName = string.Format(@"\AppointmentBooked_{0}.csv", DateTime.Today.ToString("yyyyMMdd"));
                        }
                        else if (account.Id == _settings.NammAccountId)
                        {
                            destinationPath     = string.Format(_settings.HealthPlanExportRootPath, account.FolderName);
                            appointmentFileName = string.Format(@"\AppointmentBooked_{0}.csv", DateTime.Today.ToString("yyyyMMdd"));
                        }
                        //else if (account.Id == _settings.BcbsScAccountId)
                        //{
                        //    var folder = _settings.BcbsScFolder;
                        //    destinationPath = Path.Combine(string.Format(_settings.OutTakeReportPath, folder), "Appointments");
                        //    appointmentFileName = string.Format(@"\AppointmentsBooked_{0}_{1}_{2}.csv", account.AcesClientShortName, folder, DateTime.Today.ToString("MMddyyyy"));
                        //}
                        else
                        {
                            DirectoryOperationsHelper.DeleteFiles(destinationPath, "AppointmentBookedReport*.csv");
                        }

                        AppointmentsBooked(new AppointmentsBookedListModelFilter {
                            EventFrom = fromDate, EventTo = toDate.Date, AccountId = account.Id, CustomTags = customTags, Tag = account.Tag
                        }, destinationPath, appointmentFileName);

                        var fileName = destinationPath + appointmentFileName;
                        _logger.Info(string.Format("Completed AppointmentBooked Date From. {0} To Date {1}", fromDate.Date.ToShortDateString(), toDate.ToShortDateString()));

                        if (File.Exists(fileName))
                        {
                            _pgpFileEncryptionHelper.EncryptFile(account, fileName);

                            if (account.Id == _settings.FloridaBlueFepAccountId && _settings.SendReportToFloridaBlueSftp)
                            {
                                var destinationSftpPath = _settings.FloridaBlueSftpPath + "\\" + account.FolderName + "\\Download\\Reports";
                                PostFile(fileName, destinationSftpPath, _settings.FloridaBlueSftpHost, _settings.FloridaBlueSftpUserName, _settings.FloridaBlueSftpPassword);
                            }
                            else
                            {
                                PostFileOnClientSftp(account, fromDate, fileName);
                            }
                        }
                        else
                        {
                            _logger.Info("file Not found " + fileName);
                        }

                        customSettings.LastTransactionDate = toDate;
                        _customSettingManager.SerializeandSave(appointmentSettings, customSettings);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(string.Format("Exception For AccountId {0} and Account Tag {1} : \n Error {2} \n Trace: {3} \n\n\n", account.Id, account.Tag, ex.Message, ex.StackTrace));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Main App: \n Error {0} \n Trace: {1} \n\n\n", ex.Message, ex.StackTrace));
            }
        }
Esempio n. 21
0
        public void PollForReportGeneration()
        {
            if (!_daysOfWeek.Contains(DateTime.Today.DayOfWeek))
            {
                _logger.Info(string.Format("Today is {0}. Job is set to run on {1} .", DateTime.Today.DayOfWeek, string.Join(", ", _daysOfWeek)));
                return;
            }

            if (_accountIds.IsNullOrEmpty())
            {
                _logger.Info("No accounts found for Gift Certificate Report.");
                return;
            }
            var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

            var toDate   = DateTime.Today;
            var fromDate = new DateTime(toDate.Year, 1, 1);

            foreach (var corporateAccount in corporateAccounts)
            {
                try
                {
                    var customSettingFilePath = string.Format(_customSettingFile, corporateAccount.Tag);
                    var customSettings        = _customSettingManager.Deserialize(customSettingFilePath);

                    var exportFromTime = customSettings.LastTransactionDate ?? _cutOffDate;

                    var filter = new HealthPlanGiftCertificateReportFilter
                    {
                        Tag      = corporateAccount.Tag,
                        FromDate = exportFromTime.Date,
                        ToDate   = toDate
                    };

                    fromDate = filter.FromDate.HasValue ? filter.FromDate.Value : fromDate;

                    _logger.Info(string.Format("Generating for account with ID : {0} and tag : {1} from {2} to {3}", corporateAccount.Id, corporateAccount.Tag, fromDate.ToShortDateString(), toDate.ToShortDateString()));

                    var       pageNumber = 1;
                    const int pageSize   = 100;

                    var list = new List <HealthPlanGiftCertificateReportViewModel>();

                    while (true)
                    {
                        int totalRecords;
                        var model = _eventCustomerReportingService.GetForHealthPlanGiftCertificateReport(pageNumber, pageSize, filter, out totalRecords);
                        if (model == null || model.Collection == null || !model.Collection.Any())
                        {
                            break;
                        }

                        list.AddRange(model.Collection);
                        _logger.Info(String.Format("PageNumber:{0} Totalrecords: {1}  Current Length: {2}\n\n", pageNumber, totalRecords, list.Count));

                        pageNumber++;

                        if (list.Count >= totalRecords)
                        {
                            break;
                        }
                    }

                    if (!list.Any())
                    {
                        _logger.Info(string.Format("No records found for account with ID : {0} and tag : {1}", corporateAccount.Id, corporateAccount.Tag, fromDate.ToShortDateString(), toDate.ToShortDateString()));
                        continue;
                    }

                    var internalLocation = string.Format(_giftCertificateReportInternalLocation, corporateAccount.FolderName);

                    if (!DirectoryOperationsHelper.IsDirectoryExist(internalLocation))
                    {
                        DirectoryOperationsHelper.CreateDirectory(internalLocation);
                    }

                    var fileName = @"\" + string.Format("CCI_offline_HealthFair_{0}.csv", DateTime.Today.ToString("yyyy_MM_dd"));//CCI_offline_HealthFair_YYYY_MM_DD

                    var internalFilePath = internalLocation + fileName;

                    WriteCsv(list, internalFilePath);

                    if (DirectoryOperationsHelper.IsFileExist(internalFilePath))
                    {
                        var folder = Path.Combine(string.Format(_giftCertificateReportDownloadPath, corporateAccount.FolderName), DateTime.Today.Year.ToString());

                        if (!DirectoryOperationsHelper.IsDirectoryExist(folder))
                        {
                            DirectoryOperationsHelper.CreateDirectory(folder);
                        }

                        var filePath = folder + fileName;

                        DirectoryOperationsHelper.Copy(internalFilePath, filePath);
                    }

                    _logger.Info(string.Format("Completed Gift Certificate Report for account with ID : {0} and tag : {1} from {2} to {3}", corporateAccount.Id, corporateAccount.Tag, fromDate.ToShortDateString(), toDate.ToShortDateString()));

                    customSettings.LastTransactionDate = toDate;
                    _customSettingManager.SerializeandSave(customSettingFilePath, customSettings);
                }
                catch (Exception ex)
                {
                    _logger.Info(string.Format("Error occured for account with ID : {0} and tag : {1} \nMessage : {2} \nStack Trace : {3}", corporateAccount.Id, corporateAccount.Tag, ex.Message, ex.StackTrace));
                }
            }
        }
        public void PollForPatientInputFiles()
        {
            _logger.Info("Started Patient Input File");
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }
                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

                foreach (var account in corporateAccounts)
                {
                    try
                    {
                        var eventDate       = DateTime.Today.AddDays(-1);
                        var destinationPath = string.Format(_patientInputFileDestinationPath, account.FolderName, eventDate.Year);

                        _logger.Info(string.Format("Started Patient Input File For Account Id: {0} Tag: {1} for event Date: {2}", account.Id, account.Tag, eventDate));

                        var filter = new EventBasicInfoViewModelFilter
                        {
                            AccountId = account.Id,
                            DateTo    = eventDate.Date,
                            DateFrom  = eventDate.Date
                        };
                        var fileName    = "PatientInputfiles_" + eventDate.ToString("MMddyyyy") + ".csv";
                        var csvFilePath = destinationPath + "\\" + fileName;

                        if (File.Exists(csvFilePath))
                        {
                            File.Delete(csvFilePath);
                        }

                        int pageNumber = 1;

                        while (true)
                        {
                            int totalRecords = 0;
                            var events       = _eventRepository.GetEventsbyFilters(filter, pageNumber++, PageSize, out totalRecords);

                            if (events.IsNullOrEmpty())
                            {
                                break;
                            }

                            _logger.Info("total event count :" + totalRecords);

                            foreach (var eventData in events)
                            {
                                var model = _patientInputFileService.GetPatientFileInputByEvent(eventData, account.Tag);

                                if (model != null && model.Any())
                                {
                                    _logger.Info("event id : " + eventData.Id + " customer for Event " + model.Count());
                                    WriteCsvAppointmentBooked(model, destinationPath, fileName);
                                }
                                else
                                {
                                    _logger.Info("event id : " + eventData.Id + " no customer found for event ");
                                }
                            }
                        }

                        _logger.Info(string.Format("Completed Patient Input File For Account Id: {0} Tag: {1} for event Date: {2}", account.Id, account.Tag, eventDate));
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(string.Format("some Error occured for while generating file for Tag {0} Message: {1} Stack Trace {2}", account.Tag, ex.Message, ex.StackTrace));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Error occured Message: {0} Stack trace {1}", ex.Message, ex.StackTrace));
            }

            _logger.Info("Completed Patient Input File");
        }
Esempio n. 23
0
        public void PollForEventScheduleReort()
        {
            try
            {
                _logger.Info("starting Event Schedule Report");

                var accounts = _corporateAccountRepository.GetByIds(_settings.EventScheduleAccountIds);

                foreach (var account in accounts)
                {
                    _logger.Info("Event Schedule Report for Account Tag" + account.Tag);

                    if ((account.Id == _settings.ConnecticareAccountId || account.Id == _settings.ConnecticareMaAccountId) && DateTime.Today.DayOfWeek != _settings.ConnecticareEventScheduleExportDay)
                    {
                        _logger.Info("today is " + DateTime.Today.DayOfWeek + " while service is configured to run on " + _settings.ConnecticareEventScheduleExportDay);
                        _logger.Info("Please set " + (int)DateTime.Today.DayOfWeek + " to run Service today");
                        continue;
                    }

                    var fromDate = new DateTime(DateTime.Today.Year, 1, 1);
                    var toDate   = new DateTime(DateTime.Today.Year, 12, 31);

                    var filter = new EventScheduleListModelFilter
                    {
                        AccountId = account.Id,
                        FromDate  = fromDate,
                        ToDate    = toDate,
                    };
                    var stateIds = _eventRepository.GetEventStateByAccountId(filter);

                    if (stateIds.IsNullOrEmpty())
                    {
                        _logger.Info("No State found for Account Tag " + account.Tag);
                        continue;
                    }

                    var states = _stateRepository.GetStates(stateIds);
                    foreach (var state in states)
                    {
                        try
                        {
                            _logger.Info("fetching records for State Name " + state.Name);
                            filter.StateId = state.Id;

                            var dataGen = new ExportableDataGenerator <EventScheduleModel, EventScheduleListModelFilter>(_eventReportingService.GetEventScheduleReport, _logger);
                            var model   = dataGen.GetData(filter);

                            if (model != null && !model.Collection.IsNullOrEmpty())
                            {
                                _logger.Info("Writing Event Schedule Report");
                                var exporter = ExportableDataGeneratorProcessManager <ViewModelBase, ModelFilterBase> .GetCsvExporter <EventScheduleModel>();

                                _logger.Info("Record count" + model.Collection.Count());
                                var eventScheduleReportPath = Path.Combine(_settings.EventScheduleReportPath, DateTime.Today.Year.ToString());

                                DirectoryOperationsHelper.CreateDirectoryIfNotExist(eventScheduleReportPath);
                                var reportName = "EventScheduleReport_" + account.Tag + "_" + state.Name + "_" + DateTime.Today.ToString("yyyyMMdd") + ".csv";

                                var reportfilePath = Path.Combine(eventScheduleReportPath, reportName);

                                if (account.Id == _settings.ConnecticareAccountId || account.Id == _settings.ConnecticareMaAccountId)
                                {
                                    reportfilePath = Path.Combine(_settings.HealthPlanDownloadPath, account.FolderName);
                                    reportfilePath = Path.Combine(reportfilePath, reportName);
                                }

                                DirectoryOperationsHelper.DeleteFileIfExist(reportfilePath);

                                _baseExportableReportHelper.GenerateCsv(reportfilePath, exporter, model.Collection);

                                _logger.Info("Generated report of Event Schedule Report for Account " + account.Tag + " state " + state.Name);
                                _logger.Info("Path: " + reportfilePath + " state " + state.Name);

                                if (_sendReportToSftp)
                                {
                                    _logger.Info("Sending file to sftp.");
                                    var eventScheduleReportSftpPath = string.Format(_eventScheduleReportSftpPath, fromDate.Year);
                                    var processFtp = new ProcessFtp(_logger, _sftpHost, _sftpUserName, _sftpPassword);

                                    processFtp.UploadSingleFile(reportfilePath, eventScheduleReportSftpPath, "");

                                    _logger.Info("File sent on sftp.");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.Error("some Error occurred while generating report of Event Schedule Report for Account " + account.Tag + " state " + state.Name);
                            _logger.Error("ex: " + ex.Message);
                            _logger.Error("stack Trace: " + ex.StackTrace);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("some Error occurred while generating report of Event Schedule Report ");
                _logger.Error("ex: " + ex.Message);
                _logger.Error("stack Trace: " + ex.StackTrace);
            }
        }
        public void PollForEventFilesImport()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    _logger.Info("No accounts for Event File Import.");
                    return;
                }

                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

                foreach (var corporateAccount in corporateAccounts)
                {
                    _logger.Info("Getting events for Account : " + corporateAccount.Tag);

                    var eventIds = _eventRepository.GetEventIdsByAccountIdAndDate(corporateAccount.Id, DateTime.Today, DateTime.Today.AddDays(1));

                    if (eventIds.IsNullOrEmpty())
                    {
                        _logger.Info("No events found for Account : " + corporateAccount.Tag);
                        continue;
                    }

                    foreach (var eventId in eventIds)
                    {
                        _logger.Info("Importing for EventId " + eventId);
                        try
                        {
                            string sftpHost     = string.Empty;
                            string sftpUserName = string.Empty;
                            string sftpPassword = string.Empty;
                            string corporateEventFolderLocation = string.Empty;
                            string subdirectoryPattern          = string.Empty;

                            if (corporateAccount != null && corporateAccount.Id == _settings.HcpNvAccountId)
                            {
                                sftpHost     = _settings.HcpNvSftpHost;
                                sftpUserName = _settings.HcpNvSftpUserName;
                                sftpPassword = _settings.HcpNvSftpPassword;

                                corporateEventFolderLocation = _settings.HcpNvLockCorporateEventFolderLocation + "\\" + DateTime.Today.Year + "\\PIRs and Pink Flags\\";
                                subdirectoryPattern          = "PIRs " + DateTime.Today.ToString("M.d.yy");
                            }

                            var location = _mediaRepository.GetUnlockEventsParseLocation(eventId, true);

                            if (corporateAccount != null && corporateAccount.Id == _settings.HcpNvAccountId)
                            {
                                var eventCustomers = _eventCustomerRepository.GetbyEventId(eventId);
                                if (!eventCustomers.IsNullOrEmpty())
                                {
                                    var customerIds = eventCustomers.Select(x => x.CustomerId.ToString()).ToArray();
                                    DowloadPinkFlagFromSftp(customerIds, corporateEventFolderLocation, location.PhysicalPath, sftpHost, sftpUserName, sftpPassword, "", subdirectoryPattern);
                                }
                            }
                            else if (!string.IsNullOrEmpty(sftpHost))
                            {
                                DowloadFilesFromSftp(corporateEventFolderLocation, location.PhysicalPath, sftpHost, sftpUserName, sftpPassword);
                            }
                        }
                        catch (Exception exception)
                        {
                            _logger.Error("some error occurred while parsing event id " + eventId);
                            _logger.Error(string.Format("Message: " + exception.Message + "\n stack trace: " + exception.StackTrace));
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                _logger.Error(string.Format("Message: " + exception.Message + "\n stack trace: " + exception.StackTrace));
            }
        }
Esempio n. 25
0
        public void PollForPdfDownload()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }
                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

                foreach (var corporateAccount in corporateAccounts)
                {
                    try
                    {
                        _logger.Info(string.Format("Generating for accountId {0} and account tag {1}. ", corporateAccount.Id, corporateAccount.Tag));

                        var destinationFolderPdf  = string.Format(_destinationFolderPdfSetting, corporateAccount.FolderName);
                        var customSettingFilePath = string.Format(_customSettingFile, corporateAccount.Tag);
                        var customSettings        = _customSettingManager.Deserialize(customSettingFilePath);

                        var exportToTime   = DateTime.Now.AddHours(-1);
                        var exportFromTime = customSettings.LastTransactionDate ?? _cutOfDate;

                        bool     inclcludeCustomTag = false;
                        string[] CustomTags         = null;
                        var      considerEventDate  = true;

                        DateTime?eventCutOfDate = _settings.PPEventCutOfDate;

                        if (corporateAccount.Id == _settings.HealthNowAccountId)
                        {
                            CustomTags         = _settings.HealthNowCustomTags;
                            inclcludeCustomTag = true;
                        }
                        if (corporateAccount.Id == _settings.ExcellusAccountId)
                        {
                            CustomTags         = _settings.ExcellusCustomTags;
                            inclcludeCustomTag = true;
                        }

                        if (corporateAccount.Id == _settings.PPAccountId)
                        {
                            considerEventDate = true;
                        }

                        DateTime?stopSendingPdftoHealthPlanDate = null;
                        if (corporateAccount.IsHealthPlan)
                        {
                            stopSendingPdftoHealthPlanDate = _settings.StopSendingPdftoHealthPlanDate;
                        }

                        var eventCustomerResults = _eventCustomerResultRepository.GetEventCustomerResultsToFax((int)TestResultStateNumber.ResultDelivered, (int)NewTestResultStateNumber.ResultDelivered, false, exportToTime, exportFromTime,
                                                                                                               corporateAccount.Id, corporateAccount.Tag, true, CustomTags, inclcludeCustomTag, considerEventDate, eventCutOfDate
                                                                                                               , stopSendingPdftoHealthPlanDate: stopSendingPdftoHealthPlanDate);

                        var customerResults = eventCustomerResults as EventCustomerResult[] ?? eventCustomerResults.ToArray();
                        customerResults = customerResults ?? new EventCustomerResult[] { };

                        var resultNotPostedFileName       = string.Format("ResultNotPostedto_{0}.xml", corporateAccount.Tag);
                        var resultNotPostedToPlanFileName = Path.Combine(_settings.ResultNotPostedToPlanPath, resultNotPostedFileName);

                        var resultNotPosted = _resultPdfNotPostedSerializer.Deserialize(resultNotPostedToPlanFileName);
                        resultNotPosted = resultNotPosted == null || resultNotPosted.EventCustomer.IsNullOrEmpty() ? new ResultPdfNotPosted {
                            EventCustomer = new List <EventCustomerInfo>()
                        } : resultNotPosted;

                        if (resultNotPosted.EventCustomer.Count > 0)
                        {
                            var eventCustomerIds = resultNotPosted.EventCustomer.Select(x => x.EventCustomerId);

                            if (!customerResults.IsNullOrEmpty())
                            {
                                var freshCustomerEventCustomerIds = customerResults.Select(x => x.Id);
                                eventCustomerIds = (from q in eventCustomerIds where !freshCustomerEventCustomerIds.Contains(q) select q).ToList();
                            }


                            int totalRecords = eventCustomerIds.Count();
                            int pageNumber   = 0;
                            int pagesize     = 100;

                            while (true)
                            {
                                if (totalRecords < 1)
                                {
                                    break;
                                }

                                var totalItems  = pageNumber * pagesize;
                                var customerIds = eventCustomerIds.Skip(totalItems).Take(pagesize);
                                var resultNotPostedEventCustomerResults = _eventCustomerResultRepository.GetEventCustomerResultsByIdsAndResultState(customerIds, (int)TestResultStateNumber.ResultDelivered, (int)NewTestResultStateNumber.ResultDelivered, false);

                                if (!resultNotPostedEventCustomerResults.IsNullOrEmpty())
                                {
                                    var resultReports = resultNotPostedEventCustomerResults.ToArray();

                                    if (customerResults.IsNullOrEmpty())
                                    {
                                        customerResults = resultReports.ToArray();
                                    }
                                    else
                                    {
                                        customerResults = customerResults.Concat(resultReports).ToArray();
                                    }
                                }
                                pageNumber++;

                                if (totalItems >= totalRecords)
                                {
                                    break;
                                }
                            }
                        }

                        resultNotPosted.EventCustomer = !resultNotPosted.EventCustomer.IsNullOrEmpty() ? new List <EventCustomerInfo>() : resultNotPosted.EventCustomer;

                        if (eventCustomerResults == null || !customerResults.Any())
                        {
                            _logger.Info(string.Format("No event customer result list for {0} Result Pdf Download.", corporateAccount.Tag));
                            continue;
                        }

                        _logger.Info(string.Format("Found {0} customers for {1} Result Pdf Download. ", eventCustomerResults.Count(), corporateAccount.Tag));

                        var pcpResultReport = _mediaRepository.GetPdfFileNameForPcpResultReport();

                        var healthPlanResultReport = _mediaRepository.GetPdfFileNameForHealthPlanResultReport();

                        var resultPostedToPlanFileName = Path.Combine(_resultPostedToPlanPath, string.Format("ResultPostedto_{0}.xml", corporateAccount.Tag));
                        var resultPosted = _resultPdfPostedSerializer.Deserialize(resultPostedToPlanFileName);

                        resultPosted = resultPosted == null || resultPosted.Customer.IsNullOrEmpty() ? new ResultPdfPostedXml {
                            Customer = new List <CustomerInfo>()
                        } : resultPosted;
                        var resultPostedCustomer = new List <CustomerInfo>();

                        var healthPlanDownloadPath = Path.Combine(string.Format(_settings.HealthPlanDownloadPath, corporateAccount.FolderName), string.Format("ResultPDFs_{0}", DateTime.Now.ToString("yyyyMMdd")));

                        foreach (var ecr in customerResults)
                        {
                            var sourceUrl = _mediaRepository.GetPremiumVersionResultPdfLocation(ecr.EventId, ecr.CustomerId).PhysicalPath + healthPlanResultReport;

                            if (!DirectoryOperationsHelper.IsFileExist(sourceUrl))
                            {
                                sourceUrl = _mediaRepository.GetPremiumVersionResultPdfLocation(ecr.EventId, ecr.CustomerId).PhysicalPath + pcpResultReport;
                            }

                            if (DirectoryOperationsHelper.IsFileExist(sourceUrl))
                            {
                                try
                                {
                                    string fileName = ecr.CustomerId.ToString();

                                    var eventDirectoryPdf = Path.Combine(destinationFolderPdf, ecr.EventId.ToString());
                                    var customer          = _customerRepository.GetCustomer(ecr.CustomerId);
                                    var theEvent          = _eventRepository.GetById(ecr.EventId);

                                    if (corporateAccount.Id == _martinsPointExclusiveAccountId)
                                    {
                                        fileName = "Exclusive_" + customer.InsuranceId;
                                    }
                                    else if (corporateAccount.Id == _settings.ExcellusAccountId)
                                    {
                                        fileName = customer.InsuranceId;
                                    }
                                    else if (corporateAccount.Id == _settings.HealthNowAccountId)
                                    {
                                        fileName          = customer.InsuranceId;
                                        eventDirectoryPdf = healthPlanDownloadPath;
                                    }
                                    else if (corporateAccount.Id == _settings.AppleCareAccountId)
                                    {
                                        if (!string.IsNullOrEmpty(customer.InsuranceId))
                                        {
                                            fileName = string.Format("{0}_{1}", customer.InsuranceId, theEvent.EventDate.ToString("yyyyMMdd"));
                                        }
                                        else
                                        {
                                            fileName = string.Format("NoMember_{0}_{1}", customer.CustomerId, theEvent.EventDate.ToString("yyyyMMdd"));
                                        }

                                        fileName = _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, fileName, (long)ResultFormatType.PDF);
                                    }
                                    else if (corporateAccount.Id == _settings.MedMutualAccountId)
                                    {
                                        if (!string.IsNullOrEmpty(customer.InsuranceId))
                                        {
                                            fileName = string.Format("{0}_{1}", customer.InsuranceId, theEvent.EventDate.ToString("yyyyMMdd"));
                                        }
                                        else
                                        {
                                            fileName = string.Format("NoMember_{0}_{1}", customer.CustomerId, theEvent.EventDate.ToString("yyyyMMdd"));
                                        }

                                        eventDirectoryPdf = healthPlanDownloadPath;

                                        fileName = _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, fileName, (long)ResultFormatType.PDF);
                                    }
                                    else if (corporateAccount.Id == _settings.ConnecticareAccountId)
                                    {
                                        if (!string.IsNullOrEmpty(customer.InsuranceId))
                                        {
                                            fileName = customer.InsuranceId + "_" + customer.Name.LastName + "_" + customer.Name.FirstName + " " + customer.Name.MiddleName
                                                       + theEvent.EventDate.ToString("yyyy-MM-dd") + "_HF_COMM";
                                        }

                                        else
                                        {
                                            fileName = customer.Name.LastName + "_" + customer.Name.FirstName + " " + customer.Name.MiddleName
                                                       + theEvent.EventDate.ToString("yyyy-MM-dd") + "_HF_COMM";
                                        }

                                        eventDirectoryPdf = string.Format(_settings.HealthPlanDownloadPath, corporateAccount.FolderName);
                                    }
                                    else if (corporateAccount.Id == _settings.ConnecticareMaAccountId)
                                    {
                                        if (!string.IsNullOrEmpty(customer.InsuranceId))
                                        {
                                            fileName = customer.InsuranceId + "_" + customer.Name.LastName + "_" + customer.Name.FirstName + " " + customer.Name.MiddleName
                                                       + theEvent.EventDate.ToString("yyyy-MM-dd") + "_HF_MCR";
                                        }

                                        else
                                        {
                                            fileName = customer.Name.LastName + "_" + customer.Name.FirstName + " " + customer.Name.MiddleName
                                                       + theEvent.EventDate.ToString("yyyy-MM-dd") + "_HF_MCR";
                                        }

                                        eventDirectoryPdf = string.Format(_settings.HealthPlanDownloadPath, corporateAccount.FolderName);
                                    }
                                    else if (corporateAccount.Id == _settings.BcbsAlAccountId)
                                    {
                                        if (!string.IsNullOrEmpty(customer.InsuranceId))
                                        {
                                            fileName = customer.CustomerId + "_" + customer.Name.FirstName + " " + customer.Name.LastName + "_" + customer.InsuranceId;
                                        }
                                        else
                                        {
                                            fileName = customer.CustomerId + "_" + customer.Name.FirstName + " " + customer.Name.LastName;
                                        }

                                        eventDirectoryPdf = destinationFolderPdf + "\\" + ecr.EventId + "_" + DateTime.Today.ToString("MM-dd-yyyy");
                                    }
                                    else if (corporateAccount.Id == _settings.FloridaBlueFepAccountId)
                                    {
                                        if (!string.IsNullOrEmpty(customer.InsuranceId))
                                        {
                                            fileName = string.Format("GWC_CW_{0}", customer.InsuranceId);
                                        }

                                        else
                                        {
                                            fileName = string.Format("GWC_CW_NoMemberId_{0}", customer.CustomerId);
                                        }

                                        eventDirectoryPdf = Path.Combine(string.Format(_settings.HealthPlanDownloadPath, corporateAccount.FolderName), "PDFs");
                                    }
                                    else if (corporateAccount.Id == _settings.PPAccountId)
                                    {
                                        fileName          = theEvent.Id + "_" + customer.CustomerId;
                                        eventDirectoryPdf = string.Format(_settings.HealthPlanDownloadPath, corporateAccount.FolderName);
                                    }
                                    else if (corporateAccount.Id == _settings.NammAccountId)
                                    {
                                        fileName          = theEvent.Id + "_" + customer.CustomerId;
                                        eventDirectoryPdf = string.Format(_settings.HealthPlanExportRootPath, corporateAccount.FolderName);
                                    }

                                    if (corporateAccount.MarkPennedBack && ecr.IsPennedBack)
                                    {
                                        fileName += "_" + corporateAccount.PennedBackText;
                                    }

                                    if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.PDF)
                                    {
                                        var destinationFileName = _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, fileName, (long)ResultFormatType.PDF);
                                        var pdfFileName         = destinationFileName + ".pdf";
                                        var pdfResultFile       = Path.Combine(eventDirectoryPdf, pdfFileName);
                                        _resultPdfDownloadHelper.ExportResultInPdfFormat(pdfFileName, sourceUrl, eventDirectoryPdf);

                                        var isFilePosted = true;

                                        if (DirectoryOperationsHelper.IsFileExist(pdfResultFile))
                                        {
                                            var pgpFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, pdfResultFile);

                                            if (_settings.SendReportToHcpNv && _settings.HcpNvAccountId == corporateAccount.Id)
                                            {
                                                isFilePosted = ExportResultOnHcpNvSftp(ecr.CustomerId + ".pdf", sourceUrl, ecr.EventId);
                                            }

                                            if (_settings.BcbsAlAccountId == corporateAccount.Id)
                                            {
                                                var sftpSettings = _sftpCridentialManager.Deserialize(_settings.SftpResouceFilePath + corporateAccount.Tag + ".xml");

                                                isFilePosted = ExportFileOnClientSftp(pdfResultFile, _settings.BcbsAlSftpDownloadPath + "Individual Member Results (PDFs)\\" + ecr.EventId + "_" + DateTime.Today.ToString("MM-dd-yyyy"), sftpSettings);
                                            }

                                            if (corporateAccount.Id == _settings.FloridaBlueFepAccountId)
                                            {
                                                var destinationSftpPath = _settings.FloridaBlueSftpPath + "\\" + corporateAccount.FolderName + "\\Download\\PDfs";
                                                isFilePosted = UploadSingleFile(pdfResultFile, destinationSftpPath, _settings.FloridaBlueSftpHost, _settings.FloridaBlueSftpUserName, _settings.FloridaBlueSftpPassword);
                                            }

                                            if (isFilePosted)
                                            {
                                                resultPostedCustomer.Add(_resultPdfFileHelper.GetCustomerInfo(theEvent, Path.GetFileName(pgpFilePath), (long)ResultFormatType.PDF, customer, ecr.Id));
                                            }
                                            else
                                            {
                                                resultNotPosted.EventCustomer.Add(new EventCustomerInfo
                                                {
                                                    EventCustomerId = ecr.Id,
                                                    EventId         = ecr.EventId,
                                                    CustomerId      = ecr.CustomerId,
                                                    Error           = "File Not posted on Client SFTP."
                                                });
                                            }

                                            _logger.Info("destination: " + pdfResultFile);
                                            _logger.Info("Source: " + sourceUrl);
                                        }
                                        else
                                        {
                                            resultNotPosted.EventCustomer.Add(new EventCustomerInfo
                                            {
                                                EventCustomerId = ecr.Id,
                                                EventId         = ecr.EventId,
                                                CustomerId      = ecr.CustomerId,
                                                Error           = "file not Moved on HIP SFTP."
                                            });
                                        }
                                    }

                                    if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.TIF)
                                    {
                                        var destinationFileName = _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, fileName, (long)ResultFormatType.TIF);
                                        var tipResultFile       = Path.Combine(eventDirectoryPdf, destinationFileName + ".tif");
                                        _resultPdfDownloadHelper.ExportResultInTiffFormat(destinationFileName + ".tif", sourceUrl, eventDirectoryPdf);

                                        var isFilePosted = true;
                                        var pgpFilePath  = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, tipResultFile);

                                        if (DirectoryOperationsHelper.IsFileExist(tipResultFile))
                                        {
                                            if (_settings.SendReportToHcpNv && _settings.HcpNvAccountId == corporateAccount.Id)
                                            {
                                                isFilePosted = ExportResultOnHcpNvSftp(ecr.CustomerId + ".tif", sourceUrl, ecr.EventId, false);
                                            }

                                            if (_settings.BcbsAlAccountId == corporateAccount.Id)
                                            {
                                                var sftpSettings = _sftpCridentialManager.Deserialize(_settings.SftpResouceFilePath + corporateAccount.Tag + ".xml");
                                                isFilePosted = ExportFileOnClientSftp(tipResultFile, _settings.BcbsAlSftpDownloadPath + "Individual Member Results (PDFs)\\" + ecr.EventId + "_" + DateTime.Today.ToString("MM-dd-yyyy"), sftpSettings);
                                            }
                                            if (isFilePosted)
                                            {
                                                resultPostedCustomer.Add(_resultPdfFileHelper.GetCustomerInfo(theEvent, Path.GetFileName(pgpFilePath), (long)ResultFormatType.TIF, customer, ecr.Id));
                                            }
                                            else
                                            {
                                                resultNotPosted.EventCustomer.Add(new EventCustomerInfo
                                                {
                                                    EventCustomerId = ecr.Id,
                                                    EventId         = ecr.EventId,
                                                    CustomerId      = ecr.CustomerId,
                                                    Error           = "File Not posted on Client SFTP."
                                                });
                                            }

                                            _logger.Info("destination: " + tipResultFile);
                                            _logger.Info("Source: " + sourceUrl);
                                        }
                                        else
                                        {
                                            resultNotPosted.EventCustomer.Add(new EventCustomerInfo
                                            {
                                                EventCustomerId = ecr.Id,
                                                EventId         = ecr.EventId,
                                                CustomerId      = ecr.CustomerId,
                                                Error           = "file not Moved on HIP SFTP."
                                            });
                                        }
                                    }
                                }
                                catch (Exception exception)
                                {
                                    resultNotPosted.EventCustomer.Add(new EventCustomerInfo
                                    {
                                        EventCustomerId = ecr.Id,
                                        EventId         = ecr.EventId,
                                        CustomerId      = ecr.CustomerId,
                                        Error           = "file not Moved on HIP SFTP."
                                    });

                                    _logger.Error(string.Format("some error occurred for the customerId {0}, {1},\n Message {2} \n Stack Trace {3}", ecr.CustomerId, ecr.EventId, exception.Message, exception.StackTrace));
                                }
                            }
                            else
                            {
                                _logger.Info(string.Format("File not generated or removed for the customerId {0}, {1}", ecr.CustomerId, ecr.EventId));

                                resultNotPosted.EventCustomer.Add(new EventCustomerInfo
                                {
                                    EventCustomerId = ecr.Id,
                                    EventId         = ecr.EventId,
                                    CustomerId      = ecr.CustomerId,
                                    Error           = "File not generated or removed."
                                });
                            }
                        }

                        if (corporateAccount.Id == _settings.HealthNowAccountId || corporateAccount.Id == _settings.MedMutualAccountId)
                        {
                            if (DirectoryOperationsHelper.IsDirectoryExist(healthPlanDownloadPath) &&
                                DirectoryOperationsHelper.GetFiles(healthPlanDownloadPath).Any())
                            {
                                var isZipFileCreated = false;
                                try
                                {
                                    _zipHelper.CreateZipFiles(healthPlanDownloadPath);
                                    isZipFileCreated = true;
                                }
                                catch (Exception ex)
                                {
                                    _logger.Error(string.Format("some error occurred while creating zip file for AccountId: {0} and account tag: {1} Exception Message: \n{2}, \n stack Trace: \n\t {3} ",
                                                                corporateAccount.Id, corporateAccount.Tag, ex.Message, ex.StackTrace));
                                }

                                if (isZipFileCreated)
                                {
                                    resultPosted.Customer.AddRange(resultPostedCustomer);
                                }
                                else
                                {
                                    resultNotPosted.EventCustomer.AddRange(
                                        resultPostedCustomer.Select(x => new EventCustomerInfo
                                    {
                                        EventCustomerId = x.EventCustomerId,
                                        CustomerId      = x.CustomerId,
                                        EventId         = x.EventId,
                                        Error           = "Error occurred while creating zip file."
                                    }));
                                }
                            }

                            DirectoryOperationsHelper.DeleteDirectory(healthPlanDownloadPath, true);
                        }
                        else
                        {
                            resultPosted.Customer.AddRange(resultPostedCustomer);
                        }

                        customSettings.LastTransactionDate = exportToTime;
                        _customSettingManager.SerializeandSave(customSettingFilePath, customSettings);

                        CorrectandSaveResultPosted(resultPosted, corporateAccount);
                        _resultPdfNotPostedSerializer.SerializeandSave(resultNotPostedToPlanFileName, resultNotPosted);

                        if (resultNotPosted.EventCustomer.Count > 0)
                        {
                            _resultPdfEmailNotificationHelper.SendEmailNotificationForFileNotPosted(corporateAccount.Tag, resultNotPosted.EventCustomer.Count, _logger);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(string.Format("some error occurred for AccountId: {0} and account tag: {1} Exception Message: \n{2}, \n stack Trace: \n\t {3} ", corporateAccount.Id, corporateAccount.Tag, ex.Message, ex.StackTrace));
                    }
                }
            }
            catch (Exception exception)
            {
                _logger.Error(string.Format("some error occurred Exception Message: \n{0}, \n stack Trace: \n\t {1} ", exception.Message, exception.StackTrace));
            }
        }
        public void PollForPcpLogSummaryReportExport()
        {
            try
            {
                if (_wellCarePcpSummaryLogReportDayOfWeek != DateTime.Today.DayOfWeek)
                {
                    _logger.Info("Report is schedule to run on " + _wellCarePcpSummaryLogReportDayOfWeek);
                    _logger.Info("Today is day of week " + DateTime.Today.DayOfWeek);
                    _logger.Info(string.Format("Set day of week to {0} to run today ", ((int)DateTime.Today.DayOfWeek)));
                    return;
                }

                if (_accountIds.IsNullOrEmpty())
                {
                    _logger.Info("No Account Ids found");
                    return;
                }


                var directoryPath = _destinationFolderPdfPath + "\\";

                CreateDestinationDirectory(directoryPath);

                var toDate = DateTime.Now;

                var fileName = string.Format("PCPSummaryLog-HealthFair-{0}.csv", toDate.ToString("yyyyMMdd"));


                var accounts = _corporateAccountRepository.GetByIds(_accountIds);

                var model = new PcpSummaryLogReportListModel();

                foreach (var account in accounts)
                {
                    _logger.Info("Running Report for Tag: " + account.Tag);

                    try
                    {
                        var serviceReportSettings = string.Format(_wellCarePcpSummaryLogReportSettingPath, account.Tag);
                        var customSettings        = _customSettingManager.Deserialize(serviceReportSettings);

                        var fromDate = (customSettings.LastTransactionDate != null) ? customSettings.LastTransactionDate.Value : _cutOfDate;

                        var listModel = PcpSummaryLogReport(account, fromDate, toDate, directoryPath, fileName);
                        if (listModel != null && !listModel.Collection.IsNullOrEmpty())
                        {
                            if (model.Collection.IsNullOrEmpty())
                            {
                                model.Collection = listModel.Collection;
                            }
                            else
                            {
                                model.Collection = model.Collection.Concat(listModel.Collection);
                            }
                        }

                        customSettings.LastTransactionDate = toDate;
                        _customSettingManager.SerializeandSave(serviceReportSettings, customSettings);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Some Error occurred  for Tag" + account.Tag);
                        _logger.Error("Message: " + ex.Message);
                        _logger.Error("Stack Trace: " + ex.StackTrace);
                    }
                }

                if (model != null && !model.Collection.IsNullOrEmpty())
                {
                    model.Collection = model.Collection.OrderBy(x => x.PcpMailedDate).ThenBy(x => x.EventId);

                    var exporter = ExportableDataGeneratorProcessManager <ViewModelBase, ModelFilterBase> .GetCsvExporter <PcpSummaryLogReportModel>();

                    _logger.Info("Record count" + model.Collection.Count());

                    if (File.Exists(directoryPath + fileName) && !FirstReportGenerated)
                    {
                        File.Delete(directoryPath + fileName);
                    }

                    FirstReportGenerated = _baseExportableReportHelper.GenerateCsv(directoryPath + fileName, exporter, model.Collection, skipHeader: FirstReportGenerated);


                    _logger.Info("Destination file " + directoryPath + fileName);
                }
                else
                {
                    _logger.Info(string.Format("No Data found for PCP summary log Period {0} ", toDate));
                }

                if (_settings.SendPdfToWellCareSftp)
                {
                    ExportResultOnWellCareSftp(fileName, directoryPath + fileName);
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Message: " + ex.Message);
                _logger.Error("Stack Trace: " + ex.StackTrace);
            }
        }
        public ListModelBase <HealthPlanCallQueueViewModel, HealthPlanCallQueueListModelFilter> GetHealthPlanCallQueueList(int pageNumber, int pageSize, ModelFilterBase filter, out int totalRecords)
        {
            var assignmentFilter = filter as HealthPlanCallQueueListModelFilter ??
                                   new HealthPlanCallQueueListModelFilter();

            var healthPlanCallQueuesCriteria = _healthPlanCallQueueCriteriaRepository.GetHealthPlanCallQueueCriteria(filter as HealthPlanCallQueueListModelFilter, pageNumber, pageSize, out totalRecords);

            if (healthPlanCallQueuesCriteria == null && !healthPlanCallQueuesCriteria.Any())
            {
                totalRecords = 0;
                return(null);
            }

            var callQueueIds = healthPlanCallQueuesCriteria.Select(cq => cq.CallQueueId).ToArray();

            var healthPlanIds = healthPlanCallQueuesCriteria.Where(x => x.HealthPlanId.HasValue).Select(s => s.HealthPlanId.Value).ToArray();

            IEnumerable <CorporateAccount> healthPlans = null;

            if (healthPlanIds != null && healthPlanIds.Any())
            {
                healthPlans = _corporateAccountRepository.GetByIds(healthPlanIds);
            }

            IEnumerable <CallQueue> healthPlanCallQueues = null;

            if (callQueueIds != null && callQueueIds.Any())
            {
                healthPlanCallQueues = _callQueueRepository.GetByIds(callQueueIds, false, true);
            }

            var assignOrgRoleIds = healthPlanCallQueuesCriteria.Select(a => a.DataRecorderMetaData.DataRecorderCreator.Id).Distinct().ToArray();

            var modifiedBy = healthPlanCallQueuesCriteria.Where(x => x.DataRecorderMetaData.DataRecorderModifier != null).Select(a => a.DataRecorderMetaData.DataRecorderModifier.Id).Distinct().ToArray();

            if (modifiedBy != null && modifiedBy.Any())
            {
                assignOrgRoleIds = assignOrgRoleIds.Concat(modifiedBy).ToArray();
            }

            var criteriaIds = healthPlanCallQueuesCriteria.Select(s => s.Id).ToArray();

            IEnumerable <HealthPlanCriteriaAssignment>     healthPlanCriteriaAssignment     = null;
            IEnumerable <HealthPlanCriteriaTeamAssignment> healthPlanCriteriaTeamAssignment = null;

            var campaignIds = healthPlanCallQueuesCriteria.Where(s => s.CampaignId.HasValue).Select(x => x.CampaignId.Value).ToArray();

            var campaigns = _campaignRepository.GetByIds(campaignIds);

            if (criteriaIds != null && criteriaIds.Any())
            {
                healthPlanCriteriaAssignment     = _healthPlanCriteriaAssignmentRepository.GetByCriteriaIds(criteriaIds);
                healthPlanCriteriaTeamAssignment = _healthPlanCriteriaTeamAssignmentRepository.GetByCriteriaIds(criteriaIds);

                if (healthPlanCriteriaAssignment != null && healthPlanCriteriaAssignment.Any())
                {
                    var assignAssignmentRoleUserIds = healthPlanCriteriaAssignment.Select(s => s.AssignedToOrgRoleUserId).Distinct().ToArray();

                    if (assignAssignmentRoleUserIds != null && assignAssignmentRoleUserIds.Any())
                    {
                        assignOrgRoleIds = assignOrgRoleIds.Concat(assignAssignmentRoleUserIds).ToArray();
                    }

                    var assignmentBy = healthPlanCriteriaAssignment.Select(s => s.CreatedBy).Distinct().ToArray();

                    if (assignmentBy.Any())
                    {
                        assignOrgRoleIds = assignOrgRoleIds.Concat(assignmentBy).ToArray();
                    }
                }
            }

            IEnumerable <OrderedPair <long, string> > teamIdNamePairs = null;

            if (!healthPlanCriteriaTeamAssignment.IsNullOrEmpty())
            {
                teamIdNamePairs = _callCenterTeamRepository.GetIdNamePairOfTeams(healthPlanCriteriaTeamAssignment.Select(x => x.TeamId).ToArray());

                var assignmentBy = healthPlanCriteriaTeamAssignment.Select(s => s.CreatedBy).Distinct().ToArray();

                if (assignmentBy.Any())
                {
                    assignOrgRoleIds = assignOrgRoleIds.Concat(assignmentBy).ToArray();
                }
            }

            assignOrgRoleIds = assignOrgRoleIds.Distinct().ToArray();

            var agentIdNamePairs = _organizationRoleUserRepository.GetNameIdPairofUsers(assignOrgRoleIds);

            var criteriaCustomerCountPairs = new List <OrderedPair <long, long> >();

            if (assignmentFilter.ShowAssignmentMetaData)
            {
                foreach (var criteria in healthPlanCallQueuesCriteria)
                {
                    var count = _customerCallQueueCallAttemptService.CustomerCountForHealthPlanCriteria(criteria, healthPlanCallQueues);
                    criteriaCustomerCountPairs.Add(new OrderedPair <long, long>(criteria.Id, count));
                }
            }

            var criteriaDirectMailDates = _healthPlanCriteriaDirectMailService.GetDirectMailDatesByCriteriaIds(criteriaIds);

            return(_callQueueListModelFactory.CreateHealthPlanCallQueueList(healthPlanCallQueuesCriteria, agentIdNamePairs, healthPlanCallQueues, healthPlans, healthPlanCriteriaAssignment, campaigns, healthPlanCriteriaTeamAssignment,
                                                                            teamIdNamePairs, criteriaCustomerCountPairs, criteriaDirectMailDates, assignmentFilter.ShowAssignmentMetaData));
        }
Esempio n. 28
0
        public ListModelBase <TestNotPerformedViewModel, TestNotPerformedListModelFilter> GetTestNotPerformed(int pageNumber, int pageSize, ModelFilterBase filter, out int totalRecords)
        {
            var testNotPerformFilter = filter as TestNotPerformedListModelFilter;
            var testNotPerformed     = _testNotPerformedRepository.GetTestNotPerformedForHealthPlan(testNotPerformFilter, pageNumber, pageSize, out totalRecords);

            if (testNotPerformed == null || !testNotPerformed.Any())
            {
                return(null);
            }

            var customerEventScreeningTestIds = testNotPerformed.Select(x => x.CustomerEventScreeningTestId).ToArray();

            var customerEventScreeningTests = _eventCustomerResultRepository.GetCustomerEventScreeningTestsByIds(customerEventScreeningTestIds);

            var customerEventTestStates = _customerEventTestStateRepository.GetCustomerEventTestState(customerEventScreeningTestIds);

            var orgRoleUserIds = customerEventTestStates.Where(cets => cets.ConductedByOrgRoleUserId.HasValue).Select(cets => cets.ConductedByOrgRoleUserId.Value).Distinct().ToArray();
            var idNamePairs    = _organizationRoleUserRepository.GetNameIdPairofUsers(orgRoleUserIds);

            var eventCustomerResults = _eventCustomerResultRepository.GetByIds(customerEventScreeningTests.Select(ces => ces.EventCustomerResultId).Distinct().ToArray());
            var eventIds             = eventCustomerResults.Select(ecr => ecr.EventId).Distinct().ToArray();

            var events = _eventRepository.GetEventswithPodbyIds(eventIds);
            var hosts  = _hostRepository.GetEventHosts(events.Select(x => x.Id));
            IEnumerable <OrderedPair <long, long> >   staffOrgRoleUserEventsPair = null;
            IEnumerable <OrderedPair <long, string> > staffNamePair = null;

            var npRoles = _eventRoleRepository.GetByName(_awvNpEventStaffRole);

            if (npRoles != null && npRoles.Any())
            {
                var eventStaffs = _eventStaffAssignmentRepository.GetForEvents(eventIds);
                var npRoleIds   = npRoles.Select(x => x.Id);

                if (eventStaffs != null && eventStaffs.Any())
                {
                    eventStaffs = eventStaffs.Where(x => npRoleIds.Contains(x.StaffEventRoleId)).ToArray();
                }

                staffOrgRoleUserEventsPair = eventStaffs.Select(p => new OrderedPair <long, long>(p.ScheduledStaffOrgRoleUserId, p.EventId)).ToArray();

                staffNamePair = _organizationRoleUserRepository.GetNameIdPairofUsers(staffOrgRoleUserEventsPair.Select(x => x.FirstValue).ToArray());
            }

            var customers = _customerRepository.GetCustomers(eventCustomerResults.Select(ecr => ecr.CustomerId).Distinct().ToArray());

            //var tags = customers.Select(x => x.Tag).Distinct().ToArray();

            //var corporateAccount = _corporateAccountRepository.GetByTags(tags);

            var accountIds = events.Where(x => x.AccountId.HasValue && x.AccountId > 0).Select(x => x.AccountId.Value).Distinct().ToArray();

            var corporateAccount = _corporateAccountRepository.GetByIds(accountIds);

            if (corporateAccount != null && corporateAccount.Any())
            {
                corporateAccount = corporateAccount.Where(x => x.IsHealthPlan);
            }

            var tests = ((IUniqueItemRepository <Test>)_testRepository).GetByIds(customerEventScreeningTests.Select(ces => ces.TestId).Distinct().ToArray());

            var customersPreApprovedTest = _preApprovedTestRepository.GetPreApprovedTestIdsByCustomerIds(eventCustomerResults.Select(x => x.Id));
            var pods = _podRepository.GetByIds(events.SelectMany(e => e.PodIds).Distinct());

            var eventCustomers = _eventCustomerRepository.GetByIds(customerEventScreeningTests.Select(ces => ces.EventCustomerResultId).Distinct().ToArray());

            return(_testNotPerformedFactory.Create(testNotPerformed, customerEventScreeningTests, eventCustomerResults, events, customers, tests,
                                                   customersPreApprovedTest, corporateAccount, pods, customerEventTestStates, idNamePairs, staffOrgRoleUserEventsPair, staffNamePair, hosts, eventCustomers));
        }