Exemplo n.º 1
0
        private void PostResultPdf(AnthemResultPostedViewModel resultPostedViewModel)
        {
            var ecr              = resultPostedViewModel.EventCustomerResult;
            var pdfResultFile    = resultPostedViewModel.DestinationPdfFileName;
            var corporateAccount = resultPostedViewModel.CorporateAccount;
            var sourceFile       = resultPostedViewModel.SourceFilePath;

            if (DirectoryOperationsHelper.IsFileExist(sourceFile))
            {
                try
                {
                    _resultPdfDownloaderHelper.ExportResultInPdfFormat(pdfResultFile, resultPostedViewModel.SourceFilePath, resultPostedViewModel.DestinationPathWithBatchName);

                    var pgpFilePath     = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, pdfResultFile);
                    var finalFilePosted = Path.GetFileName(pgpFilePath);

                    WriteTransactFile(resultPostedViewModel);
                    AddToCrosswalkList(resultPostedViewModel);

                    var customerInfo = _resultPdfFileHelper.GetCustomerInfo(resultPostedViewModel.Event, finalFilePosted, (long)ResultFormatType.PDF, resultPostedViewModel.Customer, ecr.Id);
                    AddToResultPosted(corporateAccount.Tag, customerInfo);

                    var destination = Path.Combine(resultPostedViewModel.DestinationPathWithBatchName, pdfResultFile);

                    _logger.Info("Source: " + resultPostedViewModel.SourceFilePath);
                    _logger.Info("destination: " + destination);
                }
                catch (Exception ex)
                {
                    _logger.Error("result not posted for Customer Id: " + ecr.CustomerId + " and event Id " + ecr.EventId);
                    _logger.Error(string.Format("some error occurred: Message {0} \\n Stack Trace: {1} ", ex.Message, ex.StackTrace));

                    AddToResultNotPosted(resultPostedViewModel);
                }
            }
            else
            {
                _logger.Info(string.Format("File not generated or removed for the Customer Id: {0}, Event Id: {1}", ecr.CustomerId, ecr.EventId));
                AddToResultNotPosted(resultPostedViewModel);
            }
        }
        public void PollForPdfDownload()
        {
            try
            {
                if (_accountId <= 0)
                {
                    return;
                }
                var corporateAccount = _corporateAccountRepository.GetById(_accountId);

                try
                {
                    _logger.Info(string.Format("Genderating for accountId {0} and account tag {1}. ", corporateAccount.Id, corporateAccount.Tag));

                    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 = _settings.StopSendingPdftoHealthPlanDate;
                    }

                    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));
                        return;
                    }

                    _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 sftpFailedRecordsFileName = Path.Combine(_resultPostedToPlanPath, string.Format("CustomerResultsFailedOnSftp_{0}.xml", corporateAccount.Tag + "_ToWellmed"));
                    var sftpFailedCustomers       = _customerResultsFailedOnSftpSerializer.Deserialize(sftpFailedRecordsFileName);
                    sftpFailedCustomers = sftpFailedCustomers == null || sftpFailedCustomers.EventCustomerIds.IsNullOrEmpty() ? new CustomerResultsFailedOnSftp {
                        EventCustomerIds = new List <long>()
                    } : sftpFailedCustomers;

                    var newSftpFailedCustomers = new CustomerResultsFailedOnSftp {
                        EventCustomerIds = new List <long>()
                    };

                    if (!sftpFailedCustomers.EventCustomerIds.IsNullOrEmpty())
                    {
                        var failedEventCustomerIds = sftpFailedCustomers.EventCustomerIds.Where(x => !customerResults.Select(ecr => ecr.Id).Contains(x));
                        if (!failedEventCustomerIds.IsNullOrEmpty())
                        {
                            int totalRecords = failedEventCustomerIds.Count();
                            int pageNumber   = 0;
                            int pagesize     = 100;

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

                                var totalItems  = pageNumber * pagesize;
                                var customerIds = failedEventCustomerIds.Skip(totalItems).Take(pagesize);
                                var failedEventCustomerResults = _eventCustomerResultRepository.GetEventCustomerResultsByIdsAndResultState(customerIds, (int)TestResultStateNumber.ResultDelivered, (int)NewTestResultStateNumber.ResultDelivered, false);
                                if (!failedEventCustomerResults.IsNullOrEmpty())
                                {
                                    customerResults.Concat(failedEventCustomerResults);
                                }
                                pageNumber++;

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

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

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

                        if (File.Exists(sourcePath))
                        {
                            try
                            {
                                var customer = _customerRepository.GetCustomer(ecr.CustomerId);

                                var eventData = _eventRepository.GetById(ecr.EventId);
                                var host      = _hostRepository.GetHostForEvent(ecr.EventId);

                                if (!string.IsNullOrEmpty(customer.InsuranceId))
                                {
                                    var destinationFolderPdfPath         = string.Empty;
                                    var destinationCatalystFolderPdfPath = string.Empty;
                                    //if (!string.IsNullOrEmpty(customer.GroupName) && _wellmedCustomerGroupName.Contains(customer.GroupName))
                                    //    destinationFolderPdfPath = _destinationCatalystFolderPdfPath + "\\" + host.Address.State + "\\" + eventData.EventDate.Year + "\\" + ecr.EventId;
                                    //else
                                    destinationFolderPdfPath = _destinationFolderPdfPath + "\\" + host.Address.State + "\\" + eventData.EventDate.Year + "\\" + ecr.EventId;

                                    var eventDirectoryPdf = GetDestinationFolderPath(destinationFolderPdfPath, customer, eventData.EventDate);

                                    var destinationFilename = "";

                                    if (!string.IsNullOrEmpty(customer.GroupName))
                                    {
                                        destinationFilename = RemoveIllegalFileChar(customer.GroupName) + "_" + RemoveIllegalFileChar(customer.InsuranceId);
                                    }
                                    else
                                    {
                                        destinationFilename = "NoGroup_" + RemoveIllegalFileChar(customer.InsuranceId);
                                    }

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

                                    if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.PDF || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both)
                                    {
                                        var fileName      = "UHC_" + _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, destinationFilename, (long)ResultFormatType.PDF);
                                        var resultPdfFile = eventDirectoryPdf + "/" + fileName + ".pdf";
                                        _resultPdfDownloadHelper.ExportResultInPdfFormat(fileName + ".pdf", sourcePath, eventDirectoryPdf);

                                        if (File.Exists(resultPdfFile))
                                        {
                                            var pgpFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, resultPdfFile);
                                        }
                                        else
                                        {
                                            _logger.Info("File Not Found : " + resultPdfFile);
                                        }

                                        if (!string.IsNullOrEmpty(customer.GroupName) && _wellmedCustomerGroupName.Contains(customer.GroupName.ToLower()))
                                        {
                                            destinationCatalystFolderPdfPath = _destinationCatalystFolderPdfPath + "\\" + host.Address.State + "\\" + eventData.EventDate.Year + "\\" + ecr.EventId;
                                            var resultCatalystPdfFile = destinationCatalystFolderPdfPath + "/" + fileName + ".pdf";

                                            _resultPdfDownloadHelper.ExportResultInPdfFormat(fileName + ".pdf", sourcePath, destinationCatalystFolderPdfPath);

                                            if (File.Exists(resultCatalystPdfFile))
                                            {
                                                var pgpCatalystFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, resultCatalystPdfFile);
                                            }
                                            else
                                            {
                                                _logger.Info("File Not Found : " + resultCatalystPdfFile);
                                            }
                                        }


                                        if (_sendReportToSftp)
                                        {
                                            var destinationSftpfolderPath = _destinationSftpFolderPdfPath + "\\" + host.Address.State + "\\" + eventData.EventDate.Year + "\\" + ecr.EventId;
                                            var resultPostedToSftp        = false;

                                            if (ExportResultInSftp(fileName + ".pdf", sourcePath, destinationSftpfolderPath)) //GetDestinationFolderPath(destinationSftpfolderPath, customer, eventData.EventDate)
                                            {
                                                _logger.Info(string.Format("File Moved to Wellmed Sftp location for customer Id {0} and eventId {1}", ecr.CustomerId, ecr.EventId));
                                                resultPostedToSftp = true;
                                            }

                                            if (resultPostedToSftp && !string.IsNullOrEmpty(customer.GroupName) && _wellmedCustomerGroupName.Contains(customer.GroupName.ToLower()))
                                            {
                                                var destinationSftpCatalystfolderPath = _destinationSftpCatalystFolderPdfPath + "\\" + host.Address.State + "\\" + eventData.EventDate.Year + "\\" + ecr.EventId;
                                                if (ExportResultInSftp(fileName + ".pdf", sourcePath, destinationSftpCatalystfolderPath))
                                                {
                                                    _logger.Info(string.Format("File Moved to Wellmed Catalyst Sftp location for customer Id {0} and eventId {1}", ecr.CustomerId, ecr.EventId));
                                                }
                                                else
                                                {
                                                    resultPostedToSftp = false;
                                                }
                                            }

                                            if (resultPostedToSftp)
                                            {
                                                resultPosted.Customer.Add(_resultPdfFileHelper.GetCustomerInfo(eventData, fileName + ".pdf", (long)ResultFormatType.PDF, customer, ecr.Id));
                                            }
                                            else
                                            {
                                                newSftpFailedCustomers.EventCustomerIds.Add(ecr.Id);
                                            }
                                        }
                                    }

                                    if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.TIF || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both)
                                    {
                                        var fileName      = "UHC_" + _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, destinationFilename, (long)ResultFormatType.TIF);
                                        var resultTifFile = eventDirectoryPdf + "/" + fileName + ".tif";

                                        _resultPdfDownloadHelper.ExportResultInTiffFormat(fileName + ".tif", sourcePath, eventDirectoryPdf);

                                        if (File.Exists(resultTifFile))
                                        {
                                            var pgpFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, resultTifFile);
                                            resultPosted.Customer.Add(_resultPdfFileHelper.GetCustomerInfo(eventData, Path.GetFileName(pgpFilePath), (long)ResultFormatType.TIF, customer, ecr.Id));
                                        }
                                        else
                                        {
                                            _logger.Info(string.Format("File {0} not Exit for pgp Encryption ", resultTifFile));
                                        }
                                    }
                                }
                                else
                                {
                                    _logger.Info(string.Format("member id is not found for customer {0} and eventId {1}", ecr.CustomerId, ecr.EventId));
                                }
                            }
                            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));
                        }
                    }

                    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
                        {
                            _resultPdfFileHelper.CreateCsvForFileShared(resultPosted.Customer, 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);

                    _customerResultsFailedOnSftpSerializer.SerializeandSave(sftpFailedRecordsFileName, newSftpFailedCustomers);
                }
                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));
            }
        }
Exemplo n.º 3
0
        public void PollForPdfDownload()
        {
            try
            {
                if (_accountId < 1)
                {
                    return;
                }

                var corporateAccount = _corporateAccountRepository.GetById(_accountId);

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

                    var destinationFolderPdf  = _settings.AnthemDownloadPath;
                    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 = _settings.StopSendingPdftoHealthPlanDate;
                    }

                    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();
                    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));
                        return;
                    }

                    _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 eventsCollection = ((IUniqueItemRepository <Event>)_eventRepository).GetByIds(customerResults.Select(x => x.EventId).Distinct().ToArray());

                    foreach (var ecr in customerResults)
                    {
                        var customerData = _customerRepository.GetCustomer(ecr.CustomerId);
                        if (string.IsNullOrEmpty(customerData.InsuranceId))
                        {
                            _logger.Info("Customer Id: " + customerData.CustomerId + " does not contain Member Id");
                        }

                        var eventData = eventsCollection.Single(x => x.Id == ecr.EventId);

                        var sourcePath = _mediaRepository.GetPremiumVersionResultPdfLocation(ecr.EventId, ecr.CustomerId).PhysicalPath + healthPlanResultReport;

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

                        if (DirectoryOperationsHelper.IsFileExist(sourcePath))
                        {
                            try
                            {
                                var eventDirectoryPdf = destinationFolderPdf;

                                if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.PDF)
                                {
                                    var patientMemerId = string.IsNullOrEmpty(customerData.InsuranceId) ? "No_MemberId_" + ecr.CustomerId + "_" : customerData.InsuranceId + "_";

                                    var pdfFileName = RemoveIllegalFileChar("HLTHFAIR_" + patientMemerId + ecr.EventId);

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

                                    pdfFileName = _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, pdfFileName, (long)ResultFormatType.PDF);
                                    //var pdfResultFile = eventDirectoryPdf + "/" + pdfFileName + ".pdf";

                                    var pdfResultFile = Path.Combine(eventDirectoryPdf, pdfFileName + ".pdf");

                                    _resultPdfDownloaderHelper.ExportResultInPdfFormat(pdfFileName + ".pdf", sourcePath, eventDirectoryPdf);

                                    if (DirectoryOperationsHelper.IsFileExist(pdfResultFile))
                                    {
                                        var pgpFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, pdfResultFile);
                                        resultPosted.Customer.Add(_resultPdfFileHelper.GetCustomerInfo(eventData, Path.GetFileName(pgpFilePath), (long)ResultFormatType.PDF, customerData, ecr.Id));

                                        _logger.Info("Source: " + sourcePath);
                                        _logger.Info("destination: " + pdfResultFile);
                                    }
                                    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 patientMemerId = string.IsNullOrEmpty(customerData.InsuranceId) ? "No_MemberId_" + ecr.CustomerId + "_" : customerData.InsuranceId + "_";

                                    var fileName = RemoveIllegalFileChar("HLTHFAIR_" + patientMemerId + ecr.EventId);

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

                                    fileName = _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, fileName, (long)ResultFormatType.TIF);
                                    // var tipResultFile = eventDirectoryPdf + "/" + fileName + ".tif";
                                    var tipResultFile = Path.Combine(eventDirectoryPdf, fileName + ".tif");
                                    _resultPdfDownloaderHelper.ExportResultInTiffFormat(ecr.CustomerId + ".tif", sourcePath, eventDirectoryPdf);

                                    if (DirectoryOperationsHelper.IsFileExist(tipResultFile))
                                    {
                                        var pgpFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, tipResultFile);
                                        resultPosted.Customer.Add(_resultPdfFileHelper.GetCustomerInfo(eventData, Path.GetFileName(pgpFilePath), (long)ResultFormatType.TIF, customerData, ecr.Id));

                                        _logger.Info("Source: " + sourcePath);
                                        _logger.Info("destination: " + tipResultFile);
                                    }
                                    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."
                            });
                        }
                    }

                    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
                        {
                            _resultPdfFileHelper.CreateCsvForFileShared(resultPosted.Customer, 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);

                    _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 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));
            }
        }
Exemplo n.º 4
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));
            }
        }
        private void SetReusltPdfNameing(EventCustomerResult ecr, CorporateAccount corporateAccount, string destinationFolderPdfPath, string sourcePath, ResultPdfPostedXml resultPosted, List <long> newCustomersWithNoMrn)
        {
            var eventDirectoryPdf   = destinationFolderPdfPath + "\\" + ecr.EventId;
            var destinationFilename = ecr.CustomerId.ToString();
            var customer            = _customerRepository.GetCustomer(ecr.CustomerId);
            var eventData           = _eventRepository.GetById(ecr.EventId);

            if (_optumAccountIds.Contains(corporateAccount.Id))
            {
                eventDirectoryPdf = destinationFolderPdfPath;
            }

            if (corporateAccount.Id == _settings.OptumNvAccountId || corporateAccount.Id == _settings.OptumNvMedicareAccountId)
            {
                if (!string.IsNullOrEmpty(customer.Mrn))
                {
                    destinationFilename = customer.Mrn + "_" + eventData.EventDate.ToString("yyyyMMdd");
                    var customerPcp = _primaryCarePhysicianRepository.Get(ecr.CustomerId);
                    destinationFilename += (customerPcp != null ? "_" + customerPcp.Name.LastName : "");
                }
                else
                {
                    newCustomersWithNoMrn.Add(ecr.CustomerId);
                    _logger.Info("MRN not available for Customer ID : " + ecr.CustomerId);
                    return;
                }
            }

            if (_monarchAccountIds.Contains(corporateAccount.Id))
            {
                destinationFilename = ResultFileName(customer);
            }

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

            if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.PDF || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both)
            {
                var fileName = _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, destinationFilename, (long)ResultFormatType.PDF);

                var resultPdfFile = eventDirectoryPdf + "/" + fileName + ".pdf";
                _resultPdfDownloadHelper.ExportResultInPdfFormat(fileName + ".pdf", sourcePath, eventDirectoryPdf);

                _logger.Info("source Url: " + sourcePath);
                _logger.Info("destination Url: " + eventDirectoryPdf + "/" + fileName + ".pdf");

                if (File.Exists(resultPdfFile))
                {
                    var pgpFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, resultPdfFile);

                    resultPosted.Customer.Add(_resultPdfFileHelper.GetCustomerInfo(eventData, Path.GetFileName(pgpFilePath), (long)ResultFormatType.PDF, customer, ecr.Id));
                }
                else
                {
                    _logger.Info("File Not Found : " + resultPdfFile);
                }
            }

            if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.TIF || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both)
            {
                var fileName = _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, destinationFilename, (long)ResultFormatType.TIF);

                var resultTifFile = eventDirectoryPdf + "/" + fileName + ".tif";
                _resultPdfDownloadHelper.ExportResultInTiffFormat(fileName + ".tif", sourcePath, eventDirectoryPdf);

                _logger.Info("source Url: " + sourcePath);
                _logger.Info("destination Url: " + eventDirectoryPdf + "/" + fileName + ".tif");

                if (File.Exists(resultTifFile))
                {
                    var pgpFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, resultTifFile);
                    resultPosted.Customer.Add(_resultPdfFileHelper.GetCustomerInfo(eventData, Path.GetFileName(pgpFilePath), (long)ResultFormatType.TIF, customer, ecr.Id));
                }
                else
                {
                    _logger.Info(string.Format("File {0} not Exist for pgp Encryption ", resultTifFile));
                }
            }
        }
Exemplo n.º 6
0
        private void PostResultPdfOnSftp(DateTime exportToTime, DateTime exportFromTime, CorporateAccount corporateAccount, string destinationFolderPdfPath, bool includeCustomerWithTag, string[] customTags)
        {
            var eventCustomerResults = _eventCustomerResultRepository.GetEventCustomerResultDelivered(exportToTime, exportFromTime, corporateAccount.Id, corporateAccount.Tag, _settings.PPEventCutOfDate, includeCustomerWithTag, customTags, 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 found for {0}.",
                                           corporateAccount.Tag));
            }

            _logger.Info(string.Format("Found {0} customers for {1} Result. ", 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;

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

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

                if (DirectoryOperationsHelper.IsFileExist(sourcePath))
                {
                    try
                    {
                        var customer = _customerRepository.GetCustomer(ecr.CustomerId);

                        var eventData = _eventRepository.GetById(ecr.EventId);

                        var destinationFilename = string.IsNullOrEmpty(customer.InsuranceId) ? "No MemberId_" + customer.CustomerId + "_" + eventData.EventDate.ToString("MM-dd-yyyy") : customer.InsuranceId + "_" + eventData.EventDate.ToString("MM-dd-yyyy");
                        destinationFilename = RemoveIllegalFileChar(destinationFilename);
                        if (corporateAccount.MarkPennedBack && ecr.IsPennedBack)
                        {
                            destinationFilename += "_" + corporateAccount.PennedBackText;
                        }

                        //var destinationFolderPdfPathWithYear = Path.Combine(destinationFolderPdfPath, eventData.EventDate.Year.ToString());

                        if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.PDF || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both)
                        {
                            var pdfFileName = _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, destinationFilename, (long)ResultFormatType.PDF);

                            var resultPdfFile = Path.Combine(destinationFolderPdfPath, pdfFileName + ".pdf");

                            _logger.Info("destination file : " + destinationFolderPdfPath + "\\" + pdfFileName + ".pdf");
                            _logger.Info("source file : " + sourcePath);

                            _resultPdfDownloadHelper.ExportResultInPdfFormat(pdfFileName + ".pdf", sourcePath, destinationFolderPdfPath);

                            if (DirectoryOperationsHelper.IsFileExist(resultPdfFile))
                            {
                                var pgpFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, resultPdfFile);
                                resultPosted.Customer.Add(_resultPdfFileHelper.GetCustomerInfo(eventData, Path.GetFileName(pgpFilePath), (long)ResultFormatType.PDF, customer, ecr.Id));
                            }
                            else
                            {
                                _logger.Info("File Not Found : " + resultPdfFile);
                                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.TIF || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both)
                        {
                            var tifFileName   = _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, destinationFilename, (long)ResultFormatType.TIF);
                            var resultTifFile = destinationFolderPdfPath + "/" + tifFileName + ".tif";
                            _resultPdfDownloadHelper.ExportResultInTiffFormat(tifFileName + ".tif", sourcePath, destinationFolderPdfPath);

                            if (DirectoryOperationsHelper.IsFileExist(resultTifFile))
                            {
                                var pgpFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, resultTifFile);
                                resultPosted.Customer.Add(_resultPdfFileHelper.GetCustomerInfo(eventData, Path.GetFileName(pgpFilePath), (long)ResultFormatType.TIF, customer, ecr.Id));
                            }
                            else
                            {
                                _logger.Info(string.Format("File {0} not Exit for pgp Encryption ", resultTifFile));
                                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}, Event Id {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 (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
                {
                    _resultPdfFileHelper.CreateCsvForFileShared(resultPosted.Customer, 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);
        }
Exemplo n.º 7
0
        public void PollForPdfDownload()
        {
            try
            {
                if (_accountIds == null || !_accountIds.Any())
                {
                    return;
                }


                foreach (var accountId in _accountIds)
                {
                    var corporateAccount = _corporateAccountRepository.GetById(accountId);

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

                        var destinationFolderPdf  = string.Format(_destinationFolderPdfPath, 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;
                        }

                        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;
                        }

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

                        var pcpResultReport = _mediaRepository.GetPdfFileNameForPcpResultReport();

                        var healthPlanResultReport = _mediaRepository.GetPdfFileNameForHealthPlanResultReport();
                        customerResults = customerResults.OrderBy(x => x.EventId).ToArray();

                        long eventId           = 0;
                        var  eventDirectoryPdf = string.Empty;
                        var  list = new List <WellCareResultPdfLog>();
                        foreach (var ecr in customerResults)
                        {
                            var sourcePath = _mediaRepository.GetPremiumVersionResultPdfLocation(ecr.EventId, ecr.CustomerId).PhysicalPath + healthPlanResultReport;

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

                            if (File.Exists(sourcePath))
                            {
                                var stftDestinationPath = string.Format(_sftpDestinationPath);

                                try
                                {
                                    var theEventData = _eventRepository.GetById(ecr.EventId);

                                    eventDirectoryPdf = destinationFolderPdf + "/" + theEventData.EventDate.Year + "/" + ecr.EventId;

                                    if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.PDF)
                                    {
                                        var pdfFileName = ecr.CustomerId + "_" + theEventData.EventDate.ToString("MMddyyyy");

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

                                        var pdfResultFile = eventDirectoryPdf + "/" + pdfFileName + ".pdf";
                                        list.Add(new WellCareResultPdfLog {
                                            CustomerId = ecr.CustomerId, FileName = pdfFileName
                                        });

                                        _resultPdfDownloaderHelper.ExportResultInPdfFormat(pdfFileName, sourcePath, eventDirectoryPdf);

                                        if (File.Exists(pdfResultFile))
                                        {
                                            _pgpFileEncryptionHelper.EncryptFile(corporateAccount, pdfResultFile);
                                        }

                                        if (_sendReportToSftp)
                                        {
                                            _logger.Info("destinationPath: " + stftDestinationPath);
                                            ExportResultInSftp(pdfFileName + ".pdf", sourcePath, stftDestinationPath);

                                            _logger.Info(string.Format("File Moved to HealthNow Sftp location for customer Id {0} and eventId {1}", ecr.CustomerId, ecr.EventId));
                                        }
                                    }

                                    if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.TIF)
                                    {
                                        var fileName = ecr.CustomerId.ToString();

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

                                        var tipResultFile = eventDirectoryPdf + "/" + fileName + ".tif";
                                        _resultPdfDownloaderHelper.ExportResultInTiffFormat(ecr.CustomerId + ".tif", sourcePath, eventDirectoryPdf);

                                        if (File.Exists(tipResultFile))
                                        {
                                            _pgpFileEncryptionHelper.EncryptFile(corporateAccount, tipResultFile);
                                        }
                                    }

                                    if (eventId != ecr.EventId)
                                    {
                                        var filePathForNewfile = eventDirectoryPdf + "/" + ecr.EventId + ".csv";
                                        GenerateHeaderCustomerResultPdfCsv(eventDirectoryPdf, filePathForNewfile);

                                        if (eventId > 0)
                                        {
                                            var appendRecordsForfile = eventDirectoryPdf + "/" + eventId + ".csv";

                                            AppendCustomerFileData(appendRecordsForfile, list);
                                            if (_sendReportToSftp)
                                            {
                                                ExportResultInSftp(eventId + ".csv", appendRecordsForfile, _sftpDestinationPath);

                                                _logger.Info("File Pushed For event customer File Records");
                                            }
                                        }

                                        eventId = ecr.EventId;
                                    }
                                }
                                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 (eventId > 0)
                        {
                            var appendRecordsForfile = eventDirectoryPdf + "/" + eventId + ".csv";

                            AppendCustomerFileData(appendRecordsForfile, list);

                            if (_sendReportToSftp)
                            {
                                ExportResultInSftp(eventId + ".csv", appendRecordsForfile, _sftpDestinationPath);

                                _logger.Info("File Pushed For event customer File Records");
                            }
                        }

                        customSettings.LastTransactionDate = exportToTime;
                        _customSettingManager.SerializeandSave(customSettingFilePath, customSettings);
                    }
                    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 PollForPdfDownload()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }
                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);

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

                        var destinationFolderPdfPath = string.Format(_destinationFolderPdfPath, corporateAccount.FolderName);
                        var sptpDestinationfolder    = string.Format(_destinationSftpFolderPdfPath, 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;
                        }

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

                        var resultPosted = GetResultPostedTo(corporateAccount.Tag);

                        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;
                        }

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

                        var pcpResultReport = _mediaRepository.GetPdfFileNameForPcpResultReport();

                        var healthPlanResultReport = _mediaRepository.GetPdfFileNameForHealthPlanResultReport();

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

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

                            if (File.Exists(sourcePath))
                            {
                                try
                                {
                                    var customer  = _customerRepository.GetCustomer(ecr.CustomerId);
                                    var eventData = _eventRepository.GetById(ecr.EventId);

                                    var destinationFileName = string.Empty;

                                    var lastName  = string.IsNullOrEmpty(customer.Name.LastName) ? string.Empty : customer.Name.LastName.Trim();
                                    var firstName = string.IsNullOrEmpty(customer.Name.FirstName) ? string.Empty : customer.Name.FirstName.Trim();

                                    if (!string.IsNullOrEmpty(customer.InsuranceId))
                                    {
                                        destinationFileName = string.Format("{0}_{1}_{2}_{3}", customer.InsuranceId, lastName, firstName, eventData.EventDate.ToString("MMddyy"));
                                    }
                                    else
                                    {
                                        destinationFileName = string.Format("{0}_{1}_{2}_{3}_{4}", "No_MemberId", customer.CustomerId, lastName, firstName, eventData.EventDate.ToString("MMddyy"));
                                    }

                                    var destinationFolderPdfPathWithEventId  = destinationFolderPdfPath + "/" + ecr.EventId + "/";
                                    var sptpDestinationfolderPathWithEventId = sptpDestinationfolder + "/pdf" + "/" + ecr.EventId;

                                    if (!string.IsNullOrEmpty(destinationFileName))
                                    {
                                        if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.PDF || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both)
                                        {
                                            destinationFileName = _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, destinationFileName, (long)ResultFormatType.PDF);

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

                                            var pdfResultFile = destinationFolderPdfPathWithEventId + destinationFileName + ".pdf";

                                            _resultPdfDownloaderHelper.ExportResultInPdfFormat(destinationFileName + ".pdf", sourcePath, destinationFolderPdfPathWithEventId);

                                            if (File.Exists(pdfResultFile))
                                            {
                                                var pgpFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, pdfResultFile);
                                            }

                                            resultPosted.Customer.Add(_resultPdfFileHelper.GetCustomerInfo(eventData, destinationFileName + ".pdf", (long)ResultFormatType.PDF, customer, ecr.Id));

                                            if (_sendReportToSftp)
                                            {
                                                sptpDestinationfolderPathWithEventId = sptpDestinationfolderPathWithEventId.Replace("\\", "/");

                                                ResultPdfonNtspSftp(destinationFileName + ".pdf", sourcePath, sptpDestinationfolderPathWithEventId);

                                                _logger.Info(string.Format("File Moved to Ntsp Sftp location for customer Id {0} and eventId {1}", ecr.CustomerId, ecr.EventId));
                                            }
                                        }

                                        if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.TIF || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both)
                                        {
                                            destinationFileName = _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, destinationFileName, (long)ResultFormatType.TIF);

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

                                            var tifResultFile = destinationFolderPdfPathWithEventId + destinationFileName + ".tif";
                                            _resultPdfDownloaderHelper.ExportResultInTiffFormat(destinationFileName + ".tif", sourcePath, destinationFolderPdfPathWithEventId);

                                            if (File.Exists(tifResultFile))
                                            {
                                                _pgpFileEncryptionHelper.EncryptFile(corporateAccount, tifResultFile);
                                            }

                                            resultPosted.Customer.Add(_resultPdfFileHelper.GetCustomerInfo(eventData, destinationFileName + ".tif", (long)ResultFormatType.PDF, customer, ecr.Id));
                                        }
                                    }
                                }
                                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));
                            }
                        }

                        CorrectandSaveResultPosted(resultPosted, corporateAccount);

                        customSettings.LastTransactionDate = exportToTime;
                        _customSettingManager.SerializeandSave(customSettingFilePath, customSettings);
                    }
                    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));
            }
        }
        private void PostResultPdfToSftp(IEnumerable <EventCustomerResult> eventCustomerResults, CorporateAccount corporateAccount, List <long> newCustomerListWithNoGmpi)
        {
            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));
            }

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

            var resultPostedToPlanFileName = Path.Combine(_resultPostedToPlanPath, "resultPostedMonarchToWellmed.xml");
            var resultPosted = _resultPdfPostedSerializer.Deserialize(resultPostedToPlanFileName);

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

            var destinationFolderPdfPath = _destinationFolderPdfPath + "/pdf";
            var pcpResultReport          = _mediaRepository.GetPdfFileNameForPcpResultReport();

            var healthPlanResultReport = _mediaRepository.GetPdfFileNameForHealthPlanResultReport();

            foreach (var ecr in customerResults)
            {
                var customer  = _customerRepository.GetCustomer(ecr.CustomerId);
                var eventData = _eventRepository.GetById(ecr.EventId);

                if (!string.IsNullOrEmpty(customer.AdditionalField4))
                {
                    var sourcePath = _mediaRepository.GetPremiumVersionResultPdfLocation(ecr.EventId, ecr.CustomerId).PhysicalPath + healthPlanResultReport;

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

                    if (File.Exists(sourcePath))
                    {
                        try
                        {
                            var eventDirectoryPdf   = destinationFolderPdfPath;
                            var destinationFilename = ResultFileName(customer);

                            if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.PDF || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both)
                            {
                                destinationFilename = _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, destinationFilename, (long)ResultFormatType.PDF);

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

                                var resultPdfFile = eventDirectoryPdf + "/" + destinationFilename + ".pdf";

                                _resultPdfDownloadHelper.ExportResultInPdfFormat(destinationFilename + ".pdf", sourcePath, eventDirectoryPdf);

                                if (File.Exists(resultPdfFile))
                                {
                                    var pgpFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, resultPdfFile);

                                    resultPosted.Customer.Add(_resultPdfFileHelper.GetCustomerInfo(eventData, Path.GetFileName(pgpFilePath), (long)ResultFormatType.PDF, customer, ecr.Id));
                                }
                                else
                                {
                                    _logger.Info("File Not Found : " + resultPdfFile);
                                }
                            }

                            if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.TIF || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both)
                            {
                                destinationFilename = _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, destinationFilename, (long)ResultFormatType.TIF);

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

                                var resultTifFile = eventDirectoryPdf + "/" + destinationFilename + ".tif";

                                _resultPdfDownloadHelper.ExportResultInTiffFormat(destinationFilename + ".tif", sourcePath, eventDirectoryPdf);

                                if (File.Exists(resultTifFile))
                                {
                                    var pgpFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, resultTifFile);
                                    resultPosted.Customer.Add(_resultPdfFileHelper.GetCustomerInfo(eventData, Path.GetFileName(pgpFilePath), (long)ResultFormatType.TIF, customer, ecr.Id));
                                }
                                else
                                {
                                    _logger.Info(string.Format("File {0} not Exist for pgp Encryption ", resultTifFile));
                                }
                            }
                        }
                        catch (Exception exception)
                        {
                            _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));
                    }
                }
                else
                {
                    if (newCustomerListWithNoGmpi != null)
                    {
                        newCustomerListWithNoGmpi.Add(customer.CustomerId);
                    }

                    _logger.Info(string.Format("Customer Id: {0}, Event id: {1} do not have GMPID ", ecr.CustomerId, ecr.EventId));
                }
            }

            _resultPdfPostedSerializer.SerializeandSave(resultPostedToPlanFileName, resultPosted);
        }
        public void PollForPdfDownload()
        {
            try
            {
                if (_accountId <= 0)
                {
                    return;
                }
                var corporateAccount = _corporateAccountRepository.GetById(_accountId);

                try
                {
                    _logger.Info(string.Format("Genderating for accountId {0} and account tag {1}. ", corporateAccount.Id, corporateAccount.Tag));

                    var customSettingFilePath = string.Format(_customDownloadSettings, 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;
                    }

                    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));
                        return;
                    }

                    var distinctEventIds = eventCustomerResults.Select(x => x.EventId).Distinct();

                    var events = ((IUniqueItemRepository <Event>)_eventRepository).GetByIds(distinctEventIds);

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

                    var pcpResultReport = _mediaRepository.GetPdfFileNameForPcpResultReport();

                    var healthPlanResultReport = _mediaRepository.GetPdfFileNameForHealthPlanResultReport();

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

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

                        if (File.Exists(sourcePath))
                        {
                            try
                            {
                                var customer  = _customerRepository.GetCustomer(ecr.CustomerId);
                                var eventData = events.Single(x => x.Id == ecr.EventId);

                                if (!string.IsNullOrEmpty(customer.InsuranceId))
                                {
                                    var eventDirectoryPdf  = _destinationFolderPdfPath + @"\";
                                    var dateOfRegeneration = ecr.RegenerationDate ?? ecr.DataRecorderMetaData.DateModified;
                                    var fileName           = customer.InsuranceId + "_" + eventData.EventDate.ToString("yyyyMMdd") + "_" + (dateOfRegeneration.Value.ToString("yyyyMMdd"));

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

                                    if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.PDF || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both)
                                    {
                                        var pdfFileName = fileName + ".pdf";

                                        _resultPdfDownloadHelper.ExportResultInPdfFormat(pdfFileName, sourcePath, eventDirectoryPdf);
                                        try
                                        {
                                            _pgpFileEncryptionHelper.EncryptFile(corporateAccount, eventDirectoryPdf + @"\" + pdfFileName);
                                        }
                                        catch (Exception exception)
                                        {
                                            _logger.Error("Message : " + exception.Message + " Stack Trace : " + exception.StackTrace);
                                        }
                                    }

                                    if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.TIF || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both)
                                    {
                                        var tifFileName = fileName + ".tif";

                                        _resultPdfDownloadHelper.ExportResultInTiffFormat(tifFileName, sourcePath, eventDirectoryPdf);

                                        try
                                        {
                                            _pgpFileEncryptionHelper.EncryptFile(corporateAccount, eventDirectoryPdf + @"\" + tifFileName);
                                        }
                                        catch (Exception exception)
                                        {
                                            _logger.Error("Message : " + exception.Message + " Stack Trace : " + exception.StackTrace);
                                        }
                                    }
                                }
                                else
                                {
                                    _logger.Info(string.Format("member id is not found for customer {0} and eventId {1}", ecr.CustomerId, ecr.EventId));
                                }
                            }
                            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));
                        }
                    }

                    customSettings.LastTransactionDate = exportToTime;
                    _customSettingManager.SerializeandSave(customSettingFilePath, customSettings);
                }
                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));
            }
        }
Exemplo n.º 11
0
        public void PollForPdfDownload()
        {
            try
            {
                if (_accountId <= 0)
                {
                    return;
                }
                var corporateAccount = _corporateAccountRepository.GetById(_accountId);

                try
                {
                    _logger.Info(string.Format("Genderating for accountId {0} and account tag {1}. ", corporateAccount.Id, corporateAccount.Tag));

                    var destinationFolderPdfPath = string.Format(_destinationFolderPdfPath, 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 = _settings.StopSendingPdftoHealthPlanDate;
                    }

                    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));
                        return;
                    }

                    _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;

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

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

                        if (File.Exists(sourcePath))
                        {
                            try
                            {
                                var customer  = _customerRepository.GetCustomer(ecr.CustomerId);
                                var eventData = _eventRepository.GetById(ecr.EventId);

                                var destinationFileName = string.Empty;
                                //if (!string.IsNullOrEmpty(customer.Mrn))
                                //{
                                //    destinationFileName = customer.Mrn + "_" + eventData.EventDate.ToString("yyyyMMdd") + "_258_Outside Diagnostics_HF";
                                //}
                                //else if (!string.IsNullOrEmpty(customer.Lpi))
                                //{
                                //    destinationFileName = "XID" + customer.Lpi + "_" + eventData.EventDate.ToString("yyyyMMdd") + "_258_Outside Diagnostics_HF";
                                //}

                                if (!string.IsNullOrEmpty(customer.Lpi))
                                {
                                    destinationFileName = "XID" + customer.Lpi + "_" + eventData.EventDate.ToString("yyyyMMdd") + "_258_Outside Diagnostics_HF";
                                }
                                else if (!string.IsNullOrEmpty(customer.Mrn))
                                {
                                    destinationFileName = customer.Mrn + "_" + eventData.EventDate.ToString("yyyyMMdd") + "_258_Outside Diagnostics_HF";
                                }
                                else
                                {
                                    destinationFileName = customer.CustomerId + "_" + eventData.EventDate.ToString("yyyyMMdd") + "_258_Outside Diagnostics_HF";
                                }

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

                                if (!string.IsNullOrEmpty(destinationFileName))
                                {
                                    if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.PDF || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both)
                                    {
                                        var fileName      = _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, destinationFileName, (long)ResultFormatType.PDF);
                                        var pdfResultFile = destinationFolderPdfPath + "/pdf/" + fileName + ".pdf";
                                        _resultPdfDownloaderHelper.ExportResultInPdfFormat(fileName + ".pdf", sourcePath, destinationFolderPdfPath + "/pdf");

                                        if (File.Exists(pdfResultFile))
                                        {
                                            var pgpFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, pdfResultFile);
                                            resultPosted.Customer.Add(_resultPdfFileHelper.GetCustomerInfo(eventData, Path.GetFileName(pgpFilePath), (long)ResultFormatType.PDF, customer, ecr.Id));
                                        }
                                    }

                                    if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.TIF || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both)
                                    {
                                        var fileName      = _resultPdfFileHelper.GetFileName(resultPosted.Customer, ecr, destinationFileName, (long)ResultFormatType.TIF);
                                        var tifResultFile = destinationFolderPdfPath + "/tif/" + fileName + ".tif";
                                        _resultPdfDownloaderHelper.ExportResultInTiffFormat(fileName + ".tif", sourcePath, destinationFolderPdfPath + "/tif");

                                        if (File.Exists(tifResultFile))
                                        {
                                            var pgpFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, tifResultFile);
                                            resultPosted.Customer.Add(_resultPdfFileHelper.GetCustomerInfo(eventData, Path.GetFileName(pgpFilePath), (long)ResultFormatType.TIF, customer, ecr.Id));
                                        }

                                        if (_sendReportToSftp)
                                        {
                                            ExportResultInSftp(fileName + ".tif", tifResultFile, "");

                                            _logger.Info(string.Format("File Moved to HCP CA Sftp location for customer Id {0} and eventId {1}", ecr.CustomerId, ecr.EventId));
                                        }
                                    }
                                }
                                else
                                {
                                    _logger.Info("customer info does nither contain LPI nor MRN info customer Id: " + customer.CustomerId + " Event Id: " + eventData.Id);
                                }
                            }
                            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));
                        }
                    }

                    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
                        {
                            _resultPdfFileHelper.CreateCsvForFileShared(resultPosted.Customer, 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);
                }
                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 PollForPdfDownload()
        {
            try
            {
                if (DateTime.Today.DayOfWeek != _dayOfWeek)
                {
                    _logger.Info(string.Format("Today is {0}. Job is set to run on {1}.", DateTime.Today.DayOfWeek, _dayOfWeek));
                    return;
                }

                var accountIds = new List <long>();
                if (string.IsNullOrEmpty(_settings.FloridaBlueAccountId))
                {
                    _logger.Info("No account Ids found.");
                    return;
                }

                var partnerIdsArray = _settings.FloridaBlueAccountId.Split(',').Where(hospitalIdstr => !string.IsNullOrEmpty(hospitalIdstr)).Select(x => x.Trim());

                foreach (var hospitalIdstr in partnerIdsArray)
                {
                    long pcpAccountId;
                    long.TryParse(hospitalIdstr, out pcpAccountId);
                    if (pcpAccountId > 0)
                    {
                        accountIds.Add(pcpAccountId);
                    }
                }

                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 destinationFolderPdfPath = string.Format(_destinationFolderPdfPath, 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;

                        var folderName = string.Format("HLF_GWC_CW_{0}", exportToTime.ToString("yyyyMMddHHmmssfff"));
                        var destinationFolderPdfPathWithCustomFolder = destinationFolderPdfPath + "/" + folderName + "/";

                        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, 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;
                        }

                        DirectoryOperationsHelper.CreateDirectoryIfNotExist(_settings.ResultPostedToPlanPath);

                        var resultPostedToPlanFileName = Path.Combine(_settings.ResultPostedToPlanPath, string.Format("resultPostedto_{0}.xml", corporateAccount.Tag));
                        var resultPosted = _resultPdfPostedSerializer.Deserialize(resultPostedToPlanFileName);
                        resultPosted = resultPosted ?? new ResultPdfPostedXml {
                            Customer = new List <CustomerInfo>()
                        };

                        //TODO: Foreach loop for one time use......TO BE REMOVED
                        foreach (var customerInfo in resultPosted.Customer.Where(x => x.FileType == 0))
                        {
                            customerInfo.FileType = (long)ResultFormatType.PDF;
                        }

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

                        var pcpResultReport = _mediaRepository.GetPdfFileNameForPcpResultReport();

                        var healthPlanResultReport = _mediaRepository.GetPdfFileNameForHealthPlanResultReport();

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

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

                            if (File.Exists(sourcePath))
                            {
                                try
                                {
                                    var customer  = _customerRepository.GetCustomer(ecr.CustomerId);
                                    var eventData = _eventRepository.GetById(ecr.EventId);

                                    var destinationFileName = string.Empty;
                                    if (!string.IsNullOrEmpty(customer.InsuranceId))
                                    {
                                        destinationFileName = string.Format("{0}_{1}", FileNamePrefix, customer.InsuranceId);
                                    }
                                    else
                                    {
                                        destinationFileName = string.Format("{0}_NoMemberId_{1}", FileNamePrefix, customer.CustomerId);
                                    }

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

                                    _logger.Info("Moving pdf file for customer Id: " + customer.CustomerId + " Event Id: " + eventData.Id);

                                    if (!string.IsNullOrEmpty(destinationFileName))
                                    {
                                        if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.PDF || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both)
                                        {
                                            var pdfResultFile = destinationFolderPdfPathWithCustomFolder + destinationFileName + ".pdf";
                                            _resultPdfDownloaderHelper.ExportResultInPdfFormat(destinationFileName + ".pdf", sourcePath, destinationFolderPdfPathWithCustomFolder);

                                            if (File.Exists(pdfResultFile))
                                            {
                                                var pgpFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, pdfResultFile);

                                                resultPosted.Customer.Add(_resultPdfFileHelper.GetCustomerInfo(eventData, Path.GetFileName(pgpFilePath), (long)ResultFormatType.PDF, customer, ecr.Id));
                                            }
                                        }

                                        if (corporateAccount.ResultFormatTypeId == (long)ResultFormatType.TIF || corporateAccount.ResultFormatTypeId == (long)ResultFormatType.Both)
                                        {
                                            var tifResultFile = destinationFolderPdfPathWithCustomFolder + destinationFileName + ".tif";
                                            _resultPdfDownloaderHelper.ExportResultInTiffFormat(destinationFileName + ".tif", sourcePath, destinationFolderPdfPathWithCustomFolder);

                                            if (File.Exists(tifResultFile))
                                            {
                                                var pgpFilePath = _pgpFileEncryptionHelper.EncryptFile(corporateAccount, tifResultFile);
                                                resultPosted.Customer.Add(_resultPdfFileHelper.GetCustomerInfo(eventData, Path.GetFileName(pgpFilePath), (long)ResultFormatType.TIF, customer, ecr.Id));
                                            }
                                        }
                                    }
                                    //else
                                    //{
                                    //    _logger.Info("customer info does not contain member Id for customer Id: " + customer.CustomerId + " Event Id: " + eventData.Id);
                                    //}
                                }
                                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));
                            }
                        }
                        resultPosted = CorrectMissingRecords(resultPosted);
                        _resultPdfPostedSerializer.SerializeandSave(resultPostedToPlanFileName, resultPosted);

                        //zip folder
                        _logger.Info("Creating Zip file");

                        var sourceDir = Directory.GetParent(destinationFolderPdfPathWithCustomFolder).FullName;

                        var outputPath = sourceDir + ".zip";

                        _zipHelper.CreateZipFiles(sourceDir, outputPath, true);

                        string directoryName = Path.GetDirectoryName(outputPath) + "\\" + Path.GetFileNameWithoutExtension(outputPath);


                        _logger.Info("Deleting directory " + directoryName);
                        if (Directory.Exists(directoryName))
                        {
                            try
                            {
                                foreach (var file in Directory.GetFiles(directoryName))
                                {
                                    File.Delete(file);
                                }

                                Directory.Delete(directoryName, true);
                            }
                            catch (Exception exception)
                            {
                                _logger.Error(string.Format("Error while deleting directory {0}. Exception Message: \n{1}, \n stack Trace: \n\t {2}", directoryName, exception.Message, exception.StackTrace));
                            }
                        }

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

                        _logger.Info("Completed");
                    }
                    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));
            }
        }